moi-computer 0.0.1

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 (106) hide show
  1. package/LICENSE +95 -0
  2. package/README.md +71 -0
  3. package/bin/moi.mjs +25 -0
  4. package/bunfig.toml +3 -0
  5. package/client/CLAUDE.md +12 -0
  6. package/client/api/workspaces.ts +158 -0
  7. package/client/assets/claude.svg +3 -0
  8. package/client/assets/favicon.png +0 -0
  9. package/client/assets/hermes-nous.png +0 -0
  10. package/client/assets/mcp/.gitkeep +0 -0
  11. package/client/assets/mcp/atlassian.png +0 -0
  12. package/client/assets/mcp/discord.png +0 -0
  13. package/client/assets/mcp/figma.png +0 -0
  14. package/client/assets/mcp/github.png +0 -0
  15. package/client/assets/mcp/gitlab.png +0 -0
  16. package/client/assets/mcp/granola.png +0 -0
  17. package/client/assets/mcp/hubspot.png +0 -0
  18. package/client/assets/mcp/linear.png +0 -0
  19. package/client/assets/mcp/neon.png +0 -0
  20. package/client/assets/mcp/notion.png +0 -0
  21. package/client/assets/mcp/sentry.png +0 -0
  22. package/client/assets/mcp/slack.png +0 -0
  23. package/client/assets/mcp/stripe.png +0 -0
  24. package/client/assets/mcp/supabase.png +0 -0
  25. package/client/assets/mcp/vercel.png +0 -0
  26. package/client/assets/moi-logo.svg +11 -0
  27. package/client/assets/openclaw.svg +22 -0
  28. package/client/components/App.tsx +35 -0
  29. package/client/components/BottomPanel.tsx +33 -0
  30. package/client/components/ChatInput.tsx +62 -0
  31. package/client/components/ChatPanel.tsx +206 -0
  32. package/client/components/ChatPopup.tsx +60 -0
  33. package/client/components/CustomizePanel.tsx +117 -0
  34. package/client/components/HiddenPanel.tsx +79 -0
  35. package/client/components/HomePage.tsx +17 -0
  36. package/client/components/MarkdownContent.tsx +41 -0
  37. package/client/components/ThreadSelector.tsx +88 -0
  38. package/client/components/TurnView.tsx +618 -0
  39. package/client/components/WidgetErrorBoundary.tsx +46 -0
  40. package/client/components/WidgetFrame.tsx +66 -0
  41. package/client/components/WidgetGrid.tsx +113 -0
  42. package/client/components/WidgetShell.tsx +44 -0
  43. package/client/components/Widgets.tsx +132 -0
  44. package/client/components/WorkspacePreview.tsx +48 -0
  45. package/client/components/WorkspacesPage.tsx +237 -0
  46. package/client/components/layout/SidebarLayout.tsx +260 -0
  47. package/client/components/playground/LedLogo.tsx +181 -0
  48. package/client/components/playground/PixelPainter.tsx +105 -0
  49. package/client/components/playground/PlaygroundPage.tsx +71 -0
  50. package/client/components/routes/workspace/[id].tsx +282 -0
  51. package/client/components/ui/button.tsx +48 -0
  52. package/client/components/ui/dropdown-menu.tsx +257 -0
  53. package/client/components/ui/input.tsx +21 -0
  54. package/client/components/ui/popover.tsx +79 -0
  55. package/client/components/ui/textarea.tsx +18 -0
  56. package/client/externalize-react.ts +29 -0
  57. package/client/hooks/useChat.ts +88 -0
  58. package/client/hooks/useFitsSidebar.ts +34 -0
  59. package/client/hooks/useGridReconcile.ts +73 -0
  60. package/client/hooks/useMeiEvents.ts +66 -0
  61. package/client/hooks/useScrollFade.ts +38 -0
  62. package/client/hooks/useWidget.ts +72 -0
  63. package/client/hooks/useWidgetList.ts +30 -0
  64. package/client/hooks/useWorkspaceTheme.ts +76 -0
  65. package/client/index.css +182 -0
  66. package/client/index.html +43 -0
  67. package/client/index.tsx +19 -0
  68. package/client/lib/WorkspaceContext.tsx +24 -0
  69. package/client/lib/WorkspaceLayoutContext.tsx +92 -0
  70. package/client/lib/cn.ts +6 -0
  71. package/client/lib/grid-pack.ts +35 -0
  72. package/client/lib/group-turns.ts +44 -0
  73. package/client/lib/mcp-icons.ts +53 -0
  74. package/client/lib/ws.ts +129 -0
  75. package/client/main.tsx +23 -0
  76. package/client/store/chat.tsx +162 -0
  77. package/client/store/ui.ts +21 -0
  78. package/client/theme.css +66 -0
  79. package/lib/claude-adapter.ts +602 -0
  80. package/lib/format.ts +212 -0
  81. package/lib/themes.ts +89 -0
  82. package/lib/types.ts +144 -0
  83. package/package.json +117 -0
  84. package/server/CLAUDE.md +6 -0
  85. package/server/agent.ts +132 -0
  86. package/server/build-widget.ts +343 -0
  87. package/server/cli.ts +632 -0
  88. package/server/constants.ts +3 -0
  89. package/server/control.ts +98 -0
  90. package/server/functions-worker.ts +89 -0
  91. package/server/functions.ts +171 -0
  92. package/server/layout.ts +83 -0
  93. package/server/openclaw-adapter.ts +242 -0
  94. package/server/openclaw-gateway.ts +255 -0
  95. package/server/openclaw-session.ts +485 -0
  96. package/server/openclaw-strip.ts +134 -0
  97. package/server/openclaw.ts +206 -0
  98. package/server/registry.ts +150 -0
  99. package/server/skills-template.ts +21 -0
  100. package/server/state.ts +87 -0
  101. package/server/theme.ts +55 -0
  102. package/server/web.ts +321 -0
  103. package/server/widgets.ts +254 -0
  104. package/tsconfig.json +21 -0
  105. package/workspace/.claude/skills/widgets/DESIGN.md +630 -0
  106. package/workspace/.claude/skills/widgets/SKILL.md +176 -0
@@ -0,0 +1,18 @@
1
+ import type { ComponentProps } from 'react'
2
+
3
+ import { cn } from '@/client/lib/cn'
4
+
5
+ function Textarea({ className, ...props }: ComponentProps<'textarea'>) {
6
+ return (
7
+ <textarea
8
+ data-slot="textarea"
9
+ className={cn(
10
+ 'flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-2.5 py-2 text-sm transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40',
11
+ className
12
+ )}
13
+ {...props}
14
+ />
15
+ )
16
+ }
17
+
18
+ export { Textarea }
@@ -0,0 +1,29 @@
1
+ import type { BunPlugin } from 'bun'
2
+
3
+ const esmModules = [
4
+ 'react',
5
+ 'react/jsx-runtime',
6
+ 'react/jsx-dev-runtime',
7
+ 'react-dom',
8
+ 'react-dom/client',
9
+ ]
10
+
11
+ const externalizeReact: BunPlugin = {
12
+ name: 'externalize-react',
13
+ setup(build) {
14
+ build.onResolve({ filter: /^react(-dom)?(\/.*)?$/ }, (args) => {
15
+ if (esmModules.includes(args.path)) {
16
+ return { path: args.path, namespace: 'esm' }
17
+ }
18
+ })
19
+
20
+ build.onLoad({ filter: /.*/, namespace: 'esm' }, (args) => {
21
+ return {
22
+ contents: `module.exports = globalThis.__esm["${args.path}"];`,
23
+ loader: 'js',
24
+ }
25
+ })
26
+ },
27
+ }
28
+
29
+ export default externalizeReact
@@ -0,0 +1,88 @@
1
+ import { useCallback, useEffect } from 'react'
2
+ import { useState } from 'react'
3
+
4
+ import { useWorkspaceId } from '@/client/lib/WorkspaceContext'
5
+ import { connectWs, disconnectWs, sendWs } from '@/client/lib/ws'
6
+ import { useChatStore, useChatStoreApi } from '@/client/store/chat'
7
+ import { emptyViewState } from '@/lib/format'
8
+ import type { ViewState } from '@/lib/types'
9
+
10
+ const EMPTY: ViewState = emptyViewState()
11
+
12
+ export function useChat() {
13
+ const workspaceId = useWorkspaceId()
14
+ const store = useChatStoreApi()
15
+ const [input, setInput] = useState('')
16
+
17
+ const activeSessionId = useChatStore(s => s.activeSessionId)
18
+ const setActiveSession = useChatStore(s => s.setActiveSession)
19
+
20
+ const view = useChatStore(s => s.views[activeSessionId ?? ''] ?? EMPTY)
21
+ const processing = useChatStore(s => s.processing[activeSessionId ?? ''] ?? false)
22
+ const error = useChatStore(s => s.errors[activeSessionId ?? ''] ?? null)
23
+
24
+ // Persistent WS for live events — reconnects if workspace changes. Hands the
25
+ // workspace's chat store to the (non-React) socket layer so it writes there.
26
+ useEffect(() => {
27
+ connectWs(workspaceId, store)
28
+ return () => disconnectWs()
29
+ }, [workspaceId, store])
30
+
31
+ // When active session changes and we don't have its events cached, fetch them
32
+ useEffect(() => {
33
+ if (!activeSessionId) return
34
+ if (store.getState().events[activeSessionId] !== undefined) return
35
+ store.getState().loadEvents(workspaceId, activeSessionId)
36
+ }, [workspaceId, activeSessionId, store])
37
+
38
+ const send = useCallback(() => {
39
+ const text = input.trim()
40
+ if (!text || processing) return
41
+
42
+ let sid = activeSessionId
43
+ let isNew = false
44
+ if (!sid) {
45
+ sid = crypto.randomUUID()
46
+ isNew = true
47
+ store.getState().setEvents(sid, [])
48
+ setActiveSession(sid)
49
+ }
50
+
51
+ // Optimistic user turn — rendered immediately, upserted in place when the
52
+ // SDK echoes it back via expectUserEcho on the server.
53
+ const optimisticId = `optimistic:${crypto.randomUUID()}`
54
+ store.getState().append(sid, {
55
+ kind: 'turn',
56
+ turn: {
57
+ id: optimisticId,
58
+ role: 'user',
59
+ origin: { kind: 'user-input' },
60
+ parts: [{ type: 'text', text }],
61
+ timestamp: new Date().toISOString()
62
+ }
63
+ })
64
+
65
+ sendWs({ type: 'chat', content: text, sessionId: sid, isNew, optimisticId })
66
+ store.getState().setError(sid, null)
67
+ setInput('')
68
+ }, [input, processing, activeSessionId, setActiveSession, store])
69
+
70
+ const dismissError = useCallback(() => {
71
+ if (!activeSessionId) return
72
+ store.getState().setError(activeSessionId, null)
73
+ }, [activeSessionId, store])
74
+
75
+ const stop = useCallback(() => {
76
+ if (!processing || !activeSessionId) return
77
+ sendWs({ type: 'stop', sessionId: activeSessionId })
78
+ }, [processing, activeSessionId])
79
+
80
+ const switchThread = useCallback(
81
+ (sessionId: string | null) => {
82
+ setActiveSession(sessionId)
83
+ },
84
+ [setActiveSession]
85
+ )
86
+
87
+ return { view, processing, error, input, setInput, send, stop, switchThread, dismissError }
88
+ }
@@ -0,0 +1,34 @@
1
+ import { useEffect, useRef, useState } from 'react'
2
+
3
+ // Resolve a CSS length token (px or rem) defined on :root to pixels, so the fit
4
+ // math shares the layout tokens in index.css rather than duplicating values.
5
+ function tokenPx(name: string): number {
6
+ const root = document.documentElement
7
+ const raw = getComputedStyle(root).getPropertyValue(name).trim()
8
+ const value = parseFloat(raw)
9
+ return raw.endsWith('rem') ? value * parseFloat(getComputedStyle(root).fontSize) : value
10
+ }
11
+
12
+ // Observe the content row (full panel width — stable regardless of whether the
13
+ // chat is docked) and dock the chat only while the widget area would stay at
14
+ // its content width (--column-w) once the chat takes its minimum (--chat-min).
15
+ // Measuring the widget area element directly would oscillate: docking shrinks
16
+ // it back under the threshold, which would undock it, which would grow it, etc.
17
+ export function useFitsSidebar<T extends HTMLElement>() {
18
+ const ref = useRef<T>(null)
19
+ const [fits, setFits] = useState(false)
20
+
21
+ useEffect(() => {
22
+ const el = ref.current
23
+ if (!el) return
24
+ const minWidget = tokenPx('--column-w')
25
+ const chatMin = tokenPx('--chat-min')
26
+ const ro = new ResizeObserver(([entry]) => {
27
+ if (entry) setFits(entry.contentRect.width - chatMin >= minWidget)
28
+ })
29
+ ro.observe(el)
30
+ return () => ro.disconnect()
31
+ }, [])
32
+
33
+ return { ref, fits }
34
+ }
@@ -0,0 +1,73 @@
1
+ import { useEffect, useRef } from 'react'
2
+
3
+ import { findFreePosition } from '@/client/lib/grid-pack'
4
+ import type { WidgetInfo, WorkspaceLayout } from '@/lib/types'
5
+
6
+ // Rebalances the widget grid as the (server-authoritative) widget set changes.
7
+ // The widgets list is the source of truth for what exists; the layout grid only
8
+ // carries positions. Placement is derived here and persisted via `setLayout`
9
+ // (the layout mutation):
10
+ // - a brand-new widget (never seen) with no grid slot → gets packed in
11
+ // - a visible widget whose config size changed → re-packed
12
+ // - a widget the user hid (known, absent from the grid) → left hidden
13
+ //
14
+ // On the first resolution per workspace nothing is placed: the saved grid is
15
+ // authoritative, so hidden widgets stay hidden and visible ones keep positions.
16
+ // This runs on every widgets change (including focus/switch-back refetches) but
17
+ // is a no-op when the set is unchanged, so it never loops or un-hides widgets.
18
+ export function useGridReconcile(
19
+ workspaceId: string,
20
+ widgets: WidgetInfo[] | undefined,
21
+ layout: WorkspaceLayout,
22
+ setLayout: (update: Partial<WorkspaceLayout>) => void
23
+ ) {
24
+ // Last-seen widget sizes, scoped to the workspace it was recorded for.
25
+ const baseline = useRef<{
26
+ workspaceId: string
27
+ sizes: Map<string, { w: number; h: number }>
28
+ } | null>(null)
29
+
30
+ useEffect(() => {
31
+ if (!widgets) return
32
+ const sizes = new Map(widgets.map(w => [w.id, { w: w.config.colSpan, h: w.config.rowSpan }]))
33
+
34
+ // First sight of this workspace's widgets — trust the saved grid, move nothing.
35
+ if (baseline.current?.workspaceId !== workspaceId) {
36
+ baseline.current = { workspaceId, sizes }
37
+ return
38
+ }
39
+
40
+ const prev = baseline.current.sizes
41
+ const gridIds = new Set(layout.widgetGrid.map(g => g.i))
42
+ const needsPositioning = widgets.filter(w => {
43
+ const known = prev.has(w.id)
44
+ if (!known) return !gridIds.has(w.id) // new widget with no slot → place it
45
+ if (!gridIds.has(w.id)) return false // known + hidden by the user → leave it hidden
46
+ const p = prev.get(w.id)! // visible → re-pack only if its size changed
47
+ return p.w !== w.config.colSpan || p.h !== w.config.rowSpan
48
+ })
49
+
50
+ baseline.current = { workspaceId, sizes }
51
+ if (needsPositioning.length === 0) return
52
+
53
+ // Keep untouched widgets where they are; reconstruct w/h from config for
54
+ // overlap detection, then pack the ones that need a (new) position.
55
+ const newConfig = new Map(widgets.map(w => [w.id, w.config]))
56
+ const kept = layout.widgetGrid
57
+ .filter(g => !needsPositioning.some(w => w.id === g.i) && newConfig.has(g.i))
58
+ .map(g => {
59
+ const c = newConfig.get(g.i)!
60
+ return { i: g.i, x: g.x, y: g.y, w: c.colSpan, h: c.rowSpan }
61
+ })
62
+
63
+ const grid = kept.map(({ i, x, y }) => ({ i, x, y }))
64
+ const placed = [...kept]
65
+ for (const w of needsPositioning) {
66
+ const pos = findFreePosition(placed, w.config.colSpan, w.config.rowSpan, 4)
67
+ grid.push({ i: w.id, x: pos.x, y: pos.y })
68
+ placed.push({ i: w.id, x: pos.x, y: pos.y, w: w.config.colSpan, h: w.config.rowSpan })
69
+ }
70
+
71
+ setLayout({ widgetGrid: grid })
72
+ }, [workspaceId, widgets, layout.widgetGrid, setLayout])
73
+ }
@@ -0,0 +1,66 @@
1
+ import { useEffect, useRef } from 'react'
2
+
3
+ import type { WidgetInfo } from '@/lib/types'
4
+
5
+ type MeiEvent =
6
+ | { type: 'widget:updated'; name: string }
7
+ | { type: 'widget-layout:updated'; widgets: WidgetInfo[] }
8
+ | { type: 'theme:updated' }
9
+
10
+ type MeiEventHandler = (event: MeiEvent) => void
11
+
12
+ const listeners = new Set<MeiEventHandler>()
13
+ let ws: WebSocket | null = null
14
+ let connecting = false
15
+
16
+ function ensureConnection() {
17
+ if (ws || connecting) return
18
+ connecting = true
19
+
20
+ const socket = new WebSocket(`ws://${location.host}/api/workspaces/ws`)
21
+
22
+ socket.onopen = () => {
23
+ ws = socket
24
+ connecting = false
25
+ }
26
+
27
+ socket.onmessage = event => {
28
+ try {
29
+ const data = JSON.parse(event.data) as MeiEvent
30
+ for (const handler of listeners) handler(data)
31
+ } catch {}
32
+ }
33
+
34
+ socket.onclose = () => {
35
+ ws = null
36
+ connecting = false
37
+ // Reconnect after 2s if there are still listeners
38
+ if (listeners.size > 0) {
39
+ setTimeout(ensureConnection, 2000)
40
+ }
41
+ }
42
+
43
+ socket.onerror = () => {
44
+ socket.close()
45
+ }
46
+ }
47
+
48
+ export function useMeiEvent(handler: MeiEventHandler) {
49
+ const handlerRef = useRef(handler)
50
+ handlerRef.current = handler
51
+
52
+ useEffect(() => {
53
+ const wrapped: MeiEventHandler = e => handlerRef.current(e)
54
+ listeners.add(wrapped)
55
+ ensureConnection()
56
+
57
+ return () => {
58
+ listeners.delete(wrapped)
59
+ // Close WS if no more listeners
60
+ if (listeners.size === 0 && ws) {
61
+ ws.close()
62
+ ws = null
63
+ }
64
+ }
65
+ }, [])
66
+ }
@@ -0,0 +1,38 @@
1
+ import { type RefObject, useEffect, useRef, useState } from 'react'
2
+
3
+ type ScrollFadeState = {
4
+ ref: RefObject<HTMLDivElement | null>
5
+ showTopFade: boolean
6
+ showBottomFade: boolean
7
+ }
8
+
9
+ export function useScrollFade(): ScrollFadeState {
10
+ const ref = useRef<HTMLDivElement>(null)
11
+ const [showTopFade, setShowTopFade] = useState(false)
12
+ const [showBottomFade, setShowBottomFade] = useState(false)
13
+
14
+ useEffect(() => {
15
+ const el = ref.current
16
+ if (!el) return
17
+
18
+ const updateFades = () => {
19
+ const atTop = el.scrollTop <= 1
20
+ const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1
21
+ const scrollable = el.scrollHeight > el.clientHeight + 1
22
+
23
+ setShowTopFade(scrollable && !atTop)
24
+ setShowBottomFade(scrollable && !atBottom)
25
+ }
26
+
27
+ updateFades()
28
+ el.addEventListener('scroll', updateFades, { passive: true })
29
+ window.addEventListener('resize', updateFades)
30
+
31
+ return () => {
32
+ el.removeEventListener('scroll', updateFades)
33
+ window.removeEventListener('resize', updateFades)
34
+ }
35
+ }, [])
36
+
37
+ return { ref, showTopFade, showBottomFade }
38
+ }
@@ -0,0 +1,72 @@
1
+ import type { ComponentType } from 'react'
2
+ import { useCallback, useEffect, useState } from 'react'
3
+
4
+ import { useWorkspaceId } from '@/client/lib/WorkspaceContext'
5
+
6
+ import { useMeiEvent } from './useMeiEvents'
7
+
8
+ type WidgetState =
9
+ | { status: 'loading'; version: number }
10
+ | { status: 'ready'; Component: ComponentType; version: number }
11
+ | { status: 'error'; error: string; version: number }
12
+
13
+ const moduleCache = new Map<string, Promise<ComponentType>>()
14
+ let version = 0
15
+
16
+ function loadWidget(workspaceId: string, name: string, bust: boolean): Promise<ComponentType> {
17
+ const key = `${workspaceId}/${name}`
18
+ if (bust) {
19
+ moduleCache.delete(key)
20
+ version++
21
+ }
22
+
23
+ const existing = moduleCache.get(key)
24
+ if (existing) return existing
25
+
26
+ // Cache-busting query param so the browser fetches fresh
27
+ const url = `/api/workspaces/${workspaceId}/widgets/${name}.js?v=${version}`
28
+ const promise = import(/* @vite-ignore */ url).then(mod => {
29
+ if (!mod.default) throw new Error(`Widget "${name}" has no default export`)
30
+ return mod.default as ComponentType
31
+ })
32
+
33
+ moduleCache.set(key, promise)
34
+ return promise
35
+ }
36
+
37
+ export function useWidget(name: string): WidgetState {
38
+ const workspaceId = useWorkspaceId()
39
+ const [state, setState] = useState<WidgetState>({ status: 'loading', version: 0 })
40
+
41
+ const load = useCallback(
42
+ (bust = false) => {
43
+ setState(prev => ({ status: 'loading', version: prev.version }))
44
+ loadWidget(workspaceId, name, bust)
45
+ .then(Component =>
46
+ setState(prev => ({ status: 'ready', Component, version: prev.version + 1 }))
47
+ )
48
+ .catch(err =>
49
+ setState(prev => ({ status: 'error', error: String(err), version: prev.version + 1 }))
50
+ )
51
+ },
52
+ [workspaceId, name]
53
+ )
54
+
55
+ useEffect(() => {
56
+ load()
57
+ }, [load])
58
+
59
+ // Reload when server says this widget was updated, OR when the agent
60
+ // triggered a global data refresh (`moi refresh`). Both paths cache-bust
61
+ // the import URL so the component remounts and useEffect-driven `rpc()`
62
+ // calls re-execute against fresh data.
63
+ useMeiEvent(event => {
64
+ if (event.type === 'widget:updated' && event.name === name) {
65
+ load(true)
66
+ } else if (event.type === 'widgets:refresh') {
67
+ load(true)
68
+ }
69
+ })
70
+
71
+ return state
72
+ }
@@ -0,0 +1,30 @@
1
+ import { useCallback, useEffect, useState } from 'react'
2
+
3
+ import { useWorkspaceId } from '@/client/lib/WorkspaceContext'
4
+ import type { WidgetInfo } from '@/lib/types'
5
+
6
+ import { useMeiEvent } from './useMeiEvents'
7
+
8
+ export function useWidgetList(): WidgetInfo[] {
9
+ const workspaceId = useWorkspaceId()
10
+ const [widgets, setWidgets] = useState<WidgetInfo[]>([])
11
+
12
+ const fetchList = useCallback(() => {
13
+ fetch(`/api/workspaces/${workspaceId}/widgets`)
14
+ .then(r => r.json())
15
+ .then(data => setWidgets(data.widgets))
16
+ .catch(() => setWidgets([]))
17
+ }, [workspaceId])
18
+
19
+ useEffect(() => {
20
+ fetchList()
21
+ }, [fetchList])
22
+
23
+ useMeiEvent(event => {
24
+ if (event.type === 'widget-layout:updated') {
25
+ fetchList()
26
+ }
27
+ })
28
+
29
+ return widgets
30
+ }
@@ -0,0 +1,76 @@
1
+ import { type RefObject, useEffect } from 'react'
2
+
3
+ import { FONT_THEMES } from '@/lib/themes'
4
+ import type { WorkspaceLayout } from '@/lib/types'
5
+
6
+ const COLOR_OVERRIDES = ['background', 'foreground'] as const
7
+ const FONT_LINK_ID = 'mei-fonts'
8
+
9
+ // Applies the workspace theme (font + color overrides) to a target element —
10
+ // the workspace panel, NOT :root — so the sidebar and other pages keep the
11
+ // default tokens. CSS custom properties inherit and every Tailwind token is a
12
+ // `var(--…)` reference, so `bg-background` / `text-foreground` / `font-sans`
13
+ // inside the subtree resolve the scoped values (the element re-declares
14
+ // `font-family: var(--font-sans)` via the `font-sans` class so the font
15
+ // re-resolves locally rather than inheriting the already-resolved root font).
16
+ //
17
+ // Everything is torn down on unmount: the inline vars are removed (the element
18
+ // usually unmounts with the page anyway) and the injected Google Fonts <link>
19
+ // is dropped, so leaving the workspace leaves no global residue.
20
+ export function useWorkspaceTheme(
21
+ theme: WorkspaceLayout['theme'],
22
+ target: RefObject<HTMLElement | null>
23
+ ) {
24
+ const font = theme?.font ?? 'default'
25
+
26
+ useEffect(() => {
27
+ const el = target.current
28
+ if (!el) return
29
+ const config = FONT_THEMES[font] ?? FONT_THEMES.default
30
+
31
+ el.style.setProperty('--font-sans', config.sans)
32
+ el.style.setProperty('--font-mono', config.mono)
33
+
34
+ // Ensure the font files are available (the <link> is global; applying the
35
+ // font is what's scoped, via the vars above).
36
+ const existing = document.getElementById(FONT_LINK_ID) as HTMLLinkElement | null
37
+ if (!config.googleFontsQuery) {
38
+ existing?.remove()
39
+ } else {
40
+ const url = `https://fonts.googleapis.com/css2?family=${config.googleFontsQuery}&display=swap`
41
+ if (existing) {
42
+ existing.href = url
43
+ } else {
44
+ const link = document.createElement('link')
45
+ link.id = FONT_LINK_ID
46
+ link.rel = 'stylesheet'
47
+ link.href = url
48
+ document.head.appendChild(link)
49
+ }
50
+ }
51
+
52
+ return () => {
53
+ el.style.removeProperty('--font-sans')
54
+ el.style.removeProperty('--font-mono')
55
+ }
56
+ }, [font, target])
57
+
58
+ useEffect(() => {
59
+ const el = target.current
60
+ if (!el) return
61
+ for (const key of COLOR_OVERRIDES) {
62
+ const value = theme?.[key]
63
+ if (value) {
64
+ el.style.setProperty(`--${key}`, value)
65
+ } else {
66
+ el.style.removeProperty(`--${key}`)
67
+ }
68
+ }
69
+ return () => {
70
+ for (const key of COLOR_OVERRIDES) el.style.removeProperty(`--${key}`)
71
+ }
72
+ }, [theme?.background, theme?.foreground, target])
73
+
74
+ // Drop the shared font <link> when the workspace unmounts.
75
+ useEffect(() => () => document.getElementById(FONT_LINK_ID)?.remove(), [])
76
+ }