get data-*, aria-*, and role attributes

This commit is contained in:
Matt Lein 2018-06-14 09:33:35 -05:00 committed by 偏右
parent 20348614d5
commit f0b684de6a
3 changed files with 49 additions and 11 deletions

View File

@ -1,5 +1,5 @@
import throttleByAnimationFrame from '../throttleByAnimationFrame';
import getDataAttributes from '../getDataAttributes';
import getDataOrAriaProps from '../getDataOrAriaProps';
describe('Test utils function', () => {
beforeAll(() => {
@ -34,7 +34,7 @@ describe('Test utils function', () => {
expect(callback).not.toBeCalled();
});
describe('getDataAttributes', () => {
describe('getDataOrAriaProps', () => {
it('returns all data-* properties from an object', () => {
const props = {
onClick: () => {},
@ -42,11 +42,46 @@ describe('Test utils function', () => {
'data-test': 'test-id',
'data-id': 1234,
};
const results = getDataAttributes(props);
const results = getDataOrAriaProps(props);
expect(results).toEqual({
'data-test': 'test-id',
'data-id': 1234,
});
});
it('does not return data-__ properties from an object', () => {
const props = {
onClick: () => {},
isOpen: true,
'data-__test': 'test-id',
'data-__id': 1234,
};
const results = getDataOrAriaProps(props);
expect(results).toEqual({});
});
it('returns all aria-* properties from an object', () => {
const props = {
onClick: () => {},
isOpen: true,
'aria-labelledby': 'label-id',
'aria-label': 'some-label',
};
const results = getDataOrAriaProps(props);
expect(results).toEqual({
'aria-labelledby': 'label-id',
'aria-label': 'some-label',
});
});
it('returns role property from an object', () => {
const props = {
onClick: () => {},
isOpen: true,
role: 'search',
};
const results = getDataOrAriaProps(props);
expect(results).toEqual({ role: 'search' });
});
});
});

View File

@ -1,8 +0,0 @@
export default function getDataAttributes(props: any) {
return Object.keys(props).reduce((prev: any, key: string) => {
if (key.substr(0, 5) === 'data-') {
prev[key] = props[key];
}
return prev;
}, {});
}

View File

@ -0,0 +1,11 @@
export default function getDataOrAriaProps(props: any) {
return Object.keys(props).reduce((prev: any, key: string) => {
if (
(key.substr(0, 5) === 'data-' || key.substr(0, 5) === 'aria-' || key === 'role') &&
key.substr(0, 7) !== 'data-__'
) {
prev[key] = props[key];
}
return prev;
}, {});
}