@anzusystems/common-admin 2.0.0-rc.30 → 2.0.0-rc.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/domains/anzuUser/components/AAnzuUserDatatable.vue.d.ts +4 -2
  2. package/dist/domains/anzuUser/components/AAnzuUserDatatable.vue.js +4 -4
  3. package/dist/domains/anzuUser/components/AAnzuUserDatatable.vue.js.map +1 -1
  4. package/dist/domains/anzuUser/components/AAnzuUserForm.vue.d.ts +3 -2
  5. package/dist/domains/anzuUser/components/AAnzuUserForm.vue.js +1 -1
  6. package/dist/domains/anzuUser/components/AAnzuUserForm.vue.js.map +1 -1
  7. package/dist/domains/anzuUser/components/AUserMetadataForm.vue.d.ts +5 -4
  8. package/dist/domains/anzuUser/components/AUserMetadataForm.vue.js +113 -108
  9. package/dist/domains/anzuUser/components/AUserMetadataForm.vue.js.map +1 -1
  10. package/dist/domains/anzuUser/composables/anzuUserValidations.d.ts +3 -2
  11. package/dist/domains/anzuUser/composables/anzuUserValidations.js +1 -1
  12. package/dist/domains/anzuUser/composables/anzuUserValidations.js.map +1 -1
  13. package/dist/domains/anzuUser/composables/userSystemDescriptor.d.ts +4 -3
  14. package/dist/domains/anzuUser/composables/userSystemDescriptor.js.map +1 -1
  15. package/dist/domains/anzuUser/filter/anzuUserFilter.d.ts +1 -2
  16. package/dist/domains/anzuUser/filter/anzuUserFilter.js.map +1 -1
  17. package/dist/domains/dam/uploadQueue/components/UploadQueueDialog.vue.js +84 -84
  18. package/dist/domains/dam/uploadQueue/components/UploadQueueDialog.vue.js.map +1 -1
  19. package/dist/domains/filters/composables/filterFactory.js +53 -52
  20. package/dist/domains/filters/composables/filterFactory.js.map +1 -1
  21. package/dist/domains/listEditor/composables/useKeyboardNav.js +3 -3
  22. package/dist/domains/listEditor/composables/useKeyboardNav.js.map +1 -1
  23. package/dist/domains/unsavedGuard/composables/useUnsavedChangesGuard.js +25 -21
  24. package/dist/domains/unsavedGuard/composables/useUnsavedChangesGuard.js.map +1 -1
  25. package/dist/lib.d.ts +2 -2
  26. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"filterFactory.js","names":["getCurrentInstance","onMounted","provide","reactive","toRaw","useDebounceFn","datatablePageKey","useDatatablePageStore","DatatablePageInViewKey","DatatablePageStoreKey","DatatablePaginationKey","FilterConfigKey","FilterDataKey","cloneDeep","isArray","isBoolean","isEmptyArray","isEmptyObject","isNull","isNumber","isObject","isString","isUndefined","SortOrder","stringToBooleanExact","stringToNumber","SORT_URL_PARAM","PAGE_URL_PARAM","ROWS_PER_PAGE_URL_PARAM","PAGE_IN_VIEW","MAX_ROWS_PER_PAGE","END_FILTER_MARKER","positiveInteger","value","max","number","RELAXED_IN_HASH","relaxHashEncoding","match","isSameFilterValue","a","b","item","index","encodeFilterHash","data","sortBy","page","params","key","buildFilterHash","filterConfig","filters","field","hash","isRouterSafeHash","defaultRenderOptions","createFilterStore","filterFields","acc","createFilter","store","options","config","filter","defaultValue","resolveValue","defaultGlobalOptions","fallback","useFilterClearHelpers","clearOne","name","filterData","clearAll","filterName","clearOneFilterSelected","optionValue","filterSelected","isClearable","selectedFound","foundIndex","newArray","clearAllFilterSelected","listDefaultSort","FilterHelpersMoreOptionsDefault","useFilterHelpers","moreOptions","storeKey","pageStoreKey","pagination","storePageInView","consumeStoredPage","getStoredRowsPerPage","getStoredView","setStoredPage","viewOf","getFilterDataForStoring","listPagination","rememberShownPage","hasStoredPage","updateLocationHash","serializeFilters","pageFitsStoredView","storeFilterLocalStorage","keepsItsView","consumeRestoredPage","view","rowsPerPageFor","restoredPage","addressOnlyFields","withoutAddressOnly","fields","kept","resetAddressOnlyFields","fromHash","includeSort","includePage","deserializeFilters","markerIndex","result","sortParam","order","rowsPerPage","fieldConfig","items","hasPage","replaceHash","url","state","patched","serialized","resetLocationHash","parseLocationHash","readStoredView","stored","loadFilterLocalStorage","hasAddressOnlyValue","filterFieldsOf","callback","source","storedFromHash","hashDescribesThisView","tryConvertNumber","tryConvertBoolean","storedPage","useDatatableList","fetchList","filterHelpersOptions","resetFilter","submitFilter","loadStoredFilters","getList","submitFilterAction"],"sources":["../../../../src/domains/filters/composables/filterFactory.ts"],"sourcesContent":["import { getCurrentInstance, onMounted, provide, reactive, type Ref, toRaw } from 'vue'\nimport { useDebounceFn } from '@vueuse/core'\nimport { datatablePageKey, useDatatablePageStore } from '@/domains/system/store/datatablePageStore'\nimport {\n DatatablePageInViewKey,\n DatatablePageStoreKey,\n DatatablePaginationKey,\n FilterConfigKey,\n FilterDataKey,\n} from '@/domains/filters/utils/filterInjectionKeys'\nimport {\n cloneDeep,\n isArray,\n isBoolean,\n isEmptyArray,\n isEmptyObject,\n isNull,\n isNumber,\n isObject,\n isString,\n isUndefined,\n} from '@/shared/utils/common'\nimport type { AnyFn } from '@vueuse/core'\nimport type { Pagination } from '@/domains/api/composables/pagination'\nimport { type DatatableSortBy } from '@/domains/filters/datatable/utils/datatableColumns'\nimport { SortOrder } from '@/domains/api/types/SortOrder'\nimport { stringToBooleanExact, stringToNumber } from '@/shared/utils/string'\nimport type { ValueObjectOption } from '@/shared/types/ValueObject'\n\nexport type FilterStoreIdentifier = { system: string; subject: string }\n\nconst SORT_URL_PARAM = '_sort'\n// The page is kept with its rows per page: page 3 at another page size shows other rows.\nconst PAGE_URL_PARAM = '_page'\nconst ROWS_PER_PAGE_URL_PARAM = '_limit'\nconst PAGE_IN_VIEW = new RegExp(`(^|[#&])${PAGE_URL_PARAM}=`)\n// A link cannot ask the API for more rows than a page size a list offers.\nconst MAX_ROWS_PER_PAGE = 100\nconst END_FILTER_MARKER = '~'\n\nconst positiveInteger = (value: string | null, max = Number.MAX_SAFE_INTEGER): number | undefined => {\n if (isNull(value) || !/^\\d+$/.test(value)) return undefined\n const number = Number(value)\n return number > 0 && number <= max ? number : undefined\n}\n\n// `URLSearchParams` percent-encodes characters a fragment accepts verbatim,\n// and vue-router runs `encodeURI` over the hash, double-escaping `%`.\n// So `_sort=id%2Cdesc` arrives as `id%252Cdesc` and the sort is lost.\n// Decoding these keeps the hash stable through `router.push({ hash })`.\n// `~` stays encoded because the end marker must never occur in a\n// value. `&` and `=` carry the structure. `+` reads back as a space.\nconst RELAXED_IN_HASH: Record<string, string> = {\n '%2C': ',',\n '%3A': ':',\n '%2F': '/',\n '%40': '@',\n '%24': '$',\n '%21': '!',\n '%27': \"'\",\n '%28': '(',\n '%29': ')',\n '%3B': ';',\n '%3F': '?',\n}\nconst relaxHashEncoding = (value: string) =>\n value.replace(/%(2C|3A|2F|40|24|21|27|28|29|3B|3F)/g, (match) => RELAXED_IN_HASH[match]!)\n\n// `structuredClone` gives each array default a new identity, so `!==` is always true.\n// Without a deep compare, an array default would be written into the URL on every submit.\nconst isSameFilterValue = (a: AllowedFilterValues, b: AllowedFilterValues): boolean => {\n if (isArray(a) && isArray(b)) {\n return a.length === b.length && a.every((item, index) => item === b[index])\n }\n return a === b\n}\n\nconst encodeFilterHash = (\n data: Record<string, AllowedFilterValues>,\n sortBy?: DatatableSortBy,\n page?: Pick<Pagination, 'page' | 'rowsPerPage'>\n): string => {\n const params = new URLSearchParams()\n for (const key in data) {\n const value = data[key]\n if (isUndefined(value) || isNull(value)) continue\n if (isArray(value) && isEmptyArray(value)) continue\n if (isObject(value) && isEmptyObject(value)) continue\n if (isString(value) && value.length === 0) continue\n params.set(key, isArray(value) ? value.join(',') : String(value))\n }\n if (sortBy) {\n params.set(SORT_URL_PARAM, `${sortBy.key},${sortBy.order}`)\n }\n // Left out on the first page, so a list there keeps the address it had.\n if (page && page.page > 1) {\n params.set(PAGE_URL_PARAM, String(page.page))\n params.set(ROWS_PER_PAGE_URL_PARAM, String(page.rowsPerPage))\n }\n if (params.size === 0) return ''\n return relaxHashEncoding(params.toString()) + END_FILTER_MARKER\n}\n\n/**\n * Hash for a filter link, leaving out values equal to their default. Returns an empty string when nothing differs.\n * Use with `router.push({ name, hash })`. The hash needs the leading `#`, or vue-router appends it to the path.\n * A hash containing `%` (diacritics, `&`, `=`) does not survive the push. Check\n * `isRouterSafeHash` and fall back to setting `window.location.hash` after navigating.\n */\nexport function buildFilterHash<F extends readonly MakeFilterOption<string>[]>(\n filterConfig: FilterConfig<F>,\n filters: Partial<Record<keyof FilterData<F> & string, AllowedFilterValues>>,\n sortBy?: DatatableSortBy\n): string {\n const data: Record<string, AllowedFilterValues> = {}\n for (const [key, value] of Object.entries(filters) as [string, AllowedFilterValues][]) {\n const field = filterConfig.fields[key as keyof FilterConfig<F>['fields']]\n if (isUndefined(field) || isSameFilterValue(value, field.default)) continue\n data[key] = value\n }\n const hash = encodeFilterHash(data, sortBy)\n return hash.length === 0 ? hash : '#' + hash\n}\n\n/** Whether `router.push({ hash })` would leave the hash intact — see `buildFilterHash`. */\nexport const isRouterSafeHash = (hash: string): boolean => !hash.includes('%')\n\nconst defaultRenderOptions: FilerRenderOptions = {\n skip: false,\n selected: true,\n xs: undefined,\n sm: undefined,\n md: undefined,\n lg: undefined,\n xl: undefined,\n}\n\nexport function createFilterStore<F extends readonly MakeFilterOption<string>[]>(filterFields: F): FilterData<F> {\n return reactive(\n filterFields.reduce((acc, field) => {\n return {\n ...acc,\n [field.name]: cloneDeep(field.default),\n }\n }, {} as FilterData<F>)\n ) as FilterData<F>\n}\n\nexport function createFilter<F extends readonly MakeFilterOption<string>[]>(\n filterFields: F,\n store: FilterData<F>,\n options?: Partial<GeneralFilterOptions>\n): {\n filterConfig: FilterConfig<F>\n filterData: FilterData<F>\n} {\n const config = filterFields.reduce(\n (acc, filter) => {\n const key = filter.name as keyof FilterData<F>\n const defaultValue = cloneDeep(filter.default)\n\n return {\n ...acc,\n [key]: {\n name: key as string,\n variant: resolveValue(filter.variant, 'eq'),\n type: resolveValue(filter.type, 'custom'),\n titleT:\n filter.titleT ??\n (options?.system && options?.subject && filter.name\n ? `${options.system}.${options.subject}.filter.${filter.name}`\n : undefined),\n apiName: resolveValue(filter.apiName, filter.name),\n clearable: resolveValue(filter.clearable, true),\n mandatory: resolveValue(filter.mandatory, false),\n multiple: isArray(defaultValue),\n advanced: resolveValue(filter.advanced, false),\n related: resolveValue(filter.related, undefined),\n exclude: resolveValue(filter.exclude, false),\n persist: resolveValue(filter.persist, true),\n default: defaultValue,\n render: { ...defaultRenderOptions, ...resolveValue(filter.render, {}) },\n },\n }\n },\n {} as FilterConfig<F>['fields']\n )\n\n // A time interval names the field holding its upper bound.\n // The query builder and the chips read that config unchecked.\n // Fail here by name rather than with a TypeError on the first query.\n for (const field of Object.values(config) as FilterField[]) {\n if (field.related && !(field.related in config)) {\n throw new Error(`createFilter: \"${field.name}\" names related field \"${field.related}\", which is not configured`)\n }\n }\n\n const defaultGlobalOptions: GeneralFilterOptions = {\n elastic: false,\n system: undefined,\n subject: undefined,\n simpleFilters: false,\n ...options,\n }\n\n if (defaultGlobalOptions.elastic) {\n defaultGlobalOptions.simpleFilters = true\n }\n\n const filterConfig = reactive({\n general: defaultGlobalOptions,\n touched: false,\n fields: config,\n }) as FilterConfig<F>\n\n return {\n filterConfig,\n filterData: store as FilterData<F>,\n }\n}\n\nfunction resolveValue<T>(value: T | undefined, fallback: T): T {\n return isUndefined(value) ? fallback : value\n}\n\nexport function useFilterClearHelpers<\n F extends readonly MakeFilterOption<string>[] = readonly MakeFilterOption<string>[],\n>() {\n const clearOne = (name: keyof FilterData<F>, filterData: FilterData<F>, filterConfig: FilterConfig<F>) => {\n if (!filterConfig.fields[name]?.clearable) return\n filterData[name] = cloneDeep(filterConfig.fields[name].default)\n }\n\n const clearAll = (filterData: FilterData<F>, filterConfig: FilterConfig<F>) => {\n for (const filterName in filterConfig.fields) {\n clearOne(filterName as keyof FilterData<F>, filterData, filterConfig)\n }\n }\n const clearOneFilterSelected = (\n name: string,\n optionValue: number | string,\n filterData: FilterData<F>,\n filterConfig: FilterConfig<F>,\n filterSelected: Ref<Map<string, ValueObjectOption<string | number>[]>>\n ) => {\n if (!isClearable(name, filterConfig)) return\n const config = filterConfig.fields[name as keyof FilterConfig<F>['fields']]\n const selectedFound = filterSelected.value.get(name)\n if (selectedFound && selectedFound.length === 1) {\n filterSelected.value.delete(name)\n } else if (selectedFound) {\n const foundIndex = selectedFound.findIndex((item) => item.value === optionValue)\n if (foundIndex !== -1) selectedFound.splice(foundIndex, 1)\n }\n if (config.type === 'timeInterval' && config.related) {\n filterData[name as keyof FilterData<F>] = config.default\n filterData[config.related as keyof FilterData<F>] =\n filterConfig.fields[config.related as keyof FilterConfig<F>['fields']].default\n } else if (\n isArray(filterData[name as keyof FilterData<F>]) &&\n (filterData[name as keyof FilterData<F>] as any[]).length > 0\n ) {\n const foundIndex = (filterData[name as keyof FilterData<F>] as any[]).findIndex(\n (item) => String(item) === String(optionValue)\n )\n if (foundIndex !== -1) {\n const newArray = [...toRaw(filterData[name as keyof FilterData<F>] as any[])]\n newArray.splice(foundIndex, 1)\n filterData[name as keyof FilterData<F>] = newArray as AllowedFilterValues\n }\n } else if (isString(filterData[name as keyof FilterData<F>]) || isNumber(filterData[name as keyof FilterData<F>])) {\n filterData[name as keyof FilterData<F>] = config.default\n } else if (isBoolean(filterData[name as keyof FilterData<F>])) {\n filterData[name as keyof FilterData<F>] = config.default\n }\n }\n\n const clearAllFilterSelected = (\n filterData: FilterData<F>,\n filterConfig: FilterConfig<F>,\n filterSelected: Ref<Map<string, ValueObjectOption<string | number>[]>>\n ) => {\n for (const key of filterSelected.value.keys()) {\n if (isClearable(key, filterConfig)) {\n filterSelected.value.delete(key)\n }\n }\n }\n\n const isClearable = (name: string, filterConfig: FilterConfig<F>) => {\n const config = filterConfig.fields[name as keyof FilterConfig<F>['fields']]\n return !(config.mandatory || !config.clearable)\n }\n\n return {\n clearOne,\n clearAll,\n clearOneFilterSelected,\n clearAllFilterSelected,\n isClearable,\n }\n}\n\n/**\n * The sort a list had when it first restored its view, before the address or the storage changed it: the list's own\n * default, also one its setup put in after `usePagination`. Kept per pagination, so a pagination a module holds keeps\n * the default of its first visit, not a sort picked before the list was opened again.\n */\nconst listDefaultSort = new WeakMap<Ref<Pagination>, DatatableSortBy>()\n\nexport interface FilterHelpersMoreOptions {\n storeFiltersLocalStorage: string | boolean // false to disable, string to override store key\n populateUrlParams: boolean\n // Keys the remembered page without turning on local storage. A select dialog sharing its subject with a list\n // sets its own, so searching or paging in it does not change the page Close returns that list to.\n pageStoreKey?: string\n}\n\nconst FilterHelpersMoreOptionsDefault = {\n storeFiltersLocalStorage: true,\n populateUrlParams: true,\n}\n\nexport function useFilterHelpers<F extends readonly MakeFilterOption<string>[] = readonly MakeFilterOption<string>[]>(\n filterData: FilterData<F>,\n filterConfig: FilterConfig<F>,\n moreOptions: Partial<FilterHelpersMoreOptions> = {}\n) {\n const options = { ...FilterHelpersMoreOptionsDefault, ...moreOptions }\n\n let storeKey: undefined | string = undefined\n if (isString(options.storeFiltersLocalStorage)) {\n storeKey = options.storeFiltersLocalStorage\n } else if (\n isBoolean(options.storeFiltersLocalStorage) &&\n true === options.storeFiltersLocalStorage &&\n isString(filterConfig.general.system) &&\n isString(filterConfig.general.subject)\n ) {\n storeKey = 'tableFilter_' + filterConfig.general.system + '_' + filterConfig.general.subject\n }\n\n // The page key exists even when filters are not persisted.\n // A string override distinguishes tables sharing a subject.\n const pageStoreKey =\n options.pageStoreKey ??\n (isString(options.storeFiltersLocalStorage)\n ? options.storeFiltersLocalStorage\n : datatablePageKey(filterConfig.general.system, filterConfig.general.subject))\n // Provided so `ADatatablePagination` picks it up. Guarded because\n // the composable may run outside setup, where Vue would warn.\n if (getCurrentInstance()) {\n provide(DatatablePageStoreKey, pageStoreKey)\n provide(DatatablePageInViewKey, (pagination) => storePageInView(pagination))\n }\n const { consumeStoredPage, getStoredRowsPerPage, getStoredView, setStoredPage } = useDatatablePageStore()\n // The filter and sort a page is shown in. Stored on load, submit and reset, which every change of them goes through.\n const viewOf = (sortBy: DatatableSortBy) => encodeFilterHash(getFilterDataForStoring(), sortBy)\n // `ADatatablePagination` stores the page only when its watcher sees a change. A list that opens on page 1,\n // or returns to it within the tick that restored another page, would keep the older page for the next Close.\n // The pagination of the list, the one load, submit and reset go through. A pager of another\n // pagination under the same provide (a dialog's) must not write this list's address.\n let listPagination: Ref<Pagination> | undefined\n const rememberShownPage = (pagination: Ref<Pagination>) => {\n listPagination = pagination\n setStoredPage(pageStoreKey, pagination.value.page, pagination.value.rowsPerPage, viewOf(pagination.value.sortBy))\n }\n // A page change goes into the address and local storage with the filter and sort,\n // so a reload, a link, Back or a return through the menu shows the same page.\n const storePageInView = (pagination: Ref<Pagination>) => {\n if (pagination !== listPagination) return\n // The first page is written only to take a page out. A reset leaves the address empty and goes to page 1,\n // which would otherwise put the sort back in.\n if (pagination.value.page === 1 && !hasStoredPage()) return\n const data = getFilterDataForStoring()\n updateLocationHash(serializeFilters(data, pagination, true, true))\n if (pageFitsStoredView(data)) storeFilterLocalStorage(serializeFilters(data, pagination, true, true))\n }\n // The page Close kept. A list that keeps neither filter nor sort (no hash, no local storage) comes back with\n // both reset, and its page 3 would show other rows, so its page comes back only into the view it was shown in.\n // Not checked for other lists: they restore their view themselves, and many adjust the sort or a filter\n // in `getList` after a submit or reset stored the view, which would turn a correct restore into page 1.\n const keepsItsView = options.populateUrlParams || !isUndefined(storeKey)\n const consumeRestoredPage = (sortBy: DatatableSortBy) => {\n const page = consumeStoredPage(pageStoreKey)\n if (page === null || keepsItsView) return page\n const view = getStoredView(pageStoreKey)\n return view === null || view === viewOf(sortBy) ? page : null\n }\n // A restored page comes back at the page size it was shown at. At another size it would show other rows.\n const rowsPerPageFor = (pagination: Ref<Pagination>, restoredPage: number | null) =>\n restoredPage === null\n ? pagination.value.rowsPerPage\n : (getStoredRowsPerPage(pageStoreKey) ?? pagination.value.rowsPerPage)\n\n const { clearAll } = useFilterClearHelpers<F>()\n\n const getFilterDataForStoring = (): Record<string, AllowedFilterValues> => {\n const data: Record<string, AllowedFilterValues> = {}\n for (const filterName in filterData) {\n try {\n const key = filterName as keyof FilterData<F>\n const value = filterData[key]\n if (\n !isUndefined(value) &&\n !isNull(value) &&\n !isEmptyArray(value) &&\n !isSameFilterValue(value, filterConfig.fields[key].default)\n ) {\n data[filterName] = value\n }\n } catch (e) {\n // Ignore errors\n }\n }\n return data\n }\n\n // Fields whose value lives in the address only (`persist: false`). Local storage never holds them.\n const addressOnlyFields = (): string[] =>\n (Object.values(filterConfig.fields) as FilterField[])\n .filter((field) => field.persist === false)\n .map((field) => field.name)\n\n const withoutAddressOnly = (data: Record<string, AllowedFilterValues>): Record<string, AllowedFilterValues> => {\n const fields = addressOnlyFields()\n if (fields.length === 0) return data\n const kept = { ...data }\n for (const name of fields) delete kept[name]\n return kept\n }\n\n // A field kept in the address takes its value from the hash, else its default. The filter store may still hold\n // the value a link gave it on an earlier visit, and a list opened from the menu would silently show it.\n const resetAddressOnlyFields = (fromHash: Record<string, AllowedFilterValues> | undefined) => {\n for (const name of addressOnlyFields()) {\n if (fromHash && !isUndefined(fromHash[name])) continue\n const key = name as keyof FilterData<F>\n filterData[key] = cloneDeep(filterConfig.fields[key].default)\n }\n }\n\n const serializeFilters = (\n data: Record<string, AllowedFilterValues>,\n pagination: Ref<Pagination>,\n includeSort: boolean,\n includePage = false\n ): string => {\n return encodeFilterHash(\n data,\n includeSort ? pagination.value.sortBy : undefined,\n includePage ? pagination.value : undefined\n )\n }\n\n const deserializeFilters = (\n hash: string\n ): {\n filters: Record<string, AllowedFilterValues>\n sortBy: DatatableSortBy\n page?: number\n rowsPerPage?: number\n } | null => {\n if (!hash) return null\n if (hash.startsWith('#')) hash = hash.substring(1)\n\n // `URLSearchParams` encodes `~` in values, so the marker never occurs in our data.\n // A hash without it is foreign or truncated. `null` lets localStorage take over.\n const markerIndex = hash.indexOf(END_FILTER_MARKER)\n if (markerIndex === -1) return null\n hash = hash.slice(0, markerIndex)\n\n const params = new URLSearchParams(hash)\n const result: Record<string, AllowedFilterValues> = {}\n let sortBy: DatatableSortBy = null\n\n const sortParam = params.get(SORT_URL_PARAM)\n if (sortParam) {\n const [key, order] = sortParam.split(',')\n if (key && (order === SortOrder.Asc || order === SortOrder.Desc)) {\n sortBy = { key, order }\n }\n params.delete(SORT_URL_PARAM)\n }\n\n const page = positiveInteger(params.get(PAGE_URL_PARAM))\n const rowsPerPage = positiveInteger(params.get(ROWS_PER_PAGE_URL_PARAM), MAX_ROWS_PER_PAGE)\n params.delete(PAGE_URL_PARAM)\n params.delete(ROWS_PER_PAGE_URL_PARAM)\n\n for (const [key, value] of params.entries()) {\n const fieldConfig = filterConfig.fields[key as keyof typeof filterConfig.fields]\n if (isUndefined(fieldConfig)) {\n console.error(`Filter config not found for ${key}`)\n continue\n }\n const isMultiple = fieldConfig.multiple ?? false\n\n if (isMultiple) {\n const items = value.split(',')\n\n const allNumeric = items.every((item) => item !== '' && String(Number(item)) === item)\n\n result[key] = allNumeric ? items.map(Number) : items\n } else {\n result[key] = value\n }\n }\n\n // A page without its rows per page is left out: it would show other rows at the list's page size.\n const hasPage = !isUndefined(page) && !isUndefined(rowsPerPage)\n\n // An empty result would still count as \"found\", shadowing localStorage.\n if (isEmptyObject(result) && isNull(sortBy) && !hasPage) return null\n\n return hasPage ? { filters: result, sortBy, page, rowsPerPage } : { filters: result, sortBy }\n }\n\n // A submit replaces the history entry instead of adding one.\n // `replaceState` fires no popstate, so vue-router runs no navigation or guards per submit.\n // Its `current` is patched so the router's next push, which rewrites this entry, keeps the hash.\n const replaceHash = (hash: string) => {\n const url = window.location.pathname + window.location.search + hash\n const state = window.history.state\n const patched =\n isObject(state) && isString((state as { current?: unknown }).current)\n ? { ...state, current: ((state as { current: string }).current.split('#')[0] ?? '') + hash }\n : state\n window.history.replaceState(patched, '', url)\n }\n\n const updateLocationHash = (serialized: string) => {\n if (options.populateUrlParams === false) return\n replaceHash('#' + serialized)\n }\n\n const resetLocationHash = () => {\n if (options.populateUrlParams === false) return\n replaceHash('')\n }\n\n const parseLocationHash = () => {\n if (options.populateUrlParams === false) return null\n return deserializeFilters(window.location.hash)\n }\n\n const storeFilterLocalStorage = (serialized: string) => {\n if (!storeKey || !localStorage) return\n localStorage.setItem(storeKey, serialized)\n }\n\n // The saved view without the fields kept in the address, also when it was saved before they were.\n const readStoredView = (): string | null => {\n if (!storeKey || !localStorage) return null\n const stored = localStorage.getItem(storeKey)\n if (!stored || !isString(stored)) return null\n const fields = addressOnlyFields()\n const markerIndex = stored.indexOf(END_FILTER_MARKER)\n if (fields.length === 0 || markerIndex === -1) return stored\n const params = new URLSearchParams(stored.slice(0, markerIndex))\n if (!fields.some((name) => params.has(name))) return stored\n for (const name of fields) params.delete(name)\n return params.size === 0 ? '' : relaxHashEncoding(params.toString()) + END_FILTER_MARKER\n }\n\n const loadFilterLocalStorage = () => {\n const stored = readStoredView()\n if (!stored) return null\n return deserializeFilters(stored)\n }\n\n const hasStoredPage = () =>\n (options.populateUrlParams !== false && PAGE_IN_VIEW.test(window.location.hash)) ||\n (!isUndefined(storeKey) && !!localStorage && PAGE_IN_VIEW.test(localStorage.getItem(storeKey) ?? ''))\n\n const hasAddressOnlyValue = (data: Record<string, AllowedFilterValues>) =>\n addressOnlyFields().some((name) => !isUndefined(data[name]))\n\n // The filter fields of a serialized view, without its sort and page, in one order.\n const filterFieldsOf = (serialized: string): string => {\n const markerIndex = serialized.indexOf(END_FILTER_MARKER)\n const params = new URLSearchParams(markerIndex === -1 ? serialized : serialized.slice(0, markerIndex))\n params.delete(SORT_URL_PARAM)\n params.delete(PAGE_URL_PARAM)\n params.delete(ROWS_PER_PAGE_URL_PARAM)\n params.sort()\n return params.toString()\n }\n\n // Local storage takes a page only with the view it restores. A view it cannot restore (a field kept in the address)\n // or another view than the one it holds (a link naming a page but no field) leaves it as it is: the menu would\n // open the saved view, or the whole list, on the page of another one. The sort is not compared, as lists switch it\n // in `getList` after a submit (a text search sorted by score), and their page would never be kept.\n const pageFitsStoredView = (data: Record<string, AllowedFilterValues>): boolean => {\n if (hasAddressOnlyValue(data)) return false\n const stored = readStoredView()\n if (!stored || !stored.includes(END_FILTER_MARKER)) return true\n return filterFieldsOf(stored) === filterFieldsOf(encodeFilterHash(data))\n }\n\n // A list that keeps its view goes back to its default sort too. The reset empties the address and the storage, and a\n // reload, Close or the menu then opened the default sort while the screen kept the one picked before (#87746).\n const resetFilter = (pagination: Ref<Pagination>, callback?: AnyFn) => {\n const sortBy =\n keepsItsView && listDefaultSort.has(pagination)\n ? cloneDeep(listDefaultSort.get(pagination) as DatatableSortBy)\n : pagination.value.sortBy\n pagination.value = { ...pagination.value, sortBy, page: 1 }\n rememberShownPage(pagination)\n if (storeKey && localStorage) {\n localStorage.removeItem(storeKey)\n }\n resetLocationHash()\n filterConfig.touched = false\n if (callback) callback()\n }\n\n const submitFilter = (pagination: Ref<Pagination>, callback?: AnyFn) => {\n const data = getFilterDataForStoring()\n updateLocationHash(serializeFilters(data, pagination, true))\n storeFilterLocalStorage(serializeFilters(withoutAddressOnly(data), pagination, true))\n pagination.value = { ...pagination.value, page: 1 }\n rememberShownPage(pagination)\n filterConfig.touched = false\n if (callback) callback()\n }\n\n const loadStoredFilters = (pagination: Ref<Pagination>, callback?: AnyFn) => {\n if (!listDefaultSort.has(pagination)) listDefaultSort.set(pagination, cloneDeep(pagination.value.sortBy))\n let source: 'hash' | 'localStorage' = 'hash'\n let storedFromHash = parseLocationHash()\n if (isNull(storedFromHash)) {\n source = 'localStorage'\n storedFromHash = loadFilterLocalStorage()\n }\n resetAddressOnlyFields(source === 'hash' && storedFromHash ? storedFromHash.filters : undefined)\n if (\n isNull(storedFromHash) ||\n (isEmptyObject(storedFromHash.filters) && isNull(storedFromHash.sortBy) && isUndefined(storedFromHash.page))\n ) {\n const restoredPage = consumeRestoredPage(pagination.value.sortBy)\n if (restoredPage !== null) {\n pagination.value = {\n ...pagination.value,\n page: restoredPage,\n rowsPerPage: rowsPerPageFor(pagination, restoredPage),\n }\n }\n rememberShownPage(pagination)\n if (callback) callback()\n return false\n }\n\n // A hash naming at least one field describes the whole view, whether\n // from a link or from going back. Reset the fields it omits.\n // Otherwise they keep values from the module-level store, and the same link lands\n // differently. Local storage still merges, since it omits fields equal to their default.\n // A `_sort`-only hash is excluded. It can come from a link for\n // another table on the same page and must not wipe this filter.\n // Only `clearable` fields are reset.\n const hashDescribesThisView = source === 'hash' && !isEmptyObject(storedFromHash.filters)\n if (hashDescribesThisView) {\n clearAll(filterData, filterConfig)\n }\n\n for (const filterName in filterData) {\n const key = filterName as keyof FilterData<F>\n let value = storedFromHash.filters[key]\n if (isUndefined(value)) continue\n if (isString(value)) {\n const tryConvertNumber = stringToNumber(value)\n if (!isNull(tryConvertNumber) && String(tryConvertNumber) === value) {\n value = tryConvertNumber\n } else {\n const tryConvertBoolean = stringToBooleanExact(value)\n if (!isNull(tryConvertBoolean)) {\n value = tryConvertBoolean\n }\n }\n }\n filterData[key] = value\n }\n if (source === 'localStorage') {\n const stored = readStoredView()\n if (stored) {\n updateLocationHash(stored)\n }\n }\n // A link may omit the sort. Taking `null` would drop `order[...]` from\n // the query, and paging without ORDER BY can repeat or skip rows.\n const sortBy = storedFromHash.sortBy ?? pagination.value.sortBy\n // Always consumed. The flag means \"the next list should restore\n // its page\". Leaving it set would pass the page to the next table.\n const restoredPage = consumeRestoredPage(sortBy)\n const storedPage = restoredPage === null ? storedFromHash.page : undefined\n pagination.value = {\n ...pagination.value,\n sortBy,\n // A link starts at the page it names, else the first. A restored page still wins.\n // Only the close button sets that flag, meaning the user returns\n // to this list, and that address carries the list's own hash.\n page: restoredPage ?? storedPage ?? (source === 'hash' ? 1 : pagination.value.page),\n rowsPerPage: isUndefined(storedPage)\n ? rowsPerPageFor(pagination, restoredPage)\n : (storedFromHash.rowsPerPage ?? pagination.value.rowsPerPage),\n }\n rememberShownPage(pagination)\n if (hashDescribesThisView) {\n // Local storage mirrors the last applied state, so a link becomes the view the user returns to.\n // Re-serialized to drop values equal to their default. A sort-only hash does not overwrite it.\n // Without the page when a field kept in the address is left out: the page is of the view with that field.\n const data = getFilterDataForStoring()\n storeFilterLocalStorage(serializeFilters(withoutAddressOnly(data), pagination, true, !hasAddressOnlyValue(data)))\n }\n if (callback) callback()\n return true\n }\n\n return {\n loadStoredFilters,\n resetFilter,\n submitFilter,\n serializeFilters,\n deserializeFilters,\n }\n}\n\n/**\n * Provides the filter (`FilterConfigKey`, `FilterDataKey`) and `pagination` (`DatatablePaginationKey`)\n * to the filter bar and `ADatatablePagination` below, and wires the list to them.\n * `getList` is a debounced `fetchList(pagination, filterData, filterConfig)` that resolves when\n * the load finishes. A call superseded within the debounce resolves at once without loading.\n * Submit, reset and sort go through `useFilterHelpers` (with `filterHelpersOptions`).\n * On mount the stored filter and remembered page are restored before the first load.\n * Use only for a datatable that is the parent of its filter bar. Wire it by hand when the first load skips the stored\n * filter, `getList` adds logic, sort is custom, `fetchList` takes other arguments, or a parent renders the filter bar.\n * @example\n * const { filterData, filterConfig } = useFaqListFilter()\n * const { fetchList, listItems } = useFaqListActions()\n * const { pagination } = usePagination(SORT_BY_ID)\n * const { getList, sortByChange, submitFilterAction, resetFilterAction\n * } = useDatatableList(filterData, filterConfig, pagination, fetchList)\n */\nexport function useDatatableList<\n F extends readonly MakeFilterOption<string>[] = readonly MakeFilterOption<string>[],\n R = unknown,\n>(\n filterData: FilterData<F>,\n filterConfig: FilterConfig<F>,\n pagination: Ref<Pagination>,\n fetchList: (pagination: Ref<Pagination>, filterData: FilterData<F>, filterConfig: FilterConfig<F>) => R,\n filterHelpersOptions: Partial<FilterHelpersMoreOptions> = {}\n) {\n provide(FilterConfigKey, filterConfig as FilterConfig)\n provide(FilterDataKey, filterData as FilterData)\n provide(DatatablePaginationKey, pagination)\n const { resetFilter, submitFilter, loadStoredFilters } = useFilterHelpers(\n filterData,\n filterConfig,\n filterHelpersOptions\n )\n const getList = useDebounceFn(() => fetchList(pagination, filterData, filterConfig))\n const submitFilterAction = () => submitFilter(pagination, getList)\n const resetFilterAction = () => resetFilter(pagination, getList)\n onMounted(() => loadStoredFilters(pagination, getList))\n return { getList, sortByChange: submitFilterAction, submitFilterAction, resetFilterAction }\n}\n\nexport type AllowedFilterValues = number | number[] | string | string[] | null | undefined | boolean\n\nexport interface GeneralFilterOptions {\n system?: string\n subject?: string\n elastic?: boolean\n simpleFilters?: boolean\n}\n\nexport interface FilerRenderOptions {\n skip: boolean\n // Whether the field shows as a chip in `FiltersSelected`. Default true.\n // Optional because other admins may construct `FilerRenderOptions`.\n selected?: boolean\n xs: number | undefined\n sm: number | undefined\n md: number | undefined\n lg: number | undefined\n xl: number | undefined\n}\n\nexport type FilterVariant =\n | 'search'\n | 'lt'\n | 'in'\n | 'notIn'\n | 'endsWith'\n | 'startsWith'\n | 'memberOf'\n | 'neq'\n | 'gte'\n | 'gt'\n | 'eq'\n | 'lte'\n | 'custom'\n\nexport type FilterType = 'boolean' | 'datetime' | 'integer' | 'string' | 'custom' | 'timeInterval'\n\nexport interface MakeFilterOption<TName extends string = string> {\n name: TName\n default: AllowedFilterValues\n type?: FilterType\n variant?: FilterVariant\n titleT?: string\n apiName?: string\n clearable?: boolean\n mandatory?: boolean\n advanced?: boolean\n exclude?: boolean\n /**\n * `false` keeps the field's value in the address only, for a field a link sets (a hidden id of a group, of a\n * record): it applies from the URL hash and goes into the hash and the API query as any other, but is never written\n * to local storage (`storeFiltersLocalStorage`) and never read back from it, also from a value saved before. A list\n * loaded without it in the hash shows it at its default, also when the filter store still holds it from an earlier\n * visit. A bookmark keeps it, as the user saves it on purpose. Default `true`.\n */\n persist?: boolean\n related?: string | undefined\n render?: Partial<FilerRenderOptions>\n}\n\nexport interface FilterField {\n name: string\n type: FilterType\n variant: FilterVariant\n titleT?: string\n default: AllowedFilterValues\n apiName: string\n clearable: boolean\n mandatory: boolean\n multiple: boolean\n advanced: boolean\n exclude: boolean\n /** See `MakeFilterOption.persist`. Optional for a field built by hand; missing reads as `true`. */\n persist?: boolean\n related: string | undefined\n render: FilerRenderOptions\n}\n\nexport type FilterConfig<F extends readonly MakeFilterOption<string>[] = readonly MakeFilterOption<string>[]> = {\n general: GeneralFilterOptions\n touched: boolean\n fields: {\n [P in F[number]['name']]: FilterField\n }\n}\n\nexport type FilterData<F extends readonly MakeFilterOption<string>[] = readonly MakeFilterOption<string>[]> = {\n [P in F[number]['name']]: AllowedFilterValues\n}\n"],"mappings":";;;;;;;;AA+BA,IAAM0B,IAAiB,SAEjBC,IAAiB,SACjBC,IAA0B,UAC1BC,IAAmB,OAAO,WAAWF,EAAe,EAAE,GAEtDG,KAAoB,KACpBC,IAAoB,KAEpBC,KAAmBC,GAAsBC,oBAAsD;CACnG,IAAIhB,EAAOe,CAAK,KAAK,CAAC,QAAQ,KAAKA,CAAK,GAAG;CAC3C,IAAME,IAAS,OAAOF,CAAK;CAC3B,OAAOE,IAAS,KAAKA,KAAUD,IAAMC,IAAS,KAAA;AAChD,GAQMC,IAA0C;CAC9C,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;AACT,GACMC,KAAqBJ,MACzBA,EAAM,QAAQ,yCAAyCK,MAAUF,EAAgBE,EAAO,GAIpFC,KAAqBC,GAAwBC,MAC7C3B,EAAQ0B,CAAC,KAAK1B,EAAQ2B,CAAC,IAClBD,EAAE,WAAWC,EAAE,UAAUD,EAAE,OAAOE,GAAMC,MAAUD,MAASD,EAAEE,EAAM,IAErEH,MAAMC,GAGTG,KACJC,GACAC,GACAC,MACW;CACX,IAAMC,IAAS,IAAI,gBAAgB;CACnC,KAAK,IAAMC,KAAOJ,GAAM;EACtB,IAAMZ,IAAQY,EAAKI;EACf3B,EAAYW,CAAK,KAAKf,EAAOe,CAAK,KAClCnB,EAAQmB,CAAK,KAAKjB,EAAaiB,CAAK,KACpCb,EAASa,CAAK,KAAKhB,EAAcgB,CAAK,KACtCZ,EAASY,CAAK,KAAKA,EAAM,WAAW,KACxCe,EAAO,IAAIC,GAAKnC,EAAQmB,CAAK,IAAIA,EAAM,KAAK,GAAG,IAAI,OAAOA,CAAK,CAAC;CAClE;CAUA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MAAM;GAAE,GAClDS,EAAkBT,CAAU,GAC5BtC,EAAa,UAAU,IACnBuF,KAAUA,EAAS;EACzB;EAiGErC;EACAgB;CACF;AACF;AAkBA,SAAgB4B,EAIdzE,GACArB,GACAsC,GACAyD,GACAC,IAA0D,CAAC,GAC3D;CACAjJ,EAAQS,GAAiBwC,CAA4B,GACrDjD,EAAQU,GAAe4D,CAAwB,GAC/CtE,EAAQQ,GAAwB+E,CAAU;CAC1C,IAAM,EAAE2D,gBAAaC,iBAAcC,yBAAsBjE,EACvDb,GACArB,GACAgG,CACF,GACMI,IAAUlJ,QAAoB6I,EAAUzD,GAAYjB,GAAYrB,CAAY,CAAC,GAC7EqG,UAA2BH,EAAa5D,GAAY8D,CAAO;CAGjE,OADAtJ,QAAgBqJ,EAAkB7D,GAAY8D,CAAO,CAAC,GAC/C;EAAEA;EAAS,cAAcC;EAAoBA;EAAoB,yBAFxCJ,EAAY3D,GAAY8D,CAAO;CAE2B;AAC5F"}
1
+ {"version":3,"file":"filterFactory.js","names":["getCurrentInstance","onMounted","provide","reactive","toRaw","useDebounceFn","datatablePageKey","useDatatablePageStore","DatatablePageInViewKey","DatatablePageStoreKey","DatatablePaginationKey","FilterConfigKey","FilterDataKey","cloneDeep","isArray","isBoolean","isEmptyArray","isEmptyObject","isNull","isNumber","isObject","isString","isUndefined","SortOrder","stringToBooleanExact","stringToNumber","SORT_URL_PARAM","PAGE_URL_PARAM","ROWS_PER_PAGE_URL_PARAM","PAGE_IN_VIEW","MAX_ROWS_PER_PAGE","END_FILTER_MARKER","positiveInteger","value","max","number","RELAXED_IN_HASH","relaxHashEncoding","match","isSameFilterValue","a","b","item","index","encodeFilterHash","data","sortBy","page","defaultRowsPerPage","params","key","buildFilterHash","filterConfig","filters","field","hash","isRouterSafeHash","defaultRenderOptions","createFilterStore","filterFields","acc","createFilter","store","options","config","filter","defaultValue","resolveValue","defaultGlobalOptions","fallback","useFilterClearHelpers","clearOne","name","filterData","clearAll","filterName","clearOneFilterSelected","optionValue","filterSelected","isClearable","selectedFound","foundIndex","newArray","clearAllFilterSelected","listDefaultSort","listDefaultRowsPerPage","FilterHelpersMoreOptionsDefault","useFilterHelpers","moreOptions","storeKey","pageStoreKey","pagination","storePageInView","consumeStoredPage","getStoredRowsPerPage","getStoredView","setStoredPage","viewOf","getFilterDataForStoring","listPagination","rememberShownPage","serialized","serializeFilters","hasStoredPage","updateLocationHash","pageFitsStoredView","storeFilterLocalStorage","keepsItsView","consumeRestoredPage","view","rowsPerPageFor","restoredPage","addressOnlyFields","withoutAddressOnly","fields","kept","resetAddressOnlyFields","fromHash","includeSort","includePage","deserializeFilters","markerIndex","result","sortParam","order","pageParam","rowsPerPage","fieldConfig","items","hasPage","replaceHash","url","state","patched","resetLocationHash","parseLocationHash","readStoredView","stored","loadFilterLocalStorage","hasAddressOnlyValue","filterFieldsOf","callback","source","storedFromHash","hashDescribesThisView","tryConvertNumber","tryConvertBoolean","storedPage","useDatatableList","fetchList","filterHelpersOptions","resetFilter","submitFilter","loadStoredFilters","getList","submitFilterAction"],"sources":["../../../../src/domains/filters/composables/filterFactory.ts"],"sourcesContent":["import { getCurrentInstance, onMounted, provide, reactive, type Ref, toRaw } from 'vue'\nimport { useDebounceFn } from '@vueuse/core'\nimport { datatablePageKey, useDatatablePageStore } from '@/domains/system/store/datatablePageStore'\nimport {\n DatatablePageInViewKey,\n DatatablePageStoreKey,\n DatatablePaginationKey,\n FilterConfigKey,\n FilterDataKey,\n} from '@/domains/filters/utils/filterInjectionKeys'\nimport {\n cloneDeep,\n isArray,\n isBoolean,\n isEmptyArray,\n isEmptyObject,\n isNull,\n isNumber,\n isObject,\n isString,\n isUndefined,\n} from '@/shared/utils/common'\nimport type { AnyFn } from '@vueuse/core'\nimport type { Pagination } from '@/domains/api/composables/pagination'\nimport { type DatatableSortBy } from '@/domains/filters/datatable/utils/datatableColumns'\nimport { SortOrder } from '@/domains/api/types/SortOrder'\nimport { stringToBooleanExact, stringToNumber } from '@/shared/utils/string'\nimport type { ValueObjectOption } from '@/shared/types/ValueObject'\n\nexport type FilterStoreIdentifier = { system: string; subject: string }\n\nconst SORT_URL_PARAM = '_sort'\n// The page is kept with its rows per page: page 3 at another page size shows other rows.\nconst PAGE_URL_PARAM = '_page'\nconst ROWS_PER_PAGE_URL_PARAM = '_limit'\nconst PAGE_IN_VIEW = new RegExp(`(^|[#&])(${PAGE_URL_PARAM}|${ROWS_PER_PAGE_URL_PARAM})=`)\n// A link cannot ask the API for more rows than a page size a list offers.\nconst MAX_ROWS_PER_PAGE = 100\nconst END_FILTER_MARKER = '~'\n\nconst positiveInteger = (value: string | null, max = Number.MAX_SAFE_INTEGER): number | undefined => {\n if (isNull(value) || !/^\\d+$/.test(value)) return undefined\n const number = Number(value)\n return number > 0 && number <= max ? number : undefined\n}\n\n// `URLSearchParams` percent-encodes characters a fragment accepts verbatim,\n// and vue-router runs `encodeURI` over the hash, double-escaping `%`.\n// So `_sort=id%2Cdesc` arrives as `id%252Cdesc` and the sort is lost.\n// Decoding these keeps the hash stable through `router.push({ hash })`.\n// `~` stays encoded because the end marker must never occur in a\n// value. `&` and `=` carry the structure. `+` reads back as a space.\nconst RELAXED_IN_HASH: Record<string, string> = {\n '%2C': ',',\n '%3A': ':',\n '%2F': '/',\n '%40': '@',\n '%24': '$',\n '%21': '!',\n '%27': \"'\",\n '%28': '(',\n '%29': ')',\n '%3B': ';',\n '%3F': '?',\n}\nconst relaxHashEncoding = (value: string) =>\n value.replace(/%(2C|3A|2F|40|24|21|27|28|29|3B|3F)/g, (match) => RELAXED_IN_HASH[match]!)\n\n// `structuredClone` gives each array default a new identity, so `!==` is always true.\n// Without a deep compare, an array default would be written into the URL on every submit.\nconst isSameFilterValue = (a: AllowedFilterValues, b: AllowedFilterValues): boolean => {\n if (isArray(a) && isArray(b)) {\n return a.length === b.length && a.every((item, index) => item === b[index])\n }\n return a === b\n}\n\nconst encodeFilterHash = (\n data: Record<string, AllowedFilterValues>,\n sortBy?: DatatableSortBy,\n page?: Pick<Pagination, 'page' | 'rowsPerPage'>,\n defaultRowsPerPage?: number\n): string => {\n const params = new URLSearchParams()\n for (const key in data) {\n const value = data[key]\n if (isUndefined(value) || isNull(value)) continue\n if (isArray(value) && isEmptyArray(value)) continue\n if (isObject(value) && isEmptyObject(value)) continue\n if (isString(value) && value.length === 0) continue\n params.set(key, isArray(value) ? value.join(',') : String(value))\n }\n if (sortBy) {\n params.set(SORT_URL_PARAM, `${sortBy.key},${sortBy.order}`)\n }\n // Left out on the first page, so a list there keeps the address it had; a non-default page size goes in for F5.\n if (page && page.page > 1) {\n params.set(PAGE_URL_PARAM, String(page.page))\n params.set(ROWS_PER_PAGE_URL_PARAM, String(page.rowsPerPage))\n } else if (page && !isUndefined(defaultRowsPerPage) && page.rowsPerPage !== defaultRowsPerPage) {\n params.set(ROWS_PER_PAGE_URL_PARAM, String(page.rowsPerPage))\n }\n if (params.size === 0) return ''\n return relaxHashEncoding(params.toString()) + END_FILTER_MARKER\n}\n\n/**\n * Hash for a filter link, leaving out values equal to their default. Returns an empty string when nothing differs.\n * Use with `router.push({ name, hash })`. The hash needs the leading `#`, or vue-router appends it to the path.\n * A hash containing `%` (diacritics, `&`, `=`) does not survive the push. Check\n * `isRouterSafeHash` and fall back to setting `window.location.hash` after navigating.\n */\nexport function buildFilterHash<F extends readonly MakeFilterOption<string>[]>(\n filterConfig: FilterConfig<F>,\n filters: Partial<Record<keyof FilterData<F> & string, AllowedFilterValues>>,\n sortBy?: DatatableSortBy\n): string {\n const data: Record<string, AllowedFilterValues> = {}\n for (const [key, value] of Object.entries(filters) as [string, AllowedFilterValues][]) {\n const field = filterConfig.fields[key as keyof FilterConfig<F>['fields']]\n if (isUndefined(field) || isSameFilterValue(value, field.default)) continue\n data[key] = value\n }\n const hash = encodeFilterHash(data, sortBy)\n return hash.length === 0 ? hash : '#' + hash\n}\n\n/** Whether `router.push({ hash })` would leave the hash intact — see `buildFilterHash`. */\nexport const isRouterSafeHash = (hash: string): boolean => !hash.includes('%')\n\nconst defaultRenderOptions: FilerRenderOptions = {\n skip: false,\n selected: true,\n xs: undefined,\n sm: undefined,\n md: undefined,\n lg: undefined,\n xl: undefined,\n}\n\nexport function createFilterStore<F extends readonly MakeFilterOption<string>[]>(filterFields: F): FilterData<F> {\n return reactive(\n filterFields.reduce((acc, field) => {\n return {\n ...acc,\n [field.name]: cloneDeep(field.default),\n }\n }, {} as FilterData<F>)\n ) as FilterData<F>\n}\n\nexport function createFilter<F extends readonly MakeFilterOption<string>[]>(\n filterFields: F,\n store: FilterData<F>,\n options?: Partial<GeneralFilterOptions>\n): {\n filterConfig: FilterConfig<F>\n filterData: FilterData<F>\n} {\n const config = filterFields.reduce(\n (acc, filter) => {\n const key = filter.name as keyof FilterData<F>\n const defaultValue = cloneDeep(filter.default)\n\n return {\n ...acc,\n [key]: {\n name: key as string,\n variant: resolveValue(filter.variant, 'eq'),\n type: resolveValue(filter.type, 'custom'),\n titleT:\n filter.titleT ??\n (options?.system && options?.subject && filter.name\n ? `${options.system}.${options.subject}.filter.${filter.name}`\n : undefined),\n apiName: resolveValue(filter.apiName, filter.name),\n clearable: resolveValue(filter.clearable, true),\n mandatory: resolveValue(filter.mandatory, false),\n multiple: isArray(defaultValue),\n advanced: resolveValue(filter.advanced, false),\n related: resolveValue(filter.related, undefined),\n exclude: resolveValue(filter.exclude, false),\n persist: resolveValue(filter.persist, true),\n default: defaultValue,\n render: { ...defaultRenderOptions, ...resolveValue(filter.render, {}) },\n },\n }\n },\n {} as FilterConfig<F>['fields']\n )\n\n // A time interval names the field holding its upper bound.\n // The query builder and the chips read that config unchecked.\n // Fail here by name rather than with a TypeError on the first query.\n for (const field of Object.values(config) as FilterField[]) {\n if (field.related && !(field.related in config)) {\n throw new Error(`createFilter: \"${field.name}\" names related field \"${field.related}\", which is not configured`)\n }\n }\n\n const defaultGlobalOptions: GeneralFilterOptions = {\n elastic: false,\n system: undefined,\n subject: undefined,\n simpleFilters: false,\n ...options,\n }\n\n if (defaultGlobalOptions.elastic) {\n defaultGlobalOptions.simpleFilters = true\n }\n\n const filterConfig = reactive({\n general: defaultGlobalOptions,\n touched: false,\n fields: config,\n }) as FilterConfig<F>\n\n return {\n filterConfig,\n filterData: store as FilterData<F>,\n }\n}\n\nfunction resolveValue<T>(value: T | undefined, fallback: T): T {\n return isUndefined(value) ? fallback : value\n}\n\nexport function useFilterClearHelpers<\n F extends readonly MakeFilterOption<string>[] = readonly MakeFilterOption<string>[],\n>() {\n const clearOne = (name: keyof FilterData<F>, filterData: FilterData<F>, filterConfig: FilterConfig<F>) => {\n if (!filterConfig.fields[name]?.clearable) return\n filterData[name] = cloneDeep(filterConfig.fields[name].default)\n }\n\n const clearAll = (filterData: FilterData<F>, filterConfig: FilterConfig<F>) => {\n for (const filterName in filterConfig.fields) {\n clearOne(filterName as keyof FilterData<F>, filterData, filterConfig)\n }\n }\n const clearOneFilterSelected = (\n name: string,\n optionValue: number | string,\n filterData: FilterData<F>,\n filterConfig: FilterConfig<F>,\n filterSelected: Ref<Map<string, ValueObjectOption<string | number>[]>>\n ) => {\n if (!isClearable(name, filterConfig)) return\n const config = filterConfig.fields[name as keyof FilterConfig<F>['fields']]\n const selectedFound = filterSelected.value.get(name)\n if (selectedFound && selectedFound.length === 1) {\n filterSelected.value.delete(name)\n } else if (selectedFound) {\n const foundIndex = selectedFound.findIndex((item) => item.value === optionValue)\n if (foundIndex !== -1) selectedFound.splice(foundIndex, 1)\n }\n if (config.type === 'timeInterval' && config.related) {\n filterData[name as keyof FilterData<F>] = config.default\n filterData[config.related as keyof FilterData<F>] =\n filterConfig.fields[config.related as keyof FilterConfig<F>['fields']].default\n } else if (\n isArray(filterData[name as keyof FilterData<F>]) &&\n (filterData[name as keyof FilterData<F>] as any[]).length > 0\n ) {\n const foundIndex = (filterData[name as keyof FilterData<F>] as any[]).findIndex(\n (item) => String(item) === String(optionValue)\n )\n if (foundIndex !== -1) {\n const newArray = [...toRaw(filterData[name as keyof FilterData<F>] as any[])]\n newArray.splice(foundIndex, 1)\n filterData[name as keyof FilterData<F>] = newArray as AllowedFilterValues\n }\n } else if (isString(filterData[name as keyof FilterData<F>]) || isNumber(filterData[name as keyof FilterData<F>])) {\n filterData[name as keyof FilterData<F>] = config.default\n } else if (isBoolean(filterData[name as keyof FilterData<F>])) {\n filterData[name as keyof FilterData<F>] = config.default\n }\n }\n\n const clearAllFilterSelected = (\n filterData: FilterData<F>,\n filterConfig: FilterConfig<F>,\n filterSelected: Ref<Map<string, ValueObjectOption<string | number>[]>>\n ) => {\n for (const key of filterSelected.value.keys()) {\n if (isClearable(key, filterConfig)) {\n filterSelected.value.delete(key)\n }\n }\n }\n\n const isClearable = (name: string, filterConfig: FilterConfig<F>) => {\n const config = filterConfig.fields[name as keyof FilterConfig<F>['fields']]\n return !(config.mandatory || !config.clearable)\n }\n\n return {\n clearOne,\n clearAll,\n clearOneFilterSelected,\n clearAllFilterSelected,\n isClearable,\n }\n}\n\n/**\n * The sort a list had when it first restored its view, before the address or the storage changed it: the list's own\n * default, also one its setup put in after `usePagination`. Kept per pagination, so a pagination a module holds keeps\n * the default of its first visit, not a sort picked before the list was opened again.\n */\nconst listDefaultSort = new WeakMap<Ref<Pagination>, DatatableSortBy>()\n// Its rows per page likewise; on the first page they are stored only when they differ.\nconst listDefaultRowsPerPage = new WeakMap<Ref<Pagination>, number>()\n\nexport interface FilterHelpersMoreOptions {\n storeFiltersLocalStorage: string | boolean // false to disable, string to override store key\n populateUrlParams: boolean\n // Keys the remembered page without turning on local storage. A select dialog sharing its subject with a list\n // sets its own, so searching or paging in it does not change the page Close returns that list to.\n pageStoreKey?: string\n}\n\nconst FilterHelpersMoreOptionsDefault = {\n storeFiltersLocalStorage: true,\n populateUrlParams: true,\n}\n\nexport function useFilterHelpers<F extends readonly MakeFilterOption<string>[] = readonly MakeFilterOption<string>[]>(\n filterData: FilterData<F>,\n filterConfig: FilterConfig<F>,\n moreOptions: Partial<FilterHelpersMoreOptions> = {}\n) {\n const options = { ...FilterHelpersMoreOptionsDefault, ...moreOptions }\n\n let storeKey: undefined | string = undefined\n if (isString(options.storeFiltersLocalStorage)) {\n storeKey = options.storeFiltersLocalStorage\n } else if (\n isBoolean(options.storeFiltersLocalStorage) &&\n true === options.storeFiltersLocalStorage &&\n isString(filterConfig.general.system) &&\n isString(filterConfig.general.subject)\n ) {\n storeKey = 'tableFilter_' + filterConfig.general.system + '_' + filterConfig.general.subject\n }\n\n // The page key exists even when filters are not persisted.\n // A string override distinguishes tables sharing a subject.\n const pageStoreKey =\n options.pageStoreKey ??\n (isString(options.storeFiltersLocalStorage)\n ? options.storeFiltersLocalStorage\n : datatablePageKey(filterConfig.general.system, filterConfig.general.subject))\n // Provided so `ADatatablePagination` picks it up. Guarded because\n // the composable may run outside setup, where Vue would warn.\n if (getCurrentInstance()) {\n provide(DatatablePageStoreKey, pageStoreKey)\n provide(DatatablePageInViewKey, (pagination) => storePageInView(pagination))\n }\n const { consumeStoredPage, getStoredRowsPerPage, getStoredView, setStoredPage } = useDatatablePageStore()\n // The filter and sort a page is shown in. Stored on load, submit and reset, which every change of them goes through.\n const viewOf = (sortBy: DatatableSortBy) => encodeFilterHash(getFilterDataForStoring(), sortBy)\n // `ADatatablePagination` stores the page only when its watcher sees a change. A list that opens on page 1,\n // or returns to it within the tick that restored another page, would keep the older page for the next Close.\n // The pagination of the list, the one load, submit and reset go through. A pager of another\n // pagination under the same provide (a dialog's) must not write this list's address.\n let listPagination: Ref<Pagination> | undefined\n const rememberShownPage = (pagination: Ref<Pagination>) => {\n listPagination = pagination\n setStoredPage(pageStoreKey, pagination.value.page, pagination.value.rowsPerPage, viewOf(pagination.value.sortBy))\n }\n // A page change goes into the address and local storage with the filter and sort,\n // so a reload, a link, Back or a return through the menu shows the same page.\n const storePageInView = (pagination: Ref<Pagination>) => {\n if (pagination !== listPagination) return\n const data = getFilterDataForStoring()\n const serialized = serializeFilters(data, pagination, true, true)\n // Page 1 at the default size is written only to take a stored page out, so a reset's emptied address stays empty.\n if (!PAGE_IN_VIEW.test(serialized) && !hasStoredPage()) return\n updateLocationHash(serialized)\n if (pageFitsStoredView(data)) storeFilterLocalStorage(serialized)\n }\n // The page Close kept. A list that keeps neither filter nor sort (no hash, no local storage) comes back with\n // both reset, and its page 3 would show other rows, so its page comes back only into the view it was shown in.\n // Not checked for other lists: they restore their view themselves, and many adjust the sort or a filter\n // in `getList` after a submit or reset stored the view, which would turn a correct restore into page 1.\n const keepsItsView = options.populateUrlParams || !isUndefined(storeKey)\n const consumeRestoredPage = (sortBy: DatatableSortBy) => {\n const page = consumeStoredPage(pageStoreKey)\n if (page === null || keepsItsView) return page\n const view = getStoredView(pageStoreKey)\n return view === null || view === viewOf(sortBy) ? page : null\n }\n // A restored page comes back at the page size it was shown at. At another size it would show other rows.\n const rowsPerPageFor = (pagination: Ref<Pagination>, restoredPage: number | null) =>\n restoredPage === null\n ? pagination.value.rowsPerPage\n : (getStoredRowsPerPage(pageStoreKey) ?? pagination.value.rowsPerPage)\n\n const { clearAll } = useFilterClearHelpers<F>()\n\n const getFilterDataForStoring = (): Record<string, AllowedFilterValues> => {\n const data: Record<string, AllowedFilterValues> = {}\n for (const filterName in filterData) {\n try {\n const key = filterName as keyof FilterData<F>\n const value = filterData[key]\n if (\n !isUndefined(value) &&\n !isNull(value) &&\n !isEmptyArray(value) &&\n !isSameFilterValue(value, filterConfig.fields[key].default)\n ) {\n data[filterName] = value\n }\n } catch (e) {\n // Ignore errors\n }\n }\n return data\n }\n\n // Fields whose value lives in the address only (`persist: false`). Local storage never holds them.\n const addressOnlyFields = (): string[] =>\n (Object.values(filterConfig.fields) as FilterField[])\n .filter((field) => field.persist === false)\n .map((field) => field.name)\n\n const withoutAddressOnly = (data: Record<string, AllowedFilterValues>): Record<string, AllowedFilterValues> => {\n const fields = addressOnlyFields()\n if (fields.length === 0) return data\n const kept = { ...data }\n for (const name of fields) delete kept[name]\n return kept\n }\n\n // A field kept in the address takes its value from the hash, else its default. The filter store may still hold\n // the value a link gave it on an earlier visit, and a list opened from the menu would silently show it.\n const resetAddressOnlyFields = (fromHash: Record<string, AllowedFilterValues> | undefined) => {\n for (const name of addressOnlyFields()) {\n if (fromHash && !isUndefined(fromHash[name])) continue\n const key = name as keyof FilterData<F>\n filterData[key] = cloneDeep(filterConfig.fields[key].default)\n }\n }\n\n const serializeFilters = (\n data: Record<string, AllowedFilterValues>,\n pagination: Ref<Pagination>,\n includeSort: boolean,\n includePage = false\n ): string => {\n return encodeFilterHash(\n data,\n includeSort ? pagination.value.sortBy : undefined,\n includePage ? pagination.value : undefined,\n listDefaultRowsPerPage.get(pagination)\n )\n }\n\n const deserializeFilters = (\n hash: string\n ): {\n filters: Record<string, AllowedFilterValues>\n sortBy: DatatableSortBy\n page?: number\n rowsPerPage?: number\n } | null => {\n if (!hash) return null\n if (hash.startsWith('#')) hash = hash.substring(1)\n\n // `URLSearchParams` encodes `~` in values, so the marker never occurs in our data.\n // A hash without it is foreign or truncated. `null` lets localStorage take over.\n const markerIndex = hash.indexOf(END_FILTER_MARKER)\n if (markerIndex === -1) return null\n hash = hash.slice(0, markerIndex)\n\n const params = new URLSearchParams(hash)\n const result: Record<string, AllowedFilterValues> = {}\n let sortBy: DatatableSortBy = null\n\n const sortParam = params.get(SORT_URL_PARAM)\n if (sortParam) {\n const [key, order] = sortParam.split(',')\n if (key && (order === SortOrder.Asc || order === SortOrder.Desc)) {\n sortBy = { key, order }\n }\n params.delete(SORT_URL_PARAM)\n }\n\n // `_limit` without `_page` is of the first page; an unusable `_page` drops `_limit` too.\n const pageParam = params.get(PAGE_URL_PARAM)\n const page = isNull(pageParam) ? 1 : positiveInteger(pageParam)\n const rowsPerPage = positiveInteger(params.get(ROWS_PER_PAGE_URL_PARAM), MAX_ROWS_PER_PAGE)\n params.delete(PAGE_URL_PARAM)\n params.delete(ROWS_PER_PAGE_URL_PARAM)\n\n for (const [key, value] of params.entries()) {\n const fieldConfig = filterConfig.fields[key as keyof typeof filterConfig.fields]\n if (isUndefined(fieldConfig)) {\n console.error(`Filter config not found for ${key}`)\n continue\n }\n const isMultiple = fieldConfig.multiple ?? false\n\n if (isMultiple) {\n const items = value.split(',')\n\n const allNumeric = items.every((item) => item !== '' && String(Number(item)) === item)\n\n result[key] = allNumeric ? items.map(Number) : items\n } else {\n result[key] = value\n }\n }\n\n // A page without its rows per page is left out: it would show other rows at the list's page size.\n const hasPage = !isUndefined(page) && !isUndefined(rowsPerPage)\n\n // An empty result would still count as \"found\", shadowing localStorage.\n if (isEmptyObject(result) && isNull(sortBy) && !hasPage) return null\n\n return hasPage ? { filters: result, sortBy, page, rowsPerPage } : { filters: result, sortBy }\n }\n\n // A submit replaces the history entry instead of adding one.\n // `replaceState` fires no popstate, so vue-router runs no navigation or guards per submit.\n // Its `current` is patched so the router's next push, which rewrites this entry, keeps the hash.\n const replaceHash = (hash: string) => {\n const url = window.location.pathname + window.location.search + hash\n const state = window.history.state\n const patched =\n isObject(state) && isString((state as { current?: unknown }).current)\n ? { ...state, current: ((state as { current: string }).current.split('#')[0] ?? '') + hash }\n : state\n window.history.replaceState(patched, '', url)\n }\n\n const updateLocationHash = (serialized: string) => {\n if (options.populateUrlParams === false) return\n replaceHash('#' + serialized)\n }\n\n const resetLocationHash = () => {\n if (options.populateUrlParams === false) return\n replaceHash('')\n }\n\n const parseLocationHash = () => {\n if (options.populateUrlParams === false) return null\n return deserializeFilters(window.location.hash)\n }\n\n const storeFilterLocalStorage = (serialized: string) => {\n if (!storeKey || !localStorage) return\n localStorage.setItem(storeKey, serialized)\n }\n\n // The saved view without the fields kept in the address, also when it was saved before they were.\n const readStoredView = (): string | null => {\n if (!storeKey || !localStorage) return null\n const stored = localStorage.getItem(storeKey)\n if (!stored || !isString(stored)) return null\n const fields = addressOnlyFields()\n const markerIndex = stored.indexOf(END_FILTER_MARKER)\n if (fields.length === 0 || markerIndex === -1) return stored\n const params = new URLSearchParams(stored.slice(0, markerIndex))\n if (!fields.some((name) => params.has(name))) return stored\n for (const name of fields) params.delete(name)\n return params.size === 0 ? '' : relaxHashEncoding(params.toString()) + END_FILTER_MARKER\n }\n\n const loadFilterLocalStorage = () => {\n const stored = readStoredView()\n if (!stored) return null\n return deserializeFilters(stored)\n }\n\n const hasStoredPage = () =>\n (options.populateUrlParams !== false && PAGE_IN_VIEW.test(window.location.hash)) ||\n (!isUndefined(storeKey) && !!localStorage && PAGE_IN_VIEW.test(localStorage.getItem(storeKey) ?? ''))\n\n const hasAddressOnlyValue = (data: Record<string, AllowedFilterValues>) =>\n addressOnlyFields().some((name) => !isUndefined(data[name]))\n\n // The filter fields of a serialized view, without its sort and page, in one order.\n const filterFieldsOf = (serialized: string): string => {\n const markerIndex = serialized.indexOf(END_FILTER_MARKER)\n const params = new URLSearchParams(markerIndex === -1 ? serialized : serialized.slice(0, markerIndex))\n params.delete(SORT_URL_PARAM)\n params.delete(PAGE_URL_PARAM)\n params.delete(ROWS_PER_PAGE_URL_PARAM)\n params.sort()\n return params.toString()\n }\n\n // Local storage takes a page only with the view it restores. A view it cannot restore (a field kept in the address)\n // or another view than the one it holds (a link naming a page but no field) leaves it as it is: the menu would\n // open the saved view, or the whole list, on the page of another one. The sort is not compared, as lists switch it\n // in `getList` after a submit (a text search sorted by score), and their page would never be kept.\n const pageFitsStoredView = (data: Record<string, AllowedFilterValues>): boolean => {\n if (hasAddressOnlyValue(data)) return false\n const stored = readStoredView()\n if (!stored || !stored.includes(END_FILTER_MARKER)) return true\n return filterFieldsOf(stored) === filterFieldsOf(encodeFilterHash(data))\n }\n\n // A list that keeps its view goes back to its default sort and page size too, as a reload of the emptied address\n // and storage opens the defaults (#87746).\n const resetFilter = (pagination: Ref<Pagination>, callback?: AnyFn) => {\n const sortBy =\n keepsItsView && listDefaultSort.has(pagination)\n ? cloneDeep(listDefaultSort.get(pagination) as DatatableSortBy)\n : pagination.value.sortBy\n const defaultRowsPerPage = listDefaultRowsPerPage.get(pagination)\n const rowsPerPage =\n keepsItsView && !isUndefined(defaultRowsPerPage) ? defaultRowsPerPage : pagination.value.rowsPerPage\n pagination.value = { ...pagination.value, sortBy, rowsPerPage, page: 1 }\n rememberShownPage(pagination)\n if (storeKey && localStorage) {\n localStorage.removeItem(storeKey)\n }\n resetLocationHash()\n filterConfig.touched = false\n if (callback) callback()\n }\n\n const submitFilter = (pagination: Ref<Pagination>, callback?: AnyFn) => {\n const data = getFilterDataForStoring()\n pagination.value = { ...pagination.value, page: 1 }\n updateLocationHash(serializeFilters(data, pagination, true, true))\n storeFilterLocalStorage(serializeFilters(withoutAddressOnly(data), pagination, true, true))\n rememberShownPage(pagination)\n filterConfig.touched = false\n if (callback) callback()\n }\n\n const loadStoredFilters = (pagination: Ref<Pagination>, callback?: AnyFn) => {\n if (!listDefaultSort.has(pagination)) listDefaultSort.set(pagination, cloneDeep(pagination.value.sortBy))\n if (!listDefaultRowsPerPage.has(pagination)) listDefaultRowsPerPage.set(pagination, pagination.value.rowsPerPage)\n let source: 'hash' | 'localStorage' = 'hash'\n let storedFromHash = parseLocationHash()\n if (isNull(storedFromHash)) {\n source = 'localStorage'\n storedFromHash = loadFilterLocalStorage()\n }\n resetAddressOnlyFields(source === 'hash' && storedFromHash ? storedFromHash.filters : undefined)\n if (\n isNull(storedFromHash) ||\n (isEmptyObject(storedFromHash.filters) && isNull(storedFromHash.sortBy) && isUndefined(storedFromHash.page))\n ) {\n const restoredPage = consumeRestoredPage(pagination.value.sortBy)\n if (restoredPage !== null) {\n pagination.value = {\n ...pagination.value,\n page: restoredPage,\n rowsPerPage: rowsPerPageFor(pagination, restoredPage),\n }\n }\n rememberShownPage(pagination)\n if (callback) callback()\n return false\n }\n\n // A hash naming at least one field describes the whole view, whether\n // from a link or from going back. Reset the fields it omits.\n // Otherwise they keep values from the module-level store, and the same link lands\n // differently. Local storage still merges, since it omits fields equal to their default.\n // A `_sort`-only hash is excluded. It can come from a link for\n // another table on the same page and must not wipe this filter.\n // Only `clearable` fields are reset.\n const hashDescribesThisView = source === 'hash' && !isEmptyObject(storedFromHash.filters)\n if (hashDescribesThisView) {\n clearAll(filterData, filterConfig)\n }\n\n for (const filterName in filterData) {\n const key = filterName as keyof FilterData<F>\n let value = storedFromHash.filters[key]\n if (isUndefined(value)) continue\n if (isString(value)) {\n const tryConvertNumber = stringToNumber(value)\n if (!isNull(tryConvertNumber) && String(tryConvertNumber) === value) {\n value = tryConvertNumber\n } else {\n const tryConvertBoolean = stringToBooleanExact(value)\n if (!isNull(tryConvertBoolean)) {\n value = tryConvertBoolean\n }\n }\n }\n filterData[key] = value\n }\n if (source === 'localStorage') {\n const stored = readStoredView()\n if (stored) {\n updateLocationHash(stored)\n }\n }\n // A link may omit the sort. Taking `null` would drop `order[...]` from\n // the query, and paging without ORDER BY can repeat or skip rows.\n const sortBy = storedFromHash.sortBy ?? pagination.value.sortBy\n // Always consumed. The flag means \"the next list should restore\n // its page\". Leaving it set would pass the page to the next table.\n const restoredPage = consumeRestoredPage(sortBy)\n const storedPage = restoredPage === null ? storedFromHash.page : undefined\n pagination.value = {\n ...pagination.value,\n sortBy,\n // A link starts at the page it names, else the first. A restored page still wins.\n // Only the close button sets that flag, meaning the user returns\n // to this list, and that address carries the list's own hash.\n page: restoredPage ?? storedPage ?? (source === 'hash' ? 1 : pagination.value.page),\n rowsPerPage: isUndefined(storedPage)\n ? rowsPerPageFor(pagination, restoredPage)\n : (storedFromHash.rowsPerPage ?? pagination.value.rowsPerPage),\n }\n rememberShownPage(pagination)\n if (hashDescribesThisView) {\n // Local storage mirrors the last applied state, so a link becomes the view the user returns to.\n // Re-serialized to drop values equal to their default. A sort-only hash does not overwrite it.\n // Without the page when a field kept in the address is left out: the page is of the view with that field.\n const data = getFilterDataForStoring()\n storeFilterLocalStorage(serializeFilters(withoutAddressOnly(data), pagination, true, !hasAddressOnlyValue(data)))\n }\n if (callback) callback()\n return true\n }\n\n return {\n loadStoredFilters,\n resetFilter,\n submitFilter,\n serializeFilters,\n deserializeFilters,\n }\n}\n\n/**\n * Provides the filter (`FilterConfigKey`, `FilterDataKey`) and `pagination` (`DatatablePaginationKey`)\n * to the filter bar and `ADatatablePagination` below, and wires the list to them.\n * `getList` is a debounced `fetchList(pagination, filterData, filterConfig)` that resolves when\n * the load finishes. A call superseded within the debounce resolves at once without loading.\n * Submit, reset and sort go through `useFilterHelpers` (with `filterHelpersOptions`).\n * On mount the stored filter and remembered page are restored before the first load.\n * Use only for a datatable that is the parent of its filter bar. Wire it by hand when the first load skips the stored\n * filter, `getList` adds logic, sort is custom, `fetchList` takes other arguments, or a parent renders the filter bar.\n * @example\n * const { filterData, filterConfig } = useFaqListFilter()\n * const { fetchList, listItems } = useFaqListActions()\n * const { pagination } = usePagination(SORT_BY_ID)\n * const { getList, sortByChange, submitFilterAction, resetFilterAction\n * } = useDatatableList(filterData, filterConfig, pagination, fetchList)\n */\nexport function useDatatableList<\n F extends readonly MakeFilterOption<string>[] = readonly MakeFilterOption<string>[],\n R = unknown,\n>(\n filterData: FilterData<F>,\n filterConfig: FilterConfig<F>,\n pagination: Ref<Pagination>,\n fetchList: (pagination: Ref<Pagination>, filterData: FilterData<F>, filterConfig: FilterConfig<F>) => R,\n filterHelpersOptions: Partial<FilterHelpersMoreOptions> = {}\n) {\n provide(FilterConfigKey, filterConfig as FilterConfig)\n provide(FilterDataKey, filterData as FilterData)\n provide(DatatablePaginationKey, pagination)\n const { resetFilter, submitFilter, loadStoredFilters } = useFilterHelpers(\n filterData,\n filterConfig,\n filterHelpersOptions\n )\n const getList = useDebounceFn(() => fetchList(pagination, filterData, filterConfig))\n const submitFilterAction = () => submitFilter(pagination, getList)\n const resetFilterAction = () => resetFilter(pagination, getList)\n onMounted(() => loadStoredFilters(pagination, getList))\n return { getList, sortByChange: submitFilterAction, submitFilterAction, resetFilterAction }\n}\n\nexport type AllowedFilterValues = number | number[] | string | string[] | null | undefined | boolean\n\nexport interface GeneralFilterOptions {\n system?: string\n subject?: string\n elastic?: boolean\n simpleFilters?: boolean\n}\n\nexport interface FilerRenderOptions {\n skip: boolean\n // Whether the field shows as a chip in `FiltersSelected`. Default true.\n // Optional because other admins may construct `FilerRenderOptions`.\n selected?: boolean\n xs: number | undefined\n sm: number | undefined\n md: number | undefined\n lg: number | undefined\n xl: number | undefined\n}\n\nexport type FilterVariant =\n | 'search'\n | 'lt'\n | 'in'\n | 'notIn'\n | 'endsWith'\n | 'startsWith'\n | 'memberOf'\n | 'neq'\n | 'gte'\n | 'gt'\n | 'eq'\n | 'lte'\n | 'custom'\n\nexport type FilterType = 'boolean' | 'datetime' | 'integer' | 'string' | 'custom' | 'timeInterval'\n\nexport interface MakeFilterOption<TName extends string = string> {\n name: TName\n default: AllowedFilterValues\n type?: FilterType\n variant?: FilterVariant\n titleT?: string\n apiName?: string\n clearable?: boolean\n mandatory?: boolean\n advanced?: boolean\n exclude?: boolean\n /**\n * `false` keeps the field's value in the address only, for a field a link sets (a hidden id of a group, of a\n * record): it applies from the URL hash and goes into the hash and the API query as any other, but is never written\n * to local storage (`storeFiltersLocalStorage`) and never read back from it, also from a value saved before. A list\n * loaded without it in the hash shows it at its default, also when the filter store still holds it from an earlier\n * visit. A bookmark keeps it, as the user saves it on purpose. Default `true`.\n */\n persist?: boolean\n related?: string | undefined\n render?: Partial<FilerRenderOptions>\n}\n\nexport interface FilterField {\n name: string\n type: FilterType\n variant: FilterVariant\n titleT?: string\n default: AllowedFilterValues\n apiName: string\n clearable: boolean\n mandatory: boolean\n multiple: boolean\n advanced: boolean\n exclude: boolean\n /** See `MakeFilterOption.persist`. Optional for a field built by hand; missing reads as `true`. */\n persist?: boolean\n related: string | undefined\n render: FilerRenderOptions\n}\n\nexport type FilterConfig<F extends readonly MakeFilterOption<string>[] = readonly MakeFilterOption<string>[]> = {\n general: GeneralFilterOptions\n touched: boolean\n fields: {\n [P in F[number]['name']]: FilterField\n }\n}\n\nexport type FilterData<F extends readonly MakeFilterOption<string>[] = readonly MakeFilterOption<string>[]> = {\n [P in F[number]['name']]: AllowedFilterValues\n}\n"],"mappings":";;;;;;;;AA+BA,IAAM0B,IAAiB,SAEjBC,I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IACnByF,KAAUA,EAAS;EACzB;EA2GE,eAzGoBlD,GAA6BkD,MAAqB;GACtE,IAAMhG,IAAOqD,EAAwB;GACrCP,EAAW,QAAQ;IAAE,GAAGA,EAAW;IAAO,MAAM;GAAE,GAClDa,EAAmBF,EAAiBzD,GAAM8C,GAAY,IAAM,EAAI,CAAC,GACjEe,EAAwBJ,EAAiBW,EAAmBpE,CAAI,GAAG8C,GAAY,IAAM,EAAI,CAAC,GAC1FS,EAAkBT,CAAU,GAC5BvC,EAAa,UAAU,IACnByF,KAAUA,EAAS;EACzB;EAkGEvC;EACAkB;CACF;AACF;AAkBA,SAAgB4B,EAId3E,GACArB,GACAuC,GACA0D,GACAC,IAA0D,CAAC,GAC3D;CACApJ,EAAQS,GAAiByC,CAA4B,GACrDlD,EAAQU,GAAe6D,CAAwB,GAC/CvE,EAAQQ,GAAwBiF,CAAU;CAC1C,IAAM,EAAE4D,gBAAaC,iBAAcC,yBAAsBlE,EACvDd,GACArB,GACAkG,CACF,GACMI,IAAUrJ,QAAoBgJ,EAAU1D,GAAYlB,GAAYrB,CAAY,CAAC,GAC7EuG,UAA2BH,EAAa7D,GAAY+D,CAAO;CAGjE,OADAzJ,QAAgBwJ,EAAkB9D,GAAY+D,CAAO,CAAC,GAC/C;EAAEA;EAAS,cAAcC;EAAoBA;EAAoB,yBAFxCJ,EAAY5D,GAAY+D,CAAO;CAE2B;AAC5F"}
@@ -83,17 +83,17 @@ function r(r) {
83
83
  return;
84
84
  case "Escape":
85
85
  if (u) {
86
- t.preventDefault();
86
+ t.preventDefault(), t.stopPropagation();
87
87
  let e = a.value;
88
88
  a.value = null, r.onGrabCancel?.(e), m(e);
89
89
  return;
90
90
  }
91
91
  if (c) {
92
- t.preventDefault(), r.onCancelReorder?.();
92
+ t.preventDefault(), t.stopPropagation(), r.onCancelReorder?.();
93
93
  return;
94
94
  }
95
95
  if (r.isEditing(e)) {
96
- t.preventDefault(), r.onCancelEdit?.(e);
96
+ t.preventDefault(), t.stopPropagation(), r.onCancelEdit?.(e);
97
97
  return;
98
98
  }
99
99
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"useKeyboardNav.js","names":["el","computed","ref","watch","useKeyboardNav","options","focusedKey","grabbedKey","orderedKeys","v","isFocused","key","isGrabbed","grabbedIndex","totalCount","rowTabindex","ordered","focusRowElement","setFocus","refocusIfLost","active","prevOrderedKeys","now","oldIndex","inReorder","releaseGrab","isFormField","target","isOwnControl","handleKeydown","e","focusedItem","isGrabbedNow","grabbedSomewhere","onFormField","grabbed"],"sources":["../../../../src/domains/listEditor/composables/useKeyboardNav.ts"],"sourcesContent":["import { computed, ref, watch, type ComputedRef, type Ref } from 'vue'\nimport type { ListEditorKey } from '@/domains/listEditor/types/listEditorTypes'\n\nexport interface KeyboardNavViewItem {\n key: ListEditorKey\n expanded?: boolean\n canExpand?: boolean\n canIndent?: boolean\n canOutdent?: boolean\n}\n\nexport type KeyboardNavVariant = 'flat' | 'sortable' | 'nested'\n\nexport interface KeyboardNavOptions {\n viewItems: ComputedRef<KeyboardNavViewItem[]>\n variant: KeyboardNavVariant\n isReorderMode: Ref<boolean> | ComputedRef<boolean>\n disabled?: Ref<boolean> | ComputedRef<boolean>\n\n isEditing: (key: ListEditorKey) => boolean\n\n onToggleEdit?: (key: ListEditorKey) => void\n onCancelEdit?: (key: ListEditorKey) => void\n\n onMoveUp?: (key: ListEditorKey) => void\n onMoveDown?: (key: ListEditorKey) => void\n onMoveTop?: (key: ListEditorKey) => void\n onMoveBottom?: (key: ListEditorKey) => void\n\n onIndent?: (key: ListEditorKey) => void\n onOutdent?: (key: ListEditorKey) => void\n onToggleChildren?: (key: ListEditorKey, expand: boolean) => void\n\n /** A row was picked up with Enter/Space in reorder mode. */\n onGrab?: (key: ListEditorKey) => void\n /** Escape dropped the grab: put the row back where `onGrab` found it. */\n onGrabCancel?: (key: ListEditorKey) => void\n\n onCancelReorder?: () => void\n}\n\nexport interface KeyboardNavApi {\n focusedKey: Ref<ListEditorKey | null>\n grabbedKey: Ref<ListEditorKey | null>\n /** 0-based index of the grabbed row in the current ordering, or -1 if no grab. */\n grabbedIndex: ComputedRef<number>\n /** Total count of rows currently in the editor. */\n totalCount: ComputedRef<number>\n isFocused: (key: ListEditorKey) => boolean\n isGrabbed: (key: ListEditorKey) => boolean\n rowTabindex: (key: ListEditorKey) => number\n setFocus: (key: ListEditorKey | null) => void\n releaseGrab: () => void\n handleKeydown: (key: ListEditorKey, e: KeyboardEvent) => void\n}\n\n// Roving tabindex + keyboard navigation for list-editor rows. Single tabstop\n// per editor; arrow keys move an internal pointer; reorder mode adds a \"grab\"\n// state where Enter/Space picks up the focused row and arrows move it.\nexport function useKeyboardNav(options: KeyboardNavOptions): KeyboardNavApi {\n const focusedKey = ref<ListEditorKey | null>(null)\n const grabbedKey = ref<ListEditorKey | null>(null)\n\n const orderedKeys = computed<ListEditorKey[]>(() => options.viewItems.value.map((v) => v.key))\n\n const isFocused = (key: ListEditorKey): boolean => focusedKey.value === key\n const isGrabbed = (key: ListEditorKey): boolean => grabbedKey.value === key\n\n const grabbedIndex = computed<number>(() => {\n if (grabbedKey.value === null) return -1\n return orderedKeys.value.indexOf(grabbedKey.value)\n })\n\n const totalCount = computed<number>(() => orderedKeys.value.length)\n\n function rowTabindex(key: ListEditorKey): number {\n const ordered = orderedKeys.value\n if (ordered.length === 0) return -1\n if (focusedKey.value === null) return ordered[0] === key ? 0 : -1\n return focusedKey.value === key ? 0 : -1\n }\n\n function focusRowElement(key: ListEditorKey | null) {\n if (key === null || typeof document === 'undefined') return\n void Promise.resolve().then(() => {\n const el = document.querySelector<HTMLElement>(`[data-id=\"${CSS.escape(String(key))}\"]`)\n el?.focus()\n })\n }\n\n function setFocus(key: ListEditorKey | null) {\n focusedKey.value = key\n focusRowElement(key)\n }\n\n // A move can re-create the grabbed row's element (indent/outdent puts it under another parent),\n // which drops focus to <body> and every further key with it.\n function refocusIfLost(key: ListEditorKey) {\n if (typeof document === 'undefined') return\n void Promise.resolve().then(() => {\n const active = document.activeElement\n if (!active || active === document.body) setFocus(key)\n })\n }\n\n // When the focused row is removed (e.g. via delete), fall to the row that\n // took its slot, or to the new last row if it was at the end. Without this,\n // focus vanishes to <body> after a delete and the user has to Tab back in.\n // We snapshot the previous ordering so we can look up where the focused key\n // *was* — by the time the watcher fires, the key is already gone from `now`.\n // eslint-disable-next-line vue/no-ref-object-reactivity-loss\n let prevOrderedKeys: ListEditorKey[] = [...orderedKeys.value]\n watch(orderedKeys, (now) => {\n if (focusedKey.value === null) {\n prevOrderedKeys = [...now]\n return\n }\n if (now.includes(focusedKey.value)) {\n prevOrderedKeys = [...now]\n return\n }\n if (now.length === 0) {\n focusedKey.value = null\n prevOrderedKeys = []\n return\n }\n const oldIndex = prevOrderedKeys.indexOf(focusedKey.value)\n const fallbackIndex = Math.min(Math.max(oldIndex, 0), now.length - 1)\n setFocus(now[fallbackIndex]!)\n prevOrderedKeys = [...now]\n })\n\n // Releasing a grab when the grabbed row is no longer in the list — keeps the\n // grab state consistent if the row gets removed externally.\n watch(orderedKeys, (now) => {\n if (grabbedKey.value !== null && !now.includes(grabbedKey.value)) {\n grabbedKey.value = null\n }\n })\n\n watch(options.isReorderMode, (inReorder) => {\n if (!inReorder) grabbedKey.value = null\n })\n\n function releaseGrab() {\n grabbedKey.value = null\n }\n\n function isFormField(target: EventTarget | null): boolean {\n const el = target as HTMLElement | null\n return !!el?.matches?.('input, textarea, select, [contenteditable], [contenteditable=\"true\"]')\n }\n\n // A row's own buttons and links (move up/down, edit, delete, menus) activate on Enter/Space themselves.\n function isOwnControl(target: EventTarget | null): boolean {\n const el = target as HTMLElement | null\n return !!el?.matches?.(\n 'button, a[href], summary, [role=\"button\"], [role=\"link\"], [role=\"menuitem\"], [role=\"checkbox\"], [role=\"switch\"], [role=\"tab\"], [role=\"option\"]'\n )\n }\n\n function handleKeydown(key: ListEditorKey, e: KeyboardEvent) {\n // A nested row's keydown bubbles into its ancestor rows; every key handled below calls\n // `preventDefault`, so an ancestor does not act on it a second time for its own row.\n if (e.defaultPrevented) return\n if (options.disabled?.value) return\n\n const ordered = orderedKeys.value\n const i = ordered.indexOf(key)\n if (i < 0) return\n\n // `ordered` is these view items' keys, so `i` indexes them too.\n const focusedItem = options.viewItems.value[i]!\n const inReorder = options.isReorderMode.value\n const isGrabbedNow = grabbedKey.value === key\n const grabbedSomewhere = grabbedKey.value !== null\n\n // Form fields keep native key behavior (cursor, newlines, selection) for\n // every key except Escape. Esc still closes the edit panel even mid-typing.\n const onFormField = isFormField(e.target)\n\n switch (e.key) {\n case 'ArrowUp':\n if (onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow) {\n options.onMoveUp?.(key)\n refocusIfLost(key)\n } else if (i > 0) {\n setFocus(ordered[i - 1]!)\n }\n return\n\n case 'ArrowDown':\n if (onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow) {\n options.onMoveDown?.(key)\n refocusIfLost(key)\n } else if (i < ordered.length - 1) {\n setFocus(ordered[i + 1]!)\n }\n return\n\n case 'Home':\n if (onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow) {\n options.onMoveTop?.(key)\n refocusIfLost(key)\n } else if (ordered.length > 0) {\n setFocus(ordered[0]!)\n }\n return\n\n case 'End':\n if (onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow) {\n options.onMoveBottom?.(key)\n refocusIfLost(key)\n } else if (ordered.length > 0) {\n setFocus(ordered[ordered.length - 1]!)\n }\n return\n\n case 'ArrowLeft':\n if (options.variant !== 'nested' || onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow && focusedItem.canOutdent) {\n options.onOutdent?.(key)\n refocusIfLost(key)\n } else if (focusedItem.expanded) {\n options.onToggleChildren?.(key, false)\n }\n return\n\n case 'ArrowRight':\n if (options.variant !== 'nested' || onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow && focusedItem.canIndent) {\n options.onIndent?.(key)\n refocusIfLost(key)\n } else if (focusedItem.canExpand && !focusedItem.expanded) {\n options.onToggleChildren?.(key, true)\n }\n return\n\n case 'Enter':\n case ' ': // Space\n if (onFormField || isOwnControl(e.target)) return\n e.preventDefault()\n if (inReorder) {\n if (isGrabbedNow) {\n grabbedKey.value = null\n } else {\n grabbedKey.value = key\n options.onGrab?.(key)\n }\n } else {\n options.onToggleEdit?.(key)\n }\n return\n\n case 'Escape':\n if (grabbedSomewhere) {\n e.preventDefault()\n const grabbed = grabbedKey.value!\n grabbedKey.value = null\n options.onGrabCancel?.(grabbed)\n refocusIfLost(grabbed)\n return\n }\n if (inReorder) {\n e.preventDefault()\n options.onCancelReorder?.()\n return\n }\n if (options.isEditing(key)) {\n e.preventDefault()\n options.onCancelEdit?.(key)\n return\n }\n return\n\n default:\n return\n }\n }\n\n return {\n focusedKey,\n grabbedKey,\n grabbedIndex,\n totalCount,\n isFocused,\n isGrabbed,\n rowTabindex,\n setFocus,\n releaseGrab,\n handleKeydown,\n }\n}\n"],"mappings":";;AA2DA,SAAgBI,EAAeC,GAA6C;CAC1E,IAAMC,IAAaJ,EAA0B,IAAI,GAC3CK,IAAaL,EAA0B,IAAI,GAE3CM,IAAcP,QAAgCI,EAAQ,UAAU,MAAM,KAAKI,MAAMA,EAAE,GAAG,CAAC,GAEvFC,KAAaC,MAAgCL,EAAW,UAAUK,GAClEC,KAAaD,MAAgCJ,EAAW,UAAUI,GAElEE,IAAeZ,QACfM,EAAW,UAAU,OAAa,KAC/BC,EAAY,MAAM,QAAQD,EAAW,KAAK,CAClD,GAEKO,IAAab,QAAuBO,EAAY,MAAM,MAAM;CAElE,SAASO,EAAYJ,GAA4B;EAC/C,IAAMK,IAAUR,EAAY;EAG5B,OAFIQ,EAAQ,WAAW,IAAU,KAC7BV,EAAW,UAAU,OAAaU,EAAQ,OAAOL,IAAM,IAAI,KACxDL,EAAW,UAAUK,IAAM,IAAI;CACxC;CAEA,SAASM,EAAgBN,GAA2B;EAC9CA,MAAQ,QAAQ,OAAO,WAAa,OACnC,QAAQ,QAAQ,CAA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Q,mBAAmBM,GAAK,EAAK;IAEvC;GAEF,KAAK;IACH,IAAIN,EAAQ,YAAY,YAAY6B,GAAa;IACjDJ,EAAE,eAAe,GACbN,KAAaQ,KAAgBD,EAAY,aAC3C1B,EAAQ,WAAWM,CAAG,GACtBQ,EAAcR,CAAG,KACRoB,EAAY,aAAa,CAACA,EAAY,YAC/C1B,EAAQ,mBAAmBM,GAAK,EAAI;IAEtC;GAEF,KAAK;GACL,KAAK;IACH,IAAIuB,KAAeN,EAAaE,EAAE,MAAM,GAAG;IAC3CA,EAAE,eAAe,GACbN,IACEQ,IACFzB,EAAW,QAAQ,QAEnBA,EAAW,QAAQI,GACnBN,EAAQ,SAASM,CAAG,KAGtBN,EAAQ,eAAeM,CAAG;IAE5B;GAEF,KAAK;IACH,IAAIsB,GAAkB;KACpBH,EAAE,eAAe;KACjB,IAAMK,IAAU5B,EAAW;KAC3BA,EAAW,QAAQ,MACnBF,EAAQ,eAAe8B,CAAO,GAC9BhB,EAAcgB,CAAO;KACrB;IACF;IACA,IAAIX,GAAW;KACbM,EAAE,eAAe,GACjBzB,EAAQ,kBAAkB;KAC1B;IACF;IACA,IAAIA,EAAQ,UAAUM,CAAG,GAAG;KAC1BmB,EAAE,eAAe,GACjBzB,EAAQ,eAAeM,CAAG;KAC1B;IACF;IACA;GAEF,SACE;EACJ;CACF;CAEA,OAAO;EACLL;EACAC;EACAM;EACAC;EACAJ;EACAE;EACAG;EACAG;EACAO;EACAI;CACF;AACF"}
1
+ {"version":3,"file":"useKeyboardNav.js","names":["el","computed","ref","watch","useKeyboardNav","options","focusedKey","grabbedKey","orderedKeys","v","isFocused","key","isGrabbed","grabbedIndex","totalCount","rowTabindex","ordered","focusRowElement","setFocus","refocusIfLost","active","prevOrderedKeys","now","oldIndex","inReorder","releaseGrab","isFormField","target","isOwnControl","handleKeydown","e","focusedItem","isGrabbedNow","grabbedSomewhere","onFormField","grabbed"],"sources":["../../../../src/domains/listEditor/composables/useKeyboardNav.ts"],"sourcesContent":["import { computed, ref, watch, type ComputedRef, type Ref } from 'vue'\nimport type { ListEditorKey } from '@/domains/listEditor/types/listEditorTypes'\n\nexport interface KeyboardNavViewItem {\n key: ListEditorKey\n expanded?: boolean\n canExpand?: boolean\n canIndent?: boolean\n canOutdent?: boolean\n}\n\nexport type KeyboardNavVariant = 'flat' | 'sortable' | 'nested'\n\nexport interface KeyboardNavOptions {\n viewItems: ComputedRef<KeyboardNavViewItem[]>\n variant: KeyboardNavVariant\n isReorderMode: Ref<boolean> | ComputedRef<boolean>\n disabled?: Ref<boolean> | ComputedRef<boolean>\n\n isEditing: (key: ListEditorKey) => boolean\n\n onToggleEdit?: (key: ListEditorKey) => void\n onCancelEdit?: (key: ListEditorKey) => void\n\n onMoveUp?: (key: ListEditorKey) => void\n onMoveDown?: (key: ListEditorKey) => void\n onMoveTop?: (key: ListEditorKey) => void\n onMoveBottom?: (key: ListEditorKey) => void\n\n onIndent?: (key: ListEditorKey) => void\n onOutdent?: (key: ListEditorKey) => void\n onToggleChildren?: (key: ListEditorKey, expand: boolean) => void\n\n /** A row was picked up with Enter/Space in reorder mode. */\n onGrab?: (key: ListEditorKey) => void\n /** Escape dropped the grab: put the row back where `onGrab` found it. */\n onGrabCancel?: (key: ListEditorKey) => void\n\n onCancelReorder?: () => void\n}\n\nexport interface KeyboardNavApi {\n focusedKey: Ref<ListEditorKey | null>\n grabbedKey: Ref<ListEditorKey | null>\n /** 0-based index of the grabbed row in the current ordering, or -1 if no grab. */\n grabbedIndex: ComputedRef<number>\n /** Total count of rows currently in the editor. */\n totalCount: ComputedRef<number>\n isFocused: (key: ListEditorKey) => boolean\n isGrabbed: (key: ListEditorKey) => boolean\n rowTabindex: (key: ListEditorKey) => number\n setFocus: (key: ListEditorKey | null) => void\n releaseGrab: () => void\n handleKeydown: (key: ListEditorKey, e: KeyboardEvent) => void\n}\n\n// Roving tabindex + keyboard navigation for list-editor rows. Single tabstop\n// per editor; arrow keys move an internal pointer; reorder mode adds a \"grab\"\n// state where Enter/Space picks up the focused row and arrows move it.\nexport function useKeyboardNav(options: KeyboardNavOptions): KeyboardNavApi {\n const focusedKey = ref<ListEditorKey | null>(null)\n const grabbedKey = ref<ListEditorKey | null>(null)\n\n const orderedKeys = computed<ListEditorKey[]>(() => options.viewItems.value.map((v) => v.key))\n\n const isFocused = (key: ListEditorKey): boolean => focusedKey.value === key\n const isGrabbed = (key: ListEditorKey): boolean => grabbedKey.value === key\n\n const grabbedIndex = computed<number>(() => {\n if (grabbedKey.value === null) return -1\n return orderedKeys.value.indexOf(grabbedKey.value)\n })\n\n const totalCount = computed<number>(() => orderedKeys.value.length)\n\n function rowTabindex(key: ListEditorKey): number {\n const ordered = orderedKeys.value\n if (ordered.length === 0) return -1\n if (focusedKey.value === null) return ordered[0] === key ? 0 : -1\n return focusedKey.value === key ? 0 : -1\n }\n\n function focusRowElement(key: ListEditorKey | null) {\n if (key === null || typeof document === 'undefined') return\n void Promise.resolve().then(() => {\n const el = document.querySelector<HTMLElement>(`[data-id=\"${CSS.escape(String(key))}\"]`)\n el?.focus()\n })\n }\n\n function setFocus(key: ListEditorKey | null) {\n focusedKey.value = key\n focusRowElement(key)\n }\n\n // A move can re-create the grabbed row's element (indent/outdent puts it under another parent),\n // which drops focus to <body> and every further key with it.\n function refocusIfLost(key: ListEditorKey) {\n if (typeof document === 'undefined') return\n void Promise.resolve().then(() => {\n const active = document.activeElement\n if (!active || active === document.body) setFocus(key)\n })\n }\n\n // When the focused row is removed (e.g. via delete), fall to the row that\n // took its slot, or to the new last row if it was at the end. Without this,\n // focus vanishes to <body> after a delete and the user has to Tab back in.\n // We snapshot the previous ordering so we can look up where the focused key\n // *was* — by the time the watcher fires, the key is already gone from `now`.\n // eslint-disable-next-line vue/no-ref-object-reactivity-loss\n let prevOrderedKeys: ListEditorKey[] = [...orderedKeys.value]\n watch(orderedKeys, (now) => {\n if (focusedKey.value === null) {\n prevOrderedKeys = [...now]\n return\n }\n if (now.includes(focusedKey.value)) {\n prevOrderedKeys = [...now]\n return\n }\n if (now.length === 0) {\n focusedKey.value = null\n prevOrderedKeys = []\n return\n }\n const oldIndex = prevOrderedKeys.indexOf(focusedKey.value)\n const fallbackIndex = Math.min(Math.max(oldIndex, 0), now.length - 1)\n setFocus(now[fallbackIndex]!)\n prevOrderedKeys = [...now]\n })\n\n // Releasing a grab when the grabbed row is no longer in the list — keeps the\n // grab state consistent if the row gets removed externally.\n watch(orderedKeys, (now) => {\n if (grabbedKey.value !== null && !now.includes(grabbedKey.value)) {\n grabbedKey.value = null\n }\n })\n\n watch(options.isReorderMode, (inReorder) => {\n if (!inReorder) grabbedKey.value = null\n })\n\n function releaseGrab() {\n grabbedKey.value = null\n }\n\n function isFormField(target: EventTarget | null): boolean {\n const el = target as HTMLElement | null\n return !!el?.matches?.('input, textarea, select, [contenteditable], [contenteditable=\"true\"]')\n }\n\n // A row's own buttons and links (move up/down, edit, delete, menus) activate on Enter/Space themselves.\n function isOwnControl(target: EventTarget | null): boolean {\n const el = target as HTMLElement | null\n return !!el?.matches?.(\n 'button, a[href], summary, [role=\"button\"], [role=\"link\"], [role=\"menuitem\"], [role=\"checkbox\"], [role=\"switch\"], [role=\"tab\"], [role=\"option\"]'\n )\n }\n\n function handleKeydown(key: ListEditorKey, e: KeyboardEvent) {\n // A nested row's keydown bubbles into its ancestor rows; every key handled below calls\n // `preventDefault`, so an ancestor does not act on it a second time for its own row.\n if (e.defaultPrevented) return\n if (options.disabled?.value) return\n\n const ordered = orderedKeys.value\n const i = ordered.indexOf(key)\n if (i < 0) return\n\n // `ordered` is these view items' keys, so `i` indexes them too.\n const focusedItem = options.viewItems.value[i]!\n const inReorder = options.isReorderMode.value\n const isGrabbedNow = grabbedKey.value === key\n const grabbedSomewhere = grabbedKey.value !== null\n\n // Form fields keep native key behavior (cursor, newlines, selection) for\n // every key except Escape. Esc still closes the edit panel even mid-typing.\n const onFormField = isFormField(e.target)\n\n switch (e.key) {\n case 'ArrowUp':\n if (onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow) {\n options.onMoveUp?.(key)\n refocusIfLost(key)\n } else if (i > 0) {\n setFocus(ordered[i - 1]!)\n }\n return\n\n case 'ArrowDown':\n if (onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow) {\n options.onMoveDown?.(key)\n refocusIfLost(key)\n } else if (i < ordered.length - 1) {\n setFocus(ordered[i + 1]!)\n }\n return\n\n case 'Home':\n if (onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow) {\n options.onMoveTop?.(key)\n refocusIfLost(key)\n } else if (ordered.length > 0) {\n setFocus(ordered[0]!)\n }\n return\n\n case 'End':\n if (onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow) {\n options.onMoveBottom?.(key)\n refocusIfLost(key)\n } else if (ordered.length > 0) {\n setFocus(ordered[ordered.length - 1]!)\n }\n return\n\n case 'ArrowLeft':\n if (options.variant !== 'nested' || onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow && focusedItem.canOutdent) {\n options.onOutdent?.(key)\n refocusIfLost(key)\n } else if (focusedItem.expanded) {\n options.onToggleChildren?.(key, false)\n }\n return\n\n case 'ArrowRight':\n if (options.variant !== 'nested' || onFormField) return\n e.preventDefault()\n if (inReorder && isGrabbedNow && focusedItem.canIndent) {\n options.onIndent?.(key)\n refocusIfLost(key)\n } else if (focusedItem.canExpand && !focusedItem.expanded) {\n options.onToggleChildren?.(key, true)\n }\n return\n\n case 'Enter':\n case ' ': // Space\n if (onFormField || isOwnControl(e.target)) return\n e.preventDefault()\n if (inReorder) {\n if (isGrabbedNow) {\n grabbedKey.value = null\n } else {\n grabbedKey.value = key\n options.onGrab?.(key)\n }\n } else {\n options.onToggleEdit?.(key)\n }\n return\n\n // A handled Escape stops here: a Vuetify dialog around the editor closes on any Escape that reaches `window`.\n case 'Escape':\n if (grabbedSomewhere) {\n e.preventDefault()\n e.stopPropagation()\n const grabbed = grabbedKey.value!\n grabbedKey.value = null\n options.onGrabCancel?.(grabbed)\n refocusIfLost(grabbed)\n return\n }\n if (inReorder) {\n e.preventDefault()\n e.stopPropagation()\n options.onCancelReorder?.()\n return\n }\n if (options.isEditing(key)) {\n e.preventDefault()\n e.stopPropagation()\n options.onCancelEdit?.(key)\n return\n }\n return\n\n default:\n return\n }\n }\n\n return {\n focusedKey,\n grabbedKey,\n grabbedIndex,\n totalCount,\n isFocused,\n isGrabbed,\n rowTabindex,\n setFocus,\n releaseGrab,\n handleKeydown,\n }\n}\n"],"mappings":";;AA2DA,SAAgBI,EAAeC,GAA6C;CAC1E,IAAMC,IAAaJ,EAA0B,IAAI,GAC3CK,IAAaL,EAA0B,IAAI,GAE3CM,IAAcP,QAAgCI,EAAQ,UAAU,MAAM,KAAKI,MAAMA,EAAE,GAAG,CAAC,GAEvFC,KAAaC,MAAgCL,EAAW,UAAUK,GAClEC,KAAaD,MAAgCJ,EAAW,UAAUI,GAElEE,IAAeZ,QACfM,EAAW,UAAU,OAAa,KAC/BC,EAAY,MAAM,QAAQD,EAAW,KAAK,CAClD,GAEKO,IAAab,QAAuBO,EAAY,MAAM,MAAM;CAElE,SAASO,EAAYJ,GAA4B;EAC/C,IAAMK,IAAUR,EAAY;EAG5B,OAFIQ,EAAQ,WAAW,IAAU,KAC7BV,EAAW,UAAU,OAAaU,EAAQ,OAAOL,IAAM,IAAI,KACxDL,EAAW,UAAUK,IAAM,IAAI;CACxC;CAEA,SAASM,EAAgBN,GAA2B;EAC9CA,MAAQ,QAAQ,OAAO,WAAa,OACnC,QAAQ,QAAQ,CAAC,CAAC,WAAW;GACrB,SAAS,cAA2B,aAAa,IAAI,OAAO,OAAOA,CAAG,CAAC,EAAE,GACpF,CAAA,EAAI,MAAM;EACZ,CAAC;CACH;CAEA,SAASO,EAASP,GAA2B;EAC3CL,EAAW,QAAQK,GACnBM,EAAgBN,CAAG;CACrB;CAIA,SAASQ,EAAcR,GAAoB;EACrC,OAAO,WAAa,OACnB,QAAQ,QAAQ,CAAC,CAAC,WAAW;GAChC,IAAMS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,IAAIuB,KAAeN,EAAaE,EAAE,MAAM,GAAG;IAC3CA,EAAE,eAAe,GACbN,IACEQ,IACFzB,EAAW,QAAQ,QAEnBA,EAAW,QAAQI,GACnBN,EAAQ,SAASM,CAAG,KAGtBN,EAAQ,eAAeM,CAAG;IAE5B;GAGF,KAAK;IACH,IAAIsB,GAAkB;KACpBH,EAAE,eAAe,GACjBA,EAAE,gBAAgB;KAClB,IAAMK,IAAU5B,EAAW;KAC3BA,EAAW,QAAQ,MACnBF,EAAQ,eAAe8B,CAAO,GAC9BhB,EAAcgB,CAAO;KACrB;IACF;IACA,IAAIX,GAAW;KACbM,EAAE,eAAe,GACjBA,EAAE,gBAAgB,GAClBzB,EAAQ,kBAAkB;KAC1B;IACF;IACA,IAAIA,EAAQ,UAAUM,CAAG,GAAG;KAC1BmB,EAAE,eAAe,GACjBA,EAAE,gBAAgB,GAClBzB,EAAQ,eAAeM,CAAG;KAC1B;IACF;IACA;GAEF,SACE;EACJ;CACF;CAEA,OAAO;EACLL;EACAC;EACAM;EACAC;EACAJ;EACAE;EACAG;EACAG;EACAO;EACAI;CACF;AACF"}
@@ -12,55 +12,59 @@ function d(d) {
12
12
  });
13
13
  f.register(n, r);
14
14
  }
15
- let p = e(() => d.sources.some((e) => l(e.value)) || f.dirtyLabels.value.length > 0), m = r(!1), h = [], g = !1, _ = null, v = () => {
15
+ let p = e(() => d.sources.some((e) => l(e.value)) || f.dirtyLabels.value.length > 0), m = r(!1), h = [], g = !1, _ = null, v = null, y = () => {
16
16
  _ !== null && (clearTimeout(_), _ = null);
17
- }, y = () => g ? (g = !1, v(), Promise.resolve(!0)) : new Promise((e) => {
17
+ }, b = () => g ? (g = !1, y(), Promise.resolve(!0)) : (v = null, new Promise((e) => {
18
18
  h.push(e), m.value = !0;
19
- }), b = (e) => {
19
+ })), x = (e) => {
20
20
  m.value = !1;
21
21
  let t = h;
22
22
  h = [], t.forEach((t) => t(e));
23
- }, x = () => {
24
- g = !0, v(), _ = setTimeout(() => {
23
+ }, S = () => {
24
+ g = !0, y(), _ = setTimeout(() => {
25
25
  g = !1, _ = null;
26
26
  }, c);
27
- }, S = () => {
28
- g = !1, v();
27
+ }, C = () => {
28
+ g = !1, y();
29
29
  };
30
30
  if (d.guardRoute !== !1 && t()) try {
31
- let e = async () => !u(d.guardRoute, !0) || !p.value || await y();
32
- a(e), o((t, n) => t.path === n.path || e());
31
+ let e = async (e) => {
32
+ if (!u(d.guardRoute, !0) || !p.value || v !== null && e.redirectedFrom === v) return !0;
33
+ let t = await b();
34
+ return t && (v = e.redirectedFrom ?? e), t;
35
+ };
36
+ a(e), o((t, n) => t.path === n.path || e(t));
33
37
  } catch {}
34
- let C = [v], w = !1;
38
+ let w = [y], T = !1;
35
39
  if (d.guardWindowUnload !== !1) {
36
40
  let e = (e) => {
37
41
  u(d.guardWindowUnload, !0) && p.value && (e.preventDefault(), e.returnValue = "");
38
42
  };
39
- typeof window < "u" && (window.addEventListener("beforeunload", e), C.push(() => window.removeEventListener("beforeunload", e)));
43
+ typeof window < "u" && (window.addEventListener("beforeunload", e), w.push(() => window.removeEventListener("beforeunload", e)));
40
44
  }
41
45
  if (d.guardDialogModel) {
42
46
  let e = d.guardDialogModel, t = !1, n = i(e, async (n, r) => {
43
47
  if (t) t = !1;
44
48
  else if (r === !0 && n === !1 && p.value) {
45
49
  t = !0, e.value = !0;
46
- let n = await y();
47
- if (w) return;
50
+ let n = await b();
51
+ if (T) return;
48
52
  n && (t = !0, e.value = !1);
49
53
  }
50
54
  });
51
- C.push(n);
55
+ w.push(n);
52
56
  }
53
- let T = () => {
54
- w || (w = !0, b(!1), C.forEach((e) => e()));
57
+ let E = () => {
58
+ T || (T = !0, v = null, x(!1), w.forEach((e) => e()));
55
59
  };
56
- return t() && n(T), {
60
+ return t() && n(E), {
57
61
  hasUnsavedChanges: p,
58
62
  dirtyLabels: f.dirtyLabels,
59
63
  promptOpen: m,
60
- resolvePrompt: b,
61
- acknowledge: x,
62
- unacknowledge: S,
63
- stop: T
64
+ resolvePrompt: x,
65
+ acknowledge: S,
66
+ unacknowledge: C,
67
+ stop: E
64
68
  };
65
69
  }
66
70
  export { d as useUnsavedChangesGuard };
@@ -1 +1 @@
1
- {"version":3,"file":"useUnsavedChangesGuard.js","names":["computed","getCurrentInstance","onBeforeUnmount","ref","watch","onBeforeRouteLeave","onBeforeRouteUpdate","provideUnsavedSectionRegistry","ACKNOWLEDGE_TTL_MS","isTruthySource","value","resolveBool","v","fallback","useUnsavedChangesGuard","options","sectionRegistry","ownSections","id","normalized","resolved","hasUnsavedChanges","s","promptOpen","pendingResolvers","acknowledgedOnce","acknowledgeTimer","clearAcknowledgeTimer","askToLeave","resolve","resolvePrompt","discard","resolvers","acknowledge","unacknowledge","guardLeave","to","from","disposers","stopped","onBeforeUnload","dialogModel","suppressNext","stopDialogWatch","now","prev","stop","dispose"],"sources":["../../../../src/domains/unsavedGuard/composables/useUnsavedChangesGuard.ts"],"sourcesContent":["import { computed, getCurrentInstance, onBeforeUnmount, ref, watch, type ComputedRef, type Ref } from 'vue'\nimport { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'\nimport {\n provideUnsavedSectionRegistry,\n type UnsavedSectionDescriptor,\n type UnsavedSectionSource,\n} from '@/domains/unsavedGuard/composables/useUnsavedSection'\n\ntype UnsavedSource = Ref<boolean | Set<unknown> | unknown[] | null | undefined>\n\nexport interface UseUnsavedChangesGuardOptions {\n /**\n * Reactive sources that signal \"unsaved\" state. Each source's truthiness is\n * checked: a Set/array is \"dirty\" when non-empty, a boolean when true, null\n * or undefined as not dirty.\n */\n sources: UnsavedSource[]\n /**\n * Block route navigation via `onBeforeRouteLeave`, and `onBeforeRouteUpdate` when the path changes. Default true.\n * Only a literal `false` skips registering the guard. A Ref is\n * read at navigation time, so blocking can be toggled later.\n */\n guardRoute?: boolean | Ref<boolean>\n /**\n * Block window/tab unload via beforeunload. Default true. Like `guardRoute`: only a literal `false`\n * skips the listener, a Ref is read when the unload happens.\n */\n guardWindowUnload?: boolean | Ref<boolean>\n /**\n * Optional Vuetify dialog v-model. When provided, attempts to close the\n * dialog while dirty are intercepted: dialog stays open until the user\n * confirms via the confirm dialog or via `acknowledge()`.\n */\n guardDialogModel?: Ref<boolean>\n /**\n * Named sections owned by the guard host component itself. Descendants use\n * `useUnsavedSection` instead — but a component can't `inject` its own\n * `provide`, so when the host *is* the section owner (e.g. a dialog), pass\n * the sections here.\n */\n ownSections?: UnsavedSectionSource\n}\n\nexport interface UseUnsavedChangesGuardApi {\n hasUnsavedChanges: ComputedRef<boolean>\n /**\n * Labels of the dirty sections registered by descendants via\n * `useUnsavedSection`. Bind to `AUnsavedConfirmDialog`'s `dirtyLabels` prop\n * so the dialog names *which* parts are unsaved. Empty when no descendant\n * registered a section (dialog falls back to the generic message).\n */\n dirtyLabels: ComputedRef<string[]>\n /**\n * v-model-bound to the confirm dialog. When the guard wants to ask the user\n * to confirm leaving, it sets this to true. The confirm dialog reads it.\n */\n promptOpen: Ref<boolean>\n /**\n * Resolves the confirm prompt with `discard=true` (proceed) or `false`\n * (stay). Called by the confirm dialog.\n */\n resolvePrompt: (discard: boolean) => void\n /**\n * Manually mark the most recent intent as acknowledged so the next\n * route/dialog/unload attempt proceeds without prompting. Useful right\n * before a programmatic navigation that the consumer has already\n * confirmed.\n *\n * The acknowledgement AUTO-EXPIRES after a few seconds if nothing consumes it\n * (see `ACKNOWLEDGE_TTL_MS`): a delete that acknowledges up-front but then FAILS\n * (throws, never navigates) must not leave the guard silently disarmed for the\n * next unrelated navigation. Consuming it (a real leave) clears the timer.\n */\n acknowledge: () => void\n /**\n * Releases the `beforeunload` listener, acknowledge timer and dialog watcher, and settles an open prompt as \"stay\".\n * Idempotent and called on unmount. Outside a component it is the only way\n * to clean up. The route-leave guard is lifecycle-bound and unaffected.\n */\n stop: () => void\n /**\n * Cancel a pending `acknowledge()` (disarm). Call from a delete's failure path\n * so a failed/aborted delete restores the guard immediately instead of waiting\n * for the TTL. No-op if nothing is acknowledged.\n */\n unacknowledge: () => void\n}\n\n// An acknowledgement is meant for an IMMINENT navigation (a delete's router.push after its HTTP\n// round-trip — tens to hundreds of ms). If none arrives within this window the delete almost\n// certainly failed, so the one-shot expires rather than arming an unrelated later navigation.\n// Generously longer than any real delete request so a legitimate slow-success never false-prompts.\nconst ACKNOWLEDGE_TTL_MS = 8000\n\nconst isTruthySource = (value: unknown): boolean => {\n if (value === null || value === undefined) return false\n if (typeof value === 'boolean') return value\n if (value instanceof Set) return value.size > 0\n if (Array.isArray(value)) return value.length > 0\n return Boolean(value)\n}\n\nconst resolveBool = (v: boolean | Ref<boolean> | undefined, fallback: boolean): boolean => {\n if (v === undefined) return fallback\n if (typeof v === 'boolean') return v\n return v.value\n}\n\nexport function useUnsavedChangesGuard(options: UseUnsavedChangesGuardOptions): UseUnsavedChangesGuardApi {\n // Provide a section registry so descendants can name their dirty sections\n // via `useUnsavedSection`. The dialog reads `dirtyLabels` from this.\n const sectionRegistry = provideUnsavedSectionRegistry()\n\n // The host component can't inject its own provide, so register its own\n // sections directly.\n if (options.ownSections) {\n const ownSections = options.ownSections\n const id = Symbol('unsaved.section.own')\n const normalized = computed<UnsavedSectionDescriptor[]>(() => {\n const resolved = ownSections()\n return Array.isArray(resolved) ? resolved : [resolved]\n })\n sectionRegistry.register(id, normalized)\n }\n\n const hasUnsavedChanges = computed<boolean>(\n () => options.sources.some((s) => isTruthySource(s.value)) || sectionRegistry.dirtyLabels.value.length > 0\n )\n\n const promptOpen = ref<boolean>(false)\n // All navigations waiting on the open prompt. One started\n // meanwhile (browser Back) also waits and gets the same answer.\n let pendingResolvers: ((discard: boolean) => void)[] = []\n let acknowledgedOnce = false\n let acknowledgeTimer: ReturnType<typeof setTimeout> | null = null\n\n const clearAcknowledgeTimer = () => {\n if (acknowledgeTimer !== null) {\n clearTimeout(acknowledgeTimer)\n acknowledgeTimer = null\n }\n }\n\n const askToLeave = (): Promise<boolean> => {\n if (acknowledgedOnce) {\n acknowledgedOnce = false\n clearAcknowledgeTimer()\n return Promise.resolve(true)\n }\n return new Promise((resolve) => {\n pendingResolvers.push(resolve)\n promptOpen.value = true\n })\n }\n\n const resolvePrompt = (discard: boolean) => {\n promptOpen.value = false\n const resolvers = pendingResolvers\n pendingResolvers = []\n resolvers.forEach((resolve) => resolve(discard))\n }\n\n const acknowledge = () => {\n acknowledgedOnce = true\n // Auto-expire: if the imminent navigation never arrives (e.g. the delete threw), don't leave\n // the guard armed for an unrelated later leave. A real consume (askToLeave) clears this first.\n clearAcknowledgeTimer()\n acknowledgeTimer = setTimeout(() => {\n acknowledgedOnce = false\n acknowledgeTimer = null\n }, ACKNOWLEDGE_TTL_MS)\n }\n\n const unacknowledge = () => {\n acknowledgedOnce = false\n clearAcknowledgeTimer()\n }\n\n // `onBeforeRouteLeave` and `onBeforeRouteUpdate` only work inside a route component. Outside one they are no-ops.\n // A Ref option is read at event time.\n if (options.guardRoute !== false && getCurrentInstance()) {\n try {\n const guardLeave = async () => {\n if (!resolveBool(options.guardRoute, true) || !hasUnsavedChanges.value) return true\n const discard = await askToLeave()\n return discard\n }\n onBeforeRouteLeave(guardLeave)\n // A path change within the same route (another article's edit page) also drops this page's changes.\n // Admins key their view by path and remount it, including child routes under a guarded parent.\n // Any path change asks. Where the view is not keyed by path, this is one\n // extra prompt, never lost changes. Query and hash changes keep the page.\n onBeforeRouteUpdate((to, from) => (to.path === from.path ? true : guardLeave()))\n } catch {\n // Not in a route context — skip silently.\n }\n }\n\n // Browsers ignore custom `beforeunload` messages but show a generic confirm when `returnValue` is set.\n // Disposers are collected, not tied to `onBeforeUnmount`, because outside a component that hook is a silent no-op.\n const disposers: Array<() => void> = [clearAcknowledgeTimer]\n let stopped = false\n\n if (options.guardWindowUnload !== false) {\n const onBeforeUnload = (e: BeforeUnloadEvent) => {\n if (!resolveBool(options.guardWindowUnload, true) || !hasUnsavedChanges.value) return\n e.preventDefault()\n e.returnValue = ''\n }\n if (typeof window !== 'undefined') {\n window.addEventListener('beforeunload', onBeforeUnload)\n disposers.push(() => window.removeEventListener('beforeunload', onBeforeUnload))\n }\n }\n\n // Dialog guard — when the parent dialog tries to close while dirty, intercept\n // and ask the user to confirm. The parent dialog model goes from false→true\n // (open) to true→false (closing); we re-open it while we await the prompt.\n if (options.guardDialogModel) {\n const dialogModel = options.guardDialogModel\n let suppressNext = false\n const stopDialogWatch = watch(dialogModel, async (now, prev) => {\n if (suppressNext) {\n suppressNext = false\n return\n }\n if (prev === true && now === false && hasUnsavedChanges.value) {\n // Re-open the dialog while we wait for the user's choice.\n suppressNext = true\n dialogModel.value = true\n const discard = await askToLeave()\n // A teardown mid-prompt must not fall through and mutate the caller's dialog model.\n if (stopped) return\n if (discard) {\n suppressNext = true\n dialogModel.value = false\n }\n }\n })\n disposers.push(stopDialogWatch)\n }\n\n const stop = () => {\n if (stopped) return\n stopped = true\n // An open prompt would leave whoever awaits askToLeave() pending forever; \"stay\" is safe.\n resolvePrompt(false)\n disposers.forEach((dispose) => dispose())\n }\n\n if (getCurrentInstance()) {\n onBeforeUnmount(stop)\n }\n\n return {\n hasUnsavedChanges,\n dirtyLabels: sectionRegistry.dirtyLabels,\n promptOpen,\n resolvePrompt,\n acknowledge,\n unacknowledge,\n stop,\n }\n}\n"],"mappings":";;;;AA4FA,IAAMQ,IAAqB,KAErBC,KAAkBC,MAClBA,KAAU,OAAoC,KAC9C,OAAOA,KAAU,YAAkBA,IACnCA,aAAiB,MAAYA,EAAM,OAAO,IAC1C,MAAM,QAAQA,CAAK,IAAUA,EAAM,SAAS,IACzC,EAAQA,GAGXC,KAAeC,GAAuCC,MACtDD,MAAM,KAAA,IAAkBC,IACxB,OAAOD,KAAM,YAAkBA,IAC5BA,EAAE;AAGX,SAAgBE,EAAuBC,GAAmE;CAGxG,IAAMC,IAAkBT,EAA8B;CAItD,IAAIQ,EAAQ,aAAa;EACvB,IAAME,IAAcF,EAAQ,aACtBG,IAAK,OAAO,qBAAqB,GACjCC,IAAanB,QAA2C;GAC5D,IAAMoB,IAAWH,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;GAC1C7B,EAAYI,EAAQ,mBAAmB,EAAI,KAAMM,EAAkB,UACxE,EAAE,eAAe,GACjB,EAAE,cAAc;EAClB;EACI,OAAO,SAAW,QACpB,OAAO,iBAAiB,gBAAgBmB,CAAc,GACtDF,EAAU,WAAW,OAAO,oBAAoB,gBAAgBE,CAAc,CAAC;CAEnF;CAKA,IAAIzB,EAAQ,kBAAkB;EAC5B,IAAM0B,IAAc1B,EAAQ,kBACxB2B,IAAe,IACbC,IAAkBvC,EAAMqC,GAAa,OAAOG,GAAKC,MAAS;GAC9D,IAAIH,GACFA,IAAe;QAGjB,IAAIG,MAAS,MAAQD,MAAQ,MAASvB,EAAkB,OAAO;IAE7DqB,IAAe,IACfD,EAAY,QAAQ;IACpB,IAAMV,IAAU,MAAMH,EAAW;IAEjC,IAAIW,GAAS;IACTR,MACFW,IAAe,IACfD,EAAY,QAAQ;GAExB;EACF,CAAC;EACDH,EAAU,KAAKK,CAAe;CAChC;CAEA,IAAMG,UAAa;EACbP,MACJA,IAAU,IAEVT,EAAc,EAAK,GACnBQ,EAAU,SAASS,MAAYA,EAAQ,CAAC;CAC1C;CAMA,OAJI9C,EAAmB,KACrBC,EAAgB4C,CAAI,GAGf;EACLzB;EACA,aAAaL,EAAgB;EAC7BO;EACAO;EACAG;EACAC;EACAY;CACF;AACF"}
1
+ {"version":3,"file":"useUnsavedChangesGuard.js","names":["computed","getCurrentInstance","onBeforeUnmount","ref","watch","onBeforeRouteLeave","onBeforeRouteUpdate","provideUnsavedSectionRegistry","ACKNOWLEDGE_TTL_MS","isTruthySource","value","resolveBool","v","fallback","useUnsavedChangesGuard","options","sectionRegistry","ownSections","id","normalized","resolved","hasUnsavedChanges","s","promptOpen","pendingResolvers","acknowledgedOnce","acknowledgeTimer","agreedLeave","clearAcknowledgeTimer","askToLeave","resolve","resolvePrompt","discard","resolvers","acknowledge","unacknowledge","guardLeave","to","from","disposers","stopped","onBeforeUnload","dialogModel","suppressNext","stopDialogWatch","now","prev","stop","dispose"],"sources":["../../../../src/domains/unsavedGuard/composables/useUnsavedChangesGuard.ts"],"sourcesContent":["import { computed, getCurrentInstance, onBeforeUnmount, ref, watch, type ComputedRef, type Ref } from 'vue'\nimport { onBeforeRouteLeave, onBeforeRouteUpdate, type RouteLocation, type RouteLocationNormalized } from 'vue-router'\nimport {\n provideUnsavedSectionRegistry,\n type UnsavedSectionDescriptor,\n type UnsavedSectionSource,\n} from '@/domains/unsavedGuard/composables/useUnsavedSection'\n\ntype UnsavedSource = Ref<boolean | Set<unknown> | unknown[] | null | undefined>\n\nexport interface UseUnsavedChangesGuardOptions {\n /**\n * Reactive sources that signal \"unsaved\" state. Each source's truthiness is\n * checked: a Set/array is \"dirty\" when non-empty, a boolean when true, null\n * or undefined as not dirty.\n */\n sources: UnsavedSource[]\n /**\n * Block route navigation via `onBeforeRouteLeave`, and `onBeforeRouteUpdate` when the path changes. Default true.\n * Only a literal `false` skips registering the guard. A Ref is\n * read at navigation time, so blocking can be toggled later.\n */\n guardRoute?: boolean | Ref<boolean>\n /**\n * Block window/tab unload via beforeunload. Default true. Like `guardRoute`: only a literal `false`\n * skips the listener, a Ref is read when the unload happens.\n */\n guardWindowUnload?: boolean | Ref<boolean>\n /**\n * Optional Vuetify dialog v-model. When provided, attempts to close the\n * dialog while dirty are intercepted: dialog stays open until the user\n * confirms via the confirm dialog or via `acknowledge()`.\n */\n guardDialogModel?: Ref<boolean>\n /**\n * Named sections owned by the guard host component itself. Descendants use\n * `useUnsavedSection` instead — but a component can't `inject` its own\n * `provide`, so when the host *is* the section owner (e.g. a dialog), pass\n * the sections here.\n */\n ownSections?: UnsavedSectionSource\n}\n\nexport interface UseUnsavedChangesGuardApi {\n hasUnsavedChanges: ComputedRef<boolean>\n /**\n * Labels of the dirty sections registered by descendants via\n * `useUnsavedSection`. Bind to `AUnsavedConfirmDialog`'s `dirtyLabels` prop\n * so the dialog names *which* parts are unsaved. Empty when no descendant\n * registered a section (dialog falls back to the generic message).\n */\n dirtyLabels: ComputedRef<string[]>\n /**\n * v-model-bound to the confirm dialog. When the guard wants to ask the user\n * to confirm leaving, it sets this to true. The confirm dialog reads it.\n */\n promptOpen: Ref<boolean>\n /**\n * Resolves the confirm prompt with `discard=true` (proceed) or `false`\n * (stay). Called by the confirm dialog.\n */\n resolvePrompt: (discard: boolean) => void\n /**\n * Manually mark the most recent intent as acknowledged so the next\n * route/dialog/unload attempt proceeds without prompting. Useful right\n * before a programmatic navigation that the consumer has already\n * confirmed.\n *\n * The acknowledgement AUTO-EXPIRES after a few seconds if nothing consumes it\n * (see `ACKNOWLEDGE_TTL_MS`): a delete that acknowledges up-front but then FAILS\n * (throws, never navigates) must not leave the guard silently disarmed for the\n * next unrelated navigation. Consuming it (a real leave) clears the timer.\n */\n acknowledge: () => void\n /**\n * Releases the `beforeunload` listener, acknowledge timer and dialog watcher, and settles an open prompt as \"stay\".\n * Idempotent and called on unmount. Outside a component it is the only way\n * to clean up. The route-leave guard is lifecycle-bound and unaffected.\n */\n stop: () => void\n /**\n * Cancel a pending `acknowledge()` (disarm). Call from a delete's failure path\n * so a failed/aborted delete restores the guard immediately instead of waiting\n * for the TTL. No-op if nothing is acknowledged.\n */\n unacknowledge: () => void\n}\n\n// An acknowledgement is meant for an IMMINENT navigation (a delete's router.push after its HTTP\n// round-trip — tens to hundreds of ms). If none arrives within this window the delete almost\n// certainly failed, so the one-shot expires rather than arming an unrelated later navigation.\n// Generously longer than any real delete request so a legitimate slow-success never false-prompts.\nconst ACKNOWLEDGE_TTL_MS = 8000\n\nconst isTruthySource = (value: unknown): boolean => {\n if (value === null || value === undefined) return false\n if (typeof value === 'boolean') return value\n if (value instanceof Set) return value.size > 0\n if (Array.isArray(value)) return value.length > 0\n return Boolean(value)\n}\n\nconst resolveBool = (v: boolean | Ref<boolean> | undefined, fallback: boolean): boolean => {\n if (v === undefined) return fallback\n if (typeof v === 'boolean') return v\n return v.value\n}\n\nexport function useUnsavedChangesGuard(options: UseUnsavedChangesGuardOptions): UseUnsavedChangesGuardApi {\n // Provide a section registry so descendants can name their dirty sections\n // via `useUnsavedSection`. The dialog reads `dirtyLabels` from this.\n const sectionRegistry = provideUnsavedSectionRegistry()\n\n // The host component can't inject its own provide, so register its own\n // sections directly.\n if (options.ownSections) {\n const ownSections = options.ownSections\n const id = Symbol('unsaved.section.own')\n const normalized = computed<UnsavedSectionDescriptor[]>(() => {\n const resolved = ownSections()\n return Array.isArray(resolved) ? resolved : [resolved]\n })\n sectionRegistry.register(id, normalized)\n }\n\n const hasUnsavedChanges = computed<boolean>(\n () => options.sources.some((s) => isTruthySource(s.value)) || sectionRegistry.dirtyLabels.value.length > 0\n )\n\n const promptOpen = ref<boolean>(false)\n // All navigations waiting on the open prompt. One started\n // meanwhile (browser Back) also waits and gets the same answer.\n let pendingResolvers: ((discard: boolean) => void)[] = []\n let acknowledgedOnce = false\n let acknowledgeTimer: ReturnType<typeof setTimeout> | null = null\n // A global guard's redirect of the agreed leave is a new navigation from this still-dirty page. Each redirect\n // in it has the agreed location (or a record redirect's) as `redirectedFrom`, so it passes without a prompt.\n let agreedLeave: RouteLocation | RouteLocationNormalized | null = null\n\n const clearAcknowledgeTimer = () => {\n if (acknowledgeTimer !== null) {\n clearTimeout(acknowledgeTimer)\n acknowledgeTimer = null\n }\n }\n\n const askToLeave = (): Promise<boolean> => {\n if (acknowledgedOnce) {\n acknowledgedOnce = false\n clearAcknowledgeTimer()\n return Promise.resolve(true)\n }\n agreedLeave = null\n return new Promise((resolve) => {\n pendingResolvers.push(resolve)\n promptOpen.value = true\n })\n }\n\n const resolvePrompt = (discard: boolean) => {\n promptOpen.value = false\n const resolvers = pendingResolvers\n pendingResolvers = []\n resolvers.forEach((resolve) => resolve(discard))\n }\n\n const acknowledge = () => {\n acknowledgedOnce = true\n // Auto-expire: if the imminent navigation never arrives (e.g. the delete threw), don't leave\n // the guard armed for an unrelated later leave. A real consume (askToLeave) clears this first.\n clearAcknowledgeTimer()\n acknowledgeTimer = setTimeout(() => {\n acknowledgedOnce = false\n acknowledgeTimer = null\n }, ACKNOWLEDGE_TTL_MS)\n }\n\n const unacknowledge = () => {\n acknowledgedOnce = false\n clearAcknowledgeTimer()\n }\n\n // `onBeforeRouteLeave` and `onBeforeRouteUpdate` only work inside a route component. Outside one they are no-ops.\n // A Ref option is read at event time.\n if (options.guardRoute !== false && getCurrentInstance()) {\n try {\n const guardLeave = async (to: RouteLocationNormalized) => {\n if (!resolveBool(options.guardRoute, true) || !hasUnsavedChanges.value) return true\n if (agreedLeave !== null && to.redirectedFrom === agreedLeave) return true\n const discard = await askToLeave()\n if (discard) agreedLeave = to.redirectedFrom ?? to\n return discard\n }\n onBeforeRouteLeave(guardLeave)\n // A path change within the same route (another article's edit page) also drops this page's changes.\n // Admins key their view by path and remount it, including child routes under a guarded parent.\n // Any path change asks. Where the view is not keyed by path, this is one\n // extra prompt, never lost changes. Query and hash changes keep the page.\n onBeforeRouteUpdate((to, from) => (to.path === from.path ? true : guardLeave(to)))\n } catch {\n // Not in a route context — skip silently.\n }\n }\n\n // Browsers ignore custom `beforeunload` messages but show a generic confirm when `returnValue` is set.\n // Disposers are collected, not tied to `onBeforeUnmount`, because outside a component that hook is a silent no-op.\n const disposers: Array<() => void> = [clearAcknowledgeTimer]\n let stopped = false\n\n if (options.guardWindowUnload !== false) {\n const onBeforeUnload = (e: BeforeUnloadEvent) => {\n if (!resolveBool(options.guardWindowUnload, true) || !hasUnsavedChanges.value) return\n e.preventDefault()\n e.returnValue = ''\n }\n if (typeof window !== 'undefined') {\n window.addEventListener('beforeunload', onBeforeUnload)\n disposers.push(() => window.removeEventListener('beforeunload', onBeforeUnload))\n }\n }\n\n // Dialog guard — when the parent dialog tries to close while dirty, intercept\n // and ask the user to confirm. The parent dialog model goes from false→true\n // (open) to true→false (closing); we re-open it while we await the prompt.\n if (options.guardDialogModel) {\n const dialogModel = options.guardDialogModel\n let suppressNext = false\n const stopDialogWatch = watch(dialogModel, async (now, prev) => {\n if (suppressNext) {\n suppressNext = false\n return\n }\n if (prev === true && now === false && hasUnsavedChanges.value) {\n // Re-open the dialog while we wait for the user's choice.\n suppressNext = true\n dialogModel.value = true\n const discard = await askToLeave()\n // A teardown mid-prompt must not fall through and mutate the caller's dialog model.\n if (stopped) return\n if (discard) {\n suppressNext = true\n dialogModel.value = false\n }\n }\n })\n disposers.push(stopDialogWatch)\n }\n\n const stop = () => {\n if (stopped) return\n stopped = true\n agreedLeave = null\n // An open prompt would leave whoever awaits askToLeave() pending forever; \"stay\" is safe.\n resolvePrompt(false)\n disposers.forEach((dispose) => dispose())\n }\n\n if (getCurrentInstance()) {\n onBeforeUnmount(stop)\n }\n\n return {\n hasUnsavedChanges,\n dirtyLabels: sectionRegistry.dirtyLabels,\n promptOpen,\n resolvePrompt,\n acknowledge,\n unacknowledge,\n stop,\n }\n}\n"],"mappings":";;;;AA4FA,IAAMQ,IAAqB,KAErBC,KAAkBC,MAClBA,KAAU,OAAoC,KAC9C,OAAOA,KAAU,YAAkBA,IACnCA,aAAiB,MAAYA,EAAM,OAAO,IAC1C,MAAM,QAAQA,CAAK,IAAUA,EAAM,SAAS,IACzC,EAAQA,GAGXC,KAAeC,GAAuCC,MACtDD,MAAM,KAAA,IAAkBC,IACxB,OAAOD,KAAM,YAAkBA,IAC5BA,EAAE;AAGX,SAAgBE,EAAuBC,GAAmE;CAGxG,IAAMC,IAAkBT,EAA8B;CAItD,IAAIQ,EAAQ,aAAa;EACvB,IAAME,IAAcF,EAAQ,aACtBG,IAAK,OAAO,qBAAqB,GACjCC,IAAanB,QAA2C;GAC5D,IAAMoB,IAAWH,EAAY;GAC7B,OAAO,MAAM,QAAQG,CAAQ,IAAIA,IAAW,CAACA,CAAQ;EACvD,CAAC;EACDJ,EAAgB,SAASE,GAAIC,CAAU;CACzC;CAEA,IAAME,IAAoBrB,QAClBe,EAAQ,QAAQ,MAAMO,MAAMb,EAAea,EAAE,KAAK,CAAC,KAAKN,EAAgB,YAAY,MAAM,SAAS,CAC3G,GAEMO,IAAapB,EA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