Data Grid - 접근성(Accessibility)
Data Grid가 국제 표준을 따르는 키보드 탐색을 포함해 접근성 기능과 지침을 어떻게 구현하는지 알아봅니다.
본문
지침(Guidelines)
접근성에 대한 일반적인 적합성 지침으로는 다음이 있습니다:
- 전 세계적으로 통용되는 표준: WCAG
- 미국:
- ADA - 미 법무부
- Section 508 - 미국 연방 기관
- 유럽: EAA (유럽 접근성법)
WCAG 2.2에는 A, AA, AAA의 세 가지 적합성 수준이 있습니다. 레벨 AA는 접근성의 기본 기준을 넘어서며 대부분의 조직에서 일반적인 목표이므로, 우리가 지원하고자 하는 수준입니다.
WAI-ARIA Authoring Practices는 데이터 그리드의 접근성을 최적화하는 방법에 대한 유용한 정보를 제공합니다.
행 헤더(Row headers)
열 헤더는 각 열의 데이터를 설명하고, 행 헤더는 각 행의 데이터를 식별합니다. 스크린 리더는 사용자가 그리드를 탐색할 때 맥락을 제공하기 위해 이러한 연결을 사용합니다.
각 행에 대해 의미 있는 라벨(예: 사람 이름이나 제품 이름)을 가진 열에 rowHeader: true를 설정하세요.
해당 열의 셀은 rowheader 역할을 받습니다:
const columns: GridColDef[] = [
{ field: 'name', headerName: 'Product', rowHeader: true },
{ field: 'price', headerName: 'Price', type: 'number' },
];
import { DataGrid, GridColDef } from '@mui/x-data-grid';
const columns: GridColDef[] = [
{ field: 'name', headerName: 'Product', width: 180, rowHeader: true },
{ field: 'category', headerName: 'Category', width: 140 },
{ field: 'price', headerName: 'Price', type: 'number', width: 100 },
];
const rows = [
{ id: 1, name: 'Desk lamp', category: 'Lighting', price: 39 },
{ id: 2, name: 'Office chair', category: 'Furniture', price: 249 },
{ id: 3, name: 'Notebook', category: 'Stationery', price: 8 },
];
export default function RowHeaderGrid() {
return (
<div style={{ height: 250, width: '100%' }}>
<DataGrid rows={rows} columns={columns} hideFooter />
</div>
);
}
임의의 인덱스를 행 헤더로 사용하지 마세요. 행을 식별하는 데 둘 이상의 값이 필요한 경우 그리드는 여러 행 헤더 열을 가질 수 있습니다.
rowHeader 속성은 셀의 의미적 역할과 열이 가상화되는 방식을 변경합니다.
열의 위치, 가시성, 스타일은 변경하지 않습니다.
행 헤더 셀은 열 가상화가 해당 열을 화면 밖으로 스크롤해도 마운트된 상태로 유지되므로, 스크린 리더가 행 어디에서든 행의 정체성을 알릴 수 있습니다. 렌더링된 열 밖에 있는 동안에는 이 셀들이 공간을 차지하지 않습니다.
밀도(Density)
DataGrid는 다음 값을 지원하는 density prop을 노출합니다:
standard(기본)compactcomfortable
밀도 프로그래밍 방식으로 설정하기
다음 방법 중 하나로 밀도를 프로그래밍 방식으로 설정할 수 있습니다:
-
비제어 –
initialState.densityprop으로 밀도를 초기화합니다.<DataGrid initialState={{ density: 'compact', }} /> -
제어 –
density와onDensityChangeprop을 전달합니다. 더 고급 사용 사례의 경우densityChange그리드 이벤트를 구독할 수도 있습니다.const [density, setDensity] = React.useState<GridDensity>('compact'); return ( <DataGrid density={density} onDensityChange={(newDensity) => setDensity(newDensity)} /> );
density prop은 제공된 rowHeight 및 columnHeaderHeight prop으로 결정된 값을 적용합니다.
사용자는 선택적인 툴바 밀도 선택기로 이 설정을 오버라이드할 수 있습니다.
사용자가 DataGrid의 밀도를 변경할 수 있는 밀도 선택기가 있는 커스텀 툴바를 만들 수 있습니다. 아래 데모에서 확인하세요.
import * as React from 'react';
import {
DataGrid,
GridDensity,
gridDensitySelector,
Toolbar,
ToolbarButton,
useGridApiContext,
useGridSelector,
} from '@mui/x-data-grid';
import { useDemoData } from '@mui/x-data-grid-generator';
import Tooltip from '@mui/material/Tooltip';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import CheckIcon from '@mui/icons-material/Check';
import SettingsIcon from '@mui/icons-material/Settings';
const DENISTY_OPTIONS: { label: string; value: GridDensity }[] = [
{ label: 'Compact density', value: 'compact' },
{ label: 'Standard density', value: 'standard' },
{ label: 'Comfortable density', value: 'comfortable' },
];
function CustomToolbar() {
const apiRef = useGridApiContext();
const density = useGridSelector(apiRef, gridDensitySelector);
const [densityMenuOpen, setDensityMenuOpen] = React.useState(false);
const densityMenuTriggerRef = React.useRef<HTMLButtonElement>(null);
return (
<Toolbar>
<Tooltip title="Settings">
<ToolbarButton
ref={densityMenuTriggerRef}
id="density-menu-trigger"
aria-controls="density-menu"
aria-haspopup="true"
aria-expanded={densityMenuOpen ? 'true' : undefined}
onClick={() => setDensityMenuOpen(true)}
>
<SettingsIcon fontSize="small" sx={{ ml: 'auto' }} />
</ToolbarButton>
</Tooltip>
<Menu
id="density-menu"
anchorEl={densityMenuTriggerRef.current}
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
open={densityMenuOpen}
onClose={() => setDensityMenuOpen(false)}
slotProps={{
list: {
'aria-labelledby': 'density-menu-trigger',
},
}}
>
{DENISTY_OPTIONS.map((option) => (
<MenuItem
key={option.value}
onClick={() => {
apiRef.current.setDensity(option.value);
setDensityMenuOpen(false);
}}
>
<ListItemIcon>
{density === option.value && <CheckIcon fontSize="small" />}
</ListItemIcon>
<ListItemText>{option.label}</ListItemText>
</MenuItem>
))}
</Menu>
</Toolbar>
);
}
export default function DensitySelectorGrid() {
const { data } = useDemoData({
dataSet: 'Commodity',
rowLength: 4,
maxColumns: 6,
});
return (
<div style={{ height: 300, width: '100%' }}>
<DataGrid
{...data}
slots={{
toolbar: CustomToolbar,
}}
showToolbar
/>
</div>
);
}
사용자 환경설정을 로컬 저장소에 저장하는 설정 메뉴를 만드는 방법의 예시는 Toolbar component—Settings menu를 참고하세요.
키보드 탐색
DataGrid는 사용자의 키보드 상호작용을 수신하고 셀 내부에서 키 입력에 응답해 이벤트를 발생시킵니다.
탭 순서(Tab sequence)
WAI-ARIA Authoring Practices에 따르면, 복합 위젯(composite widget)에 포함된 포커스 가능 요소 중 단 하나만 페이지 탭 순서에 포함되어야 합니다.
요소가 탭 순서에 포함되려면 tabIndex 값이 0 이상이어야 합니다.
사용자가 DataGrid 셀에 포커스를 두면, tabIndex={0}을 가진 첫 번째 내부 요소가 포커스를 받습니다.
tabIndex={0}을 가진 요소가 없으면 셀 자체에 포커스가 설정됩니다.
아래 두 Data Grid는 페이지 탭 순서를 잘못 관리하면 데이터셋 탐색이 어려워져 사용자 경험이 어떻게 저하되는지 보여줍니다:
import {
DataGrid,
GridColDef,
GridRenderCellParams,
GridRowsProp,
} from '@mui/x-data-grid';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Link from '@mui/material/Link';
import Typography from '@mui/material/Typography';
function CorrectRenderLink(props: GridRenderCellParams) {
return (
<Link tabIndex={props.tabIndex} href="/#tab-sequence">
more info
</Link>
);
}
function WrongRenderLink() {
return <Link href="/#tab-sequence">more info</Link>;
}
const correctColumns: GridColDef[] = [
{ field: 'link', renderCell: CorrectRenderLink, width: 200 },
];
const wrongColumns: GridColDef[] = [
{ field: 'link', renderCell: WrongRenderLink, width: 200 },
];
const rows: GridRowsProp = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }];
export default function FocusManagement() {
return (
<Grid container spacing={1}>
<Grid size={{ xs: 12, md: 6 }}>
<Typography variant="body2">Without focus management</Typography>
<Box sx={{ height: 300 }}>
<DataGrid rows={rows} columns={wrongColumns} hideFooterSelectedRowCount />
</Box>
</Grid>
<Grid size={{ xs: 12, md: 6 }}>
<Typography variant="body2">Correct focus management</Typography>
<Box sx={{ height: 300 }}>
<DataGrid
rows={rows}
columns={correctColumns}
hideFooterSelectedRowCount
/>
</Box>
</Grid>
</Grid>
);
}
renderCell() 메서드로 셀 렌더링을 커스터마이즈하면, 포커스 가능한 요소를 페이지 탭 순서에서 제거할 책임이 생깁니다.
renderCell() params로 전달되는 tabIndex prop을 사용해 렌더링된 셀에 포커스가 있는지, 그리고 그 결과 내부 요소를 탭 순서에서 제거해야 하는지 판단합니다:
renderCell: (params) => (
<div>
<Link tabIndex={params.tabIndex} href="/#">
more info
</Link>
</div>
);
탭 탐색(Tab navigation)
기본 탭 순서 동작이 대부분의 사용 사례에서 잘 동작하지만, Tab 키가 그리드 내에서 탐색하는 방식을 커스터마이즈할 수도 있습니다.
DataGrid는 이 동작을 제어하는 tabNavigation prop을 제공합니다.
<DataGrid rows={rows} columns={columns} tabNavigation="content" />
tabNavigation prop은 다음 값을 지원합니다:
-
"none"(기본): 위에서 설명한 표준 탭 순서 동작입니다. 그리드에 포함된 포커스 가능한 요소 중 하나만 페이지 탭 순서에 포함되어야 한다는 grid composite widget 패턴과 일치합니다. 이 경우DataGrid는 Tab 키 입력을 처리하지 않아 브라우저 기본 탭 순서가 포커스 이동을 제어합니다. Tab 또는 Shift+Tab을 누르면 페이지 탭 순서에서 각각 다음 또는 이전 요소로 포커스가 이동하며, 이는 그리드 밖일 수도 있습니다. -
"content": Tab 탐색이 그리드 셀(콘텐츠 영역)에서만 활성화됩니다. Tab을 누르면 같은 행의 다음 셀로, 행 끝에서 누르면 다음 행의 첫 번째 셀로 포커스가 이동합니다. Shift+Tab을 누르면 같은 행의 이전 셀로, 행 시작에서 누르면 이전 행의 마지막 셀로 포커스가 이동합니다. 열 헤더에 포커스가 있고 Tab을 누르면 첫 번째 셀로 포커스가 이동합니다. 탭 탐색은 헤더, 헤더 필터, 열 그룹에서는 활성화되지 않습니다. -
"header": Tab 탐색이 헤더 영역(열 그룹, 열 헤더, 헤더 필터)에서만 활성화됩니다. Tab을 누르면 다음 헤더 요소로, Shift+Tab을 누르면 이전 헤더 요소로 포커스가 이동합니다. 셀에 포커스가 있고 Shift+Tab을 누르면 마지막 헤더 필터나 열 헤더로 포커스가 이동합니다. 탭 탐색은 그리드 셀에서는 활성화되지 않습니다. -
"all":"content"와"header"동작을 모두 결합합니다.
아래 데모는 각 tabNavigation 모드가 키보드 탐색에 어떤 영향을 주는지 보여줍니다:
:::info 데모에서 그리드 위아래의 탭 장벽(Tab Barrier)은 데모 영역을 벗어나지 않고 그리드 밖의 탐색을 추적하기 쉽도록 포함되었습니다. Tab 키를 여러 번 눌러 장벽을 통과하세요. :::
import * as React from 'react';
import Box from '@mui/material/Box';
import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import {
DataGridPro,
DataGridProProps,
GridColDef,
GridColumnGroupingModel,
} from '@mui/x-data-grid-pro';
const columns: GridColDef[] = [
{ field: 'id', headerName: 'ID', width: 120 },
{
field: 'firstName',
headerName: 'First name',
rowHeader: true,
width: 150,
},
{
field: 'lastName',
headerName: 'Last name',
rowHeader: true,
width: 150,
},
{
field: 'age',
headerName: 'Age',
type: 'number',
width: 110,
},
];
const rows = [
{ id: 1, lastName: 'Snow', firstName: 'Jon', age: 14 },
{ id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 31 },
{ id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 31 },
{ id: 4, lastName: 'Stark', firstName: 'Arya', age: 11 },
{ id: 5, lastName: 'Targaryen', firstName: 'Daenerys', age: null },
{ id: 6, lastName: 'Melisandre', firstName: null, age: 150 },
];
const columnGroupingModel: GridColumnGroupingModel = [
{
groupId: 'Internal',
description: '',
children: [{ field: 'id' }],
},
{
groupId: 'Basic info',
children: [
{
groupId: 'Full name',
children: [{ field: 'lastName' }, { field: 'firstName' }],
},
{ field: 'age' },
],
},
];
export default function TabNavigation() {
const keyPressCount = React.useRef(0);
const [tabNavigation, setTabNavigation] =
React.useState<DataGridProProps['tabNavigation']>('all');
const preventKeyDown =
(key: string, shiftKey: boolean) => (event: React.KeyboardEvent) => {
if (keyPressCount.current > 2) {
return;
}
if (event.key === key && event.shiftKey === shiftKey) {
event.preventDefault();
keyPressCount.current += 1;
}
};
const resetKeyPressCount = () => {
keyPressCount.current = 0;
};
return (
<div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 4 }}>
<FormLabel id="tab-navigation-radio-buttons-group-label">
Tab Navigation
</FormLabel>
<FormControl component="fieldset">
<RadioGroup
row
value={tabNavigation}
onChange={(event) =>
setTabNavigation(event.target.value as DataGridProProps['tabNavigation'])
}
name="grid-tab-navigation"
aria-labelledby="tab-navigation-radio-buttons-group-label"
>
<FormControlLabel
value="none"
control={<Radio />}
label={<code>"none"</code>}
/>
<FormControlLabel
value="content"
control={<Radio />}
label={<code>"content"</code>}
/>
<FormControlLabel
value="header"
control={<Radio />}
label={<code>"header"</code>}
/>
<FormControlLabel
value="all"
control={<Radio />}
label={<code>"all"</code>}
/>
</RadioGroup>
</FormControl>
{/* Top tab barrier */}
<div
role="button"
tabIndex={0}
onKeyDown={preventKeyDown('Tab', true)}
onBlur={resetKeyPressCount}
style={{
width: '100%',
padding: '8px',
textAlign: 'center',
fontSize: '12px',
}}
>
Tab Barrier (prevents Shift+Tab 3 times)
</div>
<Box style={{ height: 500, width: '100%' }}>
<DataGridPro
rows={rows}
columns={columns}
columnGroupingModel={columnGroupingModel}
tabNavigation={tabNavigation}
headerFilters
/>
</Box>
{/* Bottom tab barrier */}
<div
role="button"
tabIndex={0}
onKeyDown={preventKeyDown('Tab', false)}
onBlur={resetKeyPressCount}
style={{
width: '100%',
padding: '8px',
textAlign: 'center',
fontSize: '12px',
}}
>
Tab Barrier (prevents Tab 3 times)
</div>
</div>
);
}
탐색(Navigation)
:::info 아래 표의 키 할당은 Windows와 Linux 사용자에게 적용됩니다.
macOS에서는 다음을 바꾸세요:
- Ctrl → ⌘ Command
- Alt → ⌥ Option
일부 기기에는 특정 키가 없어 키 조합을 사용해야 할 수 있습니다. 이 경우 다음을 바꾸세요:
- Page Up → Fn+Arrow Up
- Page Down → Fn+Arrow Down
- Home → Fn+Arrow Left
- End → Fn+Arrow Right
:::
| Keys | 설명 |
|---|---|
| Arrow Left | 셀 요소 사이를 탐색 |
| Arrow Down | 셀 요소 사이를 탐색 |
| Arrow Right | 셀 요소 사이를 탐색 |
| Arrow Up | 셀 요소 사이를 탐색 |
| Home | 현재 행의 첫 번째 셀로 탐색 |
| End | 현재 행의 마지막 셀로 탐색 |
| Ctrl+Home | 첫 번째 행의 첫 번째 셀로 탐색 |
| Ctrl+End | 마지막 행의 마지막 셀로 탐색 |
| Space | 다음 스크롤 가능 페이지로 탐색 |
| Page Up | 이전 스크롤 가능 페이지로 탐색 |
| Page Down | 다음 스크롤 가능 페이지로 탐색 |
| Space | 그룹화 셀에 포커스가 있을 때 행 하위 항목 확장 토글 |
선택(Selection)
| Keys | 설명 |
|---|---|
| Shift+Space | 현재 행 선택/선택 해제 |
| Shift+Arrow Up/Down | 현재 행과 위 또는 아래 행을 선택 |
| Shift+ 셀 클릭 | 첫 번째로 클릭한 행과 마지막으로 클릭한 행 사이의 행 범위 선택 |
| Ctrl+A | 모든 행 선택, 또는 cellSelection이 활성화되어 있으면 모든 셀 선택 |
| Ctrl+C | 현재 선택된 행 복사 |
| Ctrl+ 셀 클릭 | 다중 선택 활성화 |
| Ctrl+ 선택된 행 클릭 | 행 선택 해제 |
정렬(Sorting)
| Keys | 설명 |
|---|---|
| Ctrl+ 헤더 클릭 | 다중 정렬 활성화 |
| Shift+ 헤더 클릭 | 다중 정렬 활성화 |
| Shift+Enter | 열 헤더에 포커스가 있을 때 다중 정렬 활성화 |
| Enter | 열 헤더에 포커스가 있을 때 열 정렬 |
| Ctrl+Enter | 열 헤더에 포커스가 있을 때 열 메뉴 열기 |
그룹 및 피벗(Group and pivot)
| Keys | 설명 |
|---|---|
| Ctrl+Enter | 행의 상세 패널 토글 |