32 KiB
Hooks and utilities review — November 2026
Scope and acceptance
Reviewed every implementation reachable from apps/admin/src/hooks, apps/admin/src/utils, packages/composables/src, and packages/utils/src. Compatibility entry points were followed to their owners instead of counted as separate implementations. The source inventory contains 141 named implementations in 44 files, plus the layout-owned positionSelectedMenuItem reached through its historical utility export. Inline event callbacks and returned object methods were also inspected. Component-local hooks and utilities are covered by the component review.
Acceptance covers observable correctness, reactive state ownership, resource cleanup, bounded allocations, configuration behavior, and accurate function contracts. It does not mean every function needs a rewrite or that a CPU benchmark proves browser responsiveness.
Findings and changes
| Finding | Change | Evidence |
|---|---|---|
| Default pagination candidates shared one mutable array across hook instances. | Give each instance its own default pageSizes array. Caller-provided arrays retain caller ownership. |
Two simultaneous instances and a later instance retain independent defaults after one is mutated. |
| Pagination reset consulted startup candidates after the exposed configuration had changed. | Read pagination.value.pageSizes at reset time, including object options and the empty fallback. |
Replacement with a 25-row option and then an empty array resets to 25 and 10 respectively. |
Shared storage could overwrite valid JSON with the non-JSON result of JSON.stringify(undefined). |
Serialize first and skip writes when serialization returns undefined or throws. Keep the existing backend, prefix, and JSON format. |
undefined, functions, symbols, cycles, and BigInt preserve saved content; JSON null still writes normally. |
| A fullscreen hook could reacquire an element after its effect scope was destroyed, leaving no live cleanup owner. | Mark the instance disposed before restoring it and ignore subsequent entry attempts. | Disposal restores style priorities and previous attributes, blocks the old instance, and lets a new instance acquire the element. |
| Random identifiers invoked Web Crypto separately for every character. | Fill a bounded buffer of at most 128 samples and retain rejection sampling. | Rejected samples, multiple batches, radix boundaries, and a 70,000-character identifier are covered. No random-source weakening or modulo bias was introduced. |
| PNG Base64 conversion created one array entry per byte. | Prefer native Uint8Array.toBase64; use bounded 32 KiB string chunks when unavailable. |
Empty data, all byte values, large buffers, chunk boundaries, and forced fallback produce identical Base64. |
| Every permission requirement searched the entire permission array. | Cache a computed Set per hook instance and use direct membership checks; rebuild on reactive permission changes. | Single/all/any checks, empty-list semantics, in-place revocation, and replacing session permissions are covered. |
| The screenshot renderer was statically imported even when never used. | Dynamically import html-to-image within the existing asynchronous create method after validating the target. |
Configured/overridden formats, callback ordering, renderer errors, and missing/throwing targets remain covered. Browser/build acceptance is recorded by the integrating review. |
The Base64 fast path follows the native typed-array API; feature detection preserves older browsers. No dependency, package export, persistence key, or ciphertext format was changed.
The integrating review additionally optimized useTheme by capturing its reactive getter, actions and translator once per factory; repeated reads no longer rebuild all settings computed references. A same-instance theme/language change regression confirms the result is not a cached snapshot.
The later routing review supersedes the original root/tab behavior and documents the final neutral-workspace contract.
Per-method disposition
The directory prefixes below identify authoritative implementations. “Retained” means source, call sites, and existing tests were reviewed and no justified behavioral change was found; it is not a claim of exhaustive runtime proof.
Shared composables
| Implementation | Methods inspected | Disposition |
|---|---|---|
packages/composables/src/dom.ts |
printDom |
Retained: resolves the target when capturing, awaits capture/print submission, reports loading success/failure, and returns a boolean. Actual paper output belongs to the browser. |
element.ts |
classTokens, setClass, removeClass, hasClass |
Retained: token matching uses classList; reactive targets are watched with Vue scope ownership. hasClass intentionally observes target replacement rather than native class mutations. |
element.ts |
autoPrefixStyle, cssProperty, setStyle, removeStyle |
Retained: legacy prefix mapping stays compatible; style updates preserve unrelated declarations and support custom properties and !important. Browser parsing handles string declarations. |
element.ts |
colorToRgba, queryElements, completeSize |
Retained: hex and comma-separated rgb/hsl parsing, invalid selector fallback, and preservation of existing CSS units/expressions are covered. Clarified that color conversion is not a complete CSS color parser. |
useContextmenuCoordinate.ts |
useContextmenuCoordinate, getEventOptions, updateShow, bindContextMenuEvent, stop |
Retained: forced non-passive contextmenu handling, latest-generation opening, dynamic ignored elements, outside close, listener cleanup, and idempotent stop. |
useDayjs.ts |
createDayjsTools, at, locale, isDayjs, format, getStartAndEndOfDay, daysDiff, isDateInRange |
Retained: local timezone, integer day differences, open-interval boundaries, per-instance locale versus explicit legacy global mode. Completed the factory's parameter/return contract. |
useDevice.ts |
useDevice, observer callback |
Retained: VueUse owns resize listeners; observation tracks only size and breakpoint, so unrelated reactive reads in the observer do not retrigger it. |
useDomToImage.ts |
useDomToImage, run exposed as create |
Changed to lazy renderer loading. Kept per-call format inference, callbacks, original element resolution, and error/finally behavior. |
useElementFullscreen.ts |
useElementFullscreen, enter, exit, toggleFullscreen, restoration closure |
Fixed post-disposal entry. Retained one-owner-per-element behavior, original style priorities, target replacement handling, configurable transition and callback vetoes. Added method-level lifecycle/error contracts. |
usePagination.ts |
usePagination, onUpdatePage, onUpdatePageSize, getItemCount, setItemCount, getPage, setPage, getPageSize, setPageSize, getPagination, getCallback, setCallback, resetPagination |
Fixed default-array ownership and reset configuration. Retained state-before-callback ordering and callback replacement/removal. Documented getters and mutable configuration ownership. |
usePrint.ts |
usePrint, run exposed as print |
Retained: current target resolution, HTML default for elements, binary image/PDF conversion, and caller options. Kept the synchronous non-binary contract instead of making every print call asynchronous. |
vue/call.ts |
call |
Retained: ordered synchronous invocation; the first thrown error stops the sequence. |
vue/effect-dispose.ts |
effectDispose |
Retained: registers cleanup only when a scope exists and reports whether registration succeeded. |
vue/render-node.ts |
renderNode overloads and implementation |
Retained: nullish fallback preserves 0 and empty text; callbacks and slots are returned without being invoked early. One contract remains on the public overload. |
vue/unref-element.ts |
unrefElement |
Retained: resolves values, refs, getters, and component roots on demand, with a nullish fallback. |
vue/watch-effect-with-target.ts |
watchEffectWithTarget |
Retained: directly preserves Vue's scheduler, cleanup, scope ownership, and stop handle. |
Shared utilities
| Implementation | Methods inspected | Disposition |
|---|---|---|
packages/utils/src/core/index.ts |
isValueType, isAsyncFunction, isPromise |
Retained: type tags, declared async functions, and awaitable values remain separate concepts. No deep traversal is added. |
core/index.ts |
uuid |
Bounded random batches retain character order, allowed radix/length validation, and unbiased sampling. |
core/index.ts |
callWithErrorHandling, callWithAsyncErrorHandling |
Retained: synchronous versus awaited behavior is explicit; callback failures propagate. Arbitrary PromiseLike results are awaited by the async wrapper. |
files/index.ts |
arrayBufferToBase64Image |
Native fast path plus bounded fallback; PNG prefix and synchronous return type preserved. |
files/index.ts |
downloadBase64File, downloadAnyFile, fileToBase64 |
Retained: temporary links removed, object URLs released on failure or after browser handoff, file read errors/abort reject. A resolved download does not mean disk writes completed. |
storage.ts |
createStorage, get, set, remove |
Fixed invalid serialization overwrite; reads remain live and errors contained. Added complete host ownership, prefix, failure, and JSON contracts. |
precision.ts |
isCurrency, format, add, subtract, multiply, divide, distribute |
Retained currency.js operations, eight-digit default precision, mixed input order, signed remainder behavior, and zero-division/count validation. Documented the safe-integer limit instead of claiming arbitrary precision. |
equal-router-path.ts |
equalRouterPath, normalize |
Retained: compares path identity after stripping query/hash/trailing slashes; callers needing tab-instance identity must use full paths. |
remove-duplicate-keys.ts |
removeDuplicateKeys |
Retained the compatibility name and shallow-copy semantics, including symbol keys. |
update-object-value.ts |
updateObjectValue |
Retained own-property checks and shallow merging only for two plain objects; arrays and other values are replaced. |
app/detect-operating-system.ts |
detectOperatingSystem |
Retained browserless fallback and desktop-identified iPad handling. User-Agent classification is a display hint, not capability detection. |
Application hooks
Implementation under apps/admin/src/hooks |
Methods inspected | Disposition |
|---|---|---|
template/useAccess.ts |
useAccess, hasPermission |
Cached permission membership with reactive invalidation. Empty-list all/any behavior preserved; both factory and method now have contracts. |
template/useAppNavigation.ts |
useAppNavigation, navigationTo, navigate, deepNavigation |
Retained invalid-index rejection, first-leaf traversal, resolved dynamic paths, query merging, hash preservation, and Router Promise forwarding. |
template/useAppRoot.ts |
useAppRoot, setRootRoute |
Retained preference reads and merge updates as a deprecated compatibility API. The routing follow-up removes all landing, protection and startup-validation effects. |
template/useBadge.ts |
updateBadge, useBadge, hidden, show, update |
Retained actual menu-object lookup, metadata merging, and renderer rebuilding; missing targets do not create menus. Documented shared ownership. |
template/useContentScroll.ts |
useContentScroll, returned scrollTo |
Retained invocation-time instance lookup and safe no-op when content is unmounted. Documented both coordinate and option forms. |
template/useSiderScroll.ts |
useSiderScroll, returned scrollTo |
Retained the same late lookup for optional sidebars; documented arguments. |
template/useI18n.ts |
getI18nKey, useI18n, translate exposed as t, locale, extraction-only t |
Retained namespace idempotence, initialization/HMR recovery and argument forwarding. Documented that direct locale writes do not replace the app's synchronized settings action. |
template/useMaximize.ts |
useMaximize, maximize, returned toggleFullscreen |
Retained shared Store state and generation-checked completion callbacks. Documented per-call defaults, callback timing, and user-triggered errors. |
template/useSiderBar.ts |
normalMenuTagOption, useSiderBar, getCurrentTagIndex, checkCloseRight, checkCloseLeft, close, closeAll, closeRight, closeLeft, closeOther |
Retained bounds checks and neighbor selection. The routing follow-up allows every business tab to close, routes final/all closure to Welcome, and preserves full URLs. |
template/useSpinning.ts |
useSpinning, openSpin, closeSpin, Store-owned reload alias |
Retained boolean manual state and Store-owned latest-wins reload timer. Documented ownership and that closing manual feedback does not cancel remounting. Visual changes are covered by the UI review. |
template/useTheme.ts |
useTheme, getAppTheme, darkTheme, lightTheme, syncSystemTheme, toggleTheme |
Captures the reactive getter, actions and translator once per factory instead of rebuilding all settings getters on each theme read. Existing live theme/language behavior remains covered (6 tests). |
template/useVueRouter.ts |
useVueRouter |
Retained direct shared Router access outside setup; no copied route state. |
template/useWatermark.ts |
useWatermark, setWatermarkContent, showWatermark, hiddenWatermark, toggleWatermark |
Retained nonempty content updates, shared visibility, and settings persistence. Completed factory contract. |
web/useDayjs.ts |
useDayjs |
Retained app-language mapping and explicit legacy global-locale behavior; documented the adapter. |
Application utilities and compatibility routes
Implementation under apps/admin/src/utils |
Methods inspected | Disposition |
|---|---|---|
app/get-app-environment.ts |
getAppEnvironment |
Retained direct Vite configuration access; documented browser visibility. |
app/prefix-cache-key.ts |
prefixCacheKey |
Retained literal prefix concatenation and historical nonempty custom-prefix fallback. |
cache-backend.ts |
memoryStorage, Storage key/getItem/setItem/removeItem/clear, useMemoryCache, getStorageInstance |
Retained independent local/session in-memory maps for document examples; documented reset and lifetime behavior and browser access exceptions. |
cache.ts |
getKeyWithPrefix, hasStorage, setStorage, getStorage, removeStorage, nested remove |
Retained serialization-before-write, explicit-null preservation, backend error handling, and reverse iteration for namespace-scoped bulk deletion. |
dom.ts |
app printDom adapter |
Retained global loading-bar injection and shared capture/print behavior; documented that the host loading option overrides the supplied one. |
get-date-by-naive-date-picker.ts |
getDateByNaiveDatePicker overloads and implementation |
Retained typed range-null mapping and original values for other inputs; one contract on the public overload avoids duplication. |
legacy-crypto/encrypt.ts |
encrypt |
Retained JSON validation, legacy passphrase/OpenSSL format, and random-IV raw-key format. |
legacy-crypto/decrypt.ts |
decrypt |
Retained historical formats and contained parse/decrypt failures. No key migration or format replacement was introduced. |
historical position-selected-menu-item.ts entry |
layout-owned positionSelectedMenuItem |
Followed the alias: reads bounds before scrolling, ignores missing nodes, and only scrolls out-of-view selected items. No duplicate implementation created. |
remaining index.ts, basic.ts, c/*, web/template compatibility paths |
export forwarding and type-only declarations | Verified ownership and existing names. These files contain no additional methods to optimize or duplicate comments for. |
Comment audit
Public factories, exported utilities, and returned action methods now have adjacent contract comments where this module owns the declaration. Comments follow the initial blank line, actual parameter names/order, standalone @description, and @param → @description → @returns → @throws order. They do not add @returns to void actions. Public overloads carry one shared contract, while small private normalizers and platform-typed callback bodies use local implementation notes rather than repetitive JSDoc.
The audit also corrected specificity: the screenshot promise includes dependency loading, fullscreen callbacks do not mean animation completion, useSpinning delegates restoration to the Store, color parsing covers comma-separated rgb/hsl, and fixed-point arithmetic is bounded by Number's safe-integer range.
Verification and remaining boundaries
- Initial regression run:
pnpm test:run __test__/hooks __test__/cache __test__/basic __test__/precision __test__/utils-contracts __test__/vue __test__/element __test__/dompassed 49 files / 218 tests before the final native-Base64 fallback case was added. - Final affected-case rerun:
pnpm test:run __test__/basic/arrayBufferToBase64Image.spec.ts __test__/cache/shared-storage.spec.ts __test__/hooks/useAccess.spec.tspassed 3 files / 8 tests.vue-tsc -p tsconfig.packages.json --noEmitandvue-tsc -p tsconfig.test.json --noEmitpassed. ESLint with zero warnings and Prettier checks passed for all owned changed files. - The integrating agent records final type, lint, formatting, build and browser outcomes for the combined change. Screenshot creation on
/web-hooksis the affected lazy-load interaction; other hooks keep their visible behavior. - Browser rendering, image/font cross-origin restrictions, native print dialogs, and physical print output are not established by Happy DOM tests. No physical printing is required for the internal changes in this review.
- No universal speedup, mobile-device latency, memory ceiling, or cross-browser benchmark is claimed. The proven changes remove per-character crypto calls, per-byte fallback array entries, repeated permission scans, and eager screenshot imports while retaining the documented API behavior.
- Large synchronous Base64 requests still allocate the output string. If measured payload sizes block interaction, add an explicitly asynchronous/worker API at that consumer boundary rather than silently changing this synchronous API.
- Native Storage calls remain synchronous; demo memory storage is intended for the small isolated documentation dataset. Existing native DOM class changes do not make
hasClassreactive. Legacy AES remains a compatibility format, and fixed-point functions remain Number-backed. Revisit those choices only with a concrete workload or migration requirement.
Guidance applied
The Modern Web Guidance performance guide recommends “DO use dynamic imports”. The screenshot implementation follows that recommendation while leaving the synchronous print API intact. The generic performance guidance does not justify changing date, storage, or compatibility contracts to newer APIs without an observed need.