@stll/ui 0.89.1 → 0.90.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.
Files changed (57) hide show
  1. package/dist/calendar/day-calendar.d.ts +11 -0
  2. package/dist/calendar/day-calendar.js +9 -3
  3. package/dist/components/composer-frame.d.ts +22 -0
  4. package/dist/components/composer-frame.js +139 -0
  5. package/dist/components/composer-frame.native.d.ts +29 -0
  6. package/dist/components/composer-frame.native.js +105 -0
  7. package/dist/components/composer-frame.shared.d.ts +50 -0
  8. package/dist/components/composer-frame.shared.js +0 -0
  9. package/dist/components/composer-layout.d.ts +35 -0
  10. package/dist/components/composer-layout.js +52 -0
  11. package/dist/components/composer-tokens.d.ts +24 -44
  12. package/dist/components/composer-tokens.js +25 -45
  13. package/dist/components/composer.d.ts +2 -15
  14. package/dist/components/composer.js +2 -17
  15. package/dist/components/control-face.js +1 -1
  16. package/dist/components/details-grid.js +7 -3
  17. package/dist/components/dialog-form-state.js +4 -3
  18. package/dist/components/entity-actions.d.ts +33 -1
  19. package/dist/components/entity-actions.js +47 -23
  20. package/dist/components/hex-color-picker.js +1 -1
  21. package/dist/components/landing-shell.d.ts +3 -3
  22. package/dist/components/landing-shell.js +20 -27
  23. package/dist/components/menu.d.ts +7 -1
  24. package/dist/components/menu.js +8 -3
  25. package/dist/components/outcome-screen.js +1 -1
  26. package/dist/components/outline-rail.js +13 -12
  27. package/dist/components/select.js +1 -1
  28. package/dist/components/settings.d.ts +6 -0
  29. package/dist/components/settings.js +14 -3
  30. package/dist/components/sheet.native.js +3 -3
  31. package/dist/components/sidebar.js +15 -7
  32. package/dist/components/switch.js +2 -2
  33. package/dist/components/switch.native.d.ts +2 -1
  34. package/dist/components/switch.native.js +6 -5
  35. package/dist/components/textarea.d.ts +5 -1
  36. package/dist/components/textarea.js +2 -2
  37. package/dist/components/textarea.native.d.ts +6 -3
  38. package/dist/components/textarea.native.js +27 -8
  39. package/dist/components/textarea.shared.d.ts +8 -1
  40. package/dist/components/toggle-classes.d.ts +9 -2
  41. package/dist/components/toggle-classes.js +10 -3
  42. package/dist/data-table/schema.js +1 -5
  43. package/dist/effects/dom.d.ts +53 -0
  44. package/dist/effects/dom.js +177 -0
  45. package/dist/effects/effects.d.ts +88 -0
  46. package/dist/effects/effects.js +196 -0
  47. package/dist/hooks/use-inline-overflow.d.ts +2 -2
  48. package/dist/hooks/use-inline-overflow.js +12 -15
  49. package/dist/hooks/use-latest.d.ts +2 -19
  50. package/dist/hooks/use-latest.js +1 -27
  51. package/dist/icons.d.ts +2 -2
  52. package/dist/icons.js +2 -2
  53. package/dist/index.d.ts +1 -1
  54. package/dist/index.js +2 -2
  55. package/dist/lib/slot.js +7 -3
  56. package/dist/styles/theme.css +29 -0
  57. package/package.json +17 -1
@@ -34,10 +34,19 @@ const ROW_DEPTH_CLASS = {
34
34
  nested: "ps-10",
35
35
  top: "ps-4"
36
36
  };
37
+ /**
38
+ * Where a row's footer starts when the row has media: at its title's edge,
39
+ * past the 32px tile and the row's 12px gap, so every line of the row's
40
+ * text shares one start edge.
41
+ */
42
+ const FOOTER_PAST_MEDIA_CLASS = {
43
+ nested: "ps-21",
44
+ top: "ps-15"
45
+ };
37
46
  const SETTINGS_ROW_BOX_CLASS = "flex min-h-14 w-full flex-wrap items-center gap-x-3 gap-y-2 py-2.5 pe-4 text-start";
38
47
  /** One option: media, title and secondary line, then its control. */
39
48
  const SettingsRow = (props) => {
40
- const { children, depth = "top", description, disabled = false, footer, id, media, title } = props;
49
+ const { children, depth = "top", description, disabled = false, footer, id, media, target, title } = props;
41
50
  const ids = id === void 0 ? void 0 : settingsRowIds(id);
42
51
  const controlId = props.interaction === "label" ? settingsRowIds(props.id).control : null;
43
52
  const text = /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
@@ -55,9 +64,11 @@ const SettingsRow = (props) => {
55
64
  })] });
56
65
  const textClass = cn("flex min-w-48 flex-1 basis-48 flex-col justify-center gap-0.5 self-stretch", disabled && "opacity-64");
57
66
  return /* @__PURE__ */ jsxs("li", {
58
- className: "flex min-w-0 flex-col",
67
+ className: "data-highlighted:bg-muted flex min-w-0 flex-col outline-none",
59
68
  "data-disabled": disabled ? "" : void 0,
69
+ "data-settings-target": target,
60
70
  "data-slot": "settings-row",
71
+ tabIndex: target === void 0 ? void 0 : -1,
61
72
  children: [/* @__PURE__ */ jsxs("div", {
62
73
  className: cn(SETTINGS_ROW_BOX_CLASS, ROW_DEPTH_CLASS[depth], controlId !== null && "has-[label:hover]:bg-muted/50 has-data-disabled:has-[label:hover]:bg-transparent"),
63
74
  children: [
@@ -77,7 +88,7 @@ const SettingsRow = (props) => {
77
88
  })
78
89
  ]
79
90
  }), rendersSomething(footer) && /* @__PURE__ */ jsx("div", {
80
- className: cn("pe-4 pb-3 empty:hidden", ROW_DEPTH_CLASS[depth]),
91
+ className: cn("pe-4 pb-3 empty:hidden", rendersSomething(media) ? FOOTER_PAST_MEDIA_CLASS[depth] : ROW_DEPTH_CLASS[depth]),
81
92
  children: footer
82
93
  })]
83
94
  });
@@ -2,7 +2,7 @@ import { cn } from "../lib/utils.js";
2
2
  import { Button } from "./button.native.js";
3
3
  import { Text as Text$1 } from "./text.native.js";
4
4
  import { jsx } from "react/jsx-runtime";
5
- import { createContext, use } from "react";
5
+ import { createContext, use, useCallback } from "react";
6
6
  import { KeyboardAvoidingView, Modal, Platform, ScrollView, View } from "react-native";
7
7
  // src/components/sheet.native.tsx
8
8
  /** Closes the sheet that holds it; nothing outside a sheet. */
@@ -13,9 +13,9 @@ const SheetCloseContext = createContext(() => void 0);
13
13
  * to close it through `onOpenChange(false)`, as Escape does on the web.
14
14
  */
15
15
  const Sheet = ({ children, onOpenChange, open = false }) => {
16
- const close = () => {
16
+ const close = useCallback(() => {
17
17
  onOpenChange?.(false);
18
- };
18
+ }, [onOpenChange]);
19
19
  return /* @__PURE__ */ jsx(Modal, {
20
20
  animationType: "slide",
21
21
  onRequestClose: close,
@@ -11,7 +11,7 @@ import { deriveSidebarState, nextOpenMobile, nextRequestedOpen, resolveSidebarLa
11
11
  import { Skeleton } from "./skeleton.js";
12
12
  import { Tooltip, TooltipContent as TooltipPopup, TooltipTrigger } from "./tooltip.js";
13
13
  import { jsx, jsxs } from "react/jsx-runtime";
14
- import { createContext, use, useId, useState } from "react";
14
+ import { createContext, use, useCallback, useId, useMemo, useState } from "react";
15
15
  import { mergeProps } from "@base-ui/react/merge-props";
16
16
  import { useRender } from "@base-ui/react/use-render";
17
17
  import { panic } from "better-result";
@@ -74,21 +74,29 @@ const SidebarProvider = ({ defaultOpen, forceCollapsed = false, open: openProp,
74
74
  forceCollapsed,
75
75
  requestedOpen
76
76
  });
77
- const setOpen = (value) => {
77
+ const setOpen = useCallback((value) => {
78
78
  const openState = typeof value === "function" ? value(requestedOpen) : value;
79
79
  if (setOpenProp) setOpenProp(openState);
80
80
  else setUncontrolledOpen(openState);
81
- };
82
- const toggleSidebar = () => isMobile ? setOpenMobile(nextOpenMobile) : setOpen(nextRequestedOpen);
83
- const contextValue = {
84
- state: deriveSidebarState(open),
81
+ }, [requestedOpen, setOpenProp]);
82
+ const toggleSidebar = useCallback(() => isMobile ? setOpenMobile(nextOpenMobile) : setOpen(nextRequestedOpen), [isMobile, setOpen]);
83
+ const state = deriveSidebarState(open);
84
+ const contextValue = useMemo(() => ({
85
+ state,
85
86
  open,
86
87
  setOpen,
87
88
  isMobile,
88
89
  openMobile,
89
90
  setOpenMobile,
90
91
  toggleSidebar
91
- };
92
+ }), [
93
+ state,
94
+ open,
95
+ setOpen,
96
+ isMobile,
97
+ openMobile,
98
+ toggleSidebar
99
+ ]);
92
100
  const wrapperStyle = {
93
101
  "--sidebar-width": SIDEBAR_WIDTH,
94
102
  "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { cn } from "../lib/utils.js";
3
- import { SWITCH_ROOT_CLASS_NAME, SWITCH_ROOT_SIZE_CLASS_NAME } from "./toggle-classes.js";
3
+ import { SWITCH_ROOT_CLASS_NAME, SWITCH_ROOT_SIZE_CLASS_NAME, SWITCH_THUMB_CLASS_NAME } from "./toggle-classes.js";
4
4
  import { renderTooltipTrigger } from "./tooltip-trigger-helper.js";
5
5
  import { jsx, jsxs } from "react/jsx-runtime";
6
6
  import { useId } from "react";
@@ -18,7 +18,7 @@ const Switch = ({ className, disabled, disabledReason, size = "default", ...prop
18
18
  disabled,
19
19
  ...props,
20
20
  children: /* @__PURE__ */ jsx(Switch$1.Thumb, {
21
- className: cn("bg-background pointer-events-none block rounded-full shadow-xs transition-transform", SWITCH_THUMB_SIZE_CLASS_NAME[size]),
21
+ className: cn(SWITCH_THUMB_CLASS_NAME, SWITCH_THUMB_SIZE_CLASS_NAME[size]),
22
22
  "data-slot": "switch-thumb"
23
23
  })
24
24
  });
@@ -3,7 +3,8 @@ import { SwitchProps as SwitchProps$1 } from "react-native";
3
3
  type SwitchProps = Omit<SwitchProps$1, "value" | "onValueChange" | "disabled" | keyof SwitchContract> & SwitchContract;
4
4
  /**
5
5
  * The web's `Switch` (./switch.tsx) on a phone: the platform's own switch, in
6
- * the web's colours (the primary fill when on, the input fill when off).
6
+ * the web's colours (the green track when on, the grey one when off, a
7
+ * white thumb on both).
7
8
  * Controlled through `checked`, or holding its own state from
8
9
  * `defaultChecked`.
9
10
  */
@@ -4,7 +4,8 @@ import { Switch as Switch$1 } from "react-native";
4
4
  // src/components/switch.native.tsx
5
5
  /**
6
6
  * The web's `Switch` (./switch.tsx) on a phone: the platform's own switch, in
7
- * the web's colours (the primary fill when on, the input fill when off).
7
+ * the web's colours (the green track when on, the grey one when off, a
8
+ * white thumb on both).
8
9
  * Controlled through `checked`, or holding its own state from
9
10
  * `defaultChecked`.
10
11
  */
@@ -18,14 +19,14 @@ const Switch = ({ checked, defaultChecked = false, disabled = false, onCheckedCh
18
19
  disabled
19
20
  },
20
21
  disabled,
21
- ios_backgroundColorClassName: "accent-input",
22
+ ios_backgroundColorClassName: "accent-switch-track",
22
23
  onValueChange: (next) => {
23
24
  setOwn(next);
24
25
  onCheckedChange?.(next);
25
26
  },
26
- thumbColorClassName: "accent-background",
27
- trackColorOffClassName: "accent-input",
28
- trackColorOnClassName: "accent-primary",
27
+ thumbColorClassName: "accent-switch-thumb",
28
+ trackColorOffClassName: "accent-switch-track",
29
+ trackColorOnClassName: "accent-switch-track-checked",
29
30
  value
30
31
  });
31
32
  };
@@ -2,7 +2,11 @@ import * as React from "react";
2
2
  import { ControlSize } from "../lib/control-size.js";
3
3
  type TextareaProps = React.ComponentProps<"textarea"> & {
4
4
  size?: ControlSize | number;
5
- /** A borderless editor inside the shared large composer text well. */
5
+ /**
6
+ * A borderless editor for the `text` slot of a `ComposerFrame`: it grows
7
+ * with what is typed, and the frame sets its height floor, caps it and
8
+ * scrolls it.
9
+ */
6
10
  appearance?: "default" | "composer";
7
11
  unstyled?: boolean;
8
12
  /**
@@ -2,7 +2,7 @@
2
2
  import { useContentDir } from "../hooks/use-content-dir.js";
3
3
  import { CONTROL_SIZE } from "../lib/control-size.js";
4
4
  import { cn } from "../lib/utils.js";
5
- import { COMPOSER_LARGE_EDITOR_CLASS, COMPOSER_TEXT_CLASS } from "./composer-tokens.js";
5
+ import { COMPOSER_TEXT_CLASS } from "./composer-tokens.js";
6
6
  import { INLINE_FIELD_CLASS_NAME } from "./input-control.js";
7
7
  import { jsx, jsxs } from "react/jsx-runtime";
8
8
  import { useState } from "react";
@@ -12,7 +12,7 @@ const Textarea = ({ className, id, name, disabled, value, defaultValue, size = C
12
12
  const controlSize = typeof size === "number" ? CONTROL_SIZE.default : size;
13
13
  const composer = appearance === "composer";
14
14
  const fieldEditorClass = inline ? cn(INLINE_FIELD_CLASS_NAME, "resize-none [--textarea-pb:0px] [--textarea-pt:0px]") : cn("w-full rounded-[inherit] px-[calc(--spacing(3)-1px)] outline-none", TEXTAREA_SIZE_CLASS_NAMES[controlSize], fieldSizing === "content" && TEXTAREA_FLOOR_CLASS_NAMES[controlSize]);
15
- const editorClass = composer ? cn("placeholder:text-foreground-placeholder block w-full resize-none bg-transparent outline-none [--textarea-pb:0px] [--textarea-pt:0px]", COMPOSER_TEXT_CLASS, COMPOSER_LARGE_EDITOR_CLASS) : fieldEditorClass;
15
+ const editorClass = composer ? cn("placeholder:text-foreground-placeholder block w-full resize-none bg-transparent outline-none [--textarea-pb:0px] [--textarea-pt:0px]", COMPOSER_TEXT_CLASS) : fieldEditorClass;
16
16
  const contentDir = useContentDir({
17
17
  dir,
18
18
  value,
@@ -1,8 +1,11 @@
1
1
  import { ComponentProps } from "react";
2
2
  import { NativeField } from "./input.native.js";
3
+ import { TextareaContract } from "./textarea.shared.js";
4
+ type TextareaProps = Omit<ComponentProps<typeof NativeField>, "box" | "multiline"> & Pick<TextareaContract, "appearance">;
3
5
  /**
4
6
  * The web's `Textarea` (./textarea.tsx) on a phone: text that wraps and grows,
5
- * in the web's box, or none for a field inside a container that draws one
6
- * (the composer).
7
+ * in the web's box, or none for a field inside a container that draws one.
8
+ * With the `composer` appearance it is a `ComposerFrame`'s text.
7
9
  */
8
- export declare const Textarea: ({ size, unstyled, ...props }: Omit<ComponentProps<typeof NativeField>, "box" | "multiline">) => import("react").JSX.Element;
10
+ export declare const Textarea: ({ appearance, size, style, unstyled, ...props }: TextareaProps) => import("react").JSX.Element;
11
+ export {};
@@ -1,3 +1,4 @@
1
+ import "./composer-tokens.js";
1
2
  import { NativeField } from "./input.native.js";
2
3
  import { jsx } from "react/jsx-runtime";
3
4
  // src/components/textarea.native.tsx
@@ -14,14 +15,32 @@ const UNSTYLED_BOX = {
14
15
  lg: "p-0"
15
16
  };
16
17
  /**
18
+ * The composer's text: no box, and it gives way to the frame's capped text
19
+ * region (`shrink`), where it scrolls itself, so the caret stays in view as
20
+ * the draft runs past the cap.
21
+ */
22
+ const COMPOSER_BOX = "shrink p-0";
23
+ /** The composer's one line, which `ComposerFrame` measures its text against. */
24
+ const COMPOSER_LINE_STYLE = { lineHeight: 24 };
25
+ /**
17
26
  * The web's `Textarea` (./textarea.tsx) on a phone: text that wraps and grows,
18
- * in the web's box, or none for a field inside a container that draws one
19
- * (the composer).
27
+ * in the web's box, or none for a field inside a container that draws one.
28
+ * With the `composer` appearance it is a `ComposerFrame`'s text.
20
29
  */
21
- const Textarea = ({ size = "default", unstyled = false, ...props }) => /* @__PURE__ */ jsx(NativeField, {
22
- ...props,
23
- box: unstyled ? UNSTYLED_BOX[size] : BOX[size],
24
- multiline: true,
25
- size
26
- });
30
+ const Textarea = ({ appearance = "default", size = "default", style, unstyled = false, ...props }) => {
31
+ if (appearance === "composer") return /* @__PURE__ */ jsx(NativeField, {
32
+ ...props,
33
+ box: COMPOSER_BOX,
34
+ multiline: true,
35
+ size,
36
+ style: [COMPOSER_LINE_STYLE, style]
37
+ });
38
+ return /* @__PURE__ */ jsx(NativeField, {
39
+ ...props,
40
+ box: unstyled ? UNSTYLED_BOX[size] : BOX[size],
41
+ multiline: true,
42
+ size,
43
+ style
44
+ });
45
+ };
27
46
  export { Textarea };
@@ -1,2 +1,9 @@
1
1
  import { TextFieldContract } from "./input.shared.js";
2
- export type TextareaContract = Omit<TextFieldContract, "onValueChange">;
2
+ export type TextareaContract = Omit<TextFieldContract, "onValueChange"> & {
3
+ /**
4
+ * `composer`: a borderless editor for the `text` slot of a
5
+ * `ComposerFrame`, in the composer's type. It grows with what is typed; the
6
+ * frame caps it and scrolls it.
7
+ */
8
+ appearance?: "default" | "composer";
9
+ };
@@ -5,8 +5,15 @@ export declare const CHECKBOX_CLASS_NAME = "border-input bg-background ring-ring
5
5
  * beside small type.
6
6
  */
7
7
  export type SwitchSize = "sm" | "default";
8
- /** The switch's track: its shape, colours and focus ring. */
9
- export declare const SWITCH_ROOT_CLASS_NAME = "focus-visible:ring-ring focus-visible:ring-offset-background data-checked:bg-primary data-unchecked:bg-input relative inline-flex shrink-0 items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-offset-1 data-disabled:opacity-64";
8
+ /**
9
+ * The switch's track: its shape, colours and focus ring. On is the green
10
+ * checked track, off the grey one; both stand 3:1 against the surface in
11
+ * every palette (`--switch-track*` in ../styles/theme.css), under a white
12
+ * thumb.
13
+ */
14
+ export declare const SWITCH_ROOT_CLASS_NAME = "focus-visible:ring-ring focus-visible:ring-offset-background data-checked:bg-switch-track-checked data-unchecked:bg-switch-track relative inline-flex shrink-0 items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-offset-1 data-disabled:opacity-64";
15
+ /** The switch's thumb: white on both tracks, in light and dark. */
16
+ export declare const SWITCH_THUMB_CLASS_NAME = "pointer-events-none block rounded-full bg-switch-thumb shadow-xs transition-transform";
10
17
  export declare const SWITCH_ROOT_SIZE_CLASS_NAME: {
11
18
  readonly default: "h-5 w-9";
12
19
  readonly sm: "h-4 w-7";
@@ -1,10 +1,17 @@
1
1
  // src/components/toggle-classes.ts
2
2
  /** The checkbox's box: its size, border, focus ring and states. */
3
3
  const CHECKBOX_CLASS_NAME = "border-input bg-background ring-ring focus-visible:ring-offset-background aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/48 dark:not-data-checked:bg-input/32 dark:aria-invalid:ring-destructive/24 relative inline-flex size-4.5 shrink-0 items-center justify-center rounded-sm border shadow-xs/5 outline-none not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-sm)-1px)] not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] focus-visible:ring-2 focus-visible:ring-offset-1 data-disabled:opacity-64 sm:size-4 dark:not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)] [[data-disabled],[data-checked],[aria-invalid]]:shadow-none";
4
- /** The switch's track: its shape, colours and focus ring. */
5
- const SWITCH_ROOT_CLASS_NAME = "focus-visible:ring-ring focus-visible:ring-offset-background data-checked:bg-primary data-unchecked:bg-input relative inline-flex shrink-0 items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-offset-1 data-disabled:opacity-64";
4
+ /**
5
+ * The switch's track: its shape, colours and focus ring. On is the green
6
+ * checked track, off the grey one; both stand 3:1 against the surface in
7
+ * every palette (`--switch-track*` in ../styles/theme.css), under a white
8
+ * thumb.
9
+ */
10
+ const SWITCH_ROOT_CLASS_NAME = "focus-visible:ring-ring focus-visible:ring-offset-background data-checked:bg-switch-track-checked data-unchecked:bg-switch-track relative inline-flex shrink-0 items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-offset-1 data-disabled:opacity-64";
11
+ /** The switch's thumb: white on both tracks, in light and dark. */
12
+ const SWITCH_THUMB_CLASS_NAME = "pointer-events-none block rounded-full bg-switch-thumb shadow-xs transition-transform";
6
13
  const SWITCH_ROOT_SIZE_CLASS_NAME = {
7
14
  default: "h-5 w-9",
8
15
  sm: "h-4 w-7"
9
16
  };
10
- export { CHECKBOX_CLASS_NAME, SWITCH_ROOT_CLASS_NAME, SWITCH_ROOT_SIZE_CLASS_NAME };
17
+ export { CHECKBOX_CLASS_NAME, SWITCH_ROOT_CLASS_NAME, SWITCH_ROOT_SIZE_CLASS_NAME, SWITCH_THUMB_CLASS_NAME };
@@ -17,11 +17,7 @@ const visibleColumnIds = (schema, hiddenColumnIds) => {
17
17
  return schema.columns.filter((column) => !column.capabilities.hide || !hidden.has(column.id)).map((column) => column.id);
18
18
  };
19
19
  /** The starting width of every column, keyed by id. */
20
- const tableColumnSizing = (schema) => {
21
- const sizing = {};
22
- for (const column of schema.columns) sizing[column.id] = column.size;
23
- return sizing;
24
- };
20
+ const tableColumnSizing = (schema) => Object.fromEntries(schema.columns.map((column) => [column.id, column.size]));
25
21
  /**
26
22
  * A duplicate column id silently drops a column: the table keys by id, so the
27
23
  * second declaration wins and the first disappears with no error anywhere.
@@ -0,0 +1,53 @@
1
+ import { DependencyList } from "react";
2
+ type Scalar = string | number | boolean | null | undefined;
3
+ /** A value the equality guard can always compare: a scalar or a flat record of scalars. */
4
+ export type Flat = Scalar | Readonly<Record<string, Scalar>>;
5
+ /** Equal scalars, or flat records with the same keys and equal values. */
6
+ export declare const flatEqual: (left: Flat, right: Flat) => boolean;
7
+ type OscillationBreaker = {
8
+ admit: (value: Flat) => boolean;
9
+ };
10
+ export declare const createOscillationBreaker: (now?: () => number) => OscillationBreaker;
11
+ /**
12
+ * Runs `observe(element, emit)` while `element` is non-null (from a layout
13
+ * effect, so a synchronous first emit lands before paint) and returns the
14
+ * last emitted value, or `fallback` while there is no element or nothing
15
+ * has been emitted for it. Pass the element held in state
16
+ * (`const [el, setEl] = useState<HTMLElement | null>(null)`, `ref={setEl}`)
17
+ * so a node that mounts later is observed too.
18
+ *
19
+ * `observe` is read at subscription time; it re-subscribes when `element`
20
+ * or `deps` change, never because `observe` is a new function.
21
+ */
22
+ export declare const useObservedValue: <E extends Element, T extends Flat>(element: E | null, observe: (element: E, emit: (value: T) => void) => () => void, deps: DependencyList, fallback: T) => T;
23
+ /**
24
+ * `measure(element)` before the first paint and again whenever the element
25
+ * resizes. `measure` must only read the DOM. Round fractional pixels when
26
+ * sub-pixel jitter is not meaningful to the caller. Resizes are those of the
27
+ * content box; `useElementSize` follows the border box.
28
+ */
29
+ export declare const useLayoutMeasurement: <E extends Element, T extends Flat>(element: E | null, measure: (element: E) => T, deps: DependencyList, fallback: T) => T;
30
+ type ElementSize = {
31
+ readonly width: number;
32
+ readonly height: number;
33
+ };
34
+ /** The element's rendered size in CSS pixels, or `null` without an element. */
35
+ export declare const useElementSize: (element: Element | null) => ElementSize | null;
36
+ type IntersectingOptions = {
37
+ readonly root?: Element | null;
38
+ readonly rootMargin?: string;
39
+ readonly threshold?: number;
40
+ /** Stop observing once the element has intersected. */
41
+ readonly once?: boolean;
42
+ };
43
+ /**
44
+ * Whether the element intersects its root. Without IntersectionObserver
45
+ * every element counts as intersecting.
46
+ */
47
+ export declare const useIntersecting: (element: Element | null, { root, rootMargin, threshold, once }?: IntersectingOptions) => boolean;
48
+ /**
49
+ * An object URL for `blob` while the component shows it, revoked when the
50
+ * last component holding it lets go. `undefined` without a blob.
51
+ */
52
+ export declare const useObjectUrl: (blob: Blob | null | undefined) => string | undefined;
53
+ export {};
@@ -0,0 +1,177 @@
1
+ import { useLatest } from "./effects.js";
2
+ import { useLayoutEffect, useState, useSyncExternalStore } from "react";
3
+ // src/effects/dom.ts
4
+ const isRecord = (value) => typeof value === "object" && value !== null;
5
+ /** Equal scalars, or flat records with the same keys and equal values. */
6
+ const flatEqual = (left, right) => {
7
+ if (Object.is(left, right)) return true;
8
+ if (!isRecord(left) || !isRecord(right)) return false;
9
+ const leftKeys = Object.keys(left);
10
+ return leftKeys.length === Object.keys(right).length && leftKeys.every((key) => Object.hasOwn(right, key) && Object.is(left[key], right[key]));
11
+ };
12
+ /** Consecutive alternating emits that count as layout feedback. */
13
+ const OSCILLATION_EMITS = 8;
14
+ /** The window those emits must fall inside. */
15
+ const OSCILLATION_WINDOW_MS = 400;
16
+ const createOscillationBreaker = (now = () => performance.now()) => {
17
+ const recent = [];
18
+ let latched = false;
19
+ return { admit: (value) => {
20
+ if (latched) return false;
21
+ recent.push({
22
+ value,
23
+ at: now()
24
+ });
25
+ if (recent.length > OSCILLATION_EMITS) recent.shift();
26
+ const first = recent.at(0);
27
+ const last = recent.at(-1);
28
+ if (recent.length === OSCILLATION_EMITS && first !== void 0 && last !== void 0 && last.at - first.at <= OSCILLATION_WINDOW_MS && recent.every((entry, index) => index < 2 || flatEqual(entry.value, recent[index - 2]?.value) && !flatEqual(entry.value, recent[index - 1]?.value))) {
29
+ latched = true;
30
+ globalThis.reportError(/* @__PURE__ */ new Error("[layout-oscillation] an observed value kept alternating between two values; holding the current one. The render it causes changes the measurement back: break the feedback (reserve the space, or measure an element the value does not resize)."));
31
+ return false;
32
+ }
33
+ return true;
34
+ } };
35
+ };
36
+ /**
37
+ * Runs `observe(element, emit)` while `element` is non-null (from a layout
38
+ * effect, so a synchronous first emit lands before paint) and returns the
39
+ * last emitted value, or `fallback` while there is no element or nothing
40
+ * has been emitted for it. Pass the element held in state
41
+ * (`const [el, setEl] = useState<HTMLElement | null>(null)`, `ref={setEl}`)
42
+ * so a node that mounts later is observed too.
43
+ *
44
+ * `observe` is read at subscription time; it re-subscribes when `element`
45
+ * or `deps` change, never because `observe` is a new function.
46
+ */
47
+ const useObservedValue = (element, observe, deps, fallback) => {
48
+ const [slot, setSlot] = useState({
49
+ element: null,
50
+ value: fallback
51
+ });
52
+ const latestObserve = useLatest(observe);
53
+ useLayoutEffect(() => {
54
+ if (element === null) return;
55
+ const breaker = createOscillationBreaker();
56
+ let admitted = null;
57
+ return latestObserve.current(element, (next) => {
58
+ if (admitted !== null && flatEqual(admitted.value, next)) return;
59
+ if (!breaker.admit(next)) return;
60
+ admitted = { value: next };
61
+ setSlot((current) => current.element === element && flatEqual(current.value, next) ? current : {
62
+ element,
63
+ value: next
64
+ });
65
+ });
66
+ }, [element, ...deps]);
67
+ return slot.element === element && element !== null ? slot.value : fallback;
68
+ };
69
+ /**
70
+ * `measure(element)` before the first paint and again whenever the element
71
+ * resizes. `measure` must only read the DOM. Round fractional pixels when
72
+ * sub-pixel jitter is not meaningful to the caller. Resizes are those of the
73
+ * content box; `useElementSize` follows the border box.
74
+ */
75
+ const useLayoutMeasurement = (element, measure, deps, fallback) => {
76
+ const latestMeasure = useLatest(measure);
77
+ return useObservedValue(element, (observed, emit) => {
78
+ emit(latestMeasure.current(observed));
79
+ if (typeof ResizeObserver === "undefined") return () => void 0;
80
+ const observer = new ResizeObserver(() => {
81
+ emit(latestMeasure.current(observed));
82
+ });
83
+ observer.observe(observed);
84
+ return () => {
85
+ observer.disconnect();
86
+ };
87
+ }, deps, fallback);
88
+ };
89
+ /** The element's rendered size in CSS pixels, or `null` without an element. */
90
+ const useElementSize = (element) => useObservedValue(element, (observed, emit) => {
91
+ const measure = () => {
92
+ const { width, height } = observed.getBoundingClientRect();
93
+ emit({
94
+ width,
95
+ height
96
+ });
97
+ };
98
+ measure();
99
+ if (typeof ResizeObserver === "undefined") return () => void 0;
100
+ const observer = new ResizeObserver(measure);
101
+ observer.observe(observed, { box: "border-box" });
102
+ return () => {
103
+ observer.disconnect();
104
+ };
105
+ }, [], null);
106
+ /**
107
+ * Whether the element intersects its root. Without IntersectionObserver
108
+ * every element counts as intersecting.
109
+ */
110
+ const useIntersecting = (element, { root = null, rootMargin, threshold, once = false } = {}) => useObservedValue(element, (observed, emit) => {
111
+ if (typeof IntersectionObserver === "undefined") {
112
+ emit(true);
113
+ return () => void 0;
114
+ }
115
+ const observer = new IntersectionObserver((entries) => {
116
+ const intersecting = once ? entries.some((entry) => entry.isIntersecting) : entries.at(-1)?.isIntersecting ?? false;
117
+ emit(intersecting);
118
+ if (intersecting && once) observer.disconnect();
119
+ }, {
120
+ root,
121
+ ...rootMargin === void 0 ? {} : { rootMargin },
122
+ ...threshold === void 0 ? {} : { threshold }
123
+ });
124
+ observer.observe(observed);
125
+ return () => {
126
+ observer.disconnect();
127
+ };
128
+ }, [
129
+ root,
130
+ rootMargin,
131
+ threshold,
132
+ once
133
+ ], false);
134
+ const objectUrls = /* @__PURE__ */ new WeakMap();
135
+ const createObjectUrlEntry = (blob) => {
136
+ const url = URL.createObjectURL(blob);
137
+ return {
138
+ url,
139
+ revoke: () => {
140
+ URL.revokeObjectURL(url);
141
+ },
142
+ holders: 0
143
+ };
144
+ };
145
+ const holdObjectUrl = (blob) => {
146
+ const entry = objectUrls.get(blob) ?? createObjectUrlEntry(blob);
147
+ entry.holders += 1;
148
+ objectUrls.set(blob, entry);
149
+ return () => {
150
+ entry.holders -= 1;
151
+ queueMicrotask(() => {
152
+ if (entry.holders === 0 && objectUrls.get(blob) === entry) {
153
+ objectUrls.delete(blob);
154
+ entry.revoke();
155
+ }
156
+ });
157
+ };
158
+ };
159
+ const NO_SUBSCRIPTION = () => () => void 0;
160
+ const objectUrlSubscriptions = /* @__PURE__ */ new WeakMap();
161
+ const subscribeObjectUrl = (blob) => {
162
+ const existing = objectUrlSubscriptions.get(blob);
163
+ if (existing) return existing;
164
+ const subscribe = (onChange) => {
165
+ const release = holdObjectUrl(blob);
166
+ onChange();
167
+ return release;
168
+ };
169
+ objectUrlSubscriptions.set(blob, subscribe);
170
+ return subscribe;
171
+ };
172
+ /**
173
+ * An object URL for `blob` while the component shows it, revoked when the
174
+ * last component holding it lets go. `undefined` without a blob.
175
+ */
176
+ const useObjectUrl = (blob) => useSyncExternalStore(blob ? subscribeObjectUrl(blob) : NO_SUBSCRIPTION, () => blob ? objectUrls.get(blob)?.url : void 0, () => void 0);
177
+ export { createOscillationBreaker, flatEqual, useElementSize, useIntersecting, useLayoutMeasurement, useObjectUrl, useObservedValue };
@@ -0,0 +1,88 @@
1
+ import { DependencyList, Dispatch, EffectCallback, RefObject, SetStateAction } from "react";
2
+ /**
3
+ * Setup/teardown synchronization with an external system, once per mount.
4
+ * Use for DOM imperatives (focus, scroll), third-party widget lifecycles,
5
+ * and browser-API subscriptions. To start fresh when an id changes, remount
6
+ * with a `key` instead of adding a dependency here.
7
+ */
8
+ export declare const useMountEffect: (effect: EffectCallback) => void;
9
+ /**
10
+ * Push a *changing* React value into an external system when it changes
11
+ * (e.g. an imperative editor's zoom or content). Every call must be an
12
+ * external-system sync — never derived state, an event relay, or data
13
+ * fetching.
14
+ */
15
+ export declare const useExternalSyncEffect: (effect: EffectCallback, deps: DependencyList) => void;
16
+ /**
17
+ * The layout twin of `useExternalSyncEffect`: a host write that must land
18
+ * before the browser paints (scroll anchoring, zoom, a class toggle, an
19
+ * animated value, registering with a registry other layout effects read).
20
+ * Never React state: a value measured from the DOM goes through
21
+ * `useLayoutMeasurement` (`@stll/ui/effects-dom`).
22
+ */
23
+ export declare const useLayoutSyncEffect: (effect: EffectCallback, deps: DependencyList) => void;
24
+ /** The mount-only layout twin: a registration or host write before paint. */
25
+ export declare const useMountLayoutEffect: (effect: EffectCallback) => void;
26
+ /**
27
+ * A ref that always holds the latest committed value, readable from
28
+ * event handlers, imperative bridges, and async paths without making
29
+ * them depend on the value.
30
+ *
31
+ * The write happens in a layout effect, so readers see the value of the
32
+ * last committed render. Never read the returned ref during render;
33
+ * derive render output from the value directly instead. Replaces
34
+ * hand-written render-body mirrors (`ref.current = value`), which
35
+ * `no-ref-mirror` bans.
36
+ */
37
+ export declare const useLatest: <T>(value: T) => RefObject<T>;
38
+ /**
39
+ * A function with one identity for the component's lifetime that always
40
+ * calls the latest committed `fn`. Hand it to systems outside React's
41
+ * render and effect lifecycle: query contexts, imperative editor bridges,
42
+ * external emitters, listeners registered by an effect.
43
+ *
44
+ * Never call it during render. It switches to the new `fn` on passive-effect
45
+ * timing: until the commit's passive effects run, it still calls the previous
46
+ * one. Layout timing would let a child's layout effect call a callback from
47
+ * a render that has not finished committing, which feeds loops in editors
48
+ * that call back synchronously.
49
+ */
50
+ export declare const useLatestCallback: <A extends unknown[], R>(fn: (...args: A) => R) => ((...args: A) => R);
51
+ /**
52
+ * Whether the component is mounted, for async continuations that must not
53
+ * act after it unmounts. Read it from callbacks, never during render.
54
+ */
55
+ export declare const useIsMounted: () => (() => boolean);
56
+ /**
57
+ * `false` on the first render, `true` from the render after mount: the one
58
+ * mount latch, for work that must not start before the component commits
59
+ * (a chrome query whose fetch could otherwise resolve on a fiber that has
60
+ * not mounted yet). It costs one extra render per mount and never more.
61
+ */
62
+ export declare const useHasMounted: () => boolean;
63
+ /** A value `useKeyedState` can key on: compared with `Object.is`. */
64
+ export type StateKey = string | number | boolean | null | undefined;
65
+ /**
66
+ * Local state that starts over from `initial` whenever `key` changes: the
67
+ * draft of the record whose id is `key`, a selection that belongs to one
68
+ * result set. Prefer remounting with `key` when the whole subtree may start
69
+ * over; use this when sibling state must survive the reset.
70
+ *
71
+ * It replaces an effect that resets state when a prop changes. The reset
72
+ * happens during the render that sees the new key, before anything
73
+ * commits, so no stale value is ever shown and no extra commit happens.
74
+ * The setter has one identity for the component's lifetime and bails out
75
+ * when the value does not change.
76
+ */
77
+ export declare const useKeyedState: <T>(key: StateKey, initial: T | (() => T)) => readonly [T, Dispatch<SetStateAction<T>>];
78
+ /**
79
+ * The current time in epoch milliseconds, redrawn every `intervalMs` while the
80
+ * component is mounted: for elapsed times and relative timestamps. Replaces
81
+ * an effect that sets "now" on mount and on every tick.
82
+ *
83
+ * A server-rendered component that shows the time passes `serverNow`, the
84
+ * timestamp the server rendered with (serialized into the page): the server
85
+ * render and hydration both use it, so they match, and the live clock takes
86
+ * over once the component subscribes.
87
+ */
88
+ export declare const useNow: (intervalMs: number, serverNow?: number) => number;