Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle focus on focusable formatters #2104

Merged
merged 6 commits into from
Jul 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
- `column.minWidth`
- `column.maxWidth`
- `column.headerCellClass`
- `column.formatterOptions`
- More info in [#2104](https://github.com/adazzle/react-data-grid/pull/2104)
- `scrollToRow` method
- ⚠️ This replaces the `scrollToRowIndex` prop
- **Removed:**
Expand All @@ -30,7 +32,7 @@
- ⚠️ `cellContentRenderer`
- ⚠️ `contextMenu`
<!-- TODO: fill link to storybook -->
- Check the [Context Menu]() example
- Check the [Context Menu](https://adazzle.github.io/react-data-grid/canary/?path=/story/demos--context-menu) example
- ⚠️ `enableCellSelect`
- ⚠️ `enableCellAutoFocus`
- ⚠️ `getValidFilterValues`
Expand Down
1 change: 1 addition & 0 deletions src/Cell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ function Cell<R, SR>({
column={column}
rowIdx={rowIdx}
row={row}
isCellSelected={isSelected}
isRowSelected={isRowSelected}
onRowSelectionChange={onRowSelectionChange}
/>
Expand Down
5 changes: 5 additions & 0 deletions src/Columns.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,14 @@ export const SelectColumn: Column<any, any> = {
return (
<SelectCellFormatter
aria-label="Select"
tabIndex={-1}
isCellSelected={props.isCellSelected}
value={props.isRowSelected}
onChange={props.onRowSelectionChange}
/>
);
},
formatterOptions: {
focusable: true
}
};
2 changes: 2 additions & 0 deletions src/DataGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,8 @@ function DataGrid<R, K extends keyof R, SR>({
if (selectedPosition === prevSelectedPosition.current || selectedPosition.mode === 'EDIT' || !isCellWithinBounds(selectedPosition)) return;
prevSelectedPosition.current = selectedPosition;
scrollToCell(selectedPosition);
const column = columns[selectedPosition.idx];
if (column.formatterOptions?.focusable) return; // Let the formatter handle focus
focusSinkRef.current!.focus();
});

Expand Down
15 changes: 14 additions & 1 deletion src/formatters/SelectCellFormatter.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,35 @@
import React from 'react';
import React, { useLayoutEffect, useRef } from 'react';
import clsx from 'clsx';

type SharedInputProps = Pick<React.InputHTMLAttributes<HTMLInputElement>,
| 'disabled'
| 'tabIndex'
| 'aria-label'
| 'aria-labelledby'
>;

export interface SelectCellFormatterProps extends SharedInputProps {
isCellSelected?: boolean;
value: boolean;
onChange: (value: boolean, isShiftClick: boolean) => void;
}

export function SelectCellFormatter({
value,
tabIndex,
isCellSelected,
disabled,
onChange,
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy
}: SelectCellFormatterProps) {
const inputRef = useRef<HTMLInputElement>(null);

useLayoutEffect(() => {
if (!isCellSelected) return;
inputRef.current?.focus();
}, [isCellSelected]);

function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
onChange(e.target.checked, (e.nativeEvent as MouseEvent).shiftKey);
}
Expand All @@ -28,6 +39,8 @@ export function SelectCellFormatter({
<input
aria-label={ariaLabel}
aria-labelledby={ariaLabelledBy}
tabIndex={tabIndex}
ref={inputRef}
type="checkbox"
className="rdg-checkbox-input"
disabled={disabled}
Expand Down
4 changes: 4 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export interface Column<TRow, TSummaryRow = unknown> {
summaryCellClass?: string | ((row: TSummaryRow) => string);
/** Formatter to be used to render the cell content */
formatter?: React.ComponentType<FormatterProps<TRow, TSummaryRow>>;
formatterOptions?: {
focusable?: boolean;
};
/** Formatter to be used to render the summary cell content */
summaryFormatter?: React.ComponentType<SummaryFormatterProps<TSummaryRow, TRow>>;
/** Enables cell editing. If set and no editor property specified, then a textinput will be used as the cell editor */
Expand Down Expand Up @@ -69,6 +72,7 @@ export interface FormatterProps<TRow = any, TSummaryRow = any> {
rowIdx: number;
column: CalculatedColumn<TRow, TSummaryRow>;
row: TRow;
isCellSelected: boolean;
isRowSelected: boolean;
onRowSelectionChange: (checked: boolean, isShiftClick: boolean) => void;
}
Expand Down
19 changes: 5 additions & 14 deletions stories/demos/TreeView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,22 +106,25 @@ export default function TreeView() {
{
key: 'format',
name: 'format',
formatter({ row }) {
formatterOptions: { focusable: true },
formatter({ row, isCellSelected }) {
const hasChildren = row.children !== undefined;
const style = !hasChildren ? { marginLeft: 30 } : undefined;
return (
<>
{hasChildren && (
<CellExpanderFormatter
isCellSelected={isCellSelected}
expanded={row.isExpanded === true}
onCellExpand={() => dispatch({ id: row.id, type: 'toggleSubRow' })}
/>
)}
<div className="rdg-cell-value">
{!hasChildren && (
<ChildRowDeleteButton
onDeleteSubRow={() => dispatch({ id: row.id, type: 'deleteSubRow' })}
isCellSelected={isCellSelected}
isDeleteSubRowEnabled={allowDelete}
onDeleteSubRow={() => dispatch({ id: row.id, type: 'deleteSubRow' })}
/>
)}
<div style={style}>
Expand All @@ -130,18 +133,6 @@ export default function TreeView() {
</div>
</>
);
},
unsafe_onCellInput(event, row) {
const hasChildren = row.children !== undefined;
if (event.key === ' ' && hasChildren) {
event.preventDefault();
dispatch({ id: row.id, type: 'toggleSubRow' });
}

if (event.key === 'Delete' && !hasChildren) {
event.preventDefault();
dispatch({ id: row.id, type: 'deleteSubRow' });
}
}
},
{
Expand Down
32 changes: 27 additions & 5 deletions stories/demos/components/Formatters/CellExpanderFormatter.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,44 @@
import React from 'react';
import React, { useRef, useLayoutEffect } from 'react';

import './CellExpanderFormatter.less';

export interface CellExpanderFormatterProps {
isCellSelected: boolean;
expanded: boolean;
onCellExpand: () => void;
}

export function CellExpanderFormatter({ expanded, onCellExpand }: CellExpanderFormatterProps) {
function handleCellExpand(e: React.MouseEvent<HTMLSpanElement>) {
export function CellExpanderFormatter({ isCellSelected, expanded, onCellExpand }: CellExpanderFormatterProps) {
const iconRef = useRef<HTMLSpanElement>(null);
useLayoutEffect(() => {
if (!isCellSelected) return;
iconRef.current?.focus({ preventScroll: true });
}, [isCellSelected]);

function handleClick(e: React.MouseEvent<HTMLSpanElement>) {
e.stopPropagation();
onCellExpand();
}

function handleKeyDown(e: React.KeyboardEvent<HTMLSpanElement>) {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
onCellExpand();
}
}

return (
<div className="rdg-cell-expand">
<span onClick={handleCellExpand}>
{expanded ? '\u25BC' : '\u25B6'}
<span
onClick={handleClick}
onKeyDown={handleKeyDown}
>
<span
ref={iconRef}
tabIndex={-1}
>
{expanded ? '\u25BC' : '\u25B6'}
</span>
</span>
</div>
);
Expand Down
28 changes: 24 additions & 4 deletions stories/demos/components/Formatters/ChildRowDeleteButton.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,37 @@
import React from 'react';
import React, { useRef, useLayoutEffect } from 'react';

export interface ChildRowDeleteButtonProps {
onDeleteSubRow: () => void;
isCellSelected: boolean;
isDeleteSubRowEnabled: boolean;
onDeleteSubRow: () => void;
}

export function ChildRowDeleteButton({ onDeleteSubRow, isDeleteSubRowEnabled }: ChildRowDeleteButtonProps) {
export function ChildRowDeleteButton({ isCellSelected, onDeleteSubRow, isDeleteSubRowEnabled }: ChildRowDeleteButtonProps) {
const iconRef = useRef<HTMLSpanElement>(null);
useLayoutEffect(() => {
if (!isCellSelected) return;
iconRef.current?.focus({ preventScroll: true });
}, [isCellSelected]);

function handleKeyDown(e: React.KeyboardEvent<HTMLSpanElement>) {
if (e.key === 'Enter') {
e.preventDefault();
onDeleteSubRow();
}
}

return (
<>
<div className="rdg-child-row-action-cross" />
{isDeleteSubRowEnabled && (
<div className="rdg-child-row-btn" onClick={onDeleteSubRow}>
<span
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why add another element?
Also I think if you just set onClick={onDeleteSubRow} instead of handling onKeyDown manually it might work just as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Otherwise it looks like this

image

ref={iconRef}
tabIndex={-1}
onKeyDown={handleKeyDown}
>
</span>
</div>
)}
</>
Expand Down