@mdbase-dev/ui 0.1.2 → 0.1.3

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,22 @@
1
+ import { type JSX } from "react";
2
+ export interface SegmentedOption<Value extends string = string> {
3
+ readonly value: Value;
4
+ readonly label: string;
5
+ readonly disabled?: boolean | undefined;
6
+ }
7
+ export interface SegmentedProps<Value extends string> {
8
+ readonly value: Value;
9
+ readonly options: readonly SegmentedOption<Value>[];
10
+ readonly onChange: (value: Value) => void;
11
+ /** The radios' form name; generated when omitted. */
12
+ readonly name?: string | undefined;
13
+ readonly disabled?: boolean | undefined;
14
+ readonly className?: string | undefined;
15
+ readonly "aria-label"?: string | undefined;
16
+ readonly "aria-labelledby"?: string | undefined;
17
+ }
18
+ /**
19
+ * A single choice among two to four short options that all stay in view, chosen in one
20
+ * click. Use Select when there are more, or when their labels are long.
21
+ */
22
+ export declare function Segmented<Value extends string>({ value, options, onChange, name, disabled, className, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, }: SegmentedProps<Value>): JSX.Element;
@@ -0,0 +1,74 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useId, useLayoutEffect, useRef } from "react";
3
+ /**
4
+ * A single choice among two to four short options that all stay in view, chosen in one
5
+ * click. Use Select when there are more, or when their labels are long.
6
+ */
7
+ export function Segmented({
8
+ value,
9
+ options,
10
+ onChange,
11
+ name,
12
+ disabled,
13
+ className,
14
+ "aria-label": ariaLabel,
15
+ "aria-labelledby": ariaLabelledBy
16
+ }) {
17
+ const generatedName = useId();
18
+ const groupRef = useRef(null);
19
+ const thumbRef = useRef(null);
20
+ const optionKey = options.map(option => option.value).join("\n");
21
+ // The thumb takes the checked option's box. A new choice names the edge that leads, which
22
+ // CSS moves first, so the thumb stretches on the way; anything else places it at once.
23
+ const place = chosen => {
24
+ const group = groupRef.current;
25
+ const thumb = thumbRef.current;
26
+ const option = group.querySelector("input:checked")?.closest("label");
27
+ const shown = !thumb.hidden;
28
+ thumb.hidden = !option;
29
+ if (!option) return;
30
+ const left = `${String(option.offsetLeft)}px`;
31
+ const right = `${String(group.clientWidth - option.offsetLeft - option.offsetWidth)}px`;
32
+ if (thumb.style.left === left && thumb.style.right === right) return;
33
+ if (chosen && shown) {
34
+ group.dataset["moving"] = option.offsetLeft > parseFloat(thumb.style.left) ? "end" : "start";
35
+ } else {
36
+ delete group.dataset["moving"];
37
+ }
38
+ thumb.style.left = left;
39
+ thumb.style.right = right;
40
+ };
41
+ useLayoutEffect(() => place(true), [value, optionKey]);
42
+ // Fonts arriving, a locale change or a narrower container all move the options.
43
+ useLayoutEffect(() => {
44
+ if (typeof ResizeObserver !== "function") return;
45
+ const observer = new ResizeObserver(() => place(false));
46
+ const group = groupRef.current;
47
+ observer.observe(group);
48
+ for (const option of group.querySelectorAll(".mdbase-segmented-option")) observer.observe(option);
49
+ return () => observer.disconnect();
50
+ }, [optionKey]);
51
+ return _jsxs("div", {
52
+ ref: groupRef,
53
+ role: "radiogroup",
54
+ className: ["mdbase-segmented", className].filter(Boolean).join(" "),
55
+ "aria-label": ariaLabel,
56
+ "aria-labelledby": ariaLabelledBy,
57
+ children: [_jsx("span", {
58
+ ref: thumbRef,
59
+ className: "mdbase-segmented-thumb",
60
+ "aria-hidden": "true",
61
+ hidden: true
62
+ }), options.map(option => _jsxs("label", {
63
+ className: "mdbase-segmented-option",
64
+ children: [_jsx("input", {
65
+ type: "radio",
66
+ name: name ?? generatedName,
67
+ value: option.value,
68
+ checked: option.value === value,
69
+ disabled: disabled || option.disabled,
70
+ onChange: () => onChange(option.value)
71
+ }), option.label]
72
+ }, option.value))]
73
+ });
74
+ }
@@ -0,0 +1,14 @@
1
+ import type { ButtonHTMLAttributes, JSX, ReactNode } from "react";
2
+ type ButtonAttributes = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "type" | "role" | "aria-checked" | "onChange" | "children">;
3
+ export interface SwitchProps extends ButtonAttributes {
4
+ readonly checked: boolean;
5
+ readonly onChange: (checked: boolean) => void;
6
+ /** Text beside the switch. Without it, name the switch with aria-label or aria-labelledby. */
7
+ readonly children?: ReactNode;
8
+ }
9
+ /**
10
+ * A setting that is on or off and takes effect at once. For a choice that waits for a Save,
11
+ * use Checkbox.
12
+ */
13
+ export declare function Switch({ checked, onChange, children, className, onClick, ...button }: SwitchProps): JSX.Element;
14
+ export {};
package/dist/Switch.js ADDED
@@ -0,0 +1,35 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * A setting that is on or off and takes effect at once. For a choice that waits for a Save,
4
+ * use Checkbox.
5
+ */
6
+ export function Switch({
7
+ checked,
8
+ onChange,
9
+ children,
10
+ className,
11
+ onClick,
12
+ ...button
13
+ }) {
14
+ const control = _jsx("button", {
15
+ ...button,
16
+ type: "button",
17
+ role: "switch",
18
+ "aria-checked": checked,
19
+ className: ["mdbase-switch", className].filter(Boolean).join(" "),
20
+ onClick: event => {
21
+ onClick?.(event);
22
+ if (!event.defaultPrevented) onChange(!checked);
23
+ },
24
+ children: _jsx("span", {
25
+ "aria-hidden": "true"
26
+ })
27
+ });
28
+ if (children === undefined) return control;
29
+ return _jsxs("label", {
30
+ className: "mdbase-switch-row",
31
+ children: [_jsx("span", {
32
+ children: children
33
+ }), control]
34
+ });
35
+ }
@@ -1,10 +1,11 @@
1
1
  import type { JSX } from "react";
2
2
  import { type ThemePreference } from "./theme.js";
3
3
  /**
4
- * The one control for choosing System, Light or Dark. The app owns the preference (with
5
- * loadThemePreference and saveThemePreference) because commands and menus may change it too.
4
+ * The one control for choosing System, Light or Dark: all three in view, one click each. The
5
+ * app owns the preference (with loadThemePreference and saveThemePreference) because commands
6
+ * and menus may change it too.
6
7
  */
7
- export declare function ThemeSelect({ value, onChange, className, label }: {
8
+ export declare function ThemeSelect({ value, onChange, className, label, }: {
8
9
  readonly value: ThemePreference;
9
10
  readonly onChange: (value: ThemePreference) => void;
10
11
  readonly className?: string | undefined;
@@ -1,7 +1,7 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { i18n as _i18n } from "@lingui/core";
3
3
  import { useLocaleRevision } from "./i18n.js";
4
- import { Select } from "./Select.js";
4
+ import { Segmented } from "./Segmented.js";
5
5
  import { themePreferences } from "./theme.js";
6
6
  const themeLabels = {
7
7
  get system() {
@@ -32,13 +32,10 @@ const themeLabels = {
32
32
  });
33
33
  }
34
34
  };
35
- const themeOptions = () => themePreferences.map(value => ({
36
- value,
37
- label: themeLabels[value]
38
- }));
39
35
  /**
40
- * The one control for choosing System, Light or Dark. The app owns the preference (with
41
- * loadThemePreference and saveThemePreference) because commands and menus may change it too.
36
+ * The one control for choosing System, Light or Dark: all three in view, one click each. The
37
+ * app owns the preference (with loadThemePreference and saveThemePreference) because commands
38
+ * and menus may change it too.
42
39
  */
43
40
  export function ThemeSelect({
44
41
  value,
@@ -53,11 +50,14 @@ export function ThemeSelect({
53
50
  })
54
51
  }) {
55
52
  useLocaleRevision();
56
- return _jsx(Select, {
53
+ return _jsx(Segmented, {
57
54
  "aria-label": label,
58
55
  className: className,
59
56
  value: value,
60
- options: themeOptions(),
57
+ options: themePreferences.map(value => ({
58
+ value,
59
+ label: themeLabels[value]
60
+ })),
61
61
  onChange: onChange
62
62
  });
63
63
  }
package/dist/Toaster.d.ts CHANGED
@@ -1,6 +1,8 @@
1
+ import { type JSX } from "react";
1
2
  export interface ToastItem {
2
3
  id: string;
3
4
  message: string;
5
+ /** success and error put a mark before the message; info (the default) has none. */
4
6
  tone?: "info" | "success" | "error";
5
7
  action?: {
6
8
  label: string;
@@ -8,12 +10,27 @@ export interface ToastItem {
8
10
  busy?: boolean;
9
11
  dismiss?: boolean;
10
12
  };
13
+ /** Stays until dismissed. */
11
14
  sticky?: boolean;
12
15
  dismissible?: boolean;
13
16
  durationMs?: number;
14
17
  }
15
- export declare function toast(message: string, undo?: () => void): void;
16
- export declare function Toaster({ items, onDismiss }: {
18
+ /** Everything a toast can carry except its text and the id `toast` gives it. */
19
+ export type ToastOptions = Omit<ToastItem, "id" | "message">;
20
+ /**
21
+ * Shows a toast in the page's `<Toaster />` and returns a function that dismisses it.
22
+ * Pass a function for the common receipt with Undo, or options for anything else:
23
+ *
24
+ * toast("Renamed", () => rename(before));
25
+ * toast("Could not save", { tone: "error", sticky: true });
26
+ */
27
+ export declare function toast(message: string, undo?: () => void): () => void;
28
+ export declare function toast(message: string, options: ToastOptions): () => void;
29
+ /**
30
+ * Where toasts appear. Render one per page. With no props it shows what `toast` queues; with
31
+ * `items` the app owns the list and hears about dismissals through `onDismiss`.
32
+ */
33
+ export declare function Toaster({ items, onDismiss, }: {
17
34
  items?: readonly ToastItem[];
18
35
  onDismiss?: (id: string) => void;
19
- }): import("react").JSX.Element;
36
+ }): JSX.Element;
package/dist/Toaster.js CHANGED
@@ -1,32 +1,55 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useEffect, useEffectEvent, useRef, useState } from "react";
3
- import { useOverlay } from "./overlay.js";
4
3
  import { i18n, useLocaleRevision } from "./i18n.js";
4
+ import { useOverlay } from "./overlay.js";
5
+ const MAX_OPEN = 4;
6
+ /** How long a toast from `toast` stays: a plain receipt, and one with an action to reach. */
7
+ const RECEIPT_MS = 5_000;
8
+ const ACTION_MS = 8_000;
9
+ /** An app-owned item that names no duration. */
10
+ const ITEM_MS = 6_000;
5
11
  let queue = [];
6
12
  let nextId = 0;
7
13
  const listeners = new Set();
8
14
  const notify = () => listeners.forEach(listener => listener());
9
- export function toast(message, undo) {
10
- const active = queue.filter(item => item.open);
11
- if (active.length >= 4) active[1].open = false;
12
- queue.push({
13
- id: `toast-${++nextId}`,
14
- message,
15
- action: undo ? {
15
+ function close(id) {
16
+ queue = queue.map(item => item.id === id ? {
17
+ ...item,
18
+ open: false
19
+ } : item);
20
+ notify();
21
+ }
22
+ export function toast(message, options) {
23
+ const given = typeof options === "function" ? {
24
+ action: {
16
25
  label: i18n._(
17
26
  /** i18n */
18
27
  {
19
28
  id: "9uI_rE",
20
29
  message: "Undo"
21
30
  }),
22
- onAction: undo,
31
+ onAction: options,
23
32
  dismiss: true
24
- } : undefined,
25
- durationMs: undo ? 8_000 : 5_000,
33
+ }
34
+ } : options ?? {};
35
+ const open = queue.filter(item => item.open);
36
+ // The oldest toast stays, so the first receipt of a burst is never lost to the rest.
37
+ if (open.length >= MAX_OPEN) open[1].open = false;
38
+ const id = `toast-${String(++nextId)}`;
39
+ queue.push({
40
+ durationMs: given.action ? ACTION_MS : RECEIPT_MS,
41
+ ...given,
42
+ id,
43
+ message,
26
44
  open: true
27
45
  });
28
46
  notify();
47
+ return () => close(id);
29
48
  }
49
+ /**
50
+ * Where toasts appear. Render one per page. With no props it shows what `toast` queues; with
51
+ * `items` the app owns the list and hears about dismissals through `onDismiss`.
52
+ */
30
53
  export function Toaster({
31
54
  items,
32
55
  onDismiss
@@ -41,6 +64,7 @@ export function Toaster({
41
64
  })));
42
65
  if (source !== previous) {
43
66
  setPrevious(source);
67
+ // A toast that left the source stays, closed, until its exit has played.
44
68
  setVisible([...source.map(item => ({
45
69
  ...item,
46
70
  open: "open" in item ? Boolean(item.open) : true
@@ -55,23 +79,22 @@ export function Toaster({
55
79
  update();
56
80
  return () => {
57
81
  listeners.delete(update);
82
+ // StrictMode replays this effect; only a Toaster that is really gone clears the queue.
58
83
  void Promise.resolve().then(() => {
59
84
  if (!listeners.size) queue.length = 0;
60
85
  });
61
86
  };
62
87
  }, []);
63
88
  const dismiss = useEffectEvent(id => {
64
- if (items) onDismiss?.(id);else {
65
- queue = queue.map(item => item.id === id ? {
66
- ...item,
67
- open: false
68
- } : item);
69
- notify();
70
- }
89
+ if (items) onDismiss?.(id);else close(id);
71
90
  });
72
91
  useEffect(() => {
73
92
  const escape = event => {
74
- if (event.key !== "Escape" || event.defaultPrevented || document.querySelector('dialog[open], [role="dialog"], [role="alertdialog"], [role="menu"]')) return;
93
+ if (event.key !== "Escape" || event.defaultPrevented) return;
94
+ // Escape belongs to an open dialog or menu before it belongs to a toast.
95
+ if (document.querySelector('dialog[open], [role="dialog"], [role="alertdialog"], [role="menu"]')) {
96
+ return;
97
+ }
75
98
  const item = [...visible].reverse().find(item => item.open && item.dismissible !== false && !item.action?.busy);
76
99
  if (item) {
77
100
  event.preventDefault();
@@ -96,6 +119,10 @@ export function Toaster({
96
119
  }, item.id))
97
120
  });
98
121
  }
122
+ const tonePaths = {
123
+ success: "m3.5 8.5 3 3 6-7",
124
+ error: "M8 4.5v4.5M8 11.5v.01"
125
+ };
99
126
  function Toast({
100
127
  item,
101
128
  onDismiss,
@@ -107,15 +134,16 @@ function Toast({
107
134
  } = useOverlay(item.open);
108
135
  const [hovered, setHovered] = useState(false);
109
136
  const [focused, setFocused] = useState(false);
110
- const remaining = useRef(item.durationMs ?? 6_000);
137
+ const remaining = useRef(item.durationMs ?? ITEM_MS);
111
138
  const dismiss = useEffectEvent(onDismiss);
112
139
  const remove = useEffectEvent(onRemoved);
113
140
  useEffect(() => {
114
- remaining.current = item.durationMs ?? 6_000;
141
+ remaining.current = item.durationMs ?? ITEM_MS;
115
142
  }, [item.message, item.durationMs]);
116
143
  useEffect(() => {
117
144
  if (!present) remove();
118
145
  }, [present]);
146
+ // The clock stops while the toast is hovered, focused or working, and resumes where it was.
119
147
  useEffect(() => {
120
148
  if (!item.open || item.sticky || item.action?.busy || hovered || focused) return;
121
149
  const started = Date.now();
@@ -126,6 +154,10 @@ function Toast({
126
154
  };
127
155
  }, [item.open, item.sticky, item.message, item.durationMs, item.action?.busy, hovered, focused]);
128
156
  if (!present) return null;
157
+ const {
158
+ action
159
+ } = item;
160
+ const tonePath = item.tone && item.tone !== "info" ? tonePaths[item.tone] : undefined;
129
161
  return _jsx("div", {
130
162
  ref: ref,
131
163
  "data-open": item.open,
@@ -142,26 +174,48 @@ function Toast({
142
174
  children: _jsxs("div", {
143
175
  className: "mdbase-toast",
144
176
  "data-tone": item.tone,
145
- children: [_jsx("span", {
177
+ children: [tonePath && _jsx("svg", {
178
+ className: "mdbase-toast-tone",
179
+ viewBox: "0 0 16 16",
180
+ "aria-hidden": "true",
181
+ children: _jsx("path", {
182
+ d: tonePath,
183
+ pathLength: 1
184
+ })
185
+ }), _jsx("span", {
186
+ className: "mdbase-toast-message",
146
187
  children: item.message
147
- }), item.action && _jsx("button", {
148
- className: "mdbase-button is-secondary",
149
- disabled: item.action.busy,
150
- "aria-busy": item.action.busy || undefined,
188
+ }), action && _jsx("button", {
189
+ type: "button",
190
+ className: "mdbase-button",
191
+ disabled: action.busy,
192
+ "aria-busy": action.busy || undefined,
151
193
  onClick: () => {
152
- if (item.action?.dismiss) dismiss();
153
- item.action?.onAction();
194
+ if (action.dismiss) dismiss();
195
+ action.onAction();
154
196
  },
155
- children: item.action.label
197
+ children: action.label
156
198
  }), item.dismissible !== false && _jsx("button", {
157
- className: "mdbase-button is-tertiary",
158
- disabled: item.action?.busy,
159
- onClick: dismiss,
160
- children: i18n._(
199
+ type: "button",
200
+ className: "mdbase-icon-button",
201
+ "aria-label": i18n._(
161
202
  /** i18n */
162
203
  {
163
204
  id: "1QfxQT",
164
205
  message: "Dismiss"
206
+ }),
207
+ disabled: action?.busy,
208
+ onClick: dismiss,
209
+ children: _jsx("svg", {
210
+ viewBox: "0 0 24 24",
211
+ "aria-hidden": "true",
212
+ fill: "none",
213
+ stroke: "currentColor",
214
+ strokeWidth: "1.6",
215
+ strokeLinecap: "round",
216
+ children: _jsx("path", {
217
+ d: "m6 6 12 12M18 6 6 18"
218
+ })
165
219
  })
166
220
  })]
167
221
  })
package/dist/Tooltip.d.ts CHANGED
@@ -1,6 +1,11 @@
1
- import { type ButtonHTMLAttributes, type ReactElement } from "react";
2
- export declare function Tooltip({ label, shortcut, children }: {
1
+ import { type HTMLAttributes, type JSX, type ReactElement } from "react";
2
+ /**
3
+ * Names an icon-only control on hover and keyboard focus, with its shortcut when it has one.
4
+ * The label also becomes the control's accessible name unless it already has one. Wrap a
5
+ * single focusable element: a button or a link.
6
+ */
7
+ export declare function Tooltip({ label, shortcut, children, }: {
3
8
  readonly label: string;
4
9
  readonly shortcut?: string;
5
- readonly children: ReactElement<ButtonHTMLAttributes<HTMLButtonElement>>;
6
- }): import("react").JSX.Element;
10
+ readonly children: ReactElement<HTMLAttributes<HTMLElement>>;
11
+ }): JSX.Element;