@makoai/app-sdk 2.15.0 → 2.17.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.
package/README.md CHANGED
@@ -42,6 +42,36 @@ const { refresh, refreshing } = useQuery("latest_sales");
42
42
  </button>
43
43
  ```
44
44
 
45
+ ### Performance: SQL does the work
46
+
47
+ One 193k-row app froze ~10 s on every filter click. It loaded the binding
48
+ with `useQuery` and filtered it in a component. The rules:
49
+
50
+ 1. Filters, joins and aggregation run in SQL through `useDuckDB(sql)`, filters
51
+ in the `WHERE` clause. Only the rows a panel draws come back to JS.
52
+ `withConnection` serves a result several panels share. `useQuery(name)` is
53
+ for bindings under ~10k rows or already aggregated to what the page shows.
54
+ 2. One query per panel. Each panel returns a skeleton of its final size while
55
+ `loading`, never a "0" or an empty chart. Filter controls update on the
56
+ click frame; panels read filters through `useDeferredValue` or
57
+ `startTransition`.
58
+ 3. Measure before calling a UI done: the clicked control updates in under
59
+ 50 ms, no main-thread task runs over 200 ms during a filter change.
60
+ 4. Keep bindings small: aggregate in the binding, drop unused columns, split
61
+ a binding when one view needs far more rows.
62
+ 5. One engine: never a private parquet reader or a second DuckDB.
63
+
64
+ ```tsx
65
+ const f = useDeferredValue(country);
66
+ const q = useDuckDB(`select day, sum(revenue) r from latest_sales
67
+ where country = '${f.replace(/'/g, "''")}' group by 1 order by 1`);
68
+ if (q.loading) return <div className="skeleton" style={{ height: 280 }} />;
69
+ ```
70
+
71
+ In dev (`import.meta.env.DEV`), `useQuery` logs one `console.warn` per
72
+ binding that returns more than 20,000 rows, pointing to
73
+ `useDuckDB` (2.16+). Production builds never warn.
74
+
45
75
  ### Which SDK is running: `SDK_VERSION` (2.9+)
46
76
 
47
77
  `import { SDK_VERSION } from "@makoai/app-sdk"` is this package's version.
@@ -358,10 +388,9 @@ import {
358
388
  <MultiSelect options={["CH", "ES", "IT"]} value={countries} onChange={setCountries} allLabel="All countries" />
359
389
  ```
360
390
 
361
- - `MultiSelect` — controlled (`value` / `onChange`). An empty selection means
362
- "all" unless `emptyMeansAll={false}` (then "all" = every value selected).
363
- Options are strings or `{ value, label, color }`; `showOnly` adds an "Only"
364
- button per row. On phones the menu is a bottom sheet.
391
+ - `MultiSelect` — controlled (`value` / `onChange`). Options are strings or
392
+ `{ value, label, color }`; `showOnly` adds an "Only" button per row. On
393
+ phones the menu is a bottom sheet. See "MultiSelect: the All rule" below.
365
394
  - `FreshnessBadge` — presentational: the app decides what fresh means and
366
395
  passes `tone` (`ok` / `warn` / `bad`, or `green` / `amber` / `red`), a
367
396
  `headline`, and per-source rows; `action` is a callout slot (e.g. a "Load
@@ -391,6 +420,37 @@ import {
391
420
  and declare it once (`src/vite-env.d.ts`):
392
421
  `declare const __APP_BINDING_NAMES__: string[];`
393
422
 
423
+ ### MultiSelect: the All rule and one open popover (2.17+)
424
+
425
+ **All.** Nothing is filtered when `value` is empty or holds every option. The
426
+ All row is then ticked and every option row unticked, whichever of the two the
427
+ app passes. A click on an option under All selects only that option.
428
+ Unticking the last option, or ticking the last missing one, returns to All.
429
+ `emptyMeansAll` (default `true`) only sets what All emits: `[]`, or every
430
+ option's value when `false`.
431
+
432
+ **Trigger.** It reads the All label, the one selected label, or "3 selected".
433
+ `formatMany={n => `${n} markets`}` changes the last one. The trigger's `title`
434
+ lists the selected labels. Chips and `maxChips` are gone.
435
+
436
+ **Checkbox.** `Checkbox` (`checked`: `true` / `false` / `"mixed"`) is the
437
+ kit's one checkbox, coloured from `--primary` and `--input`. Draw the rows of
438
+ an app's own Radix menu with it, so every menu on the page ticks alike.
439
+
440
+ **One open at a time.** Opening a kit popover (`MultiSelect`,
441
+ `FreshnessBadge`) closes any other. Escape, a pointerdown outside and focus
442
+ leaving it close it too. The kit listens for pointerdown in the capture phase,
443
+ because Radix triggers cancel the mouse events of their pointerdown. When an
444
+ app's own menu opens, call `closePopovers()`:
445
+
446
+ ```tsx
447
+ <DropdownMenu modal={false} onOpenChange={o => o && closePopovers()}>
448
+ ```
449
+
450
+ Pure helpers for app-side menus: `multiSelectState(value, optionValues)`,
451
+ `multiSelectToggle(value, optionValues, v, emptyMeansAll)`,
452
+ `multiSelectText(value, options, allLabel, formatMany)`.
453
+
394
454
  ### Chart tooltips: `TableTooltip` (2.10+, every series from 2.15)
395
455
 
396
456
  Every chart tooltip is a table, never recharts' coloured `name : value` list:
package/data-core.js CHANGED
@@ -360,3 +360,22 @@ export function retryDelayMs(error, retries) {
360
360
  const wait = table[retries] ?? Infinity;
361
361
  return Math.max(wait, typeof error.retryAfterMs === "number" ? error.retryAfterMs : 0);
362
362
  }
363
+
364
+ /** Rows past which `useQuery` warns in dev: a page that filters this many in JS janks. */
365
+ export const LARGE_QUERY_ROWS = 20000;
366
+
367
+ /**
368
+ * The dev-console warning for a `useQuery` that handed JS `rows` rows, or null
369
+ * at or under `limit`. The fix is SQL: `useDuckDB` filters and aggregates in
370
+ * DuckDB and returns only what a panel draws.
371
+ */
372
+ export function largeQueryWarning(name, rows, limit = LARGE_QUERY_ROWS) {
373
+ if (!(rows > limit)) return null;
374
+ return (
375
+ "[@makoai/app-sdk] useQuery(" + JSON.stringify(String(name)) + ") returned " +
376
+ rows.toLocaleString("en-US") + " rows to JS. Filtering or aggregating them in a component " +
377
+ "blocks the main thread on every filter change. Run filters, joins and aggregation in SQL " +
378
+ "with useDuckDB(\"select … from " + quoteIdent(name) + " where …\"), one query per panel, " +
379
+ "so only the rows a panel draws come back. (Dev-only warning, shown once per binding.)"
380
+ );
381
+ }
package/index.js CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  toPlainRows,
30
30
  parseBindingSnapshot,
31
31
  snapshotUrl,
32
+ largeQueryWarning,
32
33
  } from "./data-core.js";
33
34
 
34
35
  /**
@@ -36,7 +37,7 @@ import {
36
37
  * in a page (or this export) says which SDK a deployed app actually runs.
37
38
  * Kept in step with package.json by snapshot.test.mjs.
38
39
  */
39
- export const SDK_VERSION = "2.15.0";
40
+ export const SDK_VERSION = "2.17.0";
40
41
  if (typeof window !== "undefined") {
41
42
  try {
42
43
  window.__MAKO_APP_SDK__ = SDK_VERSION;
@@ -1680,6 +1681,18 @@ function useSnapshotPreview(name, enabled, rowLimit) {
1680
1681
  return preview;
1681
1682
  }
1682
1683
 
1684
+ // Vite replaces import.meta.env with { DEV: false, … } in every build, so this
1685
+ // is false in production and outside Vite (import.meta.env undefined).
1686
+ const DEV_BUILD = Boolean(import.meta.env && import.meta.env.DEV);
1687
+ const warnedLarge = new Set();
1688
+ function warnIfLarge(name, rows) {
1689
+ if (!DEV_BUILD || warnedLarge.has(name)) return;
1690
+ const message = largeQueryWarning(name, rows);
1691
+ if (!message) return;
1692
+ warnedLarge.add(name);
1693
+ console.warn(message);
1694
+ }
1695
+
1683
1696
  export function useQuery(name, opts) {
1684
1697
  bootEngine();
1685
1698
  const rowLimit = opts ? opts.rowLimit : undefined;
@@ -1690,6 +1703,7 @@ export function useQuery(name, opts) {
1690
1703
  hold(name);
1691
1704
  await registerBinding(name);
1692
1705
  const r = await runSql("SELECT * FROM " + quoteIdent(name), rowLimit, undefined, new Set([name]));
1706
+ warnIfLarge(name, r.rows.length);
1693
1707
  return { data: r.rows, fields: r.fields, truncated: r.truncated, rowCount: r.rowCount };
1694
1708
  },
1695
1709
  [name, rowLimit],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@makoai/app-sdk",
3
- "version": "2.15.0",
3
+ "version": "2.17.0",
4
4
  "description": "Mako app SDK: data bindings (useQuery/useDuckDB), URL state, theme, and the house dashboard kit (/ui).",
5
5
  "license": "MIT",
6
6
  "repository": {
package/ui-core.js CHANGED
@@ -322,3 +322,79 @@ export function csvToTsv(text) {
322
322
  .map(r => r.map(v => v.replace(/[\t\r\n]+/g, " ")).join("\t"))
323
323
  .join("\n");
324
324
  }
325
+
326
+ // ---------------------------------------------------------------------------
327
+ // MultiSelect: the All rule and the trigger text
328
+ // ---------------------------------------------------------------------------
329
+
330
+ /**
331
+ * Where a MultiSelect stands. Nothing is filtered when the value is empty or
332
+ * holds every option: `all` is true and `selected` is empty, so the All row
333
+ * is ticked and every option row unticked. Otherwise `selected` is the value
334
+ * in option order (values the options don't list yet are kept at the end).
335
+ */
336
+ export function multiSelectState(value, optionValues) {
337
+ const picked = [...new Set(value ?? [])];
338
+ const covers = optionValues.length > 0 && optionValues.every(v => picked.includes(v));
339
+ if (picked.length === 0 || covers) return { all: true, selected: [] };
340
+ const known = optionValues.filter(v => picked.includes(v));
341
+ return { all: false, selected: [...known, ...picked.filter(v => !optionValues.includes(v))] };
342
+ }
343
+
344
+ /** The value that means "All": [] by default, every option when `emptyMeansAll` is false. */
345
+ export function multiSelectAll(optionValues, emptyMeansAll = true) {
346
+ return emptyMeansAll ? [] : [...optionValues];
347
+ }
348
+
349
+ /**
350
+ * The next value after a click on option `v`. Under All, the click selects
351
+ * only `v`. Otherwise it toggles `v`; unticking the last option or ticking
352
+ * the last missing one returns to All.
353
+ */
354
+ export function multiSelectToggle(value, optionValues, v, emptyMeansAll = true) {
355
+ const { all, selected } = multiSelectState(value, optionValues);
356
+ if (all) return optionValues.length === 1 ? multiSelectAll(optionValues, emptyMeansAll) : [v];
357
+ const next = selected.includes(v) ? selected.filter(x => x !== v) : [...selected, v];
358
+ return multiSelectState(next, optionValues).all ? multiSelectAll(optionValues, emptyMeansAll) : next;
359
+ }
360
+
361
+ /**
362
+ * The trigger text: the All label, the one selected option's label, or
363
+ * "N selected" (or `many(n)`).
364
+ */
365
+ export function multiSelectText(value, options, allLabel = "All", many = n => `${n} selected`) {
366
+ const { all, selected } = multiSelectState(value, options.map(o => o.value));
367
+ if (all) return allLabel;
368
+ if (selected.length === 1) return options.find(o => o.value === selected[0])?.label ?? selected[0];
369
+ return many(selected.length);
370
+ }
371
+
372
+ // ---------------------------------------------------------------------------
373
+ // One open popover at a time
374
+ // ---------------------------------------------------------------------------
375
+ let openPopoverClose = null;
376
+
377
+ /**
378
+ * Register the popover that just opened: `close` is how to close it. Any other
379
+ * kit popover that is open closes first.
380
+ */
381
+ export function claimPopover(close) {
382
+ const prev = openPopoverClose;
383
+ openPopoverClose = close;
384
+ if (prev && prev !== close) prev();
385
+ }
386
+
387
+ /** Forget `close` if it is still the open popover (on close or unmount). */
388
+ export function releasePopover(close) {
389
+ if (openPopoverClose === close) openPopoverClose = null;
390
+ }
391
+
392
+ /**
393
+ * Close whichever kit popover is open. Call it when a popover the kit doesn't
394
+ * own opens (a Radix menu's onOpenChange), so one dropdown is open at a time.
395
+ */
396
+ export function closePopovers() {
397
+ const close = openPopoverClose;
398
+ openPopoverClose = null;
399
+ if (close) close();
400
+ }
package/ui.css CHANGED
@@ -271,14 +271,9 @@ button:not(:disabled), [role="button"]:not(:disabled) { cursor: pointer; }
271
271
  .mk-ms-trigger:hover { background: var(--accent); }
272
272
  .mk-ms-trigger:focus-visible { outline: none; }
273
273
  .mk-ms-trigger.open, .mk-ms-trigger:focus-visible { border-color: var(--ring); box-shadow: var(--mk-ring-focus); }
274
- .mk-ms-value { display: flex; align-items: center; min-width: 0; overflow: hidden; }
275
- .mk-ms-chips { display: inline-flex; align-items: center; gap: 4px; }
276
- .mk-ms-chip {
277
- display: inline-flex; align-items: center; gap: 5px; height: 20px; padding: 0 8px;
278
- font-size: 12px; font-weight: 500; border-radius: 999px; white-space: nowrap;
279
- background: var(--secondary); color: var(--secondary-foreground);
280
- }
281
- .mk-ms-more { color: var(--muted-foreground); }
274
+ .mk-ms-value { display: flex; align-items: center; gap: 6px; min-width: 0; overflow: hidden; }
275
+ /* The trigger reads "All", the one selected label, or "N selected". */
276
+ .mk-ms-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
282
277
  .mk-ms-caret { color: var(--muted-foreground); flex-shrink: 0; transition: transform .15s ease; }
283
278
  .mk-ms-trigger.open .mk-ms-caret { transform: rotate(180deg); }
284
279
  .mk-ms-menu {
@@ -295,6 +290,7 @@ button:not(:disabled), [role="button"]:not(:disabled) { cursor: pointer; }
295
290
  .mk-ms-opt:hover, .mk-ms-opt:focus-visible { background: var(--accent); outline: none; }
296
291
  .mk-ms-opt.active { font-weight: 500; }
297
292
  .mk-ms-label { flex: 1; }
293
+ /* The kit's one checkbox (Checkbox, MultiSelect rows): theme tokens only. */
298
294
  .mk-ms-box {
299
295
  display: inline-flex; align-items: center; justify-content: center;
300
296
  width: 16px; height: 16px; flex-shrink: 0; border-radius: var(--mk-radius-sm);
package/ui.d.ts CHANGED
@@ -73,17 +73,25 @@ export interface MultiSelectOption<V extends string = string> {
73
73
 
74
74
  export interface MultiSelectProps<V extends string = string> {
75
75
  options: ReadonlyArray<V | MultiSelectOption<V>>;
76
+ /**
77
+ * The selected values. Empty, or every option, means "All": the All row is
78
+ * ticked and every option row unticked. Under All a click on an option
79
+ * selects only that option; unticking the last option, or ticking the last
80
+ * missing one, returns to All.
81
+ */
76
82
  value: readonly V[];
77
83
  onChange: (next: V[]) => void;
78
84
  allLabel?: string;
79
85
  /**
80
- * true (default): an empty selection means "all".
81
- * false: "all" is every value selected; the All row selects every option.
86
+ * What All emits. true (default): []. false: every option's value.
87
+ * Both spellings display as All either way.
82
88
  */
83
89
  emptyMeansAll?: boolean;
84
90
  /** An "Only" button on each row that selects just that value. */
85
91
  showOnly?: boolean;
86
- /** Chips shown in the trigger before "+n". Default 2. */
92
+ /** Trigger text for several values. Default `${n} selected`. */
93
+ formatMany?: (n: number) => string;
94
+ /** @deprecated 2.17: the trigger reads "All", the one label, or "N selected". Ignored. */
87
95
  maxChips?: number;
88
96
  /** Which edge the menu aligns to before flipping. Default "start". */
89
97
  align?: "start" | "end";
@@ -92,6 +100,37 @@ export interface MultiSelectProps<V extends string = string> {
92
100
  }
93
101
  export function MultiSelect<V extends string = string>(props: MultiSelectProps<V>): React.ReactElement;
94
102
 
103
+ /**
104
+ * The kit's one checkbox, drawn only (the row around it takes the click),
105
+ * coloured from theme tokens. Use it for the rows of an app's own menus.
106
+ */
107
+ export function Checkbox(props: { checked?: boolean | "mixed"; className?: string }): React.ReactElement;
108
+
109
+ /** Where a MultiSelect stands: `all` when the value is empty or holds every option (then `selected` is empty). */
110
+ export function multiSelectState<V extends string>(
111
+ value: readonly V[] | null | undefined,
112
+ optionValues: readonly V[],
113
+ ): { all: boolean; selected: V[] };
114
+ /** The next value after a click on `v`, by the All rule. */
115
+ export function multiSelectToggle<V extends string>(
116
+ value: readonly V[],
117
+ optionValues: readonly V[],
118
+ v: V,
119
+ emptyMeansAll?: boolean,
120
+ ): V[];
121
+ /** The trigger text: the All label, the one label, or "N selected" (`many(n)`). */
122
+ export function multiSelectText<V extends string>(
123
+ value: readonly V[],
124
+ options: ReadonlyArray<{ value: V; label: string }>,
125
+ allLabel?: string,
126
+ many?: (n: number) => string,
127
+ ): string;
128
+ /**
129
+ * Close whichever kit popover (MultiSelect, FreshnessBadge) is open. Call it
130
+ * when an app's own menu opens: `onOpenChange={o => o && closePopovers()}`.
131
+ */
132
+ export function closePopovers(): void;
133
+
95
134
  export interface FreshnessSource {
96
135
  key?: string;
97
136
  label: React.ReactNode;
package/ui.js CHANGED
@@ -12,6 +12,8 @@ import * as React from "react";
12
12
  import { createPortal } from "react-dom";
13
13
  import { bindingPhaseLabel, refreshBinding, useBindingProgress } from "./index.js";
14
14
  import {
15
+ claimPopover,
16
+ closePopovers,
15
17
  COLUMN_WIDTHS,
16
18
  columnLayout,
17
19
  compareValues,
@@ -20,11 +22,16 @@ import {
20
22
  csvToTsv,
21
23
  defaultColumnWidth,
22
24
  formatSeconds as fmtSecs,
25
+ multiSelectAll,
26
+ multiSelectState,
27
+ multiSelectText,
28
+ multiSelectToggle,
23
29
  nextSort,
24
30
  normalizeTone,
25
31
  pageSlice,
26
32
  pageToSync,
27
33
  refreshOrder,
34
+ releasePopover,
28
35
  serializeResetKey,
29
36
  sortRows,
30
37
  toCsv,
@@ -34,6 +41,7 @@ import {
34
41
  } from "./ui-core.js";
35
42
 
36
43
  export {
44
+ closePopovers,
37
45
  COLUMN_WIDTHS,
38
46
  columnLayout,
39
47
  compareValues,
@@ -41,6 +49,9 @@ export {
41
49
  csvDate,
42
50
  csvToTsv,
43
51
  defaultColumnWidth,
52
+ multiSelectState,
53
+ multiSelectText,
54
+ multiSelectToggle,
44
55
  nextSort,
45
56
  normalizeTone,
46
57
  pageSlice,
@@ -84,6 +95,8 @@ function svg(size, strokeWidth, children, className) {
84
95
  }
85
96
  const IconCheck = ({ size = 11 }) =>
86
97
  svg(size, 3.2, [h("polyline", { key: "p", points: "20 6 9 17 4 12" })]);
98
+ const IconMinus = ({ size = 11 }) =>
99
+ svg(size, 3.2, [h("line", { key: "l", x1: 6, y1: 12, x2: 18, y2: 12 })]);
87
100
  const IconChevron = ({ className }) =>
88
101
  svg(12, 2.2, [h("polyline", { key: "p", points: "6 9 12 15 18 9" })], className);
89
102
  const IconX = ({ size = 16 }) =>
@@ -102,25 +115,36 @@ const IconRefresh = () =>
102
115
  const PHONE = "(max-width: 640px)";
103
116
 
104
117
  /**
105
- * Close on outside click and Escape, and keep the `.mk-pop` inside `wrapRef`
106
- * within the viewport: it opens under its trigger aligned to `align`, flips
107
- * to the other edge when that would overflow, and as a last resort is pinned
108
- * to the viewport margin. On phones the popover is a bottom sheet (CSS) and
109
- * is left alone.
118
+ * One kit popover is open at a time: opening this one closes any other (a
119
+ * module-level registry, see claimPopover). It closes on Escape, on a
120
+ * pointerdown outside it, and when focus moves outside it. Pointerdown, in
121
+ * the capture phase, because Radix menu triggers cancel the mouse events of
122
+ * their pointerdown, so an outside mousedown/click listener never hears them.
123
+ *
124
+ * It also keeps the `.mk-pop` inside `wrapRef` within the viewport: it opens
125
+ * under its trigger aligned to `align`, flips to the other edge when that
126
+ * would overflow, and as a last resort is pinned to the viewport margin. On
127
+ * phones the popover is a bottom sheet (CSS) and is left alone.
110
128
  */
111
129
  function usePopover(open, setOpen, wrapRef, align) {
112
130
  React.useEffect(() => {
113
131
  if (!open) return undefined;
114
- const onDoc = e => {
115
- if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
132
+ const close = () => setOpen(false);
133
+ claimPopover(close);
134
+ const outside = e => {
135
+ const wrap = wrapRef.current;
136
+ if (wrap && e.target instanceof Node && !wrap.contains(e.target)) close();
116
137
  };
117
138
  const onKey = e => {
118
- if (e.key === "Escape") setOpen(false);
139
+ if (e.key === "Escape") close();
119
140
  };
120
- document.addEventListener("mousedown", onDoc);
141
+ document.addEventListener("pointerdown", outside, true);
142
+ document.addEventListener("focusin", outside, true);
121
143
  document.addEventListener("keydown", onKey);
122
144
  return () => {
123
- document.removeEventListener("mousedown", onDoc);
145
+ releasePopover(close);
146
+ document.removeEventListener("pointerdown", outside, true);
147
+ document.removeEventListener("focusin", outside, true);
124
148
  document.removeEventListener("keydown", onKey);
125
149
  };
126
150
  }, [open, setOpen, wrapRef]);
@@ -621,19 +645,39 @@ export function DataTable({
621
645
  }
622
646
 
623
647
  // ---------------------------------------------------------------------------
624
- // MultiSelect
648
+ // Checkbox + MultiSelect
625
649
  // ---------------------------------------------------------------------------
626
650
  function toOption(o) {
627
651
  return typeof o === "string" ? { value: o, label: o } : o;
628
652
  }
629
653
 
654
+ /**
655
+ * The kit's one checkbox, drawn only (the row around it takes the click).
656
+ * `checked`: true, false or "mixed". Colours come from the theme tokens
657
+ * (--primary when ticked, --input border when not), so every menu on a page,
658
+ * the kit's or the app's own Radix menus, ticks the same way.
659
+ */
660
+ export function Checkbox({ checked = false, className }) {
661
+ const on = checked === true || checked === "mixed";
662
+ return h(
663
+ "span",
664
+ { className: cx("mk-ms-box", on && "on", className), "aria-hidden": "true" },
665
+ checked === "mixed" ? h(IconMinus) : on ? h(IconCheck) : null,
666
+ );
667
+ }
668
+
630
669
  /**
631
670
  * Multi-select filter (shadcn combobox look). Controlled: `value` is the
632
671
  * selected values, `onChange` gets the next array.
633
672
  *
634
- * `emptyMeansAll` (default true): an empty selection is "all" — the common
635
- * filter shape. Set it to false when "all" is every value selected; the
636
- * "All" row then selects every option instead of clearing.
673
+ * The All rule: nothing is filtered when `value` is empty or holds every
674
+ * option. The All row is then ticked and every option row unticked. A click
675
+ * on an option under All selects only that option. Unticking the last
676
+ * option, or ticking the last missing one, returns to All. The trigger reads
677
+ * the All label, the one selected label, or "N selected".
678
+ *
679
+ * `emptyMeansAll` (default true) only picks what All emits: [] by default,
680
+ * every option's value when false.
637
681
  */
638
682
  export function MultiSelect({
639
683
  options,
@@ -642,7 +686,7 @@ export function MultiSelect({
642
686
  allLabel = "All",
643
687
  emptyMeansAll = true,
644
688
  showOnly = false,
645
- maxChips = 2,
689
+ formatMany,
646
690
  align = "start",
647
691
  className,
648
692
  "aria-label": ariaLabel,
@@ -651,16 +695,15 @@ export function MultiSelect({
651
695
  const ref = React.useRef(null);
652
696
  usePopover(open, setOpen, ref, align);
653
697
  const opts = options.map(toOption);
654
- const allOn = emptyMeansAll ? value.length === 0 : value.length === opts.length;
655
- const chosen = opts.filter(o => value.includes(o.value));
656
-
657
- const toggle = v =>
658
- onChange(value.includes(v) ? value.filter(x => x !== v) : [...value, v]);
659
- const all = () => onChange(emptyMeansAll ? [] : opts.map(o => o.value));
698
+ const values = opts.map(o => o.value);
699
+ const { all: allOn, selected } = multiSelectState(value, values);
700
+ const text = multiSelectText(value, opts, allLabel, formatMany);
701
+ const single = selected.length === 1 ? opts.find(o => o.value === selected[0]) : null;
660
702
 
661
- const box = on => h("span", { className: cx("mk-ms-box", on && "on") }, on && h(IconCheck));
703
+ const toggle = v => onChange(multiSelectToggle(value, values, v, emptyMeansAll));
704
+ const all = () => onChange(multiSelectAll(values, emptyMeansAll));
662
705
  const dot = o =>
663
- o.color ? h("span", { className: "mk-ms-swatch", style: { background: o.color } }) : null;
706
+ o?.color ? h("span", { className: "mk-ms-swatch", style: { background: o.color } }) : null;
664
707
 
665
708
  return h(
666
709
  "div",
@@ -673,23 +716,12 @@ export function MultiSelect({
673
716
  "aria-haspopup": "listbox",
674
717
  "aria-expanded": open,
675
718
  "aria-label": ariaLabel,
719
+ title: selected.length > 1
720
+ ? selected.map(v => opts.find(o => o.value === v)?.label ?? v).join(", ")
721
+ : undefined,
676
722
  onClick: () => setOpen(o => !o),
677
723
  },
678
- h(
679
- "span",
680
- { className: "mk-ms-value" },
681
- allOn || chosen.length === 0
682
- ? h("span", null, allLabel)
683
- : h(
684
- "span",
685
- { className: "mk-ms-chips" },
686
- ...chosen.slice(0, maxChips).map(o =>
687
- h("span", { key: o.value, className: "mk-ms-chip" }, dot(o), o.label),
688
- ),
689
- chosen.length > maxChips &&
690
- h("span", { key: "+", className: "mk-ms-chip mk-ms-more" }, `+${chosen.length - maxChips}`),
691
- ),
692
- ),
724
+ h("span", { className: "mk-ms-value" }, dot(single), h("span", { className: "mk-ms-text" }, text)),
693
725
  h(IconChevron, { className: "mk-ms-caret" }),
694
726
  ),
695
727
  open &&
@@ -698,13 +730,13 @@ export function MultiSelect({
698
730
  { className: "mk-pop mk-ms-menu", role: "listbox", "aria-multiselectable": true },
699
731
  h(
700
732
  "button",
701
- { type: "button", className: cx("mk-ms-opt", allOn && "active"), onClick: all },
702
- box(allOn),
733
+ { type: "button", className: cx("mk-ms-opt", allOn && "active"), "aria-pressed": allOn, onClick: all },
734
+ h(Checkbox, { checked: allOn }),
703
735
  h("span", { className: "mk-ms-label" }, allLabel),
704
736
  ),
705
737
  h("div", { className: "mk-ms-sep" }),
706
738
  ...opts.map(o => {
707
- const on = value.includes(o.value);
739
+ const on = selected.includes(o.value);
708
740
  return h(
709
741
  "div",
710
742
  {
@@ -721,7 +753,7 @@ export function MultiSelect({
721
753
  }
722
754
  },
723
755
  },
724
- box(on),
756
+ h(Checkbox, { checked: on }),
725
757
  dot(o),
726
758
  h("span", { className: "mk-ms-label" }, o.label),
727
759
  showOnly &&
@@ -732,7 +764,7 @@ export function MultiSelect({
732
764
  className: "mk-ms-only",
733
765
  onClick: e => {
734
766
  e.stopPropagation();
735
- onChange([o.value]);
767
+ onChange(multiSelectToggle([], values, o.value, emptyMeansAll));
736
768
  },
737
769
  },
738
770
  "Only",