@pyric/ui 0.1.0-alpha.11 → 0.1.0-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/package.json +5 -4
  2. package/src/agents/ContextWindowUsage.tsx +514 -0
  3. package/src/agents/EmptyState.tsx +27 -0
  4. package/src/agents/Fold.tsx +64 -0
  5. package/src/agents/Modal.tsx +65 -0
  6. package/src/agents/PulsingDot.tsx +28 -0
  7. package/src/agents/inbrowser-agent-usage.d.ts +141 -0
  8. package/src/agents/index.ts +28 -0
  9. package/src/auth/authApi.ts +72 -0
  10. package/src/auth/claims.ts +63 -0
  11. package/src/auth/components/AuthProviderToggles.tsx +147 -0
  12. package/src/auth/components/AuthSignInHelper.tsx +197 -0
  13. package/src/auth/components/AuthUserForm.tsx +328 -0
  14. package/src/auth/components/AuthUserList.tsx +219 -0
  15. package/src/auth/components/ClaimsField.tsx +50 -0
  16. package/src/auth/components/confirmActions.tsx +114 -0
  17. package/src/auth/controller.ts +173 -0
  18. package/src/auth/hooks/index.ts +36 -0
  19. package/src/auth/hooks/useAuthFlowHelper.ts +55 -0
  20. package/src/auth/hooks/useAuthProviderConfig.ts +139 -0
  21. package/src/auth/hooks/useAuthUserEditor.ts +76 -0
  22. package/src/auth/hooks/useAuthUsers.ts +154 -0
  23. package/src/auth/index.ts +42 -0
  24. package/src/auth/providers.ts +28 -0
  25. package/src/auth/reducers/userEditor.ts +186 -0
  26. package/src/events/components/ActivityActionItems.tsx +136 -0
  27. package/src/events/components/ActivityGrid.tsx +197 -0
  28. package/src/events/components/ActivityGridRow.tsx +65 -0
  29. package/src/events/components/ProposedChangeDiff.tsx +175 -0
  30. package/src/events/components/format.ts +21 -0
  31. package/src/events/components/index.ts +17 -0
  32. package/src/events/digest.ts +630 -0
  33. package/src/events/hooks/index.ts +9 -0
  34. package/src/events/hooks/useActivityDigest.ts +42 -0
  35. package/src/events/hooks/useActivityStream.ts +86 -0
  36. package/src/events/index.ts +39 -0
  37. package/src/events/types.ts +152 -0
  38. package/src/firestore/components/CollectionList.tsx +78 -0
  39. package/src/firestore/components/DeleteWithConfirm.tsx +88 -0
  40. package/src/firestore/components/DocumentEditor.tsx +350 -0
  41. package/src/firestore/components/DocumentList.tsx +217 -0
  42. package/src/firestore/components/DocumentPreview.tsx +265 -0
  43. package/src/firestore/components/FieldRenderer.tsx +25 -0
  44. package/src/firestore/components/QueryBuilder.tsx +181 -0
  45. package/src/firestore/components/ReferencePicker.tsx +212 -0
  46. package/src/firestore/components/TreeEntry.tsx +58 -0
  47. package/src/firestore/components/context.ts +25 -0
  48. package/src/firestore/fieldEditors/array.tsx +30 -0
  49. package/src/firestore/fieldEditors/boolean.tsx +39 -0
  50. package/src/firestore/fieldEditors/bytes.tsx +53 -0
  51. package/src/firestore/fieldEditors/geopoint.tsx +71 -0
  52. package/src/firestore/fieldEditors/map.tsx +33 -0
  53. package/src/firestore/fieldEditors/null.tsx +27 -0
  54. package/src/firestore/fieldEditors/number.tsx +43 -0
  55. package/src/firestore/fieldEditors/reference.tsx +87 -0
  56. package/src/firestore/fieldEditors/registry.ts +45 -0
  57. package/src/firestore/fieldEditors/string.tsx +33 -0
  58. package/src/firestore/fieldEditors/timestamp.tsx +75 -0
  59. package/src/firestore/fieldEditors/types.ts +68 -0
  60. package/src/firestore/fieldEditors/vector.tsx +142 -0
  61. package/src/firestore/firestoreApi.ts +86 -0
  62. package/src/firestore/hooks/coerceError.ts +34 -0
  63. package/src/firestore/hooks/index.ts +46 -0
  64. package/src/firestore/hooks/useCollectionList.ts +102 -0
  65. package/src/firestore/hooks/useDocumentEditor.ts +161 -0
  66. package/src/firestore/hooks/useDocumentList.ts +242 -0
  67. package/src/firestore/hooks/useDocumentSubcollections.ts +86 -0
  68. package/src/firestore/hooks/useFirestoreCollection.ts +51 -0
  69. package/src/firestore/hooks/useFirestoreDoc.ts +55 -0
  70. package/src/firestore/hooks/useQueryBuilder.ts +188 -0
  71. package/src/firestore/hooks/useRecursiveDelete.ts +77 -0
  72. package/src/firestore/hooks/useReferencePicker.ts +228 -0
  73. package/src/firestore/import/parseImport.ts +137 -0
  74. package/src/firestore/index.ts +87 -0
  75. package/src/firestore/reducers/defaults.ts +38 -0
  76. package/src/firestore/reducers/documentEditor.ts +239 -0
  77. package/src/firestore/reducers/tree.ts +140 -0
  78. package/src/firestore/reducers/types.ts +92 -0
  79. package/src/firestore/reducers/validation.ts +129 -0
  80. package/src/firestore/types.ts +231 -0
  81. package/src/firestore/validation/ids.ts +45 -0
  82. package/src/firestore/valueEquality.ts +43 -0
  83. package/src/index.ts +10 -0
  84. package/src/primitives/Badge.tsx +40 -0
  85. package/src/primitives/ConfirmDialog.tsx +137 -0
  86. package/src/primitives/CopyButton.tsx +62 -0
  87. package/src/primitives/JsonView.tsx +151 -0
  88. package/src/primitives/SegmentedControl.tsx +72 -0
  89. package/src/primitives/Toast.tsx +161 -0
  90. package/src/primitives/VirtualList.tsx +104 -0
  91. package/src/primitives/hooks/useContainerSize.ts +53 -0
  92. package/src/primitives/hooks/useUpdateHighlights.ts +109 -0
  93. package/src/primitives/index.ts +39 -0
  94. package/src/primitives/useConfirm.tsx +113 -0
  95. package/src/rtdb/components/RtdbPathBar.tsx +135 -0
  96. package/src/rtdb/components/RtdbTree.tsx +409 -0
  97. package/src/rtdb/editor.ts +79 -0
  98. package/src/rtdb/hooks/useRtdbTree.ts +137 -0
  99. package/src/rtdb/index.ts +66 -0
  100. package/src/rtdb/pathInput.ts +47 -0
  101. package/src/rtdb/reducers/tree.ts +191 -0
  102. package/src/rtdb/rtdbApi.ts +23 -0
  103. package/src/rtdb/values.ts +188 -0
  104. package/src/rules/components/DenialInspector.tsx +227 -0
  105. package/src/rules/components/format.ts +171 -0
  106. package/src/rules/components/index.ts +12 -0
  107. package/src/rules/components/scope.ts +75 -0
  108. package/src/rules/hooks/index.ts +5 -0
  109. package/src/rules/hooks/useDenialTrace.ts +100 -0
  110. package/src/rules/index.ts +24 -0
  111. package/src/rules/types.ts +91 -0
  112. package/src/storage/collisionRename.ts +114 -0
  113. package/src/storage/components/DeleteSelectionWithConfirm.tsx +193 -0
  114. package/src/storage/components/ObjectBrowser.tsx +219 -0
  115. package/src/storage/components/ObjectInspector.tsx +169 -0
  116. package/src/storage/components/PathBreadcrumb.tsx +84 -0
  117. package/src/storage/components/UploadDropzone.tsx +182 -0
  118. package/src/storage/folderPlaceholder.ts +40 -0
  119. package/src/storage/hooks/index.ts +59 -0
  120. package/src/storage/hooks/useMetadataEditor.ts +329 -0
  121. package/src/storage/hooks/useObjectUpload.ts +262 -0
  122. package/src/storage/hooks/usePathState.ts +94 -0
  123. package/src/storage/hooks/useStorageDelete.ts +195 -0
  124. package/src/storage/hooks/useStorageList.ts +261 -0
  125. package/src/storage/hooks/useStorageObject.ts +162 -0
  126. package/src/storage/hooks/useStorageRulesGate.ts +270 -0
  127. package/src/storage/hooks/useStorageSelection.ts +90 -0
  128. package/src/storage/index.ts +59 -0
  129. package/src/storage/pendingPrefixes.ts +125 -0
  130. package/src/storage/previews.tsx +120 -0
  131. package/src/storage/storageApi.ts +54 -0
  132. package/src/traffic/components/RuleHeatmap.tsx +97 -0
  133. package/src/traffic/components/TrafficDetail.tsx +160 -0
  134. package/src/traffic/components/TrafficGroupRow.tsx +91 -0
  135. package/src/traffic/components/TrafficLineChart.tsx +139 -0
  136. package/src/traffic/components/TrafficLog.tsx +175 -0
  137. package/src/traffic/components/TrafficMetricCards.tsx +77 -0
  138. package/src/traffic/components/TrafficRow.tsx +69 -0
  139. package/src/traffic/components/TrafficStats.tsx +73 -0
  140. package/src/traffic/components/TrafficTimeline.tsx +289 -0
  141. package/src/traffic/components/format.ts +22 -0
  142. package/src/traffic/components/index.ts +22 -0
  143. package/src/traffic/hooks/index.ts +60 -0
  144. package/src/traffic/hooks/useRuleHeatmap.ts +92 -0
  145. package/src/traffic/hooks/useTrafficBuckets.ts +146 -0
  146. package/src/traffic/hooks/useTrafficFilter.ts +74 -0
  147. package/src/traffic/hooks/useTrafficGroups.ts +126 -0
  148. package/src/traffic/hooks/useTrafficMetrics.ts +250 -0
  149. package/src/traffic/hooks/useTrafficMonitor.ts +111 -0
  150. package/src/traffic/hooks/useTrafficStats.ts +77 -0
  151. package/src/traffic/index.ts +13 -0
  152. package/src/traffic/types.ts +85 -0
@@ -0,0 +1,86 @@
1
+ import { useEffect, useMemo, useRef, useState } from 'react';
2
+ import type { ActivitySource, AnyActivityEvent } from '../types.js';
3
+
4
+ export interface UseActivityStreamOptions {
5
+ /**
6
+ * The subscription — `sandbox.onEvent` satisfies this directly. Pass
7
+ * a stable reference; the hook re-subscribes on identity change.
8
+ */
9
+ source: ActivitySource;
10
+ /**
11
+ * Seed the buffer with a snapshot before the live subscription
12
+ * attaches — typically `sandbox.history()`, so a late-attaching
13
+ * consumer sees the whole session, not just events from `subscribe`
14
+ * onward. Read once on mount.
15
+ */
16
+ initial?: readonly AnyActivityEvent[];
17
+ /**
18
+ * Ring-buffer cap. Once exceeded, the oldest events drop. Default
19
+ * 5000 (mirrors the traffic monitor's cap — a load-test session can
20
+ * emit 100k+ events).
21
+ */
22
+ bufferSize?: number;
23
+ /** Start paused — incoming events drop (not queued) while paused. */
24
+ paused?: boolean;
25
+ }
26
+
27
+ export interface UseActivityStreamResult {
28
+ /** The buffered events, oldest-first. Stable per emission — safe to
29
+ * hand straight to {@link useActivityDigest}. */
30
+ events: AnyActivityEvent[];
31
+ isPaused: boolean;
32
+ pause: () => void;
33
+ resume: () => void;
34
+ /** Empty the buffer (does NOT re-seed from `initial`). */
35
+ clear: () => void;
36
+ }
37
+
38
+ /**
39
+ * Buffers the unified sandbox event stream into a capped ring buffer
40
+ * with optional history seeding + pause/resume/clear. Decoupled from
41
+ * `pyric` — `source` is just a `(cb) => unsubscribe`.
42
+ *
43
+ * Sibling to the traffic monitor's `useTrafficMonitor`; the difference
44
+ * is the wider event type (`AnyActivityEvent`, the full union) and the
45
+ * `initial` seed so `history()` + live compose into one buffer.
46
+ */
47
+ export function useActivityStream({
48
+ source,
49
+ initial,
50
+ bufferSize = 5000,
51
+ paused = false,
52
+ }: UseActivityStreamOptions): UseActivityStreamResult {
53
+ const [events, setEvents] = useState<AnyActivityEvent[]>(() =>
54
+ initial ? initial.slice(-bufferSize) : [],
55
+ );
56
+ const [isPaused, setIsPaused] = useState(paused);
57
+
58
+ const pausedRef = useRef(isPaused);
59
+ pausedRef.current = isPaused;
60
+ const bufferSizeRef = useRef(bufferSize);
61
+ bufferSizeRef.current = bufferSize;
62
+
63
+ useEffect(() => {
64
+ const unsubscribe = source((event) => {
65
+ if (pausedRef.current) return;
66
+ setEvents((prev) => {
67
+ const next =
68
+ prev.length >= bufferSizeRef.current ? prev.slice(1) : prev.slice();
69
+ next.push(event);
70
+ return next;
71
+ });
72
+ });
73
+ return unsubscribe;
74
+ }, [source]);
75
+
76
+ return useMemo(
77
+ () => ({
78
+ events,
79
+ isPaused,
80
+ pause: () => setIsPaused(true),
81
+ resume: () => setIsPaused(false),
82
+ clear: () => setEvents([]),
83
+ }),
84
+ [events, isPaused],
85
+ );
86
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `@pyric/ui/events` — headless activity view over the unified
3
+ * `SandboxEvent` stream (Pyric Studio's keystone). Aggregates the whole
4
+ * stream (Firestore request/write + the cross-service `service_mutation`
5
+ * envelope for auth/storage/rtdb) into category bands with per-row
6
+ * provenance — the activity grid. Sibling to `@pyric/ui/traffic` (which
7
+ * is per-request, not aggregated-by-category).
8
+ *
9
+ * Ships zero styling — Pyric Studio applies the `data-pyric-*` contract.
10
+ */
11
+ export * from './hooks/index.js';
12
+ export * from './components/index.js';
13
+
14
+ export {
15
+ computeActivityDigest,
16
+ type ActivityDigest,
17
+ type ActivityDigestOptions,
18
+ type ActivityGroupBy,
19
+ type ActivityBand,
20
+ type ActivityBandWithGroups,
21
+ type ActivitySubgroup,
22
+ type ActivityBandKey,
23
+ type ActivityRow,
24
+ } from './digest.js';
25
+
26
+ export type {
27
+ ActivityEvent,
28
+ AnyActivityEvent,
29
+ ActivitySource,
30
+ ActivityRequestEvent,
31
+ ActivityWriteEvent,
32
+ ActivityServiceMutationEvent,
33
+ ActivityProvenance,
34
+ ActivityService,
35
+ ActivityActor,
36
+ ActivityLens,
37
+ ActivityResult,
38
+ ActivityAuthState,
39
+ } from './types.js';
@@ -0,0 +1,152 @@
1
+ /**
2
+ * The events/activity domain types. These are a local, structurally-
3
+ * compatible mirror of `pyric`'s unified `SandboxEvent` union (and its
4
+ * `EventProvenance`) — the `@pyric/ui` packages never import `pyric` so
5
+ * the headless layer stays decoupled from the sandbox impl (the same
6
+ * stance the sibling `traffic/` area takes with `RequestEvent`).
7
+ *
8
+ * `sandbox.onEvent` / `sandbox.history()` are assignable as an
9
+ * `ActivitySource` / `ActivityEvent[]` with zero adapter code: every
10
+ * field here is a subset (by name + shape) of the matching field on the
11
+ * sandbox type. A production audit feed satisfying the same shape works
12
+ * too.
13
+ *
14
+ * Unlike `traffic/` (which models only Firestore `request` events, one
15
+ * row per evaluated op), the events area aggregates the FULL stream —
16
+ * Firestore `request`/`write` plus the cross-service `service_mutation`
17
+ * envelope (auth / storage / rtdb) — into category bands. So the local
18
+ * types cover the union members the digest reads, not just one kind.
19
+ */
20
+
21
+ /** Which sandbox service emitted an event. Absent ⇒ `'firestore'`. */
22
+ export type ActivityService = 'firestore' | 'auth' | 'storage' | 'rtdb';
23
+
24
+ /** Who initiated the op behind an event. Absent ⇒ the served app. */
25
+ export type ActivityActor =
26
+ | { kind: 'app' }
27
+ | { kind: 'studio' }
28
+ | { kind: 'agent'; name: string }
29
+ | { kind: 'app-builder' };
30
+
31
+ /**
32
+ * The auth lens an op ran under. `admin` bypasses rules, `as` evaluates
33
+ * rules as a specific uid (impersonation), `app-session` is the app's
34
+ * own signed-in user. Absent ⇒ `app-session`.
35
+ */
36
+ export type ActivityLens =
37
+ | { mode: 'admin' }
38
+ | { mode: 'as'; uid: string }
39
+ | { mode: 'app-session' };
40
+
41
+ /** Identity in effect for an op. `null` is anonymous / signed out. */
42
+ export interface ActivityAuthState {
43
+ uid: string;
44
+ token?: Record<string, unknown>;
45
+ }
46
+
47
+ /**
48
+ * Provenance carried by every event. All optional + additive — pre-
49
+ * provenance emitters omit them (read as firestore / app / app-session).
50
+ */
51
+ export interface ActivityProvenance {
52
+ service?: ActivityService;
53
+ actor?: ActivityActor;
54
+ authLens?: ActivityLens;
55
+ /** Set when the op is part of an agent plan (dry-run / accept). */
56
+ planId?: string;
57
+ }
58
+
59
+ /** Firestore op outcome — present on `request` events only. */
60
+ export type ActivityResult = 'allow' | 'deny' | 'unsupported';
61
+
62
+ /**
63
+ * A Firestore `request` event — one per evaluated op. The digest reads
64
+ * these for denials (`result === 'deny'`) and, when no `write` event is
65
+ * present, for the allow trail. Structurally a subset of `RequestEvent`.
66
+ */
67
+ export interface ActivityRequestEvent extends ActivityProvenance {
68
+ kind: 'request';
69
+ id: string;
70
+ at: number;
71
+ method: 'get' | 'list' | 'create' | 'update' | 'set' | 'delete';
72
+ path: string;
73
+ auth: ActivityAuthState | null;
74
+ result: ActivityResult;
75
+ /** Simulator debug trail. Used to surface the deciding rule on denials. */
76
+ reasons: string[];
77
+ request?: { resourceData?: Record<string, unknown> };
78
+ resourceBefore?: { data: Record<string, unknown> | null; exists: boolean };
79
+ resourceAfter?: { data: Record<string, unknown> | null; exists: boolean };
80
+ matchedRule?: { ruleIndex: number; operations: string[] };
81
+ origin: 'user' | 'listener' | 'transaction' | 'batch';
82
+ groupId?: string;
83
+ triggeredBy?: { method: string; path: string };
84
+ }
85
+
86
+ /**
87
+ * A committed Firestore write — `create`/`update`/`set`/`delete` that
88
+ * the rule engine allowed and the keyspace applied. The digest leads
89
+ * with these for the added/updated/removed bands (richer than `request`:
90
+ * carries prior/next state for the change summary). Subset of
91
+ * `WriteSandboxEvent`.
92
+ */
93
+ export interface ActivityWriteEvent extends ActivityProvenance {
94
+ kind: 'write';
95
+ id: string;
96
+ at: number;
97
+ method: 'create' | 'update' | 'set' | 'delete';
98
+ path: string;
99
+ auth: ActivityAuthState | null;
100
+ data?: Record<string, unknown>;
101
+ priorState: Record<string, unknown> | null;
102
+ nextState: Record<string, unknown> | null;
103
+ groupId?: string;
104
+ }
105
+
106
+ /**
107
+ * Cross-service mutation — the unified envelope auth / storage / rtdb
108
+ * emit. The digest maps `service` + `op` to a band (signed-in, added,
109
+ * updated, removed, …). Subset of `ServiceMutationEvent`.
110
+ */
111
+ export interface ActivityServiceMutationEvent extends ActivityProvenance {
112
+ kind: 'service_mutation';
113
+ id: string;
114
+ at: number;
115
+ service: 'auth' | 'storage' | 'rtdb';
116
+ op: string;
117
+ path?: string;
118
+ auth: ActivityAuthState | null;
119
+ before?: unknown;
120
+ after?: unknown;
121
+ detail?: Record<string, unknown>;
122
+ }
123
+
124
+ /**
125
+ * The union members the activity digest aggregates. This is a SUBSET of
126
+ * `pyric`'s `SandboxEvent` — the listener-lifecycle / snapshot-delivery /
127
+ * session-boundary kinds carry no user-visible mutation, so the digest
128
+ * ignores them. The reducer accepts any object with a `kind` and skips
129
+ * the kinds it doesn't model, so a full `SandboxEvent[]` passes through
130
+ * cleanly (the extra kinds fall into the "unknown ⇒ skipped" branch).
131
+ */
132
+ export type ActivityEvent =
133
+ | ActivityRequestEvent
134
+ | ActivityWriteEvent
135
+ | ActivityServiceMutationEvent;
136
+
137
+ /**
138
+ * The widened input the reducer accepts: any `ActivityEvent`, plus a
139
+ * permissive escape for unmodelled `SandboxEvent` kinds carrying a
140
+ * string `kind` (skipped). Lets `sandbox.history()` flow in unfiltered.
141
+ */
142
+ export type AnyActivityEvent =
143
+ | ActivityEvent
144
+ | { kind: string; [k: string]: unknown };
145
+
146
+ /**
147
+ * A subscription: register a callback, get an unsubscribe.
148
+ * `sandbox.onEvent` matches this signature.
149
+ */
150
+ export type ActivitySource = (
151
+ cb: (event: AnyActivityEvent) => void,
152
+ ) => () => void;
@@ -0,0 +1,78 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { CollectionReference } from 'pyric/firestore';
3
+
4
+ export interface CollectionListProps {
5
+ collections: CollectionReference[];
6
+ isLoading?: boolean;
7
+ error?: Error;
8
+ /** Fired when a list item is clicked. Consumer wires navigation. */
9
+ onSelect?: (collection: CollectionReference) => void;
10
+ /** Optional empty-state node. Rendered when `collections.length`
11
+ * is 0 and the list isn't loading. */
12
+ emptyState?: ReactNode;
13
+ className?: string;
14
+ }
15
+
16
+ /**
17
+ * Headless collection list. Takes a pre-fetched array of references
18
+ * (from `useCollectionList`) plus a select callback. Renders one
19
+ * row per collection with `data-pyric-collection-id` for styling
20
+ * and testing. The library does not own the data fetch — the hook
21
+ * does — so this component is a thin presentational layer.
22
+ */
23
+ export function CollectionList({
24
+ collections,
25
+ isLoading,
26
+ error,
27
+ onSelect,
28
+ emptyState,
29
+ className,
30
+ }: CollectionListProps) {
31
+ if (error) {
32
+ return (
33
+ <div
34
+ className={className}
35
+ data-pyric-ui="collection-list"
36
+ data-pyric-error=""
37
+ role="alert"
38
+ >
39
+ {error.message}
40
+ </div>
41
+ );
42
+ }
43
+ if (isLoading && collections.length === 0) {
44
+ return (
45
+ <div
46
+ className={className}
47
+ data-pyric-ui="collection-list"
48
+ data-pyric-loading=""
49
+ />
50
+ );
51
+ }
52
+ if (collections.length === 0) {
53
+ return (
54
+ <div className={className} data-pyric-ui="collection-list" data-pyric-empty="">
55
+ {emptyState}
56
+ </div>
57
+ );
58
+ }
59
+ return (
60
+ <ul className={className} data-pyric-ui="collection-list">
61
+ {collections.map((coll) => (
62
+ <li
63
+ key={coll.path}
64
+ data-pyric-collection-entry
65
+ data-pyric-collection-id={coll.id}
66
+ >
67
+ <button
68
+ type="button"
69
+ onClick={() => onSelect?.(coll)}
70
+ data-pyric-collection-select
71
+ >
72
+ {coll.id}
73
+ </button>
74
+ </li>
75
+ ))}
76
+ </ul>
77
+ );
78
+ }
@@ -0,0 +1,88 @@
1
+ import { type ReactNode } from 'react';
2
+ import type {
3
+ CollectionReference,
4
+ DocumentReference,
5
+ } from 'pyric/firestore';
6
+ import { useConfirm } from '../../primitives/useConfirm.js';
7
+ import {
8
+ useRecursiveDelete,
9
+ type RecursiveDeleteImpl,
10
+ } from '../hooks/useRecursiveDelete.js';
11
+
12
+ export interface DeleteWithConfirmProps {
13
+ /** The doc / collection to delete. */
14
+ target: DocumentReference | CollectionReference;
15
+ /** Implementation that walks the tree + deletes. Consumer-supplied.
16
+ * Sandbox-backed apps usually wire `pyric/sandbox` introspection;
17
+ * production apps usually call a Cloud Function. */
18
+ impl: RecursiveDeleteImpl;
19
+ /** Confirm-dialog title. Defaults to a sensible derivation from
20
+ * the target's path. */
21
+ title?: string;
22
+ /** Confirm-dialog body. */
23
+ body?: ReactNode;
24
+ /** Label on the destructive button. */
25
+ confirmLabel?: string;
26
+ /** Fired after the delete iterator finishes successfully. */
27
+ onDeleted?: () => void;
28
+ /** Optional render override for the trigger button. */
29
+ renderTrigger?: (props: {
30
+ onClick: () => void;
31
+ isRunning: boolean;
32
+ progress: number;
33
+ }) => ReactNode;
34
+ /** Class forwarded to the default trigger button. */
35
+ className?: string;
36
+ }
37
+
38
+ /**
39
+ * Composition that wires `useConfirm` + `useRecursiveDelete`. Requires
40
+ * a `<ConfirmProvider>` ancestor.
41
+ *
42
+ * The default trigger renders a plain `<button>` carrying the
43
+ * destructive intent (the consumer styles via `[data-pyric-destructive]`).
44
+ * Consumers wanting different chrome pass `renderTrigger`.
45
+ */
46
+ export function DeleteWithConfirm({
47
+ target,
48
+ impl,
49
+ title,
50
+ body,
51
+ confirmLabel = 'Delete',
52
+ onDeleted,
53
+ renderTrigger,
54
+ className,
55
+ }: DeleteWithConfirmProps) {
56
+ const confirm = useConfirm();
57
+ const { delete: runDelete, isRunning, progress, error } = useRecursiveDelete(impl);
58
+
59
+ const handleClick = async () => {
60
+ const ok = await confirm({
61
+ title: title ?? `Delete ${target.path}?`,
62
+ body,
63
+ destructive: true,
64
+ confirmLabel,
65
+ });
66
+ if (!ok) return;
67
+ await runDelete(target);
68
+ if (!error) onDeleted?.();
69
+ };
70
+
71
+ if (renderTrigger) {
72
+ return <>{renderTrigger({ onClick: handleClick, isRunning, progress })}</>;
73
+ }
74
+
75
+ return (
76
+ <button
77
+ type="button"
78
+ onClick={handleClick}
79
+ className={className}
80
+ disabled={isRunning}
81
+ data-pyric-ui="delete-with-confirm"
82
+ data-pyric-destructive=""
83
+ data-pyric-running={isRunning ? '' : undefined}
84
+ >
85
+ {isRunning ? `Deleting… (${progress})` : confirmLabel}
86
+ </button>
87
+ );
88
+ }