UNPKG

@reusable-ui/button

Version:

A button component for initiating an action.

57 lines (56 loc) 2.36 kB
// react: import { // react: default as React, } from 'react'; // reusable-ui core: import { useSemantic, useTestSemantic, // a set of client-side functions: isClientSideLink, } from '@reusable-ui/core'; // a set of reusable-ui packages which are responsible for building any component // defaults: const _defaultSemanticTag = ['button', 'a']; // uses <button> as the default semantic tag , fallbacks to <a> const _defaultSemanticRole = ['button', 'link']; // uses [role="button"] as the default semantic role, fallbacks to [role="link"] const _defaultLinkSemanticTag = ['a', 'button']; // uses <a> as the default semantic tag , fallbacks to <button> const _defaultLinkSemanticRole = ['link', 'button']; // uses [role="link"] as the default semantic role, fallbacks to [role="button"] export const useSemanticButton = (props) => { // fn props: const isNativeLink = !!props.href; // assigning [href] will render the <Button> as <a> const isClientLink = !isNativeLink && React.Children.toArray(props.children).some(isClientSideLink); /* if has [href] or <Link> => default to <a> or <foo role='link'> else => default to <button> or <foo role='button'> */ const semanticTag = props.semanticTag ?? ((isNativeLink || isClientLink) ? _defaultLinkSemanticTag : _defaultSemanticTag); const semanticRole = props.semanticRole ?? ((isNativeLink || isClientLink) ? _defaultLinkSemanticRole : _defaultSemanticRole); const { tag: finalTag, role: finalRole, } = useSemantic({ tag: props.tag, role: props.role, semanticTag, semanticRole, }); const { isDesiredType: isButtonType, isSemanticTag: isSemanticButton, } = useTestSemantic( // test: { tag: props.tag, role: props.role, semanticTag, semanticRole, }, // expected: { semanticTag: 'button', semanticRole: 'button', }); const type = props.type ?? (isSemanticButton ? 'button' : undefined); return { isNativeLink, isClientSideLink: isClientLink, semanticTag, semanticRole, tag: finalTag, role: finalRole, isButtonType, isSemanticButton, type, }; }; //#endregion SemanticButton