moi-computer 0.3.0-next.0 → 0.3.0-next.2

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 (150) hide show
  1. package/bunfig.toml +5 -1
  2. package/client/AGENTS.md +15 -0
  3. package/client/accept-hmr-dependencies.ts +22 -0
  4. package/client/api/http.ts +31 -0
  5. package/client/api/query-options.ts +6 -0
  6. package/client/api/workspace-keys.ts +17 -0
  7. package/client/app/AppRouter.tsx +35 -0
  8. package/client/app/routes/HomeRoute.tsx +13 -0
  9. package/client/app/routes/WorkspaceRoute.tsx +89 -0
  10. package/client/app/shell/SidebarLayout.tsx +191 -0
  11. package/client/assets.d.ts +9 -0
  12. package/client/components/playground/PixelPainter.tsx +10 -21
  13. package/client/components/playground/PlaygroundPage.tsx +9 -11
  14. package/client/components/playground/ToolCallsPage.tsx +9 -11
  15. package/client/components/{BottomPanel.tsx → shared/BottomPanel.tsx} +1 -1
  16. package/client/components/shared/PanelHeader.tsx +9 -0
  17. package/client/components/shared/ReorderableList.tsx +199 -0
  18. package/client/components/ui/button.tsx +10 -7
  19. package/client/components/ui/collapsible.tsx +15 -0
  20. package/client/components/ui/dialog.tsx +2 -2
  21. package/client/components/ui/dropdown-menu.tsx +5 -5
  22. package/client/components/ui/hover-card.tsx +1 -1
  23. package/client/components/ui/popover.tsx +1 -1
  24. package/client/components/ui/skeleton.tsx +13 -0
  25. package/client/components/ui/tooltip.tsx +1 -1
  26. package/client/externalize-react.ts +7 -1
  27. package/client/{components → features/applets}/WidgetErrorBoundary.tsx +1 -1
  28. package/client/{components → features/applets}/WidgetShell.tsx +1 -1
  29. package/client/{hooks → features/applets}/useApplet.ts +6 -7
  30. package/client/{components/ChatInput.tsx → features/chat/ChatComposer.tsx} +29 -23
  31. package/client/features/chat/ChatPanel.tsx +188 -0
  32. package/client/{components → features/chat}/ChatPopup.tsx +23 -12
  33. package/client/{components → features/chat}/MarkdownContent.tsx +1 -1
  34. package/client/{components → features/chat}/ModelPicker.tsx +68 -17
  35. package/client/{components → features/chat}/ThreadSelector.tsx +11 -9
  36. package/client/{components → features/chat}/TurnView.tsx +16 -9
  37. package/client/features/chat/api.ts +78 -0
  38. package/client/features/chat/chat-connection.ts +107 -0
  39. package/client/features/chat/chat-frames.ts +131 -0
  40. package/client/{lib → features/chat}/preview-turn.ts +1 -1
  41. package/client/{components → features/chat}/tool-group/ReadImagePreview.tsx +1 -1
  42. package/client/{components → features/chat}/tool-group/SubagentCard.tsx +12 -10
  43. package/client/{components → features/chat}/tool-group/TimelineRow.tsx +5 -5
  44. package/client/{components → features/chat}/tool-group/ToolCallGroup.tsx +12 -4
  45. package/client/{components → features/chat}/tool-group/ToolOutput.tsx +12 -18
  46. package/client/{hooks → features/chat}/useChat.ts +7 -11
  47. package/client/features/connectors/ConnectorsPage.tsx +92 -0
  48. package/client/features/connectors/McpMenu.tsx +162 -0
  49. package/client/features/connectors/api.ts +28 -0
  50. package/client/features/home/CreateWorkspaceDialog.tsx +224 -0
  51. package/client/features/home/HomePage.tsx +220 -0
  52. package/client/{components → features/home}/WorkspacePreview.tsx +2 -2
  53. package/client/features/home/api.ts +148 -0
  54. package/client/features/home/workspace-presentation.tsx +44 -0
  55. package/client/features/scratchpad/Scratchpad.tsx +312 -0
  56. package/client/features/scratchpad/ScratchpadControls.tsx +503 -0
  57. package/client/features/scratchpad/useScratchpadSnapshot.tsx +115 -0
  58. package/client/features/settings/EnvironmentSettings.tsx +149 -0
  59. package/client/features/settings/GeneralSettings.tsx +90 -0
  60. package/client/{components → features}/settings/IconPicker.tsx +73 -222
  61. package/client/features/settings/SettingsLayout.tsx +53 -0
  62. package/client/{components → features}/settings/WorkspaceSettings.tsx +12 -16
  63. package/client/features/settings/api.ts +88 -0
  64. package/client/features/settings/icon-picker-options.ts +161 -0
  65. package/client/{hooks → features/settings}/useEnvVars.ts +4 -4
  66. package/client/{components → features/widgets}/HiddenPanel.tsx +3 -3
  67. package/client/{components → features/widgets}/WidgetFrame.tsx +3 -8
  68. package/client/{components → features/widgets}/WidgetGrid.tsx +2 -9
  69. package/client/features/widgets/Widgets.tsx +215 -0
  70. package/client/{lib/grid-pack.ts → features/widgets/grid.ts} +7 -1
  71. package/client/{hooks → features/widgets}/useGridReconcile.ts +1 -1
  72. package/client/{components → features/workspace}/CustomizePanel.tsx +5 -6
  73. package/client/{lib → features/workspace}/WorkspaceLayoutContext.tsx +15 -8
  74. package/client/features/workspace/WorkspaceScreen.tsx +536 -0
  75. package/client/features/workspace/WorkspaceTabs.tsx +205 -0
  76. package/client/features/workspace/api.ts +56 -0
  77. package/client/features/workspace/useFitsSplitLayout.ts +37 -0
  78. package/client/global.d.ts +5 -0
  79. package/client/index.css +6 -10
  80. package/client/index.html +1 -1
  81. package/client/index.tsx +14 -31
  82. package/client/lib/ws-url.ts +10 -0
  83. package/client/main.tsx +2 -2
  84. package/client/runtime/hmr-watchdog.ts +39 -0
  85. package/client/{hooks/useMeiEvents.ts → runtime/useWorkspaceEvents.ts} +11 -7
  86. package/client/store/ui.ts +5 -1
  87. package/client/theme.css +0 -2
  88. package/dist/chunk-11cab5dq.css +1 -0
  89. package/dist/chunk-23cgr1tz.css +1 -0
  90. package/dist/chunk-3hy3qy6d.js +10 -0
  91. package/dist/chunk-c4j722at.js +546 -0
  92. package/dist/chunk-dyfaffyz.js +119 -0
  93. package/dist/chunk-kpe40hm8.js +1 -0
  94. package/dist/chunk-p68fnz3q.js +2 -0
  95. package/dist/chunk-pcnahct1.js +5 -0
  96. package/dist/chunk-tqd3pkg8.css +1 -0
  97. package/dist/chunk-ty6dvda0.js +1 -0
  98. package/dist/index.html +2 -2
  99. package/lib/types.ts +18 -7
  100. package/lib/workspace-name.ts +14 -0
  101. package/package.json +3 -2
  102. package/server/api.ts +127 -17
  103. package/server/applets.ts +84 -8
  104. package/server/cli.ts +11 -5
  105. package/server/layout.ts +38 -7
  106. package/server/mcp.ts +72 -15
  107. package/server/moi-scaffold.ts +55 -10
  108. package/server/registry.ts +16 -0
  109. package/server/views.ts +0 -0
  110. package/server/web.ts +1 -0
  111. package/server/widgets.ts +3 -2
  112. package/server/workspace-init.ts +5 -19
  113. package/tsconfig.json +1 -1
  114. package/workspace/.claude/skills/moi-workspace/DESIGN.md +1 -1
  115. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +1 -1
  116. package/client/api/workspaces.ts +0 -427
  117. package/client/components/App.tsx +0 -41
  118. package/client/components/ChatPanel.tsx +0 -275
  119. package/client/components/HomePage.tsx +0 -17
  120. package/client/components/McpMenu.tsx +0 -125
  121. package/client/components/Scratchpad.tsx +0 -935
  122. package/client/components/Widgets.tsx +0 -132
  123. package/client/components/WorkspacesPage.tsx +0 -245
  124. package/client/components/layout/SidebarLayout.tsx +0 -258
  125. package/client/components/routes/workspace/[id].tsx +0 -675
  126. package/client/components/routes/workspace/create.tsx +0 -155
  127. package/client/components/settings/SettingsPages.tsx +0 -255
  128. package/client/hooks/useFitsSidebar.ts +0 -34
  129. package/client/lib/connection.ts +0 -237
  130. package/dist/chunk-07qf2tv1.css +0 -1
  131. package/dist/chunk-c3zjp9ez.js +0 -672
  132. /package/client/components/{playground → shared}/LedLogo.tsx +0 -0
  133. /package/client/{lib → features/applets}/applet-cache.ts +0 -0
  134. /package/client/{components → features/chat}/ShimmerText.tsx +0 -0
  135. /package/client/{store/live.ts → features/chat/chat-store.ts} +0 -0
  136. /package/client/{lib → features/chat}/group-turns.ts +0 -0
  137. /package/client/{components → features/chat}/tool-group/CodeBlock.tsx +0 -0
  138. /package/client/{components → features/chat}/tool-group/Collapse.tsx +0 -0
  139. /package/client/{components → features/chat}/tool-group/detect.ts +0 -0
  140. /package/client/{components → features/chat}/tool-group/fixtures.ts +0 -0
  141. /package/client/{components → features/chat}/tool-group/format.ts +0 -0
  142. /package/client/{components → features/chat}/tool-group/index.ts +0 -0
  143. /package/client/{lib → features/chat}/uploads.ts +0 -0
  144. /package/client/{hooks → features/chat}/useStickToBottom.ts +0 -0
  145. /package/client/{components → features/connectors}/IconMcp.tsx +0 -0
  146. /package/client/{lib → features/connectors}/mcp-icons.ts +0 -0
  147. /package/client/{lib → features/scratchpad}/scratch-executor.ts +0 -0
  148. /package/client/{lib → features/settings}/render-icon.ts +0 -0
  149. /package/client/{lib → features/workspace}/WorkspaceContext.tsx +0 -0
  150. /package/client/{hooks → features/workspace}/useWorkspaceTheme.ts +0 -0
@@ -1,935 +0,0 @@
1
- import { Fragment, type ReactElement, useCallback, useEffect, useRef, useState } from 'react'
2
-
3
- import {
4
- type Editor,
5
- type StyleProp,
6
- type TLAssetStore,
7
- type TLComponents,
8
- type TLDefaultColorStyle,
9
- type TLDefaultDashStyle,
10
- type TLDefaultFillStyle,
11
- type TLDefaultSizeStyle,
12
- type TLEditorSnapshot,
13
- type TLStore,
14
- type TLUiOverrides,
15
- DefaultColorStyle,
16
- DefaultDashStyle,
17
- DefaultFillStyle,
18
- DefaultFontStyle,
19
- DefaultHorizontalAlignStyle,
20
- DefaultSizeStyle,
21
- DefaultVerticalAlignStyle,
22
- GeoShapeGeoStyle,
23
- Tldraw,
24
- createTLStore,
25
- defaultBindingUtils,
26
- defaultShapeUtils,
27
- getSnapshot,
28
- loadSnapshot,
29
- react
30
- } from 'tldraw'
31
- import 'tldraw/tldraw.css'
32
- import { motion } from 'motion/react'
33
- import {
34
- IconArrowUpRight,
35
- IconEraser,
36
- IconHandStop,
37
- IconHighlight,
38
- IconLine,
39
- IconPointer2,
40
- IconSketching,
41
- IconSquare,
42
- IconSticker2,
43
- IconTypography,
44
- IconVersions
45
- } from '@tabler/icons-react'
46
-
47
- import { cn } from '@/client/lib/cn'
48
- import { useWorkspaceId } from '@/client/lib/WorkspaceContext'
49
- import { setScratchExecutor } from '@/client/lib/scratch-executor'
50
- import { type MeiEvent, useMeiEvent } from '@/client/hooks/useMeiEvents'
51
- import { describeNewerWriter, sequencesAhead } from '@/lib/scratchpad-skew'
52
- import type { ScratchOp, ScratchOpResult, ScratchpadWriter } from '@/lib/types'
53
-
54
- // Identifies this tab's writes so it can ignore the `scratchpad:updated` echo of
55
- // its own save (see the MEI reload below). Per page load.
56
- const ORIGIN_ID = Math.random().toString(36).slice(2)
57
-
58
- const AUTOSAVE_MS = 500
59
-
60
- // tldraw license key, inlined at build time from the PUBLIC_TLDRAW_LICENSE_KEY
61
- // env var (Bun's prefix-based env inlining — see bunfig.toml `[serve.static] env`
62
- // for dev and scripts/build-client.ts for prod). The key is public by design
63
- // (domain-scoped, ships in the client bundle). Empty/unset → undefined →
64
- // tldraw's default unlicensed watermark. See docs/moi-scratchpad.md.
65
- // Inlining requires the var to be set when the server process starts — the CLI
66
- // launcher defaults it (server/cli.ts); a bare ref here throws in the browser.
67
- const LICENSE_KEY = process.env.PUBLIC_TLDRAW_LICENSE_KEY || undefined
68
-
69
- // Execute a relayed op in this tab. Only `view` is relayed now — rasterizing the
70
- // canvas to a PNG needs the browser (`editor.toImageDataUrl`); every mutation runs
71
- // server-side against the disk snapshot (see server/scratchpad-executor.ts), so a
72
- // non-view op arriving here is unexpected.
73
- function makeExecutor(editor: Editor) {
74
- return async (op: ScratchOp): Promise<ScratchOpResult> => {
75
- if (op.kind !== 'view') {
76
- throw new Error(`Scratchpad op "${op.kind}" runs on the server, not the browser.`)
77
- }
78
- const ids = [...editor.getCurrentPageShapeIds()]
79
- if (ids.length === 0) throw new Error('Canvas is empty — nothing to view.')
80
- const { url } = await editor.toImageDataUrl(ids, {
81
- format: 'png',
82
- background: true,
83
- padding: 32
84
- })
85
- return { image: url }
86
- }
87
- }
88
-
89
- // File-backed assets: without this, tldraw inlines every pasted/dropped image as
90
- // a base64 data URL inside the document — megabytes re-serialized into
91
- // `.moi/.scratchpad.json` on every autosave and shipped over every GET/PUT.
92
- // Instead `upload` POSTs the bytes once and stores a tiny `asset:<file>` src on
93
- // the record; `resolve` maps it back to the serving URL at render time. Legacy
94
- // snapshots still holding data URLs pass through `resolve` untouched (the
95
- // server extracts them to files on the next save). See server/scratchpad-assets.ts.
96
- function makeAssetStore(workspaceId: string): TLAssetStore {
97
- const base = `/api/workspaces/${workspaceId}/scratchpad/assets`
98
- return {
99
- async upload(_asset, file) {
100
- const res = await fetch(base, {
101
- method: 'POST',
102
- headers: { 'Content-Type': file.type || 'application/octet-stream' },
103
- body: file
104
- })
105
- if (!res.ok) throw new Error(`Upload failed: ${await res.text()}`)
106
- const { src } = (await res.json()) as { src: string }
107
- return { src }
108
- },
109
- resolve(asset) {
110
- const src = asset.props.src
111
- if (src?.startsWith('asset:')) return `${base}/${src.slice('asset:'.length)}`
112
- return src
113
- }
114
- }
115
- }
116
-
117
- // --- Scratchpad UI shell --------------------------------------------------
118
- // We replace tldraw's full UI with a curated subset (see docs/moi-scratchpad.md
119
- // for the prioritization). Backbone v1: a custom vertical tool bar on the left,
120
- // most menus dropped, pages disabled, export hard-removed, grid on. The default
121
- // (contextual) style panel and zoom control are kept as-is for now; style
122
- // trimming is a follow-up.
123
-
124
- // Drop tldraw's built-in chrome we replace with custom overlays (tool bar, style
125
- // bar). `null` removes a component entirely. NavigationPanel is kept — we like its
126
- // native zoom control — but Minimap is nulled, which also strips its toggle button
127
- // from the panel, leaving just the zoom menu. Kept on defaults: NavigationPanel
128
- // (zoom), ContextMenu, KeyboardShortcutsDialog.
129
- const SCRATCH_COMPONENTS: TLComponents = {
130
- Toolbar: null,
131
- StylePanel: null,
132
- Minimap: null,
133
- MainMenu: null,
134
- PageMenu: null,
135
- ActionsMenu: null,
136
- QuickActions: null,
137
- HelpMenu: null,
138
- DebugMenu: null
139
- }
140
-
141
- // Remove dropped tools (kills their shortcuts too) and hard-disable export/print.
142
- // Deleting an unknown action id is a harmless no-op.
143
- const SCRATCH_OVERRIDES: TLUiOverrides = {
144
- tools(_editor, tools) {
145
- delete tools.frame
146
- delete tools.laser
147
- return tools
148
- },
149
- actions(_editor, actions) {
150
- for (const id of ['export-as-svg', 'export-as-png', 'copy-as-svg', 'copy-as-png', 'print']) {
151
- delete actions[id]
152
- }
153
- return actions
154
- }
155
- }
156
-
157
- // One page only — disables the page selector and all multi-page UI.
158
- const SCRATCH_OPTIONS = { maxPages: 1 }
159
-
160
- // Browser drag/drop/paste limits (tldraw defaults: reject >10MB, no rescale). We
161
- // accept larger drops and rescale big images to fit so a phone-sized photo lands
162
- // as a lightweight asset instead of bloating the snapshot's sidecar files. The
163
- // size check runs BEFORE the rescale, so a 32MB drop is admitted and then shrunk.
164
- // (The agent's `moi scratch add image` path has its own presets — see the
165
- // executor's IMAGE_PRESETS; this only governs what the browser accepts.)
166
- const MAX_DROP_BYTES = 32 * 1024 * 1024
167
- const MAX_IMAGE_DIMENSION = 2048
168
-
169
- type IconC = typeof IconPointer2
170
-
171
- // The curated left-bar entries, grouped by `sep` dividers. `tool` selects a
172
- // tldraw tool; `geo` selects the geo tool (rectangle); `menu` is a placeholder
173
- // (noop for now); `sep` is a divider.
174
- type ToolEntry =
175
- | { kind: 'tool'; id: string; label: string; Icon: IconC }
176
- | { kind: 'geo'; label: string; Icon: IconC }
177
- | { kind: 'menu'; label: string; Icon: IconC }
178
- | { kind: 'sep' }
179
-
180
- const TOOL_ENTRIES: ToolEntry[] = [
181
- { kind: 'tool', id: 'select', label: 'Select', Icon: IconPointer2 },
182
- { kind: 'tool', id: 'hand', label: 'Hand', Icon: IconHandStop },
183
- { kind: 'sep' },
184
- { kind: 'tool', id: 'draw', label: 'Pencil', Icon: IconSketching },
185
- { kind: 'geo', label: 'Rectangle', Icon: IconSquare },
186
- { kind: 'tool', id: 'note', label: 'Sticker', Icon: IconSticker2 },
187
- { kind: 'tool', id: 'text', label: 'Text', Icon: IconTypography },
188
- { kind: 'tool', id: 'line', label: 'Line', Icon: IconLine },
189
- { kind: 'tool', id: 'arrow', label: 'Arrow', Icon: IconArrowUpRight },
190
- { kind: 'sep' },
191
- { kind: 'tool', id: 'highlight', label: 'Highlighter', Icon: IconHighlight },
192
- { kind: 'tool', id: 'eraser', label: 'Eraser', Icon: IconEraser }
193
- // Temporarily hidden — `menu` kind + IconDots import kept for future use.
194
- // { kind: "menu", label: "Menu", Icon: IconDots },
195
- ]
196
-
197
- type ToolButtonProps = {
198
- label: string
199
- active: boolean
200
- Icon: IconC
201
- onClick: () => void
202
- }
203
-
204
- function ToolButton({ label, active, Icon, onClick }: ToolButtonProps) {
205
- return (
206
- <button
207
- type="button"
208
- title={label}
209
- onClick={onClick}
210
- className={cn(
211
- 'flex size-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-muted hover:text-foreground',
212
- active &&
213
- 'bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground'
214
- )}
215
- >
216
- <Icon size={20} stroke={1.5} />
217
- </button>
218
- )
219
- }
220
-
221
- type ScratchToolbarProps = { editor: Editor }
222
-
223
- // tldraw shares style props (dash, size, font…) globally across tools, so a
224
- // dashed pen would leak into a freshly-picked rect. On each tool activation we
225
- // pin the styles that tool doesn't expose to fixed values, keeping every tool
226
- // visually independent.
227
- function applyToolLocks(editor: Editor, toolId: string) {
228
- if (toolId === 'geo') {
229
- // Rects: always a rough (hand-drawn) outline at a consistent stroke — never
230
- // inherit the pen's dashed/solid or its size.
231
- editor.setStyleForNextShapes(DefaultDashStyle, 'draw')
232
- editor.setStyleForNextShapes(DefaultSizeStyle, 'm')
233
- } else if (toolId === 'note') {
234
- editor.setStyleForNextShapes(DefaultFontStyle, 'draw')
235
- editor.setStyleForNextShapes(DefaultHorizontalAlignStyle, 'middle')
236
- editor.setStyleForNextShapes(DefaultVerticalAlignStyle, 'middle')
237
- ensurePaletteColor(editor, 'sticker', 'yellow')
238
- } else if (toolId === 'text') {
239
- editor.setStyleForNextShapes(DefaultFontStyle, 'draw')
240
- editor.setStyleForNextShapes(DefaultHorizontalAlignStyle, 'middle')
241
- editor.setStyleForNextShapes(DefaultVerticalAlignStyle, 'middle')
242
- } else if (toolId === 'highlight') {
243
- ensurePaletteColor(editor, 'highlight', 'yellow')
244
- } else if (toolId === 'arrow') {
245
- // Arrows don't expose dash — pin it rough to match the hand-drawn look and
246
- // never inherit a dashed/solid stroke from a previous tool.
247
- editor.setStyleForNextShapes(DefaultDashStyle, 'draw')
248
- } else if (toolId === 'draw' || toolId === 'line') {
249
- // Pen/line only offer rough or dashed — if we're arriving from a rect's
250
- // 'solid', fall back to rough so a valid dash is always selected.
251
- const dash = editor.getStyleForNextShape(DefaultDashStyle)
252
- if (dash !== 'draw' && dash !== 'dashed') {
253
- editor.setStyleForNextShapes(DefaultDashStyle, 'draw')
254
- }
255
- }
256
- }
257
-
258
- // Custom vertical tool bar, rendered as an overlay over the canvas (outside
259
- // tldraw's own UI layout). Tracks the current tool reactively via `react`.
260
- function ScratchToolbar({ editor }: ScratchToolbarProps) {
261
- const [toolId, setToolId] = useState(() => editor.getCurrentToolId())
262
-
263
- useEffect(() => {
264
- setToolId(editor.getCurrentToolId())
265
- return react('scratch current tool', () => setToolId(editor.getCurrentToolId()))
266
- }, [editor])
267
-
268
- const activate = (toolId: string) => {
269
- editor.run(() => {
270
- applyToolLocks(editor, toolId)
271
- editor.setCurrentTool(toolId)
272
- })
273
- }
274
-
275
- const selectRectangle = () => {
276
- editor.run(() => {
277
- editor.setStyleForNextShapes(GeoShapeGeoStyle, 'rectangle')
278
- applyToolLocks(editor, 'geo')
279
- editor.setCurrentTool('geo')
280
- })
281
- }
282
-
283
- return (
284
- <div className="absolute top-1/2 left-3 z-10 -translate-y-1/2">
285
- <motion.div
286
- initial={{ x: -72, opacity: 0 }}
287
- animate={{ x: 0, opacity: 1 }}
288
- transition={{ type: 'spring', bounce: 0.4, duration: 0.55 }}
289
- className="flex flex-col gap-1 rounded-xl bg-background/95 p-1 shadow-[0_2px_8px_rgba(0,0,0,0.08),0_4px_16px_rgba(0,0,0,0.06),0_0_0_1px_rgba(0,0,0,0.04)] backdrop-blur"
290
- >
291
- {TOOL_ENTRIES.map((entry, i) => {
292
- if (entry.kind === 'sep') {
293
- return <div key={`sep-${i}`} className="mx-1 my-0.5 h-px bg-border" />
294
- }
295
- if (entry.kind === 'geo') {
296
- return (
297
- <ToolButton
298
- key="geo"
299
- label={entry.label}
300
- Icon={entry.Icon}
301
- active={toolId === 'geo'}
302
- onClick={selectRectangle}
303
- />
304
- )
305
- }
306
- if (entry.kind === 'menu') {
307
- return (
308
- <ToolButton
309
- key="menu"
310
- label={entry.label}
311
- Icon={entry.Icon}
312
- active={false}
313
- onClick={() => {}}
314
- />
315
- )
316
- }
317
- return (
318
- <ToolButton
319
- key={entry.id}
320
- label={entry.label}
321
- Icon={entry.Icon}
322
- active={toolId === entry.id}
323
- onClick={() => activate(entry.id)}
324
- />
325
- )
326
- })}
327
- </motion.div>
328
- </div>
329
- )
330
- }
331
-
332
- // --- Second bar: per-tool contextual style controls -----------------------
333
- // Each tool exposes a different subset of controls (color/size/dash/fill). The
334
- // sub-bar shows the active tool's set, or — when the Select tool has a selection
335
- // — the union of the selected shapes' sets. Size maps small→'m', large→'xl'.
336
- // Sticker & text also lock align=center and font=rough (set on mount, not shown).
337
-
338
- type StyleControl = 'color' | 'size' | 'dash' | 'fill'
339
- const CONTROL_ORDER: StyleControl[] = ['color', 'size', 'dash', 'fill']
340
-
341
- // Controls exposed while a creating tool is active.
342
- const CONTROLS_BY_TOOL: Record<string, StyleControl[]> = {
343
- draw: ['color', 'size', 'dash'],
344
- geo: ['color', 'fill'],
345
- note: ['color', 'size'],
346
- text: ['color', 'size'],
347
- line: ['color', 'dash', 'size'],
348
- highlight: ['color', 'size'],
349
- arrow: ['color', 'size']
350
- }
351
-
352
- // Controls exposed per selected shape type (Select tool with a selection).
353
- const CONTROLS_BY_SHAPE: Record<string, StyleControl[]> = {
354
- draw: ['color', 'size', 'dash'],
355
- geo: ['color', 'fill'],
356
- note: ['color', 'size'],
357
- text: ['color', 'size'],
358
- line: ['color', 'dash', 'size'],
359
- highlight: ['color', 'size'],
360
- arrow: ['color', 'size']
361
- }
362
-
363
- // Three contextual color palettes (all subsets of tldraw's color enum):
364
- // regular (most tools), highlighter-friendly, and sticky-note pastels.
365
- type Swatch = { value: TLDefaultColorStyle; klass: string }
366
- type PaletteKind = 'regular' | 'highlight' | 'sticker'
367
- type Palette = { swatches: Swatch[] }
368
-
369
- // Swatch display hexes are tldraw's actual light-theme colors, picked to match
370
- // how each tool paints: regular → stroke `solid`, highlight → `highlightSrgb`,
371
- // sticker → `noteFill`.
372
- const PALETTES: Record<PaletteKind, Palette> = {
373
- regular: {
374
- swatches: [
375
- { value: 'black', klass: 'bg-[#1d1d1d]' },
376
- { value: 'red', klass: 'bg-[#e03131]' },
377
- { value: 'yellow', klass: 'bg-[#f1ac4b]' },
378
- { value: 'green', klass: 'bg-[#099268]' },
379
- { value: 'blue', klass: 'bg-[#4465e9]' },
380
- { value: 'grey', klass: 'bg-[#9fa8b2]' }
381
- ]
382
- },
383
- highlight: {
384
- swatches: [
385
- { value: 'yellow', klass: 'bg-[#fddd00]' },
386
- { value: 'green', klass: 'bg-[#00ffc8]' },
387
- { value: 'blue', klass: 'bg-[#10acff]' }
388
- ]
389
- },
390
- sticker: {
391
- swatches: [
392
- { value: 'yellow', klass: 'bg-[#fed49a]' },
393
- { value: 'blue', klass: 'bg-[#8aa3ff]' },
394
- { value: 'green', klass: 'bg-[#6fc896]' }
395
- ]
396
- }
397
- }
398
-
399
- // Which palette applies right now — by active creating tool, else by the single
400
- // selected shape type, else regular.
401
- function paletteKind(editor: Editor): PaletteKind {
402
- const toolId = editor.getCurrentToolId()
403
- if (toolId === 'highlight') return 'highlight'
404
- if (toolId === 'note') return 'sticker'
405
- if (CONTROLS_BY_TOOL[toolId]) return 'regular'
406
-
407
- const types = new Set(editor.getSelectedShapeIds().map(id => editor.getShape(id)?.type))
408
- if (types.size === 1) {
409
- if (types.has('highlight')) return 'highlight'
410
- if (types.has('note')) return 'sticker'
411
- }
412
- return 'regular'
413
- }
414
-
415
- // If the next-shape color isn't in `kind`'s palette, snap it to a sensible
416
- // default so the swatch row always has an active selection.
417
- function ensurePaletteColor(editor: Editor, kind: PaletteKind, fallback: TLDefaultColorStyle) {
418
- const values = PALETTES[kind].swatches.map(s => s.value)
419
- if (!values.includes(editor.getStyleForNextShape(DefaultColorStyle))) {
420
- editor.setStyleForNextShapes(DefaultColorStyle, fallback)
421
- }
422
- }
423
-
424
- // Two sizes only — small→'m', large→'xl'. Each option carries previews for the
425
- // three size renderings (see sizeGlyphKind): `dot` blob for most tools, `stroke`
426
- // pen-icon weight for the pencil, `glyph` letter px for text.
427
- const SIZE_OPTIONS: {
428
- value: TLDefaultSizeStyle
429
- label: string
430
- dot: string
431
- stroke: number
432
- glyph: number
433
- }[] = [
434
- { value: 'm', label: 'Small', dot: 'size-1.5', stroke: 1.5, glyph: 14 },
435
- { value: 'xl', label: 'Large', dot: 'size-3', stroke: 3, glyph: 22 }
436
- ]
437
-
438
- // Rough (hand-drawn) vs dashed stroke.
439
- const DASH_OPTIONS: { value: TLDefaultDashStyle; label: string; preview: string }[] = [
440
- { value: 'draw', label: 'Rough', preview: 'border-b-2 border-current' },
441
- { value: 'dashed', label: 'Dash', preview: 'border-b-2 border-dashed border-current' }
442
- ]
443
-
444
- // Three fills: empty, full color, hatch. (tldraw's translucent 'semi' read as
445
- // "stroke only", so we drop it — 'solid' is the fullest native color fill.)
446
- const FILL_OPTIONS: { value: TLDefaultFillStyle; label: string; preview: string }[] = [
447
- // tldraw quirk (see defaultFills): fillStyle 'solid' paints the lighter "semi"
448
- // color, while 'fill' paints the true solid (body === border color).
449
- { value: 'none', label: 'None', preview: 'border border-foreground/50' },
450
- { value: 'solid', label: 'Semi', preview: 'border border-foreground/40 bg-foreground/25' },
451
- { value: 'fill', label: 'Solid', preview: 'border border-foreground bg-foreground' },
452
- {
453
- value: 'pattern',
454
- label: 'Pattern',
455
- preview:
456
- 'border border-foreground/40 bg-[repeating-linear-gradient(45deg,currentColor_0,currentColor_1px,transparent_1px,transparent_3px)]'
457
- }
458
- ]
459
-
460
- // Read the active value of a style: shared value across the selection, or the
461
- // next-shape value when nothing is selected.
462
- function readStyleValue<T>(editor: Editor, style: StyleProp<T>): T | undefined {
463
- if (editor.getSelectedShapeIds().length > 0) {
464
- return editor.getSharedStyles().getAsKnownValue(style)
465
- }
466
- return editor.getStyleForNextShape(style)
467
- }
468
-
469
- // Apply to the selection (if any) and make it the default for the next shape.
470
- function applyStyle<T>(editor: Editor, style: StyleProp<T>, value: T) {
471
- editor.run(() => {
472
- editor.setStyleForNextShapes(style, value)
473
- if (editor.getSelectedShapeIds().length > 0) {
474
- editor.setStyleForSelectedShapes(style, value)
475
- }
476
- })
477
- }
478
-
479
- // Which controls the sub-bar should show right now: the active creating tool's
480
- // set, else the union for the current selection, else none (bar hidden).
481
- function activeControls(editor: Editor): StyleControl[] {
482
- const toolControls = CONTROLS_BY_TOOL[editor.getCurrentToolId()]
483
- if (toolControls) return toolControls
484
-
485
- const ids = editor.getSelectedShapeIds()
486
- if (ids.length === 0) return []
487
- const set = new Set<StyleControl>()
488
- for (const id of ids) {
489
- const shape = editor.getShape(id)
490
- if (!shape) continue
491
- for (const control of CONTROLS_BY_SHAPE[shape.type] ?? []) set.add(control)
492
- }
493
- return CONTROL_ORDER.filter(control => set.has(control))
494
- }
495
-
496
- // How the size control previews itself, matched to what "size" means for the
497
- // active tool: the pencil's is a stroke weight (pen glyph at varying strokes),
498
- // text's is a font size (a letter at varying sizes), everything else a plain blob.
499
- // Keyed off the active tool, or a uniform selection under the Select tool.
500
- function sizeGlyphKind(editor: Editor): 'pen' | 'letter' | 'dot' {
501
- const toolId = editor.getCurrentToolId()
502
- if (toolId === 'draw') return 'pen'
503
- if (toolId === 'text') return 'letter'
504
- const ids = editor.getSelectedShapeIds()
505
- const types = new Set(ids.map(id => editor.getShape(id)?.type))
506
- if (types.size === 1) {
507
- if (types.has('draw')) return 'pen'
508
- if (types.has('text')) return 'letter'
509
- }
510
- return 'dot'
511
- }
512
-
513
- type StyleBarState = {
514
- controls: StyleControl[]
515
- palette: Palette
516
- color: TLDefaultColorStyle | undefined
517
- size: TLDefaultSizeStyle | undefined
518
- sizeGlyph: 'pen' | 'letter' | 'dot'
519
- dash: TLDefaultDashStyle | undefined
520
- fill: TLDefaultFillStyle | undefined
521
- }
522
-
523
- function readStyleBarState(editor: Editor): StyleBarState {
524
- return {
525
- controls: activeControls(editor),
526
- palette: PALETTES[paletteKind(editor)],
527
- color: readStyleValue(editor, DefaultColorStyle),
528
- size: readStyleValue(editor, DefaultSizeStyle),
529
- sizeGlyph: sizeGlyphKind(editor),
530
- dash: readStyleValue(editor, DefaultDashStyle),
531
- fill: readStyleValue(editor, DefaultFillStyle)
532
- }
533
- }
534
-
535
- type ScratchStyleBarProps = { editor: Editor }
536
-
537
- function ScratchStyleBar({ editor }: ScratchStyleBarProps) {
538
- const [state, setState] = useState<StyleBarState>(() => readStyleBarState(editor))
539
-
540
- useEffect(() => {
541
- setState(readStyleBarState(editor))
542
- return react('scratch styles', () => setState(readStyleBarState(editor)))
543
- }, [editor])
544
-
545
- if (state.controls.length === 0) return null
546
-
547
- const groups: Record<StyleControl, ReactElement> = {
548
- color: (
549
- <div className="flex flex-col items-center gap-2 pt-1">
550
- {state.palette.swatches.map(c => (
551
- <button
552
- key={c.value}
553
- type="button"
554
- title={c.value}
555
- onClick={() => applyStyle(editor, DefaultColorStyle, c.value)}
556
- className={cn(
557
- 'size-5.5 rounded-full ring-offset-1 ring-offset-background',
558
- c.klass,
559
- state.color === c.value ? 'ring-2 ring-primary' : 'ring-1 ring-black/15'
560
- )}
561
- />
562
- ))}
563
- </div>
564
- ),
565
- size: (
566
- <div className="flex flex-col items-center gap-1 text-foreground">
567
- {SIZE_OPTIONS.map(s => (
568
- <button
569
- key={s.value}
570
- type="button"
571
- title={s.label}
572
- onClick={() => applyStyle(editor, DefaultSizeStyle, s.value)}
573
- className={cn(
574
- 'flex size-7.5 items-center justify-center rounded-full hover:bg-muted',
575
- state.size === s.value &&
576
- 'bg-muted-foreground/25 text-primary hover:bg-muted-foreground/25'
577
- )}
578
- >
579
- {state.sizeGlyph === 'pen' ? (
580
- <IconSketching size={18} stroke={s.stroke} />
581
- ) : state.sizeGlyph === 'letter' ? (
582
- <IconTypography size={s.glyph} stroke={1.5} />
583
- ) : (
584
- <span className={cn('rounded-full bg-current', s.dot)} />
585
- )}
586
- </button>
587
- ))}
588
- </div>
589
- ),
590
- dash: (
591
- <div className="flex flex-col items-center gap-1 text-foreground">
592
- {DASH_OPTIONS.map(d => (
593
- <button
594
- key={d.value}
595
- type="button"
596
- title={d.label}
597
- onClick={() => applyStyle(editor, DefaultDashStyle, d.value)}
598
- className={cn(
599
- 'flex size-7.5 items-center justify-center rounded-full hover:bg-muted',
600
- state.dash === d.value &&
601
- 'bg-muted-foreground/25 text-primary hover:bg-muted-foreground/25'
602
- )}
603
- >
604
- <span className={cn('w-3.5', d.preview)} />
605
- </button>
606
- ))}
607
- </div>
608
- ),
609
- fill: (
610
- <div className="flex flex-col items-center gap-1 text-foreground">
611
- {FILL_OPTIONS.map(f => (
612
- <button
613
- key={f.value}
614
- type="button"
615
- title={f.label}
616
- onClick={() => applyStyle(editor, DefaultFillStyle, f.value)}
617
- className={cn(
618
- 'flex size-7.5 items-center justify-center rounded-full hover:bg-muted',
619
- state.fill === f.value &&
620
- 'bg-muted-foreground/25 text-primary hover:bg-muted-foreground/25'
621
- )}
622
- >
623
- <span className={cn('size-4.5 rounded-sm', f.preview)} />
624
- </button>
625
- ))}
626
- </div>
627
- )
628
- }
629
-
630
- return (
631
- <div className="absolute top-1/2 left-15 z-10 flex -translate-y-1/2 flex-col items-center gap-1.5 rounded-full bg-background/95 px-1 py-1 shadow-[0_2px_8px_rgba(0,0,0,0.08),0_4px_16px_rgba(0,0,0,0.06),0_0_0_1px_rgba(0,0,0,0.04)] backdrop-blur">
632
- {state.controls.map((control, i) => (
633
- <Fragment key={control}>
634
- {i > 0 && <div className="h-px w-5 bg-border" />}
635
- {groups[control]}
636
- </Fragment>
637
- ))}
638
- </div>
639
- )
640
- }
641
-
642
- // --- Version-skew pre-flight ------------------------------------------------
643
- // tldraw snapshots migrate forward only: a canvas saved by a newer tldraw can
644
- // never load here, and handing it to <Tldraw> anyway lands on tldraw's crash
645
- // screen — whose main button is a destructive "Reset data". So every fetched
646
- // document is pre-flighted against this bundle's schema first; on failure we
647
- // render a friendly read-only notice and never mount the editor, which is what
648
- // guarantees this stale client can't autosave over the newer file. See
649
- // lib/scratchpad-skew.ts and docs/moi-scratchpad.md § Version skew.
650
-
651
- // What GET /api/workspaces/:id/scratchpad returns (see server/scratchpad.ts).
652
- type ScratchpadFetch = {
653
- document: TLEditorSnapshot['document'] | null
654
- writer?: ScratchpadWriter
655
- }
656
-
657
- // Why the canvas can't be shown: a newer writer (version skew) or a snapshot
658
- // that fails to load for some other reason. Either way the file is left alone.
659
- type ScratchpadSkew = { newer: boolean; writer?: ScratchpadWriter; detail: string }
660
-
661
- // This bundle's schema, built once and lazily — the same store config the
662
- // editor and the server executor use, so the pre-flight verdict matches what
663
- // <Tldraw> would do.
664
- let runtimeSchemaCache: TLStore['schema'] | null = null
665
- function runtimeSchema(): TLStore['schema'] {
666
- if (!runtimeSchemaCache) {
667
- runtimeSchemaCache = createTLStore({
668
- shapeUtils: defaultShapeUtils,
669
- bindingUtils: defaultBindingUtils
670
- }).schema
671
- }
672
- return runtimeSchemaCache
673
- }
674
-
675
- // Dry-run the migration <Tldraw>/`loadSnapshot` would perform. Returns null when
676
- // the document is safe to mount, else the skew to display.
677
- function detectSkew(
678
- document: NonNullable<TLEditorSnapshot['document']>,
679
- writer: ScratchpadWriter | undefined
680
- ): ScratchpadSkew | null {
681
- const schema = runtimeSchema()
682
- try {
683
- if (schema.migrateStoreSnapshot(document).type === 'success') return null
684
- } catch {}
685
- const ahead = sequencesAhead(document.schema, schema.serialize().sequences)
686
- if (ahead.length > 0) return { newer: true, writer, detail: describeNewerWriter(writer, ahead) }
687
- return { newer: false, writer, detail: 'The saved snapshot failed to load.' }
688
- }
689
-
690
- // Hydrate the saved canvas once per workspace from the REST snapshot endpoint.
691
- // Returns a STABLE snapshot reference (held in a ref, never a fresh object per
692
- // render): tldraw rebuilds its entire store whenever the `snapshot` prop identity
693
- // changes, so handing it a new object each render loops it forever — remounting the
694
- // store and re-fetching fonts/translations endlessly. `document: null` → empty
695
- // canvas; `loaded` gates the placeholder until the fetch settles. A document that
696
- // fails the pre-flight sets `skew` instead of the snapshot; `flagSkew` lets the
697
- // remote-reload path flip the same state mid-session.
698
- function useScratchpadSnapshot(workspaceId: string): {
699
- loaded: boolean
700
- snapshot: Partial<TLEditorSnapshot> | undefined
701
- skew: ScratchpadSkew | null
702
- flagSkew: (skew: ScratchpadSkew) => void
703
- } {
704
- const [loaded, setLoaded] = useState(false)
705
- const [skew, setSkew] = useState<ScratchpadSkew | null>(null)
706
- const snapshot = useRef<Partial<TLEditorSnapshot> | undefined>(undefined)
707
-
708
- useEffect(() => {
709
- let cancelled = false
710
- setLoaded(false)
711
- setSkew(null)
712
- snapshot.current = undefined
713
- fetch(`/api/workspaces/${workspaceId}/scratchpad`)
714
- .then(r => r.json())
715
- .then((d: ScratchpadFetch) => {
716
- if (cancelled) return
717
- if (d?.document) {
718
- const found = detectSkew(d.document, d.writer)
719
- if (found) setSkew(found)
720
- else snapshot.current = { document: d.document }
721
- }
722
- setLoaded(true)
723
- })
724
- .catch(() => {
725
- if (!cancelled) setLoaded(true)
726
- })
727
- return () => {
728
- cancelled = true
729
- }
730
- }, [workspaceId])
731
-
732
- return { loaded, snapshot: snapshot.current, skew, flagSkew: setSkew }
733
- }
734
-
735
- type ScratchpadSkewNoticeProps = { skew: ScratchpadSkew }
736
-
737
- // The read-only stand-in for an unloadable canvas. Deliberately mounts no
738
- // editor and offers no "load anyway": with no store there is nothing to
739
- // autosave, so the newer file on disk stays byte-for-byte intact.
740
- function ScratchpadSkewNotice({ skew }: ScratchpadSkewNoticeProps) {
741
- return (
742
- <div className="flex min-h-0 flex-1 items-center justify-center bg-muted/40 bg-[radial-gradient(var(--color-border)_1px,transparent_1px)] [background-size:16px_16px] p-6">
743
- <div className="flex max-w-md animate-in flex-col gap-3 rounded-md bg-background p-6 shadow-xs duration-200 fade-in-0 zoom-in-95">
744
- <div className="flex items-center gap-2">
745
- <IconVersions size={20} stroke={1.5} className="shrink-0 text-amber-600" />
746
- <h2 className="font-medium text-foreground">
747
- {skew.newer ? 'This canvas needs a newer moi' : 'This canvas couldn’t be loaded'}
748
- </h2>
749
- </div>
750
- {skew.newer ? (
751
- <>
752
- <p className="text-sm text-pretty text-muted-foreground">
753
- This scratchpad was saved by a newer version of moi
754
- {skew.writer ? ` (v${skew.writer.moi})` : ''}.<br /> Please update moi and restart the
755
- server:
756
- </p>
757
- <code className="self-start rounded bg-muted px-2 py-1 font-mono text-xs text-foreground">
758
- bun install -g moi-computer@latest
759
- </code>
760
- </>
761
- ) : (
762
- <p className="text-sm text-muted-foreground">{skew.detail}</p>
763
- )}
764
- </div>
765
- </div>
766
- )
767
- }
768
-
769
- // The Scratchpad surface: a real tldraw editor, hydrated from and autosaved to
770
- // `.moi/.scratchpad.json` via REST. One canvas shared by the user and the agent —
771
- // the agent reaches it through `moi scratch` (relayed ops execute here). See
772
- // docs/moi-scratchpad.md.
773
- export function Scratchpad() {
774
- const workspaceId = useWorkspaceId()
775
- const editorRef = useRef<Editor | null>(null)
776
- // The whole scratchpad region (canvas + tool bar + style bar). Focus is driven
777
- // off whether a pointerdown lands inside this, so clicking a tool keeps the
778
- // editor focused — see the pointerdown handler in onMount.
779
- const rootRef = useRef<HTMLDivElement>(null)
780
- const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
781
- // Set before a remote `loadSnapshot`; the autosave listener consumes it on the
782
- // first (throttled) flush so the load doesn't echo back out as a save. (Store
783
- // listeners fire on the next frame, not synchronously, so a timer-based clear
784
- // would race — consuming it in the listener is timing-independent.)
785
- const applyingRemote = useRef(false)
786
- // Reactive handle to the mounted editor, used to render the custom tool bar.
787
- const [editor, setEditor] = useState<Editor | null>(null)
788
- const { loaded, snapshot, skew, flagSkew } = useScratchpadSnapshot(workspaceId)
789
- // Stable identity per workspace, held in a ref rather than useMemo (which React
790
- // may discard): a fresh `assets` identity makes <Tldraw> rebuild its store and
791
- // remount the editor, dropping unsaved edits and resetting the camera.
792
- const assetStoreRef = useRef<{ id: string; store: TLAssetStore } | null>(null)
793
- if (assetStoreRef.current?.id !== workspaceId) {
794
- assetStoreRef.current = { id: workspaceId, store: makeAssetStore(workspaceId) }
795
- }
796
- const assetStore = assetStoreRef.current.store
797
-
798
- const save = useCallback(() => {
799
- const editor = editorRef.current
800
- if (!editor) return
801
- let document: TLEditorSnapshot['document']
802
- try {
803
- document = getSnapshot(editor.store).document
804
- } catch {
805
- return
806
- }
807
- void fetch(`/api/workspaces/${workspaceId}/scratchpad`, {
808
- method: 'PUT',
809
- headers: { 'Content-Type': 'application/json' },
810
- body: JSON.stringify({ document, origin: ORIGIN_ID })
811
- }).catch(() => {})
812
- }, [workspaceId])
813
-
814
- // A remote save (another tab, or an agent draw landing in another tab) — pull
815
- // the new snapshot and load it into the live store. Skip our own echo. The
816
- // fetched document is pre-flighted like the initial load: if the server was
817
- // swapped for a newer moi mid-session, `loadSnapshot` here would throw — flip
818
- // the skew notice instead (unmounting the editor, which also stops the
819
- // autosave timer) so this stale tab can't save over the newer file.
820
- useMeiEvent((e: MeiEvent) => {
821
- if (e.type !== 'scratchpad:updated' || e.workspaceId !== workspaceId) return
822
- if (e.origin && e.origin === ORIGIN_ID) return
823
- if (!editorRef.current) return
824
- fetch(`/api/workspaces/${workspaceId}/scratchpad`)
825
- .then(r => r.json())
826
- .then((d: ScratchpadFetch) => {
827
- const editor = editorRef.current
828
- if (!editor || !d?.document) return
829
- const found = detectSkew(d.document, d.writer)
830
- if (found) {
831
- if (saveTimer.current) clearTimeout(saveTimer.current)
832
- flagSkew(found)
833
- return
834
- }
835
- applyingRemote.current = true
836
- loadSnapshot(editor.store, { document: d.document })
837
- })
838
- .catch(() => {})
839
- })
840
-
841
- const onMount = useCallback(
842
- (editor: Editor) => {
843
- editorRef.current = editor
844
- setEditor(editor)
845
- // Grid on by default (no toggle in the UI).
846
- editor.updateInstanceState({ isGridMode: true })
847
- // Locked defaults that have no UI control: hand-drawn font, centered text.
848
- editor.run(() => {
849
- editor.setStyleForNextShapes(DefaultFontStyle, 'draw')
850
- editor.setStyleForNextShapes(DefaultHorizontalAlignStyle, 'middle')
851
- editor.setStyleForNextShapes(DefaultVerticalAlignStyle, 'middle')
852
- // Rectangles start solid-filled. Still user-adjustable via the style bar —
853
- // applyToolLocks deliberately never re-pins fill, so this is a default, not
854
- // a lock. ('fill' = the style bar's "Solid"; 'solid' there means "Semi".)
855
- editor.setStyleForNextShapes(DefaultFillStyle, 'fill')
856
- })
857
- const unlisten = editor.store.listen(
858
- () => {
859
- if (applyingRemote.current) {
860
- applyingRemote.current = false
861
- return
862
- }
863
- if (saveTimer.current) clearTimeout(saveTimer.current)
864
- saveTimer.current = setTimeout(save, AUTOSAVE_MS)
865
- },
866
- { source: 'user', scope: 'document' }
867
- )
868
- setScratchExecutor(workspaceId, makeExecutor(editor))
869
- // Focus management: tldraw only fires keyboard shortcuts while the editor's
870
- // instance `isFocused` is set, but with `autoFocus={false}` it never flips
871
- // that on its own. We drive it from where the pointer lands — a pointerdown
872
- // inside the scratchpad (canvas, tool bar, or style bar, all under rootRef)
873
- // focuses the editor; one anywhere else (e.g. the chat) blurs it, so hotkeys
874
- // are live only when the scratchpad is the active surface. Guarded on the
875
- // current state so a click already inside (e.g. double-click to edit a
876
- // shape's text) doesn't re-focus the container and steal focus from the
877
- // text field. Capture phase so we see it regardless of downstream handlers.
878
- const onPointerDown = (e: PointerEvent) => {
879
- const target = e.target as Node | null
880
- const inside = !!target && !!rootRef.current?.contains(target)
881
- if (inside) {
882
- if (!editor.getIsFocused()) editor.focus()
883
- } else if (editor.getIsFocused()) {
884
- editor.blur()
885
- }
886
- }
887
- const doc = editor.getContainerDocument()
888
- doc.addEventListener('pointerdown', onPointerDown, true)
889
- // First open: grab focus so the user can reach for the keyboard right away.
890
- // `focus()` both sets `isFocused` and DOM-focuses the canvas container, so it
891
- // becomes the active element — clearing tldraw's secondary guard that mutes
892
- // shortcuts while an input/textarea (e.g. the chat) holds focus.
893
- editor.focus()
894
- return () => {
895
- unlisten()
896
- doc.removeEventListener('pointerdown', onPointerDown, true)
897
- if (saveTimer.current) clearTimeout(saveTimer.current)
898
- setScratchExecutor(workspaceId, null)
899
- setEditor(null)
900
- editorRef.current = null
901
- }
902
- },
903
- [workspaceId, save]
904
- )
905
-
906
- if (!loaded) return <div className="min-h-0 flex-1 bg-muted/40" />
907
- if (skew) return <ScratchpadSkewNotice skew={skew} />
908
-
909
- return (
910
- <div ref={rootRef} className="relative min-h-0 flex-1 overflow-hidden">
911
- <div className="absolute inset-0">
912
- <Tldraw
913
- snapshot={snapshot}
914
- assets={assetStore}
915
- licenseKey={LICENSE_KEY}
916
- onMount={onMount}
917
- components={SCRATCH_COMPONENTS}
918
- overrides={SCRATCH_OVERRIDES}
919
- options={SCRATCH_OPTIONS}
920
- // Accept drops up to 32MB and rescale big images to fit (tldraw checks
921
- // the size before rescaling, so a large photo is admitted then shrunk).
922
- maxAssetSize={MAX_DROP_BYTES}
923
- maxImageDimension={MAX_IMAGE_DIMENSION}
924
- // Hand focus control entirely to us: tldraw's own `autoFocus` only seeds
925
- // the `isFocused` flag (hotkeys would fire window-wide, even from the
926
- // chat) without ever DOM-focusing the canvas. Instead onMount focuses
927
- // the editor on open and a pointerdown handler toggles it thereafter.
928
- autoFocus={false}
929
- />
930
- </div>
931
- {editor && <ScratchToolbar editor={editor} />}
932
- {editor && <ScratchStyleBar editor={editor} />}
933
- </div>
934
- )
935
- }