refactor(monorepo): decouple api and webui into workspaces packages

This commit is contained in:
yiling
2026-06-01 23:35:00 +08:00
parent e3f4fa219e
commit 1f341c15d0
288 changed files with 18024 additions and 21178 deletions
+92
View File
@@ -0,0 +1,92 @@
import { create } from 'zustand'
import type { Annotation } from '@/ui/types'
export type DrawingTool = 'select' | 'arrow' | 'line' | 'box' | 'freehand'
interface AnnotationState {
isDrawing: boolean
currentTool: DrawingTool
currentColor: string
annotations: Annotation[] // Completed annotations waiting to be sent
history: Annotation[][] // For Undo/Redo (stacks of annotation arrays)
historyIndex: number
// Actions
setIsDrawing: (isDrawing: boolean) => void
setTool: (tool: DrawingTool) => void
setColor: (color: string) => void
addAnnotation: (annotation: Annotation) => void
setAnnotations: (annotations: Annotation[]) => void // For clearing or loading
undo: () => void
redo: () => void
reset: () => void
}
export const useAnnotationStore = create<AnnotationState>((set, get) => ({
isDrawing: false,
currentTool: 'arrow',
currentColor: '#ef4444', // Default red
annotations: [],
history: [[]],
historyIndex: 0,
setIsDrawing: (isDrawing) => set({ isDrawing }),
setTool: (tool) => set({ currentTool: tool }),
setColor: (color) => set({ currentColor: color }),
addAnnotation: (annotation) => {
const { annotations, history, historyIndex } = get()
const newAnnotations = [...annotations, annotation]
// Slice history if we are in the middle of undo stack
const newHistory = history.slice(0, historyIndex + 1)
newHistory.push(newAnnotations)
set({
annotations: newAnnotations,
history: newHistory,
historyIndex: newHistory.length - 1,
})
},
setAnnotations: (annotations) => {
set({
annotations,
history: [annotations],
historyIndex: 0,
})
},
undo: () => {
const { historyIndex, history } = get()
if (historyIndex > 0) {
const newIndex = historyIndex - 1
set({
annotations: history[newIndex],
historyIndex: newIndex,
})
}
},
redo: () => {
const { historyIndex, history } = get()
if (historyIndex < history.length - 1) {
const newIndex = historyIndex + 1
set({
annotations: history[newIndex],
historyIndex: newIndex,
})
}
},
reset: () =>
set({
isDrawing: false,
currentTool: 'arrow',
annotations: [],
history: [[]],
historyIndex: 0,
}),
}))
+22
View File
@@ -0,0 +1,22 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
interface AuthState {
user: unknown | null
setUser: (user: unknown) => void
clearAuth: () => void
}
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
user: null,
setUser: (user) => set({ user }),
clearAuth: () => set({ user: null }),
}),
{
name: 'auth-storage',
storage: createJSONStorage(() => localStorage),
},
),
)
+20
View File
@@ -0,0 +1,20 @@
import type { FieldInfo as FieldInfo } from '@shumai/dtos'
import { create } from 'zustand'
interface FieldState {
fields: FieldInfo[]
loadedProjectId: string | null
setFields: (fields: FieldInfo[], projectId: string) => void
updateFields: (fields: FieldInfo[]) => void
}
export const useFieldStore = create<FieldState>((set) => ({
fields: [],
loadedProjectId: null,
setFields: (fields, projectId) =>
set({
fields,
loadedProjectId: projectId,
}),
updateFields: (fields) => set({ fields }),
}))
+47
View File
@@ -0,0 +1,47 @@
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'
import { client } from '@/ui/api/client'
import type { UserInfo } from '@shumai/dtos'
interface MemberState {
members: UserInfo[]
loadedTeamId?: string
loadedWithAgents?: boolean
loading: boolean
fetchMembers: (teamId: string, includeAgents?: boolean) => Promise<void>
}
export const useMemberStore = create<MemberState>()(
devtools(
immer((set, get) => ({
members: [],
loading: false,
fetchMembers: async (teamId, includeAgents) => {
if (get().loadedTeamId === teamId && get().loadedWithAgents === includeAgents) {
return
}
set({ loading: true })
try {
const res = await client.api.teams[':teamId'].members.$get({
param: { teamId: teamId },
query: { includeAgents: includeAgents ? 'true' : 'false' },
})
if (!res.ok) throw new Error('failed to fetch members')
const members = await res.json()
set({
members: (members as UserInfo[]) || [],
loadedTeamId: teamId,
loadedWithAgents: includeAgents,
loading: false,
})
} catch {
set({
loading: false,
})
}
},
})),
),
)
+57
View File
@@ -0,0 +1,57 @@
import { client } from '@/ui/api/client'
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
interface TeamContextState {
teamId: string | null
projectTeamMap: Record<string, string>
setTeamId: (id: string | null) => void
ensureTeamIdForProject: (projectId: string) => Promise<string | null>
}
export const useTeamContextStore = create<TeamContextState>()(
persist(
(set, get) => ({
teamId: null,
projectTeamMap: {},
setTeamId: (id) => set({ teamId: id }),
ensureTeamIdForProject: async (projectId) => {
const state = get()
// Check cache first
if (state.projectTeamMap[projectId]) {
const cachedTeamId = state.projectTeamMap[projectId]
if (state.teamId !== cachedTeamId) {
set({ teamId: cachedTeamId })
}
return cachedTeamId
}
// Fetch if not in cache
try {
const res = await client.api.projects[':projectId'].team.$get({
param: { projectId: projectId },
})
if (!res.ok) throw new Error('failed to fetch project team')
const data = await res.json()
if (data && data.teamId) {
set((prev) => ({
teamId: data.teamId!,
projectTeamMap: {
...prev.projectTeamMap,
[projectId]: data.teamId!,
},
}))
return data.teamId!
}
} catch (error) {
console.error('Failed to fetch team ID for project', projectId, error)
}
return null
},
}),
{
name: 'team-context-storage',
storage: createJSONStorage(() => localStorage),
},
),
)
+52
View File
@@ -0,0 +1,52 @@
import { create } from 'zustand'
import type { AncestorFolder } from '@shumai/dtos'
export interface TopNavProjectState {
teamId: string
projectId: string
projectName: string
ancestorFolders: AncestorFolder[]
currentAsset: {
name?: string
type: 'file' | 'folder'
version?: number
}
isRootFolder: boolean
fileId?: string
versions?: Array<{
id: string
version: number
name?: string | null
previewUrl?: string | null
creator?: { id: string; name: string | null } | null
}>
isPublic?: boolean
shareId?: string
onFolderClick?: (folderId: string) => void
}
interface TopNavStore {
projectState: TopNavProjectState | null
setProjectState: (state: TopNavProjectState | null) => void
clearProjectState: () => void
}
let timeoutId: ReturnType<typeof setTimeout> | null = null
export const useTopNavStore = create<TopNavStore>((set) => ({
projectState: null,
setProjectState: (state) => {
if (timeoutId) {
clearTimeout(timeoutId)
timeoutId = null
}
set({ projectState: state })
},
clearProjectState: () => {
if (timeoutId) clearTimeout(timeoutId)
timeoutId = setTimeout(() => {
set({ projectState: null })
timeoutId = null
}, 10) // Small debounce to prevent flicker during transitions
},
}))
+51
View File
@@ -0,0 +1,51 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
interface UiState {
fileViewLeftSidebarCollapsed: boolean
setFileViewLeftSidebarCollapsed: (collapsed: boolean) => void
fileViewRightSidebarCollapsed: boolean
setFileViewRightSidebarCollapsed: (collapsed: boolean) => void
fileListLeftSidebarCollapsed: boolean
setFileListLeftSidebarCollapsed: (collapsed: boolean) => void
fileListRightSidebarCollapsed: boolean
setFileListRightSidebarCollapsed: (collapsed: boolean) => void
viewModes: { [projectId: string]: 'card' | 'list' }
setViewMode: (projectId: string, mode: 'card' | 'list') => void
}
export const useUiStore = create<UiState>()(
persist(
(set) => ({
fileViewLeftSidebarCollapsed: true,
setFileViewLeftSidebarCollapsed: (collapsed) =>
set({ fileViewLeftSidebarCollapsed: collapsed }),
fileViewRightSidebarCollapsed: true,
setFileViewRightSidebarCollapsed: (collapsed) =>
set({ fileViewRightSidebarCollapsed: collapsed }),
fileListLeftSidebarCollapsed: false,
setFileListLeftSidebarCollapsed: (collapsed) =>
set({ fileListLeftSidebarCollapsed: collapsed }),
fileListRightSidebarCollapsed: false,
setFileListRightSidebarCollapsed: (collapsed) =>
set({ fileListRightSidebarCollapsed: collapsed }),
viewModes: {},
setViewMode: (projectId, mode) =>
set((state) => ({
viewModes: { ...state.viewModes, [projectId]: mode },
})),
}),
{
name: 'ui-storage',
storage: createJSONStorage(() => localStorage),
},
),
)
+13
View File
@@ -0,0 +1,13 @@
import { create } from 'zustand'
type UploadStore = {
uploading: number
increment: () => void
decrement: () => void
}
export const useUploadStore = create<UploadStore>((set) => ({
uploading: 0,
increment: () => set((state) => ({ uploading: state.uploading + 1 })),
decrement: () => set((state) => ({ uploading: state.uploading - 1 })),
}))
+66
View File
@@ -0,0 +1,66 @@
import { create } from 'zustand'
import { client } from '@/ui/api/client'
interface UserMetadataState {
metadata: Record<string, unknown>
isLoading: boolean
error: string | null
fetchMetadata: (teamId: string) => Promise<void>
setMetadata: (teamId: string, key: string, value: unknown) => Promise<void>
getMetadata: <T>(key: string, defaultValue?: T) => T | undefined
}
export const useUserMetadataStore = create<UserMetadataState>((set, get) => ({
metadata: {},
isLoading: false,
error: null,
fetchMetadata: async (teamId) => {
set({ isLoading: true, error: null })
try {
const res = await client.api.teams[':teamId']['user-metadata'].$get({
param: { teamId: teamId },
})
if (!res.ok) throw new Error('failed to fetch user metadata')
const data = await res.json()
const metadataMap = data.reduce((acc: Record<string, unknown>, item) => {
acc[item.key] = item.value
return acc
}, {})
set({ metadata: metadataMap, isLoading: false })
} catch (err) {
set({ error: err instanceof Error ? err.message : String(err), isLoading: false })
}
},
setMetadata: async (teamId, key, value) => {
// Optimistic update
const previousMetadata = get().metadata
set((state) => ({
metadata: { ...state.metadata, [key]: value },
}))
try {
const res = await client.api.teams[':teamId']['user-metadata'][':key'].$put({
param: { teamId: teamId, key },
json: { value },
})
if (!res.ok) throw new Error('failed to update user metadata')
} catch (err) {
// Rollback on error
set({ metadata: previousMetadata })
console.error(err)
}
},
getMetadata: (key, defaultValue) => {
const val = get().metadata[key]
// We use a cast here because the metadata store holds unknown values,
// and we want to allow the caller to specify the expected type.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (val !== undefined ? val : defaultValue) as any
},
}))