/* * Copyright (c) 2026. * Author Peter Placzek (tada5hi) * For the full copyright and license information, * view the LICENSE file that was distributed with this source code. */ import type { FilterStore } from '@vuecs/filters'; import { createMemoryFilterStore, useFilterState } from '@vuecs/filters'; import type { TableSortState } from '@vuecs/table'; import { useTableSort } from '@vuecs/table'; import type { App, InjectionKey } from 'vue'; import { computed, hasInjectionContext, inject, provide, } from 'vue'; import { PATH_SCOPE_QUERY_KEY, usePathScope } from '../path-scope/index.ts'; import type { EntityDataView, EntityDataViewOptions } from './types.ts'; const DATA_VIEW_STORE_KEY : InjectionKey = Symbol.for('AuthupDataViewStore'); /** * Where the data views below (or of the whole app) keep their filters, sort * and folder. The admin console provides the route query, so a view can be * shared as a link; a host that owns its URL provides nothing, and every * view keeps its state in memory. */ export function provideDataViewStore(store: FilterStore, app?: App) : void { if (app) { app.provide(DATA_VIEW_STORE_KEY, store); return; } provide(DATA_VIEW_STORE_KEY, store); } export function injectDataViewStore() : FilterStore { const store = hasInjectionContext() ? inject(DATA_VIEW_STORE_KEY, undefined) : undefined; return store ?? createMemoryFilterStore(); } export function toQuerySorts(state: TableSortState) : Record { const output : Record = {}; for (const descriptor of state) { output[descriptor.key] = descriptor.direction === 'desc' ? 'DESC' : 'ASC'; } return output; } /** * The state of one entity data view: its filters, its table sort and, * optionally, its folder scope, all kept in one store so that no write * drops another's keys. */ export function useEntityDataView( options: EntityDataViewOptions, store: FilterStore = injectDataViewStore(), ) : EntityDataView { const pathScope = options.pathScope ? usePathScope({ ...options.pathScope, store }) : undefined; // The folder is written by the scope; naming it here lets reset clear it // too and count it as an active filter. const filter = useFilterState(store, options.filters, { extra: pathScope ? [PATH_SCOPE_QUERY_KEY] : [] }); const { state } = useTableSort(store, { allowed: options.sort.allowed, fallback: options.sort.fallback ?? [], multiple: options.sort.multiple, }); return { store, filter, sort: state, sorts: computed(() => toQuerySorts(state.value)), multiSort: !!options.sort.multiple, pathScope, pending: computed(() => !!pathScope && pathScope.pending.value), }; }