@ttt-productions/upload-ui 0.7.10 → 0.7.12
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.
- package/dist/react/guard/index.d.ts +1 -1
- package/dist/react/guard/index.d.ts.map +1 -1
- package/dist/react/guard/index.js.map +1 -1
- package/dist/react/in-flight-uploads-provider.d.ts +8 -10
- package/dist/react/in-flight-uploads-provider.d.ts.map +1 -1
- package/dist/react/in-flight-uploads-provider.js +15 -16
- package/dist/react/in-flight-uploads-provider.js.map +1 -1
- package/dist/react/local-upload-guard-provider.d.ts +17 -1
- package/dist/react/local-upload-guard-provider.d.ts.map +1 -1
- package/dist/react/local-upload-guard-provider.js +24 -4
- package/dist/react/local-upload-guard-provider.js.map +1 -1
- package/dist/react/use-guarded-navigation.d.ts +4 -2
- package/dist/react/use-guarded-navigation.d.ts.map +1 -1
- package/dist/react/use-guarded-navigation.js +9 -3
- package/dist/react/use-guarded-navigation.js.map +1 -1
- package/dist/react/use-upload-processing.d.ts.map +1 -1
- package/dist/react/use-upload-processing.js +7 -4
- package/dist/react/use-upload-processing.js.map +1 -1
- package/package.json +8 -15
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { LocalUploadGuardProvider, useLocalUploadGuard, useLocalUploadGuardContext, useOptionalLocalUploadGuard, type LocalUploadGuardProviderProps, } from '../local-upload-guard-provider.js';
|
|
1
|
+
export { LocalUploadGuardProvider, useLocalUploadGuard, useLocalUploadGuardContext, useOptionalLocalUploadGuard, type ConfirmNavigationOptions, type LocalUploadGuardProviderProps, } from '../local-upload-guard-provider.js';
|
|
2
2
|
export { useGuardedNavigation } from '../use-guarded-navigation.js';
|
|
3
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,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,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 +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,
|
|
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,GAG5B,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 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"]}
|
|
@@ -29,11 +29,9 @@
|
|
|
29
29
|
* what a file-origin is or what message text appears in toasts.
|
|
30
30
|
*/
|
|
31
31
|
import { type ReactNode } from 'react';
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
*/
|
|
36
|
-
export type InFlightUploadStatus = 'pending' | 'processing' | 'completed' | 'failed' | 'rejected';
|
|
32
|
+
import { PendingMediaStatusSchema, type PendingMediaNonTerminalStatus, type PendingMediaStatus } from '@ttt-productions/media-schemas';
|
|
33
|
+
/** Generic pending-media status — media-schemas' one declaration. */
|
|
34
|
+
export type InFlightUploadStatus = PendingMediaStatus;
|
|
37
35
|
/**
|
|
38
36
|
* Generic in-flight upload record. The provider keeps a Map<id, InFlightUpload>
|
|
39
37
|
* built from each parsed PendingMedia. Consumers parameterize the `fileOrigin`
|
|
@@ -52,10 +50,10 @@ export type InFlightUploadBase<TFileOrigin extends string = string> = {
|
|
|
52
50
|
originalSize?: number;
|
|
53
51
|
};
|
|
54
52
|
export type InFlightUploadActive<TFileOrigin extends string = string> = InFlightUploadBase<TFileOrigin> & {
|
|
55
|
-
status:
|
|
53
|
+
status: PendingMediaNonTerminalStatus;
|
|
56
54
|
};
|
|
57
55
|
export type InFlightUploadCompleted<TFileOrigin extends string = string> = InFlightUploadBase<TFileOrigin> & {
|
|
58
|
-
status:
|
|
56
|
+
status: typeof PendingMediaStatusSchema.enum.completed;
|
|
59
57
|
completedAt: number;
|
|
60
58
|
uploadTrayClearedAt?: number;
|
|
61
59
|
uploadTrayClearedBy?: string;
|
|
@@ -63,7 +61,7 @@ export type InFlightUploadCompleted<TFileOrigin extends string = string> = InFli
|
|
|
63
61
|
uploadTraySeenBy?: string;
|
|
64
62
|
};
|
|
65
63
|
export type InFlightUploadFailed<TFileOrigin extends string = string> = InFlightUploadBase<TFileOrigin> & {
|
|
66
|
-
status:
|
|
64
|
+
status: typeof PendingMediaStatusSchema.enum.failed;
|
|
67
65
|
failedAt: number;
|
|
68
66
|
errorCategory: string;
|
|
69
67
|
errorMessage: string;
|
|
@@ -73,7 +71,7 @@ export type InFlightUploadFailed<TFileOrigin extends string = string> = InFlight
|
|
|
73
71
|
uploadTraySeenBy?: string;
|
|
74
72
|
};
|
|
75
73
|
export type InFlightUploadRejected<TFileOrigin extends string = string> = InFlightUploadBase<TFileOrigin> & {
|
|
76
|
-
status:
|
|
74
|
+
status: typeof PendingMediaStatusSchema.enum.rejected;
|
|
77
75
|
rejectedAt: number;
|
|
78
76
|
rejectionType: 'text' | 'media';
|
|
79
77
|
errorMessage: string;
|
|
@@ -238,7 +236,7 @@ export declare function useUploadsSourceState(): UploadsSourceState;
|
|
|
238
236
|
* whether a Clear action is available for an item.
|
|
239
237
|
*/
|
|
240
238
|
export declare function isTerminalUpload<TFileOrigin extends string = string>(item: InFlightUpload<TFileOrigin>): item is Exclude<InFlightUpload<TFileOrigin>, {
|
|
241
|
-
status:
|
|
239
|
+
status: PendingMediaNonTerminalStatus;
|
|
242
240
|
}>;
|
|
243
241
|
/**
|
|
244
242
|
* Tray-visible items. Includes every pending/processing upload, plus terminal
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"in-flight-uploads-provider.d.ts","sourceRoot":"","sources":["../../src/react/in-flight-uploads-provider.tsx"],"names":[],"mappings":"AAuBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAOL,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"in-flight-uploads-provider.d.ts","sourceRoot":"","sources":["../../src/react/in-flight-uploads-provider.tsx"],"names":[],"mappings":"AAuBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAOL,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AACf,OAA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ot, query, where } from 'firebase/firestore';
|
|
|
51
51
|
* what a file-origin is or what message text appears in toasts.
|
|
52
52
|
*/
|
|
53
53
|
import { createContext, useContext, useEffect, useMemo, useRef, useState, } from 'react';
|
|
54
|
+
import { isPendingMediaNonTerminalStatus, isPendingMediaTerminalStatus, PendingMediaStatusSchema, } from '@ttt-productions/media-schemas';
|
|
55
|
+
// Status values derive from media-schemas' one declaration.
|
|
56
|
+
const STATUS = PendingMediaStatusSchema.enum;
|
|
54
57
|
const InFlightUploadsContext = createContext(undefined);
|
|
55
58
|
function fromParsed(parsed) {
|
|
56
59
|
const base = {
|
|
@@ -62,13 +65,13 @@ function fromParsed(parsed) {
|
|
|
62
65
|
originalContentType: parsed.originalContentType,
|
|
63
66
|
originalSize: parsed.originalSize,
|
|
64
67
|
};
|
|
65
|
-
if (parsed.status
|
|
68
|
+
if (isPendingMediaNonTerminalStatus(parsed.status)) {
|
|
66
69
|
return { ...base, status: parsed.status };
|
|
67
70
|
}
|
|
68
|
-
if (parsed.status ===
|
|
71
|
+
if (parsed.status === STATUS.completed) {
|
|
69
72
|
return {
|
|
70
73
|
...base,
|
|
71
|
-
status:
|
|
74
|
+
status: STATUS.completed,
|
|
72
75
|
completedAt: parsed.completedAt ?? parsed.createdAt,
|
|
73
76
|
uploadTrayClearedAt: parsed.uploadTrayClearedAt,
|
|
74
77
|
uploadTrayClearedBy: parsed.uploadTrayClearedBy,
|
|
@@ -76,10 +79,10 @@ function fromParsed(parsed) {
|
|
|
76
79
|
uploadTraySeenBy: parsed.uploadTraySeenBy,
|
|
77
80
|
};
|
|
78
81
|
}
|
|
79
|
-
if (parsed.status ===
|
|
82
|
+
if (parsed.status === STATUS.failed) {
|
|
80
83
|
return {
|
|
81
84
|
...base,
|
|
82
|
-
status:
|
|
85
|
+
status: STATUS.failed,
|
|
83
86
|
failedAt: parsed.failedAt ?? parsed.createdAt,
|
|
84
87
|
errorCategory: parsed.errorCategory ?? 'system',
|
|
85
88
|
errorMessage: parsed.errorMessage ?? '',
|
|
@@ -92,7 +95,7 @@ function fromParsed(parsed) {
|
|
|
92
95
|
// rejected
|
|
93
96
|
return {
|
|
94
97
|
...base,
|
|
95
|
-
status:
|
|
98
|
+
status: STATUS.rejected,
|
|
96
99
|
rejectedAt: parsed.rejectedAt ?? parsed.createdAt,
|
|
97
100
|
rejectionType: parsed.rejectionType ?? 'media',
|
|
98
101
|
errorMessage: parsed.errorMessage ?? '',
|
|
@@ -176,10 +179,8 @@ export function InFlightUploadsProvider(props) {
|
|
|
176
179
|
updates.push({ id: parsed.id, upload });
|
|
177
180
|
const previousStatus = statusByIdRef.current.get(parsed.id);
|
|
178
181
|
const currentStatus = parsed.status;
|
|
179
|
-
const currentIsTerminal = currentStatus
|
|
180
|
-
|
|
181
|
-
currentStatus === 'rejected';
|
|
182
|
-
const previousWasNonTerminal = previousStatus === 'pending' || previousStatus === 'processing';
|
|
182
|
+
const currentIsTerminal = isPendingMediaTerminalStatus(currentStatus);
|
|
183
|
+
const previousWasNonTerminal = isPendingMediaNonTerminalStatus(previousStatus);
|
|
183
184
|
if (isInitialSnapshot) {
|
|
184
185
|
// A subscription's first snapshot is a (re-)listing of current state,
|
|
185
186
|
// not a live event: already-terminal docs stay suppressed so a page
|
|
@@ -239,13 +240,13 @@ export function InFlightUploadsProvider(props) {
|
|
|
239
240
|
surface: parsed.surface,
|
|
240
241
|
},
|
|
241
242
|
});
|
|
242
|
-
if (parsed.status ===
|
|
243
|
+
if (parsed.status === STATUS.completed) {
|
|
243
244
|
adapterRef.current.onUploadCompleted(parsed);
|
|
244
245
|
}
|
|
245
|
-
else if (parsed.status ===
|
|
246
|
+
else if (parsed.status === STATUS.failed) {
|
|
246
247
|
adapterRef.current.onUploadFailed(parsed);
|
|
247
248
|
}
|
|
248
|
-
else if (parsed.status ===
|
|
249
|
+
else if (parsed.status === STATUS.rejected) {
|
|
249
250
|
adapterRef.current.onUploadRejected(parsed);
|
|
250
251
|
}
|
|
251
252
|
}
|
|
@@ -342,9 +343,7 @@ export function useUploadsSourceState() {
|
|
|
342
343
|
* whether a Clear action is available for an item.
|
|
343
344
|
*/
|
|
344
345
|
export function isTerminalUpload(item) {
|
|
345
|
-
return (item.status
|
|
346
|
-
item.status === 'failed' ||
|
|
347
|
-
item.status === 'rejected');
|
|
346
|
+
return isPendingMediaTerminalStatus(item.status);
|
|
348
347
|
}
|
|
349
348
|
/**
|
|
350
349
|
* Tray-visible items. Includes every pending/processing upload, plus terminal
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"in-flight-uploads-provider.js","sourceRoot":"","sources":["../../src/react/in-flight-uploads-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,gFAAgF;AAChF,0EAA0E;AAC1E,iFAAiF;AACjF,+CAA+C;AAC/C,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,6EAA6E;AAC7E,kFAAkF;AAClF,mEAAmE;AACnE,+EAA+E;AAC/E,yEAAyE;AACzE,gEAAgE;AAChE,gFAAgF;AAChF,4EAA4E;AAC5E,EAAE;AACF,mFAAmF;AACnF,gFAAgF;AAChF,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAE1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EACL,aAAa,EACb,UAAU,EACV,SAAS,EACT,OAAO,EACP,MAAM,EACN,QAAQ,GAET,MAAM,OAAO,CAAC;AAwPf,MAAM,sBAAsB,GAAG,aAAa,CAA0C,SAAS,CAAC,CAAC;AASjG,SAAS,UAAU,CACjB,MAAuC;IAEvC,MAAM,IAAI,GAAoC;QAC5C,EAAE,EAAE,MAAM,CAAC,EAAE;QACb,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,SAAS,EAAE,MAAM,CAAC,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,OAAO,UAAU,CAAC,CAAC,EAAE,EAAE,sBAAsB,EAAE,IAAI,EAAE,EAAE,IAAI,CAAC,UAAmB,EAAE,IAAI,CAAC,OAAgB,CAAC,CAAC;AAC1G,CAAC,CAAC","sourcesContent":["'use client';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// SANCTIONED EXCEPTION to the \"packages read/write Firestore only through\n// @ttt-productions/query-core\" rule (see docs/packages/package-architecture.md →\n// \"Firestore access goes through 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 useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\n\n// =============================================================================\n// Generic shape of the data the provider tracks\n// =============================================================================\n\n/**\n * Generic pending-media status. Defined here so upload-ui has no dependency\n * on any app-specific package.\n */\nexport type InFlightUploadStatus =\n | 'pending'\n | 'processing'\n | 'completed'\n | 'failed'\n | 'rejected';\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: 'pending' | 'processing';\n };\n\nexport type InFlightUploadCompleted<TFileOrigin extends string = string> =\n InFlightUploadBase<TFileOrigin> & {\n status: '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: '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: '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}\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 (parsed.status === 'pending' || parsed.status === 'processing') {\n return { ...base, status: parsed.status };\n }\n if (parsed.status === 'completed') {\n return {\n ...base,\n 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 === 'failed') {\n return {\n ...base,\n 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: '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 (round-9 finding 9): dropping them on the\n // `rejected` branch — while `completed`/`failed` keep them — made a seen\n // rejected upload relight the Files dot forever, because the tray's\n // unseen-terminal check never saw `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 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 setUploads(new Map());\n setSourceState('connecting');\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 =\n currentStatus === 'completed' ||\n currentStatus === 'failed' ||\n currentStatus === 'rejected';\n const previousWasNonTerminal =\n previousStatus === 'pending' || previousStatus === 'processing';\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 setSourceState((prev) => (fromCache ? (prev === 'connecting' ? 'connecting' : 'offline') : 'live'));\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 === 'completed') {\n adapterRef.current.onUploadCompleted(parsed);\n } else if (parsed.status === 'failed') {\n adapterRef.current.onUploadFailed(parsed);\n } else if (parsed.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 return;\n }\n 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\n }, [userId, subscribe]);\n\n const value = useMemo<InFlightUploadsContextValue<TFileOrigin>>(\n () => ({ uploads, sourceState }),\n [uploads, sourceState],\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// 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: 'pending' | 'processing' }> {\n return (\n item.status === 'completed' ||\n item.status === 'failed' ||\n item.status === 'rejected'\n );\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<TFileOrigin extends string = string>(): 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\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(q, { includeMetadataChanges: true }, args.onSnapshot as never, args.onError as never);\n};\n"]}
|
|
1
|
+
{"version":3,"file":"in-flight-uploads-provider.js","sourceRoot":"","sources":["../../src/react/in-flight-uploads-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,gFAAgF;AAChF,0EAA0E;AAC1E,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O,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,CAEb,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,CAAC,CAAC,EAAE,EAAE,sBAAsB,EAAE,IAAI,EAAE,EAAE,IAAI,CAAC,UAAmB,EAAE,IAAI,CAAC,OAAgB,CAAC,CAAC;AAC1G,CAAC,CAAC","sourcesContent":["'use client';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// SANCTIONED EXCEPTION to the \"packages read/write Firestore only through\n// @ttt-productions/query-core\" rule (see docs/packages/package-architecture.md →\n// \"Firestore access goes through 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 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}\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 (round-9 finding 9): dropping them on the\n // `rejected` branch — while `completed`/`failed` keep them — made a seen\n // rejected upload relight the Files dot forever, because the tray's\n // unseen-terminal check never saw `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 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 setUploads(new Map());\n setSourceState('connecting');\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 setSourceState((prev) => (fromCache ? (prev === 'connecting' ? 'connecting' : 'offline') : 'live'));\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 return;\n }\n 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\n }, [userId, subscribe]);\n\n const value = useMemo<InFlightUploadsContextValue<TFileOrigin>>(\n () => ({ uploads, sourceState }),\n [uploads, sourceState],\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// 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<TFileOrigin extends string = string>(): 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\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(q, { includeMetadataChanges: true }, args.onSnapshot as never, args.onError as never);\n};\n"]}
|
|
@@ -22,6 +22,16 @@
|
|
|
22
22
|
* used outside a `LocalUploadGuardProvider`.
|
|
23
23
|
*/
|
|
24
24
|
import { type ReactNode } from 'react';
|
|
25
|
+
export interface ConfirmNavigationOptions {
|
|
26
|
+
/**
|
|
27
|
+
* The caller leaves through a FULL-PAGE navigation (`location.assign` /
|
|
28
|
+
* `location.replace`) once this returns true. The provider then lets that
|
|
29
|
+
* navigation's next `beforeunload` pass without the browser's own
|
|
30
|
+
* "Leave site?" prompt, because the user has just answered this one. Soft
|
|
31
|
+
* (in-app router) navigations never pass it: they fire no `beforeunload`.
|
|
32
|
+
*/
|
|
33
|
+
fullPageNavigation?: boolean;
|
|
34
|
+
}
|
|
25
35
|
interface LocalUploadGuardContextValue {
|
|
26
36
|
activeUploadCount: number;
|
|
27
37
|
registerUpload: (id: string) => void;
|
|
@@ -31,8 +41,14 @@ interface LocalUploadGuardContextValue {
|
|
|
31
41
|
/**
|
|
32
42
|
* Shows a confirm() dialog with the configured message and returns the user's
|
|
33
43
|
* choice. Safe to call when no upload is active — returns true without prompting.
|
|
44
|
+
*
|
|
45
|
+
* With `{ fullPageNavigation: true }` and a result of true (confirmed, or no
|
|
46
|
+
* upload active), arms a ONE-SHOT bypass: the next `beforeunload` is not
|
|
47
|
+
* prevented, so a confirmed full-page navigation does not prompt twice. A
|
|
48
|
+
* declined confirm never arms it; the bypass is cleared when it is consumed, when
|
|
49
|
+
* a new upload registers, and on `pageshow` (a back/forward-cache return).
|
|
34
50
|
*/
|
|
35
|
-
confirmNavigation: () => boolean;
|
|
51
|
+
confirmNavigation: (options?: ConfirmNavigationOptions) => boolean;
|
|
36
52
|
}
|
|
37
53
|
export interface LocalUploadGuardProviderProps {
|
|
38
54
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-upload-guard-provider.d.ts","sourceRoot":"","sources":["../../src/react/local-upload-guard-provider.tsx"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAQL,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAEf,UAAU,4BAA4B;IACpC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,cAAc,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;IACrC,gBAAgB,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,+EAA+E;IAC/E,uBAAuB,EAAE,MAAM,OAAO,CAAC;IACvC
|
|
1
|
+
{"version":3,"file":"local-upload-guard-provider.d.ts","sourceRoot":"","sources":["../../src/react/local-upload-guard-provider.tsx"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAQL,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAEf,MAAM,WAAW,wBAAwB;IACvC;;;;;;OAMG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,UAAU,4BAA4B;IACpC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,cAAc,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;IACrC,gBAAgB,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,+EAA+E;IAC/E,uBAAuB,EAAE,MAAM,OAAO,CAAC;IACvC;;;;;;;;;OASG;IACH,iBAAiB,EAAE,CAAC,OAAO,CAAC,EAAE,wBAAwB,KAAK,OAAO,CAAC;CACpE;AAID,MAAM,WAAW,6BAA6B;IAC5C;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;OAIG;IACH,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,QAAQ,EAAE,SAAS,CAAC;CACrB;AAOD,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,6BAA6B,+BA4F5E;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,IAAI,4BAA4B,CAQzE;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,IAAI,4BAA4B,GAAG,IAAI,CAEjF;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,mBAAmB,IAAI,4BAA4B,CAElE"}
|
|
@@ -31,9 +31,13 @@ export function LocalUploadGuardProvider(props) {
|
|
|
31
31
|
const { children, beforeUnloadMessage = DEFAULT_BEFORE_UNLOAD_MESSAGE, navigationConfirmMessage = DEFAULT_NAVIGATION_CONFIRM_MESSAGE, } = props;
|
|
32
32
|
const activeIdsRef = useRef(new Set());
|
|
33
33
|
const [activeUploadCount, setActiveUploadCount] = useState(0);
|
|
34
|
+
// One-shot: the user already confirmed the full-page navigation now unloading.
|
|
35
|
+
const bypassNextUnloadRef = useRef(false);
|
|
34
36
|
const registerUpload = useCallback((id) => {
|
|
35
37
|
if (activeIdsRef.current.has(id))
|
|
36
38
|
return;
|
|
39
|
+
// Work that starts after a confirmation was not covered by it.
|
|
40
|
+
bypassNextUnloadRef.current = false;
|
|
37
41
|
activeIdsRef.current.add(id);
|
|
38
42
|
setActiveUploadCount(activeIdsRef.current.size);
|
|
39
43
|
}, []);
|
|
@@ -47,6 +51,10 @@ export function LocalUploadGuardProvider(props) {
|
|
|
47
51
|
if (activeUploadCount <= 0)
|
|
48
52
|
return;
|
|
49
53
|
const handleBeforeUnload = (event) => {
|
|
54
|
+
if (bypassNextUnloadRef.current) {
|
|
55
|
+
bypassNextUnloadRef.current = false;
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
50
58
|
event.preventDefault();
|
|
51
59
|
// Modern browsers may ignore the custom string and show their own
|
|
52
60
|
// generic confirmation. The key behavior is that navigation is
|
|
@@ -59,14 +67,26 @@ export function LocalUploadGuardProvider(props) {
|
|
|
59
67
|
window.removeEventListener('beforeunload', handleBeforeUnload);
|
|
60
68
|
};
|
|
61
69
|
}, [activeUploadCount, beforeUnloadMessage]);
|
|
70
|
+
// A back/forward-cache return re-shows this page without reloading it: an
|
|
71
|
+
// armed bypass from the navigation that left must never outlive that navigation.
|
|
72
|
+
useEffect(() => {
|
|
73
|
+
const clearBypass = () => {
|
|
74
|
+
bypassNextUnloadRef.current = false;
|
|
75
|
+
};
|
|
76
|
+
window.addEventListener('pageshow', clearBypass);
|
|
77
|
+
return () => {
|
|
78
|
+
window.removeEventListener('pageshow', clearBypass);
|
|
79
|
+
};
|
|
80
|
+
}, []);
|
|
62
81
|
const shouldConfirmNavigation = useCallback(() => activeIdsRef.current.size > 0, []);
|
|
63
|
-
const confirmNavigation = useCallback(() => {
|
|
64
|
-
if (activeIdsRef.current.size === 0)
|
|
65
|
-
return true;
|
|
82
|
+
const confirmNavigation = useCallback((options) => {
|
|
66
83
|
// SSR / non-browser safety: if `window` isn't available, default to allow.
|
|
67
84
|
if (typeof window === 'undefined')
|
|
68
85
|
return true;
|
|
69
|
-
|
|
86
|
+
const proceed = activeIdsRef.current.size === 0 || window.confirm(navigationConfirmMessage);
|
|
87
|
+
if (proceed && options?.fullPageNavigation)
|
|
88
|
+
bypassNextUnloadRef.current = true;
|
|
89
|
+
return proceed;
|
|
70
90
|
}, [navigationConfirmMessage]);
|
|
71
91
|
const value = useMemo(() => ({
|
|
72
92
|
activeUploadCount,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-upload-guard-provider.js","sourceRoot":"","sources":["../../src/react/local-upload-guard-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EACL,aAAa,EACb,WAAW,EACX,UAAU,EACV,SAAS,EACT,OAAO,EACP,MAAM,EACN,QAAQ,GAET,MAAM,OAAO,CAAC;AAef,MAAM,uBAAuB,GAAG,aAAa,CAA2C,SAAS,CAAC,CAAC;AAkBnG,MAAM,6BAA6B,GACjC,kFAAkF,CAAC;AACrF,MAAM,kCAAkC,GACtC,oGAAoG,CAAC;AAEvG,MAAM,UAAU,wBAAwB,CAAC,KAAoC;IAC3E,MAAM,EACJ,QAAQ,EACR,mBAAmB,GAAG,6BAA6B,EACnD,wBAAwB,GAAG,kCAAkC,GAC9D,GAAG,KAAK,CAAC;IACV,MAAM,YAAY,GAAG,MAAM,CAAc,IAAI,GAAG,EAAE,CAAC,CAAC;IACpD,MAAM,CAAC,iBAAiB,EAAE,oBAAoB,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;IAE9D,MAAM,cAAc,GAAG,WAAW,CAAC,CAAC,EAAU,EAAE,EAAE;QAChD,IAAI,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YAAE,OAAO;QACzC,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,EAA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IAAI,OAAO,MAAM,KAAK,WAAW;YAAE,OAAO,IAAI,CAAC;QAC/C,OAAO,MAAM,CAAC,OAAO,CAAC,wBAAwB,CAAC,CAAC;IAClD,CAAC,EAAE,CAAC,wBAAwB,CAAC,CAAC,CAAC;IAE/B,MAAM,KAAK,GAAG,OAAO,CACnB,GAAG,EAAE,CAAC,CAAC;QACL,iBAAiB;QACjB,cAAc;QACd,gBAAgB;QAChB,uBAAuB;QACvB,iBAAiB;KAClB,CAAC,EACF,CAAC,iBAAiB,EAAE,cAAc,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,iBAAiB,CAAC,CAClG,CAAC;IAEF,OAAO,CACL,KAAC,uBAAuB,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAC3C,QAAQ,GACwB,CACpC,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,0BAA0B;IACxC,MAAM,GAAG,GAAG,UAAU,CAAC,uBAAuB,CAAC,CAAC;IAChD,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CACb,kEAAkE,CACnE,CAAC;IACJ,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","sourcesContent":["'use client';\n\n/**\n * Local upload navigation guard provider.\n *\n * Tracks the count of in-progress LOCAL byte uploads (file → Firebase\n * Storage). While the count is > 0, installs a `beforeunload` listener\n * to warn the user before they close the tab or reload mid-upload.\n *\n * Scope:\n * - Covers phases `preparing` and `uploading` only.\n * - Does NOT cover `finalizing` — at that point bytes are already in\n * Storage and the only remaining work is the `startUpload` callable.\n * - Does NOT cover backend `pendingMedia` status (`pending` /\n * `processing`). Those run server-side and are safe to leave.\n *\n * Consumers register with a stable id (typically the local upload\n * session id or `pendingMedia` doc id once known) on entering\n * `preparing`/`uploading`, and unregister on transition to\n * `finalizing`/success/error/cancel/unmount.\n *\n * Public hook: `useLocalUploadGuard()` returns\n * `{ activeUploadCount, registerUpload, unregisterUpload }`. Throws if\n * used outside a `LocalUploadGuardProvider`.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\n\ninterface LocalUploadGuardContextValue {\n activeUploadCount: number;\n registerUpload: (id: string) => void;\n unregisterUpload: (id: string) => void;\n /** Returns true iff at least one upload is currently registered. Pure read. */\n shouldConfirmNavigation: () => boolean;\n /**\n * Shows a confirm() dialog with the configured message and returns the user's\n * choice. Safe to call when no upload is active — returns true without prompting.\n */\n confirmNavigation: () => boolean;\n}\n\nconst LocalUploadGuardContext = createContext<LocalUploadGuardContextValue | undefined>(undefined);\n\nexport interface LocalUploadGuardProviderProps {\n /**\n * Message shown by the browser when the user attempts to close the tab or\n * reload during an active upload. Modern browsers may ignore the custom\n * string and show a generic dialog.\n */\n beforeUnloadMessage?: string;\n /**\n * Message shown by `confirmNavigation()` when an upload is in progress and\n * the user attempts to navigate away within the app. Defaults to a\n * reasonable English string.\n */\n navigationConfirmMessage?: string;\n children: ReactNode;\n}\n\nconst DEFAULT_BEFORE_UNLOAD_MESSAGE =\n 'File upload in progress. Are you sure you want to leave and end the file upload?';\nconst DEFAULT_NAVIGATION_CONFIRM_MESSAGE =\n 'An upload is currently in progress. If you leave this page, the upload will be canceled. Continue?';\n\nexport function LocalUploadGuardProvider(props: LocalUploadGuardProviderProps) {\n const {\n children,\n beforeUnloadMessage = DEFAULT_BEFORE_UNLOAD_MESSAGE,\n navigationConfirmMessage = DEFAULT_NAVIGATION_CONFIRM_MESSAGE,\n } = props;\n const activeIdsRef = useRef<Set<string>>(new Set());\n const [activeUploadCount, setActiveUploadCount] = useState(0);\n\n const registerUpload = useCallback((id: string) => {\n if (activeIdsRef.current.has(id)) return;\n activeIdsRef.current.add(id);\n setActiveUploadCount(activeIdsRef.current.size);\n }, []);\n\n const unregisterUpload = useCallback((id: string) => {\n if (!activeIdsRef.current.has(id)) return;\n activeIdsRef.current.delete(id);\n setActiveUploadCount(activeIdsRef.current.size);\n }, []);\n\n useEffect(() => {\n if (activeUploadCount <= 0) return;\n\n const handleBeforeUnload = (event: BeforeUnloadEvent) => {\n event.preventDefault();\n // Modern browsers may ignore the custom string and show their own\n // generic confirmation. The key behavior is that navigation is\n // blocked/warned, not the exact text.\n event.returnValue = beforeUnloadMessage;\n return event.returnValue;\n };\n\n window.addEventListener('beforeunload', handleBeforeUnload);\n return () => {\n window.removeEventListener('beforeunload', handleBeforeUnload);\n };\n }, [activeUploadCount, beforeUnloadMessage]);\n\n const shouldConfirmNavigation = useCallback(\n () => activeIdsRef.current.size > 0,\n [],\n );\n\n const confirmNavigation = useCallback((): boolean => {\n if (activeIdsRef.current.size === 0) return true;\n // SSR / non-browser safety: if `window` isn't available, default to allow.\n if (typeof window === 'undefined') return true;\n return window.confirm(navigationConfirmMessage);\n }, [navigationConfirmMessage]);\n\n const value = useMemo<LocalUploadGuardContextValue>(\n () => ({\n activeUploadCount,\n registerUpload,\n unregisterUpload,\n shouldConfirmNavigation,\n confirmNavigation,\n }),\n [activeUploadCount, registerUpload, unregisterUpload, shouldConfirmNavigation, confirmNavigation],\n );\n\n return (\n <LocalUploadGuardContext.Provider value={value}>\n {children}\n </LocalUploadGuardContext.Provider>\n );\n}\n\n/**\n * Low-level accessor for the local-upload guard context. Throws if used\n * outside a `LocalUploadGuardProvider`. Most consumers should use\n * `useLocalUploadGuard` (the public re-export below) instead.\n */\nexport function useLocalUploadGuardContext(): LocalUploadGuardContextValue {\n const ctx = useContext(LocalUploadGuardContext);\n if (ctx === undefined) {\n throw new Error(\n 'useLocalUploadGuard must be used within LocalUploadGuardProvider',\n );\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 local upload navigation guard.\n *\n * Returns `{ activeUploadCount, registerUpload, unregisterUpload }`.\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 */\nexport function useLocalUploadGuard(): LocalUploadGuardContextValue {\n return useLocalUploadGuardContext();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"local-upload-guard-provider.js","sourceRoot":"","sources":["../../src/react/local-upload-guard-provider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EACL,aAAa,EACb,WAAW,EACX,UAAU,EACV,SAAS,EACT,OAAO,EACP,MAAM,EACN,QAAQ,GAET,MAAM,OAAO,CAAC;AAgCf,MAAM,uBAAuB,GAAG,aAAa,CAA2C,SAAS,CAAC,CAAC;AAkBnG,MAAM,6BAA6B,GACjC,kFAAkF,CAAC;AACrF,MAAM,kCAAkC,GACtC,oGAAoG,CAAC;AAEvG,MAAM,UAAU,wBAAwB,CAAC,KAAoC;IAC3E,MAAM,EACJ,QAAQ,EACR,mBAAmB,GAAG,6BAA6B,EACnD,wBAAwB,GAAG,kCAAkC,GAC9D,GAAG,KAAK,CAAC;IACV,MAAM,YAAY,GAAG,MAAM,CAAc,IAAI,GAAG,EAAE,CAAC,CAAC;IACpD,MAAM,CAAC,iBAAiB,EAAE,oBAAoB,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;IAC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BAAgB,EAAE,uBAAuB,EAAE,iBAAiB,CAAC,CAClG,CAAC;IAEF,OAAO,CACL,KAAC,uBAAuB,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAC3C,QAAQ,GACwB,CACpC,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,0BAA0B;IACxC,MAAM,GAAG,GAAG,UAAU,CAAC,uBAAuB,CAAC,CAAC;IAChD,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CACb,kEAAkE,CACnE,CAAC;IACJ,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","sourcesContent":["'use client';\n\n/**\n * Local upload navigation guard provider.\n *\n * Tracks the count of in-progress LOCAL byte uploads (file → Firebase\n * Storage). While the count is > 0, installs a `beforeunload` listener\n * to warn the user before they close the tab or reload mid-upload.\n *\n * Scope:\n * - Covers phases `preparing` and `uploading` only.\n * - Does NOT cover `finalizing` — at that point bytes are already in\n * Storage and the only remaining work is the `startUpload` callable.\n * - Does NOT cover backend `pendingMedia` status (`pending` /\n * `processing`). Those run server-side and are safe to leave.\n *\n * Consumers register with a stable id (typically the local upload\n * session id or `pendingMedia` doc id once known) on entering\n * `preparing`/`uploading`, and unregister on transition to\n * `finalizing`/success/error/cancel/unmount.\n *\n * Public hook: `useLocalUploadGuard()` returns\n * `{ activeUploadCount, registerUpload, unregisterUpload }`. Throws if\n * used outside a `LocalUploadGuardProvider`.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\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 activeUploadCount: number;\n registerUpload: (id: string) => void;\n unregisterUpload: (id: string) => void;\n /** Returns true iff at least one upload is currently registered. Pure read. */\n shouldConfirmNavigation: () => boolean;\n /**\n * Shows a confirm() dialog with the configured message and returns the user's\n * choice. Safe to call when no upload is active — returns true without prompting.\n *\n * With `{ fullPageNavigation: true }` and a result of true (confirmed, or no\n * upload active), arms a ONE-SHOT bypass: the next `beforeunload` is not\n * prevented, so a confirmed full-page navigation does not prompt twice. A\n * declined confirm never arms it; the bypass is cleared when it is consumed, when\n * a new upload registers, and on `pageshow` (a 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 shown by the browser when the user attempts to close the tab or\n * reload during an active upload. Modern browsers may ignore the custom\n * string and show a generic dialog.\n */\n beforeUnloadMessage?: string;\n /**\n * Message shown by `confirmNavigation()` when an upload is in progress and\n * the user attempts to navigate away within the app. Defaults to a\n * reasonable English string.\n */\n navigationConfirmMessage?: string;\n children: ReactNode;\n}\n\nconst DEFAULT_BEFORE_UNLOAD_MESSAGE =\n 'File upload in progress. Are you sure you want to leave and end the file upload?';\nconst DEFAULT_NAVIGATION_CONFIRM_MESSAGE =\n 'An upload is currently in progress. If you leave this page, the upload will be canceled. Continue?';\n\nexport function LocalUploadGuardProvider(props: LocalUploadGuardProviderProps) {\n const {\n children,\n beforeUnloadMessage = DEFAULT_BEFORE_UNLOAD_MESSAGE,\n navigationConfirmMessage = DEFAULT_NAVIGATION_CONFIRM_MESSAGE,\n } = props;\n const activeIdsRef = useRef<Set<string>>(new Set());\n const [activeUploadCount, setActiveUploadCount] = useState(0);\n // One-shot: the user already confirmed the full-page navigation now unloading.\n const bypassNextUnloadRef = useRef(false);\n\n const registerUpload = useCallback((id: string) => {\n if (activeIdsRef.current.has(id)) return;\n // Work that starts after a confirmation was not covered by it.\n bypassNextUnloadRef.current = false;\n activeIdsRef.current.add(id);\n setActiveUploadCount(activeIdsRef.current.size);\n }, []);\n\n const unregisterUpload = useCallback((id: string) => {\n if (!activeIdsRef.current.has(id)) return;\n activeIdsRef.current.delete(id);\n setActiveUploadCount(activeIdsRef.current.size);\n }, []);\n\n useEffect(() => {\n if (activeUploadCount <= 0) 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\n // generic confirmation. The key behavior is that navigation is\n // blocked/warned, not the exact text.\n event.returnValue = beforeUnloadMessage;\n return event.returnValue;\n };\n\n window.addEventListener('beforeunload', handleBeforeUnload);\n return () => {\n window.removeEventListener('beforeunload', handleBeforeUnload);\n };\n }, [activeUploadCount, beforeUnloadMessage]);\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 const clearBypass = () => {\n bypassNextUnloadRef.current = false;\n };\n window.addEventListener('pageshow', clearBypass);\n return () => {\n window.removeEventListener('pageshow', clearBypass);\n };\n }, []);\n\n const shouldConfirmNavigation = useCallback(\n () => activeIdsRef.current.size > 0,\n [],\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 =\n activeIdsRef.current.size === 0 || window.confirm(navigationConfirmMessage);\n if (proceed && options?.fullPageNavigation) bypassNextUnloadRef.current = true;\n return proceed;\n },\n [navigationConfirmMessage],\n );\n\n const value = useMemo<LocalUploadGuardContextValue>(\n () => ({\n activeUploadCount,\n registerUpload,\n unregisterUpload,\n shouldConfirmNavigation,\n confirmNavigation,\n }),\n [activeUploadCount, registerUpload, unregisterUpload, shouldConfirmNavigation, confirmNavigation],\n );\n\n return (\n <LocalUploadGuardContext.Provider value={value}>\n {children}\n </LocalUploadGuardContext.Provider>\n );\n}\n\n/**\n * Low-level accessor for the local-upload guard context. Throws if used\n * outside a `LocalUploadGuardProvider`. Most consumers should use\n * `useLocalUploadGuard` (the public re-export below) instead.\n */\nexport function useLocalUploadGuardContext(): LocalUploadGuardContextValue {\n const ctx = useContext(LocalUploadGuardContext);\n if (ctx === undefined) {\n throw new Error(\n 'useLocalUploadGuard must be used within LocalUploadGuardProvider',\n );\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 local upload navigation guard.\n *\n * Returns `{ activeUploadCount, registerUpload, unregisterUpload }`.\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 */\nexport function useLocalUploadGuard(): LocalUploadGuardContextValue {\n return useLocalUploadGuardContext();\n}\n"]}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { type ConfirmNavigationOptions } from './local-upload-guard-provider.js';
|
|
1
2
|
/**
|
|
2
3
|
* Returns a callable that wraps a navigation action. Calling the returned
|
|
3
4
|
* function with `performNavigation` either invokes it immediately (when no
|
|
4
5
|
* active uploads) or shows a confirmation prompt; if the user confirms,
|
|
5
|
-
* `performNavigation` is invoked.
|
|
6
|
+
* `performNavigation` is invoked. `options` passes through to
|
|
7
|
+
* `confirmNavigation()`.
|
|
6
8
|
*/
|
|
7
|
-
export declare function useGuardedNavigation(): (performNavigation: () => void) => void;
|
|
9
|
+
export declare function useGuardedNavigation(): (performNavigation: () => void, options?: ConfirmNavigationOptions) => void;
|
|
8
10
|
//# sourceMappingURL=use-guarded-navigation.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-guarded-navigation.d.ts","sourceRoot":"","sources":["../../src/react/use-guarded-navigation.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"use-guarded-navigation.d.ts","sourceRoot":"","sources":["../../src/react/use-guarded-navigation.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAuB,KAAK,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAEtG;;;;;;GAMG;AACH,wBAAgB,oBAAoB,IAAI,CACtC,iBAAiB,EAAE,MAAM,IAAI,EAC7B,OAAO,CAAC,EAAE,wBAAwB,KAC/B,IAAI,CAUR"}
|
|
@@ -7,11 +7,16 @@
|
|
|
7
7
|
*
|
|
8
8
|
* Designed to be framework-agnostic — the consumer supplies the navigator
|
|
9
9
|
* (Next.js router.push, React Router navigate, plain location.assign, etc.).
|
|
10
|
+
* A FULL-PAGE navigator (`location.assign` / `location.replace`) passes
|
|
11
|
+
* `{ fullPageNavigation: true }`, so the unload that follows a confirmed
|
|
12
|
+
* navigation does not raise the browser's own "Leave site?" as a second prompt
|
|
13
|
+
* (see `ConfirmNavigationOptions`). Router navigations pass nothing.
|
|
10
14
|
*
|
|
11
15
|
* Typical use inside a button:
|
|
12
16
|
*
|
|
13
17
|
* const guardedNav = useGuardedNavigation();
|
|
14
18
|
* <Button onClick={() => guardedNav(() => router.push('/somewhere'))}>Go</Button>
|
|
19
|
+
* <Button onClick={() => guardedNav(() => location.assign(url), { fullPageNavigation: true })}>Leave</Button>
|
|
15
20
|
*
|
|
16
21
|
* For links, use the `<GuardedLink>` render-prop wrapper.
|
|
17
22
|
*/
|
|
@@ -21,12 +26,13 @@ import { useLocalUploadGuard } from './local-upload-guard-provider.js';
|
|
|
21
26
|
* Returns a callable that wraps a navigation action. Calling the returned
|
|
22
27
|
* function with `performNavigation` either invokes it immediately (when no
|
|
23
28
|
* active uploads) or shows a confirmation prompt; if the user confirms,
|
|
24
|
-
* `performNavigation` is invoked.
|
|
29
|
+
* `performNavigation` is invoked. `options` passes through to
|
|
30
|
+
* `confirmNavigation()`.
|
|
25
31
|
*/
|
|
26
32
|
export function useGuardedNavigation() {
|
|
27
33
|
const { confirmNavigation } = useLocalUploadGuard();
|
|
28
|
-
return useCallback((performNavigation) => {
|
|
29
|
-
if (confirmNavigation()) {
|
|
34
|
+
return useCallback((performNavigation, options) => {
|
|
35
|
+
if (confirmNavigation(options)) {
|
|
30
36
|
performNavigation();
|
|
31
37
|
}
|
|
32
38
|
}, [confirmNavigation]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-guarded-navigation.js","sourceRoot":"","sources":["../../src/react/use-guarded-navigation.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb
|
|
1
|
+
{"version":3,"file":"use-guarded-navigation.js","sourceRoot":"","sources":["../../src/react/use-guarded-navigation.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAiC,MAAM,kCAAkC,CAAC;AAEtG;;;;;;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 when an upload is in\n * progress. Returns a function that takes the consumer's actual navigation\n * call and either runs it immediately (no active uploads) 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 { useLocalUploadGuard, type ConfirmNavigationOptions } 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 no\n * active uploads) 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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-upload-processing.d.ts","sourceRoot":"","sources":["../../src/react/use-upload-processing.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"use-upload-processing.d.ts","sourceRoot":"","sources":["../../src/react/use-upload-processing.ts"],"names":[],"mappings":"AAqBA,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,YAAY,GAAG,SAAS,GAAG,QAAQ,GAAG,eAAe,GAAG,gBAAgB,CAAC;IACtG,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,CAqBvB"}
|
|
@@ -11,7 +11,10 @@
|
|
|
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
15
|
import { useInFlightUpload } from './in-flight-uploads-provider.js';
|
|
16
|
+
// Pending-media status values derive from media-schemas' one declaration.
|
|
17
|
+
const STATUS = PendingMediaStatusSchema.enum;
|
|
15
18
|
const DEFAULT_PROCESSING_MESSAGE = 'Processing your content...';
|
|
16
19
|
const DEFAULT_SUCCESS_MESSAGE = 'Complete!';
|
|
17
20
|
const DEFAULT_FAILED_MESSAGE = 'Processing failed';
|
|
@@ -31,7 +34,7 @@ function buildState(upload, opts) {
|
|
|
31
34
|
isRejected: false,
|
|
32
35
|
};
|
|
33
36
|
}
|
|
34
|
-
if (upload.status
|
|
37
|
+
if (isPendingMediaNonTerminalStatus(upload.status)) {
|
|
35
38
|
return {
|
|
36
39
|
status: upload.status,
|
|
37
40
|
message: processingMessage,
|
|
@@ -41,7 +44,7 @@ function buildState(upload, opts) {
|
|
|
41
44
|
isRejected: false,
|
|
42
45
|
};
|
|
43
46
|
}
|
|
44
|
-
if (upload.status ===
|
|
47
|
+
if (upload.status === STATUS.completed) {
|
|
45
48
|
return {
|
|
46
49
|
status: 'success',
|
|
47
50
|
message: successMessage,
|
|
@@ -51,7 +54,7 @@ function buildState(upload, opts) {
|
|
|
51
54
|
isRejected: false,
|
|
52
55
|
};
|
|
53
56
|
}
|
|
54
|
-
if (upload.status ===
|
|
57
|
+
if (upload.status === STATUS.failed) {
|
|
55
58
|
return {
|
|
56
59
|
status: 'failed',
|
|
57
60
|
message: failedMessage,
|
|
@@ -62,7 +65,7 @@ function buildState(upload, opts) {
|
|
|
62
65
|
isRejected: false,
|
|
63
66
|
};
|
|
64
67
|
}
|
|
65
|
-
if (upload.status ===
|
|
68
|
+
if (upload.status === STATUS.rejected) {
|
|
66
69
|
return {
|
|
67
70
|
status: upload.rejectionType === 'text' ? 'rejected-text' : 'rejected-media',
|
|
68
71
|
message: rejectedMessage,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-upload-processing.js","sourceRoot":"","sources":["../../src/react/use-upload-processing.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAuB,MAAM,iCAAiC,CAAC;
|
|
1
|
+
{"version":3,"file":"use-upload-processing.js","sourceRoot":"","sources":["../../src/react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C;IAC9D,MAAM,KAAK,GAAG,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC1C,MAAM,YAAY,GAAG,MAAM,CAAgB,IAAI,CAAC,CAAC;IAEjD,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,CAAC,UAAU;YAAE,OAAO;QACxB,IAAI,CAAC,cAAc,EAAE,CAAC;YACpB,YAAY,CAAC,OAAO,GAAG,IAAI,CAAC;YAC5B,OAAO;QACT,CAAC;QACD,IAAI,KAAK,CAAC,UAAU,IAAI,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,UAAU,EAAE,CAAC;YAC3D,MAAM,GAAG,GAAG,GAAG,cAAc,IAAI,KAAK,CAAC,MAAM,EAAE,CAAC;YAChD,IAAI,YAAY,CAAC,OAAO,KAAK,GAAG,EAAE,CAAC;gBACjC,YAAY,CAAC,OAAO,GAAG,GAAG,CAAC;gBAC3B,UAAU,CAAC,KAAK,CAAC,CAAC;YACpB,CAAC;QACH,CAAC;IACH,CAAC,EAAE,CAAC,cAAc,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,UAAU,EAAE,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC;IAE1G,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["'use client';\n\n/**\n * Adapter that maps `useInFlightUpload` state to the legacy\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 { isPendingMediaNonTerminalStatus, PendingMediaStatusSchema } 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: '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 }, [pendingMediaId, state.status, state.isComplete, state.isFailed, state.isRejected, state, onTerminal]);\n\n return state;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ttt-productions/upload-ui",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.12",
|
|
4
4
|
"description": "Upload UI primitives: local upload guard provider, useGuardedUpload helper, DeferredUploadFormShell for forms that defer Firebase Storage upload until form submit.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -40,17 +40,16 @@
|
|
|
40
40
|
"prepublishOnly": "npm run clean && npm run build"
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@ttt-productions/file-input": "^0.11.
|
|
44
|
-
"@ttt-productions/media-schemas": "^0.14.
|
|
45
|
-
"@ttt-productions/ui-core": "^0.11.
|
|
46
|
-
"@ttt-productions/upload-core": "^0.7.
|
|
43
|
+
"@ttt-productions/file-input": "^0.11.12",
|
|
44
|
+
"@ttt-productions/media-schemas": "^0.14.7",
|
|
45
|
+
"@ttt-productions/ui-core": "^0.11.19",
|
|
46
|
+
"@ttt-productions/upload-core": "^0.7.4"
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
49
49
|
"@tanstack/react-query": ">=5.0.0",
|
|
50
|
-
"firebase": ">=
|
|
51
|
-
"
|
|
52
|
-
"react": ">=
|
|
53
|
-
"react-dom": ">=18.0.0"
|
|
50
|
+
"firebase": ">=12.0.0",
|
|
51
|
+
"react": ">=19.0.0",
|
|
52
|
+
"react-dom": ">=19.0.0"
|
|
54
53
|
},
|
|
55
54
|
"peerDependenciesMeta": {
|
|
56
55
|
"@tanstack/react-query": {
|
|
@@ -59,9 +58,6 @@
|
|
|
59
58
|
"firebase": {
|
|
60
59
|
"optional": true
|
|
61
60
|
},
|
|
62
|
-
"lucide-react": {
|
|
63
|
-
"optional": true
|
|
64
|
-
},
|
|
65
61
|
"react": {
|
|
66
62
|
"optional": true
|
|
67
63
|
},
|
|
@@ -69,9 +65,6 @@
|
|
|
69
65
|
"optional": true
|
|
70
66
|
}
|
|
71
67
|
},
|
|
72
|
-
"devDependencies": {
|
|
73
|
-
"typescript": "^5.8.3"
|
|
74
|
-
},
|
|
75
68
|
"author": "DJ (TTT Productions)",
|
|
76
69
|
"license": "MIT"
|
|
77
70
|
}
|