@stacksjs/defaults 0.75.497 → 0.75.500

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.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: stacks-actions
3
- description: Use when working with Stacks server actions - creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 716 default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/app/Actions/.
3
+ description: Use when working with Stacks server actions - creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 720 default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/app/Actions/.
4
4
  license: MIT
5
5
  compatibility: Bun >= 1.3.0, TypeScript
6
6
  allowed-tools: Read Edit Write Bash Grep Glob
@@ -748,3 +748,29 @@ numeric `highlight` values to order pinned rows. Other enabled Data models live
748
748
  under the native Sidebar's collapsed More models disclosure. Labels, icons and
749
749
  role gates apply to nested rows too. `enabled: false` omits navigation;
750
750
  `access: false` excludes generic catalogs and reads as well.
751
+
752
+ ### Personal sidebar order
753
+
754
+ Drag the grip on a section or item to reorder it. Focus a grip and press the
755
+ up/down arrow keys for the same operation. Items remain within their sibling
756
+ group, and moving a parent carries its descendants. Links, disclosure state,
757
+ role gates and model visibility remain owned by the shared Sidebar.
758
+
759
+ The guarded `GET|PUT /api/dashboard/sidebar-order` Actions persist identifiers
760
+ only in a machine-local file outside the checkout. `config/dashboard.ts` and
761
+ model `dashboard.highlight` values remain the team defaults. Reset order
762
+ restores the current defaults; new rows append in team order, and removed rows
763
+ cannot be resurrected by old preferences.
764
+
765
+ Files live under `$XDG_CONFIG_HOME/stacks/dashboard/`, or
766
+ `~/Library/Application Support/stacks/dashboard/` on macOS and
767
+ `~/.config/stacks/dashboard/` elsewhere. Canonical project-root and viewer
768
+ hashes isolate projects and authenticated users. The local developer dashboard
769
+ uses the local viewer. Writes are atomic and owner-readable; API reads are
770
+ private/no-store. These preferences survive framework upgrades and runtime
771
+ cache cleanup. They belong on the machine serving the dashboard, so browsers
772
+ and Craft windows connected to that project share the saved order.
773
+
774
+ The current Inbox SDK requires the S3 mailbox provider. Native IMAP/SMTP mail
775
+ servers do not publish Inbox/Mail Activity links; captured outgoing mail remains
776
+ available. Mail Settings requires the native MailPreference schema.
@@ -11,7 +11,7 @@ Browser runtime bindings are documented separately in `stacks-auto-imports`.
11
11
  | Package | Task guidance | Source entry | Retained tests |
12
12
  |---|---|---|---|
13
13
  | `@stacksjs/action-runner` | [`stacks-actions`](../stacks-actions/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/action-runner/src/index.ts) | 1 |
14
- | `@stacksjs/actions` | [`stacks-actions`](../stacks-actions/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/index.ts) | 106 |
14
+ | `@stacksjs/actions` | [`stacks-actions`](../stacks-actions/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/index.ts) | 107 |
15
15
  | `@stacksjs/ai` | [`stacks-ai`](../stacks-ai/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/ai/src/index.ts) | 21 |
16
16
  | `@stacksjs/alias` | [`stacks-alias`](../stacks-alias/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/alias/src/index.ts) | 3 |
17
17
  | `@stacksjs/analytics` | [`stacks-analytics`](../stacks-analytics/SKILL.md) | [entrypoint](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/analytics/src/index.ts) | 7 |
@@ -119,7 +119,7 @@ Declared runtime exports: `BlogAdminError`, `DEFAULT_IOS_DEPENDENCIES`, `DEFAULT
119
119
 
120
120
  Local source modules: [src/action.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/action.ts), [src/add.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/add.ts), [src/blog-admin.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/blog-admin.ts), [src/build/ios-toolchain.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/build/ios-toolchain.ts), [src/build/macos-native.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/build/macos-native.ts), [src/commit.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/commit.ts), [src/dev/index.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/dev/index.ts), [src/discover-packages.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/discover-packages.ts), [src/generate/index.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/generate/index.ts), [src/github-release.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/github-release.ts), [src/helpers/index.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/helpers/index.ts), [src/library/index.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/library/index.ts), [src/lint/lint.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/lint/lint.ts), [src/lint/stx-gate.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/lint/stx-gate.ts), [src/make-command.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/make-command.ts), [src/make-job.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/make-job.ts), [src/make-policy.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/make-policy.ts), [src/make-resource.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/make-resource.ts), [src/make.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/make.ts), [src/publication-preflight.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/publication-preflight.ts), [src/release-evidence.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/release-evidence.ts), [src/reviewos-evidence.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/reviewos-evidence.ts), [src/scaffold-crud.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/scaffold-crud.ts), [src/setup/index.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/setup/index.ts), [src/stacks.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/stacks.ts), [src/stx-source.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/stx-source.ts), [src/upgrade/package-project.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/upgrade/package-project.ts), [src/upgrade/route-actions.ts](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/src/upgrade/route-actions.ts).
121
121
 
122
- Evidence directory: [106 retained tests](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/tests). These files are evidence pointers, not a claim that all tests were run for this catalog.
122
+ Evidence directory: [107 retained tests](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/actions/tests). These files are evidence pointers, not a claim that all tests were run for this catalog.
123
123
 
124
124
  ### @stacksjs/ai
125
125
 
@@ -0,0 +1,22 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
2
+ import { Action } from '@stacksjs/actions/runtime'
3
+ import { response } from '@stacksjs/router'
4
+ import { readSidebarOrder, sidebarOrderScope } from './sidebar-order-store'
5
+ import { sidebarOrderViewer } from './sidebar-order-viewer'
6
+ import { dashboardOperationalError } from '../dashboard-response'
7
+
8
+ export default new Action({
9
+ name: 'SidebarOrderShowAction', method: 'GET', apiResponse: true,
10
+ description: 'Loads the current viewer\'s machine-local sidebar order.',
11
+ responses: {
12
+ 200: { description: 'The saved order, viewer scope and any recoverable file warning.', schema: { type: 'object', additionalProperties: true } },
13
+ 503: { description: 'The local preference file could not be read.' },
14
+ },
15
+ async handle(request: RequestInstance) {
16
+ try {
17
+ const location = { viewer: await sidebarOrderViewer(request) }
18
+ return response.json({ ...await readSidebarOrder(location), scope: sidebarOrderScope(location) }, { headers: { 'Cache-Control': 'private, no-store' } })
19
+ }
20
+ catch (error) { return dashboardOperationalError(error, 'Sidebar order could not be loaded.', 'SidebarOrderShowAction', 503) }
21
+ },
22
+ })
@@ -0,0 +1,35 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
2
+ import { Action } from '@stacksjs/actions/runtime'
3
+ import { response } from '@stacksjs/router'
4
+ import { schema } from '@stacksjs/validation/runtime'
5
+ import { sidebarOrderScope, writeSidebarOrder } from './sidebar-order-store'
6
+ import { sidebarOrderViewer } from './sidebar-order-viewer'
7
+ import { dashboardOperationalError } from '../dashboard-response'
8
+
9
+ export default new Action({
10
+ name: 'SidebarOrderUpdateAction', method: 'PUT', apiResponse: true,
11
+ description: 'Atomically saves personal sidebar identifiers without editing team defaults.',
12
+ validations: {
13
+ order: { rule: schema.object({}).required() },
14
+ scope: { rule: schema.string().min(32).max(32).required() },
15
+ },
16
+ responses: {
17
+ 200: { description: 'The saved personal order.', schema: { type: 'object', additionalProperties: true } },
18
+ 409: { description: 'The viewer or project changed since the order was loaded.' },
19
+ 422: { description: 'The order payload is invalid or exceeds its bounds.' },
20
+ 503: { description: 'The local preference file could not be written.' },
21
+ },
22
+ async handle(request: RequestInstance) {
23
+ try {
24
+ const location = { viewer: await sidebarOrderViewer(request) }
25
+ if (request.get('scope') !== sidebarOrderScope(location))
26
+ return response.json({ message: 'The dashboard viewer changed. Reload sidebar order before saving.' }, 409)
27
+ const order = await writeSidebarOrder(request.get('order'), location)
28
+ return response.json({ order }, { headers: { 'Cache-Control': 'private, no-store' } })
29
+ }
30
+ catch (error) {
31
+ if (error instanceof TypeError) return response.json({ message: error.message }, 422)
32
+ return dashboardOperationalError(error, 'Sidebar order could not be saved.', 'SidebarOrderUpdateAction', 503)
33
+ }
34
+ },
35
+ })
@@ -0,0 +1,49 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
3
+ import { realpathSync } from 'node:fs'
4
+ import { homedir } from 'node:os'
5
+ import { dirname, join, resolve } from 'node:path'
6
+ import { emptySidebarOrder, parseSidebarOrder, type SidebarOrder } from '../../../../resources/functions/dashboard/sidebar-order'
7
+
8
+ export interface SidebarOrderLocation { projectRoot?: string, configHome?: string, viewer?: string }
9
+ const hash = (value: string) => createHash('sha256').update(value).digest('hex').slice(0, 32)
10
+
11
+ /** Outside the checkout: runtime/cache cleanup and framework upgrades preserve personal order. */
12
+ export function sidebarOrderPath(options: SidebarOrderLocation = {}): string {
13
+ const root = realpathSync(options.projectRoot ?? process.cwd())
14
+ const configHome = options.configHome ?? process.env.XDG_CONFIG_HOME
15
+ ?? (process.platform === 'darwin' ? join(homedir(), 'Library/Application Support') : join(homedir(), '.config'))
16
+ return join(resolve(configHome), 'stacks/dashboard', hash(root), `${hash(options.viewer ?? 'local')}.json`)
17
+ }
18
+
19
+ export const sidebarOrderScope = (options: SidebarOrderLocation = {}): string => hash(sidebarOrderPath(options))
20
+
21
+ export async function readSidebarOrder(options: SidebarOrderLocation = {}): Promise<{ order: SidebarOrder, warning?: string }> {
22
+ const path = sidebarOrderPath(options)
23
+ try {
24
+ if ((await stat(path)).size > 256 * 1024) throw new SyntaxError('Oversized sidebar preferences')
25
+ const source = await readFile(path, 'utf8')
26
+ try { return { order: parseSidebarOrder(JSON.parse(source)) } }
27
+ catch { return { order: emptySidebarOrder(), warning: 'Saved sidebar order is invalid. Team defaults are shown; reset order to replace it.' } }
28
+ }
29
+ catch (error) {
30
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { order: emptySidebarOrder() }
31
+ if (error instanceof SyntaxError) return { order: emptySidebarOrder(), warning: 'Saved sidebar order is invalid. Team defaults are shown; reset order to replace it.' }
32
+ throw error
33
+ }
34
+ }
35
+
36
+ export async function writeSidebarOrder(value: unknown, options: SidebarOrderLocation = {}): Promise<SidebarOrder> {
37
+ const order = parseSidebarOrder(value)
38
+ const path = sidebarOrderPath(options)
39
+ const temporary = `${path}.${randomUUID()}.tmp`
40
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 })
41
+ // Resolve before writing so a missing project is never mistaken for another project.
42
+ await realpath(options.projectRoot ?? process.cwd())
43
+ try {
44
+ await writeFile(temporary, `${JSON.stringify(order, null, 2)}\n`, { mode: 0o600, flag: 'wx' })
45
+ await rename(temporary, path)
46
+ }
47
+ finally { await rm(temporary, { force: true }) }
48
+ return order
49
+ }
@@ -0,0 +1,9 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
2
+ import { isLocalDeployment } from '@stacksjs/env'
3
+
4
+ export async function sidebarOrderViewer(request: RequestInstance): Promise<string> {
5
+ if (isLocalDeployment()) return 'local'
6
+ const user = await request.user()
7
+ if (!user?.id) throw new Error('Authenticated sidebar viewer is required.')
8
+ return `user:${user.id}`
9
+ }
@@ -0,0 +1,245 @@
1
+ import type { WebSidebarItem, WebSidebarSection } from '../resources/functions/dashboard/sidebar'
2
+ import { emptySidebarOrder, orderSidebarSections, parseSidebarOrder, sidebarGroupKey, type SidebarOrder } from '../resources/functions/dashboard/sidebar-order'
3
+ import { dashboardApi, DashboardApiError } from './dashboard-api'
4
+
5
+ interface OrderStatus { ready: boolean, saving: boolean, custom: boolean, message: string }
6
+ interface Target { kind: 'section' | 'item', id: string, group: string, element: HTMLElement, label: string }
7
+
8
+ /** Enhances the shared Sidebar's public DOM contract, without cloning its navigation or disclosure controller. */
9
+ export function createDashboardSidebarOrder(options: {
10
+ pane: () => HTMLElement | null | undefined
11
+ sections: WebSidebarSection[]
12
+ status: (status: OrderStatus) => void
13
+ }) {
14
+ let order = emptySidebarOrder()
15
+ let acknowledged = order
16
+ let ready = false
17
+ let destroyed = false
18
+ let pending = 0
19
+ let revision = 0
20
+ let scope = ''
21
+ let writes = Promise.resolve()
22
+ let detach = () => {}
23
+ let message = 'Loading sidebar order…'
24
+ const abort = new AbortController()
25
+ const handles: HTMLButtonElement[] = []
26
+ const targets = new Map<HTMLElement, Target>()
27
+ const groups = new Map<string, string[]>()
28
+ const custom = () => order.sections.length > 0 || Object.keys(order.items).length > 0
29
+ function status() {
30
+ if (destroyed) return
31
+ options.status({ ready, saving: pending > 0, custom: custom(), message })
32
+ for (const handle of handles) handle.disabled = !ready
33
+ }
34
+
35
+ function apply() {
36
+ if (destroyed) return
37
+ const pane = options.pane()
38
+ if (!pane) return
39
+ const sectionNodes = new Map([...pane.querySelectorAll<HTMLElement>('[data-sidebar-section]')].map(node => [node.dataset.sectionId!, node]))
40
+ const sorted = orderSidebarSections(options.sections, order)
41
+ groups.set('sections', sorted.map(section => section.id))
42
+ function visit(items: WebSidebarItem[], section: string, ancestors: string[] = []) {
43
+ groups.set(sidebarGroupKey(section, ancestors), items.map(item => item.id))
44
+ const parent = sectionNodes.get(section)
45
+ for (const item of items) {
46
+ const row = [...(parent?.querySelectorAll<HTMLElement>('[data-sidebar-row]') ?? [])].find(node => node.dataset.itemId === item.id)
47
+ if (row) row.parentElement!.append(row)
48
+ if (item.children) visit(item.children, section, [...ancestors, item.id])
49
+ }
50
+ }
51
+ for (const section of sorted) {
52
+ const node = sectionNodes.get(section.id)
53
+ if (node) node.parentElement!.append(node)
54
+ visit(section.items, section.id)
55
+ }
56
+ }
57
+
58
+ function save(next: SidebarOrder) {
59
+ const mine = ++revision
60
+ const writeScope = scope
61
+ order = next
62
+ pending++
63
+ message = 'Saving sidebar order…'
64
+ apply()
65
+ status()
66
+ // Mutations are serialized, so an older slow response cannot overwrite the final drop.
67
+ writes = writes.then(async () => {
68
+ try {
69
+ const result = await dashboardApi<{ order: SidebarOrder }>('/api/dashboard/sidebar-order', { method: 'PUT', body: { order: next, scope: writeScope } })
70
+ acknowledged = parseSidebarOrder(result.order)
71
+ if (mine === revision) message = 'Order saved on this machine.'
72
+ }
73
+ catch (error) {
74
+ if (error instanceof DashboardApiError && error.status === 409) ready = false
75
+ if (mine === revision) { order = acknowledged; apply() }
76
+ message = error instanceof Error ? error.message : 'Sidebar order could not be saved.'
77
+ }
78
+ finally { pending--; status() }
79
+ })
80
+ }
81
+
82
+ function move(source: Target, target: Target, after: boolean) {
83
+ if (!ready || source.kind !== target.kind || source.group !== target.group || source.id === target.id) return
84
+ const current = groups.get(source.group) ?? []
85
+ const next = current.filter(id => id !== source.id)
86
+ const index = next.indexOf(target.id)
87
+ if (index < 0 || !current.includes(source.id)) return
88
+ next.splice(index + Number(after), 0, source.id)
89
+ if (next.join('\0') === current.join('\0')) return
90
+ save(source.kind === 'section'
91
+ ? { ...order, sections: next }
92
+ : { ...order, items: { ...order.items, [source.group]: next } })
93
+ for (const [handle, target] of targets) {
94
+ if (target === source) handle.focus({ preventScroll: true })
95
+ }
96
+ }
97
+
98
+ function attach() {
99
+ detach()
100
+ const pane = options.pane()
101
+ if (!pane || destroyed) return
102
+ pane.setAttribute('data-dashboard-sidebar-order', '')
103
+ const findRow = (section: HTMLElement, id: string) => [...section.querySelectorAll<HTMLElement>('[data-sidebar-row]')].find(row => row.dataset.itemId === id)
104
+ function grip(target: Target) {
105
+ const button = pane!.ownerDocument.createElement('button')
106
+ button.type = 'button'
107
+ button.className = 'dashboard-sidebar-order-grip'
108
+ button.dataset.sidebarOrderHandle = target.kind
109
+ button.setAttribute('aria-label', `Reorder ${target.label}`)
110
+ button.title = 'Drag to reorder, or use the up and down arrow keys.'
111
+ button.setAttribute('aria-keyshortcuts', 'ArrowUp ArrowDown Escape')
112
+ const icon = pane!.ownerDocument.createElement('span')
113
+ icon.className = 'i-hugeicons-drag-drop-vertical'
114
+ icon.setAttribute('aria-hidden', 'true')
115
+ button.append(icon)
116
+ target.element.append(button)
117
+ targets.set(button, target)
118
+ handles.push(button)
119
+ }
120
+ for (const section of options.sections) {
121
+ const node = [...pane.querySelectorAll<HTMLElement>('[data-sidebar-section]')].find(element => element.dataset.sectionId === section.id)
122
+ if (!node) continue
123
+ grip({ kind: 'section', id: section.id, group: 'sections', element: node, label: `${section.label || 'Home'} section` })
124
+ function visit(items: WebSidebarItem[], ancestors: string[] = []) {
125
+ for (const item of items) {
126
+ const row = findRow(node!, item.id)
127
+ if (row && items.length > 1) grip({ kind: 'item', id: item.id, group: sidebarGroupKey(section.id, ancestors), element: row, label: item.label })
128
+ if (item.children) visit(item.children, [...ancestors, item.id])
129
+ }
130
+ }
131
+ visit(section.items)
132
+ }
133
+ let drag: { source: Target, handle: HTMLElement, x: number, y: number, pointer: number, moved: boolean } | undefined
134
+ let destination: { target: Target, after: boolean } | undefined
135
+ function clear() {
136
+ const previous = drag
137
+ drag = undefined
138
+ if (previous?.handle.hasPointerCapture(previous.pointer)) previous.handle.releasePointerCapture(previous.pointer)
139
+ previous?.source.element.removeAttribute('data-order-dragging')
140
+ destination?.target.element.removeAttribute('data-order-drop')
141
+ destination = undefined
142
+ }
143
+ function targetAt(event: PointerEvent): Target | undefined {
144
+ const hit = pane!.ownerDocument.elementFromPoint(event.clientX, event.clientY)
145
+ const element = hit?.closest<HTMLElement>(drag?.source.kind === 'section' ? '[data-sidebar-section]' : '[data-sidebar-row]')
146
+ return [...targets.values()].find(target => target.element === element && target.kind === drag?.source.kind && target.group === drag.source.group)
147
+ }
148
+ function pointerdown(event: PointerEvent) {
149
+ const handle = (event.target as Element).closest<HTMLElement>('[data-sidebar-order-handle]')
150
+ const source = handle && targets.get(handle)
151
+ if (!source || !ready || event.button !== 0) return
152
+ event.preventDefault()
153
+ event.stopPropagation()
154
+ handle.focus()
155
+ handle.setPointerCapture(event.pointerId)
156
+ drag = { source, handle, x: event.clientX, y: event.clientY, pointer: event.pointerId, moved: false }
157
+ }
158
+ function pointermove(event: PointerEvent) {
159
+ if (!drag || drag.pointer !== event.pointerId) return
160
+ if (Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < 5 && !drag.moved) return
161
+ drag.moved = true
162
+ drag.source.element.setAttribute('data-order-dragging', 'true')
163
+ destination?.target.element.removeAttribute('data-order-drop')
164
+ destination = undefined
165
+ const target = targetAt(event)
166
+ if (!target || target.id === drag.source.id) return
167
+ const rect = (target.kind === 'section' ? target.element.querySelector('[data-sidebar-section-header]') ?? target.element : target.element).getBoundingClientRect()
168
+ const after = event.clientY >= rect.top + Math.min(rect.height, 40) / 2
169
+ destination = { target, after }
170
+ target.element.setAttribute('data-order-drop', after ? 'after' : 'before')
171
+ const scroll = pane!.querySelector<HTMLElement>('[data-sidebar-scroll]') ?? pane!
172
+ const bounds = scroll.getBoundingClientRect()
173
+ if (event.clientY < bounds.top + 36) scroll.scrollBy(0, -24)
174
+ else if (event.clientY > bounds.bottom - 36) scroll.scrollBy(0, 24)
175
+ }
176
+ function pointerup(event: PointerEvent) {
177
+ if (!drag || event.pointerId !== drag.pointer) return
178
+ const source = drag.source
179
+ const drop = drag.moved ? destination : undefined
180
+ clear()
181
+ if (drop) move(source, drop.target, drop.after)
182
+ }
183
+ function keydown(event: KeyboardEvent) {
184
+ if (event.key === 'Escape' && drag) { clear(); event.preventDefault(); event.stopPropagation(); return }
185
+ const target = targets.get(event.target as HTMLElement)
186
+ if (!target || !ready || !['ArrowUp', 'ArrowDown'].includes(event.key)) return
187
+ event.preventDefault()
188
+ event.stopPropagation()
189
+ const visible = [...targets.values()].filter(item => item.kind === target.kind && item.group === target.group && item.element.getBoundingClientRect().height > 0 && getComputedStyle(item.element).display !== 'none')
190
+ const ids = (groups.get(target.group) ?? []).filter(id => visible.some(item => item.id === id))
191
+ const next = ids[ids.indexOf(target.id) + (event.key === 'ArrowUp' ? -1 : 1)]
192
+ const neighbor = visible.find(item => item.id === next)
193
+ if (neighbor) move(target, neighbor, event.key === 'ArrowDown')
194
+ }
195
+ function click(event: MouseEvent) {
196
+ if ((event.target as Element).closest('[data-sidebar-order-handle]')) { event.preventDefault(); event.stopPropagation() }
197
+ }
198
+ pane.addEventListener('pointerdown', pointerdown, true)
199
+ pane.addEventListener('pointermove', pointermove, true)
200
+ pane.addEventListener('pointerup', pointerup, true)
201
+ pane.addEventListener('pointercancel', clear, true)
202
+ pane.addEventListener('lostpointercapture', clear, true)
203
+ pane.addEventListener('keydown', keydown, true)
204
+ pane.addEventListener('click', click, true)
205
+ detach = () => {
206
+ clear()
207
+ pane.removeEventListener('pointerdown', pointerdown, true)
208
+ pane.removeEventListener('pointermove', pointermove, true)
209
+ pane.removeEventListener('pointerup', pointerup, true)
210
+ pane.removeEventListener('pointercancel', clear, true)
211
+ pane.removeEventListener('lostpointercapture', clear, true)
212
+ pane.removeEventListener('keydown', keydown, true)
213
+ pane.removeEventListener('click', click, true)
214
+ for (const handle of handles) handle.remove()
215
+ handles.length = 0
216
+ targets.clear()
217
+ pane.removeAttribute('data-dashboard-sidebar-order')
218
+ }
219
+ apply()
220
+ status()
221
+ }
222
+
223
+ async function load() {
224
+ ready = false
225
+ status()
226
+ try {
227
+ const result = await dashboardApi<{ order: SidebarOrder, scope: string, warning?: string }>('/api/dashboard/sidebar-order', { signal: abort.signal })
228
+ if (destroyed) return
229
+ order = acknowledged = parseSidebarOrder(result.order)
230
+ scope = result.scope
231
+ ready = true
232
+ message = result.warning || 'Drag grips to reorder. Arrow keys also work.'
233
+ apply()
234
+ }
235
+ catch (error) { if (!destroyed) message = error instanceof Error ? error.message : 'Sidebar order could not be loaded.' }
236
+ status()
237
+ }
238
+
239
+ return {
240
+ attach,
241
+ load,
242
+ reset() { if (ready) save(emptySidebarOrder()) },
243
+ destroy() { destroyed = true; abort.abort(); detach() },
244
+ }
245
+ }
@@ -2,7 +2,7 @@
2
2
  "publisher": "Stacks",
3
3
  "name": "vscode-stacks",
4
4
  "displayName": "Stacks",
5
- "version": "0.75.497",
5
+ "version": "0.75.500",
6
6
  "description": "Stacks, built into VS Code: stx templates, pickier linting and formatting, encrypted env files, the dev server preview and every buddy command. No other extensions required.",
7
7
  "license": "MIT",
8
8
  "funding": "https://github.com/sponsors/chrisbbreuer",
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/defaults",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.497",
5
+ "version": "0.75.500",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/stacksjs/stacks.git",
@@ -45,10 +45,10 @@
45
45
  "dependencies": {
46
46
  "@iconify-json/f7": "^1.2.2",
47
47
  "@iconify-json/hugeicons": "^1.2.35",
48
- "@stacksjs/mobile": "0.75.497",
48
+ "@stacksjs/mobile": "0.75.500",
49
49
  "@stacksjs/sanitizer": "0.2.807",
50
50
  "@stacksjs/stx": "0.2.807",
51
- "@stacksjs/strings": "0.75.497",
51
+ "@stacksjs/strings": "0.75.500",
52
52
  "@xterm/addon-fit": "^0.11.0",
53
53
  "@xterm/xterm": "^6.0.0",
54
54
  "ts-qr-codes": "^0.1.8"
@@ -0,0 +1,56 @@
1
+ import type { WebSidebarItem, WebSidebarSection } from './sidebar'
2
+
3
+ /** Personal order contains identifiers only. Labels, access and hierarchy remain team-owned. */
4
+ export interface SidebarOrder {
5
+ version: 1
6
+ sections: string[]
7
+ items: Record<string, string[]>
8
+ }
9
+
10
+ export const emptySidebarOrder = (): SidebarOrder => ({ version: 1, sections: [], items: {} })
11
+ export const sidebarGroupKey = (section: string, ancestors: string[] = []): string => JSON.stringify([section, ...ancestors])
12
+
13
+ export function parseSidebarOrder(value: unknown): SidebarOrder {
14
+ const input = value as Partial<SidebarOrder> | null
15
+ if (!input || input.version !== 1 || !Array.isArray(input.sections) || !input.items || typeof input.items !== 'object' || Array.isArray(input.items))
16
+ throw new TypeError('Invalid sidebar order.')
17
+ const ids = (list: unknown, max: number): string[] => {
18
+ if (!Array.isArray(list) || list.length > max || list.some(id => typeof id !== 'string' || !id || id.length > 256) || new Set(list).size !== list.length)
19
+ throw new TypeError('Invalid sidebar order identifiers.')
20
+ return [...list]
21
+ }
22
+ const entries = Object.entries(input.items)
23
+ if (entries.length > 2048) throw new TypeError('Too many sidebar groups.')
24
+ const items: Record<string, string[]> = Object.create(null)
25
+ for (const [key, list] of entries) {
26
+ if (key.length > 4096) throw new TypeError('Invalid sidebar group.')
27
+ let path: unknown
28
+ try { path = JSON.parse(key) }
29
+ catch { throw new TypeError('Invalid sidebar group.') }
30
+ ids(path, 32)
31
+ if (!(path as string[]).length) throw new TypeError('Invalid sidebar group.')
32
+ items[key] = ids(list, 2048)
33
+ }
34
+ if (JSON.stringify(input).length > 256 * 1024) throw new TypeError('Sidebar order is too large.')
35
+ return { version: 1, sections: ids(input.sections, 128), items }
36
+ }
37
+
38
+ function ordered<T extends { id: string }>(defaults: T[], ids: string[] = []): T[] {
39
+ const byId = new Map(defaults.map(item => [item.id, item]))
40
+ const result: T[] = []
41
+ for (const id of ids) {
42
+ const item = byId.get(id)
43
+ if (item) { result.push(item); byId.delete(id) }
44
+ }
45
+ return [...result, ...defaults.filter(item => byId.has(item.id))]
46
+ }
47
+
48
+ /** Missing/deleted identifiers cannot resurrect a row; new team rows append in team order. */
49
+ export function orderSidebarSections(sections: WebSidebarSection[], order: SidebarOrder): WebSidebarSection[] {
50
+ const visit = (items: WebSidebarItem[], section: string, ancestors: string[] = []): WebSidebarItem[] =>
51
+ ordered(items, order.items[sidebarGroupKey(section, ancestors)]).map(item => ({
52
+ ...item,
53
+ ...(item.children && { children: visit(item.children, section, [...ancestors, item.id]) }),
54
+ }))
55
+ return ordered(sections, order.sections).map(section => ({ ...section, items: visit(section.items, section.id) }))
56
+ }
@@ -201,18 +201,21 @@ function normalizeSchemaModels(value: unknown): string[] {
201
201
  }
202
202
 
203
203
  /** Hide built-in modules whose backing models are outside this app's schema. */
204
- export function filterSchemaNavSections(sections: Array<[string, string, NavItem[]]>, schemaModels?: readonly string[]): Array<[string, string, NavItem[]]> {
205
- if (!schemaModels) return sections
206
- const available = new Set(schemaModels)
204
+ export function filterSchemaNavSections(sections: Array<[string, string, NavItem[]]>, schemaModels?: readonly string[], capabilities: { inbox?: boolean } = {}): Array<[string, string, NavItem[]]> {
205
+ if (!schemaModels && capabilities.inbox !== false) return sections
206
+ const available = schemaModels ? new Set(schemaModels) : undefined
207
207
  const required: Record<string, string[]> = {
208
208
  '/activity': ['Activity'], '/teams': ['Team'], '/subscribers': ['Subscriber'],
209
209
  '/releases': ['Release'], '/deployments': ['Deployment'], '/requests': ['Request'],
210
210
  '/queries': ['QueryLog'], '/queries/slow': ['QueryLog'], '/queries/history': ['QueryLog'],
211
211
  '/errors': ['Error'], '/notifications/dashboard': ['Notification'], '/logs': ['Log'],
212
212
  '/management/permissions': ['Role', 'Permission'], '/kanban': ['Board', 'Card', 'Column'],
213
+ '/data/activity': ['Activity'], '/data/teams': ['Team'], '/data/subscribers': ['Subscriber'],
214
+ '/inbox/settings': ['MailPreference'],
213
215
  }
214
216
  return sections.map(([id, label, items]): [string, string, NavItem[]] => [id, label, id.startsWith('app-nav-') ? items : items.filter(item =>
215
- (required[item.to] ?? []).every(model => available.has(model)))])
217
+ (!(capabilities.inbox === false && ['/inbox', '/inbox/activity'].includes(item.to))
218
+ && (required[item.to] ?? []).every(model => !available || available.has(model))))])
216
219
  .filter(([, , items]) => items.length > 0)
217
220
  }
218
221
 
@@ -744,7 +747,12 @@ function loadAppNavFromConfig(configPath = resolve(process.cwd(), 'config/dashbo
744
747
  export function buildWebSidebarSections(): WebSidebarSection[] {
745
748
  const manifest = loadDiscoveredManifest()
746
749
  const appNav = manifest.nav.length > 0 ? manifest.nav : loadAppNavFromConfig()
747
- const sections = filterSchemaNavSections(buildNavSections(manifest.models, manifest.sections, appNav), manifest.schemaModels)
750
+ const { config } = createRequire(import.meta.url)('@stacksjs/config')
751
+ // The current inbox SDK reads S3 objects. The native IMAP/SMTP server does
752
+ // not write that bucket; linking its mailboxes to this UI only produces 503s.
753
+ const mailServer = config.email?.server
754
+ const inbox = !(mailServer?.enabled && (mailServer.mode ?? 'server') === 'server')
755
+ const sections = filterSchemaNavSections(buildNavSections(manifest.models, manifest.sections, appNav), manifest.schemaModels, { inbox })
748
756
 
749
757
  const webItem = (item: NavItem): WebSidebarItem => ({
750
758
  id: item.id ?? navItemId(item.to),
@@ -55,6 +55,8 @@ function authenticatedGuard(r: any): any {
55
55
  }
56
56
 
57
57
  route.group({ prefix: '/api/dashboard', apiResponse: true }, () => {
58
+ guard(route.get('/sidebar-order', 'Actions/Dashboard/Settings/SidebarOrderShowAction'))
59
+ guard(route.put('/sidebar-order', 'Actions/Dashboard/Settings/SidebarOrderUpdateAction'))
58
60
  guard(route.get('/home', 'Actions/Dashboard/DashboardHomeAction'))
59
61
  guard(route.get('/stats', 'Actions/Dashboard/DashboardStatsAction'))
60
62
  guard(route.get('/activity', 'Actions/Dashboard/DashboardActivityAction'))
@@ -35,7 +35,7 @@ export const sidebarRoleMap: Record<string, string[]> = webSidebarRoleMap(sideba
35
35
 
36
36
  // Declared, so the client block below gets the map typed rather than inferred
37
37
  // off the implicit bridge - which is what let the mismatch above go unseen.
38
- defineClientPayload({ sidebarRoleMap })
38
+ defineClientPayload({ sidebarRoleMap, sidebarSections })
39
39
  </script>
40
40
 
41
41
  @head
@@ -400,6 +400,35 @@ html[data-appearance="arc"] [data-sidebar-section] > div:first-child {
400
400
  [data-sidebar-section][data-viewer-hidden="true"] {
401
401
  display: none;
402
402
  }
403
+ /* Grips are separate controls, so dragging never follows a link or toggles disclosure. */
404
+ [data-dashboard-sidebar-order] [data-sidebar-section],
405
+ [data-dashboard-sidebar-order] [data-sidebar-row] { position: relative; }
406
+ [data-dashboard-sidebar-order] [data-sidebar-item] { padding-right: 28px; }
407
+ [data-dashboard-sidebar-order] [data-sidebar-section-header] { padding-right: 50px; }
408
+ .dashboard-sidebar-order-grip {
409
+ position: absolute;
410
+ right: 1px;
411
+ top: 2px;
412
+ width: 24px;
413
+ height: 24px;
414
+ display: grid;
415
+ place-items: center;
416
+ border-radius: 4px;
417
+ color: currentColor;
418
+ opacity: .55;
419
+ cursor: grab;
420
+ touch-action: none;
421
+ }
422
+ .dashboard-sidebar-order-grip[data-sidebar-order-handle="section"] { right: 23px; top: 7px; }
423
+ [data-section-id="top"] > .dashboard-sidebar-order-grip { right: 1px; top: 2px; }
424
+ .dashboard-sidebar-order-grip > span { display: block; width: 14px; height: 14px; }
425
+ .dashboard-sidebar-order-grip:hover,
426
+ .dashboard-sidebar-order-grip:focus-visible { opacity: 1; background: rgba(127, 127, 127, .16); }
427
+ .dashboard-sidebar-order-grip:focus-visible { outline: 2px solid #3b82f6; outline-offset: -2px; }
428
+ .dashboard-sidebar-order-grip:disabled { cursor: wait; opacity: .25; }
429
+ [data-order-dragging="true"] > .dashboard-sidebar-order-grip { cursor: grabbing; opacity: 1; }
430
+ [data-order-drop="before"] { box-shadow: 0 -2px #3b82f6; }
431
+ [data-order-drop="after"] { box-shadow: 0 2px #3b82f6; }
403
432
  </style>
404
433
 
405
434
  <script client>
@@ -416,6 +445,7 @@ import { ensureCraftNativeSidebarMarker, useCraftSidebarSelection } from '@stack
416
445
  import { readStoredAppearance, useAppearance } from '@stacksjs/defaults/views/dashboard/composables/useAppearance'
417
446
  import { authStore } from '@stacksjs/defaults/views/dashboard/stores/auth'
418
447
  import { kanbanStore } from '@stacksjs/defaults/views/dashboard/stores/kanban'
448
+ import { createDashboardSidebarOrder } from '@stacksjs/defaults/functions/dashboard-sidebar-order'
419
449
  import { rbacStore } from '@stacksjs/defaults/views/dashboard/stores/rbac'
420
450
  const { toasts } = useToasts()
421
451
  registerStoresClient({ authStore, kanbanStore, rbacStore })
@@ -452,6 +482,12 @@ const auth = authStore
452
482
  const route = useRoute()
453
483
  const sidebarHost = useRef('dashboardSidebarHost')
454
484
  const mobileSidebarHost = useRef('dashboardMobileSidebarHost')
485
+ const sidebarOrderStatus = state({ ready: false, saving: false, custom: false, message: 'Loading sidebar order…' })
486
+ const sidebarOrder = createDashboardSidebarOrder({
487
+ pane: () => sidebarPanes()[0],
488
+ sections: sidebarSections,
489
+ status: value => sidebarOrderStatus.set(value),
490
+ })
455
491
  let removeCraftSidebarSelection = () => {}
456
492
  ensureCraftNativeSidebarMarker()
457
493
  auth.load()
@@ -651,6 +687,8 @@ useEventListener('craft:ready', () => {
651
687
  })
652
688
 
653
689
  onMount(() => {
690
+ sidebarOrder.attach()
691
+ void sidebarOrder.load()
654
692
  syncActiveSidebarRow()
655
693
  applyRoleFilter()
656
694
  applySectionVisibility()
@@ -658,6 +696,7 @@ onMount(() => {
658
696
  })
659
697
 
660
698
  onDestroy(() => {
699
+ sidebarOrder.destroy()
661
700
  removeCraftSidebarSelection()
662
701
  })
663
702
  </script>
@@ -684,6 +723,13 @@ onDestroy(() => {
684
723
  carry above their first row. -->
685
724
  <SidebarHeader windowControls="native" />
686
725
  </template>
726
+ <template #footer>
727
+ <div class="px-3 py-2 text-neutral-600 text-xs dark:text-neutral-300" data-sidebar-order-controls>
728
+ <p role="status" aria-live="polite" :text="sidebarOrderStatus.message"></p>
729
+ <Button :if="!sidebarOrderStatus.ready" variant="ghost" size="xs" @click="sidebarOrder.load()">Retry loading order</Button>
730
+ <Button :if="sidebarOrderStatus.ready" variant="ghost" size="xs" :disabled="sidebarOrderStatus.saving" @click="sidebarOrder.reset()">Reset order</Button>
731
+ </div>
732
+ </template>
687
733
  </Sidebar>
688
734
  </div>
689
735