Skip to content

Commit

Permalink
feat: PickerProps support config (#142)
Browse files Browse the repository at this point in the history
* chore: Add role in aria type

* add test case
  • Loading branch information
zombieJ committed Aug 31, 2020
1 parent 81e5fbf commit bb8a96b
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 24 deletions.
45 changes: 39 additions & 6 deletions src/pickAttrs.ts
Expand Up @@ -29,14 +29,47 @@ function match(key: string, prefix: string) {
return key.indexOf(prefix) === 0;
}

export default function pickAttrs(props: object, ariaOnly = false) {
export interface PickConfig {
aria?: boolean;
data?: boolean;
attr?: boolean;
}

/**
* Picker props from exist props with filter
* @param props Passed props
* @param ariaOnly boolean | { aria?: boolean; data?: boolean; attr?: boolean; } filter config
*/
export default function pickAttrs(
props: object,
ariaOnly: boolean | PickConfig = false,
) {
let mergedConfig: PickConfig;
if (ariaOnly === false) {
mergedConfig = {
aria: true,
data: true,
attr: true,
};
} else if (ariaOnly === true) {
mergedConfig = {
aria: true,
};
} else {
mergedConfig = {
...ariaOnly,
};
}

const attrs = {};
Object.keys(props).forEach(key => {
if (match(key, ariaPrefix)) {
attrs[key] = props[key];
} else if (
!ariaOnly &&
(propList.includes(key) || match(key, dataPrefix))
if (
// Aria
(mergedConfig.aria && (key === 'role' || match(key, ariaPrefix))) ||
// Data
(mergedConfig.data && match(key, dataPrefix)) ||
// Attr
(mergedConfig.attr && propList.includes(key))
) {
attrs[key] = props[key];
}
Expand Down
55 changes: 37 additions & 18 deletions tests/utils.test.js
Expand Up @@ -51,28 +51,47 @@ describe('utils', () => {
]);
});

it('pickAttrs', () => {
expect(
pickAttrs({
describe('pickAttrs', () => {
const originProps = {
onClick: null,
checked: true,
'data-my': 1,
'aria-this': 2,
skip: true,
role: 'button',
};

it('default', () => {
expect(pickAttrs(originProps)).toEqual({
onClick: null,
checked: true,
'data-my': 1,
'aria-this': 2,
skip: true,
}),
).toEqual({ onClick: null, checked: true, 'data-my': 1, 'aria-this': 2 });
role: 'button',
});
});

expect(
pickAttrs(
{
onClick: null,
checked: true,
'data-my': 1,
'aria-this': 2,
skip: true,
},
true,
),
).toEqual({ 'aria-this': 2 });
it('aria only', () => {
expect(pickAttrs(originProps, true)).toEqual({
'aria-this': 2,
role: 'button',
});
});

it('attr only', () => {
expect(pickAttrs(originProps, { attr: true })).toEqual({
onClick: null,
checked: true,
role: 'button',
});
});

it('aria & data', () => {
expect(pickAttrs(originProps, { aria: true, data: true })).toEqual({
'data-my': 1,
'aria-this': 2,
role: 'button',
});
});
});
});

0 comments on commit bb8a96b

Please sign in to comment.