Open source personal finance application
feat(navigation): smart back via Navigation API
Ilya Komichev22bbd04c2022
diff --git a/app/components/categories/Header.vue b/app/components/categories/Header.vueindex 26f9426c..01bc7a54 100644--- a/app/components/categories/Header.vue+++ b/app/components/categories/Header.vue@@ -1,10 +1,20 @@<script setup lang="ts">import type { CategoryItem } from '~/components/categories/types'+import { navigateToAncestor } from '~/composables/useNavigationHistory'+const props = defineProps<{category: CategoryItemparentCategory?: CategoryItem}>()++const router = useRouter()++function onParentClick(event: Event) {+ // preventDefault stops the vue-router NuxtLink guard via its defaultPrevented check.+ event.preventDefault()+ navigateToAncestor(router, `/categories/${props.category.parentId}`)+}</script><template>@@ -14,6 +24,7 @@ const props = defineProps<{<NuxtLink:to="`/categories/${props.category.parentId}`"class="text-muted truncate text-lg font-medium no-underline hover:text-(--ui-text-highlighted) @lg:text-xl"+ @click="onParentClick">{{ props.parentCategory.name }}</NuxtLink>diff --git a/app/components/categories/page/id/Edit.vue b/app/components/categories/page/id/Edit.vueindex c7ce0521..a48e16a9 100644--- a/app/components/categories/page/id/Edit.vue+++ b/app/components/categories/page/id/Edit.vue@@ -3,6 +3,7 @@ import type { CategoryId, CategoryItem } from '~/components/categories/types'import { categoryFormSchema } from '~/components/categories/types'import { useCategoriesStore } from '~/components/categories/useCategoriesStore'+import { navigateAfterSave } from '~/composables/useNavigationHistory'const { t } = useI18n()const router = useRouter()@@ -31,7 +32,7 @@ useHead({:categoryId="categoryId":categoryForm="categoryForm"@update="(key: string, value: CategoryItem[keyof CategoryItem]) => (categoryForm as Record<string, any>)[key] = value"- @afterSave="() => router.replace(`/categories/${categoryId}`)"+ @afterSave="() => navigateAfterSave(router, `/categories/${categoryId}`)"/></UiPage></template>diff --git a/app/components/ui/Header.vue b/app/components/ui/Header.vueindex 91fde9cf..2150a22a 100644--- a/app/components/ui/Header.vue+++ b/app/components/ui/Header.vue@@ -1,24 +1,35 @@<script setup lang="ts">import { useSearch } from '~/components/search/useSearch'+import { canGoBack } from '~/composables/useNavigationHistory'const { backTo } = defineProps<{backTo?: string}>()const { isSearchOpen } = useSearch()+const router = useRouter()++function onBack() {+ if (canGoBack.value)+ router.back()+ else if (backTo)+ router.replace(backTo)+}</script><template><div class="bg-default/90 sticky top-0 z-20 mb-2 backdrop-blur"><div class="border-item-4 grid min-h-12 max-w-7xl items-center border-b px-2 py-2 lg:px-4 lg:py-4"><div class="flex grow items-center">- <NuxtLink+ <buttonv-if="backTo"- :to="backTo"+ type="button"+ :aria-label="$t('base.previous')"class="interactive text-muted flex min-h-[42px] min-w-[42px] shrink-0 cursor-default items-center justify-center rounded-sm text-xl"+ @click="onBack"><Icon name="lucide:arrow-left" size="20" />- </NuxtLink>+ </button><div class="min-w-0 overflow-x-auto"><slot />diff --git a/app/components/wallets/page/id/Edit.vue b/app/components/wallets/page/id/Edit.vueindex a47baaf7..48275ca7 100644--- a/app/components/wallets/page/id/Edit.vue+++ b/app/components/wallets/page/id/Edit.vue@@ -3,6 +3,7 @@ import type { WalletId, WalletItem } from '~/components/wallets/types'import { walletItemSchema } from '~/components/wallets/types'import { useWalletsStore } from '~/components/wallets/useWalletsStore'+import { navigateAfterSave } from '~/composables/useNavigationHistory'const { t } = useI18n()const route = useRoute()@@ -41,7 +42,7 @@ useHead({ title: `${t('base.edit')}: ${walletForm.value?.name || t('wallets.form<WalletsForm:walletId:walletForm- @afterSave="() => router.replace(`/wallets/${walletId}`)"+ @afterSave="() => navigateAfterSave(router, `/wallets/${walletId}`)"@update="updateField"/></UiPage>diff --git a/app/composables/useNavigationHistory.test.ts b/app/composables/useNavigationHistory.test.tsnew file mode 100644index 00000000..602bd534--- /dev/null+++ b/app/composables/useNavigationHistory.test.ts@@ -0,0 +1,125 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++type Entry = { index: number, key: string, url: string }++function createNavigation(entries: Entry[], currentIndex: number) {+ const listeners = new Map<string, Array<() => void>>()+ return {+ _emit(type: string) {+ listeners.get(type)?.forEach(fn => fn())+ },+ addEventListener: (type: string, fn: () => void) => {+ const arr = listeners.get(type) ?? []+ arr.push(fn)+ listeners.set(type, arr)+ },+ back: vi.fn(),+ get canGoBack() { return currentIndex > 0 },+ get currentEntry() { return entries[currentIndex] ?? null },+ entries: () => entries,+ traverseTo: vi.fn(),+ }+}++function stubNavigation(entries: Entry[], currentIndex: number, extra?: Record<string, unknown>) {+ vi.stubGlobal('window', {+ location: { origin: 'http://localhost' },+ navigation: { ...createNavigation(entries, currentIndex), ...extra },+ })+ vi.resetModules()+}++function stubNoNavigation() {+ vi.stubGlobal('window', { location: { origin: 'http://localhost' } })+ vi.resetModules()+}++const defaultEntries: Entry[] = [+ { index: 0, key: 'k0', url: 'http://localhost/categories' },+ { index: 1, key: 'k1', url: 'http://localhost/categories/abc' },+ { index: 2, key: 'k2', url: 'http://localhost/categories/abc/edit' },+]++describe('useNavigationHistory', () => {+ beforeEach(() => {+ stubNavigation(defaultEntries, 2)+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ })++ it('canGoBack reflects navigation.canGoBack on import', async () => {+ const { canGoBack } = await import('~/composables/useNavigationHistory')+ expect(canGoBack.value).toBe(true)+ })++ it('canGoBack is false at the first entry', async () => {+ stubNavigation([{ index: 0, key: 'k0', url: 'http://localhost/x' }], 0)+ const { canGoBack } = await import('~/composables/useNavigationHistory')+ expect(canGoBack.value).toBe(false)+ })++ it('navigateAfterSave calls router.back when previous entry equals target', async () => {+ const { navigateAfterSave } = await import('~/composables/useNavigationHistory')+ const router = { back: vi.fn(), replace: vi.fn() }+ navigateAfterSave(router, '/categories/abc')+ expect(router.back).toHaveBeenCalledOnce()+ expect(router.replace).not.toHaveBeenCalled()+ })++ it('navigateAfterSave calls router.replace when previous entry differs', async () => {+ const { navigateAfterSave } = await import('~/composables/useNavigationHistory')+ const router = { back: vi.fn(), replace: vi.fn() }+ navigateAfterSave(router, '/somewhere/else')+ expect(router.replace).toHaveBeenCalledWith('/somewhere/else')+ expect(router.back).not.toHaveBeenCalled()+ })++ it('navigateAfterSave calls router.replace at the first entry (no prev)', async () => {+ stubNavigation([{ index: 0, key: 'k0', url: 'http://localhost/edit' }], 0)+ const { navigateAfterSave } = await import('~/composables/useNavigationHistory')+ const router = { back: vi.fn(), replace: vi.fn() }+ navigateAfterSave(router, '/detail')+ expect(router.replace).toHaveBeenCalledWith('/detail')+ })++ it('navigateToAncestor traverses to an existing earlier entry', async () => {+ const traverseTo = vi.fn()+ stubNavigation([+ { index: 0, key: 'k0', url: 'http://localhost/categories' },+ { index: 1, key: 'k1', url: 'http://localhost/categories/parent' },+ { index: 2, key: 'k2', url: 'http://localhost/categories/child' },+ ], 2, { traverseTo })+ const { navigateToAncestor } = await import('~/composables/useNavigationHistory')+ const router = { back: vi.fn(), push: vi.fn(), replace: vi.fn() }+ navigateToAncestor(router, '/categories/parent')+ expect(traverseTo).toHaveBeenCalledWith('k1')+ expect(router.push).not.toHaveBeenCalled()+ })++ it('navigateToAncestor pushes when target is not in history', async () => {+ const { navigateToAncestor } = await import('~/composables/useNavigationHistory')+ const router = { back: vi.fn(), push: vi.fn(), replace: vi.fn() }+ navigateToAncestor(router, '/categories/never-visited')+ expect(router.push).toHaveBeenCalledWith('/categories/never-visited')+ })++ it('navigateToAncestor pushes when Navigation API unavailable', async () => {+ stubNoNavigation()+ const { navigateToAncestor } = await import('~/composables/useNavigationHistory')+ const router = { back: vi.fn(), push: vi.fn(), replace: vi.fn() }+ navigateToAncestor(router, '/x')+ expect(router.push).toHaveBeenCalledWith('/x')+ })++ it('canGoBack stays false in environments without Navigation API', async () => {+ stubNoNavigation()+ const { canGoBack, navigateAfterSave } = await import('~/composables/useNavigationHistory')+ expect(canGoBack.value).toBe(false)+ const router = { back: vi.fn(), replace: vi.fn() }+ navigateAfterSave(router, '/anywhere')+ expect(router.replace).toHaveBeenCalledWith('/anywhere')+ expect(router.back).not.toHaveBeenCalled()+ })+})diff --git a/app/composables/useNavigationHistory.ts b/app/composables/useNavigationHistory.tsnew file mode 100644index 00000000..c164e100--- /dev/null+++ b/app/composables/useNavigationHistory.ts@@ -0,0 +1,64 @@+import { readonly, ref } from 'vue'++type NavigationApiEntry = { index: number, key: string, url: string }+type NavigationApi = {+ addEventListener: (type: string, fn: () => void) => void+ back: () => unknown+ canGoBack: boolean+ currentEntry: NavigationApiEntry | null+ entries: () => NavigationApiEntry[]+ traverseTo: (key: string) => unknown+}++type RouterLike = {+ back: () => unknown+ push: (to: string) => unknown+ replace: (to: string) => unknown+}++const navigation: NavigationApi | null = typeof window === 'undefined'+ ? null+ : ((window as unknown as { navigation?: NavigationApi }).navigation ?? null)++function getEntryPathname(entry: NavigationApiEntry): string {+ return new URL(entry.url, window.location.origin).pathname+}++const _canGoBack = ref(false)++if (navigation) {+ const sync = () => { _canGoBack.value = navigation.canGoBack }+ sync()+ navigation.addEventListener('currententrychange', sync)+}++export const canGoBack = readonly(_canGoBack)++function previousEntryUrl(): string | null {+ const idx = navigation?.currentEntry?.index ?? 0+ const prev = navigation?.entries()[idx - 1]+ return prev ? getEntryPathname(prev) : null+}++/** Use back() if target is the previous entry to avoid duplicating it on top. */+export function navigateAfterSave(router: RouterLike, target: string) {+ if (previousEntryUrl() === target)+ router.back()+ else+ router.replace(target)+}++/** Traverse to target if already in history; push otherwise — avoids cycles. */+export function navigateToAncestor(router: RouterLike, target: string) {+ if (navigation?.currentEntry) {+ const entries = navigation.entries()+ for (let i = navigation.currentEntry.index - 1; i >= 0; i--) {+ const entry = entries[i]+ if (entry && getEntryPathname(entry) === target) {+ navigation.traverseTo(entry.key)+ return+ }+ }+ }+ router.push(target)+}