strata-react 1.0.12 → 1.0.15

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/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import { C as readErrorBody, E as typeSteps, S as fieldErrorsOf, T as cn, _ as Textarea, a as toLoad, b as describeActionError, c as ColorSchemeChoice, d as useColorScheme, f as useSystemColorScheme, g as NativeSelect, h as Input, i as staleOf, l as ThemeProvider, m as Field, n as createQueryClient, o as useLoad, p as ChoiceGroup, r as fetchJson, s as COLOR_SCHEME_STORAGE_KEY, t as StrataQueryProvider, u as colorSchemeScript, v as useFieldControl, w as Tooltip, x as describeHttpError, y as HttpError } from "./query-CXlmWmrY.js";
1
+ import { C as describeHttpError, D as cn, E as Tooltip, O as typeSteps, S as describeActionError, T as readErrorBody, _ as NativeSelect, a as toLoad, b as controlHeight, c as ColorSchemeChoice, d as useColorScheme, f as useSystemColorScheme, g as Input, h as Field, i as staleOf, l as ThemeProvider, m as ChoiceGroup, n as createQueryClient, o as useLoad, p as Density, r as fetchJson, s as COLOR_SCHEME_STORAGE_KEY, t as StrataQueryProvider, u as colorSchemeScript, v as Textarea, w as fieldErrorsOf, x as HttpError, y as useFieldControl } from "./query-CIh1Dpgn.js";
2
2
  import * as React from "react";
3
3
  import { Autocomplete, Button as Button$1, Cell, Checkbox as Checkbox$1, Collection, Column, Dialog as Dialog$1, DialogTrigger, Disclosure as Disclosure$1, DisclosurePanel, DropIndicator, DropZone, FileTrigger, GridLayout, GridList, GridListItem, Header, Heading, I18nProvider, Input as Input$1, Keyboard, ListLayout, ListStateContext, Menu as Menu$1, MenuItem, MenuSection, MenuTrigger, Modal, ModalOverlay, NumberField as NumberField$1, Popover as Popover$1, Row, SearchField, Separator, Slider as Slider$1, SliderOutput, SliderThumb, SliderTrack, SubmenuTrigger, Switch as Switch$1, Tab, TabList, TabPanel, Table, TableBody, TableHeader, TableLayout, Tabs as Tabs$1, Text, ToggleButton, ToggleButtonGroup, Toolbar as Toolbar$1, UNSTABLE_Toast, UNSTABLE_ToastContent, UNSTABLE_ToastQueue, UNSTABLE_ToastRegion, Virtualizer, useDragAndDrop, useFilter } from "react-aria-components";
4
4
  import { cva } from "class-variance-authority";
5
5
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
- import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronRight, CircleAlert, CircleCheck, FileQuestion, GripVertical, History, ImageOff, Info, Loader, LoaderCircle, Maximize, Maximize2, Minimize, Minus, Pause, Play, RotateCcw, Scan, Search, SkipBack, SkipForward, Square, StepBack, StepForward, Trash2, TriangleAlert, Upload, Volume2, VolumeX, X, ZoomIn, ZoomOut } from "lucide-react";
6
+ import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronRight, CircleAlert, CircleCheck, FileQuestion, GripVertical, History, ImageOff, Info, Loader, LoaderCircle, Maximize, Maximize2, Minimize, Minus, Pause, Play, Redo2, RotateCcw, Scan, Search, SkipBack, SkipForward, Square, StepBack, StepForward, Trash2, TriangleAlert, Undo2, Upload, Volume2, VolumeX, X, ZoomIn, ZoomOut } from "lucide-react";
7
7
  import { Link, NavLink, useSearchParams } from "react-router";
8
8
  import { createSortedRowModel, flexRender, rowSortingFeature, tableFeatures, useTable } from "@tanstack/react-table";
9
9
  import { VisuallyHidden, mergeProps, useFocusRing, useSlider, useSliderThumb } from "react-aria";
@@ -233,7 +233,7 @@ function useInView({ active = true, rootMargin = "0px", once = false, unsupporte
233
233
  };
234
234
  }
235
235
  // src/components/button.tsx
236
- var buttonVariants = cva("inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control type-label transition-state press disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", {
236
+ var buttonVariants = cva("inline-flex max-w-full shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control type-label transition-state press disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", {
237
237
  variants: {
238
238
  variant: {
239
239
  default: "bg-primary text-primary-foreground hover:bg-primary-10",
@@ -246,7 +246,8 @@ var buttonVariants = cva("inline-flex shrink-0 cursor-pointer items-center justi
246
246
  size: {
247
247
  default: "h-(--control-h) px-4",
248
248
  sm: "h-(--control-h-sm) px-3",
249
- icon: "size-(--control-h)"
249
+ icon: "size-(--control-h)",
250
+ "icon-sm": "size-(--control-h-sm)"
250
251
  }
251
252
  },
252
253
  defaultVariants: {
@@ -260,7 +261,7 @@ var buttonVariants = cva("inline-flex shrink-0 cursor-pointer items-center justi
260
261
  * `outline`; ask for the filled accent (`variant="default"`) once per view. `type` defaults to `button`.
261
262
  * `onClick` and `disabled` are the DOM names and keep working; `onPress` is also accepted.
262
263
  */
263
- function Button({ className, variant, size, type = "button", disabled, ...props }) {
264
+ function Button({ className, variant, size, type = "button", disabled, children, ...props }) {
264
265
  return /* @__PURE__ */ jsx(Button$1, {
265
266
  type,
266
267
  isDisabled: disabled,
@@ -269,16 +270,20 @@ function Button({ className, variant, size, type = "button", disabled, ...props
269
270
  variant,
270
271
  size
271
272
  }), className),
272
- ...props
273
+ ...props,
274
+ children: typeof children === "string" ? /* @__PURE__ */ jsx("span", {
275
+ className: "min-w-0 truncate",
276
+ children
277
+ }) : children
273
278
  });
274
279
  }
275
280
  /** An icon-only button. `label` is required and becomes the accessible name and the tooltip (hover and keyboard focus); `hint` adds a muted aside to it, such as a shortcut. */
276
- function IconButton({ icon: Icon, label, hint, variant = "ghost", ...props }) {
281
+ function IconButton({ icon: Icon, label, hint, variant = "ghost", size = "default", ...props }) {
277
282
  return /* @__PURE__ */ jsx(Tooltip, {
278
283
  label,
279
284
  hint,
280
285
  children: /* @__PURE__ */ jsx(Button, {
281
- size: "icon",
286
+ size: size === "sm" ? "icon-sm" : "icon",
282
287
  variant,
283
288
  "aria-label": label,
284
289
  ...props,
@@ -925,14 +930,47 @@ var sizes = {
925
930
  md: "max-w-lg",
926
931
  lg: "max-w-3xl"
927
932
  };
933
+ function Overlay({ trigger, open, onOpenChange, children }) {
934
+ if (trigger) return /* @__PURE__ */ jsxs(DialogTrigger, {
935
+ isOpen: open,
936
+ onOpenChange,
937
+ children: [trigger, children]
938
+ });
939
+ return /* @__PURE__ */ jsx(Driven, {
940
+ open,
941
+ onOpenChange,
942
+ children
943
+ });
944
+ }
945
+ function Driven({ open, onOpenChange, children }) {
946
+ const opener = React.useRef(null);
947
+ const wasOpen = React.useRef(false);
948
+ if (open && !wasOpen.current) opener.current = typeof document === "undefined" ? null : document.activeElement;
949
+ wasOpen.current = Boolean(open);
950
+ React.useEffect(() => {
951
+ if (!open) return;
952
+ return () => {
953
+ const back = opener.current;
954
+ opener.current = null;
955
+ requestAnimationFrame(() => {
956
+ if ((!document.activeElement || document.activeElement === document.body) && back instanceof HTMLElement && back.isConnected) back.focus();
957
+ });
958
+ };
959
+ }, [open]);
960
+ return React.cloneElement(children, {
961
+ isOpen: open,
962
+ onOpenChange
963
+ });
964
+ }
928
965
  var overlayClass = "layer-overlay fixed inset-0 grid overflow-hidden bg-foreground/40";
929
966
  /** A modal dialog with a required title; focus goes in and returns, Escape and a close control dismiss it. `placement="end"` makes it a sheet. */
930
967
  function Dialog({ title, description, trigger, open, onOpenChange, className, children, actions, hideTitle, closable = true, placement = "center", size = "md" }) {
931
968
  const descriptionId = React.useId();
932
- return /* @__PURE__ */ jsxs(DialogTrigger, {
933
- isOpen: open,
969
+ return /* @__PURE__ */ jsx(Overlay, {
970
+ trigger,
971
+ open,
934
972
  onOpenChange,
935
- children: [trigger, /* @__PURE__ */ jsx(ModalOverlay, {
973
+ children: /* @__PURE__ */ jsx(ModalOverlay, {
936
974
  isDismissable: closable,
937
975
  isKeyboardDismissDisabled: !closable,
938
976
  className: cn(overlayClass, placement === "end" ? "justify-items-end" : "place-items-center p-4"),
@@ -973,7 +1011,7 @@ function Dialog({ title, description, trigger, open, onOpenChange, className, ch
973
1011
  ] })
974
1012
  })
975
1013
  })
976
- })]
1014
+ })
977
1015
  });
978
1016
  }
979
1017
  /**
@@ -1006,10 +1044,11 @@ function AlertDialog({ title, description, trigger, open, onOpenChange, classNam
1006
1044
  setError(describeActionError(thrown) ?? "That did not go through. Nothing was confirmed; try again.");
1007
1045
  }
1008
1046
  };
1009
- return /* @__PURE__ */ jsxs(DialogTrigger, {
1010
- isOpen,
1047
+ return /* @__PURE__ */ jsx(Overlay, {
1048
+ trigger,
1049
+ open: isOpen,
1011
1050
  onOpenChange: change,
1012
- children: [trigger, /* @__PURE__ */ jsx(ModalOverlay, {
1051
+ children: /* @__PURE__ */ jsx(ModalOverlay, {
1013
1052
  isDismissable: false,
1014
1053
  isKeyboardDismissDisabled: busy,
1015
1054
  className: cn(overlayClass, "place-items-center p-4"),
@@ -1054,7 +1093,7 @@ function AlertDialog({ title, description, trigger, open, onOpenChange, classNam
1054
1093
  })] })
1055
1094
  })
1056
1095
  })
1057
- })]
1096
+ })
1058
1097
  });
1059
1098
  }
1060
1099
  // src/components/popover.tsx
@@ -1727,7 +1766,7 @@ function contrastRatio(a, b) {
1727
1766
  return (hi + .05) / (lo + .05);
1728
1767
  }
1729
1768
  // src/components/value-controls.tsx
1730
- var box = "flex h-(--control-h) w-full min-w-0 items-center rounded-control border border-input bg-background px-3 type-body text-foreground transition-state disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-70 has-[input:disabled]:cursor-not-allowed has-[input:disabled]:bg-muted has-[input:disabled]:opacity-70 aria-invalid:border-danger has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-offset-2 has-[input:focus-visible]:outline-ring";
1769
+ var box = "flex w-full min-w-0 items-center rounded-control border border-input bg-background px-3 type-body text-foreground transition-state disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-70 has-[input:disabled]:cursor-not-allowed has-[input:disabled]:bg-muted has-[input:disabled]:opacity-70 aria-invalid:border-danger has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-offset-2 has-[input:focus-visible]:outline-ring";
1731
1770
  /** A number with its unit joined by a non-breaking space; `%` and `°` stay attached. */
1732
1771
  function withUnit(text, unit) {
1733
1772
  if (!unit) return text;
@@ -1780,7 +1819,7 @@ function describeRange(min, max, show, unit) {
1780
1819
  return "Enter a number.";
1781
1820
  }
1782
1821
  /** A number with a unit on React Aria's number field: typed input is validated, not clamped, so an out-of-range value is explained in the surrounding `Field` and never passed on; empty stays `null`. */
1783
- function NumberField({ value, onChange, min, max, step = 1, places, unit, locale = format.locale, required = false, disabled, id: idProp, name, className, "aria-label": ariaLabel }) {
1822
+ function NumberField({ value, onChange, min, max, step = 1, places, unit, locale = format.locale, required = false, disabled, id: idProp, name, size = "default", className, "aria-label": ariaLabel }) {
1784
1823
  const { field, report } = useFieldControl();
1785
1824
  const digits = places ?? Math.max(decimalsOf(step), min === void 0 ? 0 : decimalsOf(min));
1786
1825
  const show = useNumberText(locale, digits);
@@ -1830,7 +1869,7 @@ function NumberField({ value, onChange, min, max, step = 1, places, unit, locale
1830
1869
  isInvalid: invalid || void 0,
1831
1870
  name,
1832
1871
  "aria-label": ariaLabel ?? field?.label,
1833
- className: cn(box, className),
1872
+ className: cn(box, controlHeight[size], className),
1834
1873
  children: [/* @__PURE__ */ jsx(Input$1, {
1835
1874
  id: idProp ?? field?.id,
1836
1875
  placeholder: format.missing,
@@ -1908,6 +1947,8 @@ function Slider({ value, onChange, min, max, step = 1, unit, locale = format.loc
1908
1947
  /** Choose a colour with the platform picker, see and type its hex value, pick from the app's suggestions, and get a note when it would be hard to see on `against`. A half-typed value is never passed on. */
1909
1948
  function ColorField({ value, onChange, suggestions, against, againstLabel = "the background", minContrast = 3, disabled, id: idProp, className, "aria-label": ariaLabel }) {
1910
1949
  const { field, report } = useFieldControl();
1950
+ const label = ariaLabel ?? field?.label;
1951
+ const pickerName = label ? `${label}, picker` : "Colour picker";
1911
1952
  const [draft, setDraft] = React.useState(null);
1912
1953
  const [own, setOwn] = React.useState(false);
1913
1954
  const text = draft ?? value ?? "";
@@ -1941,7 +1982,7 @@ function ColorField({ value, onChange, suggestions, against, againstLabel = "the
1941
1982
  className: cn("grid min-w-0 gap-2", className),
1942
1983
  children: [
1943
1984
  /* @__PURE__ */ jsxs("div", {
1944
- className: cn(box, "gap-2 px-2"),
1985
+ className: cn(box, controlHeight.default, "gap-2 px-2"),
1945
1986
  "aria-invalid": invalid || void 0,
1946
1987
  children: [/* @__PURE__ */ jsxs("span", {
1947
1988
  className: "relative size-6 shrink-0 overflow-hidden rounded-control border border-input",
@@ -1951,7 +1992,7 @@ function ColorField({ value, onChange, suggestions, against, againstLabel = "the
1951
1992
  style: value ? { background: value } : void 0
1952
1993
  }), /* @__PURE__ */ jsx("input", {
1953
1994
  type: "color",
1954
- "aria-label": ariaLabel ? `${ariaLabel}, picker` : "Colour picker",
1995
+ "aria-label": pickerName,
1955
1996
  value: value ?? "#000000",
1956
1997
  disabled,
1957
1998
  onChange: (e) => pick(e.target.value),
@@ -4459,7 +4500,7 @@ function Inspector({ title, kind, empty, selectionKey, storageKey, actions, summ
4459
4500
  "aria-label": title === null ? "Properties" : void 0,
4460
4501
  className: cn("min-w-0", className),
4461
4502
  children: title === null ? empty : /* @__PURE__ */ jsxs("div", {
4462
- className: "grid gap-4",
4503
+ className: "grid grid-cols-1 gap-4",
4463
4504
  children: [
4464
4505
  /* @__PURE__ */ jsxs("header", {
4465
4506
  className: "flex items-start gap-3",
@@ -4484,7 +4525,7 @@ function Inspector({ title, kind, empty, selectionKey, storageKey, actions, summ
4484
4525
  }),
4485
4526
  summary,
4486
4527
  /* @__PURE__ */ jsx("div", {
4487
- className: "grid",
4528
+ className: "grid grid-cols-1 *:min-w-0",
4488
4529
  children
4489
4530
  }, selectionKey)
4490
4531
  ]
@@ -4523,7 +4564,7 @@ function InspectorSection({ id, title, defaultOpen = true, actions, children, cl
4523
4564
  children: actions
4524
4565
  })]
4525
4566
  }), /* @__PURE__ */ jsx(DisclosurePanel, { children: isExpanded && /* @__PURE__ */ jsx("div", {
4526
- className: "grid gap-4 pt-2 pb-4 pl-6",
4567
+ className: "grid grid-cols-1 gap-4 pt-2 pb-4 pl-6 *:min-w-0",
4527
4568
  children
4528
4569
  }) })] })
4529
4570
  });
@@ -7013,6 +7054,348 @@ function CompareGrid({ label, items, blind, missing, actions, columns = 3, keys
7013
7054
  })
7014
7055
  });
7015
7056
  }
7016
- export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareGrid, CompositionBar, ContextMenu, DEFAULT_TOLERANCE, DataTable, DataView, Dialog, Disclosure, Done, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, Inspector, InspectorSection, JobStatus, KeysLegend, LineChart, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, MediaStage, Menu, Meter, Metric, MetricStrip, MissingFile, NBSP, NativeSelect, NumberField, PageHeader, Popover, PropertyList, PropertyRow, RateChoice, RowAction, SeekBar, SelectableGrid, SideNav, Skeleton, Slider, SortableList, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, Transport, UndoBar, ViewportFrame, VirtualList, VolumeControl, actualPixelsScale, buttonVariants, canFullscreen, clampViewport, cn, colorSchemeScript, commandShortcut, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, detectPlatform, differences, fetchJson, fieldErrorsOf, format, formatChord, isReservedChord, isTypingTarget, labelOf, matchesAccept, matchesChord, noOverlap, parseChord, parseSort, readErrorBody, readPixels, resample, serialiseSort, staleOf, tickLabel, tickStep, ticksBetween, toDate, toLoad, toast, toastTimeout, transportShortcuts, typeSteps, useActiveItem, useAsyncAction, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHotkeys, useInView, useInfiniteLoad, useJob, useLoad, useSelection, useSystemColorScheme, useTimelineZoom, useUndoable, useViewport, zoomAt };
7057
+ // src/components/history.tsx
7058
+ var compose = (older, newer) => ({
7059
+ label: older.label,
7060
+ key: older.key,
7061
+ undo: () => {
7062
+ newer.undo();
7063
+ older.undo();
7064
+ },
7065
+ redo: () => {
7066
+ older.redo();
7067
+ newer.redo();
7068
+ }
7069
+ });
7070
+ /** A history of named, undoable steps with grouping, a limit, and Undo and Redo as commands. */
7071
+ function useHistory({ limit = 100 } = {}) {
7072
+ const store = React.useRef({
7073
+ past: [],
7074
+ future: [],
7075
+ open: [],
7076
+ merge: false
7077
+ });
7078
+ const [version, bump] = React.useReducer((n) => n + 1, 0);
7079
+ const max = Math.max(1, limit);
7080
+ const api = React.useMemo(() => {
7081
+ const s = store.current;
7082
+ const record = (step) => {
7083
+ const last = s.past[s.past.length - 1];
7084
+ if (s.merge && step.key && last && last.key === step.key) s.past[s.past.length - 1] = compose(last, step);
7085
+ else {
7086
+ s.past.push(step);
7087
+ if (s.past.length > max) s.past.splice(0, s.past.length - max);
7088
+ }
7089
+ s.future = [];
7090
+ s.merge = Boolean(step.key);
7091
+ bump();
7092
+ };
7093
+ const push = (step) => {
7094
+ const group = s.open[s.open.length - 1];
7095
+ if (group) group.push(step);
7096
+ else record(step);
7097
+ };
7098
+ const begin = (label) => {
7099
+ const steps = [];
7100
+ s.open.push(steps);
7101
+ let ended = false;
7102
+ return () => {
7103
+ if (ended) return;
7104
+ ended = true;
7105
+ s.open.pop();
7106
+ if (!steps.length) return;
7107
+ push({
7108
+ label,
7109
+ undo: () => [...steps].reverse().forEach((x) => x.undo()),
7110
+ redo: () => steps.forEach((x) => x.redo())
7111
+ });
7112
+ };
7113
+ };
7114
+ return {
7115
+ push,
7116
+ begin,
7117
+ group: (label, run) => {
7118
+ const end = begin(label);
7119
+ try {
7120
+ return run();
7121
+ } finally {
7122
+ end();
7123
+ }
7124
+ },
7125
+ undo: () => {
7126
+ if (s.open.length) return;
7127
+ const step = s.past.pop();
7128
+ if (!step) return;
7129
+ step.undo();
7130
+ s.future.unshift(step);
7131
+ s.merge = false;
7132
+ bump();
7133
+ },
7134
+ redo: () => {
7135
+ if (s.open.length) return;
7136
+ const step = s.future.shift();
7137
+ if (!step) return;
7138
+ step.redo();
7139
+ s.past.push(step);
7140
+ s.merge = false;
7141
+ bump();
7142
+ },
7143
+ clear: () => {
7144
+ s.past = [];
7145
+ s.future = [];
7146
+ s.merge = false;
7147
+ bump();
7148
+ }
7149
+ };
7150
+ }, [max]);
7151
+ return React.useMemo(() => {
7152
+ const { past, future } = store.current;
7153
+ const undoLabel = past[past.length - 1]?.label;
7154
+ const redoLabel = future[0]?.label;
7155
+ const commands = [{
7156
+ id: "history.undo",
7157
+ label: undoLabel ? `Undo ${undoLabel}` : "Undo",
7158
+ icon: Undo2,
7159
+ keys: ["Mod+Z"],
7160
+ disabled: undoLabel ? false : "Nothing to undo",
7161
+ run: api.undo
7162
+ }, {
7163
+ id: "history.redo",
7164
+ label: redoLabel ? `Redo ${redoLabel}` : "Redo",
7165
+ icon: Redo2,
7166
+ keys: ["Mod+Shift+Z", "Mod+Y"],
7167
+ disabled: redoLabel ? false : "Nothing to redo",
7168
+ run: api.redo
7169
+ }];
7170
+ return {
7171
+ ...api,
7172
+ canUndo: past.length > 0,
7173
+ canRedo: future.length > 0,
7174
+ undoLabel,
7175
+ redoLabel,
7176
+ past: past.map((x) => x.label),
7177
+ future: future.map((x) => x.label),
7178
+ atLimit: past.length >= max,
7179
+ commands
7180
+ };
7181
+ }, [
7182
+ api,
7183
+ version,
7184
+ max
7185
+ ]);
7186
+ }
7187
+ /**
7188
+ * React state with a history: `set(next, "move clip")` changes the value and records the step; Undo
7189
+ * and Redo put the old and new values back. For an app whose document is a plain value. An app on its
7190
+ * own store uses `useHistory` and pushes steps from its actions.
7191
+ */
7192
+ function useHistoryState(initial, options) {
7193
+ const [value, setValue] = React.useState(initial);
7194
+ const latest = React.useRef(value);
7195
+ const history = useHistory(options);
7196
+ const { push } = history;
7197
+ const write = React.useCallback((next) => {
7198
+ latest.current = next;
7199
+ setValue(next);
7200
+ }, []);
7201
+ return {
7202
+ value,
7203
+ set: React.useCallback((next, label, { key } = {}) => {
7204
+ const before = latest.current;
7205
+ const after = typeof next === "function" ? next(before) : next;
7206
+ if (Object.is(before, after)) return;
7207
+ write(after);
7208
+ push({
7209
+ label,
7210
+ key,
7211
+ undo: () => write(before),
7212
+ redo: () => write(after)
7213
+ });
7214
+ }, [push, write]),
7215
+ reset: React.useCallback((next) => {
7216
+ write(next);
7217
+ history.clear();
7218
+ }, [write, history.clear]),
7219
+ history
7220
+ };
7221
+ }
7222
+ // src/components/save.tsx
7223
+ /** Saves `value` after changes settle, never two at once, and says where it stands. The document's first `value` counts as saved. */
7224
+ function useAutoSave({ value, save, delayMs = 1500, equals = Object.is, describeError = describeActionError }) {
7225
+ const [state, setState] = React.useState({
7226
+ status: "saved",
7227
+ at: null
7228
+ });
7229
+ const latest = React.useRef({
7230
+ value,
7231
+ save,
7232
+ equals,
7233
+ describeError,
7234
+ delayMs
7235
+ });
7236
+ latest.current = {
7237
+ value,
7238
+ save,
7239
+ equals,
7240
+ describeError,
7241
+ delayMs
7242
+ };
7243
+ const saved = React.useRef(value);
7244
+ const savedAt = React.useRef(null);
7245
+ const running = React.useRef(null);
7246
+ const timer = React.useRef(void 0);
7247
+ const mounted = React.useRef(true);
7248
+ React.useEffect(() => {
7249
+ mounted.current = true;
7250
+ return () => {
7251
+ mounted.current = false;
7252
+ window.clearTimeout(timer.current);
7253
+ };
7254
+ }, []);
7255
+ const schedule = React.useCallback(() => {
7256
+ window.clearTimeout(timer.current);
7257
+ if (latest.current.delayMs === null) return;
7258
+ timer.current = window.setTimeout(() => void run(), latest.current.delayMs);
7259
+ }, []);
7260
+ const run = React.useCallback(() => {
7261
+ window.clearTimeout(timer.current);
7262
+ if (running.current) return running.current;
7263
+ const current = latest.current.value;
7264
+ if (latest.current.equals(current, saved.current)) {
7265
+ setState((s) => s.status === "saved" ? s : {
7266
+ status: "saved",
7267
+ at: /* @__PURE__ */ new Date()
7268
+ });
7269
+ return Promise.resolve();
7270
+ }
7271
+ setState({ status: "saving" });
7272
+ let settled = false;
7273
+ const attempt = (async () => {
7274
+ try {
7275
+ await latest.current.save(current);
7276
+ saved.current = current;
7277
+ savedAt.current = /* @__PURE__ */ new Date();
7278
+ if (!mounted.current) return;
7279
+ if (latest.current.equals(latest.current.value, current)) setState({
7280
+ status: "saved",
7281
+ at: savedAt.current
7282
+ });
7283
+ else {
7284
+ setState({ status: "dirty" });
7285
+ schedule();
7286
+ }
7287
+ } catch (error) {
7288
+ if (mounted.current) setState({
7289
+ status: "failed",
7290
+ reason: latest.current.describeError(error)
7291
+ });
7292
+ } finally {
7293
+ settled = true;
7294
+ running.current = null;
7295
+ }
7296
+ })();
7297
+ if (!settled) running.current = attempt;
7298
+ return attempt;
7299
+ }, [schedule]);
7300
+ React.useEffect(() => {
7301
+ if (latest.current.equals(value, saved.current)) {
7302
+ if (!running.current) {
7303
+ window.clearTimeout(timer.current);
7304
+ setState((s) => s.status === "dirty" || s.status === "failed" ? {
7305
+ status: "saved",
7306
+ at: savedAt.current
7307
+ } : s);
7308
+ }
7309
+ return;
7310
+ }
7311
+ if (!running.current) setState((s) => s.status === "failed" ? s : { status: "dirty" });
7312
+ if (!running.current) schedule();
7313
+ }, [value, schedule]);
7314
+ return {
7315
+ state,
7316
+ saveNow: run
7317
+ };
7318
+ }
7319
+ /** Asks the browser to confirm before the page is closed or reloaded, while `active`. Off when there is nothing to lose. */
7320
+ function useLeaveGuard(active) {
7321
+ React.useEffect(() => {
7322
+ if (!active) return;
7323
+ const onBeforeUnload = (e) => {
7324
+ e.preventDefault();
7325
+ e.returnValue = "";
7326
+ };
7327
+ window.addEventListener("beforeunload", onBeforeUnload);
7328
+ return () => window.removeEventListener("beforeunload", onBeforeUnload);
7329
+ }, [active]);
7330
+ }
7331
+ var labelOf$1 = (s) => s.status === "saved" ? s.at ? `Saved ${format.clock(s.at)}` : "Saved" : s.status === "saving" ? "Saving…" : s.status === "dirty" ? "Unsaved changes" : "Not saved";
7332
+ /**
7333
+ * The sign of whether the work is safe: "Saved 10:42", "Saving…", "Unsaved changes", or "Not saved"
7334
+ * with the reason and "Try again". Fixed width, so it never moves what is beside it. Announces a
7335
+ * failure, and the recovery from one, politely; a routine save is silent.
7336
+ */
7337
+ function SaveStatus({ state, onRetry, className }) {
7338
+ const lastFailure = React.useRef(false);
7339
+ const failed = state.status === "failed";
7340
+ let announcement = "";
7341
+ if (failed) announcement = `Not saved${state.reason ? `: ${state.reason}` : "."} Your changes are still here.`;
7342
+ else if (lastFailure.current && state.status === "saved") announcement = "Saved.";
7343
+ React.useEffect(() => {
7344
+ if (failed) lastFailure.current = true;
7345
+ else if (state.status === "saved") lastFailure.current = false;
7346
+ }, [failed, state.status]);
7347
+ const Icon = {
7348
+ saved: Check,
7349
+ saving: LoaderCircle,
7350
+ dirty: null,
7351
+ failed: CircleAlert
7352
+ }[state.status];
7353
+ const current = labelOf$1(state);
7354
+ const all = [
7355
+ "Saved 00:00",
7356
+ "Saving…",
7357
+ "Unsaved changes",
7358
+ "Not saved"
7359
+ ];
7360
+ const shown = failed && state.reason ? `Not saved: ${state.reason}` : current;
7361
+ return /* @__PURE__ */ jsxs("span", {
7362
+ "data-status": state.status,
7363
+ title: failed ? shown : void 0,
7364
+ className: cn("inline-flex w-72 items-center justify-end gap-2 type-body-sm", failed ? "text-danger" : "text-muted-foreground", className),
7365
+ children: [
7366
+ Icon && /* @__PURE__ */ jsx(Icon, {
7367
+ "aria-hidden": true,
7368
+ className: cn("size-4 shrink-0", state.status === "saving" && "motion-safe:animate-spin")
7369
+ }),
7370
+ failed ? /* @__PURE__ */ jsx("span", {
7371
+ className: "min-w-0 truncate",
7372
+ children: shown
7373
+ }) : /* @__PURE__ */ jsx("span", {
7374
+ className: "grid",
7375
+ children: all.map((l) => {
7376
+ const active = l === current || l === "Saved 00:00" && state.status === "saved";
7377
+ return /* @__PURE__ */ jsx("span", {
7378
+ "aria-hidden": !active,
7379
+ className: active ? "[grid-area:1/1] text-end tabular-nums" : "invisible [grid-area:1/1] text-end",
7380
+ children: active ? current : l
7381
+ }, l);
7382
+ })
7383
+ }),
7384
+ failed && /* @__PURE__ */ jsx(Button, {
7385
+ size: "sm",
7386
+ variant: "ghost",
7387
+ onClick: onRetry,
7388
+ className: "shrink-0",
7389
+ children: "Try again"
7390
+ }),
7391
+ /* @__PURE__ */ jsx("span", {
7392
+ role: "status",
7393
+ className: "sr-only",
7394
+ children: announcement
7395
+ })
7396
+ ]
7397
+ });
7398
+ }
7399
+ export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareGrid, CompositionBar, ContextMenu, DEFAULT_TOLERANCE, DataTable, DataView, Density, Dialog, Disclosure, Done, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, Inspector, InspectorSection, JobStatus, KeysLegend, LineChart, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, MediaStage, Menu, Meter, Metric, MetricStrip, MissingFile, NBSP, NativeSelect, NumberField, PageHeader, Popover, PropertyList, PropertyRow, RateChoice, RowAction, SaveStatus, SeekBar, SelectableGrid, SideNav, Skeleton, Slider, SortableList, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, Transport, UndoBar, ViewportFrame, VirtualList, VolumeControl, actualPixelsScale, buttonVariants, canFullscreen, clampViewport, cn, colorSchemeScript, commandShortcut, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, detectPlatform, differences, fetchJson, fieldErrorsOf, format, formatChord, isReservedChord, isTypingTarget, labelOf, matchesAccept, matchesChord, noOverlap, parseChord, parseSort, readErrorBody, readPixels, resample, serialiseSort, staleOf, tickLabel, tickStep, ticksBetween, toDate, toLoad, toast, toastTimeout, transportShortcuts, typeSteps, useActiveItem, useAsyncAction, useAutoSave, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useLeaveGuard, useLoad, useSelection, useSystemColorScheme, useTimelineZoom, useUndoable, useViewport, zoomAt };
7017
7400
 
7018
7401
  //# sourceMappingURL=index.js.map