@stacksjs/components 0.2.855 → 0.2.858

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 (100) hide show
  1. package/dist/ContextMenu-43g3w5tp.stx +188 -0
  2. package/dist/DataGrid-7rt7v865.stx +376 -0
  3. package/dist/GraphView-0t3t9mec.stx +320 -0
  4. package/dist/JsonTree-satc4010.stx +317 -0
  5. package/dist/PreviewFrame-erbgvzj8.stx +257 -0
  6. package/dist/SplitPane-7sqfdwqa.stx +159 -0
  7. package/dist/component-api/component-api.js +36 -0
  8. package/dist/context-menu/context-menu.js +575 -0
  9. package/dist/data-grid/data-grid.js +1244 -0
  10. package/dist/graph-view/graph-view.js +1408 -0
  11. package/dist/index.d.ts +8 -0
  12. package/dist/index.js +22 -20
  13. package/dist/json-tree/json-tree.js +1121 -0
  14. package/dist/preview-frame/preview-frame.js +356 -0
  15. package/dist/split-pane/split-pane.js +364 -0
  16. package/dist/ui/context-menu/ContextMenu.d.ts +14 -0
  17. package/dist/ui/context-menu/context-menu.d.ts +8 -0
  18. package/dist/ui/context-menu/core.d.ts +74 -0
  19. package/dist/ui/context-menu/index.d.ts +11 -0
  20. package/dist/ui/context-menu/view.d.ts +36 -0
  21. package/dist/ui/data-grid/DataGrid.d.ts +30 -0
  22. package/dist/ui/data-grid/core.d.ts +141 -0
  23. package/dist/ui/data-grid/data-grid.d.ts +9 -0
  24. package/dist/ui/data-grid/index.d.ts +20 -0
  25. package/dist/ui/data-grid/view.d.ts +56 -0
  26. package/dist/ui/graph-view/GraphView.d.ts +21 -0
  27. package/dist/ui/graph-view/core/edges.d.ts +34 -0
  28. package/dist/ui/graph-view/core/force.d.ts +10 -0
  29. package/dist/ui/graph-view/core/graph.d.ts +83 -0
  30. package/dist/ui/graph-view/core/index.d.ts +5 -0
  31. package/dist/ui/graph-view/core/layered.d.ts +24 -0
  32. package/dist/ui/graph-view/core/viewport.d.ts +34 -0
  33. package/dist/ui/graph-view/graph-view.d.ts +9 -0
  34. package/dist/ui/graph-view/index.d.ts +21 -0
  35. package/dist/ui/graph-view/view.d.ts +51 -0
  36. package/dist/ui/json-tree/JsonTree.d.ts +18 -0
  37. package/dist/ui/json-tree/core.d.ts +108 -0
  38. package/dist/ui/json-tree/index.d.ts +18 -0
  39. package/dist/ui/json-tree/json-tree.d.ts +10 -0
  40. package/dist/ui/json-tree/tinker.d.ts +84 -0
  41. package/dist/ui/json-tree/view.d.ts +59 -0
  42. package/dist/ui/preview-frame/PreviewFrame.d.ts +44 -0
  43. package/dist/ui/preview-frame/core.d.ts +81 -0
  44. package/dist/ui/preview-frame/index.d.ts +19 -0
  45. package/dist/ui/preview-frame/preview-frame.d.ts +8 -0
  46. package/dist/ui/preview-frame/view.d.ts +37 -0
  47. package/dist/ui/split-pane/SplitPane.d.ts +18 -0
  48. package/dist/ui/split-pane/core.d.ts +58 -0
  49. package/dist/ui/split-pane/index.d.ts +15 -0
  50. package/dist/ui/split-pane/split-pane.d.ts +8 -0
  51. package/dist/ui/split-pane/view.d.ts +27 -0
  52. package/dist/ui/virtual-table/index.d.ts +6 -0
  53. package/dist/utils/component-api.d.ts +4 -0
  54. package/package.json +38 -3
  55. package/src/index.ts +8 -0
  56. package/src/ui/code-editor/README.md +2 -1
  57. package/src/ui/context-menu/ContextMenu.stx +188 -0
  58. package/src/ui/context-menu/README.md +117 -0
  59. package/src/ui/context-menu/context-menu.ts +8 -0
  60. package/src/ui/context-menu/core.ts +250 -0
  61. package/src/ui/context-menu/index.ts +16 -0
  62. package/src/ui/context-menu/view.ts +540 -0
  63. package/src/ui/data-grid/DataGrid.stx +376 -0
  64. package/src/ui/data-grid/README.md +204 -0
  65. package/src/ui/data-grid/core.ts +813 -0
  66. package/src/ui/data-grid/data-grid.ts +9 -0
  67. package/src/ui/data-grid/index.ts +34 -0
  68. package/src/ui/data-grid/view.ts +806 -0
  69. package/src/ui/graph-view/GraphView.stx +320 -0
  70. package/src/ui/graph-view/README.md +210 -0
  71. package/src/ui/graph-view/core/edges.ts +180 -0
  72. package/src/ui/graph-view/core/force.ts +237 -0
  73. package/src/ui/graph-view/core/graph.ts +277 -0
  74. package/src/ui/graph-view/core/index.ts +5 -0
  75. package/src/ui/graph-view/core/layered.ts +256 -0
  76. package/src/ui/graph-view/core/viewport.ts +141 -0
  77. package/src/ui/graph-view/graph-view.ts +9 -0
  78. package/src/ui/graph-view/index.ts +35 -0
  79. package/src/ui/graph-view/view.ts +809 -0
  80. package/src/ui/json-tree/JsonTree.stx +317 -0
  81. package/src/ui/json-tree/README.md +193 -0
  82. package/src/ui/json-tree/core.ts +588 -0
  83. package/src/ui/json-tree/index.ts +28 -0
  84. package/src/ui/json-tree/json-tree.ts +10 -0
  85. package/src/ui/json-tree/tinker.ts +349 -0
  86. package/src/ui/json-tree/view.ts +665 -0
  87. package/src/ui/preview-frame/PreviewFrame.stx +257 -0
  88. package/src/ui/preview-frame/README.md +107 -0
  89. package/src/ui/preview-frame/core.ts +195 -0
  90. package/src/ui/preview-frame/index.ts +31 -0
  91. package/src/ui/preview-frame/preview-frame.ts +8 -0
  92. package/src/ui/preview-frame/view.ts +336 -0
  93. package/src/ui/split-pane/README.md +87 -0
  94. package/src/ui/split-pane/SplitPane.stx +159 -0
  95. package/src/ui/split-pane/core.ts +200 -0
  96. package/src/ui/split-pane/index.ts +24 -0
  97. package/src/ui/split-pane/split-pane.ts +8 -0
  98. package/src/ui/split-pane/view.ts +305 -0
  99. package/src/ui/virtual-table/index.ts +6 -0
  100. package/src/utils/component-api.ts +72 -0
@@ -0,0 +1,188 @@
1
+ <script server>
2
+ /*
3
+ * The items, when they arrive as a plain prop. A bound list (`:items="list()"`)
4
+ * or a function that builds one for the element clicked on (`:items="menuFor"`)
5
+ * is read live by the client script.
6
+ */
7
+ export const items = Array.isArray($props.items) ? $props.items : []
8
+ export const label = $props.label || 'Context menu'
9
+ export const disabled = $bool($props.disabled)
10
+ export const className = $props.className || ''
11
+ export const menuId = $props.id || `context-menu-${$uid}`
12
+ </script>
13
+
14
+ <script client>
15
+ /*
16
+ * <ContextMenu>: wraps the content it is the menu for. A right click inside,
17
+ * the menu key or Shift+F10 opens it; `open()` opens it from anywhere.
18
+ *
19
+ * What a menu is and how it is moved through is in ./core, the DOM in ./view.
20
+ */
21
+ import { ContextMenuView } from './view'
22
+
23
+ const emit = defineEmits(['select', 'open', 'close'])
24
+
25
+ function asBoolean(value) {
26
+ if (value == null) return false
27
+ if (typeof value === 'string') return !['false', '0', 'off', 'no'].includes(value.trim().toLowerCase())
28
+ return Boolean(value)
29
+ }
30
+ // An array, a function that returns one, or JSON from a plain attribute.
31
+ function asItems(value) {
32
+ if (Array.isArray(value) || typeof value === 'function') return value
33
+ if (typeof value === 'string' && value.charAt(0) === '[') {
34
+ try { return JSON.parse(value) }
35
+ catch (e) { return [] }
36
+ }
37
+ return []
38
+ }
39
+
40
+ const liveItems = useReactiveProp('items', {{ items }}, { parse: asItems })
41
+ const liveDisabled = useReactiveProp('disabled', {{ disabled }}, { parse: asBoolean })
42
+
43
+ const rootRef = useRef('context-menu')
44
+ let menu = null
45
+
46
+ onMount(() => {
47
+ const root = rootRef()
48
+ if (!root) return
49
+
50
+ menu = new ContextMenuView(root, {
51
+ items: asItems(liveItems()),
52
+ label: {{ label }},
53
+ disabled: asBoolean(liveDisabled()),
54
+ }, {
55
+ onSelect(detail) { emit('select', detail) },
56
+ onOpen(detail) { emit('open', detail) },
57
+ onClose(detail) { emit('close', detail) },
58
+ })
59
+
60
+ effect(() => menu.setItems(asItems(liveItems())))
61
+ effect(() => menu.setDisabled(asBoolean(liveDisabled())))
62
+ })
63
+
64
+ onDestroy(() => {
65
+ if (menu) menu.destroy()
66
+ menu = null
67
+ })
68
+
69
+ defineExpose({
70
+ open: (at, items, options) => (menu ? menu.open(at, items || null, options || {}) : false),
71
+ close: () => { if (menu) menu.close('api') },
72
+ isOpen: () => (menu ? menu.isOpen : false),
73
+ })
74
+ </script>
75
+
76
+ {{-- The wrapper takes no box of its own: the content lays out as if the menu
77
+ were not there. --}}
78
+ <div ref="context-menu" id="{{ menuId }}" data-stx-context-menu class="{{ className }}" style="display: contents">
79
+ <slot />
80
+ </div>
81
+
82
+ <style>
83
+ /*
84
+ * The menus live in one layer. Where the browser has a top layer the layer is
85
+ * a popover, and its own box must not paint or catch the pointer.
86
+ */
87
+ :where([data-stx-context-menu]) {
88
+ --stx-menu-bg: var(--stx-panel, #ffffff);
89
+ --stx-menu-fg: var(--stx-fg, #171717);
90
+ --stx-menu-fg-soft: var(--stx-fg-soft, #737373);
91
+ --stx-menu-line: var(--stx-line, #e5e5e5);
92
+ --stx-menu-active: var(--stx-accent-solid, #2563eb);
93
+ --stx-menu-active-fg: var(--stx-accent-ink, #ffffff);
94
+ --stx-menu-danger: var(--stx-danger, #dc2626);
95
+ --stx-menu-radius: 8px;
96
+ --stx-menu-item-radius: 5px;
97
+ --stx-menu-font-size: 13px;
98
+ --stx-menu-min-width: 11rem;
99
+ }
100
+
101
+ [data-stx-context-menu] > .stx-menu-layer {
102
+ position: fixed;
103
+ inset: 0;
104
+ z-index: 1000;
105
+ width: auto;
106
+ height: auto;
107
+ max-width: none;
108
+ max-height: none;
109
+ margin: 0;
110
+ padding: 0;
111
+ border: 0;
112
+ overflow: visible;
113
+ background: transparent;
114
+ color: inherit;
115
+ pointer-events: none;
116
+ }
117
+ [data-stx-context-menu] > .stx-menu-layer:where([hidden]) { display: none; }
118
+
119
+ .stx-menu-layer > .stx-menu {
120
+ position: fixed;
121
+ top: 0;
122
+ left: 0;
123
+ box-sizing: border-box;
124
+ min-width: var(--stx-menu-min-width);
125
+ max-width: min(24rem, calc(100vw - 16px));
126
+ max-height: calc(100vh - 16px);
127
+ overflow-y: auto;
128
+ padding: 4px;
129
+ border: 1px solid var(--stx-menu-line);
130
+ border-radius: var(--stx-menu-radius);
131
+ background: var(--stx-menu-bg);
132
+ color: var(--stx-menu-fg);
133
+ box-shadow: 0 10px 30px rgb(0 0 0 / 0.16), 0 2px 6px rgb(0 0 0 / 0.08);
134
+ font-size: var(--stx-menu-font-size);
135
+ line-height: 1.35;
136
+ outline: none;
137
+ pointer-events: auto;
138
+ user-select: none;
139
+ -webkit-user-select: none;
140
+ }
141
+
142
+ .stx-menu > .stx-menu-item {
143
+ display: grid;
144
+ grid-template-columns: 1rem 1fr auto;
145
+ align-items: center;
146
+ column-gap: 6px;
147
+ padding: 4px 8px 4px 4px;
148
+ border-radius: var(--stx-menu-item-radius);
149
+ cursor: default;
150
+ outline: none;
151
+ white-space: nowrap;
152
+ }
153
+ .stx-menu > .stx-menu-item:focus {
154
+ background: var(--stx-menu-active);
155
+ color: var(--stx-menu-active-fg);
156
+ }
157
+ .stx-menu > .stx-menu-item[aria-expanded="true"]:not(:focus) {
158
+ background: color-mix(in srgb, var(--stx-menu-fg) 10%, transparent);
159
+ }
160
+ .stx-menu > .stx-menu-item[data-danger]:not(:focus) { color: var(--stx-menu-danger); }
161
+ .stx-menu > .stx-menu-item[data-danger]:focus { background: var(--stx-menu-danger); color: #ffffff; }
162
+
163
+ /* A disabled item can still be reached and read, so it shows where focus is without looking available. */
164
+ .stx-menu > .stx-menu-item[aria-disabled="true"] { color: var(--stx-menu-fg-soft); opacity: 0.6; }
165
+ .stx-menu > .stx-menu-item[aria-disabled="true"]:focus {
166
+ background: color-mix(in srgb, var(--stx-menu-fg) 8%, transparent);
167
+ color: var(--stx-menu-fg-soft);
168
+ }
169
+
170
+ .stx-menu .stx-menu-check { text-align: center; font-size: 0.85em; }
171
+ .stx-menu .stx-menu-label { overflow: hidden; text-overflow: ellipsis; }
172
+ .stx-menu :is(.stx-menu-shortcut, .stx-menu-arrow) {
173
+ margin-left: 1.5rem;
174
+ color: var(--stx-menu-fg-soft);
175
+ font-variant-numeric: tabular-nums;
176
+ }
177
+ .stx-menu > .stx-menu-item:focus:not([aria-disabled="true"]) :is(.stx-menu-shortcut, .stx-menu-arrow) { color: inherit; opacity: 0.85; }
178
+
179
+ .stx-menu > .stx-menu-separator {
180
+ height: 1px;
181
+ margin: 4px 6px;
182
+ background: var(--stx-menu-line);
183
+ }
184
+
185
+ @media (forced-colors: active) {
186
+ .stx-menu > .stx-menu-item:focus { outline: 2px solid Highlight; outline-offset: -2px; }
187
+ }
188
+ </style>
@@ -0,0 +1,117 @@
1
+ # ContextMenu
2
+
3
+ A menu on a right click: submenus, separators, disabled and checked items,
4
+ shortcuts shown, and the whole thing usable from the keyboard.
5
+
6
+ ```html
7
+ <script client>
8
+ const items = [
9
+ { label: 'Copy value', id: 'copy', shortcut: 'Mod+C' },
10
+ { label: 'Copy path', id: 'copy-path', shortcut: 'Shift+Mod+C' },
11
+ { separator: true },
12
+ { label: 'Open in', children: [
13
+ { label: 'Table', id: 'table' },
14
+ { label: 'Graph', id: 'graph' },
15
+ ] },
16
+ { label: 'Delete', id: 'delete', danger: true },
17
+ ]
18
+
19
+ function chosen(detail) {
20
+ // detail.id is 'copy', detail.target the element that was clicked on.
21
+ }
22
+ </script>
23
+
24
+ <ContextMenu :items="items" @select="chosen($event)">
25
+ <div>Right click anywhere in here.</div>
26
+ </ContextMenu>
27
+ ```
28
+
29
+ The tag wraps the content it is the menu for and takes no box of its own
30
+ (`display: contents`). To build the items for whatever was clicked, bind a
31
+ function: `:items="menuFor"` is called with the target element and returns the
32
+ list. An empty list leaves the browser's own menu alone.
33
+
34
+ ## How it works
35
+
36
+ | File | What it is |
37
+ |---|---|
38
+ | `core.ts` | Items and their ids, which item an arrow key or a typed letter lands on, where a menu goes to stay on screen, how a shortcut is written on this platform. No DOM. |
39
+ | `view.ts` | The DOM: one layer holding every open menu, real focus on the items, opening and dismissing. |
40
+ | `ContextMenu.stx` | The template, the styles, and the props and events. |
41
+
42
+ The layer is a popover where the browser has a top layer, so a menu is never
43
+ clipped by an `overflow` or misplaced by a transformed ancestor.
44
+ `@stacksjs/components/context-menu` exports the first two.
45
+
46
+ ## Props
47
+
48
+ | Prop | Default | |
49
+ |---|---|---|
50
+ | `items` | `[]` | A list of items, or a function `(target) => items`. |
51
+ | `label` | `'Context menu'` | The accessible name of the menu. |
52
+ | `disabled` | `false` | A right click gets the browser's own menu. |
53
+ | `id`, `className` | | |
54
+
55
+ An item: `{ label, id?, shortcut?, disabled?, checked?, danger?, children?, value? }`,
56
+ or `{ separator: true }`. `checked` of `true` or `false` makes it a checkbox
57
+ item. `shortcut` is shown, not bound: `Mod+C` is drawn as `⌘C` on a Mac and
58
+ `Ctrl+C` elsewhere. An item without an `id` is named by its position (`3`,
59
+ `3.1`). Separators that divide nothing (first, last, or two in a row) are
60
+ dropped, so a list can be built from optional groups without tidying it.
61
+
62
+ ## Events
63
+
64
+ | Event | Payload |
65
+ |---|---|
66
+ | `@select` | `{ item, id, path, target }`. `target` is the element the menu was opened on. |
67
+ | `@open` | `{ x, y, target, keyboard }` |
68
+ | `@close` | `{ reason }`: `select`, `escape`, `outside`, `blur`, `tab` or `api`. |
69
+
70
+ ## Methods
71
+
72
+ From `componentApi(target)` (`@stacksjs/components/component-api`), where
73
+ `target` is the component's element, its id or a selector: `open(at, items?)`, `close()`, `isOpen()`.
74
+ `at` is `{ x, y }` in the viewport, or an element to open under. `items`
75
+ replaces the menu's own for that one opening, which is how another component's
76
+ `context` event is answered:
77
+
78
+ ```html
79
+ <JsonTree :value="tree" contextMenu @context="menu.open({ x: $event.x, y: $event.y }, itemsFor($event.node))" />
80
+ ```
81
+
82
+ ## Keys
83
+
84
+ | Key | |
85
+ |---|---|
86
+ | Menu key, Shift+F10 | Open the menu under the focused element, on its first item. |
87
+ | Up, Down | Move, skipping separators and wrapping at the ends. |
88
+ | Home, End | First and last item. |
89
+ | Right, Enter, Space | Open a submenu and move into it. |
90
+ | Left, Escape | Close a submenu and go back to the item that opened it. |
91
+ | Enter, Space | Choose the item. |
92
+ | Escape | Close the menu. Focus goes back to where it was. |
93
+ | Tab | Close the menu and move on. |
94
+ | A letter | Jump to the next item starting with it. Typing more narrows it. |
95
+
96
+ A disabled item can be reached and read, and does nothing. The menu is a
97
+ `role="menu"` of `menuitem` and `menuitemcheckbox` rows, with `aria-haspopup`
98
+ and `aria-expanded` on an item that opens a submenu, and `aria-keyshortcuts`
99
+ carrying the shortcut in words.
100
+
101
+ ## Theming
102
+
103
+ `--stx-menu-bg` (the `panel` role), `--stx-menu-fg` (`fg`), `--stx-menu-fg-soft`
104
+ (`fg-soft`), `--stx-menu-line` (`line`), `--stx-menu-active` and
105
+ `--stx-menu-active-fg` (`accent-solid`, `accent-ink`), `--stx-menu-danger`
106
+ (`danger`), and `--stx-menu-radius`, `--stx-menu-item-radius`,
107
+ `--stx-menu-font-size`, `--stx-menu-min-width`.
108
+
109
+ ## Limits of this version
110
+
111
+ - **Shortcuts are labels.** The menu shows them; binding the keys is the
112
+ host's business.
113
+ - **No icons, radio groups or item descriptions.**
114
+ - **No safe triangle.** A submenu opens after a short pause on its item, and
115
+ moving diagonally towards it across another item closes it.
116
+ - **A long press on a touch screen** opens the menu only where the engine
117
+ sends a `contextmenu` event for it.
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The context menu without its stx template.
3
+ *
4
+ * `@stacksjs/components/context-menu`. What a menu is and how it is moved
5
+ * through (`./core`, no DOM), and the view that draws one over any element.
6
+ */
7
+ export * from './core'
8
+ export * from './view'
@@ -0,0 +1,250 @@
1
+ /**
2
+ * What a menu is and how one is moved through. No DOM.
3
+ *
4
+ * The items, which of them the arrow keys can land on, what a typed letter
5
+ * jumps to, where a menu goes so that it stays on screen, and how a shortcut
6
+ * is written on this platform.
7
+ */
8
+
9
+ export interface MenuItem {
10
+ /** Names the item in a `select` event. Left out, the item's position is used (`2`, `2.0`). */
11
+ id?: string
12
+ label?: string
13
+ /** `Mod+C`, `Shift+Mod+P`, `Alt+Enter`, `F2`. `Mod` is Command on a Mac and Control elsewhere. Shown, not bound. */
14
+ shortcut?: string
15
+ disabled?: boolean
16
+ /** A dividing line. Everything else on the item is ignored. */
17
+ separator?: boolean
18
+ /** A submenu. */
19
+ children?: MenuItem[]
20
+ /** `true` or `false` makes the item a checkbox; left out it is a plain item. */
21
+ checked?: boolean
22
+ /** Drawn in the danger colour: delete, discard. */
23
+ danger?: boolean
24
+ /** Anything the host wants back in the `select` event. */
25
+ value?: unknown
26
+ }
27
+
28
+ /** An item as the view draws it: with its id settled and its place in the tree. */
29
+ export interface ResolvedItem extends MenuItem {
30
+ id: string
31
+ /** Indexes from the top menu down to this item. */
32
+ path: number[]
33
+ children?: ResolvedItem[]
34
+ }
35
+
36
+ export interface MenuPoint { x: number, y: number }
37
+ export interface MenuSize { width: number, height: number }
38
+ export interface MenuBox { left: number, top: number, right: number, bottom: number }
39
+
40
+ /**
41
+ * Settle a list of items: every item gets an id, and separators that divide
42
+ * nothing are dropped (one at either end, or two in a row), so a host can
43
+ * build a list out of optional groups without tidying it.
44
+ */
45
+ export function resolveItems(items: readonly MenuItem[] | null | undefined, parent: number[] = []): ResolvedItem[] {
46
+ const resolved: ResolvedItem[] = []
47
+ if (!Array.isArray(items))
48
+ return resolved
49
+
50
+ for (const item of items) {
51
+ if (!item || typeof item !== 'object')
52
+ continue
53
+ if (item.separator) {
54
+ if (resolved.length > 0 && !resolved[resolved.length - 1].separator)
55
+ resolved.push({ separator: true, id: '', path: [] })
56
+ continue
57
+ }
58
+ resolved.push({ ...item, id: item.id == null ? '' : String(item.id), path: [] } as ResolvedItem)
59
+ }
60
+ while (resolved.length > 0 && resolved[resolved.length - 1].separator)
61
+ resolved.pop()
62
+
63
+ resolved.forEach((item, index) => {
64
+ item.path = [...parent, index]
65
+ if (item.separator || item.id === '')
66
+ item.id = item.path.join('.')
67
+ if (!item.separator && Array.isArray(item.children))
68
+ item.children = resolveItems(item.children, item.path)
69
+ })
70
+ return resolved
71
+ }
72
+
73
+ /** Whether the keyboard can land on an item. A disabled item can be read, so it can; a separator cannot. */
74
+ export function isFocusable(item: MenuItem | undefined): boolean {
75
+ return Boolean(item) && !item!.separator
76
+ }
77
+
78
+ /** Whether choosing the item does anything. */
79
+ export function isActionable(item: MenuItem | undefined): boolean {
80
+ return Boolean(item) && !item!.separator && !item!.disabled
81
+ }
82
+
83
+ export function hasSubmenu(item: MenuItem | undefined): boolean {
84
+ return Boolean(item) && !item!.separator && Array.isArray(item!.children) && item!.children!.length > 0
85
+ }
86
+
87
+ /**
88
+ * The item an arrow key moves to from `from`, wrapping at the ends.
89
+ * `from` of -1 is "nothing yet": down goes to the first item and up to the last.
90
+ */
91
+ export function stepIndex(items: readonly MenuItem[], from: number, direction: 1 | -1): number {
92
+ const count = items.length
93
+ if (count === 0)
94
+ return -1
95
+
96
+ let index = from
97
+ for (let tries = 0; tries < count; tries++) {
98
+ index = index < 0 ? (direction === 1 ? 0 : count - 1) : (index + direction + count) % count
99
+ if (isFocusable(items[index]))
100
+ return index
101
+ }
102
+ return -1
103
+ }
104
+
105
+ export function firstIndex(items: readonly MenuItem[]): number {
106
+ return stepIndex(items, -1, 1)
107
+ }
108
+
109
+ export function lastIndex(items: readonly MenuItem[]): number {
110
+ return stepIndex(items, -1, -1)
111
+ }
112
+
113
+ /**
114
+ * The item a typed string jumps to. A single repeated letter cycles through
115
+ * the items starting with it; anything longer is a prefix, searched from the
116
+ * current item so typing more keeps the match.
117
+ */
118
+ export function typeAheadIndex(items: readonly MenuItem[], from: number, typed: string): number {
119
+ const query = typed.toLowerCase()
120
+ if (query === '' || items.length === 0)
121
+ return -1
122
+
123
+ const repeated = query.length > 1 && query.split('').every(letter => letter === query.charAt(0))
124
+ const needle = repeated ? query.charAt(0) : query
125
+ const start = query.length === 1 || repeated ? from + 1 : Math.max(from, 0)
126
+
127
+ for (let offset = 0; offset < items.length; offset++) {
128
+ const index = (start + offset + items.length) % items.length
129
+ const item = items[index]
130
+ if (isFocusable(item) && (item.label || '').toLowerCase().startsWith(needle))
131
+ return index
132
+ }
133
+ return -1
134
+ }
135
+
136
+ /** Find an item anywhere in the tree by id. */
137
+ export function findItem(items: readonly ResolvedItem[], id: string): ResolvedItem | null {
138
+ for (const item of items) {
139
+ if (item.separator)
140
+ continue
141
+ if (item.id === id)
142
+ return item
143
+ if (item.children) {
144
+ const found = findItem(item.children, id)
145
+ if (found)
146
+ return found
147
+ }
148
+ }
149
+ return null
150
+ }
151
+
152
+ /**
153
+ * Where a menu opened at a point goes.
154
+ *
155
+ * Down and to the right of the point, as a pointer expects. A menu that would
156
+ * leave the viewport on a side opens the other way from the point instead; one
157
+ * that fits neither way is pushed back inside, so its first items stay
158
+ * reachable.
159
+ */
160
+ export function placeAtPoint(point: MenuPoint, menu: MenuSize, viewport: MenuSize, margin = 8): MenuPoint {
161
+ const fit = (at: number, size: number, limit: number): number => {
162
+ if (at + size <= limit - margin)
163
+ return at
164
+ if (at - size >= margin)
165
+ return at - size
166
+ return Math.max(margin, limit - margin - size)
167
+ }
168
+
169
+ return { x: fit(point.x, menu.width, viewport.width), y: fit(point.y, menu.height, viewport.height) }
170
+ }
171
+
172
+ /** Where a menu anchored to an element goes: under it, aligned to its left edge, or above when there is no room. */
173
+ export function placeAtBox(anchor: MenuBox, menu: MenuSize, viewport: MenuSize, margin = 8, gap = 4): MenuPoint {
174
+ let x = anchor.left
175
+ if (x + menu.width > viewport.width - margin)
176
+ x = Math.max(margin, Math.min(anchor.right - menu.width, viewport.width - margin - menu.width))
177
+
178
+ let y = anchor.bottom + gap
179
+ if (y + menu.height > viewport.height - margin) {
180
+ const above = anchor.top - gap - menu.height
181
+ y = above >= margin ? above : Math.max(margin, viewport.height - margin - menu.height)
182
+ }
183
+ return { x: Math.max(margin, x), y }
184
+ }
185
+
186
+ /**
187
+ * Where a submenu goes: beside the item that opens it, level with it. To the
188
+ * right when it fits, otherwise to the left, and pushed up when it would run
189
+ * off the bottom. `overlap` tucks it slightly under its parent's edge.
190
+ */
191
+ export function placeSubmenu(item: MenuBox, menu: MenuSize, viewport: MenuSize, margin = 8, overlap = 4): MenuPoint & { side: 'right' | 'left' } {
192
+ let side: 'right' | 'left' = 'right'
193
+ let x = item.right - overlap
194
+ if (x + menu.width > viewport.width - margin) {
195
+ const left = item.left + overlap - menu.width
196
+ if (left >= margin) {
197
+ x = left
198
+ side = 'left'
199
+ }
200
+ else {
201
+ x = Math.max(margin, viewport.width - margin - menu.width)
202
+ }
203
+ }
204
+
205
+ const y = Math.max(margin, Math.min(item.top - overlap, viewport.height - margin - menu.height))
206
+ return { x, y, side }
207
+ }
208
+
209
+ const APPLE_SYMBOLS: Record<string, string> = { mod: '⌘', meta: '⌘', cmd: '⌘', command: '⌘', ctrl: '⌃', control: '⌃', alt: '⌥', option: '⌥', shift: '⇧' }
210
+ const OTHER_NAMES: Record<string, string> = { mod: 'Ctrl', meta: 'Win', cmd: 'Ctrl', command: 'Ctrl', ctrl: 'Ctrl', control: 'Ctrl', alt: 'Alt', option: 'Alt', shift: 'Shift' }
211
+ const APPLE_KEYS: Record<string, string> = { enter: '↩', backspace: '⌫', delete: '⌦', escape: '⎋', esc: '⎋', tab: '⇥', arrowup: '↑', arrowdown: '↓', arrowleft: '←', arrowright: '→', space: 'Space' }
212
+ const OTHER_KEYS: Record<string, string> = { escape: 'Esc', esc: 'Esc', delete: 'Del', arrowup: '↑', arrowdown: '↓', arrowleft: '←', arrowright: '→', space: 'Space' }
213
+ // The order a platform writes its modifiers in, whatever order the host gave.
214
+ const APPLE_ORDER = ['ctrl', 'control', 'alt', 'option', 'shift', 'mod', 'meta', 'cmd', 'command']
215
+ const OTHER_ORDER = ['mod', 'ctrl', 'control', 'cmd', 'command', 'meta', 'alt', 'option', 'shift']
216
+
217
+ function splitShortcut(shortcut: string): { modifiers: string[], key: string } {
218
+ // A trailing `+` is the plus key itself: `Mod++`.
219
+ const parts = shortcut.endsWith('++') ? [...shortcut.slice(0, -2).split('+'), '+'] : shortcut.split('+')
220
+ const cleaned = parts.map(part => part.trim()).filter(part => part !== '')
221
+ const key = cleaned.pop() || ''
222
+ return { modifiers: cleaned.map(part => part.toLowerCase()), key }
223
+ }
224
+
225
+ function capitalize(key: string): string {
226
+ return key.length === 1 ? key.toUpperCase() : key.charAt(0).toUpperCase() + key.slice(1)
227
+ }
228
+
229
+ /** A shortcut as this platform writes it: `⇧⌘P` on a Mac, `Ctrl+Shift+P` elsewhere. */
230
+ export function formatShortcut(shortcut: string | undefined, apple: boolean): string {
231
+ if (!shortcut)
232
+ return ''
233
+ const { modifiers, key } = splitShortcut(shortcut)
234
+ const order = apple ? APPLE_ORDER : OTHER_ORDER
235
+ const sorted = [...modifiers].sort((a, b) => order.indexOf(a) - order.indexOf(b))
236
+ const names = sorted.map(modifier => (apple ? APPLE_SYMBOLS : OTHER_NAMES)[modifier] ?? capitalize(modifier))
237
+ const keyName = (apple ? APPLE_KEYS : OTHER_KEYS)[key.toLowerCase()] ?? capitalize(key)
238
+
239
+ return apple ? names.join('') + keyName : [...new Set(names), keyName].join('+')
240
+ }
241
+
242
+ /** The same shortcut for `aria-keyshortcuts`, which has its own spelling. */
243
+ export function ariaShortcut(shortcut: string | undefined, apple: boolean): string {
244
+ if (!shortcut)
245
+ return ''
246
+ const { modifiers, key } = splitShortcut(shortcut)
247
+ const names: Record<string, string> = { mod: apple ? 'Meta' : 'Control', meta: 'Meta', cmd: 'Meta', command: 'Meta', ctrl: 'Control', control: 'Control', alt: 'Alt', option: 'Alt', shift: 'Shift' }
248
+
249
+ return [...new Set(modifiers.map(modifier => names[modifier] ?? capitalize(modifier))), capitalize(key)].join('+')
250
+ }
@@ -0,0 +1,16 @@
1
+ import type { MenuItem } from './core'
2
+
3
+ export { default as ContextMenu } from './ContextMenu.stx'
4
+ export * from './core'
5
+ export * from './view'
6
+
7
+ export interface ContextMenuProps {
8
+ /** The items, or a function that builds them for the element the menu was opened on. */
9
+ items?: MenuItem[] | ((target: Element | null) => MenuItem[] | null | undefined)
10
+ /** The accessible name of the menu. Default `Context menu`. */
11
+ label?: string
12
+ /** A right click gets the browser's own menu. */
13
+ disabled?: boolean
14
+ id?: string
15
+ className?: string
16
+ }