Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Create the `InputField` and `SearchBar` components (#380)

Dhruv Bhanushali73490b935545
diff --git a/.eslintrc.js b/.eslintrc.js
index ee636af4c..1c4008085 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -46,6 +46,10 @@ module.exports = {
},
],
'vuejs-accessibility/aria-role': 'warn',
+ 'vuejs-accessibility/label-has-for': [
+ 'warn',
+ { required: { some: ['nesting', 'id'] } },
+ ],
'unicorn/filename-case': ['error', { case: 'kebabCase' }],
},
settings: {
diff --git a/.storybook/decorators/with-rtl.js b/.storybook/decorators/with-rtl.js
index 6f1f8f8af..2ce8ae547 100644
--- a/.storybook/decorators/with-rtl.js
+++ b/.storybook/decorators/with-rtl.js
@@ -1,6 +1,6 @@
import Vue from 'vue'
-import { ref, watch, useContext } from '@nuxtjs/composition-api'
+import { ref, watch, useContext, onMounted } from '@nuxtjs/composition-api'
import { useEffect } from '@storybook/client-api'
const languageDirection = Vue.observable({ value: 'ltr' })
@@ -16,14 +16,20 @@ export const WithRTL = (story, context) => {
setup() {
const element = ref()
const { i18n } = useContext()
- watch(languageDirection, (direction) => {
- i18n.localeProperties.dir = direction.value
- if (element.value) {
- element.value.ownerDocument.documentElement.setAttribute(
- 'dir',
- direction.value
- )
- }
+ onMounted(() => {
+ watch(
+ languageDirection,
+ (direction) => {
+ i18n.localeProperties.dir = direction.value
+ if (element.value) {
+ element.value.ownerDocument.documentElement.setAttribute(
+ 'dir',
+ direction?.value ?? 'ltr'
+ )
+ }
+ },
+ { immediate: true }
+ )
})
return { element }
},
diff --git a/src/assets/icons/search.svg b/src/assets/icons/search.svg
new file mode 100644
index 000000000..ee371a205
--- /dev/null
+++ b/src/assets/icons/search.svg
@@ -0,0 +1,6 @@
+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <g id="icon">
+ <path d="M6 18L10 14.5" stroke="currentColor" stroke-width="1.5"/>
+ <circle cx="13.5" cy="11.5" r="4.75" stroke="currentColor" stroke-width="1.5" fill="none"/>
+ </g>
+</svg>
diff --git a/src/components/Header/SearchBar/SearchBar.vue b/src/components/Header/SearchBar/SearchBar.vue
new file mode 100644
index 000000000..fd9b7044c
--- /dev/null
+++ b/src/components/Header/SearchBar/SearchBar.vue
@@ -0,0 +1,81 @@
+<template>
+ <form class="search-bar group flex flex-row" @submit.prevent="handleSearch">
+ <InputField
+ v-model="text"
+ v-bind="$attrs"
+ class="flex-grow search-field"
+ :connection-sides="['end']"
+ input-id="search-bar"
+ type="search"
+ name="q"
+ >
+ <!-- @slot Extra information such as loading message or result count goes here. -->
+ <slot />
+ </InputField>
+ <SearchButton type="submit" />
+ </form>
+</template>
+
+<script>
+import { computed } from '@nuxtjs/composition-api'
+
+import InputField from '~/components/InputField/InputField.vue'
+import SearchButton from '~/components/Header/SearchBar/SearchButton.vue'
+
+/**
+ * Displays a text field for a search query and is attached to an action button
+ * that fires a search request. The loading state and number of hits are also
+ * displayed in the bar itself.
+ */
+export default {
+ name: 'SearchBar',
+ components: {
+ InputField,
+ SearchButton,
+ },
+ inheritAttrs: false,
+ model: {
+ prop: 'value',
+ event: 'input',
+ },
+ props: {
+ /**
+ * the search query given as input to the field
+ */
+ value: {
+ type: String,
+ default: '',
+ },
+ },
+ setup(props, { emit }) {
+ const text = computed({
+ get() {
+ return props.value
+ },
+ set(value) {
+ emit('input', value)
+ },
+ })
+
+ const handleSearch = () => {
+ emit('submit')
+ }
+
+ return {
+ text,
+
+ handleSearch,
+ }
+ },
+}
+</script>
+
+<style>
+/* Removes the cross icon to clear the field */
+.search-field input[type='search']::-webkit-search-decoration,
+.search-field input[type='search']::-webkit-search-cancel-button,
+.search-field input[type='search']::-webkit-search-results-button,
+.search-field input[type='search']::-webkit-search-results-decoration {
+ -webkit-appearance: none;
+}
+</style>
diff --git a/src/components/Header/SearchBar/SearchButton.vue b/src/components/Header/SearchBar/SearchButton.vue
new file mode 100644
index 000000000..5eb918e57
--- /dev/null
+++ b/src/components/Header/SearchBar/SearchButton.vue
@@ -0,0 +1,42 @@
+<template>
+ <button
+ :type="type"
+ class="search-button flex items-center justify-center h-12 w-12 hover:text-white group-hover:text-white hover:bg-pink group-hover:bg-pink p-0.5px ps-1.5px focus:p-0 border border-s-0 focus:border-1.5 border-dark-charcoal-20 hover:border-pink group-hover:border-pink focus:border-pink rounded-e-sm focus:outline-none"
+ :aria-label="$t('search.search')"
+ v-on="$listeners"
+ >
+ <svg
+ class="h-6 w-6"
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ aria-hidden="true"
+ focusable="false"
+ >
+ <use :href="`${searchIcon}#icon`" />
+ </svg>
+ <span class="sr-only">{{ $t('search.search') }}</span>
+ </button>
+</template>
+
+<script>
+import searchIcon from '~/assets/icons/search.svg'
+
+export default {
+ name: 'SearchButton',
+ setup(props, { attrs }) {
+ const type = attrs['type'] ?? 'button'
+
+ return {
+ searchIcon,
+
+ type,
+ }
+ },
+}
+</script>
+
+<style scoped>
+.search-button:active {
+ box-shadow: 0 0 0 1px inset white;
+}
+</style>
diff --git a/src/components/Header/SearchBar/meta/SearchBar.stories.mdx b/src/components/Header/SearchBar/meta/SearchBar.stories.mdx
new file mode 100644
index 000000000..1851645ad
--- /dev/null
+++ b/src/components/Header/SearchBar/meta/SearchBar.stories.mdx
@@ -0,0 +1,90 @@
+import {
+ ArgsTable,
+ Canvas,
+ Description,
+ Meta,
+ Story,
+} from '@storybook/addon-docs'
+import SearchBar from '~/components/Header/SearchBar/SearchBar.vue'
+
+<Meta
+ title="Components/Header/Search bar"
+ component={SearchBar}
+ argTypes={{
+ input: {
+ action: 'input',
+ },
+ submit: {
+ action: 'submit',
+ },
+ }}
+/>
+
+export const Template = (args, { argTypes }) => ({
+ template: `
+ <SearchBar v-bind="$props" v-on="$props">
+ 12,345 results
+ </SearchBar>`,
+ components: { SearchBar },
+ props: Object.keys(argTypes),
+})
+
+# Search bar
+
+<Description of={SearchBar} />
+
+<ArgsTable of={SearchBar} />
+
+The component emits an `input` event with the new contents of the field whenever
+the field receives an input. It also emits the `search` event when the search
+button is clicked.
+
+<Canvas>
+ <Story
+ name="Default"
+ args={{
+ value: 'Search query',
+ }}
+ >
+ {Template.bind({})}
+ </Story>
+</Canvas>
+
+The recommended way to use it is with `v-model` mapping to a `String`
+representing the search query.
+
+export const vModelTemplate = () => ({
+ template: `
+ <div>
+ <SearchBar v-model="text">
+ {{ text.length }}
+ </SearchBar>
+ {{ text }}
+ </div>
+ `,
+ components: { SearchBar },
+ data() {
+ return {
+ text: 'Hello, World!',
+ }
+ },
+})
+
+<Canvas>
+ <Story name="v-model">{vModelTemplate.bind({})}</Story>
+</Canvas>
+
+The `SearchBar` component passes all attributes down to the inner `InputField`
+which itself applies all its attributes to its inner `<input>` element. So it's
+easy `<input>` attributes like placeholders or HTML validations.
+
+<Canvas>
+ <Story
+ name="With placeholder"
+ args={{
+ placeholder: 'Search query',
+ }}
+ >
+ {Template.bind({})}
+ </Story>
+</Canvas>
diff --git a/src/components/InputField/InputField.vue b/src/components/InputField/InputField.vue
new file mode 100644
index 000000000..21b574e46
--- /dev/null
+++ b/src/components/InputField/InputField.vue
@@ -0,0 +1,101 @@
+<template>
+ <div
+ class="input-field group flex flex-row items-center gap-4 hover:bg-dark-charcoal-06 focus-within:bg-dark-charcoal-06 group-hover:bg-dark-charcoal-06 h-12 p-0.5px focus-within:p-0 border focus-within:border-1.5 border-dark-charcoal-20 rounded-sm overflow-hidden focus-within:border-pink"
+ :class="[
+ {
+ // Padding is set to 1.5px to accommodate the border that will appear later.
+ 'border-s-0 ps-1.5px rounded-s-none': connectionSides.includes('start'),
+ 'border-e-0 pe-1.5px rounded-e-none': connectionSides.includes('end'),
+ },
+ ]"
+ >
+ <label class="sr-only" :for="fieldId">{{ labelText }}</label>
+ <input
+ :id="fieldId"
+ v-model="text"
+ v-bind="$attrs"
+ :type="type"
+ class="flex-grow leading-none font-semibold bg-tx placeholder-dark-charcoal-70 ms-4 h-full focus:outline-none"
+ v-on="$listeners"
+ />
+ <div
+ class="info font-semibold text-xs text-dark-charcoal-70 group-hover:text-dark-charcoal group-focus:text-dark-charcoal me-4"
+ >
+ <!-- @slot Extra information goes here -->
+ <slot />
+ </div>
+ </div>
+</template>
+
+<script>
+import { computed } from '@nuxtjs/composition-api'
+
+/**
+ * Provides a control to enter text as input.
+ */
+export default {
+ name: 'InputField',
+ inheritAttrs: false,
+ model: {
+ prop: 'value',
+ event: 'input',
+ },
+ props: {
+ /**
+ * the textual content of the input field
+ */
+ value: {
+ type: String,
+ default: '',
+ },
+ /**
+ * the textual content of the label associated with this input field; This
+ * label is SR-only.
+ */
+ labelText: {
+ type: String,
+ required: true,
+ },
+ /**
+ * the ID to assign to the field; This can be used to attach custom labels
+ * to the field.
+ */
+ fieldId: {
+ type: String,
+ required: true,
+ },
+ /**
+ * list of sides where the field is connected to other controls
+ */
+ connectionSides: {
+ type: Array,
+ default: () => [],
+ validator: (val) => val.every((item) => ['start', 'end'].includes(item)),
+ },
+ },
+ setup(props, { emit, attrs }) {
+ const type = attrs['type'] ?? 'text'
+
+ const text = computed({
+ get() {
+ return props.value
+ },
+ set(value) {
+ emit('input', value)
+ },
+ })
+
+ return {
+ type,
+
+ text,
+ }
+ },
+}
+</script>
+
+<style scoped>
+.input-field:focus-within .info {
+ @apply text-dark-charcoal;
+}
+</style>
diff --git a/src/components/InputField/meta/InputField.stories.mdx b/src/components/InputField/meta/InputField.stories.mdx
new file mode 100644
index 000000000..3c893541f
--- /dev/null
+++ b/src/components/InputField/meta/InputField.stories.mdx
@@ -0,0 +1,136 @@
+import {
+ ArgsTable,
+ Canvas,
+ Description,
+ Meta,
+ Story,
+} from '@storybook/addon-docs'
+
+import InputField from '~/components/InputField/InputField.vue'
+
+<Meta
+ title="Components/Input field"
+ component={InputField}
+ argTypes={{
+ input: {
+ action: 'input',
+ },
+ }}
+/>
+
+export const Template = (args, { argTypes }) => ({
+ template: `
+ <InputField v-bind="$props" v-on="$props">
+ Extra info
+ </InputField>
+ `,
+ components: { InputField },
+ props: Object.keys(argTypes),
+})
+
+# Input field
+
+<Description of={InputField} />
+
+<ArgsTable of={InputField} />
+
+The component emits an `input` event with the new contents of the field whenever
+the field receives an input.
+
+<Canvas>
+ <Story
+ name="Default"
+ args={{
+ value: 'Text goes here',
+ }}
+ >
+ {Template.bind({})}
+ </Story>
+</Canvas>
+
+The recommended way to use it is with `v-model` mapping to a `String`.
+
+export const vModelTemplate = () => ({
+ template: `
+ <div>
+ <InputField v-model="text">
+ {{ text.length }}
+ </InputField>
+ {{ text }}
+ </div>
+ `,
+ components: { InputField },
+ data() {
+ return {
+ text: 'Hello, World!',
+ }
+ },
+})
+
+<Canvas>
+ <Story name="v-model">{vModelTemplate.bind({})}</Story>
+</Canvas>
+
+The component is a transparent wrapper over `<input>` so all attributes of the
+input element can be applied to it, e.g. `placeholder`. It is recommended not to
+change the type as the field is specifically designed for text.
+
+<Canvas>
+ <Story
+ name="With placeholder"
+ args={{
+ placeholder: 'Enter something here',
+ }}
+ >
+ {Template.bind({})}
+ </Story>
+</Canvas>
+
+For a11y, it is recommended that the input field be associated with a label. For
+this reason, the field is rendered with an SR-only label. The text can be set
+via the `labelText` prop.
+
+<Canvas>
+ <Story
+ name="With label text"
+ args={{
+ labelText: 'Label:',
+ }}
+ >
+ {Template.bind({})}
+ </Story>
+</Canvas>
+
+To provide a custom label, skip the `labelText` prop (to remove the SR-only
+label) and set the `id` attribute on the component (which is passed to the
+`<input>` element). Now use the ID as the `for` attribute of your custom
+`<label>` element.
+
+export const labelTemplate = () => ({
+ template: `
+ <div>
+ <label for="field">Label:</label>
+ <InputField id="field"/>
+ </div>
+ `,
+ components: { InputField },
+})
+
+<Canvas>
+ <Story name="With custom label">{labelTemplate.bind({})}</Story>
+</Canvas>
+
+The field can be conjoined with other controls on either the start or the end
+side and as such it provides the `connectionSides` prop to make the connections
+seamless. The field has no border or rounded corners on the connected sides.
+
+<Canvas>
+ <Story
+ name="With connections"
+ args={{
+ connectionSides: ['start', 'end'],
+ }}
+ >
+ {Template.bind({})}
+ </Story>
+</Canvas>
diff --git a/src/locales/en.json b/src/locales/en.json
index a31697fa6..66f45ddb8 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -621,6 +621,9 @@
"pause": "Pause",
"replay": "Replay"
},
+ "search": {
+ "search": "Search"
+ },
"audio-categories": {
"title": "Audio Category",
"music": "Music",
diff --git a/src/locales/po-files/openverse.pot b/src/locales/po-files/openverse.pot
index 734d8e4b5..c450f00d6 100644
--- a/src/locales/po-files/openverse.pot
+++ b/src/locales/po-files/openverse.pot
@@ -4,7 +4,7 @@ msgid ""
msgstr ""
"Project-Id-Version: Openverse \n"
"Report-Msgid-Bugs-To: https://github.com/wordpress/openverse/issues \n"
-"POT-Creation-Date: 2021-11-05T09:58:32+00:00\n"
+"POT-Creation-Date: 2021-11-10T03:17:03+00:00\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
@@ -97,6 +97,11 @@ msgctxt "audio-categories.podcast"
msgid "Podcast"
msgstr ""
+#: src/components/Header/SearchBar/SearchButton.vue:5
+msgctxt "search.search"
+msgid "Search"
+msgstr ""
+
msgctxt "play-pause.play"
msgid "Play"
msgstr ""
diff --git a/tailwind.config.js b/tailwind.config.js
index c15c4a48a..d9391c73c 100644
--- a/tailwind.config.js
+++ b/tailwind.config.js
@@ -48,7 +48,9 @@ module.exports = {
fill: (theme) => theme('colors'),
spacing: {
// Constants
+ '0.5px': '0.5px',
px: '1px',
+ '1.5px': '1.5px',
ch: '1ch',
ex: '1ex',
half: '50%',
@@ -76,6 +78,13 @@ module.exports = {
},
ringWidth: {
DEFAULT: '1.5px',
+ 0: 0,
+ },
+ borderWidth: {
+ 0: '0px',
+ DEFAULT: '1px',
+ 1.5: '1.5px',
+ 2: '2px',
},
ringOffsetWidth: {
2: '2px',
@@ -171,6 +180,8 @@ module.exports = {
ringColor: ['focus-visible'],
ringOffsetWidth: ['focus-visible'],
ringWidth: ['focus-visible'],
+ borderWidth: ['focus', 'focus-within'],
+ padding: ['focus', 'focus-within'],
},
},
plugins: [require('tailwindcss-rtl')],
diff --git a/test/unit/specs/components/Header/SearchBar/search-bar.spec.js b/test/unit/specs/components/Header/SearchBar/search-bar.spec.js
new file mode 100644
index 000000000..269cbfab4
--- /dev/null
+++ b/test/unit/specs/components/Header/SearchBar/search-bar.spec.js
@@ -0,0 +1,29 @@
+import { render, screen } from '@testing-library/vue'
+
+import SearchBar from '~/components/Header/SearchBar/SearchBar.vue'
+
+describe('SearchBar', () => {
+ it('renders an input field with placeholder and type="search"', () => {
+ render(SearchBar, {
+ attrs: {
+ placeholder: 'Enter search query',
+ },
+ })
+
+ const inputElement = screen.getByPlaceholderText('Enter search query')
+
+ expect(inputElement.tagName).toBe('INPUT')
+ expect(inputElement).toHaveAttribute('type', 'search')
+ expect(inputElement).toHaveAttribute('placeholder', 'Enter search query')
+ })
+
+ it('renders a button with type="submit", ARIA label and SR text', () => {
+ render(SearchBar)
+
+ const btnElement = screen.getByLabelText('search.search')
+
+ expect(btnElement.tagName).toBe('BUTTON')
+ expect(btnElement).toHaveAttribute('type', 'submit')
+ expect(btnElement.textContent.trim()).toEqual('search.search')
+ })
+})
diff --git a/test/unit/specs/components/InputField/input-field.spec.js b/test/unit/specs/components/InputField/input-field.spec.js
new file mode 100644
index 000000000..7bb4a736d
--- /dev/null
+++ b/test/unit/specs/components/InputField/input-field.spec.js
@@ -0,0 +1,68 @@
+import { render, screen } from '@testing-library/vue'
+
+import InputField from '~/components/InputField/InputField.vue'
+
+describe('InputField', () => {
+ it('should render an `input` element with type="text"', () => {
+ render(InputField, {
+ attrs: {
+ placeholder: 'Enter some text',
+ },
+ propsData: {
+ fieldId: 'input-id',
+ labelText: 'Label',
+ },
+ })
+
+ const element = screen.getByPlaceholderText('Enter some text')
+
+ expect(element.tagName).toBe('INPUT')
+ expect(element).toHaveAttribute('type', 'text')
+ })
+
+ it('should allow changing the type', () => {
+ render(InputField, {
+ attrs: {
+ placeholder: 'Enter some number',
+ type: 'number',
+ },
+ propsData: {
+ fieldId: 'input-id',
+ labelText: 'Label',
+ },
+ })
+
+ const element = screen.getByPlaceholderText('Enter some number')
+
+ expect(element).toHaveAttribute('type', 'number')
+ })
+
+ it('should set the ID on the `input` to allow attaching labels', () => {
+ render(InputField, {
+ attrs: {
+ placeholder: 'Enter some text',
+ },
+ propsData: {
+ fieldId: 'input-id',
+ labelText: 'Label',
+ },
+ })
+
+ const element = screen.getByPlaceholderText('Enter some text')
+
+ expect(element).toHaveAttribute('id', 'input-id')
+ })
+
+ it('should render the label text connected to the input field if specified', () => {
+ render(InputField, {
+ propsData: {
+ fieldId: 'input-id',
+ labelText: 'Label',
+ },
+ })
+
+ const element = screen.getByLabelText('Label')
+
+ expect(element.tagName).toBe('INPUT')
+ })
+})