Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Add base Button component (#372)
sarayourfriend0014df8ee8f6
diff --git a/jest.config.js b/jest.config.jsindex 900dd0903..054e834be 100644--- a/jest.config.js+++ b/jest.config.js@@ -1,4 +1,9 @@module.exports = {+ globals: {+ 'vue-jest': {+ experimentalCSSCompile: false,+ },+ },moduleFileExtensions: ['js', 'vue', 'json'],moduleNameMapper: {'^@/(.*)$': '<rootDir>/src/$1',diff --git a/package-lock.json b/package-lock.jsonindex 8cdd07e62..e9eea03a2 100644--- a/package-lock.json+++ b/package-lock.json@@ -36,6 +36,7 @@"nuxt": "^2.15.4","nuxt-ssr-cache": "^1.5.2","patch-package": "^6.4.7",+ "reakit-utils": "^0.15.2","sass": "^1.34.0","sass-loader": "^10.1.1","uuid": "^8.3.2",@@ -22858,7 +22859,6 @@"node_modules/loose-envify": {"version": "1.4.0","integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",- "dev": true,"dependencies": {"js-tokens": "^3.0.0 || ^4.0.0"},@@ -32197,7 +32197,6 @@"node_modules/prop-types": {"version": "15.7.2","integrity": "sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==",- "dev": true,"dependencies": {"loose-envify": "^1.4.0","object-assign": "^4.1.1",@@ -32206,8 +32205,7 @@},"node_modules/prop-types/node_modules/react-is": {"version": "16.13.1",- "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",- "dev": true+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="},"node_modules/proper-lockfile": {"version": "4.1.2",@@ -32608,7 +32606,6 @@"node_modules/react": {"version": "16.14.0","integrity": "sha512-0X2CImDkJGApiAlcf0ODKIneSwBPhqJawOa5wCtKbu7ZECrmS26NvtSILynQ66cgkT/RJ4LidJOc3bUESwmU8g==",- "dev": true,"dependencies": {"loose-envify": "^1.1.0","object-assign": "^4.1.1",@@ -32898,7 +32895,6 @@"node_modules/react-dom": {"version": "16.14.0","integrity": "sha512-1gCeQXDLoIqMgqD3IO2Ah9bnf0w9kzhwN5q4FGnHZ67hBm9yePzB5JJAIQCc8x3pFnNlwFq4RidZggNAAkzWWw==",- "dev": true,"dependencies": {"loose-envify": "^1.1.0","object-assign": "^4.1.1",@@ -33138,6 +33134,15 @@"node": ">=8.10.0"}},+ "node_modules/reakit-utils": {+ "version": "0.15.2",+ "resolved": "https://registry.npmjs.org/reakit-utils/-/reakit-utils-0.15.2.tgz",+ "integrity": "sha512-i/RYkq+W6hvfFmXw5QW7zvfJJT/K8a4qZ0hjA79T61JAFPGt23DsfxwyBbyK91GZrJ9HMrXFVXWMovsKBc1qEQ==",+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0",+ "react-dom": "^16.8.0 || ^17.0.0"+ }+ },"node_modules/recast": {"version": "0.20.4","integrity": "sha512-6qLIBGGRcwjrTZGIiBpJVC/NeuXpogXNyRQpqU1zWPUigCphvApoCs9KIwDYh1eDuJ6dAFlQoi/QUyE5KQ6RBQ==",@@ -34117,7 +34122,6 @@"node_modules/scheduler": {"version": "0.19.1","integrity": "sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA==",- "dev": true,"dependencies": {"loose-envify": "^1.1.0","object-assign": "^4.1.1"@@ -56984,7 +56988,6 @@"loose-envify": {"version": "1.4.0","integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",- "dev": true,"requires": {"js-tokens": "^3.0.0 || ^4.0.0"}@@ -64202,7 +64205,6 @@"prop-types": {"version": "15.7.2","integrity": "sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==",- "dev": true,"requires": {"loose-envify": "^1.4.0","object-assign": "^4.1.1",@@ -64211,8 +64213,7 @@"dependencies": {"react-is": {"version": "16.13.1",- "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",- "dev": true+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="}}},@@ -64564,7 +64565,6 @@"react": {"version": "16.14.0","integrity": "sha512-0X2CImDkJGApiAlcf0ODKIneSwBPhqJawOa5wCtKbu7ZECrmS26NvtSILynQ66cgkT/RJ4LidJOc3bUESwmU8g==",- "dev": true,"requires": {"loose-envify": "^1.1.0","object-assign": "^4.1.1",@@ -64777,7 +64777,6 @@"react-dom": {"version": "16.14.0","integrity": "sha512-1gCeQXDLoIqMgqD3IO2Ah9bnf0w9kzhwN5q4FGnHZ67hBm9yePzB5JJAIQCc8x3pFnNlwFq4RidZggNAAkzWWw==",- "dev": true,"requires": {"loose-envify": "^1.1.0","object-assign": "^4.1.1",@@ -64967,6 +64966,12 @@"picomatch": "^2.2.1"}},+ "reakit-utils": {+ "version": "0.15.2",+ "resolved": "https://registry.npmjs.org/reakit-utils/-/reakit-utils-0.15.2.tgz",+ "integrity": "sha512-i/RYkq+W6hvfFmXw5QW7zvfJJT/K8a4qZ0hjA79T61JAFPGt23DsfxwyBbyK91GZrJ9HMrXFVXWMovsKBc1qEQ==",+ "requires": {}+ },"recast": {"version": "0.20.4","integrity": "sha512-6qLIBGGRcwjrTZGIiBpJVC/NeuXpogXNyRQpqU1zWPUigCphvApoCs9KIwDYh1eDuJ6dAFlQoi/QUyE5KQ6RBQ==",@@ -65717,7 +65722,6 @@"scheduler": {"version": "0.19.1","integrity": "sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA==",- "dev": true,"requires": {"loose-envify": "^1.1.0","object-assign": "^4.1.1"diff --git a/package.json b/package.jsonindex 393e61e30..5369f8d03 100644--- a/package.json+++ b/package.json@@ -61,6 +61,7 @@"nuxt": "^2.15.4","nuxt-ssr-cache": "^1.5.2","patch-package": "^6.4.7",+ "reakit-utils": "^0.15.2","sass": "^1.34.0","sass-loader": "^10.1.1","uuid": "^8.3.2",diff --git a/src/components/VButton.vue b/src/components/VButton.vuenew file mode 100644index 000000000..44c32b0f9--- /dev/null+++ b/src/components/VButton.vue@@ -0,0 +1,263 @@+<template>+ <Component+ :is="as"+ :type="typeRef"+ :role="role"+ :class="[+ $style.button,+ $style[variant],+ pressed && $style[`${variant}-pressed`],+ $style[`size-${size}`],+ ]"+ :aria-pressed="pressed"+ :aria-disabled="ariaDisabledRef"+ :disabled="disabledAttributeRef"+ v-on="$listeners"+ >+ <!--+ @slot The content of the button+ -->+ <slot />+ </Component>+</template>++<script>+import { defineComponent, ref, watch, toRefs } from '@nuxtjs/composition-api'++/**+ * A button component that behaves just like a regular HTML `button` element+ * aside from pre-applied styles based on the passed in variant.+ *+ * All props available for the basic `button` component are available here as+ * well, including an `as` prop which allows for component polymorphism. The+ * most common use case for this prop is to turn the `VButton` component into+ * an `anchor` element, so that you can render a link instead of a `button`.+ *+ * The accessibility helpers on this component are critical and are completely+ * adapted from Reakit's Button, Clickable, and Tabbable component implementations.+ */+const VButton = defineComponent({+ name: 'VButton',+ props: {+ /**+ * Passed to `component :is` to allow the button to *appear* as a button but+ * work like another element (like an `anchor`). May only be either `button` or `a`.+ *+ * We do not support other elements because their use cases are marginal and they+ * add complexity that we can avoid otherwise.+ *+ * We also don't allow any old Vue component because Vue does not have ref-forwarding+ * so we wouldn't be able to detect the type of the DOM node that is ultimately rendered+ * by any Vue component passed.+ *+ * @default 'button'+ */+ as: {+ type: String,+ default: 'button',+ validate: (v) => ['a', 'button'].includes(v),+ },+ /**+ * The variant of the button.+ *+ * @default 'primary'+ */+ variant: {+ type: String,+ default: 'primary',+ validate: (v) =>+ [+ 'primary',+ 'secondary',+ 'tertiary',+ 'action-menu',+ 'action-menu-muted',+ ].includes(v),+ },+ /**+ * Allows for programmatically setting the pressed state of a button,+ * i.e., in the case of a button opening a menu.+ *+ * @default false+ */+ pressed: {+ type: Boolean,+ default: false,+ },+ /**+ * The size of the button.+ *+ * @default 'medium'+ */+ size: {+ type: String,+ default: 'medium',+ validate: (v) => ['large', 'medium', 'small'].includes(v),+ },+ /**+ * Whether the button is disabled. Used alone this will only+ * visually effect the button but will not "truly" disable the+ * button unless the `focusable` prop is also set to `false`.+ *+ * @default false+ */+ disabled: {+ type: Boolean,+ default: false,+ },+ /**+ * Whether the button is focusable when disabled. Should be `false`+ * in almost all cases except when a button needs to be focusable+ * while still being disabled (in the case of a form submit button+ * that is disabled due to an incomplete form for example).+ *+ * @default false+ */+ focusableWhenDisabled: {+ type: Boolean,+ default: false,+ },+ /**+ * The HTML `type` attribute for the button. Ignored if `as` is+ * passed as anything other than `"button"`.+ *+ * @default 'button'+ */+ type: {+ type: String,+ default: 'button',+ validate: (v) => ['button', 'submit', 'reset'].includes(v),+ },+ },+ /* eslint-disable no-unused-vars */+ setup(props, { attrs }) {+ const propsRef = toRefs(props)+ const disabledAttributeRef = ref(propsRef.disabled.value)+ const ariaDisabledRef = ref()+ const trulyDisabledRef = ref()+ const typeRef = ref(propsRef.type.value)+ const supportsDisabledAttributeRef = ref(true)++ watch(+ [propsRef.disabled, propsRef.focusableWhenDisabled],+ ([disabled, focusableWhenDisabled]) => {+ trulyDisabledRef.value = disabled && !focusableWhenDisabled++ // If disabled and focusable then use `aria-disabled` instead of the `disabled` attribute to allow+ // the button to still be tabbed into by screen reader users+ if (disabled && focusableWhenDisabled) {+ ariaDisabledRef.value = true+ } else {+ ariaDisabledRef.value = undefined+ }+ },+ { immediate: true }+ )++ watch(+ propsRef.as,+ (as) => {+ if (as === 'a') {+ typeRef.value = undefined+ supportsDisabledAttributeRef.value = false++ // No need to decalare `href` as an explicit prop as Vue preserves+ // the `attrs` object reference between renders and updates the properties+ // meaning we'll always have the latest values for the properties on the+ // attrs object+ if (!attrs.href || attrs.href === '#') {+ console.warn(+ 'Do not use anchor elements without a valid `href` attribute. Use a `button` instead.'+ )+ }+ }+ },+ { immediate: true }+ )++ watch(+ [trulyDisabledRef, supportsDisabledAttributeRef],+ ([trulyDisabled, supportsDisabled]) => {+ disabledAttributeRef.value =+ trulyDisabled && supportsDisabled ? true : undefined+ },+ { immediate: true }+ )++ return {+ disabledAttributeRef,+ ariaDisabledRef,+ typeRef,+ }+ },+})++export default VButton+</script>++<style module>+.button {+ @apply flex max-w-max items-center rounded-sm justify-center transition-shadow duration-100 ease-linear disabled:opacity-70 focus:outline-none focus-visible:ring focus-visible:ring-offset-2 no-underline appearance-none;+}++.button[disabled='disabled'],+.button[aria-disabled='true'] {+ @apply opacity-50;+}++.size-small {+ @apply py-1 px-2;+}++.size-medium {+ @apply py-2 px-4;+}++.size-large {+ @apply py-6 px-8;+}++a.button {+ @apply no-underline;+}++.primary {+ @apply bg-pink text-white focus-visible:ring-pink hover:bg-dark-pink hover:text-white;+}++.primary-pressed {+ @apply bg-dark-pink;+}++.secondary {+ @apply bg-dark-charcoal text-white font-bold focus-visible:ring-pink hover:bg-dark-charcoal-80 hover:text-white;+}++.secondary-pressed {+ @apply bg-dark-charcoal-80;+}++.tertiary {+ @apply bg-white text-black hover:bg-dark-charcoal hover:text-white border border-dark-charcoal-20 hover:border-tx focus-visible:ring-pink;+}++.tertiary-pressed {+ @apply bg-dark-charcoal text-white border-tx;+}++.action-menu {+ @apply bg-white text-black border border-tx hover:border-dark-charcoal-20 focus-visible:ring-pink;+}++.action-menu-pressed {+ @apply border-tx bg-dark-charcoal text-white;+}++.action-menu-muted {+ @apply bg-dark-charcoal-10 text-black border border-tx hover:border-dark-charcoal-20 focus-visible:ring-pink;+}++.action-menu-muted-pressed {+ @apply border-tx bg-dark-charcoal text-white;+}+</style>diff --git a/src/components/meta/VButton.stories.js b/src/components/meta/VButton.stories.jsnew file mode 100644index 000000000..c546c3002--- /dev/null+++ b/src/components/meta/VButton.stories.js@@ -0,0 +1,43 @@+import VButton from '~/components/VButton'++export default {+ title: 'Components/VButton',+ component: VButton,+ argTypes: {+ variant: {+ options: [+ 'primary',+ 'secondary',+ 'tertiary',+ 'action-menu',+ 'action-menu-muted',+ ],+ control: { type: 'radio' },+ },+ as: {+ options: ['button', 'a'],+ control: { type: 'radio' },+ },+ pressed: 'boolean',+ size: {+ options: ['large', 'medium', 'small'],+ control: { type: 'radio' },+ },+ disabled: 'boolean',+ focusableWhenDisabled: 'boolean',+ },+}++const VButtonStory = (args, { argTypes }) => ({+ template: `<VButton v-bind="$props" @click="onClick">Code is Poetry</VButton>`,+ components: { VButton },+ props: Object.keys(argTypes),+ methods: {+ onClick() {+ window.alert('hello!')+ },+ },+})++export const Default = VButtonStory.bind({})+Default.args = {}diff --git a/src/utils/a11y/get-tab-index.js b/src/utils/a11y/get-tab-index.jsnew file mode 100644index 000000000..6ff387426--- /dev/null+++ b/src/utils/a11y/get-tab-index.js@@ -0,0 +1,32 @@+/**+ * @see https://github.com/reakit/reakit/blob/f05d36daa6fbcc52c70cf2c71baea69025aa2402/packages/reakit/src/Tabbable/Tabbable.ts#L54+ * @param {boolean} trulyDisabled+ * @param {boolean} nativeTabbable+ * @param {boolean} supportsDisabled+ * @param {number} [htmlTabIndex]+ * @returns {number}+ */+export function getTabIndex(+ trulyDisabled,+ nativeTabbable,+ supportsDisabled,+ htmlTabIndex+) {+ if (trulyDisabled) {+ if (nativeTabbable && !supportsDisabled) {+ // Anchor, audio and video tags don't support the `disabled` attribute.+ // We must pass tabIndex={-1} so they don't receive focus on tab.+ return -1+ }+ // Elements that support the `disabled` attribute don't need tabIndex.+ return undefined+ }+ if (nativeTabbable) {+ // If the element is enabled and it's natively tabbable, we don't need to+ // specify a tabIndex attribute unless it's explicitly set by the user.+ return htmlTabIndex+ }+ // If the element is enabled and is not natively tabbable, we have to+ // fallback tabIndex={0}.+ return htmlTabIndex || 0+}diff --git a/src/utils/a11y/is-native-tabbale.js b/src/utils/a11y/is-native-tabbale.jsnew file mode 100644index 000000000..77956ecd8--- /dev/null+++ b/src/utils/a11y/is-native-tabbale.js@@ -0,0 +1,10 @@+/**+ * @see https://github.com/reakit/reakit/blob/f05d36daa6fbcc52c70cf2c71baea69025aa2402/packages/reakit/src/Tabbable/Tabbable.ts#L44+ * @param {Element} element+ * @returns {boolean}+ */+export function isNativeTabbable(element) {+ return ['BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'A'].includes(+ element.tagName+ )+}diff --git a/src/utils/a11y/supports-disabled-attribute.js b/src/utils/a11y/supports-disabled-attribute.jsnew file mode 100644index 000000000..6f6b92461--- /dev/null+++ b/src/utils/a11y/supports-disabled-attribute.js@@ -0,0 +1,8 @@+/**+ * @see https://github.com/reakit/reakit/blob/f05d36daa6fbcc52c70cf2c71baea69025aa2402/packages/reakit/src/Tabbable/Tabbable.ts#L50+ * @param {Element} element+ * @returns {boolean}+ */+export function supportsDisabledAttribute(element) {+ return ['BUTTON', 'INPUT', 'SELECT', 'TEXTAREA'].includes(element.tagName)+}diff --git a/tailwind.config.js b/tailwind.config.jsindex 87bcec5ac..0e85259fc 100644--- a/tailwind.config.js+++ b/tailwind.config.js@@ -37,11 +37,17 @@ module.exports = {// WordPress'admin-gray': '#DCDCDE',- // Semi-transparent- 'dark-charcoal-04': 'rgba(48, 39, 46, 0.04)',- 'dark-charcoal-20': 'rgba(48, 39, 46, 0.2)',- 'dark-charcoal-60': 'rgba(48, 39, 46, 0.6)',- 'dark-charcoal-70': 'rgba(48, 39, 46, 0.7)',+ // Dark Charcoal+ 'dark-charcoal-04': 'rgba(48, 39, 46, 0.04)', // This is a legacy opacity-based color. We should avoid it if possible+ 'dark-charcoal-06': '#F3F2F2',+ 'dark-charcoal-10': '#EAE9EA',+ 'dark-charcoal-20': '#D6D4D5',+ 'dark-charcoal-30': '#C1BEC0',+ 'dark-charcoal-40': '#ACA9AB',+ 'dark-charcoal-50': '#989397',+ 'dark-charcoal-60': '#837D82',+ 'dark-charcoal-70': '#6E686D',+ 'dark-charcoal-80': '#595258',// Special keywordstx: 'transparent',diff --git a/test/unit/specs/components/v-button.spec.js b/test/unit/specs/components/v-button.spec.jsnew file mode 100644index 000000000..b3c75fae7--- /dev/null+++ b/test/unit/specs/components/v-button.spec.js@@ -0,0 +1,120 @@+import { render, screen } from '@testing-library/vue'++import VButton from '~/components/VButton.vue'++/**+ * Throughout this suite we use the `screen.findBy*` functions to asynchronously+ * wait for the component to re-render. There might be some kind of performance+ * problem with the component's implementation, but if we don't "wait" for it+ * to settle, then all the props that are changed after `onMounted` completes+ * won't be rendered.+ */+describe('VButton', () => {+ let warn+ beforeAll(() => {+ warn = console.warn+ console.warn = jest.fn()+ })+ beforeEach(() => {+ console.warn.mockReset()+ })+ afterAll(() => {+ console.warn = warn+ })++ it('should render a `button` by default with type="button" and no tabindex', async () => {+ render(VButton, {+ slots: { default: 'Code is Poetry' },+ })++ const element = await screen.findByRole('button')++ expect(element.tagName).toBe('BUTTON')+ expect(element).toHaveAttribute('type', 'button')+ expect(element).not.toHaveAttribute('tabindex')+ })++ it('should allow passing an explicit type', async () => {+ render(VButton, {+ props: { type: 'submit' },+ slots: { default: 'Code is Poetry' },+ })++ const element = await screen.findByRole('button')++ expect(element).toHaveAttribute('type', 'submit')+ })++ // @todo(sarayourfriend) fix this failing test!+ it.skip('should render an anchor with no type attribute', async () => {+ render(VButton, {+ props: { as: 'a' },+ slots: { default: 'Code is Poetry' },+ })++ const element = await screen.findByText(/code is poetry/i)++ screen.debug(element)++ expect(element.tagName).toBe('A')+ expect(element).not.toHaveAttribute('type')+ })++ it('should render the disabled attribute on a button when the element is explicitly unfocusableWhenDisabled and is disabled', async () => {+ render(VButton, {+ props: { disabled: true, focusableWhenDisabled: false },+ slots: { default: 'Code is Poetry' },+ })++ const element = await screen.findByRole('button')++ // Vue renders the disabled attribute having a `true` value as `[disabled="disabled"]`+ expect(element).toHaveAttribute('disabled', 'disabled')+ })++ it('should not render the disabled attribute if the element is focusableWhenDisabled', async () => {+ render(VButton, {+ props: { disabled: true, focusableWhenDisabled: true },+ slots: { default: 'Code is Poetry' },+ })++ const element = await screen.findByRole('button')++ expect(element).not.toHaveAttribute('disabled')+ expect(element).toHaveAttribute('aria-disabled', 'true')+ })++ it('should not render the disabled attribute on elements that do not support it', async () => {+ render(VButton, {+ props: {+ as: 'a',+ disabled: true,+ focusableWhenDisabled: true,+ href: 'https://wordpress.org',+ },+ slots: { default: 'Code is Poetry' },+ })++ const element = await screen.findByText(/code is poetry/i)++ expect(element).not.toHaveAttribute('disabled')+ expect(element).toHaveAttribute('aria-disabled', 'true')+ })++ it.each([undefined, '', null, '#'])(+ 'should warn if an anchor is used without a valid href: %s',+ async (href) => {+ render(VButton, {+ props: { as: 'a', href },+ slots: { default: 'Code is Poetry' },+ })++ await screen.findByText(/code is poetry/i)++ expect(console.warn).toHaveBeenCalledTimes(1)+ expect(console.warn).toHaveBeenCalledWith(+ 'Do not use anchor elements without a valid `href` attribute. Use a `button` instead.'+ )+ }+ )+})