Skip to content

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

Convert modal-related components to script setup (#4700)

Olga Bulat12c6371678f9
diff --git a/frontend/src/components/VContentReport/VContentReportForm.vue b/frontend/src/components/VContentReport/VContentReportForm.vue
index 177f6a438..7fed8cbc1 100644
--- a/frontend/src/components/VContentReport/VContentReportForm.vue
+++ b/frontend/src/components/VContentReport/VContentReportForm.vue
@@ -1,3 +1,109 @@
+<script setup lang="ts">
+import { useRuntimeConfig } from "#imports"
+
+import { computed, ref } from "vue"
+
+import { ofetch } from "ofetch"
+
+import {
+ reasons,
+ DMCA,
+ OTHER,
+ SENT,
+ FAILED,
+ WIP,
+ DMCA_FORM_URL,
+ type ReportReason,
+} from "~/constants/content-report"
+
+import type { AudioDetail, ImageDetail } from "~/types/media"
+import { useAnalytics } from "~/composables/use-analytics"
+
+import { mediaSlug } from "~/utils/query-utils"
+
+import VButton from "~/components/VButton.vue"
+import VRadio from "~/components/VRadio/VRadio.vue"
+import VDmcaNotice from "~/components/VContentReport/VDmcaNotice.vue"
+import VReportDescForm from "~/components/VContentReport/VReportDescForm.vue"
+import VLink from "~/components/VLink.vue"
+
+const props = withDefaults(
+ defineProps<{
+ media: AudioDetail | ImageDetail
+ providerName: string
+ closeFn: () => void
+ allowCancel?: boolean
+ }>(),
+ {
+ allowCancel: true,
+ }
+)
+
+const description = ref("")
+
+const status = ref<string | null>(WIP)
+
+const selectedReason = ref<ReportReason>(DMCA)
+
+/* Buttons */
+const handleCancel = () => {
+ selectedReason.value = DMCA
+ description.value = ""
+ props.closeFn()
+}
+
+const isSubmitDisabled = computed(
+ () => selectedReason.value === OTHER && description.value.length < 20
+)
+
+const { sendCustomEvent } = useAnalytics()
+
+const handleDmcaSubmit = () => {
+ sendCustomEvent("REPORT_MEDIA", {
+ id: props.media.id,
+ mediaType: props.media.frontendMediaType,
+ provider: props.media.provider,
+ reason: selectedReason.value,
+ })
+ status.value = SENT
+}
+const handleSubmit = async (event: Event) => {
+ event.preventDefault()
+ // Submit report
+ try {
+ const mediaType = props.media.frontendMediaType
+ const reason = selectedReason.value
+
+ const {
+ public: { apiUrl },
+ } = useRuntimeConfig()
+
+ await ofetch(
+ `${apiUrl}v1/${mediaSlug(mediaType)}/${props.media.id}/report/`,
+ {
+ method: "POST",
+ body: {
+ mediaType,
+ reason,
+ identifier: props.media.id,
+ description: description.value,
+ },
+ }
+ )
+
+ sendCustomEvent("REPORT_MEDIA", {
+ mediaType,
+ reason,
+ id: props.media.id,
+ provider: props.media.provider,
+ })
+ status.value = SENT
+ } catch (error) {
+ status.value = FAILED
+ }
+}
+</script>
+
<template>
<div id="content-report-form">
<div v-if="status === SENT">
@@ -122,146 +228,3 @@
</div>
</div>
</template>
-
-<script lang="ts">
-import { useRuntimeConfig } from "#imports"
-
-import { computed, defineComponent, PropType, ref } from "vue"
-
-import { ofetch } from "ofetch"
-
-import {
- reasons,
- DMCA,
- OTHER,
- SENT,
- FAILED,
- WIP,
- DMCA_FORM_URL,
- type ReportReason,
-} from "~/constants/content-report"
-
-import type { AudioDetail, ImageDetail } from "~/types/media"
-import { useAnalytics } from "~/composables/use-analytics"
-
-import { mediaSlug } from "~/utils/query-utils"
-
-import VButton from "~/components/VButton.vue"
-import VRadio from "~/components/VRadio/VRadio.vue"
-import VDmcaNotice from "~/components/VContentReport/VDmcaNotice.vue"
-import VReportDescForm from "~/components/VContentReport/VReportDescForm.vue"
-import VLink from "~/components/VLink.vue"
-
-export default defineComponent({
- name: "VContentReportForm",
- components: {
- VButton,
- VLink,
- VRadio,
- VDmcaNotice,
- VReportDescForm,
- },
- props: {
- media: {
- type: Object as PropType<AudioDetail | ImageDetail>,
- required: true,
- },
- providerName: {
- type: String as PropType<string>,
- required: true,
- },
- closeFn: {
- type: Function,
- required: true,
- },
- allowCancel: {
- type: Boolean,
- default: true,
- },
- },
- setup(props) {
- const description = ref("")
-
- const status = ref<string | null>(WIP)
-
- const selectedReason = ref<ReportReason>(DMCA)
-
- /* Buttons */
- const handleCancel = () => {
- selectedReason.value = DMCA
- description.value = ""
- props.closeFn()
- }
-
- const isSubmitDisabled = computed(
- () => selectedReason.value === OTHER && description.value.length < 20
- )
-
- const { sendCustomEvent } = useAnalytics()
-
- const handleDmcaSubmit = () => {
- sendCustomEvent("REPORT_MEDIA", {
- id: props.media.id,
- mediaType: props.media.frontendMediaType,
- provider: props.media.provider,
- reason: selectedReason.value,
- })
- status.value = SENT
- }
- const handleSubmit = async (event: Event) => {
- event.preventDefault()
- // Submit report
- try {
- const mediaType = props.media.frontendMediaType
- const reason = selectedReason.value
-
- const {
- public: { apiUrl },
- } = useRuntimeConfig()
-
- await ofetch(
- `${apiUrl}v1/${mediaSlug(mediaType)}/${props.media.id}/report/`,
- {
- method: "POST",
- body: {
- mediaType,
- reason,
- identifier: props.media.id,
- description: description.value,
- },
- }
- )
-
- sendCustomEvent("REPORT_MEDIA", {
- mediaType,
- reason,
- id: props.media.id,
- provider: props.media.provider,
- })
- status.value = SENT
- } catch (error) {
- status.value = FAILED
- }
- }
-
- return {
- reasons,
- DMCA,
- OTHER,
- SENT,
- FAILED,
- DMCA_FORM_URL,
-
- selectedReason,
- status,
- description,
-
- handleCancel,
-
- isSubmitDisabled,
- handleSubmit,
- handleDmcaSubmit,
- }
- },
-})
-</script>
diff --git a/frontend/src/components/VFilters/VFilterChecklist.vue b/frontend/src/components/VFilters/VFilterChecklist.vue
index f6c985e92..df8d52335 100644
--- a/frontend/src/components/VFilters/VFilterChecklist.vue
+++ b/frontend/src/components/VFilters/VFilterChecklist.vue
@@ -1,3 +1,76 @@
+<script setup lang="ts">
+import { useI18n } from "#imports"
+
+import { useSearchStore } from "~/stores/search"
+
+import type { FilterItem, FilterCategory } from "~/constants/filters"
+
+import type { License } from "~/constants/license"
+
+import { getElements } from "~/utils/license"
+
+import VButton from "~/components/VButton.vue"
+import VCheckbox from "~/components/VCheckbox/VCheckbox.vue"
+import VIcon from "~/components/VIcon/VIcon.vue"
+import VIconButton from "~/components/VIconButton/VIconButton.vue"
+import VLicense from "~/components/VLicense/VLicense.vue"
+import VLicenseExplanation from "~/components/VFilters/VLicenseExplanation.vue"
+import VPopover from "~/components/VPopover/VPopover.vue"
+
+type toggleFilterPayload = {
+ filterType: FilterCategory
+ code: string
+}
+
+const props = withDefaults(
+ defineProps<{
+ options?: FilterItem[]
+ title?: string
+ filterType: FilterCategory
+ disabled?: boolean
+ }>(),
+ {
+ disabled: false,
+ }
+)
+
+const emit = defineEmits<{
+ "toggle-filter": [toggleFilterPayload]
+}>()
+
+const { t } = useI18n({ useScope: "global" })
+
+const itemLabel = (item: FilterItem) =>
+ ["audioProviders", "imageProviders"].indexOf(props.filterType) > -1
+ ? item.name
+ : t(item.name)
+
+const onValueChange = ({ value }: { value: string }) => {
+ emit("toggle-filter", {
+ code: value,
+ filterType: props.filterType,
+ })
+}
+const getLicenseExplanationCloseAria = (license: License) => {
+ const elements = getElements(license).filter((icon) => icon !== "cc")
+ const descriptions = elements
+ .map((element) => t(`browsePage.licenseDescription.${element}`))
+ .join(" ")
+ const close = t("modal.closeNamed", {
+ name: t("browsePage.aria.licenseExplanation"),
+ })
+ return `${descriptions} - ${close}`
+}
+
+const isDisabled = (item: FilterItem) =>
+ useSearchStore().isFilterDisabled(item, props.filterType) ?? props.disabled
+
+const isLicense = (code: string): code is License => {
+ // Quick check that also prevents "`code` is declared but its value is never read" warning.
+ return !!code && props.filterType === "licenses"
+}
+</script>
+
<template>
<fieldset class="mb-8">
<legend class="label-bold">{{ title }}</legend>
@@ -54,106 +127,3 @@
</div>
</fieldset>
</template>
-
-<script lang="ts">
-import { useI18n } from "#imports"
-
-import { defineComponent, PropType } from "vue"
-
-import { useSearchStore } from "~/stores/search"
-
-import type { FilterItem, FilterCategory } from "~/constants/filters"
-
-import type { License } from "~/constants/license"
-
-import { defineEvent } from "~/types/emits"
-import { getElements } from "~/utils/license"
-
-import VButton from "~/components/VButton.vue"
-import VCheckbox from "~/components/VCheckbox/VCheckbox.vue"
-import VIcon from "~/components/VIcon/VIcon.vue"
-import VIconButton from "~/components/VIconButton/VIconButton.vue"
-import VLicense from "~/components/VLicense/VLicense.vue"
-import VLicenseExplanation from "~/components/VFilters/VLicenseExplanation.vue"
-import VPopover from "~/components/VPopover/VPopover.vue"
-
-type toggleFilterPayload = {
- filterType: FilterCategory
- code: string
-}
-
-export default defineComponent({
- name: "VFilterCheckList",
- components: {
- VIconButton,
- VCheckbox,
- VButton,
- VIcon,
- VLicense,
- VLicenseExplanation,
- VPopover,
- },
- props: {
- options: {
- type: Array as PropType<FilterItem[]>,
- required: false,
- },
- title: {
- type: String,
- },
- filterType: {
- type: String as PropType<FilterCategory>,
- required: true,
- },
- disabled: {
- type: Boolean,
- default: false,
- },
- },
- emits: {
- "toggle-filter": defineEvent<[toggleFilterPayload]>(),
- },
- setup(props, { emit }) {
- const { t } = useI18n({ useScope: "global" })
-
- const itemLabel = (item: FilterItem) =>
- ["audioProviders", "imageProviders"].indexOf(props.filterType) > -1
- ? item.name
- : t(item.name)
-
- const onValueChange = ({ value }: { value: string }) => {
- emit("toggle-filter", {
- code: value,
- filterType: props.filterType,
- })
- }
- const getLicenseExplanationCloseAria = (license: License) => {
- const elements = getElements(license).filter((icon) => icon !== "cc")
- const descriptions = elements
- .map((element) => t(`browsePage.licenseDescription.${element}`))
- .join(" ")
- const close = t("modal.closeNamed", {
- name: t("browsePage.aria.licenseExplanation"),
- })
- return `${descriptions} - ${close}`
- }
-
- const isDisabled = (item: FilterItem) =>
- useSearchStore().isFilterDisabled(item, props.filterType) ??
- props.disabled
-
- const isLicense = (code: string): code is License => {
- // Quick check that also prevents "`code` is declared but its value is never read" warning.
- return !!code && props.filterType === "licenses"
- }
-
- return {
- isDisabled,
- itemLabel,
- onValueChange,
- getLicenseExplanationCloseAria,
- isLicense,
- }
- },
-})
-</script>
diff --git a/frontend/src/components/VFilters/VLicenseExplanation.vue b/frontend/src/components/VFilters/VLicenseExplanation.vue
index 41382fb12..0ed6badf7 100644
--- a/frontend/src/components/VFilters/VLicenseExplanation.vue
+++ b/frontend/src/components/VFilters/VLicenseExplanation.vue
@@ -1,3 +1,23 @@
+<script setup lang="ts">
+/**
+ * Renders the explanation of the license passed to it by breaking it down to
+ * its constituent clauses.
+ */
+import { getLicenseUrl, isLicense } from "~/utils/license"
+
+import type { License } from "~/constants/license"
+
+import VLicenseElements from "~/components/VLicense/VLicenseElements.vue"
+import VLink from "~/components/VLink.vue"
+
+defineProps<{
+ /**
+ * the code of the license whose elements need to be explained
+ */
+ license: License
+}>()
+</script>
+
<template>
<div class="license-explanation w-70 max-w-xs p-6">
<h5 class="text-base font-semibold">
@@ -35,41 +55,3 @@
</i18n-t>
</div>
</template>
-
-<script lang="ts">
-import { defineComponent, PropType } from "vue"
-
-import { getLicenseUrl, isLicense } from "~/utils/license"
-
-import type { License } from "~/constants/license"
-
-import VLicenseElements from "~/components/VLicense/VLicenseElements.vue"
-import VLink from "~/components/VLink.vue"
-
-/**
- * Renders the explanation of the license passed to it by breaking it down to
- * its constituent clauses.
- */
-export default defineComponent({
- name: "VLicenseExplanation",
- components: {
- VLicenseElements,
- VLink,
- },
- props: {
- /**
- * the code of the license whose elements need to be explained
- */
- license: {
- type: String as PropType<License>,
- required: true,
- },
- },
- setup() {
- return {
- isLicense,
- getLicenseUrl,
- }
- },
-})
-</script>
diff --git a/frontend/src/components/VHeader/VHeaderInternal.vue b/frontend/src/components/VHeader/VHeaderInternal.vue
index cccd6f373..9179a5a64 100644
--- a/frontend/src/components/VHeader/VHeaderInternal.vue
+++ b/frontend/src/components/VHeader/VHeaderInternal.vue
@@ -1,3 +1,82 @@
+<script setup lang="ts">
+import { useNuxtApp, useRoute } from "#imports"
+
+import { computed, ref, SetupContext, watch } from "vue"
+
+import { useDialogControl } from "~/composables/use-dialog-control"
+import { useHydrating } from "~/composables/use-hydrating"
+
+import { useUiStore } from "~/stores/ui"
+
+import VHomeLink from "~/components/VHeader/VHomeLink.vue"
+import VPageLinks from "~/components/VHeader/VPageLinks.vue"
+import VModalContent from "~/components/VModal/VModalContent.vue"
+import VPopoverContent from "~/components/VPopover/VPopoverContent.vue"
+import VWordPressLink from "~/components/VHeader/VWordPressLink.vue"
+import VIconButton from "~/components/VIconButton/VIconButton.vue"
+
+const emit = defineEmits<{
+ open: []
+ close: []
+}>() as SetupContext["emit"]
+
+const menuButtonRef = ref<InstanceType<typeof VIconButton> | null>(null)
+const nodeRef = ref<HTMLElement | null>(null)
+const modalContentRef = ref<{
+ $el: HTMLElement
+ deactivateFocusTrap: () => void
+} | null>(null)
+
+const uiStore = useUiStore()
+
+const route = useRoute()
+
+const { $sendCustomEvent } = useNuxtApp()
+
+const isModalVisible = ref(false)
+
+const isSm = computed(() => uiStore.isBreakpoint("sm"))
+
+const triggerElement = computed(
+ () => (menuButtonRef.value?.$el as HTMLElement) || null
+)
+
+const lockBodyScroll = computed(() => !isSm.value)
+
+const deactivateFocusTrap = computed(
+ () => modalContentRef.value?.deactivateFocusTrap
+)
+
+const { doneHydrating } = useHydrating()
+
+const {
+ close: closePageMenu,
+ open: openPageMenu,
+ onTriggerClick: internalOnTriggerClick,
+ triggerA11yProps,
+} = useDialogControl({
+ visibleRef: isModalVisible,
+ nodeRef,
+ lockBodyScroll,
+ emit,
+ deactivateFocusTrap,
+})
+
+const onTriggerClick = () => {
+ if (!isModalVisible.value) {
+ $sendCustomEvent("OPEN_PAGES_MENU", {})
+ }
+ return internalOnTriggerClick()
+}
+
+// When clicking on an internal link in the modal, close the modal
+watch(route, () => {
+ if (isModalVisible.value) {
+ closePageMenu()
+ }
+})
+</script>
+
<template>
<header
ref="nodeRef"
@@ -84,112 +163,3 @@
</div>
</header>
</template>
-
-<script lang="ts">
-import { useRoute } from "#imports"
-
-import { computed, defineComponent, ref, watch } from "vue"
-
-import { useDialogControl } from "~/composables/use-dialog-control"
-import { useAnalytics } from "~/composables/use-analytics"
-import { useHydrating } from "~/composables/use-hydrating"
-import usePages from "~/composables/use-pages"
-
-import { useUiStore } from "~/stores/ui"
-
-import VHomeLink from "~/components/VHeader/VHomeLink.vue"
-import VPageLinks from "~/components/VHeader/VPageLinks.vue"
-import VModalContent from "~/components/VModal/VModalContent.vue"
-import VPopoverContent from "~/components/VPopover/VPopoverContent.vue"
-import VWordPressLink from "~/components/VHeader/VWordPressLink.vue"
-import VIconButton from "~/components/VIconButton/VIconButton.vue"
-
-export default defineComponent({
- name: "VHeaderInternal",
- components: {
- VIconButton,
- VModalContent,
- VPopoverContent,
- VHomeLink,
- VPageLinks,
- VWordPressLink,
- },
- setup(_, { emit }) {
- const menuButtonRef = ref<InstanceType<typeof VIconButton> | null>(null)
- const nodeRef = ref<HTMLElement | null>(null)
- const modalContentRef = ref<{
- $el: HTMLElement
- deactivateFocusTrap: () => void
- } | null>(null)
-
- const uiStore = useUiStore()
-
- const route = useRoute()
-
- const { sendCustomEvent } = useAnalytics()
-
- const { all: allPages, current: currentPage } = usePages()
-
- const isModalVisible = ref(false)
-
- const isSm = computed(() => uiStore.isBreakpoint("sm"))
-
- const triggerElement = computed(
- () => (menuButtonRef.value?.$el as HTMLElement) || null
- )
-
- const lockBodyScroll = computed(() => !isSm.value)
-
- const deactivateFocusTrap = computed(
- () => modalContentRef.value?.deactivateFocusTrap
- )
-
- const { doneHydrating } = useHydrating()
-
- const {
- close: closePageMenu,
- open: openPageMenu,
- onTriggerClick,
- triggerA11yProps,
- } = useDialogControl({
- visibleRef: isModalVisible,
- nodeRef,
- lockBodyScroll,
- emit: emit as (event: string) => void,
- deactivateFocusTrap,
- })
-
- const eventedOnTriggerClick = () => {
- if (!isModalVisible.value) {
- sendCustomEvent("OPEN_PAGES_MENU", {})
- }
- return onTriggerClick()
- }
-
- // When clicking on an internal link in the modal, close the modal
- watch(route, () => {
- if (isModalVisible.value) {
- closePageMenu()
- }
- })
-
- return {
- menuButtonRef,
- modalContentRef,
- nodeRef,
-
- allPages,
- currentPage,
-
- isModalVisible,
- doneHydrating,
- closePageMenu,
- openPageMenu,
- isSm,
- onTriggerClick: eventedOnTriggerClick,
- triggerA11yProps,
- triggerElement,
- }
- },
-})
-</script>
diff --git a/frontend/src/components/VHeader/VHeaderMobile/VContentSettingsModalContent.vue b/frontend/src/components/VHeader/VHeaderMobile/VContentSettingsModalContent.vue
index 1b0ac76bf..c9745c381 100644
--- a/frontend/src/components/VHeader/VHeaderMobile/VContentSettingsModalContent.vue
+++ b/frontend/src/components/VHeader/VHeaderMobile/VContentSettingsModalContent.vue
@@ -1,3 +1,73 @@
+<script setup lang="ts">
+import { computed, ref } from "vue"
+
+import { useSearchStore } from "~/stores/search"
+
+import useSearchType from "~/composables/use-search-type"
+
+import { SearchType } from "~/constants/media"
+
+import VButton from "~/components/VButton.vue"
+import VFilterTab from "~/components/VHeader/VHeaderMobile/VFilterTab.vue"
+import VIcon from "~/components/VIcon/VIcon.vue"
+import VModalContent from "~/components/VModal/VModalContent.vue"
+import VSearchGridFilter from "~/components/VFilters/VSearchGridFilter.vue"
+import VSearchTypes from "~/components/VContentSwitcher/VSearchTypes.vue"
+import VShowResultsButton from "~/components/VHeader/VHeaderMobile/VShowResultsButton.vue"
+import VTab from "~/components/VTabs/VTab.vue"
+import VTabPanel from "~/components/VTabs/VTabPanel.vue"
+import VTabs from "~/components/VTabs/VTabs.vue"
+import VSafeBrowsing from "~/components/VSafeBrowsing/VSafeBrowsing.vue"
+import VIconButton from "~/components/VIconButton/VIconButton.vue"
+
+type ContentSettingsTab = "content-settings" | "filters"
+
+const props = withDefaults(
+ defineProps<{
+ triggerElement?: HTMLElement | null
+ variant?: "fit-content" | "two-thirds"
+ isFetching?: boolean
+ close: () => void
+ visible?: boolean
+ showFilters?: boolean
+ useLinks?: boolean
+ }>(),
+ {
+ triggerElement: null,
+ variant: "fit-content",
+ isFetching: false,
+ visible: false,
+ showFilters: true,
+ useLinks: true,
+ }
+)
+
+defineEmits<{
+ select: [SearchType]
+}>()
+
+const searchStore = useSearchStore()
+const content = useSearchType()
+const selectedTab = ref<ContentSettingsTab>("content-settings")
+const changeSelectedTab = (tab: string) => {
+ selectedTab.value = tab as ContentSettingsTab
+}
+
+const showClearFiltersButton = computed(
+ () => props.showFilters && selectedTab.value === "filters"
+)
+const isClearButtonDisabled = computed(() => !searchStore.isAnyFilterApplied)
+const appliedFilterCount = computed<number>(
+ () => searchStore.appliedFilterCount
+)
+
+const searchType = computed(() => content.getSearchTypeProps())
+
+const clearFilters = () => {
+ searchStore.clearFilters()
+}
+</script>
+
<template>
<VModalContent
:aria-label="$t('header.aria.menu')"
@@ -79,122 +149,3 @@
</footer>
</VModalContent>
</template>
-
-<script lang="ts">
-import { computed, defineComponent, PropType, ref } from "vue"
-
-import { useSearchStore } from "~/stores/search"
-
-import useSearchType from "~/composables/use-search-type"
-
-import { defineEvent } from "~/types/emits"
-
-import { SearchType } from "~/constants/media"
-
-import VButton from "~/components/VButton.vue"
-import VFilterTab from "~/components/VHeader/VHeaderMobile/VFilterTab.vue"
-import VIcon from "~/components/VIcon/VIcon.vue"
-import VModalContent from "~/components/VModal/VModalContent.vue"
-import VSearchGridFilter from "~/components/VFilters/VSearchGridFilter.vue"
-import VSearchTypes from "~/components/VContentSwitcher/VSearchTypes.vue"
-import VShowResultsButton from "~/components/VHeader/VHeaderMobile/VShowResultsButton.vue"
-import VTab from "~/components/VTabs/VTab.vue"
-import VTabPanel from "~/components/VTabs/VTabPanel.vue"
-import VTabs from "~/components/VTabs/VTabs.vue"
-import VSafeBrowsing from "~/components/VSafeBrowsing/VSafeBrowsing.vue"
-import VIconButton from "~/components/VIconButton/VIconButton.vue"
-
-type ContentSettingsTab = "content-settings" | "filters"
-
-export default defineComponent({
- name: "VContentSettingsModalContent",
- components: {
- VIconButton,
- VSafeBrowsing,
- VIcon,
- VModalContent,
- VButton,
- VFilterTab,
- VSearchGridFilter,
- VSearchTypes,
- VShowResultsButton,
- VTab,
- VTabPanel,
- VTabs,
- },
- props: {
- triggerElement: {
- type: (import.meta.server
- ? Object
- : HTMLElement) as PropType<HTMLElement>,
- default: null,
- },
- variant: {
- type: String as PropType<"fit-content" | "two-thirds">,
- default: "fit-content",
- },
- isFetching: {
- type: Boolean,
- default: false,
- },
- close: {
- type: Function as PropType<() => void>,
- required: true,
- },
- visible: {
- type: Boolean,
- default: false,
- },
- showFilters: {
- type: Boolean,
- default: true,
- },
- useLinks: {
- type: Boolean,
- default: true,
- },
- },
- emits: {
- select: defineEvent<[SearchType]>(),
- },
- setup(props) {
- const searchStore = useSearchStore()
- const content = useSearchType()
- const selectedTab = ref<ContentSettingsTab>("content-settings")
- const changeSelectedTab = (tab: string) => {
- selectedTab.value = tab as ContentSettingsTab
- }
-
- const areFiltersSelected = computed(() => searchStore.isAnyFilterApplied)
-
- const showClearFiltersButton = computed(
- () => props.showFilters && selectedTab.value === "filters"
- )
- const isClearButtonDisabled = computed(
- () => !searchStore.isAnyFilterApplied
- )
- const appliedFilterCount = computed<number>(
- () => searchStore.appliedFilterCount
- )
-
- const searchType = computed(() => content.getSearchTypeProps())
-
- const clearFilters = () => {
- searchStore.clearFilters()
- }
-
- return {
- searchType,
-
- selectedTab,
- changeSelectedTab,
-
- areFiltersSelected,
- appliedFilterCount,
- showClearFiltersButton,
- isClearButtonDisabled,
- clearFilters,
- }
- },
-})
-</script>
diff --git a/frontend/src/components/VHeader/VHeaderMobile/VHeaderMobile.vue b/frontend/src/components/VHeader/VHeaderMobile/VHeaderMobile.vue
index 98d921bee..c1dbb7e04 100644
--- a/frontend/src/components/VHeader/VHeaderMobile/VHeaderMobile.vue
+++ b/frontend/src/components/VHeader/VHeaderMobile/VHeaderMobile.vue
@@ -1,3 +1,260 @@
+<script setup lang="ts">
+import { firstParam, focusIn, useNuxtApp, useRoute, useRouter } from "#imports"
+
+import { computed, nextTick, ref, SetupContext, watch } from "vue"
+import { onClickOutside } from "@vueuse/core"
+
+import {
+ ensureFocus,
+ getAllTabbableIn,
+ getFirstTabbableIn,
+} from "~/utils/reakit-utils/focus"
+
+import { useDialogControl } from "~/composables/use-dialog-control"
+import { useSearch } from "~/composables/use-search"
+import { useHydrating } from "~/composables/use-hydrating"
+import { useRecentSearches } from "~/composables/use-recent-searches"
+
+import { useMediaStore } from "~/stores/media"
+import { useSearchStore } from "~/stores/search"
+
+import { skipToContentTargetId } from "~/constants/window"
+
+import VLogoButton from "~/components/VHeader/VLogoButton.vue"
+import VContentSettingsModalContent from "~/components/VHeader/VHeaderMobile/VContentSettingsModalContent.vue"
+import VContentSettingsButton from "~/components/VHeader/VHeaderMobile/VContentSettingsButton.vue"
+import VRecentSearches from "~/components/VRecentSearches/VRecentSearches.vue"
+import VSearchBarButton from "~/components/VHeader/VHeaderMobile/VSearchBarButton.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.
+ */
+
+const searchInputRef = ref<HTMLInputElement | null>(null)
+const headerRef = ref<HTMLElement | null>(null)
+const recentSearchesRef = ref<InstanceType<typeof VRecentSearches> | null>(null)
+const contentSettingsButtonRef = ref<InstanceType<
+ typeof VContentSettingsButton
+> | null>(null)
+const contentSettingsButton = computed(
+ () => (contentSettingsButtonRef.value?.$el as HTMLElement) ?? undefined
+)
+const clearButtonRef = ref<InstanceType<typeof VSearchBarButton> | null>(null)
+
+const mediaStore = useMediaStore()
+const searchStore = useSearchStore()
+
+const isSearchBarActive = ref(false)
+const isInputFocused = ref(false)
+const contentSettingsOpen = ref(false)
+
+const appliedFilterCount = computed(() => searchStore.appliedFilterCount)
+const isFetching = computed(() => mediaStore.fetchState.isFetching)
+
+/**
+ * The selection range of the input field. Used to make sure that the cursor
+ * is at the correct position when the search bar is clicked on.
+ */
+const selection = ref<{ start: number; end: number }>({ start: 0, end: 0 })
+
+const { $sendCustomEvent } = useNuxtApp()
+const { updateSearchState, searchTerm, searchStatus } =
+ useSearch($sendCustomEvent)
+const localSearchTerm = ref(searchTerm.value)
+
+const focusInput = () => {
+ const input = searchInputRef.value as HTMLInputElement
+ ensureFocus(input)
+ input.selectionStart = selection.value.start
+ input.selectionEnd = selection.value.end
+}
+
+const handleFormSubmit = () => {
+ if (localSearchTerm.value && localSearchTerm.value !== searchTerm.value) {
+ searchTerm.value = localSearchTerm.value
+ }
+ hideRecentSearches()
+ handleSearch()
+}
+const handleSearch = () => {
+ window.scrollTo({ top: 0, left: 0, behavior: "auto" })
+ updateSearchState()
+}
+
+/**
+ * Activate the search bar and open the recent searches modal.
+ */
+const activate = () => {
+ isInputFocused.value = true
+ isSearchBarActive.value = true
+ if (!isRecentVisible.value) {
+ showRecentSearches()
+ }
+}
+
+/** Deactivate the search bar */
+const deactivate = () => {
+ isInputFocused.value = false
+ isSearchBarActive.value = false
+}
+
+/**
+ * Set the selection range of the input field to the saved value.
+ * This is necessary because when opening the recent search modal,
+ * the input field is blurred and focused again.
+ */
+const updateSelection = () => {
+ const inputElement = searchInputRef.value as HTMLInputElement
+ const lastPos =
+ inputElement.value.length > 0 ? inputElement.value.length - 1 : 0
+ selection.value = {
+ start: inputElement.selectionStart ?? lastPos,
+ end: inputElement.selectionEnd ?? lastPos,
+ }
+}
+
+/**
+ * When the user tabs into the input field, the `isInputFocused` is set to true,
+ * but the search bar is not activated until the user types something.
+ *
+ * On the `input` event, update the search term and the selection range,
+ * and activate the search bar.
+ */
+const updateSearchText = () => {
+ localSearchTerm.value = (searchInputRef.value as HTMLInputElement).value
+ updateSelection()
+ if (isInputFocused.value && !isSearchBarActive.value) {
+ activate()
+ }
+}
+
+const clearSearchText = () => {
+ localSearchTerm.value = ""
+ focusInput()
+}
+
+const {
+ handleKeydown: handleInputKeydown,
+ handleSelect,
+ handleClear,
+ recent: {
+ isVisible: isRecentVisible,
+ show: showRecentSearches,
+ hide: hideRecentSearches,
+ entries,
+ selectedIdx,
+ },
+} = useRecentSearches({
+ focusInput,
+ term: localSearchTerm,
+ isMobile: true,
+ isInputFocused,
+})
+
+watch(isRecentVisible, (isVisible) => {
+ if (!isVisible) {
+ deactivate()
+ if (localSearchTerm.value !== searchTerm.value) {
+ searchTerm.value = localSearchTerm.value
+ handleSearch()
+ }
+ }
+})
+
+const handleInputFocus = () => (isInputFocused.value = true)
+const handleInputBlur = () => {
+ if (!isRecentVisible.value && isInputFocused.value) {
+ deactivate()
+ }
+}
+
+/**
+ * Deactivate the search bar when the user clicks outside the header,
+ * but not when the click is inside the recent searches modal.
+ */
+onClickOutside(headerRef, (event) => {
+ const clickInsideModal = recentSearchesRef.value?.$el?.contains(
+ event.target as Node
+ )
+ if (!clickInsideModal) {
+ isInputFocused.value = false
+ }
+})
+
+/**
+ * When activating the search bar by clicking, preserve the cursor position.
+ */
+const handleInputClick = () => {
+ if (!isSearchBarActive.value) {
+ updateSelection()
+ activate()
+ }
+}
+
+/**
+ * Special handling of focus order after leaving the search bar because
+ * the input modal is inserted into the page and change the HTML elements order.
+ * @param direction
+ */
+const handleTabOut = (direction: "forward" | "backward") => {
+ hideRecentSearches()
+ nextTick().then(() => {
+ const element =
+ direction === "forward"
+ ? document.getElementById(skipToContentTargetId)
+ : getAllTabbableIn(document.body)[1]
+ ensureFocus(element ?? (getFirstTabbableIn(document.body) as HTMLElement))
+ })
+}
+
+const emit = defineEmits<{
+ open: []
+ close: []
+}>() as SetupContext["emit"]
+
+const {
+ close: closeContentSettings,
+ onTriggerClick: toggleContentSettings,
+ triggerA11yProps,
+} = useDialogControl({
+ visibleRef: contentSettingsOpen,
+ nodeRef: headerRef,
+ lockBodyScroll: true,
+ emit,
+})
+
+const route = useRoute()
+const routeSearchTerm = computed(() => firstParam(route?.query.q))
+watch(routeSearchTerm, (newSearchTerm) => {
+ localSearchTerm.value = newSearchTerm ?? ""
+})
+
+const { doneHydrating } = useHydrating()
+
+const router = useRouter()
+router.beforeEach((to, from, next) => {
+ if (to.path !== from.path) {
+ closeContentSettings()
+ deactivate()
+ }
+ next()
+})
+
+const handleTab = (
+ event: KeyboardEvent & { key: "Tab" },
+ button: "content-settings" | "clear-input"
+) => {
+ if (isRecentVisible.value) {
+ event.preventDefault()
+ focusIn(recentSearchesRef.value?.$el, 1)
+ } else if (button === "content-settings") {
+ handleTabOut("forward")
+ }
+}
+</script>
+
<template>
<header
ref="headerRef"
@@ -85,7 +342,6 @@
@keydown.tab.exact="handleTab($event, 'content-settings')"
/>
<VContentSettingsModalContent
- v-show="!isRecentVisible"
variant="two-thirds"
:visible="contentSettingsOpen"
:is-fetching="isFetching"
@@ -121,322 +377,3 @@
</VModalContent>
</header>
</template>
-
-<script lang="ts">
-import { firstParam, focusIn, useNuxtApp, useRoute, useRouter } from "#imports"
-
-import { computed, defineComponent, nextTick, ref, watch } from "vue"
-import { onClickOutside } from "@vueuse/core"
-
-import {
- ensureFocus,
- getAllTabbableIn,
- getFirstTabbableIn,
-} from "~/utils/reakit-utils/focus"
-
-import { useDialogControl } from "~/composables/use-dialog-control"
-import { useSearch } from "~/composables/use-search"
-import { useHydrating } from "~/composables/use-hydrating"
-import { useRecentSearches } from "~/composables/use-recent-searches"
-
-import { useMediaStore } from "~/stores/media"
-import { useSearchStore } from "~/stores/search"
-
-import { skipToContentTargetId } from "~/constants/window"
-
-import VLogoButton from "~/components/VHeader/VLogoButton.vue"
-import VContentSettingsModalContent from "~/components/VHeader/VHeaderMobile/VContentSettingsModalContent.vue"
-import VContentSettingsButton from "~/components/VHeader/VHeaderMobile/VContentSettingsButton.vue"
-import VRecentSearches from "~/components/VRecentSearches/VRecentSearches.vue"
-import VSearchBarButton from "~/components/VHeader/VHeaderMobile/VSearchBarButton.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 defineComponent({
- name: "VHeaderMobile",
- components: {
- VContentSettingsModalContent,
- VContentSettingsButton,
- VLogoButton,
- VRecentSearches,
- VSearchBarButton,
- },
- setup(_, { emit }) {
- const searchInputRef = ref<HTMLInputElement | null>(null)
- const headerRef = ref<HTMLElement | null>(null)
- const recentSearchesRef = ref<InstanceType<typeof VRecentSearches> | null>(
- null
- )
- const contentSettingsButtonRef = ref<InstanceType<
- typeof VContentSettingsButton
- > | null>(null)
- const contentSettingsButton = computed(
- () => (contentSettingsButtonRef.value?.$el as HTMLElement) ?? undefined
- )
- const clearButtonRef = ref<InstanceType<typeof VSearchBarButton> | null>(
- null
- )
-
- const mediaStore = useMediaStore()
- const searchStore = useSearchStore()
-
- const isSearchBarActive = ref(false)
- const isInputFocused = ref(false)
- const contentSettingsOpen = ref(false)
-
- const appliedFilterCount = computed(() => searchStore.appliedFilterCount)
- const isFetching = computed(() => mediaStore.fetchState.isFetching)
-
- /**
- * The selection range of the input field. Used to make sure that the cursor
- * is at the correct position when the search bar is clicked on.
- */
- const selection = ref<{ start: number; end: number }>({ start: 0, end: 0 })
-
- const { $sendCustomEvent } = useNuxtApp()
- const { updateSearchState, searchTerm, searchStatus } =
- useSearch($sendCustomEvent)
- const localSearchTerm = ref(searchTerm.value)
-
- const focusInput = () => {
- const input = searchInputRef.value as HTMLInputElement
- ensureFocus(input)
- input.selectionStart = selection.value.start
- input.selectionEnd = selection.value.end
- }
-
- const handleFormSubmit = () => {
- if (localSearchTerm.value && localSearchTerm.value !== searchTerm.value) {
- searchTerm.value = localSearchTerm.value
- }
- recent.hide()
- handleSearch()
- }
- const handleSearch = () => {
- window.scrollTo({ top: 0, left: 0, behavior: "auto" })
- updateSearchState()
- }
-
- /**
- * Activate the search bar and open the recent searches modal.
- */
- const activate = () => {
- isInputFocused.value = true
- isSearchBarActive.value = true
- if (!recent.isVisible.value) {
- recent.show()
- }
- }
-
- /** Deactivate the search bar */
- const deactivate = () => {
- isInputFocused.value = false
- isSearchBarActive.value = false
- }
-
- /**
- * Set the selection range of the input field to the saved value.
- * This is necessary because when opening the recent search modal,
- * the input field is blurred and focused again.
- */
- const updateSelection = () => {
- const inputElement = searchInputRef.value as HTMLInputElement
- const lastPos =
- inputElement.value.length > 0 ? inputElement.value.length - 1 : 0
- selection.value = {
- start: inputElement.selectionStart ?? lastPos,
- end: inputElement.selectionEnd ?? lastPos,
- }
- }
-
- /**
- * When the user tabs into the input field, the `isInputFocused` is set to true,
- * but the search bar is not activated until the user types something.
- *
- * On the `input` event, update the search term and the selection range,
- * and activate the search bar.
- */
- const updateSearchText = () => {
- localSearchTerm.value = (searchInputRef.value as HTMLInputElement).value
- updateSelection()
- if (isInputFocused.value && !isSearchBarActive.value) {
- activate()
- }
- }
-
- const clearSearchText = () => {
- localSearchTerm.value = ""
- focusInput()
- }
-
- const {
- handleKeydown: handleInputKeydown,
- handleSelect,
- handleClear,
- recent,
- } = useRecentSearches({
- focusInput,
- term: localSearchTerm,
- isMobile: true,
- isInputFocused,
- })
-
- watch(recent.isVisible, (isVisible) => {
- if (!isVisible) {
- deactivate()
- if (localSearchTerm.value !== searchTerm.value) {
- searchTerm.value = localSearchTerm.value
- handleSearch()
- }
- }
- })
-
- const handleInputFocus = () => (isInputFocused.value = true)
- const handleInputBlur = () => {
- if (!recent.isVisible.value && isInputFocused.value) {
- deactivate()
- }
- }
-
- /**
- * Deactivate the search bar when the user clicks outside the header,
- * but not when the click is inside the recent searches modal.
- */
- onClickOutside(headerRef, (event) => {
- const clickInsideModal = recentSearchesRef.value?.$el?.contains(
- event.target as Node
- )
- if (!clickInsideModal) {
- isInputFocused.value = false
- }
- })
-
- /**
- * When activating the search bar by clicking, preserve the cursor position.
- */
- const handleInputClick = () => {
- if (!isSearchBarActive.value) {
- updateSelection()
- activate()
- }
- }
-
- /**
- * Close the modal when the last clickable element is clicked
- * (clear button when there are no recent searches).
- */
- const handleClearButtonTab = () => {
- if (!recent.entries.value.length) {
- handleTabOut("forward")
- }
- }
-
- /**
- * Special handling of focus order after leaving the search bar because
- * the input modal is inserted into the page and change the HTML elements order.
- * @param direction
- */
- const handleTabOut = (direction: "forward" | "backward") => {
- recent.hide()
- nextTick().then(() => {
- const element =
- direction === "forward"
- ? document.getElementById(skipToContentTargetId)
- : getAllTabbableIn(document.body)[1]
- ensureFocus(
- element ?? (getFirstTabbableIn(document.body) as HTMLElement)
- )
- })
- }
-
- const {
- close: closeContentSettings,
- open: openContentSettings,
- onTriggerClick: toggleContentSettings,
- triggerA11yProps,
- } = useDialogControl({
- visibleRef: contentSettingsOpen,
- nodeRef: headerRef,
- lockBodyScroll: true,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- emit: emit as (event: string, ...args: any[]) => void,
- })
-
- const route = useRoute()
- const routeSearchTerm = computed(() => firstParam(route?.query.q))
- watch(routeSearchTerm, (newSearchTerm) => {
- localSearchTerm.value = newSearchTerm ?? ""
- })
-
- const { doneHydrating } = useHydrating()
-
- const router = useRouter()
- router.beforeEach((to, from, next) => {
- if (to.path !== from.path) {
- closeContentSettings()
- deactivate()
- }
- next()
- })
-
- const handleTab = (
- event: KeyboardEvent & { key: "Tab" },
- button: "content-settings" | "clear-input"
- ) => {
- if (recent.isVisible.value) {
- event.preventDefault()
- focusIn(recentSearchesRef.value?.$el, 1)
- } else if (button === "content-settings") {
- handleTabOut("forward")
- }
- }
-
- return {
- isInputFocused,
- searchInputRef,
- headerRef,
- recentSearchesRef,
- clearButtonRef,
- contentSettingsButtonRef,
- contentSettingsButton,
-
- isFetching,
- appliedFilterCount,
- doneHydrating,
-
- contentSettingsOpen,
- triggerA11yProps,
- openContentSettings,
- closeContentSettings,
- toggleContentSettings,
-
- searchStatus,
- localSearchTerm,
- isSearchBarActive,
- deactivate,
- handleInputFocus,
- handleInputBlur,
- handleInputClick,
- handleInputKeydown,
-
- clearSearchText,
- updateSearchText,
- handleSearch,
- handleFormSubmit,
-
- isRecentVisible: recent.isVisible,
- selectedIdx: recent.selectedIdx,
- entries: recent.entries,
- hideRecentSearches: recent.hide,
- handleSelect,
- handleClear,
- handleClearButtonTab,
- handleTabOut,
- handleTab,
- }
- },
-})
-</script>
diff --git a/frontend/src/components/VHomepageContent.vue b/frontend/src/components/VHomepageContent.vue
index bfe8ba3aa..3fe61b5e1 100644
--- a/frontend/src/components/VHomepageContent.vue
+++ b/frontend/src/components/VHomepageContent.vue
@@ -1,3 +1,80 @@
+<script setup lang="ts">
+import { computed, ref } from "vue"
+
+import type { SearchType } from "~/constants/media"
+import { skipToContentTargetId } from "~/constants/window"
+
+import useSearchType from "~/composables/use-search-type"
+import { useDialogControl } from "~/composables/use-dialog-control"
+
+import { useUiStore } from "~/stores/ui"
+
+import VContentSettingsModalContent from "~/components/VHeader/VHeaderMobile/VContentSettingsModalContent.vue"
+import VLink from "~/components/VLink.vue"
+import VPopoverContent from "~/components/VPopover/VPopoverContent.vue"
+import VSearchTypeButton from "~/components/VContentSwitcher/VSearchTypeButton.vue"
+import VSearchTypes from "~/components/VContentSwitcher/VSearchTypes.vue"
+import VStandaloneSearchBar from "~/components/VHeader/VSearchBar/VStandaloneSearchBar.vue"
+
+const props = defineProps<{
+ handleSearch: (query: string) => void
+ searchType: SearchType
+ setSearchType: (searchType: SearchType) => void
+}>()
+
+const emit = defineEmits<{
+ keydown: []
+ blur: []
+ focus: []
+ open: []
+ close: []
+}>()
+
+const searchTypeButtonRef = ref<InstanceType<typeof VSearchTypeButton> | null>(
+ null
+)
+const searchBarRef = ref<InstanceType<typeof VStandaloneSearchBar> | null>(null)
+const nodeRef = computed(() => searchBarRef.value?.$el ?? null)
+
+const { getSearchTypeProps } = useSearchType()
+const uiStore = useUiStore()
+
+const searchTypeProps = computed(() => getSearchTypeProps())
+
+const isContentSwitcherVisible = ref(false)
+
+const isSm = computed(() => uiStore.isBreakpoint("sm"))
+const isLg = computed(() => uiStore.isBreakpoint("lg"))
+
+const triggerElement = computed(() => searchTypeButtonRef.value?.$el || null)
+
+const lockBodyScroll = computed(() => !isLg.value)
+
+/**
+ * When a search type is selected, we close the popover or modal,
+ * and focus the search input.
+ *
+ * @param searchType
+ */
+const handleSelect = (searchType: SearchType) => {
+ props.setSearchType(searchType)
+ searchBarRef.value?.focusInput()
+ closeContentSwitcher()
+}
+
+const {
+ close: closeContentSwitcher,
+ open: openContentSwitcher,
+ onTriggerClick,
+ triggerA11yProps,
+} = useDialogControl({
+ visibleRef: isContentSwitcherVisible,
+ nodeRef,
+ lockBodyScroll,
+ emit: emit as (event: string) => void,
+})
+</script>
+
<template>
<div :id="skipToContentTargetId" tabindex="-1">
<h1
@@ -77,116 +154,3 @@
</i18n-t>
</div>
</template>
-
-<script lang="ts">
-import { computed, defineComponent, ref, PropType } from "vue"
-
-import type { SearchType } from "~/constants/media"
-import { skipToContentTargetId } from "~/constants/window"
-
-import useSearchType from "~/composables/use-search-type"
-import { useDialogControl } from "~/composables/use-dialog-control"
-
-import { useUiStore } from "~/stores/ui"
-
-import VContentSettingsModalContent from "~/components/VHeader/VHeaderMobile/VContentSettingsModalContent.vue"
-import VLink from "~/components/VLink.vue"
-import VPopoverContent from "~/components/VPopover/VPopoverContent.vue"
-import VSearchTypeButton from "~/components/VContentSwitcher/VSearchTypeButton.vue"
-import VSearchTypes from "~/components/VContentSwitcher/VSearchTypes.vue"
-import VStandaloneSearchBar from "~/components/VHeader/VSearchBar/VStandaloneSearchBar.vue"
-
-export default defineComponent({
- name: "VHomepageContent",
- components: {
- VContentSettingsModalContent,
- VSearchTypes,
- VPopoverContent,
- VSearchTypeButton,
- VStandaloneSearchBar,
- VLink,
- },
- props: {
- handleSearch: {
- type: Function as PropType<(query: string) => void>,
- required: true,
- },
- searchType: {
- type: String as PropType<SearchType>,
- required: true,
- },
- setSearchType: {
- type: Function as PropType<(searchType: SearchType) => void>,
- required: true,
- },
- },
- setup(props, { emit }) {
- const searchTypeButtonRef = ref<InstanceType<
- typeof VSearchTypeButton
- > | null>(null)
- const searchBarRef = ref<InstanceType<typeof VStandaloneSearchBar> | null>(
- null
- )
- const nodeRef = computed(() => searchBarRef.value?.$el ?? null)
-
- const { getSearchTypeProps } = useSearchType()
- const uiStore = useUiStore()
-
- const searchTypeProps = computed(() => getSearchTypeProps())
-
- const isContentSwitcherVisible = ref(false)
-
- const isSm = computed(() => uiStore.isBreakpoint("sm"))
- const isLg = computed(() => uiStore.isBreakpoint("lg"))
-
- const triggerElement = computed(
- () => searchTypeButtonRef.value?.$el || null
- )
-
- const lockBodyScroll = computed(() => !isLg.value)
-
- /**
- * When a search type is selected, we close the popover or modal,
- * and focus the search input.
- *
- * @param searchType
- */
- const handleSelect = (searchType: SearchType) => {
- props.setSearchType(searchType)
- searchBarRef.value?.focusInput()
- closeContentSwitcher()
- }
-
- const {
- close: closeContentSwitcher,
- open: openContentSwitcher,
- onTriggerClick,
- triggerA11yProps,
- } = useDialogControl({
- visibleRef: isContentSwitcherVisible,
- nodeRef,
- lockBodyScroll,
- emit: emit as (event: string) => void,
- })
-
- return {
- searchTypeButtonRef,
- searchBarRef,
-
- isLg,
- isSm,
-
- triggerElement,
- onTriggerClick,
- handleSelect,
- searchTypeProps,
- closeContentSwitcher,
- openContentSwitcher,
- isContentSwitcherVisible,
- triggerA11yProps,
-
- skipToContentTargetId,
- }
- },
-})
-</script>
diff --git a/frontend/src/components/VMediaInfo/VMediaDetails.vue b/frontend/src/components/VMediaInfo/VMediaDetails.vue
index 53f0533f3..ff1b454e5 100644
--- a/frontend/src/components/VMediaInfo/VMediaDetails.vue
+++ b/frontend/src/components/VMediaInfo/VMediaDetails.vue
@@ -1,3 +1,37 @@
+<script setup lang="ts">
+import { useI18n } from "#imports"
+
+import { computed } from "vue"
+
+import type { AudioDetail, ImageDetail, Metadata } from "~/types/media"
+import { IMAGE } from "~/constants/media"
+
+import { getMediaMetadata } from "~/utils/metadata"
+
+import VContentReportPopover from "~/components/VContentReport/VContentReportPopover.vue"
+import VMetadata from "~/components/VMediaInfo/VMetadata.vue"
+import VMediaTags from "~/components/VMediaInfo/VMediaTags.vue"
+
+const props = defineProps<{ media: AudioDetail | ImageDetail }>()
+
+const i18n = useI18n({ useScope: "global" })
+
+const metadata = computed<null | Metadata[]>(() => {
+ if (!props.media) {
+ return null
+ }
+ let imageInfo =
+ props.media.frontendMediaType === IMAGE
+ ? {
+ width: props.media.width,
+ height: props.media.height,
+ type: props.media.filetype,
+ }
+ : {}
+ return getMediaMetadata(props.media, i18n, imageInfo)
+})
+</script>
+
<template>
<section class="flex flex-col gap-y-6 md:gap-y-8">
<header class="flex flex-row items-center justify-between">
@@ -25,54 +59,3 @@
</div>
</section>
</template>
-
-<script lang="ts">
-import { useI18n } from "#imports"
-
-import { computed, defineComponent, PropType } from "vue"
-
-import type { AudioDetail, ImageDetail, Metadata } from "~/types/media"
-import { IMAGE } from "~/constants/media"
-
-import { getMediaMetadata } from "~/utils/metadata"
-
-import VContentReportPopover from "~/components/VContentReport/VContentReportPopover.vue"
-import VMetadata from "~/components/VMediaInfo/VMetadata.vue"
-import VMediaTags from "~/components/VMediaInfo/VMediaTags.vue"
-
-export default defineComponent({
- components: {
- VMediaTags,
- VMetadata,
- VContentReportPopover,
- },
- props: {
- media: {
- type: Object as PropType<AudioDetail | ImageDetail>,
- required: true,
- },
- },
- setup(props) {
- const i18n = useI18n({ useScope: "global" })
-
- const metadata = computed<null | Metadata[]>(() => {
- if (!props.media) {
- return null
- }
- let imageInfo =
- props.media.frontendMediaType === IMAGE
- ? {
- width: props.media.width,
- height: props.media.height,
- type: props.media.filetype,
- }
- : {}
- return getMediaMetadata(props.media, i18n, imageInfo)
- })
-
- return {
- metadata,
- }
- },
-})
-</script>
diff --git a/frontend/src/components/VModal/VModal.vue b/frontend/src/components/VModal/VModal.vue
index 7c102c1d1..f0f478d6b 100644
--- a/frontend/src/components/VModal/VModal.vue
+++ b/frontend/src/components/VModal/VModal.vue
@@ -128,6 +128,10 @@ const {
emit: emit as SetupContext["emit"],
deactivateFocusTrap,
})
+
+defineExpose({
+ close,
+})
</script>
<template>
diff --git a/frontend/src/components/VModal/VModalContent.vue b/frontend/src/components/VModal/VModalContent.vue
index 0ff93b79c..f0d2010bf 100644
--- a/frontend/src/components/VModal/VModalContent.vue
+++ b/frontend/src/components/VModal/VModalContent.vue
@@ -82,6 +82,11 @@ const { onKeyDown, onBlur, deactivateFocusTrap } = useDialogContent({
attrs,
})
+const handleClose = (event: MouseEvent) => {
+ event.stopPropagation()
+ props.hide()
+}
+
defineExpose({
dialogRef,
deactivateFocusTrap,
@@ -89,93 +94,91 @@ defineExpose({
</script>
<template>
- <div>
- <Teleport to="#teleports">
+ <Teleport to="#teleports">
+ <div
+ v-show="visible"
+ class="h-dyn-screen min-h-dyn-screen fixed inset-0 z-40 flex justify-center overflow-y-auto"
+ :class="[
+ { 'flex-col items-center': variant === 'centered' },
+ variant === 'mobile-input'
+ ? 'top-20 h-[calc(100dvh-80px)] bg-tx'
+ : 'bg-dark-charcoal bg-opacity-75',
+ contentClasses,
+ ]"
+ >
+ <!-- re: disabled static element interactions rule https://github.com/WordPress/openverse/issues/2906 -->
+ <!-- eslint-disable-next-line vuejs-accessibility/no-static-element-interactions -->
<div
- v-show="visible"
- class="h-dyn-screen min-h-dyn-screen fixed inset-0 z-40 flex justify-center overflow-y-auto"
+ ref="dialogRef"
+ v-bind="$attrs"
+ class="flex flex-col"
:class="[
- { 'flex-col items-center': variant === 'centered' },
- variant === 'mobile-input'
- ? 'top-20 h-[calc(100dvh-80px)] bg-tx'
- : 'bg-dark-charcoal bg-opacity-75',
- contentClasses,
+ mode === 'dark'
+ ? 'bg-black text-white'
+ : 'bg-white text-dark-charcoal',
+ {
+ 'w-full md:max-w-[768px] lg:w-[768px] xl:w-[1024px] xl:max-w-[1024px]':
+ variant === 'default',
+ 'w-full': variant === 'full',
+ 'mt-auto h-2/3 w-full rounded-se-lg rounded-ss-lg bg-white':
+ variant === 'two-thirds',
+ 'mt-auto w-full rounded-se-lg rounded-ss-lg bg-white':
+ variant === 'fit-content',
+ 'm-6 rounded sm:m-0': variant === 'centered',
+ },
]"
+ role="dialog"
+ aria-modal="true"
+ @keydown="onKeyDown"
+ @blur="onBlur"
>
- <!-- re: disabled static element interactions rule https://github.com/WordPress/openverse/issues/2906 -->
- <!-- eslint-disable-next-line vuejs-accessibility/no-static-element-interactions -->
- <div
- ref="dialogRef"
- v-bind="$attrs"
- class="flex flex-col"
- :class="[
- mode === 'dark'
- ? 'bg-black text-white'
- : 'bg-white text-dark-charcoal',
- {
- 'w-full md:max-w-[768px] lg:w-[768px] xl:w-[1024px] xl:max-w-[1024px]':
- variant === 'default',
- 'w-full': variant === 'full',
- 'mt-auto h-2/3 w-full rounded-se-lg rounded-ss-lg bg-white':
- variant === 'two-thirds',
- 'mt-auto w-full rounded-se-lg rounded-ss-lg bg-white':
- variant === 'fit-content',
- 'm-6 rounded sm:m-0': variant === 'centered',
- },
- ]"
- role="dialog"
- aria-modal="true"
- @keydown="onKeyDown"
- @blur="onBlur"
- >
- <slot name="top-bar" :close="hide">
- <!--
+ <slot name="top-bar" :close="hide">
+ <!--
These specific padding and margin values serve to
visually align the Openverse logo button in the modal
with the header logo button so that there isn't a
jarring "shifting" effect when opening the mobile modal.
-->
- <div
- v-if="variant === 'default'"
- class="flex w-full shrink-0 justify-between bg-white py-4 pe-3 ps-4 md:justify-end md:bg-tx md:px-0 md:py-3"
- >
- <VIconButton
- ref="closeButton"
- :label="$t('modal.ariaClose')"
- variant="filled-white"
- size="small"
- @click="hide()"
- />
- </div>
- </slot>
-
<div
- class="modal-content flex w-full flex-grow flex-col"
- :class="{
- 'text-left align-bottom md:rounded-se-lg md:rounded-ss-lg':
- variant === 'default',
- 'w-auto rounded': variant === 'centered',
- 'mt-auto w-full rounded-se-lg rounded-ss-lg bg-white':
- variant === 'fit-content',
- 'flex w-full flex-col justify-between px-6 pb-10':
- variant === 'full',
- 'overflow-y-hidden rounded-se-lg rounded-ss-lg':
- variant === 'two-thirds',
- 'h-full': variant === 'mobile-input',
- 'bg-black text-white': mode === 'dark',
- 'bg-white text-dark-charcoal': mode === 'light',
- 'fallback-padding':
- variant === 'fit-content' ||
- variant === 'two-thirds' ||
- variant === 'mobile-input',
- }"
+ v-if="variant === 'default'"
+ class="flex w-full shrink-0 justify-between bg-white py-4 pe-3 ps-4 md:justify-end md:bg-tx md:px-0 md:py-3"
>
- <slot />
+ <VIconButton
+ ref="closeButton"
+ :label="$t('modal.ariaClose')"
+ variant="filled-white"
+ size="small"
+ @click="handleClose"
+ />
</div>
+ </slot>
+
+ <div
+ class="modal-content flex w-full flex-grow flex-col"
+ :class="{
+ 'text-left align-bottom md:rounded-se-lg md:rounded-ss-lg':
+ variant === 'default',
+ 'w-auto rounded': variant === 'centered',
+ 'mt-auto w-full rounded-se-lg rounded-ss-lg bg-white':
+ variant === 'fit-content',
+ 'flex w-full flex-col justify-between px-6 pb-10':
+ variant === 'full',
+ 'overflow-y-hidden rounded-se-lg rounded-ss-lg':
+ variant === 'two-thirds',
+ 'h-full': variant === 'mobile-input',
+ 'bg-black text-white': mode === 'dark',
+ 'bg-white text-dark-charcoal': mode === 'light',
+ 'fallback-padding':
+ variant === 'fit-content' ||
+ variant === 'two-thirds' ||
+ variant === 'mobile-input',
+ }"
+ >
+ <slot />
</div>
</div>
- </Teleport>
- </div>
+ </div>
+ </Teleport>
</template>
<style scoped>
diff --git a/frontend/src/components/VPopover/VPopover.vue b/frontend/src/components/VPopover/VPopover.vue
index 5c8873873..72a447df5 100644
--- a/frontend/src/components/VPopover/VPopover.vue
+++ b/frontend/src/components/VPopover/VPopover.vue
@@ -1,51 +1,9 @@
-<template>
- <div>
- <!-- re: disabled static element interactions rule https://github.com/WordPress/openverse/issues/2906 -->
- <!-- eslint-disable-next-line vuejs-accessibility/click-events-have-key-events, vuejs-accessibility/no-static-element-interactions -->
- <div
- ref="triggerContainerRef"
- class="flex w-min items-stretch whitespace-nowrap"
- @click="onTriggerClick"
- >
- <!--
- @slot The trigger, should be a button 99.99% of the time. If you need custom event handling on the trigger button, ensure bubbling is not prevented or else the popover will not open
- @binding {object} a11yProps
- @binding {boolean} visible
- -->
- <slot
- name="trigger"
- :a11y-props="triggerA11yProps"
- :visible="visibleRef"
- />
- </div>
- <VPopoverContent
- v-if="triggerRef"
- :z-index="zIndex"
- :visible="visibleRef"
- :trigger-element="triggerRef"
- :placement="placement"
- :strategy="strategy"
- :clippable="clippable"
- :hide-on-esc="hideOnEsc"
- :hide-on-click-outside="hideOnClickOutside"
- :auto-focus-on-show="autoFocusOnShow"
- :auto-focus-on-hide="autoFocusOnHide"
- :trap-focus="trapFocus"
- :hide="close"
- :aria-label="label"
- :aria-labelledby="labelledBy"
- >
- <!--
- @slot The content of the popover
- @binding {function} close
- -->
- <slot name="default" :close="close" />
- </VPopoverContent>
- </div>
-</template>
-
-<script lang="ts">
-import { defineComponent, ref, computed, PropType, SetupContext } from "vue"
+<script setup lang="ts">
+/**
+ * NB: Most of these technically default to `undefined` so that the underlying `VPopoverContent`
+ * default for each of them can take over.
+ */
+import { ref, computed, SetupContext } from "vue"
import { zIndexValidator } from "~/constants/z-indices"
@@ -55,24 +13,18 @@ import VPopoverContent from "~/components/VPopover/VPopoverContent.vue"
import type { Placement, Strategy } from "@floating-ui/dom"
-export default defineComponent({
- name: "VPopover",
- components: { VPopoverContent },
- /**
- * NB: Most of these technically default to `undefined` so that the underlying `VPopoverContent`
- * default for each of them can take over.
- */
- props: {
+const props = withDefaults(
+ defineProps<{
/**
* Whether the popover should show when the trigger is hovered on.
*/
- activateOnHover: { type: Boolean, default: undefined },
+ activateOnHover?: boolean
/**
* Whether the popover should hide when the <kbd>Escape</kbd> key is pressed.
*
* @default true
*/
- hideOnEsc: { type: Boolean, default: undefined },
+ hideOnEsc?: boolean
/**
* Whether the popover should hide when a click happens outside the popover content,
* excluding the trigger. When the trigger is clicked and the popover is open, nothing
@@ -80,20 +32,20 @@ export default defineComponent({
*
* @default true
*/
- hideOnClickOutside: { type: Boolean, default: undefined },
+ hideOnClickOutside?: boolean
/**
* Whether the popover content should automatically receive focus when the popover
* opens.
*
* @default true
*/
- autoFocusOnShow: { type: Boolean, default: undefined },
+ autoFocusOnShow?: boolean
/**
* Whether the trigger should automatically receive focus when the popover closes.
*
* @default true
*/
- autoFocusOnHide: { type: Boolean, default: undefined },
+ autoFocusOnHide?: boolean
/**
* The placement of the popover relative to the trigger. Should be one of the options
* for `placement` passed to floating-ui.
@@ -102,10 +54,7 @@ export default defineComponent({
*
* @default 'bottom'
*/
- placement: {
- type: String as PropType<Placement>,
- },
- /**
+ placement?: Placement /**
* The positioning strategy of the popover. If your reference element is in a fixed container
* use the fixed strategy; otherwise use the default, absolute strategy.
*
@@ -113,78 +62,126 @@ export default defineComponent({
*
* @default 'absolute'
*/
- strategy: {
- type: String as PropType<Strategy>,
- },
+ strategy?: Strategy
/**
* The label of the popover content. Must be provided if `labelledBy` is empty.
*
* @default undefined
*/
- label: { type: String },
+ label?: string
/**
* The id of the element labelling the popover content. Must be provided if `label` is empty.
*
* @default undefined
*/
- labelledBy: { type: String },
+ labelledBy?: string
/**
* the z-index to apply to the popover content
*/
- zIndex: {
- type: [Number, String],
- default: "popover", // named z-index
- validator: zIndexValidator,
- },
+ zIndex?: number | string
/**
* Whether the popover height should be clipped and made scrollable
* if the window height is too small.
*
* @default false
*/
- clippable: { type: Boolean, default: false },
+ clippable?: boolean
/**
* Whether the popover should trap focus. This means that when the popover is open,
* the user cannot tab out of the popover content. This is useful for ensuring that
* the popover content is accessible.
* @default true
*/
- trapFocus: { type: Boolean, default: undefined },
- },
- emits: [
- /**
- * Fires when the popover opens, regardless of reason. There are no extra parameters.
- */
- "open",
- /**
- * Fires when the popover closes, regardless of reason. There are no extra parameters.
- */
- "close",
- ],
- setup(props, { emit }) {
- const visibleRef = ref(false)
- const triggerContainerRef = ref<HTMLElement | null>(null)
+ trapFocus?: boolean
+ }>(),
+ {
+ activateOnHover: undefined,
+ hideOnEsc: undefined,
+ hideOnClickOutside: undefined,
+ autoFocusOnShow: undefined,
+ autoFocusOnHide: undefined,
+ zIndex: "popover",
+ clippable: false,
+ trapFocus: undefined,
+ }
+)
- const triggerRef = computed(() =>
- triggerContainerRef.value?.firstElementChild
- ? (triggerContainerRef.value.firstElementChild as HTMLElement)
- : undefined
- )
+if (!zIndexValidator(props.zIndex)) {
+ throw new Error(`Invalid z-index value in VPopover: ${props.zIndex}`)
+}
- const { close, open, onTriggerClick, triggerA11yProps } = useDialogControl({
- visibleRef,
- emit: emit as SetupContext["emit"],
- })
+const emit = defineEmits<{
+ /**
+ * Fires when the popover opens, regardless of reason. There are no extra parameters.
+ */
+ open: []
+ /**
+ * Fires when the popover closes, regardless of reason. There are no extra parameters.
+ */
+ close: []
+}>()
+
+const visibleRef = ref(false)
+const triggerContainerRef = ref<HTMLElement | null>(null)
+
+const triggerRef = computed(() =>
+ triggerContainerRef.value?.firstElementChild
+ ? (triggerContainerRef.value.firstElementChild as HTMLElement)
+ : undefined
+)
+
+const { close, onTriggerClick, triggerA11yProps } = useDialogControl({
+ visibleRef,
+ emit: emit as SetupContext["emit"],
+})
- return {
- open,
- close,
- visibleRef,
- triggerContainerRef,
- triggerRef,
- onTriggerClick,
- triggerA11yProps,
- }
- },
+defineExpose({
+ close,
})
</script>
+
+<template>
+ <div>
+ <!-- re: disabled static element interactions rule https://github.com/WordPress/openverse/issues/2906 -->
+ <!-- eslint-disable-next-line vuejs-accessibility/click-events-have-key-events, vuejs-accessibility/no-static-element-interactions -->
+ <div
+ ref="triggerContainerRef"
+ class="flex w-min items-stretch whitespace-nowrap"
+ @click="onTriggerClick"
+ >
+ <!--
+ @slot The trigger, should be a button 99.99% of the time. If you need custom event handling on the trigger button, ensure bubbling is not prevented or else the popover will not open
+ @binding {object} a11yProps
+ @binding {boolean} visible
+ -->
+ <slot
+ name="trigger"
+ :a11y-props="triggerA11yProps"
+ :visible="visibleRef"
+ />
+ </div>
+ <VPopoverContent
+ v-if="triggerRef"
+ :z-index="zIndex"
+ :visible="visibleRef"
+ :trigger-element="triggerRef"
+ :placement="placement"
+ :strategy="strategy"
+ :clippable="clippable"
+ :hide-on-esc="hideOnEsc"
+ :hide-on-click-outside="hideOnClickOutside"
+ :auto-focus-on-show="autoFocusOnShow"
+ :auto-focus-on-hide="autoFocusOnHide"
+ :trap-focus="trapFocus"
+ :hide="close"
+ :aria-label="label"
+ :aria-labelledby="labelledBy"
+ >
+ <!--
+ @slot The content of the popover
+ @binding {function} close
+ -->
+ <slot name="default" :close="close" />
+ </VPopoverContent>
+ </div>
+</template>