@dudousxd/nestjs-catalog-react 0.19.0 → 0.21.0

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.
@@ -0,0 +1,343 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * Taking an edit back, throwing the whole draft away, and not losing it by
4
+ * accident.
5
+ *
6
+ * WHY THIS IS ITS OWN FILE
7
+ * ------------------------
8
+ * Everything here is about the same one thing — the gap between what is on the
9
+ * canvas and what the server has — and none of it is about drawing a graph.
10
+ * `WorkflowCanvas.tsx` is already six thousand lines and is the file every
11
+ * feature wants to grow, so the rule that keeps it readable is that a concern
12
+ * with its own vocabulary gets its own module. This one has four words in it:
13
+ * an ACTION (the unit undo steps over), the PAST (the actions still takeable
14
+ * back), the BASELINE (the graph as the server last described it) and DIRTY
15
+ * (whether those two differ).
16
+ *
17
+ * WHAT THIS DOES NOT COVER, AND SAYS SO ON SCREEN
18
+ * ----------------------------------------------
19
+ * Undo is about the DRAFT and nothing else. Saving, publishing, running and
20
+ * deleting the workflow are requests the server has already answered; a control
21
+ * that appeared to unmake one of them would be promising something no client
22
+ * can deliver. The boundary is stated in {@link UNDO_SCOPE}, which is rendered —
23
+ * as a tooltip for a pointer and as text for a screen reader — rather than left
24
+ * in this comment, because a boundary somebody has to read the source to learn
25
+ * is not a boundary they will learn.
26
+ *
27
+ * WHY SNAPSHOTS RATHER THAN INVERSE COMMANDS
28
+ * ------------------------------------------
29
+ * The alternative is an undo stack of operations that know how to reverse
30
+ * themselves. That is smaller in memory and considerably more code, and every
31
+ * new gesture on the canvas is a new inverse that can be written wrongly — a
32
+ * wrong inverse is silent, and lands in a SAVED graph. A snapshot cannot be
33
+ * wrong about what the graph was. The cost is bounded by {@link UNDO_DEPTH} and
34
+ * by the fact that a snapshot holds the same node and edge ARRAYS the draft
35
+ * already held: this canvas replaces arrays rather than mutating them (see the
36
+ * copy note in `draftFrom`), so an entry costs four references, not a graph.
37
+ */
38
+ import { RotateCcw, Undo2 } from 'lucide-react';
39
+ import { useEffect } from 'react';
40
+ import { cn } from '../cn';
41
+ import { Button } from '../ui/button';
42
+ import { ConfirmDialog } from '../ui/dialog';
43
+ import { Tooltip } from '../ui/tooltip';
44
+ import { nodeName } from './model';
45
+ import { WORKFLOW_NAME } from './name';
46
+ /**
47
+ * How many actions can be taken back.
48
+ *
49
+ * A cap rather than an unbounded stack, and 50 rather than 500, because the
50
+ * promise a history makes should be one it can keep at any graph size. Fifty
51
+ * snapshots of a hundred-node graph is fifty times four references — nothing —
52
+ * but the honesty matters more than the arithmetic: an unbounded stack grows
53
+ * with how long somebody has had the tab open, which is exactly the session
54
+ * where they can least afford the tab to get slow.
55
+ *
56
+ * At the limit the OLDEST entry is dropped, so undo always steps back from
57
+ * where the person is rather than refusing. What is lost is the ability to walk
58
+ * all the way to the beginning — and that is what Reset is for, which is why the
59
+ * two controls sit beside each other and why {@link resetDescription} says how
60
+ * many actions are about to go.
61
+ */
62
+ export const UNDO_DEPTH = 50;
63
+ /**
64
+ * How long a run of edits stays open, when nothing else closes it.
65
+ *
66
+ * The fallback half of the granularity rule. A gesture with a real end — a drag
67
+ * — says so through `continuing` and ignores this entirely; a gesture without
68
+ * one — typing into a field, holding an arrow key — has only elapsed time to go
69
+ * on. 700ms is longer than a fast typist's inter-key gap and shorter than the
70
+ * pause somebody makes when they stop to think, which is the boundary between
71
+ * "still writing the name" and "wrote the name, then did something else".
72
+ */
73
+ export const RUN_WINDOW_MS = 700;
74
+ /** What undo can and cannot reach, in the words the controls use. */
75
+ export const UNDO_SCOPE = `Undo steps back through your edits to this drawing, one action at a time — up to the last ${UNDO_DEPTH}. It does not touch anything the server has already done: saving, publishing, running and deleting the ${WORKFLOW_NAME.singular} are not undone here.`;
76
+ /** Said once, when somebody reaches for a redo that deliberately does not exist. */
77
+ export const NO_REDO = 'There is no redo on this canvas. Undo only steps backwards; Reset returns the whole drawing to the last saved version.';
78
+ export function snapshotOf(draft) {
79
+ return {
80
+ name: draft.name,
81
+ description: draft.description,
82
+ nodes: draft.nodes,
83
+ edges: draft.edges,
84
+ };
85
+ }
86
+ /**
87
+ * Whether two snapshots are the same graph.
88
+ *
89
+ * Reference identity on the arrays, and that is the point rather than a
90
+ * shortcut. Nothing on this canvas mutates a node or an edge array in place —
91
+ * every path replaces — so two identical references ARE the same graph, and the
92
+ * comparison cannot report "unchanged" for a graph that has changed. It can
93
+ * report "changed" for a graph that has been edited back to where it started
94
+ * through two different arrays, and that asymmetry is the safe one: the only
95
+ * consequence is a save button that stays live and a leave-warning that still
96
+ * fires, which is a nuisance. The opposite error loses work.
97
+ *
98
+ * Undo restores the very arrays it recorded, so walking all the way back to the
99
+ * baseline compares equal and the draft goes genuinely clean — which is what
100
+ * makes the beforeunload guard below trustworthy enough to be worth having.
101
+ */
102
+ export function sameSnapshot(a, b) {
103
+ return (a.name === b.name &&
104
+ a.description === b.description &&
105
+ a.nodes === b.nodes &&
106
+ a.edges === b.edges);
107
+ }
108
+ /**
109
+ * An edit, recorded.
110
+ *
111
+ * Pure, and it has to be: this runs inside a `setState` updater, which React is
112
+ * free to call twice for the same input. Nothing here reads or writes anything
113
+ * outside its arguments except the clock, and the clock only moves a timestamp
114
+ * that two calls a microsecond apart agree about anyway.
115
+ */
116
+ export function withEdit(before, after, action) {
117
+ return { ...after, dirty: true, past: pushed(before, action) };
118
+ }
119
+ function pushed(before, action) {
120
+ const past = before.past;
121
+ const top = past.at(-1);
122
+ const now = Date.now();
123
+ if (top && action.run !== undefined && top.run === action.run) {
124
+ const open = action.continuing === true || now - top.at <= RUN_WINDOW_MS;
125
+ // The entry already holds the state from before the gesture began, so
126
+ // folding into it is simply not pushing. Its clock moves so the run stays
127
+ // open for as long as the gesture keeps producing frames.
128
+ if (open)
129
+ return [...past.slice(0, -1), { ...top, at: now }];
130
+ }
131
+ const next = [
132
+ ...past,
133
+ { before: snapshotOf(before), label: action.label, run: action.run, at: now },
134
+ ];
135
+ // Drop from the front, never refuse at the back: a person who has made
136
+ // fifty-one edits wants the fifty-first taken back, not a message about a
137
+ // limit.
138
+ return next.length > UNDO_DEPTH ? next.slice(next.length - UNDO_DEPTH) : next;
139
+ }
140
+ /** The next thing undo would take back, for a control that has to name it. */
141
+ export function nextUndo(draft) {
142
+ return draft.past.at(-1);
143
+ }
144
+ /**
145
+ * One action back.
146
+ *
147
+ * Returns the label as well as the draft because the announcement is half the
148
+ * feature: undo can revert something that is scrolled off the canvas, and a
149
+ * silent revert of an invisible thing is indistinguishable from nothing
150
+ * happening.
151
+ */
152
+ export function undone(draft) {
153
+ const top = nextUndo(draft);
154
+ if (!top)
155
+ return null;
156
+ const past = draft.past.slice(0, -1);
157
+ const restored = { ...draft, ...top.before, past };
158
+ return {
159
+ draft: { ...restored, dirty: !sameSnapshot(top.before, draft.baseline) },
160
+ label: top.label,
161
+ };
162
+ }
163
+ /**
164
+ * All the way back to the last saved version.
165
+ *
166
+ * The history goes with it. Keeping it would offer to undo the reset, which is
167
+ * a redo of everything by another name — and this module does not have one.
168
+ */
169
+ export function reverted(draft) {
170
+ return { ...draft, ...draft.baseline, past: [], dirty: false };
171
+ }
172
+ /** The ids still in the graph, for the per-node bookkeeping the canvas keeps. */
173
+ export function keepKnown(ids, nodes) {
174
+ const alive = new Set(nodes.map((node) => node.id));
175
+ const kept = [...ids].filter((id) => alive.has(id));
176
+ return kept.length === ids.size ? ids : new Set(kept);
177
+ }
178
+ /** How many nodes, named where naming them is short enough to be useful. */
179
+ export function namesOf(nodes, ids) {
180
+ const found = [...ids].map((id) => {
181
+ const node = nodes.find((candidate) => candidate.id === id);
182
+ return node ? `"${nodeName(node)}"` : id;
183
+ });
184
+ if (found.length === 0)
185
+ return 'nothing';
186
+ if (found.length === 1)
187
+ return found[0];
188
+ if (found.length === 2)
189
+ return `${found[0]} and ${found[1]}`;
190
+ return `${found.length} nodes`;
191
+ }
192
+ /**
193
+ * One edit to a node, described by which of its fields moved.
194
+ *
195
+ * The run key carries the CHANGED FIELDS, not just the node, and that is the
196
+ * difference between a useful granularity and an irritating one: typing into a
197
+ * name box folds into one action, but typing a name and then flipping a switch
198
+ * on the same node a moment later stays two — because the second edit touches a
199
+ * different field and so opens a new run. Without the field in the key those two
200
+ * would merge, and undoing the switch would silently retype the name.
201
+ *
202
+ * The fields are read through `Object.entries` rather than by name: a node is a
203
+ * union of six shapes with different fields each, and a hand-written list here
204
+ * would go quietly out of date the next time a node kind gains one — which
205
+ * shows up as an edit that mysteriously will not undo on its own.
206
+ */
207
+ export function nodeEditAction(before, after) {
208
+ const label = `editing "${nodeName(before ?? after)}"`;
209
+ if (!before)
210
+ return { label };
211
+ const was = new Map(Object.entries(before));
212
+ const now = new Map(Object.entries(after));
213
+ const fields = [...new Set([...was.keys(), ...now.keys()])]
214
+ .filter((field) => !Object.is(was.get(field), now.get(field)))
215
+ .sort();
216
+ return { label, run: `node:${after.id}:${fields.join(',')}` };
217
+ }
218
+ /** What Reset is about to do, in the numbers the person can check it against. */
219
+ export function resetDescription(draft) {
220
+ const count = draft.past.length;
221
+ const actions = count === 0
222
+ ? 'Everything unsaved'
223
+ : count >= UNDO_DEPTH
224
+ ? `At least ${count} actions`
225
+ : `${count} ${count === 1 ? 'action' : 'actions'}`;
226
+ return `${actions} will be thrown away and the drawing goes back to the version the server last stored. This cannot be undone — Undo only steps back through edits, and Reset clears them. Nothing the server holds is touched: no run is stopped, nothing is unpublished, and the stored ${WORKFLOW_NAME.singular} stays exactly as it is.`;
227
+ }
228
+ /**
229
+ * A tab that will not close on unsaved work without asking.
230
+ *
231
+ * Registered only while there IS unsaved work, which is the whole design
232
+ * constraint: a page that always warns teaches people to dismiss the dialog
233
+ * without reading it, and then it is not a guard, it is a habit. Cleaning up on
234
+ * `dirty` going false is what makes a save silence it immediately.
235
+ *
236
+ * The wording belongs to the browser — every engine ignores whatever string a
237
+ * page supplies here, and has for a decade — so this asks for the dialog and
238
+ * says nothing. `returnValue` is set as well as `preventDefault` because Chrome
239
+ * and Safari have historically disagreed about which one arms it.
240
+ *
241
+ * Nothing happens on a server: `useEffect` does not run there, so a host
242
+ * rendering this canvas into HTML sees no `window`.
243
+ */
244
+ export function useUnsavedGuard(dirty) {
245
+ useEffect(() => {
246
+ if (!dirty)
247
+ return;
248
+ const warn = (event) => {
249
+ event.preventDefault();
250
+ event.returnValue = '';
251
+ };
252
+ window.addEventListener('beforeunload', warn);
253
+ return () => window.removeEventListener('beforeunload', warn);
254
+ }, [dirty]);
255
+ }
256
+ /**
257
+ * Whether a key press belongs to something being typed into.
258
+ *
259
+ * The reason Cmd/Ctrl+Z can be bound at all. This canvas contains a name field,
260
+ * a description box, several config fields and a real code editor, and in every
261
+ * one of them Cmd+Z means "undo my typing" — a canvas-level binding that fired
262
+ * there would silently discard a graph edit instead, which is the worst possible
263
+ * outcome for a control whose entire job is not losing work.
264
+ *
265
+ * `closest` rather than the target itself: a contenteditable code surface puts
266
+ * the caret on a descendant span, so the event target is not the editable host.
267
+ * The dialog and sheet cases are the same argument one level up — a modal over
268
+ * the canvas is a different document with its own undo, and the canvas has no
269
+ * business acting on keys pressed inside it.
270
+ *
271
+ * Narrowed with `instanceof` rather than asserted: `event.target` is typed
272
+ * `EventTarget | null` and genuinely can be a `Window` or a text node.
273
+ */
274
+ export function isTypingTarget(target) {
275
+ if (!(target instanceof Element))
276
+ return false;
277
+ return (target.closest('input, textarea, select, [contenteditable="true"], [contenteditable=""], [role="textbox"]') !== null || target.closest('[role="dialog"], [role="alertdialog"], [role="menu"]') !== null);
278
+ }
279
+ /**
280
+ * Cmd/Ctrl+Z, on the canvas and nowhere else.
281
+ *
282
+ * Shift+Cmd/Ctrl+Z is caught deliberately rather than left to the browser: the
283
+ * hands that reach for it are expecting a redo, and silence would read as a
284
+ * broken shortcut. It says there is none, once, in the same live region
285
+ * everything else on this canvas speaks through.
286
+ *
287
+ * On `window` rather than on the canvas element because the canvas is not
288
+ * reliably focused — somebody who has just clicked a toolbar button, or closed
289
+ * the inspector, has focus on chrome — and a shortcut that only works when the
290
+ * right thing happens to be focused is a shortcut people stop trusting.
291
+ */
292
+ export function useUndoShortcut({ enabled, onUndo, onSay, }) {
293
+ useEffect(() => {
294
+ if (!enabled)
295
+ return;
296
+ const onKeyDown = (event) => {
297
+ if (!(event.metaKey || event.ctrlKey) || event.altKey)
298
+ return;
299
+ if (event.key.toLowerCase() !== 'z')
300
+ return;
301
+ if (isTypingTarget(event.target))
302
+ return;
303
+ // Only once the press is definitely ours: preventing the default before
304
+ // the typing check would swallow the browser's own undo in a field.
305
+ event.preventDefault();
306
+ if (event.shiftKey) {
307
+ onSay(NO_REDO);
308
+ return;
309
+ }
310
+ onUndo();
311
+ };
312
+ window.addEventListener('keydown', onKeyDown);
313
+ return () => window.removeEventListener('keydown', onKeyDown);
314
+ }, [enabled, onUndo, onSay]);
315
+ }
316
+ /**
317
+ * Undo, Reset, and the fact that there is unsaved work — as one cluster.
318
+ *
319
+ * Together because they are one subject and answer each other: the chip says
320
+ * something is at risk, Undo takes back the last thing, Reset gives up on all of
321
+ * it. Split across the screen they would be three unrelated controls, and the
322
+ * chip in particular means nothing without something to do about it.
323
+ *
324
+ * The unsaved chip is `role="status"`, so it is announced when it appears rather
325
+ * than only when somebody goes looking. It appears once per clean→dirty
326
+ * transition, because its text does not change while dirty — a status that
327
+ * re-announced on every keystroke would be unusable.
328
+ */
329
+ export function HistoryControls({ draft, canEdit, reducedMotion, resetting, onResettingChange, onUndo, onReset, }) {
330
+ const top = nextUndo(draft);
331
+ const depth = draft.past.length;
332
+ return (_jsxs(_Fragment, { children: [_jsx(Tooltip, { content: top
333
+ ? `Take back: ${top.label}. ${UNDO_SCOPE} ${depth === 1 ? 'This is the last one.' : `${depth} to go.`} Keyboard: Ctrl+Z, or ⌘Z.`
334
+ : `Nothing to take back yet. ${UNDO_SCOPE}`, children: _jsxs(Button, { variant: "ghost", size: "sm", onClick: onUndo, disabled: !canEdit || !top, "aria-label": top ? `Undo: ${top.label}` : 'Undo — nothing to take back yet', children: [_jsx(Undo2, { size: 12 }), _jsx("span", { className: "hidden md:inline", children: "Undo" })] }) }), _jsx(Tooltip, { content: "Throw away every unsaved edit and go back to the version the server last stored. Not the same as undoing repeatedly: if you saved partway through, this returns to THAT save, not to where you started.", children: _jsxs(Button, { variant: "ghost", size: "sm", onClick: () => onResettingChange(true), disabled: !canEdit || !draft.dirty, "aria-label": "Reset to the last saved version, discarding every unsaved edit",
335
+ // Coloured like the delete control beside it, and for the same reason:
336
+ // this destroys work, and a control that destroys work should look
337
+ // like one before it is pressed rather than after.
338
+ className: "text-zinc-400 hover:text-red-600", children: [_jsx(RotateCcw, { size: 12 }), _jsx("span", { className: "hidden md:inline", children: "Reset" })] }) }), draft.dirty && (_jsxs("output", { className: "flex shrink-0 items-center gap-1.5 rounded px-1.5 py-0.5 font-mono text-[10px] text-amber-700 dark:text-amber-300", children: [_jsx("span", { "aria-hidden": true, className: cn('h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500',
339
+ // A quiet pulse, because the whole job of this dot is to be
340
+ // noticed in peripheral vision — and nothing at all for somebody
341
+ // who has asked their machine to stop moving things.
342
+ !reducedMotion && 'animate-pulse') }), "Unsaved"] })), _jsx("p", { className: "sr-only", children: UNDO_SCOPE }), _jsx(ConfirmDialog, { open: resetting, onOpenChange: onResettingChange, title: "Discard every unsaved edit?", description: resetDescription(draft), confirmLabel: "Discard and reset", onConfirm: onReset })] }));
343
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudousxd/nestjs-catalog-react",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "Ready-made React screens for @dudousxd/nestjs-catalog — a model manager and a generic object explorer you can drop into your own app shell.",
5
5
  "license": "MIT",
6
6
  "author": "Davide Carvalho",
@@ -45,10 +45,6 @@
45
45
  "dist",
46
46
  "LICENSE-bklit"
47
47
  ],
48
- "scripts": {
49
- "build": "tsc -p tsconfig.json",
50
- "dev": "tsc -p tsconfig.json --watch"
51
- },
52
48
  "peerDependencies": {
53
49
  "@base-ui/react": ">=1.6.0",
54
50
  "@pierre/diffs": ">=1.3.3",
@@ -84,7 +80,6 @@
84
80
  "@dnd-kit/core": "6.3.1",
85
81
  "@dnd-kit/sortable": "10.0.0",
86
82
  "@dnd-kit/utilities": "3.2.2",
87
- "@dudousxd/nestjs-catalog": "workspace:*",
88
83
  "@pierre/diffs": "1.3.3",
89
84
  "@tanstack/react-query": "5.99.2",
90
85
  "@tanstack/react-table": "9.0.0",
@@ -114,7 +109,8 @@
114
109
  "recharts": "2.15.4",
115
110
  "tailwind-merge": "3.4.1",
116
111
  "tiptap-markdown": "0.9.0",
117
- "typescript": "5.9.3"
112
+ "typescript": "5.9.3",
113
+ "@dudousxd/nestjs-catalog": "0.18.0"
118
114
  },
119
115
  "dependencies": {
120
116
  "clsx": "2.1.1",
@@ -160,5 +156,9 @@
160
156
  "@xyflow/react": {
161
157
  "optional": true
162
158
  }
159
+ },
160
+ "scripts": {
161
+ "build": "tsc -p tsconfig.json",
162
+ "dev": "tsc -p tsconfig.json --watch"
163
163
  }
164
- }
164
+ }