@tanstack/db
Version:
A reactive client store for building super fast apps on sync
1 lines • 5.7 kB
Source Map (JSON)
{"version":3,"file":"debounceStrategy.cjs","names":["createSerialPacer","runWithCommitCompletion"],"sources":["../../../src/strategies/debounceStrategy.ts"],"sourcesContent":["import { createSerialPacer } from './serial-pacer'\nimport { runWithCommitCompletion } from './commit-completion'\nimport type { DebounceStrategy, DebounceStrategyOptions } from './types'\nimport type { Transaction } from '../transactions'\n\n/**\n * Creates a debounce strategy that delays transaction execution until after\n * a period of inactivity.\n *\n * Ideal for scenarios like search inputs or auto-save fields where you want\n * to wait for the user to stop typing before persisting changes.\n *\n * @param options - Configuration for the debounce behavior\n * @returns A debounce strategy instance\n *\n * @example\n * ```ts\n * const mutate = usePacedMutations({\n * onMutate: (value) => {\n * collection.update(id, draft => { draft.value = value })\n * },\n * mutationFn: async ({ transaction }) => {\n * await api.save(transaction.mutations)\n * },\n * strategy: debounceStrategy({ wait: 500 })\n * })\n * ```\n */\nexport function debounceStrategy(\n options: DebounceStrategyOptions,\n): DebounceStrategy {\n const leading = options.leading ?? false\n const trailing = options.trailing ?? true\n const serial = createSerialPacer(0)\n let canLead = true\n let leadingPending = false\n let leadingOwner: object | undefined\n let timeout: ReturnType<typeof setTimeout> | undefined\n const trailingRuns = new Map<\n object,\n { run: () => Promise<unknown>; isCanceled: () => boolean }\n >()\n\n return {\n _type: `debounce`,\n options,\n execute: <T extends object = Record<string, unknown>>(\n fn: () => Transaction<T>,\n onAdmit?: () => Transaction<T> | void,\n onCommit?: () => Promise<unknown> | undefined,\n ) => {\n const run = () => runWithCommitCompletion(fn, onCommit)\n const leadingCall = leading && canLead\n const admitted = leadingCall || trailing\n // Reserve the edge before optimistic mutation can reenter execute.\n const wasLeadAvailable = canLead\n canLead = false\n let owner: object = fn\n let transaction: Transaction<T> | undefined\n try {\n if (admitted) {\n const admittedOwner = onAdmit?.()\n if (admittedOwner) {\n transaction = admittedOwner\n owner = admittedOwner\n }\n }\n } catch (error) {\n // A nested admitted call may have installed its own quiet timer.\n if (timeout === undefined) canLead = wasLeadAvailable\n throw error\n }\n // A replacement transaction after rollback cannot inherit a canceled\n // leading callback's eligibility. It needs its own quiet-edge schedule.\n const joinsPendingLeading =\n leadingPending && !leadingCall && owner === leadingOwner\n if (timeout !== undefined) clearTimeout(timeout)\n // A new call renews the quiet period, including after an earlier timer\n // became eligible while persistence was held.\n if (trailing)\n for (const pendingOwner of trailingRuns.keys())\n serial.cancel(pendingOwner)\n if (trailing && admitted && !leadingCall && !joinsPendingLeading) {\n trailingRuns.set(owner, {\n run,\n isCanceled: () => transaction?.state === `failed`,\n })\n }\n timeout = setTimeout(() => {\n timeout = undefined\n canLead = true\n for (const [pendingOwner, pending] of trailingRuns) {\n if (pending.isCanceled()) {\n trailingRuns.delete(pendingOwner)\n continue\n }\n serial.schedule(() => {\n trailingRuns.delete(pendingOwner)\n return pending.run()\n }, pendingOwner)\n }\n }, options.wait)\n if (leadingCall) {\n // A same-manager reentrant trailing call joins this leading transaction.\n // A different manager's trailing transaction keeps the shared edge.\n trailingRuns.delete(owner)\n leadingPending = true\n leadingOwner = owner\n serial.schedule(() => {\n leadingPending = false\n leadingOwner = undefined\n return run()\n }, owner)\n }\n if (!admitted) return false\n return\n },\n cleanup: () => {\n // Admitted work retains its timer and persistence obligation.\n },\n }\n}\n"],"mappings":";;AA4BA,SAAgB,iBACd,SACkB;CAClB,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,SAASA,qBAAAA,kBAAkB,CAAC;CAClC,IAAI,UAAU;CACd,IAAI,iBAAiB;CACrB,IAAI;CACJ,IAAI;CACJ,MAAM,+BAAe,IAAI,IAGvB;CAEF,OAAO;EACL,OAAO;EACP;EACA,UACE,IACA,SACA,aACG;GACH,MAAM,YAAYC,0BAAAA,wBAAwB,IAAI,QAAQ;GACtD,MAAM,cAAc,WAAW;GAC/B,MAAM,WAAW,eAAe;GAEhC,MAAM,mBAAmB;GACzB,UAAU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