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

feat: PickerProps support config #142

Merged
merged 2 commits into from Aug 31, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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',
});
});
});
});