Files
FabledCurator/frontend/src/composables/useTabQuery.js
T
bvandeusen 1322056b22 refactor(dry-F5): useTabQuery composable for ?tab= query-param routing
ArtistView and SubscriptionsView both two-way-bound a tab ref with the
?tab= query param via identical tab->URL and URL->tab watchers. Extracted
useTabQuery(validTabs, defaultTab) — defaultTab accepts a string or a
function (ArtistView's default is postCount-dependent), and resolve() is
exposed so ArtistView can re-apply it after the artist loads. Both views
drop their now-orphaned ref/useRouter imports.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 15:20:30 -04:00

31 lines
1.1 KiB
JavaScript

import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
// Two-way bind a tab ref with the ?tab= query param: the initial value comes
// from the URL (when it names a valid tab) else `defaultTab` — a string, or a
// function for a state-dependent default. Tab changes push to the URL via
// router.replace (no history spam); URL changes (back/forward) flow back into
// the ref. Returns { tab, resolve } where resolve() re-applies the URL-or-
// default rule (callers re-run it when their default inputs change).
export function useTabQuery(validTabs, defaultTab) {
const route = useRoute()
const router = useRouter()
const resolveDefault = () =>
(typeof defaultTab === 'function' ? defaultTab() : defaultTab)
const resolve = () =>
(validTabs.includes(route.query.tab) ? route.query.tab : resolveDefault())
const tab = ref(resolve())
watch(tab, (t) => {
if (route.query.tab === t) return
router.replace({ query: { ...route.query, tab: t } })
})
watch(() => route.query.tab, (q) => {
if (q && validTabs.includes(q) && tab.value !== q) tab.value = q
})
return { tab, resolve }
}