@getcortexlabs/create-mavis 0.1.0-rc.13 → 0.1.0-rc.15

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 (80) hide show
  1. package/README.md +44 -7
  2. package/package.json +4 -2
  3. package/src/adapters.mjs +56 -20
  4. package/src/add-desktop.mjs +308 -0
  5. package/src/add-macos.mjs +386 -0
  6. package/src/capabilities.mjs +352 -85
  7. package/src/cli.mjs +181 -9
  8. package/src/desktop.mjs +155 -0
  9. package/src/doctor.mjs +181 -18
  10. package/src/macos-capabilities.generated.mjs +4190 -0
  11. package/src/macos.mjs +147 -29
  12. package/src/migrate-directory.mjs +121 -0
  13. package/src/native-framework.mjs +144 -0
  14. package/src/portability.mjs +123 -5
  15. package/src/scaffold.mjs +59 -11
  16. package/src/ui.mjs +69 -12
  17. package/templates/desktop/common/LICENSE +21 -0
  18. package/templates/desktop/common/build.mjs +58 -0
  19. package/templates/desktop/common/src/components.ts +60 -0
  20. package/templates/desktop/common/src/contract.mjs +35 -0
  21. package/templates/desktop/common/src/renderer.ts +76 -0
  22. package/templates/desktop/common/src/storage.ts +29 -0
  23. package/templates/desktop/directory/main.ts +35 -0
  24. package/templates/desktop/macos/launch.mjs +6 -0
  25. package/templates/desktop/macos/package.mjs +114 -0
  26. package/templates/desktop/macos/src/host.mjs +468 -0
  27. package/templates/desktop/macos/src/motion.mjs +51 -0
  28. package/templates/desktop/welcome/Welcome.vue +56 -0
  29. package/templates/desktop/welcome/main.ts +24 -0
  30. package/templates/desktop/windows/NativeScript-LICENSE +19 -0
  31. package/templates/desktop/windows/launch.mjs +16 -0
  32. package/templates/desktop/windows/package.mjs +54 -0
  33. package/templates/desktop/windows/prepare-host.mjs +73 -0
  34. package/templates/desktop/windows/src/host.mjs +277 -0
  35. package/templates/directory/host/directory-storage.ts +78 -0
  36. package/templates/directory/macos/DirectoryStorage.swift +68 -0
  37. package/templates/directory/mobile/src/app.ts +11 -8
  38. package/templates/directory/nuxt/app/plugins/mavis.ts +11 -8
  39. package/templates/directory/shared/Edit.vue +8 -5
  40. package/templates/directory/shared/directory-store.ts +42 -46
  41. package/templates/directory/vite/src/main.ts +11 -8
  42. package/templates/macos/examples/tasks/shared/TaskDetail.lite.tsx +2 -2
  43. package/templates/macos/examples/tasks/shared/Tasks.lite.tsx +2 -2
  44. package/templates/macos/examples/tasks/shared/types.ts +1 -0
  45. package/templates/macos/mobile/src/App.vue +4 -2
  46. package/templates/macos/native/Package.swift +3 -1
  47. package/templates/macos/native/Sources/MavisDesktop/App.swift +26 -11
  48. package/templates/macos/native/Sources/MavisDesktop/Fonts/LICENSE +45 -0
  49. package/templates/macos/native/Sources/MavisDesktop/Fonts/lucide.ttf +0 -0
  50. package/templates/macos/scripts/generate.mjs +3 -26
  51. package/templates/macos/scripts/macos-manifest.mjs +33 -0
  52. package/templates/macos/scripts/macos.mjs +20 -18
  53. package/templates/macos/web/index.html +1 -1
  54. package/templates/macos/web/src/main.js +176 -3
  55. package/templates/macos/web/src/mavis.js +2 -0
  56. package/templates/macos/web/src/style.css +2 -1
  57. package/templates/macos/web/vite.config.mjs +12 -1
  58. package/templates/migrations/directory-rc13.json +36 -0
  59. package/templates/mobile/src/mavis.ts +2 -82
  60. package/templates/mobile/webpack.config.js +4 -0
  61. package/templates/native-framework/angular/screen.ts +84 -0
  62. package/templates/native-framework/common/nativescript.config.ts +6 -0
  63. package/templates/native-framework/common/src/app.ts +5 -0
  64. package/templates/native-framework/common/src/model.ts +40 -0
  65. package/templates/native-framework/common/src/references.d.ts +8 -0
  66. package/templates/native-framework/common/tsconfig.json +16 -0
  67. package/templates/native-framework/common/webpack.config.js +67 -0
  68. package/templates/native-framework/plain/screen.ts +102 -0
  69. package/templates/native-framework/react/screen.ts +83 -0
  70. package/templates/native-framework/solid/screen.ts +111 -0
  71. package/templates/native-framework/svelte/Welcome.svelte +26 -0
  72. package/templates/native-framework/svelte/screen.ts +14 -0
  73. package/templates/native-framework/svelte-tooling/svelte.config.js +20 -0
  74. package/templates/nuxt/app/mavis.ts +2 -84
  75. package/templates/vite/src/mavis.ts +2 -84
  76. package/templates/macos/scripts/portable/emit-swift.mjs +0 -1287
  77. package/templates/macos/scripts/portable/emit-vue.mjs +0 -615
  78. package/templates/macos/scripts/portable/index.mjs +0 -95
  79. package/templates/macos/scripts/portable/model.mjs +0 -1441
  80. package/templates/macos/scripts/portable/program.mjs +0 -163
@@ -0,0 +1,73 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import {
3
+ copyFileSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ readdirSync,
8
+ writeFileSync,
9
+ } from 'node:fs'
10
+ import { dirname, join, resolve } from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+
13
+ export function findManifestTool() {
14
+ const kits = join(
15
+ process.env['ProgramFiles(x86)'] ?? 'C:/Program Files (x86)',
16
+ 'Windows Kits/10/bin',
17
+ )
18
+ let manifestTool = process.env.MAVIS_MT
19
+ if (!manifestTool && existsSync(kits)) {
20
+ for (const version of readdirSync(kits).sort((a, b) =>
21
+ b.localeCompare(a, undefined, { numeric: true }),
22
+ )) {
23
+ for (const arch of [process.arch === 'arm64' ? 'arm64' : 'x64', 'x64']) {
24
+ const candidate = join(kits, version, arch, 'mt.exe')
25
+ if (existsSync(candidate)) {
26
+ manifestTool = candidate
27
+ break
28
+ }
29
+ }
30
+ if (manifestTool) break
31
+ }
32
+ }
33
+ return manifestTool && existsSync(manifestTool) ? manifestTool : undefined
34
+ }
35
+
36
+ /** XAML Islands require a manifest on the executable hosting Node-API. */
37
+ export function prepareWindowsHost(destination) {
38
+ if (process.platform !== 'win32') throw new Error('Build and run the Windows app on Windows.')
39
+ const executable = resolve(destination)
40
+ const stamp = `${executable}.json`
41
+ const identity = JSON.stringify({ node: process.version, arch: process.arch, manifest: 1 })
42
+ if (existsSync(executable) && existsSync(stamp) && readFileSync(stamp, 'utf8') === identity)
43
+ return executable
44
+ const manifestTool = findManifestTool()
45
+ if (!manifestTool)
46
+ throw new Error('Install the Windows 10/11 SDK (Manifest Tool), or set MAVIS_MT to mt.exe.')
47
+ mkdirSync(dirname(executable), { recursive: true })
48
+ copyFileSync(process.execPath, executable)
49
+ const manifest = `${executable}.manifest`
50
+ execFileSync(manifestTool, ['-nologo', `-inputresource:${executable};#1`, `-out:${manifest}`])
51
+ const bytes = readFileSync(manifest)
52
+ let xml = bytes
53
+ .toString(bytes[0] === 255 && bytes[1] === 254 ? 'utf16le' : 'utf8')
54
+ .replace(/^\uFEFF/, '')
55
+ const maximum = '<maxversiontested Id="10.0.18362.0"/>'
56
+ if (/<maxversiontested\b[^>]*\/>/.test(xml))
57
+ xml = xml.replace(/<maxversiontested\b[^>]*\/>/, maximum)
58
+ else if (/<compatibility\b/.test(xml))
59
+ xml = xml.replace(/(<compatibility\b[\s\S]*?)(<\/application>)/, `$1${maximum}$2`)
60
+ else
61
+ xml = xml.replace(
62
+ '</assembly>',
63
+ `<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"><application>${maximum}</application></compatibility></assembly>`,
64
+ )
65
+ if (!xml.includes(maximum)) throw new Error('Cannot add XAML compatibility to the Node manifest.')
66
+ writeFileSync(manifest, xml)
67
+ execFileSync(manifestTool, ['-nologo', '-manifest', manifest, `-outputresource:${executable};#1`])
68
+ writeFileSync(stamp, identity)
69
+ return executable
70
+ }
71
+
72
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url))
73
+ console.log(prepareWindowsHost(process.argv[2] ?? '.mavis/runtime/node.exe'))
@@ -0,0 +1,277 @@
1
+ import { nativeProps } from './contract.mjs'
2
+ import { createRequire } from 'node:module'
3
+ import { mavis, midnight } from '@getcortexlabs/mavis-core'
4
+ const { Windows, XamlWindow, native } = createRequire(import.meta.url)('@nativescript/windows-napi')
5
+ const Xaml = Windows.UI.Xaml
6
+ const C = Xaml.Controls
7
+ const emit = (listener, ...args) => {
8
+ for (const fn of Array.isArray(listener) ? listener : [listener])
9
+ if (typeof fn === 'function') fn(...args)
10
+ }
11
+ const text = (node) => node.text || node.children.map(text).join('')
12
+ const brush = (hex) => {
13
+ const value = Number.parseInt(hex.replace('#', '').slice(0, 6), 16)
14
+ return new Xaml.Media.SolidColorBrush(
15
+ Windows.UI.ColorHelper.FromArgb(255, value >> 16, (value >> 8) & 255, value & 255),
16
+ )
17
+ }
18
+ const supported = {
19
+ root: [],
20
+ screen: ['scroll'],
21
+ column: ['padding', 'gap'],
22
+ row: ['padding', 'gap'],
23
+ grid: ['minColumnWidth', 'gap'],
24
+ text: ['text', 'as', 'variant', 'tone'],
25
+ input: [
26
+ 'modelValue',
27
+ 'label',
28
+ 'placeholder',
29
+ 'readonly',
30
+ 'disabled',
31
+ 'onUpdate:modelValue',
32
+ 'onSubmit',
33
+ 'onEscape',
34
+ ],
35
+ reveal: ['show'],
36
+ button: ['href', 'text', 'loading', 'loadingText', 'disabled', 'onClick'],
37
+ link: ['href', 'text', 'disabled', 'onClick'],
38
+ card: ['href', 'padding', 'gap', 'onClick', 'disabled'],
39
+ }
40
+
41
+ /** Explicit XAML Islands subset. NativeScript Core mobile widgets are not used on Windows. */
42
+ export function createHost({ title = '__MAVIS_NAME__', onClose = () => {} } = {}) {
43
+ const window = new XamlWindow({ title, theme: 'light' })
44
+ const root = {
45
+ kind: 'root',
46
+ text: '',
47
+ props: {},
48
+ children: [],
49
+ parent: null,
50
+ native: new C.Canvas(),
51
+ }
52
+ root.content = root.native
53
+ window.content = root.native
54
+ window.place({ width: 780, height: 620 })
55
+ const nodes = new Set([root])
56
+ let closed = false,
57
+ scheduled = false,
58
+ timer,
59
+ theme = mavis
60
+ const tokens = (key) => (typeof key === 'number' ? key : (theme.space[key] ?? 0))
61
+ function create(kind) {
62
+ if (!(kind in supported) && !['#text', '#comment'].includes(kind))
63
+ throw new Error(`Windows desktop host does not implement ${kind}`)
64
+ const node = { kind, text: '', props: {}, children: [], parent: null }
65
+ nodes.add(node)
66
+ if (kind[0] === '#') return node
67
+ if (kind === 'text') {
68
+ node.native = new C.TextBlock()
69
+ node.native.TextWrapping = Xaml.TextWrapping.Wrap
70
+ } else if (kind === 'input') {
71
+ node.native = node.editor = new C.TextBox()
72
+ node.native.TextChanged = () => {
73
+ if (!node.updating && !closed) emit(node.props['onUpdate:modelValue'], node.editor.Text)
74
+ }
75
+ node.native.KeyDown = (_sender, event) => {
76
+ if (event.Key === Windows.System.VirtualKey.Enter) emit(node.props.onSubmit)
77
+ if (event.Key === Windows.System.VirtualKey.Escape) emit(node.props.onEscape)
78
+ }
79
+ } else if (['button', 'link', 'card'].includes(kind)) {
80
+ node.native = new C.Button()
81
+ node.native.HorizontalContentAlignment = Xaml.HorizontalAlignment.Stretch
82
+ node.native.Click = () => {
83
+ if (!closed && !node.props.disabled && !node.props.loading) emit(node.props.onClick)
84
+ }
85
+ if (kind === 'card') node.native.Content = node.content = new C.Canvas()
86
+ } else if (kind === 'screen') {
87
+ node.native = new C.ScrollViewer()
88
+ node.native.VerticalScrollBarVisibility = C.ScrollBarVisibility.Auto
89
+ node.native.HorizontalScrollBarVisibility = C.ScrollBarVisibility.Disabled
90
+ node.native.Content = node.content = new C.Canvas()
91
+ } else node.native = new C.Canvas()
92
+ node.content ??= node.native
93
+ node.dispose = () => {
94
+ if (node.editor) {
95
+ node.editor.TextChanged = null
96
+ node.editor.KeyDown = null
97
+ }
98
+ if (['button', 'link', 'card'].includes(kind)) node.native.Click = null
99
+ nodes.delete(node)
100
+ }
101
+ return node
102
+ }
103
+ function update(node) {
104
+ if (!node.native || closed) return
105
+ const p = node.props,
106
+ view = node.native
107
+ for (const key of Object.keys(p))
108
+ if (!nativeProps(node.kind, 'windows').includes(key))
109
+ throw new Error(`Windows desktop host does not implement ${node.kind}.${key}`)
110
+ Xaml.Automation.AutomationProperties.SetAutomationId(view, String(p.id ?? ''))
111
+ if (p.accessibilityLabel)
112
+ Xaml.Automation.AutomationProperties.SetName(view, String(p.accessibilityLabel))
113
+ if (node.kind === 'text') {
114
+ view.Text = String(p.text ?? text(node))
115
+ view.FontSize = { title: 28, heading: 20, caption: 12 }[p.variant] ?? 14
116
+ view.Foreground = brush(theme.colors[p.tone] ?? theme.colors.text)
117
+ }
118
+ if (node.kind === 'input') {
119
+ node.updating = true
120
+ try {
121
+ view.Header = String(p.label ?? '')
122
+ if (view.Text !== String(p.modelValue ?? '')) view.Text = String(p.modelValue ?? '')
123
+ view.PlaceholderText = String(p.placeholder ?? '')
124
+ view.IsReadOnly = Boolean(p.readonly)
125
+ view.IsEnabled = !p.disabled
126
+ } finally {
127
+ node.updating = false
128
+ }
129
+ }
130
+ if (['button', 'link', 'card'].includes(node.kind)) {
131
+ if (node.kind !== 'card')
132
+ view.Content = String(p.loading ? (p.loadingText ?? 'Loading…') : (p.text ?? text(node)))
133
+ view.IsEnabled = !p.disabled && !p.loading
134
+ }
135
+ if (node.kind === 'reveal') {
136
+ node.shown = p.show !== false
137
+ view.Visibility = node.shown ? Xaml.Visibility.Visible : Xaml.Visibility.Collapsed
138
+ }
139
+ if (node.kind === 'screen')
140
+ view.VerticalScrollMode = p.scroll === false ? C.ScrollMode.Disabled : C.ScrollMode.Enabled
141
+ }
142
+ function detachNative(node) {
143
+ const parent = node.attached
144
+ if (parent) {
145
+ const children = parent.content.Children
146
+ // Rebuild from known native children: no reliance on WinRT object wrapper identity.
147
+ children.Clear()
148
+ for (const sibling of parent.children)
149
+ if (sibling !== node && sibling.native) children.Append(sibling.native)
150
+ node.attached = null
151
+ }
152
+ }
153
+ function attach(node, parent) {
154
+ if (!node.native) return
155
+ if (node.attached && node.attached !== parent) detachNative(node)
156
+ parent.content.Children.Clear()
157
+ for (const sibling of parent.children)
158
+ if (sibling.native) parent.content.Children.Append(sibling.native)
159
+ node.attached = parent
160
+ }
161
+ function detach(node) {
162
+ detachNative(node)
163
+ nodes.delete(node)
164
+ }
165
+ function layoutNode(node, x, y, width, viewport) {
166
+ if (!node.native) return 0
167
+ const p = node.props,
168
+ view = node.native
169
+ let height = 0
170
+ width = Math.max(0, width)
171
+ if (node.kind === 'reveal' && !node.shown) height = 0
172
+ else if (node.kind === 'text') {
173
+ view.Width = width
174
+ view.Measure({ Width: width, Height: 100000 })
175
+ height = Math.max(20, view.DesiredSize.Height)
176
+ } else if (node.kind === 'input') height = p.label ? 70 : 40
177
+ else if (['button', 'link'].includes(node.kind)) height = 38
178
+ else {
179
+ const pad = tokens(p.padding ?? (node.kind === 'card' ? 'md' : 'none')),
180
+ gap = tokens(p.gap)
181
+ const children = node.children.filter(
182
+ (child) => child.native && !(child.kind === 'reveal' && !child.shown),
183
+ )
184
+ const columns =
185
+ node.kind === 'grid'
186
+ ? Math.max(
187
+ 1,
188
+ Math.floor((width - pad * 2 + gap) / (Number(p.minColumnWidth ?? 240) + gap)),
189
+ )
190
+ : node.kind === 'row'
191
+ ? Math.max(1, children.length)
192
+ : 1
193
+ const cellWidth = (width - pad * 2 - gap * (columns - 1)) / columns
194
+ let top = pad
195
+ for (let i = 0; i < children.length; i += columns) {
196
+ let rowHeight = 0
197
+ for (let col = 0; col < columns && i + col < children.length; col++)
198
+ rowHeight = Math.max(
199
+ rowHeight,
200
+ layoutNode(children[i + col], pad + col * (cellWidth + gap), top, cellWidth, viewport),
201
+ )
202
+ top += rowHeight + gap
203
+ }
204
+ height = top + pad - (children.length ? gap : 0)
205
+ if (node.kind === 'screen') {
206
+ node.content.Width = width
207
+ node.content.Height = Math.max(viewport, height)
208
+ height = viewport
209
+ }
210
+ if (node.kind === 'card') {
211
+ node.content.Width = Math.max(0, width - 16)
212
+ node.content.Height = height
213
+ height += 16
214
+ }
215
+ }
216
+ if (node.kind !== 'root') {
217
+ C.Canvas.SetLeft(view, x)
218
+ C.Canvas.SetTop(view, y)
219
+ view.Width = width
220
+ view.Height = Math.max(0, height)
221
+ }
222
+ return height
223
+ }
224
+ function layout() {
225
+ if (closed || scheduled) return
226
+ scheduled = true
227
+ queueMicrotask(() => {
228
+ scheduled = false
229
+ if (!closed)
230
+ layoutNode(root, 0, 0, root.native.ActualWidth || 780, root.native.ActualHeight || 620)
231
+ })
232
+ }
233
+ root.native.SizeChanged = layout
234
+ function setTheme(dark) {
235
+ theme = dark ? midnight : mavis
236
+ root.native.RequestedTheme = dark ? Xaml.ElementTheme.Dark : Xaml.ElementTheme.Light
237
+ root.native.Background = brush(theme.colors.background)
238
+ for (const node of nodes) update(node)
239
+ layout()
240
+ }
241
+ function stop() {
242
+ if (closed) return
243
+ closed = true
244
+ clearInterval(timer)
245
+ root.native.SizeChanged = null
246
+ for (const node of nodes) node.dispose?.()
247
+ nodes.clear()
248
+ }
249
+ window.on('closed', () => {
250
+ onClose()
251
+ stop()
252
+ })
253
+ function show() {
254
+ window.show()
255
+ timer = setInterval(() => native.pumpMessages(), 8)
256
+ layout()
257
+ }
258
+ return {
259
+ root,
260
+ window,
261
+ nodes,
262
+ create,
263
+ update,
264
+ attach,
265
+ detach,
266
+ layout,
267
+ show,
268
+ stop,
269
+ setTheme,
270
+ close() {
271
+ window.close()
272
+ },
273
+ get closed() {
274
+ return closed
275
+ },
276
+ }
277
+ }
@@ -0,0 +1,78 @@
1
+ import {
2
+ directorySeed,
3
+ validDirectoryEntries,
4
+ type DirectoryEntry,
5
+ type DirectorySnapshot,
6
+ type DirectoryStorage,
7
+ } from '../shared/directory-store'
8
+
9
+ export interface DirectoryPersistence {
10
+ read(): Promise<string | null>
11
+ write(value: string): Promise<void>
12
+ }
13
+
14
+ /** Host boundary: JSON and the write queue stay out of the shared screen/store. */
15
+ export function createDirectoryStorage(persistence: DirectoryPersistence): DirectoryStorage {
16
+ let entries = directorySeed.map((entry) => ({ ...entry }))
17
+ let revision = 0
18
+ let loadError = false
19
+ let restoring: Promise<void> | undefined
20
+ let writing = Promise.resolve()
21
+ const snapshot = (): DirectorySnapshot => ({
22
+ entries: entries.map((entry) => ({ ...entry })),
23
+ revision,
24
+ loadError,
25
+ })
26
+ const restore = () =>
27
+ (restoring ??= (async () => {
28
+ try {
29
+ const value = await persistence.read()
30
+ if (value === null) return
31
+ const parsed: unknown = JSON.parse(value)
32
+ if (
33
+ !Array.isArray(parsed) ||
34
+ !parsed.every(
35
+ (entry) =>
36
+ entry !== null &&
37
+ typeof entry === 'object' &&
38
+ typeof entry.id === 'string' &&
39
+ typeof entry.name === 'string' &&
40
+ typeof entry.city === 'string',
41
+ ) ||
42
+ !validDirectoryEntries(parsed)
43
+ )
44
+ throw new Error('Invalid saved directory')
45
+ entries = (parsed as DirectoryEntry[]).map(({ id, name, city }) => ({ id, name, city }))
46
+ } catch {
47
+ loadError = true
48
+ }
49
+ })())
50
+ return {
51
+ async load() {
52
+ await restore()
53
+ return snapshot()
54
+ },
55
+ rename(id, name) {
56
+ const operation = writing
57
+ .catch(() => {})
58
+ .then(async () => {
59
+ await restore()
60
+ if (!name.trim() || !entries.some((entry) => entry.id === id))
61
+ throw new Error('Invalid entry')
62
+ const next = entries.map((entry) =>
63
+ entry.id === id ? { ...entry, name: name.trim() } : { ...entry },
64
+ )
65
+ await persistence.write(JSON.stringify(next))
66
+ entries = next
67
+ revision += 1
68
+ return snapshot()
69
+ })
70
+ // A failed write does not poison the queue or change the committed state.
71
+ writing = operation.then(
72
+ () => {},
73
+ () => {},
74
+ )
75
+ return operation
76
+ },
77
+ }
78
+ }
@@ -0,0 +1,68 @@
1
+ import Foundation
2
+
3
+ /// One instance per app. Uses the same JSON array and key as the Web and NativeScript hosts.
4
+ @MainActor final class UserDefaultsDirectoryStorage: DirectoryStorage {
5
+ private let defaults: UserDefaults
6
+ private let key: String
7
+ private var entries = DirectoryStoreModule.directorySeed
8
+ private var loaded = false
9
+ private var revision: Double = 0
10
+ private var loadError = false
11
+
12
+ init(defaults: UserDefaults = .standard, key: String = "mavis:directory") {
13
+ self.defaults = defaults
14
+ self.key = key
15
+ }
16
+
17
+ private func snapshot() -> DirectorySnapshot {
18
+ DirectorySnapshot(entries: entries, revision: revision, loadError: loadError)
19
+ }
20
+
21
+ private func restore() {
22
+ guard !loaded else { return }
23
+ loaded = true
24
+ guard let text = defaults.string(forKey: key) else { return }
25
+ do {
26
+ guard let data = text.data(using: .utf8),
27
+ let values = try JSONSerialization.jsonObject(with: data) as? [[String: Any]]
28
+ else { throw MavisFailure(message: "Invalid saved directory") }
29
+ let decoded = try values.map { value -> DirectoryEntry in
30
+ guard let id = value["id"] as? String,
31
+ let name = value["name"] as? String,
32
+ let city = value["city"] as? String
33
+ else { throw MavisFailure(message: "Invalid saved directory") }
34
+ return DirectoryEntry(id: id, name: name, city: city)
35
+ }
36
+ guard DirectoryStoreModule.validDirectoryEntries(decoded)
37
+ else { throw MavisFailure(message: "Invalid saved directory") }
38
+ entries = decoded
39
+ } catch {
40
+ loadError = true
41
+ }
42
+ }
43
+
44
+ func load() async throws -> DirectorySnapshot {
45
+ restore()
46
+ return snapshot()
47
+ }
48
+
49
+ func rename(_ id: String, _ name: String) async throws -> DirectorySnapshot {
50
+ // This operation has no suspension: MainActor serializes restore/edit/write/commit.
51
+ restore()
52
+ let trimmed = mavisTrim(name)
53
+ guard !trimmed.isEmpty, entries.contains(where: { $0.id == id })
54
+ else { throw MavisFailure(message: "Invalid entry") }
55
+ let next = entries.map { entry in
56
+ DirectoryEntry(id: entry.id, name: entry.id == id ? trimmed : entry.name, city: entry.city)
57
+ }
58
+ let data = try JSONSerialization.data(withJSONObject: next.map {
59
+ ["id": $0.id, "name": $0.name, "city": $0.city]
60
+ })
61
+ guard let text = String(data: data, encoding: .utf8)
62
+ else { throw MavisFailure(message: "Could not encode directory") }
63
+ defaults.set(text, forKey: key)
64
+ entries = next
65
+ revision += 1
66
+ return snapshot()
67
+ }
68
+ }
@@ -6,16 +6,19 @@ import { createRouterNavigation, mavis, midnight } from '@getcortexlabs/mavis-co
6
6
  import { createDirectory, directoryKey } from '__MAVIS_SHARED__/directory-store'
7
7
  import { routes } from '__MAVIS_SHARED__/routes'
8
8
  import App from './App.vue'
9
+ import { createDirectoryStorage } from './directory-storage'
9
10
 
10
11
  const router = createRouter({ routes })
11
- const directory = createDirectory({
12
- async read() {
13
- return ApplicationSettings.getString('mavis:directory', '') || null
14
- },
15
- async write(value) {
16
- ApplicationSettings.setString('mavis:directory', value)
17
- },
18
- })
12
+ const directory = createDirectory(
13
+ createDirectoryStorage({
14
+ async read() {
15
+ return ApplicationSettings.getString('mavis:directory', '') || null
16
+ },
17
+ async write(value) {
18
+ ApplicationSettings.setString('mavis:directory', value)
19
+ },
20
+ }),
21
+ )
19
22
  createApp(App)
20
23
  .use(router)
21
24
  .use(
@@ -2,6 +2,7 @@ import { createMavisServices } from '@getcortexlabs/mavis-web/services'
2
2
  import { createRouterNavigation, mavis, midnight } from '@getcortexlabs/mavis-core'
3
3
  import { useMavisTheme } from '@getcortexlabs/mavis-core/vue'
4
4
  import { createDirectory, directoryKey } from '__MAVIS_SHARED__/directory-store'
5
+ import { createDirectoryStorage } from '../utils/directory-storage'
5
6
 
6
7
  export default defineNuxtPlugin(({ vueApp, $router }) => {
7
8
  const saved = useCookie<string>('appearance')
@@ -18,14 +19,16 @@ export default defineNuxtPlugin(({ vueApp, $router }) => {
18
19
  )
19
20
  const theme = vueApp.runWithContext(useMavisTheme)
20
21
  // Each server request has its own store. Storage is accessed only after hydration.
21
- const directory = createDirectory({
22
- async read() {
23
- return localStorage.getItem('mavis:directory')
24
- },
25
- async write(value) {
26
- localStorage.setItem('mavis:directory', value)
27
- },
28
- })
22
+ const directory = createDirectory(
23
+ createDirectoryStorage({
24
+ async read() {
25
+ return localStorage.getItem('mavis:directory')
26
+ },
27
+ async write(value) {
28
+ localStorage.setItem('mavis:directory', value)
29
+ },
30
+ }),
31
+ )
29
32
  vueApp.provide(directoryKey, directory)
30
33
  onNuxtReady(() => {
31
34
  theme.setAppearance(saved.value === 'dark' || saved.value === 'light' ? saved.value : 'system')
@@ -20,9 +20,12 @@ const dirty = ref(false),
20
20
  saving = ref(false),
21
21
  saved = ref(false),
22
22
  error = ref('')
23
- watch(entry, (value) => {
24
- if (!dirty.value) name.value = value?.name ?? ''
25
- })
23
+ watch(
24
+ () => entry.value?.name ?? '',
25
+ (value) => {
26
+ if (!dirty.value) name.value = value
27
+ },
28
+ )
26
29
  watch(
27
30
  () => props.id,
28
31
  () => {
@@ -38,8 +41,8 @@ function edit() {
38
41
  }
39
42
  async function save() {
40
43
  if (saving.value || !name.value.trim()) return
41
- const id = props.id,
42
- draft = name.value
44
+ const id = props.id
45
+ const draft = name.value
43
46
  saving.value = true
44
47
  saved.value = false
45
48
  error.value = ''