Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Fix recent searches test (#4789)
Olga Bulatf944960fdea2
diff --git a/frontend/src/components/VAudioTrack/VAudioControl.vue b/frontend/src/components/VAudioTrack/VAudioControl.vueindex 0e3842dc9..9931dc75a 100644--- a/frontend/src/components/VAudioTrack/VAudioControl.vue+++ b/frontend/src/components/VAudioTrack/VAudioControl.vue@@ -1,14 +1,11 @@-<script lang="ts">-import { computed, defineComponent, PropType } from "vue"--import {- AudioLayout,- audioLayouts,- AudioStatus,- audioStatuses,- statusVerbMap,-} from "~/constants/audio"-import { defineEvent } from "~/types/emits"+<script setup lang="ts">+/**+ * Displays the control for switching between the playing and paused states of+ * a media file.+ */+import { computed } from "vue"++import { AudioLayout, AudioStatus, statusVerbMap } from "~/constants/audio"import type { ButtonConnections } from "~/types/button"import { useHydrating } from "~/composables/use-hydrating"@@ -40,109 +37,73 @@ const sizes = {large: { button: "larger", icon: 10 },} as const-/**- * Displays the control for switching between the playing and paused states of- * a media file.- */-export default defineComponent({- name: "VAudioControl",- components: { VIconButton },- model: {- prop: "status",- event: "toggle",- },- props: {+const props = withDefaults(+ defineProps<{/*** the current play status of the audio*/- status: {- type: String as PropType<AudioStatus>,- required: true,- validator: (val: string) =>- (audioStatuses as readonly string[]).includes(val),- },+ status: AudioStatus/*** The size of the button. The size affects both the size of the button* itself and the icon inside it.*/- size: {- type: String as PropType<"small" | "medium" | "large">,- required: true,- validator: (val: string) => ["small", "medium", "large"].includes(val),- },+ size: "small" | "medium" | "large"/*** The parent audio layout currently in use. The connections are determined* by the layout and the size of the button.*/- layout: {- type: String as PropType<AudioLayout>,- default: "full",- validator: (val: string) =>- (audioLayouts as readonly string[]).includes(val),- },+ layout: AudioLayout/*** Whether the audio control button can be focused by using the `Tab` key*/- isTabbable: {- type: Boolean,- default: true,- },- },- emits: {- toggle: defineEvent<["paused" | "playing"]>(),- },- setup(props, { emit }) {- const isPlaying = computed(() => props.status === "playing")- const isLoading = computed(() => props.status === "loading")- /**- * Get the button label based on the current status of the player.- */- const label = computed(() => `playPause.${statusVerbMap[props.status]}`)- /**- * Get the button icon based on the current status of the player.- */- const icon = computed(() => statusIconMap[props.status])+ isTabbable?: boolean+ }>(),+ {+ layout: "full",+ isTabbable: true,+ }+)- /**- * Set the connections (none-rounded corners) for the button based on the layout.- */- const connections = computed(() => {- return props.layout === "row" && props.size === "small"- ? []- : [...layoutConnectionsMap[props.layout]]- })-- /** Convert the `audio-control` sizes to `VIconButton` sizes */- const buttonSize = computed(() => sizes[props.size].button)-- const iSize = computed(() => sizes[props.size].icon)-- const handleMouseDown = (event: MouseEvent) => {- if (!props.isTabbable) {- // to prevent focus- event.preventDefault()- }- }- const handleClick = () => {- emit("toggle", isPlaying.value || isLoading.value ? "paused" : "playing")- }-- const { doneHydrating } = useHydrating()-- return {- label,- icon,- connections,- buttonSize,- iSize,- isLoading,-- handleClick,- handleMouseDown,- doneHydrating,- }- },+const emit = defineEmits<{+ toggle: ["paused" | "playing"]+}>()++const isPlaying = computed(() => props.status === "playing")+const isLoading = computed(() => props.status === "loading")+/**+ * Get the button label based on the current status of the player.+ */+const label = computed(() => `playPause.${statusVerbMap[props.status]}`)+/**+ * Get the button icon based on the current status of the player.+ */+const icon = computed(() => statusIconMap[props.status])++/**+ * Set the connections (none-rounded corners) for the button based on the layout.+ */+const connections = computed(() => {+ return props.layout === "row" && props.size === "small"+ ? []+ : [...layoutConnectionsMap[props.layout]]})++/** Convert the `audio-control` sizes to `VIconButton` sizes */+const buttonSize = computed(() => sizes[props.size].button)++const iSize = computed(() => sizes[props.size].icon)++const handleMouseDown = (event: MouseEvent) => {+ if (!props.isTabbable) {+ // to prevent focus+ event.preventDefault()+ }+}+const handleClick = () => {+ emit("toggle", isPlaying.value || isLoading.value ? "paused" : "playing")+}++const { doneHydrating } = useHydrating()</script><template>diff --git a/frontend/src/components/VAudioTrack/VAudioTrack.vue b/frontend/src/components/VAudioTrack/VAudioTrack.vueindex b61a5fb9f..f288429fb 100644--- a/frontend/src/components/VAudioTrack/VAudioTrack.vue+++ b/frontend/src/components/VAudioTrack/VAudioTrack.vue@@ -1,14 +1,11 @@-<script lang="ts">+<script setup lang="ts">+/**+ * Displays the waveform and basic information about the track, along with+ * controls to play, pause or seek to a point on the track.+ */import { firstParam, useI18n, useRoute } from "#imports"-import {- computed,- defineComponent,- onUnmounted,- PropType,- ref,- watch,-} from "vue"+import { computed, onUnmounted, ref, watch } from "vue"import { useActiveAudio } from "~/composables/use-active-audio"import { defaultRef } from "~/composables/default-ref"@@ -32,9 +29,6 @@ import {import type { AudioInteraction, AudioInteractionData } from "~/types/analytics"import type { AudioDetail } from "~/types/media"--import { defineEvent } from "~/types/emits"-import type { AudioTrackClickEvent } from "~/types/events"import VAudioControl from "~/components/VAudioTrack/VAudioControl.vue"@@ -45,517 +39,457 @@ import VBoxLayout from "~/components/VAudioTrack/layouts/VBoxLayout.vue"import VGlobalLayout from "~/components/VAudioTrack/layouts/VGlobalLayout.vue"import VLink from "~/components/VLink.vue"-/**- * Displays the waveform and basic information about the track, along with- * controls to play, pause or seek to a point on the track.- */-export default defineComponent({- name: "VAudioTrack",- components: {- VAudioControl,- VWaveform,- VLink,-- // Layouts- VFullLayout,- VRowLayout,- VBoxLayout,- VGlobalLayout,- },- props: {- /**- * the information about the track, typically from a track's detail endpoint- */- audio: {- type: Object as PropType<AudioDetail>,- required: true,- },+const props = defineProps<{+ /**+ * The information about the track, typically from a track's detail endpoint+ */+ audio: AudioDetail+ /**+ * The arrangement of the contents on the canvas. This determines the+ * overall L&F of the audio component.+ */+ layout: AudioLayout+ /**+ * The size of the component; Both 'box' and 'row' layouts offer multiple+ * sizes to choose from.+ */+ size?: AudioSize+ /**+ * The search term that was used to find this track. This is used+ * in the link to the track's detail page.+ */+ searchTerm?: string+}>()+const emit = defineEmits<{+ "shift-tab": [KeyboardEvent]+ interacted: [Omit<AudioInteractionData, "component">]+ mousedown: [AudioTrackClickEvent]+ focus: [FocusEvent]+}>()++const { t } = useI18n({ useScope: "global" })++const activeMediaStore = useActiveMediaStore()+const route = useRoute()++const activeAudio = useActiveAudio()++const status = ref<AudioStatus>("paused")+const currentTime = ref(0)++const initLocalAudio = () => {+ // Preserve existing local audio if we plucked it from the global active audio+ if (!localAudio) {+ localAudio = new Audio(props.audio.url)+ }++ Object.entries(eventMap).forEach(([name, fn]) =>/**- * the arrangement of the contents on the canvas; This determines the- * overall L&F of the audio component.+ * This cast is safe, it just filters `undefined` that is still present on the+ * `localAudio`'s type despite the check above to create it if it doesn't exist.*/- layout: {- type: String as PropType<AudioLayout>,- required: true,- },- /**- * the size of the component; Both 'box' and 'row' layouts offer multiple- * sizes to choose from.- */- size: {- type: String as PropType<AudioSize>,- },- /**- * the search term that was used to find this track; This is used- * in the link to the track's detail page.- */- searchTerm: {- type: String,- },- },- emits: {- "shift-tab": defineEvent<[KeyboardEvent]>(),- interacted: defineEvent<[Omit<AudioInteractionData, "component">]>(),- mousedown: defineEvent<[AudioTrackClickEvent]>(),- focus: defineEvent<[FocusEvent]>(),- },- setup(props, { emit }) {- const { t } = useI18n({ useScope: "global" })-- const activeMediaStore = useActiveMediaStore()- const route = useRoute()-- const activeAudio = useActiveAudio()-- const status = ref<AudioStatus>("paused")- const currentTime = ref(0)-- const initLocalAudio = () => {- // Preserve existing local audio if we plucked it from the global active audio- if (!localAudio) {- localAudio = new Audio(props.audio.url)- }-- Object.entries(eventMap).forEach(([name, fn]) =>- /**- * This cast is safe, it just filters `undefined` that is still present on the- * `localAudio`'s type despite the check above to create it if it doesn't exist.- */- (localAudio as HTMLAudioElement).addEventListener(name, fn)- )-- /**- * Similar to the behavior in the global audio track,- * if the local audio was set to an already existing and- * matching active global track, then we'll need to initialize- * the status based on the `paused` and `ended` booleans- * on the audio object.- *- * For newly initialized audio objects, this is harmless,- * but it is essential for making sure page transitions- * preserve the existing, already manipulated audio- * object's state.- *- * Unlike the global audio track, however, this will not- * always result in a status of `playing` in practice,- * as the state of the active global track could be any- * of the three statuses we track when the page transition- * happens. For example, the audio track on the result page- * could have been played through (and thus `ended`), or it- * could be paused mid-way (and thus `paused`), or neither- * and thus would be playing.- */- if (localAudio.paused) {- if (localAudio.ended) {- setPlayed()- } else {- setPaused()- }- } else {- setPlaying()- }-- currentTime.value = localAudio.currentTime+ (localAudio as HTMLAudioElement).addEventListener(name, fn)+ )++ /**+ * Similar to the behavior in the global audio track,+ * if the local audio was set to an already existing and+ * matching active global track, then we'll need to initialize+ * the status based on the `paused` and `ended` booleans+ * on the audio object.+ *+ * For newly initialized audio objects, this is harmless,+ * but it is essential for making sure page transitions+ * preserve the existing, already manipulated audio+ * object's state.+ *+ * Unlike the global audio track, however, this will not+ * always result in a status of `playing` in practice,+ * as the state of the active global track could be any+ * of the three statuses we track when the page transition+ * happens. For example, the audio track on the result page+ * could have been played through (and thus `ended`), or it+ * could be paused mid-way (and thus `paused`), or neither+ * and thus would be playing.+ */+ if (localAudio.paused) {+ if (localAudio.ended) {+ setPlayed()+ } else {+ setPaused()}+ } else {+ setPlaying()+ }- /**- * We can only create the local audio object on the client,- * so the initialization of this variable is hidden inside- * the `initLocalAudio` function which is only called when- * playback is first requested or when the track is first seeked.- *- * However, when navigating to an audio result page, if- * the globally active audio already matches the result- * that was clicked on, hijack that object instead and- * treat it as the local audio for this instance.- */- let localAudio =- activeAudio.obj.value?.src === props.audio.url- ? activeAudio.obj.value- : undefined-- const updateTimeLoop = () => {- if (localAudio) {- if (activeAudioStatus.includes(status.value)) {- currentTime.value = localAudio.currentTime- window.requestAnimationFrame(updateTimeLoop)- } else {- currentTime.value = localAudio.currentTime- }- }- }+ currentTime.value = localAudio.currentTime+}- const mediaStore = useMediaStore()- const setLoaded = () => {- mediaStore.setMediaProperties("audio", props.audio.id, {- hasLoaded: true,- })- status.value = "playing"- }- const setWaiting = () => {- status.value = "loading"- }- const setPlaying = () => {- if (props.audio.hasLoaded) {- status.value = "playing"- } else {- status.value = "loading"- }- activeAudio.obj.value = localAudio- activeMediaStore.setActiveMediaItem({- type: "audio",- id: props.audio.id,- })- activeMediaStore.setMessage({ message: null })- updateTimeLoop()+/**+ * We can only create the local audio object on the client,+ * so the initialization of this variable is hidden inside+ * the `initLocalAudio` function which is only called when+ * playback is first requested or when the track is first seeked.+ *+ * However, when navigating to an audio result page, if+ * the globally active audio already matches the result+ * that was clicked on, hijack that object instead and+ * treat it as the local audio for this instance.+ */+let localAudio =+ activeAudio.obj.value?.src === props.audio.url+ ? activeAudio.obj.value+ : undefined++const updateTimeLoop = () => {+ if (localAudio) {+ if (activeAudioStatus.includes(status.value)) {+ currentTime.value = localAudio.currentTime+ window.requestAnimationFrame(updateTimeLoop)+ } else {+ currentTime.value = localAudio.currentTime}- const setPaused = () => {+ }+}++const mediaStore = useMediaStore()+const setLoaded = () => {+ mediaStore.setMediaProperties("audio", props.audio.id, {+ hasLoaded: true,+ })+ status.value = "playing"+}+const setWaiting = () => {+ status.value = "loading"+}+const setPlaying = () => {+ if (props.audio.hasLoaded) {+ status.value = "playing"+ } else {+ status.value = "loading"+ }+ activeAudio.obj.value = localAudio+ activeMediaStore.setActiveMediaItem({+ type: "audio",+ id: props.audio.id,+ })+ activeMediaStore.setMessage({ message: null })+ updateTimeLoop()+}+const setPaused = () => {+ status.value = "paused"+ activeMediaStore.pauseActiveMediaItem()+}+const setPlayed = () => (status.value = "played")+const setTimeWhenPaused = () => {+ if (status.value !== "playing" && localAudio) {+ currentTime.value = localAudio.currentTime+ if (status.value === "played") {+ // Set to pause to remove replay iconstatus.value = "paused"- activeMediaStore.pauseActiveMediaItem()- }- const setPlayed = () => (status.value = "played")- const setTimeWhenPaused = () => {- if (status.value !== "playing" && localAudio) {- currentTime.value = localAudio.currentTime- if (status.value === "played") {- // Set to pause to remove replay icon- status.value = "paused"- }- }}- const duration = defaultRef(() => {- if (localAudio) {- return localAudio.duration- }- if (typeof props.audio?.duration === "number") {- return props.audio.duration / 1e3- }- return 0- })- const setDuration = () => {- if (localAudio) {- duration.value = localAudio.duration- }- }-- const eventMap = {- play: setPlaying,- pause: setPaused,- ended: setPlayed,- timeupdate: setTimeWhenPaused,- durationchange: setDuration,- waiting: setWaiting,- playing: setLoaded,- } as const+ }+}+const duration = defaultRef(() => {+ if (localAudio) {+ return localAudio.duration+ }+ if (typeof props.audio?.duration === "number") {+ return props.audio.duration / 1e3+ }+ return 0+})+const setDuration = () => {+ if (localAudio) {+ duration.value = localAudio.duration+ }+}++const eventMap = {+ play: setPlaying,+ pause: setPaused,+ ended: setPlayed,+ timeupdate: setTimeWhenPaused,+ durationchange: setDuration,+ waiting: setWaiting,+ playing: setLoaded,+} as const- /**- * If we're transforming the globally active audio- * into our local audio, then we need to initialize- * the local state syncing from the audio object- * to our local refs.- *- * This lives here instead of closer to where `localAudio`- * is defined because `initLocalAudio` and several of- * the functions it depends on also all depend on the- * `localAudio` variable. This is the earliest in- * `setup` that this can be called.- */- if (localAudio) {- initLocalAudio()- }+/**+ * If we're transforming the globally active audio+ * into our local audio, then we need to initialize+ * the local state syncing from the audio object+ * to our local refs.+ *+ * This lives here instead of closer to where `localAudio`+ * is defined because `initLocalAudio` and several of+ * the functions it depends on also all depend on the+ * `localAudio` variable. This is the earliest in+ * `setup` that this can be called.+ */+if (localAudio) {+ initLocalAudio()+}- onUnmounted(() => {- if (!localAudio) {- return- }+onUnmounted(() => {+ if (!localAudio) {+ return+ }- Object.entries(eventMap).forEach(([name, fn]) =>- localAudio?.removeEventListener(name, fn)- )-- const { matches: isSearchRoute } = useMatchSearchRoutes()- const { matches: isSingleResultRoute } = useMatchSingleResultRoutes()-- const mediaId = firstParam(route?.params.id)-- if (- (isSingleResultRoute.value && mediaId && mediaId === props.audio.id) ||- (isSearchRoute.value && mediaStore.getItemById(AUDIO, props.audio.id))- ) {- /**- * If switching to any route other than the single result- * route for this track, pause it. Otherwise, let it keep- * playing to introduce a "seamless" feeling between the- * search results page and the single result page.- *- * This handles going from the search page to the single- * result page for a different track than is currently playing.- * It also handles the same interaction for related audio.- * Also for related audio, it will handle pausing any related- * audio when navigating back from the single result page- * to the search results page.- *- * Also, if the currently playing audio is present in the- * existing list of search results, then also let it keep- * playing.- */- return- }+ Object.entries(eventMap).forEach(([name, fn]) =>+ localAudio?.removeEventListener(name, fn)+ )- localAudio.pause()- })+ const { matches: isSearchRoute } = useMatchSearchRoutes()+ const { matches: isSingleResultRoute } = useMatchSingleResultRoutes()- const play = () => {- // Delay initializing the local audio element until playback is requested- if (!localAudio) {- initLocalAudio()- }- activeMediaStore.playAudio(localAudio)- }- const pause = () => localAudio?.pause()-- watch(- activeAudio.obj,- (audio) => {- if (- audio !== localAudio &&- (status.value === "playing" || status.value === "loading")- ) {- localAudio?.pause()- }- },- { immediate: true }- )-- /* Timekeeping */-- const message = computed(() =>- activeMediaStore.message- ? t(`audioTrack.messages.${activeMediaStore.message}`)- : ""- )-- /* Interface with VAudioControl */+ const mediaId = firstParam(route?.params.id)+ if (+ (isSingleResultRoute.value && mediaId && mediaId === props.audio.id) ||+ (isSearchRoute.value && mediaStore.getItemById(AUDIO, props.audio.id))+ ) {/**- * This function can safely ignore the `loading` status because- * that status is never toggled _to_.+ * If switching to any route other than the single result+ * route for this track, pause it. Otherwise, let it keep+ * playing to introduce a "seamless" feeling between the+ * search results page and the single result page.+ *+ * This handles going from the search page to the single+ * result page for a different track than is currently playing.+ * It also handles the same interaction for related audio.+ * Also for related audio, it will handle pausing any related+ * audio when navigating back from the single result page+ * to the search results page.+ *+ * Also, if the currently playing audio is present in the+ * existing list of search results, then also let it keep+ * playing.*/- const handleToggle = (state?: Exclude<AudioStatus, "loading">) => {- let event: AudioInteraction | undefined = undefined- if (!state) {- switch (status.value) {- case "playing": {- state = "paused"- break- }- case "paused":- case "played": {- state = "playing"- break- }- }- }+ return+ }- switch (state) {- case "playing": {- play()- event = "play"- break- }- case "paused": {- pause()- event = "pause"- break- }- }- emitInteracted(event)- }+ localAudio.pause()+})- const emitInteracted = (event?: AudioInteraction) => {- if (!event) {- return- }- snackbar.dismiss()- emit("interacted", {- event,- id: props.audio.id,- provider: props.audio.provider,- })+const play = () => {+ // Delay initializing the local audio element until playback is requested+ if (!localAudio) {+ initLocalAudio()+ }+ activeMediaStore.playAudio(localAudio)+}+const pause = () => localAudio?.pause()++watch(+ activeAudio.obj,+ (audio) => {+ if (+ audio !== localAudio &&+ (status.value === "playing" || status.value === "loading")+ ) {+ localAudio?.pause()}+ },+ { immediate: true }+)- /* Interface with VWaveform */+/* Timekeeping */- const handleSeeked = (frac: number) => {- if (!localAudio) {- initLocalAudio()- }- /**- * Calling initLocalAudio will guarantee localAudio- * to be an HTMLAudioElement, but we can't prove that- * to TypeScript without jumping through some tricky- * hoops (using `assert`) or adding unnecessary- * runtime checks.- */- if (localAudio) {- if (Number.isFinite(duration.value)) {- localAudio.currentTime = frac * duration.value- } else if (Number.isFinite(localAudio.duration)) {- localAudio.currentTime = frac * localAudio.duration- } else {- console.warn("Duration is not finite. Skipping seek.")- }- }- emitInteracted("seek")- }+const message = computed(() =>+ activeMediaStore.message+ ? t(`audioTrack.messages.${activeMediaStore.message}`)+ : ""+)- /* Layout */- const layoutMappings = {- full: VFullLayout,- row: VRowLayout,- box: VBoxLayout,- global: VGlobalLayout,- }- const layoutComponent = computed(() => layoutMappings[props.layout])+/* Interface with VAudioControl */- /**- * Sets default size if not provided.- */- const layoutSize = computed(() => {- if (props.layout === "box" && !props.size) {- return undefined+/**+ * This function can safely ignore the `loading` status because+ * that status is never toggled _to_.+ */+const handleToggle = (state?: Exclude<AudioStatus, "loading">) => {+ let event: AudioInteraction | undefined = undefined+ if (!state) {+ switch (status.value) {+ case "playing": {+ state = "paused"+ break+ }+ case "paused":+ case "played": {+ state = "playing"+ break}- return props.size ?? "m"- })-- /**- * A ref used on the play/pause button,- * so we can capture clicks and skip- * sending an event to the boxed layout.- */- const audioControlRef = ref<InstanceType<typeof VAudioControl> | null>(null)-- /**- * A ref used on the waveform, so we can capture mousedown on the- * audio track outside it as it will open a detail page.- */- const waveformRef = ref<InstanceType<typeof VWaveform> | null>(null)-- const handleMousedown = (event: MouseEvent) => {- const inWaveform =- waveformRef.value?.$el.contains(event.target as Node) ?? false- snackbar.handleMouseDown()- emit("mousedown", { event, inWaveform })}+ }- /**- * These layout-conditional props and listeners allow us- * to set properties on the parent element depending on- * the layout in use.- */- const isComposite = computed(() => ["box", "row"].includes(props.layout))- const layoutBasedProps = computed(() =>- isComposite.value- ? {- href: `/audio/${props.audio.id}/${- props.searchTerm ? "?q=" + props.searchTerm : ""- }`,- class: [- "cursor-pointer",- {- "focus-bold-filled": props.layout === "box",- "focus-slim-tx": props.layout === "row",- },- ],- }- : {}- )- const ariaLabel = computed(() =>- isComposite.value- ? t("audioTrack.ariaLabelInteractiveSeekable", {- title: props.audio.title,- })- : t("audioTrack.ariaLabel", { title: props.audio.title })- )-- const togglePlayback = () => {- status.value = activeAudioStatus.includes(status.value)- ? "paused"- : "playing"- handleToggle(status.value)+ switch (state) {+ case "playing": {+ play()+ event = "play"+ break}-- const { isSeeking, ...seekable } = useSeekable({- duration,- currentTime,- isReady: ref(true),- isSeekable: computed(() => props.layout !== "box"),- onSeek: handleSeeked,- onTogglePlayback: togglePlayback,- })- const handleKeydown = (event: KeyboardEvent) => {- seekable.listeners.keydown(event)+ case "paused": {+ pause()+ event = "pause"+ break+ }+ }+ emitInteracted(event)+}++const emitInteracted = (event?: AudioInteraction) => {+ if (!event) {+ return+ }+ snackbar.dismiss()+ emit("interacted", {+ event,+ id: props.audio.id,+ provider: props.audio.provider,+ })+}++/* Interface with VWaveform */++const handleSeeked = (frac: number) => {+ if (!localAudio) {+ initLocalAudio()+ }+ /**+ * Calling initLocalAudio will guarantee localAudio+ * to be an HTMLAudioElement, but we can't prove that+ * to TypeScript without jumping through some tricky+ * hoops (using `assert`) or adding unnecessary+ * runtime checks.+ */+ if (localAudio) {+ if (Number.isFinite(duration.value)) {+ localAudio.currentTime = frac * duration.value+ } else if (Number.isFinite(localAudio.duration)) {+ localAudio.currentTime = frac * localAudio.duration+ } else {+ console.warn("Duration is not finite. Skipping seek.")}+ }+ emitInteracted("seek")+}++/* Layout */+const layoutMappings = {+ full: VFullLayout,+ row: VRowLayout,+ box: VBoxLayout,+ global: VGlobalLayout,+}+const layoutComponent = computed(() => layoutMappings[props.layout])- const containerAttributes = computed(() => ({- // ARIA slider attributes are only added when interactive- ...(isComposite.value ? seekable.attributes.value : {}),- ...layoutBasedProps.value,- }))+/**+ * Sets default size if not provided.+ */+const layoutSize = computed(() => {+ if (props.layout === "box" && !props.size) {+ return undefined+ }+ return props.size ?? "m"+})- const snackbar = useAudioSnackbar()+/**+ * A ref used on the play/pause button,+ * so we can capture clicks and skip+ * sending an event to the boxed layout.+ */+const audioControlRef = ref<InstanceType<typeof VAudioControl> | null>(null)- const handleFocus = (event: FocusEvent) => {- snackbar.show()- emit("focus", event)- }+/**+ * A ref used on the waveform, so we can capture mousedown on the+ * audio track outside it as it will open a detail page.+ */+const waveformRef = ref<InstanceType<typeof VWaveform> | null>(null)- const handleBlur = () => {- snackbar.hide()- seekable.listeners.blur()- }+const handleMousedown = (event: MouseEvent) => {+ const inWaveform =+ waveformRef.value?.$el.contains(event.target as Node) ?? false+ snackbar.handleMouseDown()+ emit("mousedown", { event, inWaveform })+}- const handleWaveformFocus = (event: FocusEvent) => {- if (!isComposite.value) {- handleFocus(event)- }- }- const handleWaveformBlur = () => {- if (!isComposite.value) {- handleBlur()+/**+ * These layout-conditional props and listeners allow us+ * to set properties on the parent element depending on+ * the layout in use.+ */+const isComposite = computed(() => ["box", "row"].includes(props.layout))+const layoutBasedProps = computed(() =>+ isComposite.value+ ? {+ href: `/audio/${props.audio.id}/${+ props.searchTerm ? "?q=" + props.searchTerm : ""+ }`,+ class: [+ "cursor-pointer",+ {+ "focus-bold-filled": props.layout === "box",+ "focus-slim-tx": props.layout === "row",+ },+ ],}- }-- return {- status,- message,- ariaLabel,- handleToggle,- handleSeeked,- handleKeydown,- handleBlur,- handleMousedown,- handleFocus,- handleWaveformBlur,- handleWaveformFocus,-- isSeeking,-- currentTime,- duration,-- layoutComponent,- layoutSize,-- isComposite,- containerAttributes,-- audioControlRef,- waveformRef,- VLink,- }- },+ : {}+)+const ariaLabel = computed(() =>+ isComposite.value+ ? t("audioTrack.ariaLabelInteractiveSeekable", {+ title: props.audio.title,+ })+ : t("audioTrack.ariaLabel", { title: props.audio.title })+)++const togglePlayback = () => {+ status.value = activeAudioStatus.includes(status.value) ? "paused" : "playing"+ handleToggle(status.value)+}++const { isSeeking, ...seekable } = useSeekable({+ duration,+ currentTime,+ isReady: ref(true),+ isSeekable: computed(() => props.layout !== "box"),+ onSeek: handleSeeked,+ onTogglePlayback: togglePlayback,})+const handleKeydown = (event: KeyboardEvent) => {+ seekable.listeners.keydown(event)+}++const containerAttributes = computed(() => ({+ // ARIA slider attributes are only added when interactive+ ...(isComposite.value ? seekable.attributes.value : {}),+ ...layoutBasedProps.value,+}))++const snackbar = useAudioSnackbar()++const handleFocus = (event: FocusEvent) => {+ snackbar.show()+ emit("focus", event)+}++const handleBlur = () => {+ snackbar.hide()+ seekable.listeners.blur()+}++const handleWaveformFocus = (event: FocusEvent) => {+ if (!isComposite.value) {+ handleFocus(event)+ }+}+const handleWaveformBlur = () => {+ if (!isComposite.value) {+ handleBlur()+ }+}</script><template>diff --git a/frontend/src/components/VAudioTrack/VGlobalAudioTrack.vue b/frontend/src/components/VAudioTrack/VGlobalAudioTrack.vueindex ed0358bf9..7fc991b0f 100644--- a/frontend/src/components/VAudioTrack/VGlobalAudioTrack.vue+++ b/frontend/src/components/VAudioTrack/VGlobalAudioTrack.vue@@ -1,7 +1,11 @@-<script lang="ts">+<script setup lang="ts">+/**+ * Displays the waveform and basic information about the track, along with+ * controls to play, pause or seek to a point on the track.+ */import { useI18n, useNuxtApp } from "#imports"-import { computed, defineComponent, PropType, ref, watch } from "vue"+import { computed, ref, watch } from "vue"import { useActiveAudio } from "~/composables/use-active-audio"import { defaultRef } from "~/composables/default-ref"@@ -17,225 +21,196 @@ import VAudioControl from "~/components/VAudioTrack/VAudioControl.vue"import VWaveform from "~/components/VAudioTrack/VWaveform.vue"import VGlobalLayout from "~/components/VAudioTrack/layouts/VGlobalLayout.vue"-/**- * Displays the waveform and basic information about the track, along with- * controls to play, pause or seek to a point on the track.- */-export default defineComponent({- name: "VGlobalAudioTrack",- components: {- VAudioControl,- VWaveform,- VGlobalLayout,- },- props: {- /**- * the information about the track, typically from a track's detail endpoint- */- audio: {- type: Object as PropType<AudioDetail>,- required: true,- },- },- setup(props) {- const { t } = useI18n({ useScope: "global" })- const activeMediaStore = useActiveMediaStore()- const activeAudio = useActiveAudio()- const { $sendCustomEvent } = useNuxtApp()-- const ariaLabel = computed(() =>- t("audioTrack.ariaLabel", { title: props.audio.title })- )-- const status = ref<AudioStatus>("paused")- const currentTime = ref(0)- const duration = defaultRef(() => {- if (typeof props.audio?.duration === "number") {- return props.audio.duration / 1e3- }- return 0- })-- const setPlaying = () => {- if (props.audio.hasLoaded) {- status.value = "playing"- } else {- status.value = "loading"- }- updateTimeLoop()- }- const setPaused = () => (status.value = "paused")- const setPlayed = () => (status.value = "played")-- const setTimeWhenPaused = (event: Event) => {- if (status.value !== "playing" && event.target) {- currentTime.value = (event.target as HTMLAudioElement).currentTime ?? 0- if (status.value === "played") {- // Set to pause to remove replay icon- status.value = "paused"- }- }- }- const setDuration = () => {- if (activeAudio.obj.value) {- duration.value = activeAudio.obj.value.duration- }- }-- const updateTimeLoop = () => {- if (- activeAudio.obj.value &&- (status.value === "playing" || status.value === "loading")- ) {- currentTime.value = activeAudio.obj.value.currentTime- window.requestAnimationFrame(updateTimeLoop)- }- }+const props = defineProps<{+ /**+ * The information about the track, typically from a track's detail endpoint+ */+ audio: AudioDetail+}>()++const { t } = useI18n({ useScope: "global" })+const activeMediaStore = useActiveMediaStore()+const activeAudio = useActiveAudio()+const { $sendCustomEvent } = useNuxtApp()++const ariaLabel = computed(() =>+ t("audioTrack.ariaLabel", { title: props.audio.title })+)++const status = ref<AudioStatus>("paused")+const currentTime = ref(0)+const duration = defaultRef(() => {+ if (typeof props.audio?.duration === "number") {+ return props.audio.duration / 1e3+ }+ return 0+})- const mediaStore = useMediaStore()- const setLoaded = () => {- mediaStore.setMediaProperties("audio", props.audio.id, {- hasLoaded: true,- })- status.value = "playing"+const setPlaying = () => {+ if (props.audio.hasLoaded) {+ status.value = "playing"+ } else {+ status.value = "loading"+ }+ updateTimeLoop()+}+const setPaused = () => (status.value = "paused")+const setPlayed = () => (status.value = "played")++const setTimeWhenPaused = (event: Event) => {+ if (status.value !== "playing" && event.target) {+ currentTime.value = (event.target as HTMLAudioElement).currentTime ?? 0+ if (status.value === "played") {+ // Set to pause to remove replay icon+ status.value = "paused"}- const setWaiting = () => {- status.value = "loading"+ }+}+const setDuration = () => {+ if (activeAudio.obj.value) {+ duration.value = activeAudio.obj.value.duration+ }+}++const updateTimeLoop = () => {+ if (+ activeAudio.obj.value &&+ (status.value === "playing" || status.value === "loading")+ ) {+ currentTime.value = activeAudio.obj.value.currentTime+ window.requestAnimationFrame(updateTimeLoop)+ }+}++const mediaStore = useMediaStore()+const setLoaded = () => {+ mediaStore.setMediaProperties("audio", props.audio.id, {+ hasLoaded: true,+ })+ status.value = "playing"+}+const setWaiting = () => {+ status.value = "loading"+}++const eventMap = {+ play: setPlaying,+ pause: setPaused,+ ended: setPlayed,+ timeupdate: setTimeWhenPaused,+ durationchange: setDuration,+ waiting: setWaiting,+ playing: setLoaded,+} as const++watch(+ activeAudio.obj,+ (audio, _, onInvalidate) => {+ if (!audio) {+ return}- const eventMap = {- play: setPlaying,- pause: setPaused,- ended: setPlayed,- timeupdate: setTimeWhenPaused,- durationchange: setDuration,- waiting: setWaiting,- playing: setLoaded,- } as const-- watch(- activeAudio.obj,- (audio, _, onInvalidate) => {- if (!audio) {- return- }-- Object.entries(eventMap).forEach(([name, fn]) =>- audio.addEventListener(name, fn)- )-- currentTime.value = audio.currentTime- if (audio.duration && !isNaN(audio.duration)) {- duration.value = audio.duration- }-- /**- * By the time the `activeAudio` is updated and a rerender- * happens (triggering this watch function), all the events- * we've registered above will already have fired, so we- * need to derive the current status of the audio from the- * `paused` and `ended` booleans on the audio object.- *- * In practice this will always result in the status being- * set to `playing` as the active audio is only updated when- * a new track is set to play. But for good measure we might- * as well do this robustly and make sure that the status is- * always synced any time the active audio hangs.- */- if (audio.paused) {- if (audio.ended) {- setPlayed()- } else {- setPaused()- }- } else {- setPlaying()- }-- onInvalidate(() => {- Object.entries(eventMap).forEach(([name, fn]) =>- audio.removeEventListener(name, fn)- )- })- },- { immediate: true }- )-- const play = () => activeMediaStore.playAudio(activeAudio.obj.value)- const pause = () => activeAudio.obj.value?.pause()-- /* Timekeeping */- const message = computed(() =>- activeMediaStore.message- ? t(`audioTrack.messages.${activeMediaStore.message}`)- : ""+ Object.entries(eventMap).forEach(([name, fn]) =>+ audio.addEventListener(name, fn))- /* Interface with VAudioControl */-- const sendAudioInteractionEvent = (event: AudioInteraction) => {- $sendCustomEvent("AUDIO_INTERACTION", {- id: props.audio.id,- provider: props.audio.provider,- event,- component: "VGlobalAudioTrack",- })+ currentTime.value = audio.currentTime+ if (audio.duration && !isNaN(audio.duration)) {+ duration.value = audio.duration}- const handleToggle = (- state?: Exclude<AudioStatus, "loading" | "played">- ) => {- if (!state) {- switch (status.value) {- case "playing": {- state = "paused"- break- }- case "paused":- case "played": {- state = "playing"- break- }- }- }- let event: AudioInteraction | undefined = undefined- switch (state) {- case "playing": {- play()- event = "play"- break- }- case "paused": {- pause()- event = "pause"- break- }- }- if (event) {- sendAudioInteractionEvent(event)++ /**+ * By the time the `activeAudio` is updated and a rerender+ * happens (triggering this watch function), all the events+ * we've registered above will already have fired, so we+ * need to derive the current status of the audio from the+ * `paused` and `ended` booleans on the audio object.+ *+ * In practice this will always result in the status being+ * set to `playing` as the active audio is only updated when+ * a new track is set to play. But for good measure we might+ * as well do this robustly and make sure that the status is+ * always synced any time the active audio hangs.+ */+ if (audio.paused) {+ if (audio.ended) {+ setPlayed()+ } else {+ setPaused()}+ } else {+ setPlaying()}- /* Interface with VWaveform */-- const handleSeeked = (frac: number) => {- if (activeAudio.obj.value) {- activeAudio.obj.value.currentTime = frac * duration.value- sendAudioInteractionEvent("seek")+ onInvalidate(() => {+ Object.entries(eventMap).forEach(([name, fn]) =>+ audio.removeEventListener(name, fn)+ )+ })+ },+ { immediate: true }+)++const play = () => activeMediaStore.playAudio(activeAudio.obj.value)+const pause = () => activeAudio.obj.value?.pause()++/* Timekeeping */+const message = computed(() =>+ activeMediaStore.message+ ? t(`audioTrack.messages.${activeMediaStore.message}`)+ : ""+)++/* Interface with VAudioControl */++const sendAudioInteractionEvent = (event: AudioInteraction) => {+ $sendCustomEvent("AUDIO_INTERACTION", {+ id: props.audio.id,+ provider: props.audio.provider,+ event,+ component: "VGlobalAudioTrack",+ })+}+const handleToggle = (state?: Exclude<AudioStatus, "loading" | "played">) => {+ if (!state) {+ switch (status.value) {+ case "playing": {+ state = "paused"+ break+ }+ case "paused":+ case "played": {+ state = "playing"+ break}}-- return {- status,- message,- handleToggle,- handleSeeked,-- currentTime,- duration,- ariaLabel,+ }+ let event: AudioInteraction | undefined = undefined+ switch (state) {+ case "playing": {+ play()+ event = "play"+ break}- },-})+ case "paused": {+ pause()+ event = "pause"+ break+ }+ }+ if (event) {+ sendAudioInteractionEvent(event)+ }+}++/* Interface with VWaveform */++const handleSeeked = (frac: number) => {+ if (activeAudio.obj.value) {+ activeAudio.obj.value.currentTime = frac * duration.value+ sendAudioInteractionEvent("seek")+ }+}</script><template>diff --git a/frontend/src/components/VAudioTrack/VWaveform.vue b/frontend/src/components/VAudioTrack/VWaveform.vueindex 9cc4a9363..14841befc 100644--- a/frontend/src/components/VAudioTrack/VWaveform.vue+++ b/frontend/src/components/VAudioTrack/VWaveform.vue@@ -1,5 +1,9 @@-<script lang="ts">-import { computed, defineComponent, PropType, ref, toRef } from "vue"+<script setup lang="ts">+/**+ * Renders an SVG representation of the waveform given a list of heights for the+ * bars.+ */+import { computed, ref, toRef } from "vue"import { downsampleArray, upsampleArray } from "~/utils/resampling"import { timeFmt } from "~/utils/time-fmt"@@ -11,410 +15,333 @@ import useResizeObserver from "~/composables/use-resize-observer"import { hash, rand as prng } from "~/utils/prng"-import { defineEvent } from "~/types/emits"-/*** If the duration is above this threshold, the progress timestamp will show ms.*/const MAX_SECONDS_FOR_MS = 1-/**- * Renders an SVG representation of the waveform given a list of heights for the- * bars.- */-export default defineComponent({- name: "VWaveform",- props: {+const props = withDefaults(+ defineProps<{/**- * an array of heights of the bars; The waveform will be generated with+ * An array of heights of the bars. The waveform will be generated with* bars of random length if the prop is not provided.*/- peaks: {- type: Array as PropType<number[]>,- required: false,- validator: (val: unknown[]) =>- val.every((item) => typeof item === "number"),- },+ peaks?: number[]/**- * the message to display instead of the waveform; This is useful when+ * The message to display instead of the waveform. This is useful when* displaying a loading or error state.*/- message: {- type: String,- },+ message?: string/**- * the current play time of the audio track+ * The current play time of the audio track.*/- currentTime: {- type: Number,- default: 0,- },+ currentTime?: number/**- * the total play time of the audio track+ * The total play time of the audio track.*/- duration: {- type: Number as PropType<number>,- default: 0,- },+ duration?: number/**- * the fraction of the waveform height to use for the bars and timestamp;+ * The fraction of the waveform height to use for the bars and timestamp.* The remaining space can be used to place other elements.*/- usableFrac: {- type: Number,- default: 1,- },+ usableFrac?: number/**- * selectively enable features in the waveform; Available features are+ * Selectively enable features in the waveform. Available features are* `'timestamps'`, `'duration'`, `'seek'`.*/- features: {- type: Array as PropType<AudioFeature[]>,- default: () => ["timestamps", "seek"],- },+ features?: readonly AudioFeature[]/*** An object of notices to display when a feature is disabled.* `'timestamps'`, `'duration'`, `'seek'`.*/- featureNotices: {- type: Object as PropType<Record<AudioFeature, boolean>>,- default: () => ({}),- },+ featureNotices?: Partial<Record<AudioFeature, string>>/*** Audio id to make the randomly-created peaks deterministic.*/- audioId: {- type: String,- required: true,- },+ audioId: string/**- * whether the waveform can be focused by using the `Tab` key+ * Whether the waveform can be focused by using the `Tab` key*/- isTabbable: {- type: Boolean,- default: true,- },+ isTabbable?: boolean/**- * whether the waveform should render as seeking when it is controlled by+ * Whether the waveform should render as seeking when it is controlled by* the parent audio track*/- isParentSeeking: {- type: Boolean,- default: false,- },- },- emits: {- /**- * Emitted when the waveform receives mouse events for seeking,- * either single clicks on a specific part of the waveform,- * or a click and drag.- *- * Also emitted when the waveform receives arrow key or home/end- * keyboard events that also correspond to seeking.- */- seeked: defineEvent<[number]>(),- "toggle-playback": defineEvent<[]>(),- focus: defineEvent<[FocusEvent]>(),- blur: defineEvent<[FocusEvent]>(),- },- setup(props, { emit }) {- /* Utils */+ isParentSeeking?: boolean+ }>(),+ {+ currentTime: 0,+ duration: 0,+ usableFrac: 1,+ features: () => ["timestamps", "seek"] as AudioFeature[],+ featureNotices: () => ({}),+ isTabbable: true,+ isParentSeeking: false,+ }+)++const emit = defineEmits<{+ /**+ * Emitted when the waveform receives mouse events for seeking,+ * either single clicks on a specific part of the waveform,+ * or a click and drag.+ *+ * Also emitted when the waveform receives arrow key or home/end+ * keyboard events that also correspond to seeking.+ */+ seeked: [number]+ "toggle-playback": []+ focus: [FocusEvent]+ blur: [FocusEvent]+}>()++/* Utils */- /**- * Get the x-coordinate of the event with respect to the bounding box of the- * waveform.- * @param event - the event from which to get the position- * @returns the x-position of the event inside the waveform- */- const getPosition = (event: MouseEvent): number => {- return el.value- ? event.clientX - el.value.getBoundingClientRect().x- : event.clientX- }- /**- * Get the x-position of the event with respect to the bounding box of the- * waveform, as a fraction of the waveform width.- * @param event - the event from which to get the position- * @returns the x-position of the event as a fraction- */- const getPositionFrac = (event: MouseEvent): number => {- const xPos = getPosition(event)- return xPos / waveformDimens.value.width- }- /**- * Get the number of peaks that will fit within the given width.- * @param width - the number of pixels inside which to count peaks- * @returns the number of peaks that can be accommodated- */- const getPeaksInWidth = (width: number): number => {- return Math.floor((width - barGap) / (barWidth + barGap))- }-- /* Element dimensions */-- const el = ref<HTMLElement | null>(null) // template ref- const { dimens: waveformDimens } = useResizeObserver(el)+/**+ * Get the x-coordinate of the event with respect to the bounding box of the+ * waveform.+ * @param event - the event from which to get the position+ * @returns the x-position of the event inside the waveform+ */+const getPosition = (event: MouseEvent): number => {+ return el.value+ ? event.clientX - el.value.getBoundingClientRect().x+ : event.clientX+}+/**+ * Get the x-position of the event with respect to the bounding box of the+ * waveform, as a fraction of the waveform width.+ * @param event - the event from which to get the position+ * @returns the x-position of the event as a fraction+ */+const getPositionFrac = (event: MouseEvent): number => {+ const xPos = getPosition(event)+ return xPos / waveformDimens.value.width+}+/**+ * Get the number of peaks that will fit within the given width.+ * @param width - the number of pixels inside which to count peaks+ * @returns the number of peaks that can be accommodated+ */+const getPeaksInWidth = (width: number): number => {+ return Math.floor((width - barGap) / (barWidth + barGap))+}- /* Features */+/* Element dimensions */- const showDuration = computed(() => props.features.includes("duration"))- const showTimestamps = computed(() => props.features.includes("timestamps"))- const isSeekable = computed(() => props.features.includes("seek"))+const el = ref<HTMLElement | null>(null) // template ref+const { dimens: waveformDimens } = useResizeObserver(el)- /* State */+/* Features */- const isReady = computed(() => !props.message)- const isInteractive = computed(() => isSeekable.value && isReady.value)- const isSeeking = computed(- () => (!props.isTabbable && props.isParentSeeking) || isSelfSeeking.value- )+const showDuration = computed(() => props.features.includes("duration"))+const showTimestamps = computed(() => props.features.includes("timestamps"))+const isSeekable = computed(() => props.features.includes("seek"))- /* Resampling */+/* State */- const barWidth = 2- const barGap = 2- const peakCount = computed(() =>- getPeaksInWidth(waveformDimens.value.width)- )+const isReady = computed(() => !props.message)+const isInteractive = computed(() => isSeekable.value && isReady.value)+const isSeeking = computed(+ () => (!props.isTabbable && props.isParentSeeking) || isSelfSeeking.value+)- const createRandomPeaks = (audioId: string) => {- const rand = prng(hash(audioId))- return Array.from({ length: 100 }, () => rand())- }- const peaks = computed(() =>- props.peaks?.length ? props.peaks : createRandomPeaks(props.audioId)- )- const normalizedPeaks = computed(() => {- let samples = peaks.value-- const givenLength = samples.length- const required = peakCount.value- if (givenLength < required) {- samples = upsampleArray(samples, required)- } else if (givenLength > required) {- samples = downsampleArray(samples, required)- }-- return samples.map(- (peak) => Math.max(peak, 0) * waveformDimens.value.height- )- })-- /* SVG drawing */-- const viewBox = computed(() =>- [0, 0, waveformDimens.value.width, waveformDimens.value.height].join(" ")- )- const spaceBefore = (index: number) => index * barWidth + index * barGap- const spaceAbove = (index: number) =>- waveformDimens.value.height - normalizedPeaks.value[index]-- /* Progress bar */- const progressBarWidth = computed(() => {- const frac = isDragging.value ? (seekFrac.value ?? 0) : currentFrac.value- return waveformDimens.value.width * frac- })-- /* Progress timestamp */-- const progressTimestampEl = ref<HTMLElement>()- const progressTimestamp = computed(() =>- isDragging.value ? seekTimestamp.value : props.currentTime- )- const isProgressTimestampCutoff = computed(() => {- if (!progressTimestampEl.value) {- return false- }- const barWidth = progressBarWidth.value- const timestampWidth = progressTimestampEl.value.offsetWidth- return barWidth < timestampWidth + 2- })+/* Resampling */- /**- * Whether to show the ms part in the timestamps. True when the duration- * is below MAX_SECONDS_FOR_MS seconds.- */- const showMsInTimestamp = computed(- () =>- Number.isFinite(props.duration) && props.duration < MAX_SECONDS_FOR_MS- )-- /* Seek bar */-- const seekFrac = ref<number | null>(null)- const seekBarWidth = computed(() => {- const frac = seekFrac.value ?? currentFrac.value- return waveformDimens.value.width * frac- })- const seekIndex = computed(() => getPeaksInWidth(seekBarWidth.value))-- /* Seek timestamp */-- const seekTimestampEl = ref<HTMLElement | null>(null)- const seekTimestamp = computed(() =>- seekFrac.value ? seekFrac.value * props.duration : props.duration- )- const isSeekTimestampCutoff = computed(() => {- if (!seekTimestampEl.value) {- return false- }- const barWidth = seekBarWidth.value- const timestampWidth = seekTimestampEl.value.offsetWidth- return barWidth < timestampWidth + 2- })-- const { isSeeking: isSelfSeeking, ...seekable } = useSeekable({- duration: toRef(props, "duration"),- currentTime: toRef(props, "currentTime"),- isSeekable,- isReady,- onSeek: (frac) => {- clearSeekProgress()- emit("seeked", frac)- },- onTogglePlayback: () => emit("toggle-playback"),- })- const waveformAttributes = computed(() => ({- // ARIA slider attributes are only added when interactive- ...(isInteractive.value ? seekable.attributes.value : {}),- }))-- /* Seeking */+const barWidth = 2+const barGap = 2+const peakCount = computed(() => getPeaksInWidth(waveformDimens.value.width))- /**- * the seek jump length as a % of the track- */- const { currentFrac } = seekable.meta- const setSeekProgress = (event: MouseEvent) => {- seekFrac.value = getPositionFrac(event)- }- const clearSeekProgress = () => {- seekFrac.value = null- }- const seek = (event: MouseEvent) => {- emit("seeked", getPositionFrac(event))- }+const createRandomPeaks = (audioId: string) => {+ const rand = prng(hash(audioId))+ return Array.from({ length: 100 }, () => rand())+}+const peaks = computed(() =>+ props.peaks?.length ? props.peaks : createRandomPeaks(props.audioId)+)+const normalizedPeaks = computed(() => {+ let samples = peaks.value++ const givenLength = samples.length+ const required = peakCount.value+ if (givenLength < required) {+ samples = upsampleArray(samples, required)+ } else if (givenLength > required) {+ samples = downsampleArray(samples, required)+ }++ return samples.map((peak) => Math.max(peak, 0) * waveformDimens.value.height)+})- /* Dragging */-- const dragThreshold = 2 // px- let startPos: null | number = null- const isDragging = ref(false)- const handleMouseDown = (event: MouseEvent) => {- if (!props.isTabbable) {- // to prevent focus- event.preventDefault()- }- isDragging.value = false- startPos = getPosition(event)- setSeekProgress(event)- }- const handleMouseMove = (event: MouseEvent) => {- if (startPos) {- const clickPos = getPosition(event)- if (Math.abs(clickPos - startPos) > dragThreshold) {- isDragging.value = true- }- }- setSeekProgress(event)- }- const handleMouseUp = (event: MouseEvent) => {- isDragging.value = false- startPos = null- seek(event)- }- const handleMouseLeave = () => {- clearSeekProgress()- }- const handleClick = (event: MouseEvent) => {- // Prevent event from bubbling to the parent anchor tag.- event.stopPropagation()- event.preventDefault()- }- const handleFocus = (event: FocusEvent) => {- emit("focus", event)- }- const handleBlur = (event: FocusEvent) => {- seekable.listeners.blur()- emit("blur", event)- }+/* SVG drawing */- /* v-on */-- const eventHandlers = computed(() => {- if (isInteractive.value) {- return {- mousedown: handleMouseDown,- mousemove: handleMouseMove,- mouseup: handleMouseUp,- mouseleave: handleMouseLeave,- click: handleClick,- blur: handleBlur,- focus: handleFocus,- keydown: seekable.listeners.keydown,- }- } else {- return {}- }- })-- const heightProperties = computed(() => ({- "--usable-height": `${Math.floor(props.usableFrac * 100)}%`,- "--unusable-height": `${Math.floor((1 - props.usableFrac) * 100)}%`,- }))-- const progressTimeLeft = computed(() => ({- "--progress-time-left": `${progressBarWidth.value}px`,- }))-- const seekTimeLeft = computed(() => ({- "--seek-time-left": `${seekBarWidth.value}px`,- }))+const viewBox = computed(() =>+ [0, 0, waveformDimens.value.width, waveformDimens.value.height].join(" ")+)+const spaceBefore = (index: number) => index * barWidth + index * barGap+const spaceAbove = (index: number) =>+ waveformDimens.value.height - normalizedPeaks.value[index]- return {- timeFmt,+/* Progress bar */+const progressBarWidth = computed(() => {+ const frac = isDragging.value ? (seekFrac.value ?? 0) : currentFrac.value+ return waveformDimens.value.width * frac+})- el, // template ref+/* Progress timestamp */++const progressTimestampEl = ref<HTMLElement>()+const progressTimestamp = computed(() =>+ isDragging.value ? seekTimestamp.value : props.currentTime+)+const isProgressTimestampCutoff = computed(() => {+ if (!progressTimestampEl.value) {+ return false+ }+ const barWidth = progressBarWidth.value+ const timestampWidth = progressTimestampEl.value.offsetWidth+ return barWidth < timestampWidth + 2+})- showDuration,- showTimestamps,- isSeekable,+/**+ * Whether to show the ms part in the timestamps. True when the duration+ * is below MAX_SECONDS_FOR_MS seconds.+ */+const showMsInTimestamp = computed(+ () => Number.isFinite(props.duration) && props.duration < MAX_SECONDS_FOR_MS+)- isReady,- isInteractive,- isSeeking,+/* Seek bar */- barWidth,- normalizedPeaks,+const seekFrac = ref<number | null>(null)+const seekBarWidth = computed(() => {+ const frac = seekFrac.value ?? currentFrac.value+ return waveformDimens.value.width * frac+})+const seekIndex = computed(() => getPeaksInWidth(seekBarWidth.value))++/* Seek timestamp */++const seekTimestampEl = ref<HTMLElement | null>(null)+const seekTimestamp = computed(() =>+ seekFrac.value ? seekFrac.value * props.duration : props.duration+)+const isSeekTimestampCutoff = computed(() => {+ if (!seekTimestampEl.value) {+ return false+ }+ const barWidth = seekBarWidth.value+ const timestampWidth = seekTimestampEl.value.offsetWidth+ return barWidth < timestampWidth + 2+})- waveformDimens,- viewBox,- spaceBefore,- spaceAbove,+const { isSeeking: isSelfSeeking, ...seekable } = useSeekable({+ duration: toRef(props, "duration"),+ currentTime: toRef(props, "currentTime"),+ isSeekable,+ isReady,+ onSeek: (frac) => {+ clearSeekProgress()+ emit("seeked", frac)+ },+ onTogglePlayback: () => emit("toggle-playback"),+})+const waveformAttributes = computed(() => ({+ // ARIA slider attributes are only added when interactive+ ...(isInteractive.value ? seekable.attributes.value : {}),+}))- progressBarWidth,- progressTimestamp,- progressTimestampEl,- isProgressTimestampCutoff,- showMsInTimestamp,+/* Seeking */- seekFrac,- seekBarWidth,- seekIndex,+/**+ * the seek jump length as a % of the track+ */+const { currentFrac } = seekable.meta+const setSeekProgress = (event: MouseEvent) => {+ seekFrac.value = getPositionFrac(event)+}+const clearSeekProgress = () => {+ seekFrac.value = null+}+const seek = (event: MouseEvent) => {+ emit("seeked", getPositionFrac(event))+}- seekTimestamp,- seekTimestampEl,- isSeekTimestampCutoff,- waveformAttributes,+/* Dragging */++const dragThreshold = 2 // px+let startPos: null | number = null+const isDragging = ref(false)+const handleMouseDown = (event: MouseEvent) => {+ if (!props.isTabbable) {+ // to prevent focus+ event.preventDefault()+ }+ isDragging.value = false+ startPos = getPosition(event)+ setSeekProgress(event)+}+const handleMouseMove = (event: MouseEvent) => {+ if (startPos) {+ const clickPos = getPosition(event)+ if (Math.abs(clickPos - startPos) > dragThreshold) {+ isDragging.value = true+ }+ }+ setSeekProgress(event)+}+const handleMouseUp = (event: MouseEvent) => {+ isDragging.value = false+ startPos = null+ seek(event)+}+const handleMouseLeave = () => {+ clearSeekProgress()+}+const handleClick = (event: MouseEvent) => {+ // Prevent event from bubbling to the parent anchor tag.+ event.stopPropagation()+ event.preventDefault()+}+const handleFocus = (event: FocusEvent) => {+ emit("focus", event)+}+const handleBlur = (event: FocusEvent) => {+ seekable.listeners.blur()+ emit("blur", event)+}- eventHandlers,+/* v-on */- heightProperties,- progressTimeLeft,- seekTimeLeft,+const eventHandlers = computed(() => {+ if (isInteractive.value) {+ return {+ mousedown: handleMouseDown,+ mousemove: handleMouseMove,+ mouseup: handleMouseUp,+ mouseleave: handleMouseLeave,+ click: handleClick,+ blur: handleBlur,+ focus: handleFocus,+ keydown: seekable.listeners.keydown,}- },+ } else {+ return {}+ }})++const heightProperties = computed(() => ({+ "--usable-height": `${Math.floor(props.usableFrac * 100)}%`,+ "--unusable-height": `${Math.floor((1 - props.usableFrac) * 100)}%`,+}))++const progressTimeLeft = computed(() => ({+ "--progress-time-left": `${progressBarWidth.value}px`,+}))++const seekTimeLeft = computed(() => ({+ "--seek-time-left": `${seekBarWidth.value}px`,+}))</script><template>@@ -533,7 +460,7 @@ export default defineComponent({]":style="progressTimeLeft">- {{ timeFmt(progressTimestamp) }}+ {{ timeFmt(progressTimestamp, showMsInTimestamp) }}</div><divv-if="seekFrac"@@ -542,14 +469,14 @@ export default defineComponent({:class="{ '-translate-x-full': !isSeekTimestampCutoff }":style="seekTimeLeft">- {{ timeFmt(seekTimestamp) }}+ {{ timeFmt(seekTimestamp, showMsInTimestamp) }}</div></template><divv-if="showDuration"class="duration timestamp bg-background-var right-0">- {{ timeFmt(duration) }}+ {{ timeFmt(duration, showMsInTimestamp) }}</div></template>diff --git a/frontend/src/components/VAudioTrack/layouts/VBoxLayout.vue b/frontend/src/components/VAudioTrack/layouts/VBoxLayout.vueindex 23b949409..1d867fa81 100644--- a/frontend/src/components/VAudioTrack/layouts/VBoxLayout.vue+++ b/frontend/src/components/VAudioTrack/layouts/VBoxLayout.vue@@ -1,7 +1,7 @@-<script lang="ts">+<script setup lang="ts">import { useI18n } from "#imports"-import { computed, defineComponent, type PropType } from "vue"+import { computed } from "vue"import type { AudioDetail } from "~/types/media"import type { AudioSize } from "~/constants/audio"@@ -9,39 +9,20 @@ import { useSensitiveMedia } from "~/composables/use-sensitive-media"import VLicense from "~/components/VLicense/VLicense.vue"-export default defineComponent({- name: "VBoxLayout",- components: {- VLicense,- },- props: {- audio: {- type: Object as PropType<AudioDetail>,- required: true,- },- size: {- type: String as PropType<Extract<AudioSize, "s" | "l">>,- required: true,- },- },- setup(props) {- const { t } = useI18n({ useScope: "global" })+const props = defineProps<{+ audio: AudioDetail+ size: Extract<AudioSize, "s" | "l">+}>()- const isSmall = computed(() => props.size === "s")+const { t } = useI18n({ useScope: "global" })- const categoryLabel = computed(() =>- t(`filters.audioCategories.${props.audio.category}`)- )+const isSmall = computed(() => props.size === "s")- const { isHidden: shouldBlur } = useSensitiveMedia(props.audio)- return {- isSmall,- shouldBlur,+const categoryLabel = computed(() =>+ t(`filters.audioCategories.${props.audio.category}`)+)- categoryLabel,- }- },-})+const { isHidden: shouldBlur } = useSensitiveMedia(props.audio)</script><template>@@ -72,9 +53,9 @@ export default defineComponent({<div class="flex-none p-2"><slotname="audio-control"- size="small"- layout="box"- :is-tabbable="false"+ v-bind="+ { size: 'small', layout: 'box', isTabbable: false } as const+ "/></div><p v-if="audio.category && isSmall" class="label-regular self-center">diff --git a/frontend/src/components/VAudioTrack/layouts/VFullLayout.vue b/frontend/src/components/VAudioTrack/layouts/VFullLayout.vueindex 9cdee10c0..603775b39 100644--- a/frontend/src/components/VAudioTrack/layouts/VFullLayout.vue+++ b/frontend/src/components/VAudioTrack/layouts/VFullLayout.vue@@ -1,37 +1,16 @@-<script lang="ts">-import { defineComponent, PropType } from "vue"-+<script setup lang="ts">import type { AudioDetail } from "~/types/media"import { audioFeatures, AudioSize, AudioStatus } from "~/constants/audio"import VGetMediaButton from "~/components/VMediaInfo/VGetMediaButton.vue"import VMediaInfo from "~/components/VMediaInfo/VMediaInfo.vue"-export default defineComponent({- name: "VFullLayout",- components: { VMediaInfo, VGetMediaButton },- props: {- audio: {- type: Object as PropType<AudioDetail>,- required: true,- },- size: {- type: String as PropType<AudioSize>,- },- status: {- type: String as PropType<AudioStatus>,- },- currentTime: {- type: Number,- required: true,- },- },- setup() {- return {- audioFeatures,- }- },-})+defineProps<{+ audio: AudioDetail+ size?: AudioSize+ status?: AudioStatus+ currentTime: number+}>()</script><template>@@ -57,7 +36,10 @@ export default defineComponent({<divclass="row-start-1 flex justify-between gap-x-6 sm:col-start-2 sm:mt-1">- <slot name="audio-control" layout="full" size="medium" />+ <slot+ name="audio-control"+ v-bind="{ layout: 'full', size: 'medium' } as const"+ /><VGetMediaButton:media="audio"media-type="audio"diff --git a/frontend/src/components/VAudioTrack/layouts/VGlobalLayout.vue b/frontend/src/components/VAudioTrack/layouts/VGlobalLayout.vueindex 6ae774412..c72abc9bc 100644--- a/frontend/src/components/VAudioTrack/layouts/VGlobalLayout.vue+++ b/frontend/src/components/VAudioTrack/layouts/VGlobalLayout.vue@@ -1,5 +1,5 @@-<script lang="ts">-import { toRefs, defineComponent, PropType } from "vue"+<script setup lang="ts">+import { toRefs } from "vue"import type { AudioDetail } from "~/types/media"@@ -8,27 +8,11 @@ import { useSensitiveMedia } from "~/composables/use-sensitive-media"import VAudioThumbnail from "~/components/VAudioThumbnail/VAudioThumbnail.vue"import VLink from "~/components/VLink.vue"-export default defineComponent({- name: "VGlobalLayout",- components: {- VAudioThumbnail,- VLink,- },- props: {- audio: {- type: Object as PropType<AudioDetail>,- required: true,- },- },- setup(props) {- const { audio } = toRefs(props)- const { isHidden: shouldBlur } = useSensitiveMedia(audio)-- return {- shouldBlur,- }- },-})+const props = defineProps<{+ audio: AudioDetail+}>()+const { audio } = toRefs(props)+const { isHidden: shouldBlur } = useSensitiveMedia(audio)</script><template>diff --git a/frontend/src/components/VAudioTrack/layouts/VRowLayout.vue b/frontend/src/components/VAudioTrack/layouts/VRowLayout.vueindex 44ebd2dc5..7f837b913 100644--- a/frontend/src/components/VAudioTrack/layouts/VRowLayout.vue+++ b/frontend/src/components/VAudioTrack/layouts/VRowLayout.vue@@ -1,9 +1,9 @@-<script lang="ts">-import { computed, defineComponent, PropType } from "vue"+<script setup lang="ts">+import { computed } from "vue"import { timeFmt } from "~/utils/time-fmt"import type { AudioDetail } from "~/types/media"-import { audioFeatures, AudioSize } from "~/constants/audio"+import { audioFeatures, type AudioSize } from "~/constants/audio"import { useSensitiveMedia } from "~/composables/use-sensitive-media"@@ -12,53 +12,25 @@ import { useUiStore } from "~/stores/ui"import VAudioThumbnail from "~/components/VAudioThumbnail/VAudioThumbnail.vue"import VLicense from "~/components/VLicense/VLicense.vue"-export default defineComponent({- name: "VRowLayout",- components: {- VAudioThumbnail,- VLicense,- },- props: {- audio: {- type: Object as PropType<AudioDetail>,- required: true,- },- size: {- type: String as PropType<AudioSize>,- required: false,- },- },- setup(props) {- const featureNotices: {- timestamps?: string- duration?: string- seek?: string- } = {}-- const isSmall = computed(() => props.size === "s")- const isMedium = computed(() => props.size === "m")- const isLarge = computed(() => props.size === "l")-- const { isHidden: shouldBlur } = useSensitiveMedia(props.audio)-- const uiStore = useUiStore()- const isMd = computed(() => uiStore.isBreakpoint("md"))-- return {- timeFmt,-- audioFeatures,- featureNotices,-- isSmall,- isMedium,- isLarge,- isMd,-- shouldBlur,- }- },-})+const props = defineProps<{+ audio: AudioDetail+ size?: AudioSize+}>()++const featureNotices: {+ timestamps?: string+ duration?: string+ seek?: string+} = {}++const isSmall = computed(() => props.size === "s")+const isMedium = computed(() => props.size === "m")+const isLarge = computed(() => props.size === "l")++const { isHidden: shouldBlur } = useSensitiveMedia(props.audio)++const uiStore = useUiStore()+const isMd = computed(() => uiStore.isBreakpoint("md"))</script><template>@@ -78,9 +50,7 @@ export default defineComponent({><slotname="audio-control"- size="small"- layout="row"- :is-tabbable="false"+ v-bind="{ size: 'small', layout: 'row', isTabbable: false } as const"/></div></div>@@ -145,9 +115,13 @@ export default defineComponent({><slotname="audio-control"- :size="isLarge ? 'large' : 'medium'"- layout="row"- :is-tabbable="false"+ v-bind="+ {+ size: isLarge ? 'large' : 'medium',+ layout: 'row',+ isTabbable: false,+ } as const+ "/><slotname="controller"diff --git a/frontend/src/components/VIcon/VIcon.vue b/frontend/src/components/VIcon/VIcon.vueindex a56324743..061801e97 100644--- a/frontend/src/components/VIcon/VIcon.vue+++ b/frontend/src/components/VIcon/VIcon.vue@@ -1,4 +1,4 @@-<script lang="ts" setup>+<script setup lang="ts">import { ref, watch } from "vue"import { useSprite } from "~/composables/use-sprite"