@ttt-productions/upload-ui 0.7.15 → 0.7.17

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 (77) hide show
  1. package/dist/index.d.ts +2 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +3 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/react/guard/guarded-link.d.ts.map +1 -0
  6. package/dist/react/guard/guarded-link.js.map +1 -0
  7. package/dist/react/guard/index.d.ts +3 -3
  8. package/dist/react/guard/index.d.ts.map +1 -1
  9. package/dist/react/guard/index.js +3 -3
  10. package/dist/react/guard/index.js.map +1 -1
  11. package/dist/react/guard/local-upload-guard-provider.d.ts.map +1 -0
  12. package/dist/react/guard/local-upload-guard-provider.js.map +1 -0
  13. package/dist/react/guard/use-guarded-navigation.d.ts.map +1 -0
  14. package/dist/react/{use-guarded-navigation.js → guard/use-guarded-navigation.js} +1 -1
  15. package/dist/react/guard/use-guarded-navigation.js.map +1 -0
  16. package/dist/react/tray/in-flight-uploads-provider.d.ts.map +1 -0
  17. package/dist/react/{in-flight-uploads-provider.js → tray/in-flight-uploads-provider.js} +11 -8
  18. package/dist/react/tray/in-flight-uploads-provider.js.map +1 -0
  19. package/dist/react/tray/index.d.ts +4 -4
  20. package/dist/react/tray/index.d.ts.map +1 -1
  21. package/dist/react/tray/index.js +4 -4
  22. package/dist/react/tray/index.js.map +1 -1
  23. package/dist/react/tray/use-clear-upload-activity.d.ts.map +1 -0
  24. package/dist/react/tray/use-clear-upload-activity.js.map +1 -0
  25. package/dist/react/tray/use-mark-upload-activity-seen.d.ts +16 -0
  26. package/dist/react/tray/use-mark-upload-activity-seen.d.ts.map +1 -0
  27. package/dist/react/tray/use-mark-upload-activity-seen.js +65 -0
  28. package/dist/react/tray/use-mark-upload-activity-seen.js.map +1 -0
  29. package/dist/react/tray/use-upload-processing.d.ts.map +1 -0
  30. package/dist/react/{use-upload-processing.js → tray/use-upload-processing.js} +11 -3
  31. package/dist/react/tray/use-upload-processing.js.map +1 -0
  32. package/dist/react/{deferred-upload-form-shell.d.ts → upload/deferred-upload-form-shell.d.ts} +1 -1
  33. package/dist/react/upload/deferred-upload-form-shell.d.ts.map +1 -0
  34. package/dist/react/{deferred-upload-form-shell.js → upload/deferred-upload-form-shell.js} +5 -1
  35. package/dist/react/upload/deferred-upload-form-shell.js.map +1 -0
  36. package/dist/react/upload/index.d.ts +2 -2
  37. package/dist/react/upload/index.d.ts.map +1 -1
  38. package/dist/react/upload/index.js +2 -2
  39. package/dist/react/upload/index.js.map +1 -1
  40. package/dist/react/upload/use-guarded-upload.d.ts.map +1 -0
  41. package/dist/react/{use-guarded-upload.js → upload/use-guarded-upload.js} +2 -2
  42. package/dist/react/upload/use-guarded-upload.js.map +1 -0
  43. package/dist/upload-display.d.ts +39 -0
  44. package/dist/upload-display.d.ts.map +1 -0
  45. package/dist/upload-display.js +64 -0
  46. package/dist/upload-display.js.map +1 -0
  47. package/package.json +5 -5
  48. package/dist/react/deferred-upload-form-shell.d.ts.map +0 -1
  49. package/dist/react/deferred-upload-form-shell.js.map +0 -1
  50. package/dist/react/guarded-link.d.ts.map +0 -1
  51. package/dist/react/guarded-link.js.map +0 -1
  52. package/dist/react/in-flight-uploads-provider.d.ts.map +0 -1
  53. package/dist/react/in-flight-uploads-provider.js.map +0 -1
  54. package/dist/react/local-upload-guard-provider.d.ts.map +0 -1
  55. package/dist/react/local-upload-guard-provider.js.map +0 -1
  56. package/dist/react/use-clear-upload-activity.d.ts.map +0 -1
  57. package/dist/react/use-clear-upload-activity.js.map +0 -1
  58. package/dist/react/use-guarded-navigation.d.ts.map +0 -1
  59. package/dist/react/use-guarded-navigation.js.map +0 -1
  60. package/dist/react/use-guarded-upload.d.ts.map +0 -1
  61. package/dist/react/use-guarded-upload.js.map +0 -1
  62. package/dist/react/use-mark-upload-activity-seen.d.ts +0 -8
  63. package/dist/react/use-mark-upload-activity-seen.d.ts.map +0 -1
  64. package/dist/react/use-mark-upload-activity-seen.js +0 -29
  65. package/dist/react/use-mark-upload-activity-seen.js.map +0 -1
  66. package/dist/react/use-upload-processing.d.ts.map +0 -1
  67. package/dist/react/use-upload-processing.js.map +0 -1
  68. /package/dist/react/{guarded-link.d.ts → guard/guarded-link.d.ts} +0 -0
  69. /package/dist/react/{guarded-link.js → guard/guarded-link.js} +0 -0
  70. /package/dist/react/{local-upload-guard-provider.d.ts → guard/local-upload-guard-provider.d.ts} +0 -0
  71. /package/dist/react/{local-upload-guard-provider.js → guard/local-upload-guard-provider.js} +0 -0
  72. /package/dist/react/{use-guarded-navigation.d.ts → guard/use-guarded-navigation.d.ts} +0 -0
  73. /package/dist/react/{in-flight-uploads-provider.d.ts → tray/in-flight-uploads-provider.d.ts} +0 -0
  74. /package/dist/react/{use-clear-upload-activity.d.ts → tray/use-clear-upload-activity.d.ts} +0 -0
  75. /package/dist/react/{use-clear-upload-activity.js → tray/use-clear-upload-activity.js} +0 -0
  76. /package/dist/react/{use-upload-processing.d.ts → tray/use-upload-processing.d.ts} +0 -0
  77. /package/dist/react/{use-guarded-upload.d.ts → upload/use-guarded-upload.d.ts} +0 -0
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- export {};
1
+ export { formatFileSize, createUploadDisplayFormatters } from './upload-display.js';
2
+ export type { UploadDisplayCopy, UploadDisplayConfig, UploadDisplayFormatters, } from './upload-display.js';
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAG,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC;AACpF,YAAY,EACV,iBAAiB,EACjB,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -1,2 +1,4 @@
1
- export {};
1
+ // Server-safe entry: no React. React code lives at `@ttt-productions/upload-ui/react/guard`,
2
+ // `/react/upload`, and `/react/tray`.
3
+ export { formatFileSize, createUploadDisplayFormatters } from './upload-display.js';
2
4
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"","sourcesContent":["// Server-safe entry. React code lives at `@ttt-productions/upload-ui/react/guard`, `/react/upload`, and `/react/tray`.\n// This file is intentionally empty; the package's public surface is exposed via\n// the `./react/guard`, `./react/upload`, and `./react/tray` subpaths. Keeping main\n// empty preserves the server-safe contract (no React imports leak through\n// `import x from '@ttt-productions/upload-ui'`).\nexport { };"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,6FAA6F;AAC7F,sCAAsC;AACtC,OAAO,EAAE,cAAc,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["// Server-safe entry: no React. React code lives at `@ttt-productions/upload-ui/react/guard`,\n// `/react/upload`, and `/react/tray`.\nexport { formatFileSize, createUploadDisplayFormatters } from './upload-display.js';\nexport type {\n UploadDisplayCopy,\n UploadDisplayConfig,\n UploadDisplayFormatters,\n} from './upload-display.js';\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guarded-link.d.ts","sourceRoot":"","sources":["../../../src/react/guard/guarded-link.tsx"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAGnD,MAAM,WAAW,qBAAqB;IACpC,6EAA6E;IAC7E,OAAO,EAAE,CAAC,KAAK,EAAE,UAAU,CAAC,WAAW,CAAC,KAAK,IAAI,CAAC;IAClD,yEAAyE;IACzE,QAAQ,EAAE,SAAS,CAAC;CACrB;AAED,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,SAAS,CAAC;IACpB,UAAU,EAAE,CAAC,IAAI,EAAE,qBAAqB,KAAK,SAAS,CAAC;CACxD;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,+BAWlD"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guarded-link.js","sourceRoot":"","sources":["../../../src/react/guard/guarded-link.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AA6Bb,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAcvE,MAAM,UAAU,WAAW,CAAC,KAAuB;IACjD,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,KAAK,CAAC;IACvC,MAAM,EAAE,iBAAiB,EAAE,GAAG,mBAAmB,EAAE,CAAC;IAEpD,MAAM,OAAO,GAAG,CAAC,KAA8B,EAAE,EAAE;QACjD,IAAI,CAAC,iBAAiB,EAAE,EAAE,CAAC;YACzB,KAAK,CAAC,cAAc,EAAE,CAAC;QACzB,CAAC;IACH,CAAC,CAAC;IAEF,OAAO,4BAAG,UAAU,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,GAAI,CAAC;AAClD,CAAC","sourcesContent":["'use client';\n\n/**\n * Render-prop link wrapper that guards navigation while an upload or unsaved\n * work is registered. The consumer owns the actual navigator component (Next.js Link,\n * React Router Link, plain anchor, etc.) — this wrapper only injects the\n * onClick interceptor.\n *\n * Why render-prop and not `as={Link}`? Polymorphic `as` props create\n * notoriously bad TypeScript inference and force the wrapper to forward all\n * link-specific props. Render-prop keeps the consumer in full control of the\n * link API, costs one extra wrapper closure, and keeps upload-ui agnostic of\n * Next.js / React Router / etc.\n *\n * Design note: the design spec lists `<GuardedNavigationButton>` as a second\n * component. We deliberately don't ship it — buttons that navigate use\n * `useGuardedNavigation()` directly in one line. A second component would\n * split the same surface for no payoff.\n *\n * Usage:\n *\n * <GuardedLink renderLink={({ onClick, children }) => (\n * <Link href=\"/your/destination\" onClick={onClick}>{children}</Link>\n * )}>\n * View all uploads →\n * </GuardedLink>\n */\n\nimport type { MouseEvent, ReactNode } from 'react';\nimport { useLocalUploadGuard } from './local-upload-guard-provider.js';\n\nexport interface GuardedLinkRenderArgs {\n /** Click handler the consumer MUST attach to its underlying link element. */\n onClick: (event: MouseEvent<HTMLElement>) => void;\n /** The children passed to `<GuardedLink>` — forward them to the link. */\n children: ReactNode;\n}\n\nexport interface GuardedLinkProps {\n children: ReactNode;\n renderLink: (args: GuardedLinkRenderArgs) => ReactNode;\n}\n\nexport function GuardedLink(props: GuardedLinkProps) {\n const { children, renderLink } = props;\n const { confirmNavigation } = useLocalUploadGuard();\n\n const onClick = (event: MouseEvent<HTMLElement>) => {\n if (!confirmNavigation()) {\n event.preventDefault();\n }\n };\n\n return <>{renderLink({ onClick, children })}</>;\n}\n"]}
@@ -1,4 +1,4 @@
1
- export { LocalUploadGuardProvider, useLocalUploadGuard, useLocalUploadGuardContext, useOptionalLocalUploadGuard, useUnsavedWorkGuard, type ConfirmNavigationOptions, type LocalUploadGuardProviderProps, } from '../local-upload-guard-provider.js';
2
- export { useGuardedNavigation } from '../use-guarded-navigation.js';
3
- export { GuardedLink, type GuardedLinkProps, type GuardedLinkRenderArgs, } from '../guarded-link.js';
1
+ export { LocalUploadGuardProvider, useLocalUploadGuard, useLocalUploadGuardContext, useOptionalLocalUploadGuard, useUnsavedWorkGuard, type ConfirmNavigationOptions, type LocalUploadGuardProviderProps, } from './local-upload-guard-provider.js';
2
+ export { useGuardedNavigation } from './use-guarded-navigation.js';
3
+ export { GuardedLink, type GuardedLinkProps, type GuardedLinkRenderArgs } from './guarded-link.js';
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/react/guard/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC1B,2BAA2B,EAC3B,mBAAmB,EACnB,KAAK,wBAAwB,EAC7B,KAAK,6BAA6B,GACnC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EACL,WAAW,EACX,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,GAC3B,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/react/guard/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC1B,2BAA2B,EAC3B,mBAAmB,EACnB,KAAK,wBAAwB,EAC7B,KAAK,6BAA6B,GACnC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAE,KAAK,qBAAqB,EAAE,MAAM,mBAAmB,CAAC"}
@@ -1,4 +1,4 @@
1
- export { LocalUploadGuardProvider, useLocalUploadGuard, useLocalUploadGuardContext, useOptionalLocalUploadGuard, useUnsavedWorkGuard, } from '../local-upload-guard-provider.js';
2
- export { useGuardedNavigation } from '../use-guarded-navigation.js';
3
- export { GuardedLink, } from '../guarded-link.js';
1
+ export { LocalUploadGuardProvider, useLocalUploadGuard, useLocalUploadGuardContext, useOptionalLocalUploadGuard, useUnsavedWorkGuard, } from './local-upload-guard-provider.js';
2
+ export { useGuardedNavigation } from './use-guarded-navigation.js';
3
+ export { GuardedLink } from './guarded-link.js';
4
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/react/guard/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC1B,2BAA2B,EAC3B,mBAAmB,GAGpB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EACL,WAAW,GAGZ,MAAM,oBAAoB,CAAC","sourcesContent":["export {\n LocalUploadGuardProvider,\n useLocalUploadGuard,\n useLocalUploadGuardContext,\n useOptionalLocalUploadGuard,\n useUnsavedWorkGuard,\n type ConfirmNavigationOptions,\n type LocalUploadGuardProviderProps,\n} from '../local-upload-guard-provider.js';\nexport { useGuardedNavigation } from '../use-guarded-navigation.js';\nexport {\n GuardedLink,\n type GuardedLinkProps,\n type GuardedLinkRenderArgs,\n} from '../guarded-link.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/react/guard/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC1B,2BAA2B,EAC3B,mBAAmB,GAGpB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,WAAW,EAAqD,MAAM,mBAAmB,CAAC","sourcesContent":["export {\n LocalUploadGuardProvider,\n useLocalUploadGuard,\n useLocalUploadGuardContext,\n useOptionalLocalUploadGuard,\n useUnsavedWorkGuard,\n type ConfirmNavigationOptions,\n type LocalUploadGuardProviderProps,\n} from './local-upload-guard-provider.js';\nexport { useGuardedNavigation } from './use-guarded-navigation.js';\nexport { GuardedLink, type GuardedLinkProps, type GuardedLinkRenderArgs } from './guarded-link.js';\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local-upload-guard-provider.d.ts","sourceRoot":"","sources":["../../../src/react/guard/local-upload-guard-provider.tsx"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EASL,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAEf,MAAM,WAAW,wBAAwB;IACvC;;;;;;OAMG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,UAAU,4BAA4B;IACpC,gCAAgC;IAChC,iBAAiB,EAAE,MAAM,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IACxC,MAAM,GAAG,GAAG,UAAU,CAAC,uBAAuB,CAAC,CAAC;IAChD,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;IACtF,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,2BAA2B;IACzC,OAAO,UAAU,CAAC,uBAAuB,CAAC,IAAI,IAAI,CAAC;AACrD,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,mBAAmB;IACjC,OAAO,0BAA0B,EAAE,CAAC;AACtC,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CAAC,cAAuB;IACzD,MAAM,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,GAAG,0BAA0B,EAAE,CAAC;IACpF,MAAM,EAAE,GAAG,KAAK,EAAE,CAAC;IACnB,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,CAAC,cAAc;YAAE,OAAO;QAC5B,mBAAmB,CAAC,EAAE,CAAC,CAAC;QACxB,OAAO,GAAG,EAAE,CAAC,qBAAqB,CAAC,EAAE,CAAC,CAAC;IACzC,CAAC,EAAE,CAAC,cAAc,EAAE,EAAE,EAAE,mBAAmB,EAAE,qBAAqB,CAAC,CAAC,CAAC;IACrE,MAAM,OAAO,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,qBAAqB,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,qBAAqB,CAAC,CAAC,CAAC;IAC1F,OAAO,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;AACjD,CAAC","sourcesContent":["'use client';\n\n/**\n * The navigation and leave guard: warns before the user leaves while work that leaving would lose\n * is registered — a LOCAL byte upload in flight, or an editor's unsaved input.\n *\n * Uploads: phases `preparing` and `uploading` only. `finalizing` and backend `pendingMedia`\n * processing are safe to leave (the bytes are already in Storage), so they are not registered.\n * Unsaved work: an editor registers while it holds input its user has not saved, and unregisters\n * when the input is saved, discarded, or the editor unmounts.\n *\n * While anything is registered the provider installs ONE `beforeunload` listener (tab close,\n * reload, full-page navigation), and `confirmNavigation()` asks before an in-app navigation. It is\n * the one leave guard: an editor never installs its own `beforeunload` handler (FRONTEND-207).\n *\n * Consumers register with a stable id per piece of work; registering a registered id, or\n * unregistering an absent one, is a no-op. Uploads and unsaved work are counted separately, so the\n * same id may be both.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\n\nexport interface ConfirmNavigationOptions {\n /**\n * The caller leaves through a FULL-PAGE navigation (`location.assign` /\n * `location.replace`) once this returns true. The provider then lets that\n * navigation's next `beforeunload` pass without the browser's own\n * \"Leave site?\" prompt, because the user has just answered this one. Soft\n * (in-app router) navigations never pass it: they fire no `beforeunload`.\n */\n fullPageNavigation?: boolean;\n}\n\ninterface LocalUploadGuardContextValue {\n /** Registered local uploads. */\n activeUploadCount: number;\n /** Registered pieces of unsaved work. */\n unsavedWorkCount: number;\n /** Everything the guard warns about: uploads plus unsaved work. Zero means leaving asks nothing. */\n guardedWorkCount: number;\n registerUpload: (id: string) => void;\n unregisterUpload: (id: string) => void;\n registerUnsavedWork: (id: string) => void;\n unregisterUnsavedWork: (id: string) => void;\n /** Returns true iff an upload or unsaved work is currently registered. Pure read. */\n shouldConfirmNavigation: () => boolean;\n /**\n * Shows a confirm() dialog with the message for what is registered and returns the user's\n * choice. Safe to call when nothing is registered — returns true without prompting.\n *\n * With `{ fullPageNavigation: true }` and a result of true (confirmed, or nothing registered),\n * arms a ONE-SHOT bypass: the next `beforeunload` is not prevented, so a confirmed full-page\n * navigation does not prompt twice. A declined confirm never arms it; the bypass is cleared when\n * it is consumed, when new work (an upload or unsaved work) registers, and on `pageshow` (a\n * back/forward-cache return).\n */\n confirmNavigation: (options?: ConfirmNavigationOptions) => boolean;\n}\n\nconst LocalUploadGuardContext = createContext<LocalUploadGuardContextValue | undefined>(undefined);\n\nexport interface LocalUploadGuardProviderProps {\n /**\n * Message the browser is given when the user closes the tab, reloads, or leaves the page while\n * work is registered. Modern browsers show their own generic dialog and ignore it; when omitted,\n * the default for what is registered is used.\n */\n beforeUnloadMessage?: string;\n /** `confirmNavigation()`'s message while an upload is in progress (and no unsaved work). */\n navigationConfirmMessage?: string;\n /** `confirmNavigation()`'s message while unsaved work is registered (and no upload). */\n unsavedWorkConfirmMessage?: string;\n /** `confirmNavigation()`'s message while both an upload and unsaved work are registered. */\n uploadAndUnsavedWorkConfirmMessage?: string;\n children: ReactNode;\n}\n\nconst DEFAULT_NAVIGATION_CONFIRM_MESSAGE =\n 'An upload is currently in progress. If you leave this page, the upload will be canceled. Continue?';\nconst DEFAULT_UNSAVED_WORK_CONFIRM_MESSAGE =\n 'You have unsaved changes. If you leave this page, they will be lost. Continue?';\nconst DEFAULT_UPLOAD_AND_UNSAVED_WORK_CONFIRM_MESSAGE =\n 'An upload is in progress and you have unsaved changes. If you leave this page, the upload will be canceled and your changes will be lost. Continue?';\nconst DEFAULT_UPLOAD_BEFORE_UNLOAD_MESSAGE =\n 'File upload in progress. Are you sure you want to leave and end the file upload?';\nconst DEFAULT_UNSAVED_WORK_BEFORE_UNLOAD_MESSAGE =\n 'You have unsaved changes. Are you sure you want to leave and lose them?';\n\nfunction useRegistry(onRegister: () => void) {\n const idsRef = useRef<Set<string>>(new Set());\n const [count, setCount] = useState(0);\n\n const register = useCallback(\n (id: string) => {\n if (idsRef.current.has(id)) return;\n onRegister();\n idsRef.current.add(id);\n setCount(idsRef.current.size);\n },\n [onRegister],\n );\n\n const unregister = useCallback((id: string) => {\n if (!idsRef.current.has(id)) return;\n idsRef.current.delete(id);\n setCount(idsRef.current.size);\n }, []);\n\n return { idsRef, count, register, unregister };\n}\n\nexport function LocalUploadGuardProvider(props: LocalUploadGuardProviderProps) {\n const {\n children,\n beforeUnloadMessage,\n navigationConfirmMessage = DEFAULT_NAVIGATION_CONFIRM_MESSAGE,\n unsavedWorkConfirmMessage = DEFAULT_UNSAVED_WORK_CONFIRM_MESSAGE,\n uploadAndUnsavedWorkConfirmMessage = DEFAULT_UPLOAD_AND_UNSAVED_WORK_CONFIRM_MESSAGE,\n } = props;\n // One-shot: the user already confirmed the full-page navigation now unloading.\n const bypassNextUnloadRef = useRef(false);\n // Also run when work registers: work that starts after a confirmation was not covered by it.\n const clearBypass = useCallback(() => {\n bypassNextUnloadRef.current = false;\n }, []);\n\n const uploads = useRegistry(clearBypass);\n const unsavedWork = useRegistry(clearBypass);\n const uploadIdsRef = uploads.idsRef;\n const unsavedWorkIdsRef = unsavedWork.idsRef;\n const guardedWorkCount = uploads.count + unsavedWork.count;\n const hasGuardedWork = guardedWorkCount > 0;\n\n // Read at the moment of asking, so a message always matches what is registered right then.\n const confirmMessage = useCallback((): string => {\n const uploading = uploadIdsRef.current.size > 0;\n const unsaved = unsavedWorkIdsRef.current.size > 0;\n if (uploading && unsaved) return uploadAndUnsavedWorkConfirmMessage;\n return uploading ? navigationConfirmMessage : unsavedWorkConfirmMessage;\n }, [\n uploadIdsRef,\n unsavedWorkIdsRef,\n navigationConfirmMessage,\n unsavedWorkConfirmMessage,\n uploadAndUnsavedWorkConfirmMessage,\n ]);\n\n useEffect(() => {\n if (!hasGuardedWork) return;\n\n const handleBeforeUnload = (event: BeforeUnloadEvent) => {\n if (bypassNextUnloadRef.current) {\n bypassNextUnloadRef.current = false;\n return;\n }\n event.preventDefault();\n // Modern browsers may ignore the custom string and show their own generic confirmation;\n // what matters is that leaving is warned, not the exact text.\n event.returnValue =\n beforeUnloadMessage ??\n (uploadIdsRef.current.size > 0\n ? DEFAULT_UPLOAD_BEFORE_UNLOAD_MESSAGE\n : DEFAULT_UNSAVED_WORK_BEFORE_UNLOAD_MESSAGE);\n return event.returnValue;\n };\n\n window.addEventListener('beforeunload', handleBeforeUnload);\n return () => {\n window.removeEventListener('beforeunload', handleBeforeUnload);\n };\n }, [hasGuardedWork, beforeUnloadMessage, uploadIdsRef]);\n\n // A back/forward-cache return re-shows this page without reloading it: an\n // armed bypass from the navigation that left must never outlive that navigation.\n useEffect(() => {\n window.addEventListener('pageshow', clearBypass);\n return () => {\n window.removeEventListener('pageshow', clearBypass);\n };\n }, [clearBypass]);\n\n const shouldConfirmNavigation = useCallback(\n () => uploadIdsRef.current.size > 0 || unsavedWorkIdsRef.current.size > 0,\n [uploadIdsRef, unsavedWorkIdsRef],\n );\n\n const confirmNavigation = useCallback(\n (options?: ConfirmNavigationOptions): boolean => {\n // SSR / non-browser safety: if `window` isn't available, default to allow.\n if (typeof window === 'undefined') return true;\n const proceed = !shouldConfirmNavigation() || window.confirm(confirmMessage());\n if (proceed && options?.fullPageNavigation) bypassNextUnloadRef.current = true;\n return proceed;\n },\n [shouldConfirmNavigation, confirmMessage],\n );\n\n const value = useMemo<LocalUploadGuardContextValue>(\n () => ({\n activeUploadCount: uploads.count,\n unsavedWorkCount: unsavedWork.count,\n guardedWorkCount,\n registerUpload: uploads.register,\n unregisterUpload: uploads.unregister,\n registerUnsavedWork: unsavedWork.register,\n unregisterUnsavedWork: unsavedWork.unregister,\n shouldConfirmNavigation,\n confirmNavigation,\n }),\n [\n uploads.count,\n uploads.register,\n uploads.unregister,\n unsavedWork.count,\n unsavedWork.register,\n unsavedWork.unregister,\n guardedWorkCount,\n shouldConfirmNavigation,\n confirmNavigation,\n ],\n );\n\n return (\n <LocalUploadGuardContext.Provider value={value}>{children}</LocalUploadGuardContext.Provider>\n );\n}\n\n/**\n * Low-level accessor for the guard context. Throws if used outside a\n * `LocalUploadGuardProvider`. Most consumers should use `useLocalUploadGuard`\n * (the public re-export below) instead.\n */\nexport function useLocalUploadGuardContext(): LocalUploadGuardContextValue {\n const ctx = useContext(LocalUploadGuardContext);\n if (ctx === undefined) {\n throw new Error('useLocalUploadGuard must be used within LocalUploadGuardProvider');\n }\n return ctx;\n}\n\n/**\n * Optional accessor: returns the guard context, or `null` when rendered\n * outside a `LocalUploadGuardProvider`. For package components (e.g. the\n * chat composer registering an in-flight send) that must degrade gracefully\n * in consumers that don't mount the provider, instead of throwing.\n */\nexport function useOptionalLocalUploadGuard(): LocalUploadGuardContextValue | null {\n return useContext(LocalUploadGuardContext) ?? null;\n}\n\n/**\n * Public hook for the navigation and leave guard.\n *\n * Typical usage in an upload flow:\n *\n * const { registerUpload, unregisterUpload } = useLocalUploadGuard();\n * useEffect(() => {\n * if (phase === 'preparing' || phase === 'uploading') {\n * registerUpload(uploadId);\n * return () => unregisterUpload(uploadId);\n * }\n * }, [phase, uploadId, registerUpload, unregisterUpload]);\n *\n * An editor holding input uses `useUnsavedWorkGuard(hasUnsavedWork)` instead.\n */\nexport function useLocalUploadGuard(): LocalUploadGuardContextValue {\n return useLocalUploadGuardContext();\n}\n\n/**\n * Registers the calling editor's unsaved input with the leave guard while `hasUnsavedWork` is\n * true, and unregisters it when that turns false or the editor unmounts. While registered, closing\n * the tab, reloading, a full-page navigation, and every guarded in-app navigation ask first.\n * Throws outside a `LocalUploadGuardProvider`.\n *\n * Returns `release`, which unregisters at once: an editor that saves and then navigates in the\n * same handler calls it after the save, because its dirty flag clears only on the next render.\n */\nexport function useUnsavedWorkGuard(hasUnsavedWork: boolean): { release: () => void } {\n const { registerUnsavedWork, unregisterUnsavedWork } = useLocalUploadGuardContext();\n const id = useId();\n useEffect(() => {\n if (!hasUnsavedWork) return;\n registerUnsavedWork(id);\n return () => unregisterUnsavedWork(id);\n }, [hasUnsavedWork, id, registerUnsavedWork, unregisterUnsavedWork]);\n const release = useCallback(() => unregisterUnsavedWork(id), [id, unregisterUnsavedWork]);\n return useMemo(() => ({ release }), [release]);\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-guarded-navigation.d.ts","sourceRoot":"","sources":["../../../src/react/guard/use-guarded-navigation.ts"],"names":[],"mappings":"AAyBA,OAAO,EAEL,KAAK,wBAAwB,EAC9B,MAAM,kCAAkC,CAAC;AAE1C;;;;;;GAMG;AACH,wBAAgB,oBAAoB,IAAI,CACtC,iBAAiB,EAAE,MAAM,IAAI,EAC7B,OAAO,CAAC,EAAE,wBAAwB,KAC/B,IAAI,CAUR"}
@@ -21,7 +21,7 @@
21
21
  * For links, use the `<GuardedLink>` render-prop wrapper.
22
22
  */
23
23
  import { useCallback } from 'react';
24
- import { useLocalUploadGuard } from './local-upload-guard-provider.js';
24
+ import { useLocalUploadGuard, } from './local-upload-guard-provider.js';
25
25
  /**
26
26
  * Returns a callable that wraps a navigation action. Calling the returned
27
27
  * function with `performNavigation` either invokes it immediately (when
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-guarded-navigation.js","sourceRoot":"","sources":["../../../src/react/guard/use-guarded-navigation.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACpC,OAAO,EACL,mBAAmB,GAEpB,MAAM,kCAAkC,CAAC;AAE1C;;;;;;GAMG;AACH,MAAM,UAAU,oBAAoB;IAIlC,MAAM,EAAE,iBAAiB,EAAE,GAAG,mBAAmB,EAAE,CAAC;IACpD,OAAO,WAAW,CAChB,CAAC,iBAA6B,EAAE,OAAkC,EAAE,EAAE;QACpE,IAAI,iBAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;YAC/B,iBAAiB,EAAE,CAAC;QACtB,CAAC;IACH,CAAC,EACD,CAAC,iBAAiB,CAAC,CACpB,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\n/**\n * Wraps a navigation action so it prompts the user while an upload or unsaved\n * work is registered. Returns a function that takes the consumer's actual navigation\n * call and either runs it immediately (nothing registered) or shows a confirm()\n * dialog first.\n *\n * Designed to be framework-agnostic — the consumer supplies the navigator\n * (Next.js router.push, React Router navigate, plain location.assign, etc.).\n * A FULL-PAGE navigator (`location.assign` / `location.replace`) passes\n * `{ fullPageNavigation: true }`, so the unload that follows a confirmed\n * navigation does not raise the browser's own \"Leave site?\" as a second prompt\n * (see `ConfirmNavigationOptions`). Router navigations pass nothing.\n *\n * Typical use inside a button:\n *\n * const guardedNav = useGuardedNavigation();\n * <Button onClick={() => guardedNav(() => router.push('/somewhere'))}>Go</Button>\n * <Button onClick={() => guardedNav(() => location.assign(url), { fullPageNavigation: true })}>Leave</Button>\n *\n * For links, use the `<GuardedLink>` render-prop wrapper.\n */\n\nimport { useCallback } from 'react';\nimport {\n useLocalUploadGuard,\n type ConfirmNavigationOptions,\n} from './local-upload-guard-provider.js';\n\n/**\n * Returns a callable that wraps a navigation action. Calling the returned\n * function with `performNavigation` either invokes it immediately (when\n * nothing is registered) or shows a confirmation prompt; if the user confirms,\n * `performNavigation` is invoked. `options` passes through to\n * `confirmNavigation()`.\n */\nexport function useGuardedNavigation(): (\n performNavigation: () => void,\n options?: ConfirmNavigationOptions,\n) => void {\n const { confirmNavigation } = useLocalUploadGuard();\n return useCallback(\n (performNavigation: () => void, options?: ConfirmNavigationOptions) => {\n if (confirmNavigation(options)) {\n performNavigation();\n }\n },\n [confirmNavigation],\n );\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-flight-uploads-provider.d.ts","sourceRoot":"","sources":["../../../src/react/tray/in-flight-uploads-provider.tsx"],"names":[],"mappings":"AAsBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAQL,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AACf,OAAO,EAGL,wBAAwB,EACxB,KAAK,6BAA6B,EAClC,KAAK,kBAAkB,EACxB,MAAM,gCAAgC,CAAC;AASxC,qEAAqE;AACrE,MAAM,MAAM,oBAAoB,GAAG,kBAAkB,CAAC;AAEtD;;;;;;;GAOG;AACH,MAAM,MAAM,kBAAkB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,IAAI;IACpE,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,WAAW,CA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AiG;IACjG,QAAQ,EAAE,OAAO,CAAC;CACnB;AAID,MAAM,WAAW,4BAA4B,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM;IAC/E,OAAO,EAAE,sBAAsB,CAAC,WAAW,CAAC,CAAC;IAC7C,0FAA0F;IAC1F,SAAS,CAAC,EAAE,oBAAoB,CAAC;IACjC,QAAQ,EAAE,SAAS,CAAC;CACrB;AA4DD,wBAAgB,uBAAuB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,EACzE,KAAK,EAAE,4BAA4B,CAAC,WAAW,CAAC,+BA0PjD;AAMD,wBAAgB,uBAAuB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,KAAK,GAAG,CACjF,MAAM,EACN,cAAc,CAAC,WAAW,CAAC,CAC5B,CAMA;AAED,wBAAgB,iBAAiB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,EACnE,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAC5B,cAAc,CAAC,WAAW,CAAC,GAAG,SAAS,CAOzC;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,IAAI,kBAAkB,CAM1D;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,IAAI,kBAAkB,CAM1D;AAMD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,EAClE,IAAI,EAAE,cAAc,CAAC,WAAW,CAAC,GAChC,IAAI,IAAI,OAAO,CAAC,cAAc,CAAC,WAAW,CAAC,EAAE;IAAE,MAAM,EAAE,6BAA6B,CAAA;CAAE,CAAC,CAEzF;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,WAAW,SAAS,MAAM,GAAG,MAAM,KAChC,cAAc,CAAC,WAAW,CAAC,EAAE,CAUjC"}
@@ -1,9 +1,8 @@
1
1
  'use client';
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  // ─────────────────────────────────────────────────────────────────────────────
4
- // SANCTIONED EXCEPTION to the "packages read/write Firestore only through
5
- // @ttt-productions/query-core" rule (see docs/packages/package-architecture.md →
6
- // "Firestore access goes through query-core").
4
+ // SANCTIONED EXCEPTION to ARCH-206 (packages read and write Firestore only
5
+ // through @ttt-productions/query-core).
7
6
  //
8
7
  // WHY this provider reads Firestore directly instead of via a query-core hook:
9
8
  // 1. It needs snapshot *transition events* — onSnapshot's `docChanges()` with
@@ -102,10 +101,10 @@ function fromParsed(parsed) {
102
101
  violationId: parsed.violationId,
103
102
  uploadTrayClearedAt: parsed.uploadTrayClearedAt,
104
103
  uploadTrayClearedBy: parsed.uploadTrayClearedBy,
105
- // Carry the seen fields through (round-9 finding 9): dropping them on the
106
- // `rejected` branch — while `completed`/`failed` keep them — made a seen
107
- // rejected upload relight the Files dot forever, because the tray's
108
- // unseen-terminal check never saw `uploadTraySeenAt`.
104
+ // Carry the seen fields through on the `rejected` branch as `completed` /
105
+ // `failed` do: without them a seen rejected upload relights the Files dot
106
+ // forever, because the tray's unseen-terminal check never sees
107
+ // `uploadTraySeenAt`.
109
108
  uploadTraySeenAt: parsed.uploadTraySeenAt,
110
109
  uploadTraySeenBy: parsed.uploadTraySeenBy,
111
110
  };
@@ -227,7 +226,11 @@ export function InFlightUploadsProvider(props) {
227
226
  // (the server may refuse again). Otherwise a snapshot after a failed listener comes from a new
228
227
  // subscription: not yet live, never offline.
229
228
  if (!(restarting && fromCache)) {
230
- setSourceState((prev) => fromCache ? (prev === 'connecting' || prev === 'error' ? 'connecting' : 'offline') : 'live');
229
+ setSourceState((prev) => fromCache
230
+ ? prev === 'connecting' || prev === 'error'
231
+ ? 'connecting'
232
+ : 'offline'
233
+ : 'live');
231
234
  restarting = false;
232
235
  setRetrying(false);
233
236
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"in-flight-uploads-provider.js","sourceRoot":"","sources":["../../../src/react/tray/in-flight-uploads-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,gFAAgF;AAChF,2EAA2E;AAC3E,wC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EjC,OAAO,4BAA4B,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACnD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,sBAAsB;IAGpC,MAAM,OAAO,GAAG,uBAAuB,EAAe,CAAC;IACvD,OAAO,OAAO,CAAC,GAAG,EAAE;QAClB,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;aAChC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE;YACf,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC;gBAAE,OAAO,IAAI,CAAC;YACzC,OAAO,IAAI,CAAC,mBAAmB,KAAK,SAAS,CAAC;QAChD,CAAC,CAAC;aACD,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC;IAC/C,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;AAChB,CAAC;AAED,gFAAgF;AAChF,gDAAgD;AAChD,gFAAgF;AAEhF;;;;;;;;;;;;;;;GAeG;AACH,MAAM,yBAAyB,GAAyB,CAAC,IAAI,EAAE,EAAE;IAC/D,MAAM,CAAC,GAAG,KAAK,CACb,UAAU,CAAC,IAAI,CAAC,EAAS,EAAE,IAAI,CAAC,cAAc,CAAC,EAC/C,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAClC,KAAK,CAAC,WAAW,EAAE,IAAI,EAAE,IAAI,CAAC,aAAa,CAAC,CAC7C,CAAC;IACF,sFAAsF;IACtF,uFAAuF;IACvF,OAAO,UAAU,CACf,CAAC,EACD,EAAE,sBAAsB,EAAE,IAAI,EAAE,EAChC,IAAI,CAAC,UAAmB,EACxB,IAAI,CAAC,OAAgB,CACtB,CAAC;AACJ,CAAC,CAAC","sourcesContent":["'use client';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// SANCTIONED EXCEPTION to ARCH-206 (packages read and write Firestore only\n// through @ttt-productions/query-core).\n//\n// WHY this provider reads Firestore directly instead of via a query-core hook:\n// 1. It needs snapshot *transition events* — onSnapshot's `docChanges()` with\n// added / modified / removed — to fire one-shot terminal callbacks and to\n// suppress the initial snapshot. query-core's hooks return \"the current\n// list\", not per-doc transitions, so they cannot express this state machine.\n// 2. The subscription is already abstracted behind an injectable\n// `FirestoreSubscribeFn` (the `subscribe` prop); the direct firebase code\n// path lives ONLY in `defaultFirestoreSubscribe` below and is fully\n// swappable (tests / alternate backends inject their own).\n// 3. The static ESM `firebase/firestore` import is load-bearing for Next.js +\n// Turbopack module identity (see defaultFirestoreSubscribe's comment).\n//\n// Do NOT \"migrate\" this onto query-core without preserving docChanges() semantics.\n// ─────────────────────────────────────────────────────────────────────────────\nimport { collection, onSnapshot, query, where } from 'firebase/firestore';\n\n/**\n * Generic in-flight uploads provider.\n *\n * Provides a global Map of in-flight upload state by `pendingMediaId`, derived\n * from a Firestore listener over the consumer-supplied collection. On terminal\n * status transitions observed THIS SESSION, fires consumer-supplied success /\n * failure / rejection callbacks. Records monitoring breadcrumbs and parse\n * errors through the injected monitoring callback.\n *\n * EVERY app-specific value is supplied by the consumer:\n * - userId resolution\n * - Firestore `db` reference\n * - collection path\n * - listener time window (ms)\n * - parser/schema for raw Firestore doc → typed PendingMedia\n * - success copy per origin\n * - notification callback (cache invalidation, etc.)\n * - toast callback\n * - rejection callback (for the media-rejection dialog or equivalent)\n * - monitoring callback (breadcrumbs + captured errors)\n *\n * Read APIs:\n * - `useInFlightUploadsState()` — full Map.\n * - `useInFlightUpload(id)` — single doc, narrowable on status.\n * - `useUploadActivityState()` — tray-visible items, sorted newest-first.\n *\n * The package owns the deduplication, initial-snapshot suppression, and\n * non-terminal → terminal transition tracking. It does NOT own anything about\n * what a file-origin is or what message text appears in toasts.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport {\n isPendingMediaNonTerminalStatus,\n isPendingMediaTerminalStatus,\n PendingMediaStatusSchema,\n type PendingMediaNonTerminalStatus,\n type PendingMediaStatus,\n} from '@ttt-productions/media-schemas';\n\n// Status values derive from media-schemas' one declaration.\nconst STATUS = PendingMediaStatusSchema.enum;\n\n// =============================================================================\n// Generic shape of the data the provider tracks\n// =============================================================================\n\n/** Generic pending-media status — media-schemas' one declaration. */\nexport type InFlightUploadStatus = PendingMediaStatus;\n\n/**\n * Generic in-flight upload record. The provider keeps a Map<id, InFlightUpload>\n * built from each parsed PendingMedia. Consumers parameterize the `fileOrigin`\n * type via the parser's return type (the provider treats it as opaque).\n *\n * `TFileOrigin` defaults to `string` so unannotated consumers get a permissive\n * shape; consuming apps bind it to their own `FileOrigin` union at the call site.\n */\nexport type InFlightUploadBase<TFileOrigin extends string = string> = {\n id: string;\n fileOrigin: TFileOrigin;\n surface: string;\n createdAt: number;\n targetIds?: string[];\n originalContentType?: string;\n originalSize?: number;\n};\n\nexport type InFlightUploadActive<TFileOrigin extends string = string> =\n InFlightUploadBase<TFileOrigin> & {\n status: PendingMediaNonTerminalStatus;\n };\n\nexport type InFlightUploadCompleted<TFileOrigin extends string = string> =\n InFlightUploadBase<TFileOrigin> & {\n status: typeof PendingMediaStatusSchema.enum.completed;\n completedAt: number;\n uploadTrayClearedAt?: number;\n uploadTrayClearedBy?: string;\n uploadTraySeenAt?: number;\n uploadTraySeenBy?: string;\n };\n\nexport type InFlightUploadFailed<TFileOrigin extends string = string> =\n InFlightUploadBase<TFileOrigin> & {\n status: typeof PendingMediaStatusSchema.enum.failed;\n failedAt: number;\n errorCategory: string;\n errorMessage: string;\n uploadTrayClearedAt?: number;\n uploadTrayClearedBy?: string;\n uploadTraySeenAt?: number;\n uploadTraySeenBy?: string;\n };\n\nexport type InFlightUploadRejected<TFileOrigin extends string = string> =\n InFlightUploadBase<TFileOrigin> & {\n status: typeof PendingMediaStatusSchema.enum.rejected;\n rejectedAt: number;\n rejectionType: 'text' | 'media';\n errorMessage: string;\n violationId?: string;\n uploadTrayClearedAt?: number;\n uploadTrayClearedBy?: string;\n uploadTraySeenAt?: number;\n uploadTraySeenBy?: string;\n };\n\nexport type InFlightUpload<TFileOrigin extends string = string> =\n | InFlightUploadActive<TFileOrigin>\n | InFlightUploadCompleted<TFileOrigin>\n | InFlightUploadFailed<TFileOrigin>\n | InFlightUploadRejected<TFileOrigin>;\n\n// =============================================================================\n// Adapter contract — every app-specific behavior is injected here\n// =============================================================================\n\n/**\n * Result of the consumer-supplied parser. The provider keeps the raw parsed\n * record for callbacks (so consumers can read domain events, target IDs, etc.)\n * AND derives the generic InFlightUpload from it for the public Map.\n *\n * The parser MUST throw if validation fails; the provider catches and routes\n * the error to the monitoring callback.\n */\nexport type ParsedPendingMedia<TFileOrigin extends string = string> = {\n id: string;\n userId: string;\n fileOrigin: TFileOrigin;\n status: InFlightUploadStatus;\n createdAt: number;\n surface: string;\n targetIds?: string[];\n originalContentType?: string;\n originalSize?: number;\n // Terminal-status fields (only meaningful for the matching status)\n completedAt?: number;\n failedAt?: number;\n rejectedAt?: number;\n errorCategory?: string;\n errorMessage?: string;\n rejectionType?: 'text' | 'media';\n violationId?: string;\n uploadTrayClearedAt?: number;\n uploadTrayClearedBy?: string;\n uploadTraySeenAt?: number;\n uploadTraySeenBy?: string;\n /**\n * Opaque consumer-controlled domain-event payload, surfaced to the\n * `onUploadCompleted` and `onUploadRejected` callbacks for cache\n * invalidation. The provider does not interpret it.\n */\n domainEvents?: unknown;\n};\n\nexport type InFlightUploadsAdapter<TFileOrigin extends string = string> = {\n /** Returns the current user's uid, or null if not signed in. */\n getCurrentUserId: () => string | null;\n\n /** Firestore database adapter (loose typing — `unknown` keeps zero firebase coupling at the type level). */\n db: unknown;\n\n /** Collection path holding pending-media docs (e.g. \"pendingMedia\"). */\n collectionPath: string;\n\n /** Listener window in milliseconds — only docs with `createdAt >= now - window` are tracked. */\n listenerWindowMs: number;\n\n /**\n * Parse a raw Firestore doc snapshot's `.data()` into the generic shape the\n * provider tracks. Throws on validation failure; the provider routes thrown\n * errors to `onMonitoringEvent`.\n */\n parsePendingMedia: (raw: unknown) => ParsedPendingMedia<TFileOrigin>;\n\n /** Called once per observed non-terminal → terminal completed transition. */\n onUploadCompleted: (parsed: ParsedPendingMedia<TFileOrigin>) => void;\n\n /** Called once per observed non-terminal → terminal failed transition. */\n onUploadFailed: (parsed: ParsedPendingMedia<TFileOrigin>) => void;\n\n /** Called once per observed non-terminal → terminal rejected transition. */\n onUploadRejected: (parsed: ParsedPendingMedia<TFileOrigin>) => void;\n\n /**\n * Monitoring callback. Receives:\n * - `breadcrumb`: informational, fired on every observed terminal transition.\n * - `parse-error`: when `parsePendingMedia` throws.\n * - `listener-error`: when the Firestore listener's error callback fires.\n *\n * Consumers wire this to Sentry, OpenTelemetry, or any other observability\n * provider. The provider does NOT import any monitoring SDK directly.\n */\n onMonitoringEvent: (event: InFlightUploadsMonitoringEvent<TFileOrigin>) => void;\n};\n\nexport type InFlightUploadsMonitoringEvent<TFileOrigin extends string = string> =\n | {\n type: 'breadcrumb';\n category: 'upload.terminal';\n level: 'info';\n message: string;\n data: {\n id: string;\n fileOrigin: TFileOrigin;\n status: InFlightUploadStatus;\n surface: string;\n };\n }\n | {\n type: 'parse-error';\n docId: string;\n error: unknown;\n data: unknown;\n }\n | {\n type: 'listener-error';\n error: unknown;\n };\n\n// =============================================================================\n// Firestore subscription contract — abstracted to avoid firebase coupling\n// =============================================================================\n\n/**\n * Minimal subscription contract used by the provider. The default\n * implementation lives in `firestore-subscribe.ts` and uses the standard\n * `firebase/firestore` `onSnapshot` + `query` + `where` builders.\n *\n * Tests inject a fake to drive the listener without spinning up Firestore.\n */\nexport type FirestoreSubscribeFn = (args: {\n db: unknown;\n collectionPath: string;\n userId: string;\n windowStartMs: number;\n onSnapshot: (snapshot: FirestoreLikeSnapshot) => void;\n onError: (error: unknown) => void;\n}) => () => void;\n\nexport type FirestoreLikeSnapshot = {\n docChanges: () => FirestoreLikeDocChange[];\n /**\n * Snapshot metadata. Present when the subscription is opened with\n * `{ includeMetadataChanges: true }` (the default firebase implementation does).\n * `fromCache === false` means a server-confirmed snapshot. Optional so injected\n * test fakes need not supply it (absent ⇒ treated as server-confirmed).\n */\n metadata?: { fromCache: boolean };\n};\n\n/**\n * Metadata-derived liveness of the uploads listener, mirroring query-core's\n * `FirestoreSourceState`. Firestore serves cached snapshots offline WITHOUT\n * firing the error callback, so the Files tray source needs this to show a\n * degraded indicator instead of a false \"all caught up\":\n * - `connecting` — no server-confirmed snapshot yet.\n * - `live` — at least one server-confirmed snapshot (`fromCache === false`).\n * - `offline` — only cached data after having been live.\n * - `error` — the listener error callback fired.\n */\nexport type UploadsSourceState = 'connecting' | 'live' | 'offline' | 'error';\n\nexport type FirestoreLikeDocChange = {\n type: 'added' | 'modified' | 'removed';\n doc: {\n id: string;\n data: () => unknown;\n };\n};\n\n// =============================================================================\n// Provider\n// =============================================================================\n\ninterface InFlightUploadsContextValue<TFileOrigin extends string = string> {\n uploads: Map<string, InFlightUpload<TFileOrigin>>;\n sourceState: UploadsSourceState;\n retry: () => void;\n retrying: boolean;\n}\n\n/** Restarting the uploads listener after it failed, and whether that restart is running. */\nexport interface UploadsSourceRetry {\n /**\n * Tear the listener down and subscribe again on a fresh retry ladder. While the restart runs the\n * source state stays as it was (an `error` stays `error`), so a failure shown on it stays on\n * screen with its control pending.\n */\n retry: () => void;\n /** A `retry` is running: true until the restarted listener answers or its ladder fails again. */\n retrying: boolean;\n}\n\nconst InFlightUploadsContext = createContext<InFlightUploadsContextValue | undefined>(undefined);\n\nexport interface InFlightUploadsProviderProps<TFileOrigin extends string = string> {\n adapter: InFlightUploadsAdapter<TFileOrigin>;\n /** Firestore subscription function. Defaults to the firebase/firestore implementation. */\n subscribe?: FirestoreSubscribeFn;\n children: ReactNode;\n}\n\nfunction fromParsed<TFileOrigin extends string>(\n parsed: ParsedPendingMedia<TFileOrigin>,\n): InFlightUpload<TFileOrigin> {\n const base: InFlightUploadBase<TFileOrigin> = {\n id: parsed.id,\n fileOrigin: parsed.fileOrigin,\n surface: parsed.surface,\n createdAt: parsed.createdAt,\n targetIds: parsed.targetIds,\n originalContentType: parsed.originalContentType,\n originalSize: parsed.originalSize,\n };\n if (isPendingMediaNonTerminalStatus(parsed.status)) {\n return { ...base, status: parsed.status };\n }\n if (parsed.status === STATUS.completed) {\n return {\n ...base,\n status: STATUS.completed,\n completedAt: parsed.completedAt ?? parsed.createdAt,\n uploadTrayClearedAt: parsed.uploadTrayClearedAt,\n uploadTrayClearedBy: parsed.uploadTrayClearedBy,\n uploadTraySeenAt: parsed.uploadTraySeenAt,\n uploadTraySeenBy: parsed.uploadTraySeenBy,\n };\n }\n if (parsed.status === STATUS.failed) {\n return {\n ...base,\n status: STATUS.failed,\n failedAt: parsed.failedAt ?? parsed.createdAt,\n errorCategory: parsed.errorCategory ?? 'system',\n errorMessage: parsed.errorMessage ?? '',\n uploadTrayClearedAt: parsed.uploadTrayClearedAt,\n uploadTrayClearedBy: parsed.uploadTrayClearedBy,\n uploadTraySeenAt: parsed.uploadTraySeenAt,\n uploadTraySeenBy: parsed.uploadTraySeenBy,\n };\n }\n // rejected\n return {\n ...base,\n status: STATUS.rejected,\n rejectedAt: parsed.rejectedAt ?? parsed.createdAt,\n rejectionType: parsed.rejectionType ?? 'media',\n errorMessage: parsed.errorMessage ?? '',\n violationId: parsed.violationId,\n uploadTrayClearedAt: parsed.uploadTrayClearedAt,\n uploadTrayClearedBy: parsed.uploadTrayClearedBy,\n // Carry the seen fields through on the `rejected` branch as `completed` /\n // `failed` do: without them a seen rejected upload relights the Files dot\n // forever, because the tray's unseen-terminal check never sees\n // `uploadTraySeenAt`.\n uploadTraySeenAt: parsed.uploadTraySeenAt,\n uploadTraySeenBy: parsed.uploadTraySeenBy,\n };\n}\n\nexport function InFlightUploadsProvider<TFileOrigin extends string = string>(\n props: InFlightUploadsProviderProps<TFileOrigin>,\n) {\n const { adapter, subscribe = defaultFirestoreSubscribe, children } = props;\n\n const [uploads, setUploads] = useState<Map<string, InFlightUpload<TFileOrigin>>>(new Map());\n const [sourceState, setSourceState] = useState<UploadsSourceState>('connecting');\n const [restarts, setRestarts] = useState(0);\n const [retrying, setRetrying] = useState(false);\n /** Set by `retry` for the subscription the restart opens; that run keeps the source state. */\n const restartRequestedRef = useRef(false);\n const seenTerminalIdsRef = useRef<Set<string>>(new Set());\n const statusByIdRef = useRef<Map<string, InFlightUploadStatus>>(new Map());\n const hasProcessedInitialSnapshotRef = useRef(false);\n /** The identity the dedup/tracking refs belong to — they outlive resubscribes\n * for the SAME user (auth-settling flaps) and reset only on a real identity\n * change. See the reset block in the subscription effect. */\n const trackedUserIdRef = useRef<string | null>(null);\n\n // Stable refs for adapter callbacks — read from latest adapter inside effect.\n const adapterRef = useRef(adapter);\n useEffect(() => {\n adapterRef.current = adapter;\n });\n\n const userId = adapter.getCurrentUserId();\n\n useEffect(() => {\n // The uploads map and source state rebuild from every subscription's initial\n // snapshot, so they reset on every effect run. The terminal-dedup and\n // status-tracking refs are IDENTITY-scoped, not subscription-scoped: an\n // auth-settling flap (uid → null → same uid re-subscribes) must neither\n // re-fire terminals the previous subscription already fired (seen set\n // persists) nor lose the observed non-terminal statuses that let the new\n // subscription's initial listing detect a transition that completed during\n // the gap. A real identity change — including UID-A → UID-B with no\n // intermediate null user — starts clean; never rely on an intermediate\n // sign-out to clear refs between two authenticated UIDs.\n // A restart the person asked for keeps the source state it had (a failure stays a failure\n // until the restarted listener answers); every other run starts over as `connecting`.\n // A restart belongs to the identity it was asked for: one that lands with a sign-out or a switch\n // of account is an ordinary new subscription, which starts over.\n let restarting =\n restartRequestedRef.current && userId !== null && userId === trackedUserIdRef.current;\n restartRequestedRef.current = false;\n setUploads(new Map());\n if (!restarting) {\n setSourceState('connecting');\n setRetrying(false);\n }\n if (userId !== null && userId !== trackedUserIdRef.current) {\n seenTerminalIdsRef.current = new Set();\n statusByIdRef.current = new Map();\n trackedUserIdRef.current = userId;\n }\n hasProcessedInitialSnapshotRef.current = false;\n\n if (!userId) {\n return;\n }\n\n const a = adapterRef.current;\n const windowStartMs = Date.now() - a.listenerWindowMs;\n\n const handleSnapshot = (snapshot: FirestoreLikeSnapshot) => {\n const updates: Array<{ id: string; upload: InFlightUpload<TFileOrigin> | null }> = [];\n const newlyTerminal: Array<ParsedPendingMedia<TFileOrigin>> = [];\n const isInitialSnapshot = !hasProcessedInitialSnapshotRef.current;\n\n for (const change of snapshot.docChanges()) {\n if (change.type === 'removed') {\n updates.push({ id: change.doc.id, upload: null });\n statusByIdRef.current.delete(change.doc.id);\n seenTerminalIdsRef.current.delete(change.doc.id);\n continue;\n }\n\n let parsed: ParsedPendingMedia<TFileOrigin>;\n try {\n parsed = adapterRef.current.parsePendingMedia(change.doc.data());\n } catch (error) {\n adapterRef.current.onMonitoringEvent({\n type: 'parse-error',\n docId: change.doc.id,\n error,\n data: change.doc.data(),\n });\n continue;\n }\n\n const upload = fromParsed(parsed);\n updates.push({ id: parsed.id, upload });\n\n const previousStatus = statusByIdRef.current.get(parsed.id);\n const currentStatus = parsed.status;\n const currentIsTerminal = isPendingMediaTerminalStatus(currentStatus);\n const previousWasNonTerminal = isPendingMediaNonTerminalStatus(previousStatus);\n\n if (isInitialSnapshot) {\n // A subscription's first snapshot is a (re-)listing of current state,\n // not a live event: already-terminal docs stay suppressed so a page\n // refresh never re-toasts. ONE exception — this provider instance\n // tracked the doc as non-terminal before (same-identity resubscribe\n // gap; the tracking refs survive those), so the terminal listing IS\n // the transition, observed across the gap, and must fire.\n if (currentIsTerminal) {\n if (previousWasNonTerminal && !seenTerminalIdsRef.current.has(parsed.id)) {\n newlyTerminal.push(parsed);\n }\n seenTerminalIdsRef.current.add(parsed.id);\n }\n } else if (currentIsTerminal && !seenTerminalIdsRef.current.has(parsed.id)) {\n // Any unseen terminal in a LIVE snapshot fires — including a doc whose\n // FIRST client-visible state is already terminal. A fast backend\n // outcome (moderation rejection in ~2s) can coalesce created→terminal\n // into one delivery, and the uploader is actively waiting on exactly\n // this callback; swallowing it silently loses a rejection dialog.\n seenTerminalIdsRef.current.add(parsed.id);\n newlyTerminal.push(parsed);\n }\n\n statusByIdRef.current.set(parsed.id, currentStatus);\n }\n\n hasProcessedInitialSnapshotRef.current = true;\n\n // Metadata-derived source state: stay `connecting` until a server-confirmed\n // snapshot, `offline` if only cached data arrives after being live.\n const fromCache = snapshot.metadata?.fromCache ?? false;\n // A restart ends on the server's answer: a cached snapshot during it keeps the failure on screen\n // (the server may refuse again). Otherwise a snapshot after a failed listener comes from a new\n // subscription: not yet live, never offline.\n if (!(restarting && fromCache)) {\n setSourceState((prev) =>\n fromCache\n ? prev === 'connecting' || prev === 'error'\n ? 'connecting'\n : 'offline'\n : 'live',\n );\n restarting = false;\n setRetrying(false);\n }\n\n if (updates.length > 0) {\n setUploads((prev) => {\n const next = new Map(prev);\n for (const { id, upload } of updates) {\n if (upload === null) next.delete(id);\n else next.set(id, upload);\n }\n return next;\n });\n }\n\n for (const parsed of newlyTerminal) {\n handleTerminal(parsed);\n }\n };\n\n function handleTerminal(parsed: ParsedPendingMedia<TFileOrigin>) {\n adapterRef.current.onMonitoringEvent({\n type: 'breadcrumb',\n category: 'upload.terminal',\n level: 'info',\n message: `${parsed.fileOrigin}:${parsed.status}`,\n data: {\n id: parsed.id,\n fileOrigin: parsed.fileOrigin,\n status: parsed.status,\n surface: parsed.surface,\n },\n });\n\n if (parsed.status === STATUS.completed) {\n adapterRef.current.onUploadCompleted(parsed);\n } else if (parsed.status === STATUS.failed) {\n adapterRef.current.onUploadFailed(parsed);\n } else if (parsed.status === STATUS.rejected) {\n adapterRef.current.onUploadRejected(parsed);\n }\n }\n\n // Bounded RESUBSCRIBE on listener error: a cold-session race (e.g. Firestore\n // App Check enforcement rejecting the first attach before the token is\n // minted) must not kill the listener for the whole session — observed live:\n // one permission-denied at first login → sourceState 'error' forever, every\n // tray file status dead until reload. Retry on a short ladder; a snapshot\n // resets the ladder (healthy again); exhausting it goes terminal 'error'\n // (a real rules denial stays denied — retries are cheap and bounded).\n const RESUBSCRIBE_DELAYS_MS = [1_000, 3_000, 10_000, 30_000];\n let attempt = 0;\n let disposed = false;\n let retryTimer: ReturnType<typeof setTimeout> | undefined;\n let unsubscribe: (() => void) | undefined;\n\n const start = () => {\n unsubscribe = subscribe({\n db: a.db,\n collectionPath: a.collectionPath,\n userId,\n windowStartMs,\n onSnapshot: (snapshot) => {\n attempt = 0; // healthy — future errors get a fresh ladder\n handleSnapshot(snapshot);\n },\n onError: (error) => {\n adapterRef.current.onMonitoringEvent({ type: 'listener-error', error });\n unsubscribe?.();\n unsubscribe = undefined;\n if (disposed || attempt >= RESUBSCRIBE_DELAYS_MS.length) {\n setSourceState('error');\n setRetrying(false);\n return;\n }\n if (!restarting) setSourceState('connecting');\n retryTimer = setTimeout(() => {\n if (disposed) return;\n attempt += 1;\n start();\n }, RESUBSCRIBE_DELAYS_MS[attempt]);\n },\n });\n };\n start();\n\n return () => {\n disposed = true;\n if (retryTimer) clearTimeout(retryTimer);\n unsubscribe?.();\n };\n // adapter is intentionally NOT in the deps array — adapter is read via\n // adapterRef on every snapshot, so identity changes don't re-subscribe.\n }, [userId, subscribe, restarts]);\n\n const retry = useCallback(() => {\n restartRequestedRef.current = true;\n setRetrying(true);\n setRestarts((count) => count + 1);\n }, []);\n\n const value = useMemo<InFlightUploadsContextValue<TFileOrigin>>(\n () => ({ uploads, sourceState, retry, retrying }),\n [uploads, sourceState, retry, retrying],\n );\n\n return (\n <InFlightUploadsContext.Provider value={value as InFlightUploadsContextValue}>\n {children}\n </InFlightUploadsContext.Provider>\n );\n}\n\n// =============================================================================\n// Read APIs\n// =============================================================================\n\nexport function useInFlightUploadsState<TFileOrigin extends string = string>(): Map<\n string,\n InFlightUpload<TFileOrigin>\n> {\n const ctx = useContext(InFlightUploadsContext);\n if (ctx === undefined) {\n throw new Error('useInFlightUploadsState must be used within InFlightUploadsProvider');\n }\n return ctx.uploads as Map<string, InFlightUpload<TFileOrigin>>;\n}\n\nexport function useInFlightUpload<TFileOrigin extends string = string>(\n id: string | null | undefined,\n): InFlightUpload<TFileOrigin> | undefined {\n const ctx = useContext(InFlightUploadsContext);\n if (ctx === undefined) {\n throw new Error('useInFlightUpload must be used within InFlightUploadsProvider');\n }\n if (!id) return undefined;\n return ctx.uploads.get(id) as InFlightUpload<TFileOrigin> | undefined;\n}\n\n/**\n * Metadata-derived source state of the uploads listener\n * (`connecting | live | offline | error`). The Files tray uses this to show a\n * degraded indicator and never display \"all caught up\" while the source is\n * `offline`/`error`/`connecting`.\n */\nexport function useUploadsSourceState(): UploadsSourceState {\n const ctx = useContext(InFlightUploadsContext);\n if (ctx === undefined) {\n throw new Error('useUploadsSourceState must be used within InFlightUploadsProvider');\n }\n return ctx.sourceState;\n}\n\n/**\n * The uploads listener's restart — the Try again of a failure shown on `useUploadsSourceState` —\n * and whether it is running.\n */\nexport function useUploadsSourceRetry(): UploadsSourceRetry {\n const ctx = useContext(InFlightUploadsContext);\n if (ctx === undefined) {\n throw new Error('useUploadsSourceRetry must be used within InFlightUploadsProvider');\n }\n return { retry: ctx.retry, retrying: ctx.retrying };\n}\n\n// =============================================================================\n// Tray helpers\n// =============================================================================\n\n/**\n * `true` for `completed` / `failed` / `rejected`. Used by tray UI to decide\n * whether a Clear action is available for an item.\n */\nexport function isTerminalUpload<TFileOrigin extends string = string>(\n item: InFlightUpload<TFileOrigin>,\n): item is Exclude<InFlightUpload<TFileOrigin>, { status: PendingMediaNonTerminalStatus }> {\n return isPendingMediaTerminalStatus(item.status);\n}\n\n/**\n * Tray-visible items. Includes every pending/processing upload, plus terminal\n * uploads that have NOT been cleared from the tray. Sorted newest-first by\n * createdAt.\n *\n * The public selector name in upload-ui is `useUploadActivityState`. The\n * mutation hook is `useClearUploadActivity` (in a separate file).\n */\nexport function useUploadActivityState<\n TFileOrigin extends string = string,\n>(): InFlightUpload<TFileOrigin>[] {\n const uploads = useInFlightUploadsState<TFileOrigin>();\n return useMemo(() => {\n return Array.from(uploads.values())\n .filter((item) => {\n if (!isTerminalUpload(item)) return true;\n return item.uploadTrayClearedAt === undefined;\n })\n .sort((a, b) => b.createdAt - a.createdAt);\n }, [uploads]);\n}\n\n// =============================================================================\n// Default Firestore subscription implementation\n// =============================================================================\n\n/**\n * Default Firestore subscription using the consumer's `firebase/firestore`\n * module instance (via static ESM import at the top of this file).\n *\n * Using static ESM import — NOT `require()` — is load-bearing. CommonJS\n * `require('firebase/firestore')` and ESM `import 'firebase/firestore'` resolve\n * to different module instances under Next.js + Turbopack. If the consumer\n * constructs `db` via ESM and we receive it here, but we then call\n * `collection()` from a CJS-loaded copy of firebase, the firebase runtime\n * does not recognize the db as a Firestore instance and throws\n * \"Expected first argument to collection() to be a CollectionReference,\n * a DocumentReference or FirebaseFirestore\".\n *\n * Consumers who want to skip the firebase code path entirely (tests, alt\n * backends) supply their own `subscribe` prop to `InFlightUploadsProvider`.\n */\nconst defaultFirestoreSubscribe: FirestoreSubscribeFn = (args) => {\n const q = query(\n collection(args.db as any, args.collectionPath),\n where('userId', '==', args.userId),\n where('createdAt', '>=', args.windowStartMs),\n );\n // includeMetadataChanges so the provider can derive a `connecting|live|offline|error`\n // source state from `snapshot.metadata.fromCache` (the Files tray degraded indicator).\n return onSnapshot(\n q,\n { includeMetadataChanges: true },\n args.onSnapshot as never,\n args.onError as never,\n );\n};\n"]}
@@ -1,5 +1,5 @@
1
- export { InFlightUploadsProvider, useInFlightUploadsState, useInFlightUpload, useUploadActivityState, useUploadsSourceState, useUploadsSourceRetry, isTerminalUpload, type UploadsSourceState, type UploadsSourceRetry, type InFlightUpload, type InFlightUploadActive, type InFlightUploadCompleted, type InFlightUploadFailed, type InFlightUploadRejected, type InFlightUploadBase, type InFlightUploadStatus, type InFlightUploadsAdapter, type InFlightUploadsMonitoringEvent, type InFlightUploadsProviderProps, type ParsedPendingMedia, type FirestoreSubscribeFn, type FirestoreLikeSnapshot, type FirestoreLikeDocChange, } from '../in-flight-uploads-provider.js';
2
- export { useClearUploadActivity, type ClearUploadActivityOptions, } from '../use-clear-upload-activity.js';
3
- export { useMarkUploadActivitySeen, type MarkUploadActivitySeenOptions, } from '../use-mark-upload-activity-seen.js';
4
- export { useUploadProcessing, type UploadProcessingState, type UseUploadProcessingOptions, } from '../use-upload-processing.js';
1
+ export { InFlightUploadsProvider, useInFlightUploadsState, useInFlightUpload, useUploadActivityState, useUploadsSourceState, useUploadsSourceRetry, isTerminalUpload, type UploadsSourceState, type UploadsSourceRetry, type InFlightUpload, type InFlightUploadActive, type InFlightUploadCompleted, type InFlightUploadFailed, type InFlightUploadRejected, type InFlightUploadBase, type InFlightUploadStatus, type InFlightUploadsAdapter, type InFlightUploadsMonitoringEvent, type InFlightUploadsProviderProps, type ParsedPendingMedia, type FirestoreSubscribeFn, type FirestoreLikeSnapshot, type FirestoreLikeDocChange, } from './in-flight-uploads-provider.js';
2
+ export { useClearUploadActivity, type ClearUploadActivityOptions, } from './use-clear-upload-activity.js';
3
+ export { useMarkUploadActivitySeen, MarkUploadActivitySeenError, type MarkUploadActivitySeenOptions, } from './use-mark-upload-activity-seen.js';
4
+ export { useUploadProcessing, type UploadProcessingState, type UseUploadProcessingOptions, } from './use-upload-processing.js';
5
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/react/tray/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,EACrB,gBAAgB,EAChB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,cAAc,EACnB,KAAK,oBAAoB,EACzB,KAAK,uBAAuB,EAC5B,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,EAC3B,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,EAC3B,KAAK,8BAA8B,EACnC,KAAK,4BAA4B,EACjC,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EACzB,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,GAC5B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,sBAAsB,EACtB,KAAK,0BAA0B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,yBAAyB,EACzB,KAAK,6BAA6B,GACnC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,mBAAmB,EACnB,KAAK,qBAAqB,EAC1B,KAAK,0BAA0B,GAChC,MAAM,6BAA6B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/react/tray/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,EACrB,gBAAgB,EAChB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,cAAc,EACnB,KAAK,oBAAoB,EACzB,KAAK,uBAAuB,EAC5B,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,EAC3B,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,EAC3B,KAAK,8BAA8B,EACnC,KAAK,4BAA4B,EACjC,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EACzB,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,GAC5B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,sBAAsB,EACtB,KAAK,0BAA0B,GAChC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,yBAAyB,EACzB,2BAA2B,EAC3B,KAAK,6BAA6B,GACnC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,mBAAmB,EACnB,KAAK,qBAAqB,EAC1B,KAAK,0BAA0B,GAChC,MAAM,4BAA4B,CAAC"}
@@ -1,5 +1,5 @@
1
- export { InFlightUploadsProvider, useInFlightUploadsState, useInFlightUpload, useUploadActivityState, useUploadsSourceState, useUploadsSourceRetry, isTerminalUpload, } from '../in-flight-uploads-provider.js';
2
- export { useClearUploadActivity, } from '../use-clear-upload-activity.js';
3
- export { useMarkUploadActivitySeen, } from '../use-mark-upload-activity-seen.js';
4
- export { useUploadProcessing, } from '../use-upload-processing.js';
1
+ export { InFlightUploadsProvider, useInFlightUploadsState, useInFlightUpload, useUploadActivityState, useUploadsSourceState, useUploadsSourceRetry, isTerminalUpload, } from './in-flight-uploads-provider.js';
2
+ export { useClearUploadActivity, } from './use-clear-upload-activity.js';
3
+ export { useMarkUploadActivitySeen, MarkUploadActivitySeenError, } from './use-mark-upload-activity-seen.js';
4
+ export { useUploadProcessing, } from './use-upload-processing.js';
5
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/react/tray/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,EACrB,gBAAgB,GAiBjB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,sBAAsB,GAEvB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,yBAAyB,GAE1B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,mBAAmB,GAGpB,MAAM,6BAA6B,CAAC","sourcesContent":["export {\n InFlightUploadsProvider,\n useInFlightUploadsState,\n useInFlightUpload,\n useUploadActivityState,\n useUploadsSourceState,\n useUploadsSourceRetry,\n isTerminalUpload,\n type UploadsSourceState,\n type UploadsSourceRetry,\n type InFlightUpload,\n type InFlightUploadActive,\n type InFlightUploadCompleted,\n type InFlightUploadFailed,\n type InFlightUploadRejected,\n type InFlightUploadBase,\n type InFlightUploadStatus,\n type InFlightUploadsAdapter,\n type InFlightUploadsMonitoringEvent,\n type InFlightUploadsProviderProps,\n type ParsedPendingMedia,\n type FirestoreSubscribeFn,\n type FirestoreLikeSnapshot,\n type FirestoreLikeDocChange,\n} from '../in-flight-uploads-provider.js';\nexport {\n useClearUploadActivity,\n type ClearUploadActivityOptions,\n} from '../use-clear-upload-activity.js';\nexport {\n useMarkUploadActivitySeen,\n type MarkUploadActivitySeenOptions,\n} from '../use-mark-upload-activity-seen.js';\nexport {\n useUploadProcessing,\n type UploadProcessingState,\n type UseUploadProcessingOptions,\n} from '../use-upload-processing.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/react/tray/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,iBAAiB,EACjB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,EACrB,gBAAgB,GAiBjB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,sBAAsB,GAEvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,yBAAyB,EACzB,2BAA2B,GAE5B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,mBAAmB,GAGpB,MAAM,4BAA4B,CAAC","sourcesContent":["export {\n InFlightUploadsProvider,\n useInFlightUploadsState,\n useInFlightUpload,\n useUploadActivityState,\n useUploadsSourceState,\n useUploadsSourceRetry,\n isTerminalUpload,\n type UploadsSourceState,\n type UploadsSourceRetry,\n type InFlightUpload,\n type InFlightUploadActive,\n type InFlightUploadCompleted,\n type InFlightUploadFailed,\n type InFlightUploadRejected,\n type InFlightUploadBase,\n type InFlightUploadStatus,\n type InFlightUploadsAdapter,\n type InFlightUploadsMonitoringEvent,\n type InFlightUploadsProviderProps,\n type ParsedPendingMedia,\n type FirestoreSubscribeFn,\n type FirestoreLikeSnapshot,\n type FirestoreLikeDocChange,\n} from './in-flight-uploads-provider.js';\nexport {\n useClearUploadActivity,\n type ClearUploadActivityOptions,\n} from './use-clear-upload-activity.js';\nexport {\n useMarkUploadActivitySeen,\n MarkUploadActivitySeenError,\n type MarkUploadActivitySeenOptions,\n} from './use-mark-upload-activity-seen.js';\nexport {\n useUploadProcessing,\n type UploadProcessingState,\n type UseUploadProcessingOptions,\n} from './use-upload-processing.js';\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-clear-upload-activity.d.ts","sourceRoot":"","sources":["../../../src/react/tray/use-clear-upload-activity.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAe,KAAK,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEtE,MAAM,WAAW,0BAA0B;IACzC,sEAAsE;IACtE,OAAO,EAAE,CAAC,cAAc,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACnD,sFAAsF;IACtF,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,cAAc,EAAE,MAAM,KAAK,IAAI,CAAC;IACzD;;;;OAIG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;CAC3B;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,0BAA0B,mFASzE"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-clear-upload-activity.js","sourceRoot":"","sources":["../../../src/react/tray/use-clear-upload-activity.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,WAAW,EAAoB,MAAM,uBAAuB,CAAC;AAetE,MAAM,UAAU,sBAAsB,CAAC,OAAmC;IACxE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;IAClD,OAAO,WAAW,CAAsB;QACtC,WAAW;QACX,UAAU,EAAE,OAAO;QACnB,OAAO,EAAE,CAAC,KAAK,EAAE,cAAc,EAAE,EAAE;YACjC,OAAO,EAAE,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;QACnC,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["'use client';\n\n/**\n * Generic mutation hook to clear a terminal pendingMedia item from the tray.\n *\n * Pure adapter: the consumer supplies `clearFn` (typically a wrapped Firebase\n * callable in the consuming app, or a fetch call elsewhere). The package owns the\n * useMutation wiring and the optional `onError` toast hook; the consumer owns\n * the network call.\n *\n * The provider's Firestore listener observes the `uploadTrayClearedAt` write\n * and removes the item from the tray selector automatically — no optimistic\n * update is needed in this hook.\n *\n * The returned object is the standard `useMutation` result (`mutate`,\n * `mutateAsync`, `isPending`, …). Pass `mutationKey` to register the clear in\n * React Query's shared `MutationCache` under a stable key, so a consumer can\n * read per-item pending with `useMutationState` (the pendingMediaId is the\n * mutation variables) — pending that survives the clearing row unmounting.\n */\n\nimport { useMutation, type MutationKey } from '@tanstack/react-query';\n\nexport interface ClearUploadActivityOptions {\n /** Network call performing the clear. Receives the pendingMediaId. */\n clearFn: (pendingMediaId: string) => Promise<void>;\n /** Optional error callback. Receives the error and the pendingMediaId that failed. */\n onError?: (error: Error, pendingMediaId: string) => void;\n /**\n * Optional stable key for the underlying mutation, registering it in the\n * shared `MutationCache` so pending can be read with `useMutationState`.\n * Omitted ⇒ an unkeyed mutation (the prior behavior).\n */\n mutationKey?: MutationKey;\n}\n\nexport function useClearUploadActivity(options: ClearUploadActivityOptions) {\n const { clearFn, onError, mutationKey } = options;\n return useMutation<void, Error, string>({\n mutationKey,\n mutationFn: clearFn,\n onError: (error, pendingMediaId) => {\n onError?.(error, pendingMediaId);\n },\n });\n}\n"]}
@@ -0,0 +1,16 @@
1
+ export interface MarkUploadActivitySeenOptions {
2
+ /** Network call performing the mark-seen for at most `maxIdsPerCall` pendingMediaIds. */
3
+ markFn: (pendingMediaIds: string[]) => Promise<void>;
4
+ /** The most ids one `markFn` call accepts — the app's own per-call cap. */
5
+ maxIdsPerCall: number;
6
+ /** Optional error callback. Receives the first failure and every id that was not marked. */
7
+ onError?: (error: Error, pendingMediaIds: string[]) => void;
8
+ }
9
+ /** The mutation's failure when one or more calls failed: the first failure, and the ids left unmarked. */
10
+ export declare class MarkUploadActivitySeenError extends Error {
11
+ readonly failure: Error;
12
+ readonly unmarkedIds: string[];
13
+ constructor(failure: Error, unmarkedIds: string[]);
14
+ }
15
+ export declare function useMarkUploadActivitySeen(options: MarkUploadActivitySeenOptions): import("@tanstack/react-query").UseMutationResult<void, Error, string[], unknown>;
16
+ //# sourceMappingURL=use-mark-upload-activity-seen.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-mark-upload-activity-seen.d.ts","sourceRoot":"","sources":["../../../src/react/tray/use-mark-upload-activity-seen.ts"],"names":[],"mappings":"AAyBA,MAAM,WAAW,6BAA6B;IAC5C,yFAAyF;IACzF,MAAM,EAAE,CAAC,eAAe,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACrD,2EAA2E;IAC3E,aAAa,EAAE,MAAM,CAAC;IACtB,4FAA4F;IAC5F,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,KAAK,IAAI,CAAC;CAC7D;AAED,0GAA0G;AAC1G,qBAAa,2BAA4B,SAAQ,KAAK;IACpD,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;IACxB,QAAQ,CAAC,WAAW,EAAE,MAAM,EAAE,CAAC;gBAEnB,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE;CAMlD;AAwBD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,6BAA6B,qFAS/E"}
@@ -0,0 +1,65 @@
1
+ 'use client';
2
+ /**
3
+ * Generic mutation hook to mark terminal pendingMedia items as seen in the tray.
4
+ *
5
+ * Pure adapter: the consumer supplies `markFn` (typically a wrapped Firebase
6
+ * callable in the consuming app that writes `uploadTraySeenAt`/`uploadTraySeenBy` on the
7
+ * caller's own terminal pendingMedia docs). The package owns the useMutation
8
+ * wiring and the optional `onError` hook; the consumer owns the network call.
9
+ *
10
+ * The provider's Firestore listener observes the `uploadTraySeenAt` write and
11
+ * updates the in-flight upload records automatically — no optimistic update is
12
+ * needed in this hook. Marking seen is tray UX state, not a sensitive action,
13
+ * so it mirrors `useClearUploadActivity` exactly (no audit event).
14
+ *
15
+ * The mutation takes every id to mark (typically every currently-unseen terminal
16
+ * item when the File-status tab opens) and sends them to `markFn` in sequential
17
+ * calls of at most `maxIdsPerCall` — the app's own per-call cap, so no call is
18
+ * refused for its size. A failed call does not stop the rest: its ids simply stay
19
+ * unseen. When any call failed, the mutation fails, and `onError` receives the first
20
+ * failure and every id left unmarked. An empty array makes no call.
21
+ */
22
+ import { useMutation } from '@tanstack/react-query';
23
+ /** The mutation's failure when one or more calls failed: the first failure, and the ids left unmarked. */
24
+ export class MarkUploadActivitySeenError extends Error {
25
+ failure;
26
+ unmarkedIds;
27
+ constructor(failure, unmarkedIds) {
28
+ super(failure.message);
29
+ this.name = 'MarkUploadActivitySeenError';
30
+ this.failure = failure;
31
+ this.unmarkedIds = unmarkedIds;
32
+ }
33
+ }
34
+ async function markInBatches(markFn, maxIdsPerCall, pendingMediaIds) {
35
+ if (!Number.isInteger(maxIdsPerCall) || maxIdsPerCall < 1) {
36
+ throw new Error(`maxIdsPerCall must be a positive whole number, got ${maxIdsPerCall}.`);
37
+ }
38
+ let firstFailure = null;
39
+ const unmarkedIds = [];
40
+ for (let start = 0; start < pendingMediaIds.length; start += maxIdsPerCall) {
41
+ const batch = pendingMediaIds.slice(start, start + maxIdsPerCall);
42
+ try {
43
+ await markFn(batch);
44
+ }
45
+ catch (err) {
46
+ firstFailure ??= err instanceof Error ? err : new Error(String(err));
47
+ unmarkedIds.push(...batch);
48
+ }
49
+ }
50
+ if (firstFailure)
51
+ throw new MarkUploadActivitySeenError(firstFailure, unmarkedIds);
52
+ }
53
+ export function useMarkUploadActivitySeen(options) {
54
+ const { markFn, maxIdsPerCall, onError } = options;
55
+ return useMutation({
56
+ mutationFn: (pendingMediaIds) => markInBatches(markFn, maxIdsPerCall, pendingMediaIds),
57
+ onError: (error, pendingMediaIds) => {
58
+ if (error instanceof MarkUploadActivitySeenError)
59
+ onError?.(error.failure, error.unmarkedIds);
60
+ else
61
+ onError?.(error, pendingMediaIds);
62
+ },
63
+ });
64
+ }
65
+ //# sourceMappingURL=use-mark-upload-activity-seen.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-mark-upload-activity-seen.js","sourceRoot":"","sources":["../../../src/react/tray/use-mark-upload-activity-seen.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAWpD,0GAA0G;AAC1G,MAAM,OAAO,2BAA4B,SAAQ,KAAK;IAC3C,OAAO,CAAQ;IACf,WAAW,CAAW;IAE/B,YAAY,OAAc,EAAE,WAAqB;QAC/C,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,6BAA6B,CAAC;QAC1C,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF;AAED,KAAK,UAAU,aAAa,CAC1B,MAAoD,EACpD,aAAqB,EACrB,eAAyB;IAEzB,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,aAAa,CAAC,IAAI,aAAa,GAAG,CAAC,EAAE,CAAC;QAC1D,MAAM,IAAI,KAAK,CAAC,sDAAsD,aAAa,GAAG,CAAC,CAAC;IAC1F,CAAC;IACD,IAAI,YAAY,GAAiB,IAAI,CAAC;IACtC,MAAM,WAAW,GAAa,EAAE,CAAC;IACjC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,eAAe,CAAC,MAAM,EAAE,KAAK,IAAI,aAAa,EAAE,CAAC;QAC3E,MAAM,KAAK,GAAG,eAAe,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,aAAa,CAAC,CAAC;QAClE,IAAI,CAAC;YACH,MAAM,MAAM,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,YAAY,KAAK,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;YACrE,WAAW,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;IACD,IAAI,YAAY;QAAE,MAAM,IAAI,2BAA2B,CAAC,YAAY,EAAE,WAAW,CAAC,CAAC;AACrF,CAAC;AAED,MAAM,UAAU,yBAAyB,CAAC,OAAsC;IAC9E,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACnD,OAAO,WAAW,CAAwB;QACxC,UAAU,EAAE,CAAC,eAAe,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,aAAa,EAAE,eAAe,CAAC;QACtF,OAAO,EAAE,CAAC,KAAK,EAAE,eAAe,EAAE,EAAE;YAClC,IAAI,KAAK,YAAY,2BAA2B;gBAAE,OAAO,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,WAAW,CAAC,CAAC;;gBACzF,OAAO,EAAE,CAAC,KAAK,EAAE,eAAe,CAAC,CAAC;QACzC,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["'use client';\n\n/**\n * Generic mutation hook to mark terminal pendingMedia items as seen in the tray.\n *\n * Pure adapter: the consumer supplies `markFn` (typically a wrapped Firebase\n * callable in the consuming app that writes `uploadTraySeenAt`/`uploadTraySeenBy` on the\n * caller's own terminal pendingMedia docs). The package owns the useMutation\n * wiring and the optional `onError` hook; the consumer owns the network call.\n *\n * The provider's Firestore listener observes the `uploadTraySeenAt` write and\n * updates the in-flight upload records automatically — no optimistic update is\n * needed in this hook. Marking seen is tray UX state, not a sensitive action,\n * so it mirrors `useClearUploadActivity` exactly (no audit event).\n *\n * The mutation takes every id to mark (typically every currently-unseen terminal\n * item when the File-status tab opens) and sends them to `markFn` in sequential\n * calls of at most `maxIdsPerCall` — the app's own per-call cap, so no call is\n * refused for its size. A failed call does not stop the rest: its ids simply stay\n * unseen. When any call failed, the mutation fails, and `onError` receives the first\n * failure and every id left unmarked. An empty array makes no call.\n */\n\nimport { useMutation } from '@tanstack/react-query';\n\nexport interface MarkUploadActivitySeenOptions {\n /** Network call performing the mark-seen for at most `maxIdsPerCall` pendingMediaIds. */\n markFn: (pendingMediaIds: string[]) => Promise<void>;\n /** The most ids one `markFn` call accepts — the app's own per-call cap. */\n maxIdsPerCall: number;\n /** Optional error callback. Receives the first failure and every id that was not marked. */\n onError?: (error: Error, pendingMediaIds: string[]) => void;\n}\n\n/** The mutation's failure when one or more calls failed: the first failure, and the ids left unmarked. */\nexport class MarkUploadActivitySeenError extends Error {\n readonly failure: Error;\n readonly unmarkedIds: string[];\n\n constructor(failure: Error, unmarkedIds: string[]) {\n super(failure.message);\n this.name = 'MarkUploadActivitySeenError';\n this.failure = failure;\n this.unmarkedIds = unmarkedIds;\n }\n}\n\nasync function markInBatches(\n markFn: (pendingMediaIds: string[]) => Promise<void>,\n maxIdsPerCall: number,\n pendingMediaIds: string[],\n): Promise<void> {\n if (!Number.isInteger(maxIdsPerCall) || maxIdsPerCall < 1) {\n throw new Error(`maxIdsPerCall must be a positive whole number, got ${maxIdsPerCall}.`);\n }\n let firstFailure: Error | null = null;\n const unmarkedIds: string[] = [];\n for (let start = 0; start < pendingMediaIds.length; start += maxIdsPerCall) {\n const batch = pendingMediaIds.slice(start, start + maxIdsPerCall);\n try {\n await markFn(batch);\n } catch (err) {\n firstFailure ??= err instanceof Error ? err : new Error(String(err));\n unmarkedIds.push(...batch);\n }\n }\n if (firstFailure) throw new MarkUploadActivitySeenError(firstFailure, unmarkedIds);\n}\n\nexport function useMarkUploadActivitySeen(options: MarkUploadActivitySeenOptions) {\n const { markFn, maxIdsPerCall, onError } = options;\n return useMutation<void, Error, string[]>({\n mutationFn: (pendingMediaIds) => markInBatches(markFn, maxIdsPerCall, pendingMediaIds),\n onError: (error, pendingMediaIds) => {\n if (error instanceof MarkUploadActivitySeenError) onError?.(error.failure, error.unmarkedIds);\n else onError?.(error, pendingMediaIds);\n },\n });\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-upload-processing.d.ts","sourceRoot":"","sources":["../../../src/react/tray/use-upload-processing.ts"],"names":[],"mappings":"AAwBA,MAAM,WAAW,qBAAqB;IACpC,MAAM,EACJ,MAAM,GAAG,SAAS,GAAG,YAAY,GAAG,SAAS,GAAG,QAAQ,GAAG,eAAe,GAAG,gBAAgB,CAAC;IAChG,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,OAAO,CAAC;IACtB,UAAU,EAAE,OAAO,CAAC;IACpB,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,EAAE,OAAO,CAAC;CACrB;AAOD,MAAM,WAAW,0BAA0B;IACzC,6CAA6C;IAC7C,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,0CAA0C;IAC1C,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,yCAAyC;IACzC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,2CAA2C;IAC3C,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAyED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,SAAS,MAAM,GAAG,MAAM,EACrE,cAAc,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACzC,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,qBAAqB,KAAK,IAAI,EACnD,OAAO,GAAE,0BAA+B,GACvC,qBAAqB,CA6BvB"}
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
  /**
3
- * Adapter that maps `useInFlightUpload` state to the legacy
3
+ * Adapter that maps `useInFlightUpload` state to the
4
4
  * `{ isProcessing, message, isComplete, isRejected, isFailed }` shape used
5
5
  * by per-component spinners and overlays.
6
6
  *
@@ -11,7 +11,7 @@
11
11
  * (clearing form state, closing modals, etc.).
12
12
  */
13
13
  import { useEffect, useRef } from 'react';
14
- import { isPendingMediaNonTerminalStatus, PendingMediaStatusSchema } from '@ttt-productions/media-schemas';
14
+ import { isPendingMediaNonTerminalStatus, PendingMediaStatusSchema, } from '@ttt-productions/media-schemas';
15
15
  import { useInFlightUpload } from './in-flight-uploads-provider.js';
16
16
  // Pending-media status values derive from media-schemas' one declaration.
17
17
  const STATUS = PendingMediaStatusSchema.enum;
@@ -109,7 +109,15 @@ export function useUploadProcessing(pendingMediaId, onTerminal, options = {}) {
109
109
  onTerminal(state);
110
110
  }
111
111
  }
112
- }, [pendingMediaId, state.status, state.isComplete, state.isFailed, state.isRejected, state, onTerminal]);
112
+ }, [
113
+ pendingMediaId,
114
+ state.status,
115
+ state.isComplete,
116
+ state.isFailed,
117
+ state.isRejected,
118
+ state,
119
+ onTerminal,
120
+ ]);
113
121
  return state;
114
122
  }
115
123
  //# sourceMappingURL=use-upload-processing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-upload-processing.js","sourceRoot":"","sources":["../../../src/react/tray/use-upload-processing.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAC1C,OAAO,EACL,+BAA+B,EAC/B,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAuB,MAAM,iCAAiC,CAAC;AAEzF,0EAA0E;AAC1E,MAAM,MAAM,GAAG,wBAAwB,CAAC,IAAI,CAAC;AAa7C,MAAM,0BAA0B,GAAG,4BAA4B,CAAC;AAChE,MAAM,uBAAuB,GAAG,WAAW,CAAC;AAC5C,MAAM,sBAAsB,GAAG,mBAAmB,CAAC;AACnD,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;AAapD,SAAS,UAAU,CACjB,MAA+C,EAC/C,IAAgC;IAEhC,MAAM,iBAAiB,GAAG,IAAI,C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AAU,CAAC,KAAK,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;IACH,CAAC,EAAE;QACD,cAAc;QACd,KAAK,CAAC,MAAM;QACZ,KAAK,CAAC,UAAU;QAChB,KAAK,CAAC,QAAQ;QACd,KAAK,CAAC,UAAU;QAChB,KAAK;QACL,UAAU;KACX,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["'use client';\n\n/**\n * Adapter that maps `useInFlightUpload` state to the\n * `{ isProcessing, message, isComplete, isRejected, isFailed }` shape used\n * by per-component spinners and overlays.\n *\n * Routing of toasts and rejection dialogs lives in `InFlightUploadsProvider`\n * via the consumer-supplied callbacks — `useUploadProcessing` only surfaces\n * local UI state. The `onTerminal` callback fires once per terminal status\n * (completed / failed / rejected) and is intended for local UI cleanup\n * (clearing form state, closing modals, etc.).\n */\n\nimport { useEffect, useRef } from 'react';\nimport {\n isPendingMediaNonTerminalStatus,\n PendingMediaStatusSchema,\n} from '@ttt-productions/media-schemas';\nimport { useInFlightUpload, type InFlightUpload } from './in-flight-uploads-provider.js';\n\n// Pending-media status values derive from media-schemas' one declaration.\nconst STATUS = PendingMediaStatusSchema.enum;\n\nexport interface UploadProcessingState {\n status:\n 'idle' | 'pending' | 'processing' | 'success' | 'failed' | 'rejected-text' | 'rejected-media';\n message: string;\n errorMessage?: string;\n isProcessing: boolean;\n isComplete: boolean;\n isFailed: boolean;\n isRejected: boolean;\n}\n\nconst DEFAULT_PROCESSING_MESSAGE = 'Processing your content...';\nconst DEFAULT_SUCCESS_MESSAGE = 'Complete!';\nconst DEFAULT_FAILED_MESSAGE = 'Processing failed';\nconst DEFAULT_REJECTED_MESSAGE = 'Content rejected';\n\nexport interface UseUploadProcessingOptions {\n /** Override the processing-phase message. */\n processingMessage?: string;\n /** Override the success-phase message. */\n successMessage?: string;\n /** Override the failed-phase message. */\n failedMessage?: string;\n /** Override the rejected-phase message. */\n rejectedMessage?: string;\n}\n\nfunction buildState<TFileOrigin extends string>(\n upload: InFlightUpload<TFileOrigin> | undefined,\n opts: UseUploadProcessingOptions,\n): UploadProcessingState {\n const processingMessage = opts.processingMessage ?? DEFAULT_PROCESSING_MESSAGE;\n const successMessage = opts.successMessage ?? DEFAULT_SUCCESS_MESSAGE;\n const failedMessage = opts.failedMessage ?? DEFAULT_FAILED_MESSAGE;\n const rejectedMessage = opts.rejectedMessage ?? DEFAULT_REJECTED_MESSAGE;\n\n if (!upload) {\n return {\n status: 'idle',\n message: '',\n isProcessing: false,\n isComplete: false,\n isFailed: false,\n isRejected: false,\n };\n }\n if (isPendingMediaNonTerminalStatus(upload.status)) {\n return {\n status: upload.status,\n message: processingMessage,\n isProcessing: true,\n isComplete: false,\n isFailed: false,\n isRejected: false,\n };\n }\n if (upload.status === STATUS.completed) {\n return {\n status: 'success',\n message: successMessage,\n isProcessing: false,\n isComplete: true,\n isFailed: false,\n isRejected: false,\n };\n }\n if (upload.status === STATUS.failed) {\n return {\n status: 'failed',\n message: failedMessage,\n errorMessage: upload.errorMessage,\n isProcessing: false,\n isComplete: false,\n isFailed: true,\n isRejected: false,\n };\n }\n if (upload.status === STATUS.rejected) {\n return {\n status: upload.rejectionType === 'text' ? 'rejected-text' : 'rejected-media',\n message: rejectedMessage,\n errorMessage: upload.errorMessage,\n isProcessing: false,\n isComplete: false,\n isFailed: false,\n isRejected: true,\n };\n }\n return {\n status: 'processing',\n message: processingMessage,\n isProcessing: true,\n isComplete: false,\n isFailed: false,\n isRejected: false,\n };\n}\n\n/**\n * Returns local UI processing state for the given pendingMediaId. If the\n * `onTerminal` callback is provided, it fires once when the doc reaches a\n * terminal status (completed / failed / rejected). Use `onTerminal` for\n * local UI cleanup — global toast/dialog routing belongs in the provider.\n */\nexport function useUploadProcessing<TFileOrigin extends string = string>(\n pendingMediaId: string | null | undefined,\n onTerminal?: (state: UploadProcessingState) => void,\n options: UseUploadProcessingOptions = {},\n): UploadProcessingState {\n const upload = useInFlightUpload<TFileOrigin>(pendingMediaId);\n const state = buildState(upload, options);\n const lastFiredRef = useRef<string | null>(null);\n\n useEffect(() => {\n if (!onTerminal) return;\n if (!pendingMediaId) {\n lastFiredRef.current = null;\n return;\n }\n if (state.isComplete || state.isFailed || state.isRejected) {\n const sig = `${pendingMediaId}:${state.status}`;\n if (lastFiredRef.current !== sig) {\n lastFiredRef.current = sig;\n onTerminal(state);\n }\n }\n }, [\n pendingMediaId,\n state.status,\n state.isComplete,\n state.isFailed,\n state.isRejected,\n state,\n onTerminal,\n ]);\n\n return state;\n}\n"]}
@@ -17,7 +17,7 @@ export interface DeferredUploadFormShellProps<TVariables extends {
17
17
  buildVariables: (file: File | null, onProgress: (s: UploadState | null) => void, signal: AbortSignal,
18
18
  /** The untrusted claim MediaInput emitted with the selected file (advisory;
19
19
  * the server byte inspection is the only classification authority). Rides
20
- * and clears with the file — additive 4th arg, existing callers unchanged. */
20
+ * and clears with the file. */
21
21
  claim?: ClientMediaClaim) => TVariables;
22
22
  onSuccess?: (result: TResult) => void;
23
23
  onError?: (err: unknown) => void;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deferred-upload-form-shell.d.ts","sourceRoot":"","sources":["../../../src/react/upload/deferred-upload-form-shell.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,EAMZ,KAAK,SAAS,EACd,KAAK,GAAG,EACT,MAAM,OAAO,CAAC;AAGf,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,WAAW,EACZ,MAAM,gCAAgC,CAAC;AAExC,MAAM,WAAW,6BAA6B;IAC5C,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB;AAED,MAAM,WAAW,4BAA4B,CAC3C,UAAU,SAAS;IACjB,UAAU,CAAC,EAAE,CAAC,CAAC,EAAE,WAAW,GAAG,IAAI,KAAK,IAAI,CAAC;IAC7C,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,EACD,OAAO,GAAG,OAAO;IAEjB;wFACoF;IACpF,IAAI,EAAE,eAAe,CAAC;IACtB,QAAQ,EAAE;QACR,WAAW,EAAE,CAAC,IAAI,EAAE,UAAU,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;QACpD,SAAS,EAAE,OAAO,CAAC;KACpB,CAAC;IACF,cAAc,EAAE,CACd,IAAI,EAAE,IAAI,GAAG,IAAI,EACjB,UAAU,EAAE,CAAC,CAAC,EAAE,WAAW,GAAG,IAAI,KAAK,IAAI,EAC3C,MAAM,EAAE,WAAW;IACnB;;oCAEgC;IAChC,KAAK,CAAC,EAAE,gBAAgB,KACrB,UAAU,CAAC;IAChB,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;IACtC,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAC;IACjC;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,KAAK,IAAI,CAAC;IAC3C;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAClD,QAAQ,CAAC,EAAE,SAAS,CAAC;CACtB;AA+GD,eAAO,MAAM,uBAAuB,EAA+C,CACjF,UAAU,SAAS;IACjB,UAAU,CAAC,EAAE,CAAC,CAAC,EAAE,WAAW,GAAG,IAAI,KAAK,IAAI,CAAC;IAC7C,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,EACD,OAAO,GAAG,OAAO,EAEjB,KAAK,EAAE,4BAA4B,CAAC,UAAU,EAAE,OAAO,CAAC,GAAG;IACzD,GAAG,CAAC,EAAE,GAAG,CAAC,6BAA6B,CAAC,CAAC;CAC1C,KACE,KAAK,CAAC,YAAY,CAAC"}
@@ -54,7 +54,11 @@ function DeferredUploadFormShellInner(props, ref) {
54
54
  abortControllerRef.current = null;
55
55
  }
56
56
  }, [mutation, selectedFile, selectedClaim, buildVariables, onSuccess, onError, onFileChange]);
57
- useImperativeHandle(ref, () => ({ submit: () => { void handleSubmit(); } }), [handleSubmit]);
57
+ useImperativeHandle(ref, () => ({
58
+ submit: () => {
59
+ void handleSubmit();
60
+ },
61
+ }), [handleSubmit]);
58
62
  return (_jsxs(_Fragment, { children: [children, _jsx("div", { ref: fileAreaRef, tabIndex: -1, "aria-live": "polite", className: "outline-none", children: _jsx(MediaInput, { spec: spec, selectedFile: selectedFile, uploadState: uploadState, isLoading: mutation.isPending, disabled: mutation.isPending, onChange: handleMediaChange, onClear: handleClear, onCancel: handleCancel, onBeforeSelect: onBeforeSelect }) })] }));
59
63
  }
60
64
  export const DeferredUploadFormShell = forwardRef(DeferredUploadFormShellInner);
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deferred-upload-form-shell.js","sourceRoot":"","sources":["../../../src/react/upload/deferred-upload-form-shell.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAc,EACZ,QAAQ,EACR,MAAM,EACN,WAAW,EACX,mBAAmB,EACnB,UAAU,GAGX,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAsD/D,SAAS,4BAA4B,CAOnC,KAAwD,EACxD,GAAuC;IAEvC,MAAM,EACJ,IAAI,EACJ,QAAQ,EACR,cAAc,EACd,SAAS,EACT,OAAO,EACP,YAAY,EACZ,cAAc,EACd,QAAQ,GACT,GAAG,KAAK,CAAC;IAEV,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,GAAG,QAAQ,CAAc,IAAI,CAAC,CAAC;IACpE,MAAM,CAAC,aAAa,EAAE,gBAAgB,CAAC,GAAG,QAAQ,CAA+B,SAAS,CAAC,CAAC;IAC5F,MAAM,CAAC,WAAW,EAAE,cAAc,CAAC,GAAG,QAAQ,CAAqB,IAAI,CAAC,CAAC;IACzE,MAAM,WAAW,GAAG,MAAM,CAAiB,IAAI,CAAC,CAAC;IACjD,MAAM,kBAAkB,GAAG,MAAM,CAAyB,IAAI,CAAC,CAAC;IAEhE,MAAM,iBAAiB,GAAG,WAAW,CACnC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YAAY,EACtB,cAAc,EAAE,cAAc,GAC9B,GACE,IACL,CACJ,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,uBAAuB,GAAG,UAAU,CAAC,4BAA4B,CAUvD,CAAC","sourcesContent":["'use client';\n\nimport React, {\n useState,\n useRef,\n useCallback,\n useImperativeHandle,\n forwardRef,\n type ReactNode,\n type Ref,\n} from 'react';\nimport { MediaInput } from '@ttt-productions/file-input/react';\nimport type { MediaInputChangePayload } from '@ttt-productions/file-input';\nimport type {\n ClientMediaClaim,\n MediaOriginSpec,\n UploadState,\n} from '@ttt-productions/media-schemas';\n\nexport interface DeferredUploadFormShellHandle {\n submit: () => void;\n}\n\nexport interface DeferredUploadFormShellProps<\n TVariables extends {\n onProgress?: (s: UploadState | null) => void;\n signal?: AbortSignal;\n },\n TResult = unknown,\n> {\n /** The media-origin spec describing accept patterns, size caps, and label.\n * Consumers pass this directly — the shell does not look it up from a registry. */\n spec: MediaOriginSpec;\n mutation: {\n mutateAsync: (vars: TVariables) => Promise<TResult>;\n isPending: boolean;\n };\n buildVariables: (\n file: File | null,\n onProgress: (s: UploadState | null) => void,\n signal: AbortSignal,\n /** The untrusted claim MediaInput emitted with the selected file (advisory;\n * the server byte inspection is the only classification authority). Rides\n * and clears with the file. */\n claim?: ClientMediaClaim,\n ) => TVariables;\n onSuccess?: (result: TResult) => void;\n onError?: (err: unknown) => void;\n /**\n * Optional callback fired whenever the shell's internal selectedFile state\n * changes — on user select, on user clear, and on the post-success internal\n * reset. Forms typically use this to mirror selectedFile externally so they\n * can compute their own submit-button `disabled` flag (e.g. require-a-file\n * submit gating).\n */\n onFileChange?: (file: File | null) => void;\n /**\n * Optional guard forwarded to MediaInput, fired before the picker/capture\n * opens for any action. Return false (or a Promise resolving false) to abort\n * — e.g. an email-verification gate. See MediaInputProps.onBeforeSelect.\n */\n onBeforeSelect?: () => boolean | Promise<boolean>;\n children?: ReactNode;\n}\n\nfunction DeferredUploadFormShellInner<\n TVariables extends {\n onProgress?: (s: UploadState | null) => void;\n signal?: AbortSignal;\n },\n TResult = unknown,\n>(\n props: DeferredUploadFormShellProps<TVariables, TResult>,\n ref: Ref<DeferredUploadFormShellHandle>,\n) {\n const {\n spec,\n mutation,\n buildVariables,\n onSuccess,\n onError,\n onFileChange,\n onBeforeSelect,\n children,\n } = props;\n\n const [selectedFile, setSelectedFile] = useState<File | null>(null);\n const [selectedClaim, setSelectedClaim] = useState<ClientMediaClaim | undefined>(undefined);\n const [uploadState, setUploadState] = useState<UploadState | null>(null);\n const fileAreaRef = useRef<HTMLDivElement>(null);\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const handleMediaChange = useCallback(\n (payload: MediaInputChangePayload) => {\n const next = payload.error ? null : (payload.file ?? null);\n setSelectedFile(next);\n setSelectedClaim(next ? payload.claim : undefined);\n onFileChange?.(next);\n },\n [onFileChange],\n );\n\n const handleClear = useCallback(() => {\n setSelectedFile(null);\n setSelectedClaim(undefined);\n onFileChange?.(null);\n }, [onFileChange]);\n\n const handleCancel = useCallback(() => {\n abortControllerRef.current?.abort();\n }, []);\n\n const handleSubmit = useCallback(async () => {\n if (mutation.isPending) return;\n if (selectedFile) {\n fileAreaRef.current?.focus();\n }\n const controller = new AbortController();\n abortControllerRef.current = controller;\n try {\n const result = await mutation.mutateAsync(\n buildVariables(selectedFile, setUploadState, controller.signal, selectedClaim),\n );\n setUploadState(null);\n setSelectedFile(null);\n setSelectedClaim(undefined);\n onFileChange?.(null);\n onSuccess?.(result);\n } catch (err) {\n setUploadState(null);\n // User-initiated cancel: swallow the AbortError, reset selection, do not fire onError.\n if (err instanceof Error && err.name === 'AbortError') {\n setSelectedFile(null);\n setSelectedClaim(undefined);\n onFileChange?.(null);\n return;\n }\n onError?.(err);\n } finally {\n abortControllerRef.current = null;\n }\n }, [mutation, selectedFile, selectedClaim, buildVariables, onSuccess, onError, onFileChange]);\n\n useImperativeHandle(\n ref,\n () => ({\n submit: () => {\n void handleSubmit();\n },\n }),\n [handleSubmit],\n );\n\n return (\n <>\n {children}\n\n <div ref={fileAreaRef} tabIndex={-1} aria-live=\"polite\" className=\"outline-none\">\n <MediaInput\n spec={spec}\n selectedFile={selectedFile}\n uploadState={uploadState}\n isLoading={mutation.isPending}\n disabled={mutation.isPending}\n onChange={handleMediaChange}\n onClear={handleClear}\n onCancel={handleCancel}\n onBeforeSelect={onBeforeSelect}\n />\n </div>\n </>\n );\n}\n\nexport const DeferredUploadFormShell = forwardRef(DeferredUploadFormShellInner) as <\n TVariables extends {\n onProgress?: (s: UploadState | null) => void;\n signal?: AbortSignal;\n },\n TResult = unknown,\n>(\n props: DeferredUploadFormShellProps<TVariables, TResult> & {\n ref?: Ref<DeferredUploadFormShellHandle>;\n },\n) => React.ReactElement;\n"]}