mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-01 05:14:25 +00:00
refactor(monorepo): decouple api and webui into workspaces packages
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { createAgentSession, fieldsToTypeBoxSchema, type AutofillField } from '../index'
|
||||
import { DatabaseSessionStorage } from '../database-session-storage'
|
||||
import type { Prisma, Skill } from '@shumai/db'
|
||||
import { logger } from '@/logger'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
|
||||
@@ -2,7 +2,7 @@ import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { Type } from '@sinclair/typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent, type TextContent } from '@earendil-works/pi-ai'
|
||||
import { detectSupportedMimeType } from '@/utils/mime'
|
||||
import { detectSupportedMimeType } from '@shumai/core/src/utils/mime'
|
||||
|
||||
const analyzeAssetMediaSchema = Type.Object({
|
||||
key: Type.String({
|
||||
|
||||
@@ -4,7 +4,7 @@ import { executeAgentToolWorkflow } from './utils'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { detectSupportedMimeType } from '@/utils/mime'
|
||||
import { detectSupportedMimeType } from '@shumai/core/src/utils/mime'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
function getMimeType(filePath: string): string {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { executeAgentToolWorkflow } from './utils'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { detectSupportedMimeType } from '@/utils/mime'
|
||||
import { detectSupportedMimeType } from '@shumai/core/src/utils/mime'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
function getMimeType(filePath: string): string {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { logger } from '@/logger'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
|
||||
import { type AgentTool, type AgentToolResult } from '@earendil-works/pi-agent-core'
|
||||
import { Type } from '@sinclair/typebox'
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@shumai/api",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"dependencies": {
|
||||
"@shumai/core": "workspace:*",
|
||||
"@shumai/db": "workspace:*",
|
||||
"@shumai/dtos": "workspace:*",
|
||||
"@shumai/workflow-core": "workspace:*",
|
||||
"@shumai/agent": "workspace:*",
|
||||
"@shumai/transcode": "workspace:*",
|
||||
"@shumai/worker-db": "workspace:*",
|
||||
"hono": "^4.12.14",
|
||||
"@hono/zod-validator": "^0.7.6",
|
||||
"zod": "^4.4.3",
|
||||
"better-auth": "^1.6.6",
|
||||
"pino": "^10.3.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import app from './agent'
|
||||
|
||||
vi.mock('@shumai/core/src/agent/agent')
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
|
||||
describe('Agent API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/agents', () => {
|
||||
it('returns list of agents', async () => {
|
||||
const mockAgents = [
|
||||
{
|
||||
id: 'agent1',
|
||||
user: { name: 'Bot 1', image: 'avatar1' },
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Soul',
|
||||
config: {
|
||||
provider: 'prov1',
|
||||
model: 'model1',
|
||||
thinkingLevel: 'high',
|
||||
systemPrompt: 'prompt',
|
||||
},
|
||||
skills: [],
|
||||
},
|
||||
]
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.listAgents).mockResolvedValue(mockAgents as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].name).toBe('Bot 1')
|
||||
expect(data[0].providerId).toBe('prov1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/agents', () => {
|
||||
it('creates an agent', async () => {
|
||||
const mockAgent = {
|
||||
id: 'agent2',
|
||||
user: { name: 'New Agent', image: 'avatar2' },
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'New Soul',
|
||||
config: { provider: 'prov1', model: 'model1', thinkingLevel: 'low', systemPrompt: 'p' },
|
||||
skills: [],
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.createAgent).mockResolvedValue(mockAgent as any)
|
||||
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Agent',
|
||||
type: 'chat',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
thinkingLevel: 'low',
|
||||
systemPrompt: 'p',
|
||||
soul: 'New Soul',
|
||||
skills: ['skill1'],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('New Agent')
|
||||
expect(data.soul).toBe('New Soul')
|
||||
})
|
||||
|
||||
it('validates request', async () => {
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: '',
|
||||
type: 'chat',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PUT /agents/:agentId', () => {
|
||||
it('updates an agent', async () => {
|
||||
const mockAgent = {
|
||||
id: 'agent1',
|
||||
user: { name: 'Updated Agent', image: 'avatar1' },
|
||||
type: 'autofill',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Updated Soul',
|
||||
config: { provider: 'prov1', model: 'model1' },
|
||||
skills: [],
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.updateAgent).mockResolvedValue(mockAgent as any)
|
||||
|
||||
const res = await app.request('/agents/agent1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Updated Agent',
|
||||
type: 'autofill',
|
||||
providerId: 'prov1',
|
||||
modelId: 'model1',
|
||||
soul: 'Updated Soul',
|
||||
skills: [],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('Updated Agent')
|
||||
expect(data.soul).toBe('Updated Soul')
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /agents/:agentId', () => {
|
||||
it('deletes an agent', async () => {
|
||||
const res = await app.request('/agents/agent1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(agentService.deleteAgent).toHaveBeenCalledWith({ agentId: 'agent1' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /agent-sessions/:sessionId/entries', () => {
|
||||
it('returns entries of agent session if user is admin', async () => {
|
||||
const mockEntries = [
|
||||
{
|
||||
id: 'entry1',
|
||||
sessionId: 'session1',
|
||||
entry: { step: 1, message: 'Step 1' },
|
||||
},
|
||||
]
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(agentService.getSessionEntries).mockResolvedValue(mockEntries as any)
|
||||
|
||||
const res = await app.request('/agent-sessions/session1/entries', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].id).toBe('entry1')
|
||||
expect(data[0].entry.step).toBe(1)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: undefined,
|
||||
permission: 'Admin',
|
||||
type: 'agentSession',
|
||||
id: 'session1',
|
||||
})
|
||||
})
|
||||
|
||||
it('denies access if user is not admin', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
|
||||
|
||||
const res = await app.request('/agent-sessions/session1/entries', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,169 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
createAgentRequestSchema,
|
||||
updateAgentRequestSchema,
|
||||
AgentInfo,
|
||||
AgentType,
|
||||
} from '@shumai/dtos'
|
||||
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/agents', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const agents = await agentService.listAgents({ teamId })
|
||||
|
||||
const res: AgentInfo[] = agents.map((agent) => {
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
return {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
return c.json(res, 200)
|
||||
})
|
||||
.post('/teams/:teamId/agents', zValidator('json', createAgentRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const agent = await agentService.createAgent({
|
||||
teamId,
|
||||
...req,
|
||||
})
|
||||
|
||||
if (!agent) throw new Error('failed to create agent')
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
|
||||
return c.json(info, 200)
|
||||
})
|
||||
.put('/agents/:agentId', zValidator('json', updateAgentRequestSchema), async (c) => {
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Agent,
|
||||
id: agentId,
|
||||
})
|
||||
|
||||
const agent = await agentService.updateAgent({
|
||||
agentId,
|
||||
...req,
|
||||
})
|
||||
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const info: AgentInfo = {
|
||||
id: agent.id,
|
||||
name: agent.user.name,
|
||||
type: agent.type as AgentType,
|
||||
enabled: agent.enabled,
|
||||
avatar: agent.user.image || undefined,
|
||||
providerId: agent.providerId || undefined,
|
||||
modelId: agent.modelId || undefined,
|
||||
thinkingLevel: config.thinkingLevel || '',
|
||||
systemPrompt: config.systemPrompt,
|
||||
soul: agent.soul || undefined,
|
||||
skills: agent.skills.map((s) => ({
|
||||
id: s.id,
|
||||
skillId: s.skillId,
|
||||
skill: s.skill,
|
||||
})),
|
||||
}
|
||||
|
||||
return c.json(info, 200)
|
||||
})
|
||||
.delete('/agents/:agentId', async (c) => {
|
||||
const agentId = c.req.param('agentId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Agent,
|
||||
id: agentId,
|
||||
})
|
||||
|
||||
await agentService.deleteAgent({
|
||||
agentId,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.get('/agent-sessions/:sessionId/entries', async (c) => {
|
||||
const sessionId = c.req.param('sessionId')
|
||||
const userReq = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user: userReq,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.AgentSession,
|
||||
id: sessionId,
|
||||
})
|
||||
|
||||
const entries = await agentService.getSessionEntries({ sessionId })
|
||||
const infos = entries.map((entry) => ({
|
||||
id: entry.id,
|
||||
sessionId: entry.sessionId,
|
||||
entry: entry.entry,
|
||||
}))
|
||||
|
||||
return c.json(infos, 200)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import attachmentRoute from './attachment'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { AssetType } from '@shumai/db'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// any is used here because Hono's Context and Next types are complex to mock in vitest.mock
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/core/src/asset/asset')
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
presign: vi.fn().mockResolvedValue('http://mock-s3-url'),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Attachment API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', attachmentRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/attachments', async () => {
|
||||
// We only need the id for this test
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(assetService.createAsset).mockResolvedValue({ id: 'asset1' } as any)
|
||||
|
||||
const res = await app.request('/projects/project1/attachments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
fileName: 'test.txt',
|
||||
contentType: 'text/plain',
|
||||
size: 100,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('asset1')
|
||||
expect(json.uploadUrl).toBe('http://mock-s3-url')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: 'project1',
|
||||
})
|
||||
expect(assetService.createAsset).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: 'test.txt',
|
||||
type: AssetType.attachment,
|
||||
projectId: 'project1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { postAttachmentRequestSchema } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { AssetType } from '@shumai/db'
|
||||
import { ulid } from 'ulid'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>().post(
|
||||
'/projects/:projectId/attachments',
|
||||
zValidator('json', postAttachmentRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const key = `attachments/${ulid()}/${req.fileName}`
|
||||
|
||||
const assetInfo = await assetService.createAsset({
|
||||
name: req.fileName,
|
||||
type: AssetType.attachment,
|
||||
projectId: projectId,
|
||||
key: key,
|
||||
sizeByte: req.size,
|
||||
contentType: req.contentType,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
const uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT')
|
||||
|
||||
return c.json({
|
||||
id: assetInfo.id,
|
||||
uploadUrl: uploadUrl,
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import authnRoute from './authn'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
|
||||
describe('authn api', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSignupInfo: any
|
||||
|
||||
beforeEach(() => {
|
||||
mockGetSignupInfo = vi.spyOn(teamService, 'getSignupInfo')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /signup-info', async () => {
|
||||
mockGetSignupInfo.mockResolvedValue({
|
||||
userCount: 5,
|
||||
enablePublicSignup: true,
|
||||
})
|
||||
|
||||
const app = new Hono().route('/', authnRoute)
|
||||
const res = await app.request('/signup-info')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
userCount: 5,
|
||||
enablePublicSignup: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Hono } from 'hono'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { z } from 'zod'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
const identifySchema = z.object({
|
||||
username: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
})
|
||||
|
||||
const route = app
|
||||
.get('/signup-info', async (c) => {
|
||||
const info = await teamService.getSignupInfo()
|
||||
return c.json({
|
||||
userCount: info.userCount,
|
||||
enablePublicSignup: info.enablePublicSignup,
|
||||
})
|
||||
})
|
||||
.get('/me', async (c) => {
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
return c.json({ id: session?.user?.id ?? null })
|
||||
})
|
||||
.post('/identify', zValidator('json', identifySchema), async (c) => {
|
||||
const { username, email } = c.req.valid('json')
|
||||
|
||||
const dummyEmail = `guest_${ulid()}@guest.local`
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: username,
|
||||
email: dummyEmail,
|
||||
guestEmail: email,
|
||||
type: 'human',
|
||||
},
|
||||
})
|
||||
|
||||
return c.json({ id: user.id })
|
||||
})
|
||||
.all('/auth/*', (c) => {
|
||||
return auth.handler(c.req.raw)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { collectionService } from '@shumai/core/src/collection/collection'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { Hono, Context, Next } from 'hono'
|
||||
import collectionRoute from './collection'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user-1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Project: 'project',
|
||||
Collection: 'collection',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Collection API', () => {
|
||||
const projectId = 'project-1'
|
||||
const collectionId = 'col-1'
|
||||
const authMiddleware = async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user-1', name: 'Test User' })
|
||||
await next()
|
||||
}
|
||||
const app = new Hono().use('*', authMiddleware).route('/', collectionRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/collections', async () => {
|
||||
const mockCreate = vi.spyOn(collectionService, 'createCollection').mockResolvedValue({
|
||||
id: collectionId,
|
||||
name: 'New Collection',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
projectId,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/projects/${projectId}/collections`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Collection',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockCreate).toHaveBeenCalledWith(projectId, expect.any(Object))
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/collections', async () => {
|
||||
const mockList = vi.spyOn(collectionService, 'listCollections').mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: collectionId,
|
||||
name: 'Col 1',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
projectId,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1 },
|
||||
})
|
||||
|
||||
const res = await app.request(`/projects/${projectId}/collections`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(mockList).toHaveBeenCalled()
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /collections/:collectionId', async () => {
|
||||
const mockGet = vi.spyOn(collectionService, 'getCollection').mockResolvedValue({
|
||||
id: collectionId,
|
||||
name: 'Col 1',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
projectId,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/collections/${collectionId}`)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockGet).toHaveBeenCalledWith(collectionId)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /collections/:collectionId', async () => {
|
||||
const mockUpdate = vi.spyOn(collectionService, 'updateCollection').mockResolvedValue({
|
||||
id: collectionId,
|
||||
name: 'Updated Name',
|
||||
filter: {
|
||||
sourceFolderId: 'root-1',
|
||||
searchFilter: { conditions: [], operator: 'AND', recursively: true },
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
projectId,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
|
||||
const res = await app.request(`/collections/${collectionId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Updated Name' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockUpdate).toHaveBeenCalledWith(collectionId, { name: 'Updated Name' })
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /collections/:collectionId', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mockDelete = vi.spyOn(collectionService, 'deleteCollection').mockResolvedValue({} as any)
|
||||
|
||||
const res = await app.request(`/collections/${collectionId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockDelete).toHaveBeenCalledWith(collectionId)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.any(Object),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { collectionService } from '@shumai/core/src/collection/collection'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
createCollectionRequestSchema,
|
||||
updateCollectionRequestSchema,
|
||||
listCollectionsRequestSchema,
|
||||
CollectionInfo,
|
||||
CollectionFilter,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
function toCollectionInfo(c: Prisma.CollectionGetPayload<Record<string, never>>): CollectionInfo {
|
||||
return {
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
filter: c.filter as unknown as CollectionFilter,
|
||||
projectId: c.projectId,
|
||||
createdAt: c.createdAt.toISOString(),
|
||||
updatedAt: c.updatedAt.toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post(
|
||||
'/projects/:projectId/collections',
|
||||
zValidator('json', createCollectionRequestSchema),
|
||||
async (c) => {
|
||||
const { projectId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const collection = await collectionService.createCollection(projectId, req)
|
||||
return c.json(toCollectionInfo(collection))
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/projects/:projectId/collections',
|
||||
zValidator('query', listCollectionsRequestSchema),
|
||||
async (c) => {
|
||||
const { projectId } = c.req.param()
|
||||
const req = c.req.valid('query')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const collections = await collectionService.listCollections(projectId, req)
|
||||
return c.json({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
data: collections.data.map((c: any) => toCollectionInfo(c)),
|
||||
pageInfo: collections.pageInfo,
|
||||
})
|
||||
},
|
||||
)
|
||||
.get('/collections/:collectionId', async (c) => {
|
||||
const { collectionId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
|
||||
const collection = await collectionService.getCollection(collectionId)
|
||||
if (!collection) {
|
||||
return c.json({ error: 'Collection not found' }, 404)
|
||||
}
|
||||
|
||||
return c.json(toCollectionInfo(collection))
|
||||
})
|
||||
.patch(
|
||||
'/collections/:collectionId',
|
||||
zValidator('json', updateCollectionRequestSchema),
|
||||
async (c) => {
|
||||
const { collectionId } = c.req.param()
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
|
||||
const collection = await collectionService.updateCollection(collectionId, req)
|
||||
return c.json(toCollectionInfo(collection))
|
||||
},
|
||||
)
|
||||
.delete('/collections/:collectionId', async (c) => {
|
||||
const { collectionId } = c.req.param()
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Collection,
|
||||
id: collectionId,
|
||||
})
|
||||
|
||||
await collectionService.deleteCollection(collectionId)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,405 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import { prisma } from '@shumai/db'
|
||||
import fileRoute from './file'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Asset: 'asset',
|
||||
Team: 'team',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (c: Context, next: Next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('file api', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'getAssetContext').mockResolvedValue({ teamId: 'test-team' })
|
||||
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'createComment').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listComments').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(metadataService, 'updateAssetMetadata').mockImplementation(vi.fn())
|
||||
vi.spyOn(notificationService, 'create').mockImplementation(vi.fn())
|
||||
vi.spyOn(s3Service, 'putObject').mockImplementation(vi.fn())
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /files/:fileId', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-file',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('test-file')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /files/:fileId', async () => {
|
||||
vi.mocked(assetService.updateAssetName).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'new-name',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-name' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-name')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /files', async () => {
|
||||
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /files/restore', async () => {
|
||||
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/restore', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /files/:fileId/comments', async () => {
|
||||
vi.mocked(assetService.createComment).mockResolvedValue({
|
||||
id: 'comment-id',
|
||||
assetId: 'file-id',
|
||||
message: 'hello',
|
||||
annotations: null,
|
||||
second: null,
|
||||
creator: { id: 'user-id', name: 'Test User' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
})
|
||||
|
||||
// Mock assetService.getAsset to return teamId for notification
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
project: { teamId: 'test-team' },
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id/comments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: 'hello', attachmentIds: [] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
const json = await res.json()
|
||||
expect(json.message).toBe('hello')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
type: 'comment_created',
|
||||
teamId: 'test-team',
|
||||
creatorId: 'user1',
|
||||
assetId: 'test-id',
|
||||
commentMessage: 'hello',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /files/:fileId/comments - reply_created targets parent comment creator', async () => {
|
||||
vi.mocked(assetService.createComment).mockResolvedValue({
|
||||
id: 'comment-id',
|
||||
assetId: 'file-id',
|
||||
message: 'hello reply',
|
||||
annotations: null,
|
||||
second: null,
|
||||
creator: { id: 'user-id', name: 'Test User' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
})
|
||||
|
||||
// Mock assetService.getAsset to return teamId for notification
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
project: { teamId: 'test-team' },
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const mockFindUnique = vi.spyOn(prisma.assetComment, 'findUnique').mockResolvedValue({
|
||||
id: 'parent-comment-id',
|
||||
creatorId: 'parent-comment-creator-id',
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id/comments', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
message: 'hello reply',
|
||||
replyToId: 'parent-comment-id',
|
||||
attachmentIds: [],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
const json = await res.json()
|
||||
expect(json.message).toBe('hello reply')
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
type: 'reply_created',
|
||||
teamId: 'test-team',
|
||||
creatorId: 'user1',
|
||||
assetId: 'test-id',
|
||||
userId: 'parent-comment-creator-id',
|
||||
commentMessage: 'hello reply',
|
||||
})
|
||||
|
||||
mockFindUnique.mockRestore()
|
||||
})
|
||||
|
||||
it('GET /files/:fileId/comments', async () => {
|
||||
vi.mocked(assetService.listComments).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'comment-id',
|
||||
assetId: 'file-id',
|
||||
message: 'hello',
|
||||
annotations: null,
|
||||
second: null,
|
||||
creator: { id: 'user-id', name: 'Test User' },
|
||||
replies: [],
|
||||
attachments: [],
|
||||
mentions: [],
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
sessionId: null,
|
||||
},
|
||||
],
|
||||
pageInfo: { cursor: 'cursor', total: 1 },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id/comments')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].message).toBe('hello')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/files', async () => {
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue(undefined)
|
||||
|
||||
const formData = new FormData()
|
||||
const file = new File(['test content'], 'test.jpg', { type: 'image/jpeg' })
|
||||
formData.append('file', file)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/teams/test-team/files', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.key).toMatch(/^files\//)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 'test-team',
|
||||
})
|
||||
expect(s3Service.putObject).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('PATCH /files/:fileId/metadata', async () => {
|
||||
vi.mocked(metadataService.updateAssetMetadata).mockResolvedValue(undefined)
|
||||
// Mock assetService.getAsset to return teamId for notification
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
project: { teamId: 'test-team' },
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id/metadata', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ key: 'status', value: 'approved' }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(notificationService.create).toHaveBeenCalledWith({
|
||||
type: 'metadata_field_updated_status',
|
||||
teamId: 'test-team',
|
||||
creatorId: 'user1',
|
||||
assetId: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /files/:fileId/metadata rejects readonly fields with 422', async () => {
|
||||
vi.mocked(metadataService.updateAssetMetadata).mockRejectedValue(
|
||||
new Error('Field some-key is read-only'),
|
||||
)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id/metadata', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ key: 'some-key', value: 'approved' }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(422)
|
||||
const body = await res.json()
|
||||
expect(body.error).toContain('Field some-key is read-only')
|
||||
})
|
||||
|
||||
it('PATCH /files/:fileId/order', async () => {
|
||||
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-file',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'file',
|
||||
status: 'active',
|
||||
mediaType: 'image/jpeg',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', fileRoute)
|
||||
const res = await app.request('/files/test-id/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ beforeIndex: 'index-1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
|
||||
beforeIndex: 'index-1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,238 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import {
|
||||
updateFileRequestSchema,
|
||||
updateAssetOrderRequestSchema,
|
||||
deleteFilesRequestSchema,
|
||||
restoreFilesRequestSchema,
|
||||
createCommentRequestSchema,
|
||||
uploadFileRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { updateAssetMetadataRequestSchema } from '@shumai/dtos'
|
||||
import { paginationParamsSchema } from '@shumai/dtos'
|
||||
import { ulid } from 'ulid'
|
||||
import { z } from 'zod'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/files/:fileId', async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const asset = await assetService.getAsset({ assetId: fileId })
|
||||
return c.json(asset)
|
||||
})
|
||||
.patch('/files/:fileId/order', zValidator('json', updateAssetOrderRequestSchema), async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const updated = await assetService.updateAssetOrder(fileId, req)
|
||||
return c.json(updated)
|
||||
})
|
||||
.put('/files/:fileId', zValidator('json', updateFileRequestSchema), async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const updatedAsset = await assetService.updateAssetName({
|
||||
id: fileId,
|
||||
name: req.name,
|
||||
})
|
||||
|
||||
return c.json(updatedAsset)
|
||||
})
|
||||
.delete('/files', zValidator('json', deleteFilesRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.deleteAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.patch(
|
||||
'/files/:fileId/metadata',
|
||||
zValidator('json', z.array(updateAssetMetadataRequestSchema)),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
try {
|
||||
await metadataService.updateAssetMetadata(fileId, req)
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.message.includes('is read-only')) {
|
||||
return c.json({ error: err.message }, 422)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
const hasStatus = req.some((m) => m.key === 'status')
|
||||
if (hasStatus) {
|
||||
const context = await assetService.getAssetContext(fileId)
|
||||
if (context?.teamId) {
|
||||
notificationService.create({
|
||||
type: 'metadata_field_updated_status',
|
||||
teamId: context.teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return c.json('')
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/files/:fileId/comments',
|
||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
assetId: fileId,
|
||||
userId: user.id,
|
||||
replyToId: req.replyToId,
|
||||
message: req.message,
|
||||
annotations: req.annotations,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
})
|
||||
|
||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||
|
||||
const context = await assetService.getAssetContext(fileId)
|
||||
|
||||
if (context?.teamId) {
|
||||
let targetUserId: string | undefined
|
||||
if (req.replyToId) {
|
||||
const parentComment = await prisma.assetComment.findUnique({
|
||||
where: { id: req.replyToId },
|
||||
})
|
||||
if (parentComment?.creatorId) {
|
||||
targetUserId = parentComment.creatorId
|
||||
}
|
||||
}
|
||||
|
||||
notificationService.create({
|
||||
type: notifType,
|
||||
teamId: context.teamId,
|
||||
creatorId: user.id,
|
||||
assetId: fileId,
|
||||
userId: targetUserId,
|
||||
commentMessage: req.message,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json(comment, 201)
|
||||
},
|
||||
)
|
||||
.get('/files/:fileId/comments', zValidator('query', paginationParamsSchema), async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: fileId,
|
||||
})
|
||||
|
||||
const comments = await assetService.listComments(fileId, req)
|
||||
return c.json(comments)
|
||||
})
|
||||
.post('/files/restore', zValidator('json', restoreFilesRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.restoreAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post('/teams/:teamId/files', zValidator('form', uploadFileRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const { file } = c.req.valid('form')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
return c.json('file too large, max 10MB', 400)
|
||||
}
|
||||
|
||||
const key = `files/${ulid()}`
|
||||
const buffer = Buffer.from(await file.arrayBuffer())
|
||||
|
||||
await s3Service.putObject(process.env.S3_BUCKET || 'shumai', key, buffer, file.size, file.type)
|
||||
|
||||
return c.json({ key })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,289 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import folderRoute from './folder'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { searchService } from '@shumai/core/src/search/search'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('folder api', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(authzService.hasPermission).mockClear()
|
||||
|
||||
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'createAsset').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'restoreAssets').mockImplementation(vi.fn())
|
||||
vi.spyOn(assetService, 'listChildren').mockImplementation(vi.fn())
|
||||
vi.spyOn(searchService, 'search').mockImplementation(vi.fn())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('GET /folders/:folderId', async () => {
|
||||
vi.mocked(assetService.getAsset).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-folder',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('test-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /folders/:folderId', async () => {
|
||||
vi.mocked(assetService.updateAssetName).mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'new-name',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-name' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-name')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /folders', async () => {
|
||||
vi.mocked(assetService.createAsset).mockResolvedValue({
|
||||
id: 'new-id',
|
||||
name: 'new-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new-folder', parentId: 'parent-id' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('new-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'parent-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /folders/:folderId/children', async () => {
|
||||
vi.mocked(assetService.listChildren).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'child-id',
|
||||
name: 'child-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1, cursor: '' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/children?assetType=folder')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].name).toBe('child-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /folders', async () => {
|
||||
vi.mocked(assetService.deleteAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /folders/restore', async () => {
|
||||
vi.mocked(assetService.restoreAssets).mockResolvedValue(undefined)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/restore', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: ['test-id'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
expect(assetService.restoreAssets).toHaveBeenCalledWith(['test-id'])
|
||||
})
|
||||
|
||||
it('POST /folders/:folderId/search', async () => {
|
||||
vi.mocked(searchService.search).mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
id: 'result-id',
|
||||
name: 'result-folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: { total: 1, cursor: '' },
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
conditions: [{ field: 'name', operator: 'eq', value: 'result-folder' }],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.data[0].name).toBe('result-folder')
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /folders/:folderId/order', async () => {
|
||||
vi.spyOn(assetService, 'updateAssetOrder').mockResolvedValue({
|
||||
id: 'test-id',
|
||||
name: 'test-folder',
|
||||
sizeByte: 10,
|
||||
fileCount: 1,
|
||||
type: 'folder',
|
||||
status: 'active',
|
||||
mediaType: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', folderRoute)
|
||||
const res = await app.request('/folders/test-id/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ beforeIndex: 'index-1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user1', name: 'Test User' },
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'test-id',
|
||||
})
|
||||
|
||||
expect(assetService.updateAssetOrder).toHaveBeenCalledWith('test-id', {
|
||||
beforeIndex: 'index-1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,160 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { searchService } from '@shumai/core/src/search/search'
|
||||
import {
|
||||
createFolderRequestSchema,
|
||||
updateFolderRequestSchema,
|
||||
deleteFoldersRequestSchema,
|
||||
restoreFoldersRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { listChildrenRequestSchema, updateAssetOrderRequestSchema } from '@shumai/dtos'
|
||||
import { searchRequestSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/folders', zValidator('json', createFolderRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.parentId,
|
||||
})
|
||||
|
||||
const newAsset = await assetService.createAsset({
|
||||
name: req.name,
|
||||
parentId: req.parentId,
|
||||
type: 'folder',
|
||||
})
|
||||
|
||||
return c.json(newAsset)
|
||||
})
|
||||
.patch(
|
||||
'/folders/:folderId/order',
|
||||
zValidator('json', updateAssetOrderRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const updated = await assetService.updateAssetOrder(folderId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.put('/folders/:folderId', zValidator('json', updateFolderRequestSchema), async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const updatedAsset = await assetService.updateAssetName({
|
||||
id: folderId,
|
||||
name: req.name,
|
||||
})
|
||||
|
||||
return c.json(updatedAsset)
|
||||
})
|
||||
.get('/folders/:folderId', async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const assetInfo = await assetService.getAsset({ assetId: folderId })
|
||||
return c.json(assetInfo)
|
||||
})
|
||||
.get('/folders/:folderId/children', zValidator('query', listChildrenRequestSchema), async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const resp = await assetService.listChildren({
|
||||
assetId: folderId,
|
||||
assetType: req.assetType,
|
||||
projectId: req.projectId,
|
||||
showDeleted: req.showDeleted,
|
||||
sort: req.sort,
|
||||
order: req.order,
|
||||
})
|
||||
return c.json(resp)
|
||||
})
|
||||
.delete('/folders', zValidator('json', deleteFoldersRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.deleteAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post('/folders/restore', zValidator('json', restoreFoldersRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
for (const id of req.ids) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.restoreAssets(req.ids)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post('/folders/:folderId/search', zValidator('json', searchRequestSchema), async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: folderId,
|
||||
})
|
||||
|
||||
const result = await searchService.search(folderId, req)
|
||||
return c.json(result)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,186 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import inviteRoute from './invite'
|
||||
import publicInviteRoute from './public-invite'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { inviteService } from '@shumai/core/src/invite/invite'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
|
||||
vi.mock('@shumai/core/src/invite/invite')
|
||||
vi.mock('@shumai/core/src/notification/notification')
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (
|
||||
c: Context<{ Variables: { user: { id: string; name: string } } }>,
|
||||
next: Next,
|
||||
) => {
|
||||
c.set('user', { id: 'u1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
const getApp = () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
.route('/', publicInviteRoute)
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'u1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', inviteRoute)
|
||||
return app
|
||||
}
|
||||
|
||||
describe('Invite API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /invite/:code', async () => {
|
||||
const app = getApp()
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.getInvite).mockResolvedValue({
|
||||
code: 'code123',
|
||||
teamId: 't1',
|
||||
team: { name: 'My Team' },
|
||||
inviter: { name: 'Inviter' },
|
||||
role: 'editor',
|
||||
used: false,
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/invite/code123')
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'code123',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
teamName: 'My Team',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/invite', async () => {
|
||||
const app = getApp()
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.createTeamInvite).mockResolvedValue({
|
||||
code: 'test-code',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/teams/t1/invite', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ role: 'editor' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'test-code',
|
||||
role: 'editor',
|
||||
teamId: 't1',
|
||||
teamName: 'Team A',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
expect(inviteService.createTeamInvite).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
role: 'editor',
|
||||
inviterId: 'u1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/invite', async () => {
|
||||
const app = getApp()
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.createProjectInvite).mockResolvedValue({
|
||||
code: 'proj-code',
|
||||
role: 'reviewer',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
project: { id: 'p1', name: 'Project A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/projects/p1/invite', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ role: 'reviewer' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
code: 'proj-code',
|
||||
role: 'reviewer',
|
||||
teamId: 't1',
|
||||
teamName: 'Team A',
|
||||
projectId: 'p1',
|
||||
projectName: 'Project A',
|
||||
inviterName: 'Inviter',
|
||||
isUsed: false,
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
expect(inviteService.createProjectInvite).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
role: 'reviewer',
|
||||
inviterId: 'u1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /join (Team)', async () => {
|
||||
const app = getApp()
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(notificationService.create).mockResolvedValue(undefined as any)
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(inviteService.getInvite).mockResolvedValue({
|
||||
code: 'code123',
|
||||
teamId: 't1',
|
||||
team: { name: 'Team A' },
|
||||
inviter: { name: 'Inviter' },
|
||||
used: false,
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(inviteService.consumeInvite).mockResolvedValue(undefined as any)
|
||||
|
||||
const res = await app.request('/join', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer fake',
|
||||
},
|
||||
body: JSON.stringify({ code: 'code123' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(inviteService.consumeInvite).toHaveBeenCalledWith('code123', 'u1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,113 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import {
|
||||
createProjectInviteRequestSchema,
|
||||
createTeamInviteRequestSchema,
|
||||
joinRequestSchema,
|
||||
InviteInfo,
|
||||
} from '@shumai/dtos'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { inviteService } from '@shumai/core/src/invite/invite'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mapToInviteInfo = (inv: any): InviteInfo => {
|
||||
const info: InviteInfo = {
|
||||
code: inv.code,
|
||||
role: inv.role!,
|
||||
teamId: inv.teamId,
|
||||
teamName: inv.team.name,
|
||||
inviterName: inv.inviter.name,
|
||||
isUsed: inv.used,
|
||||
}
|
||||
|
||||
if (inv.project) {
|
||||
info.projectId = inv.project.id
|
||||
info.projectName = inv.project.name
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/invite', zValidator('json', createTeamInviteRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const inv = await inviteService.createTeamInvite({
|
||||
teamId,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
role: req.role as any,
|
||||
inviterId: user.id,
|
||||
})
|
||||
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
})
|
||||
.post(
|
||||
'/projects/:projectId/invite',
|
||||
zValidator('json', createProjectInviteRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const inv = await inviteService.createProjectInvite({
|
||||
projectId,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
role: req.role as any,
|
||||
inviterId: user.id,
|
||||
})
|
||||
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
},
|
||||
)
|
||||
.post('/join', zValidator('json', joinRequestSchema), async (c) => {
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
try {
|
||||
const info = await inviteService.getInvite(req.code)
|
||||
|
||||
await inviteService.consumeInvite(req.code, user.id)
|
||||
|
||||
if (info.projectId) {
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_project,
|
||||
teamId: info.teamId,
|
||||
projectId: info.projectId,
|
||||
userId: user.id,
|
||||
})
|
||||
} else {
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId: info.teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
}
|
||||
|
||||
return new Response(null, { status: 200 })
|
||||
} catch {
|
||||
return c.json({ error: 'Bad Request' }, 400)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,208 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import metadataRoute from './metadata'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (
|
||||
c: Context<{ Variables: { user: { id: string; name: string } } }>,
|
||||
next: Next,
|
||||
) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/core/src/metadata/metadata')
|
||||
|
||||
describe('metadata api', () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', metadataRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/fields', async () => {
|
||||
const mockField = {
|
||||
key: 'field1',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'Test Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
}
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(metadataService.listTeamFields).mockResolvedValue([mockField as any]) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/teams/t1/fields')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toHaveLength(1)
|
||||
expect(json[0].id).toBe('field1')
|
||||
expect(json[0].config.name).toBe('Test Field')
|
||||
expect(json[0].aiAutofill).toBe(true)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/fields', async () => {
|
||||
const mockField = {
|
||||
key: 'newfield',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'New Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
}
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(metadataService.createTeamField).mockResolvedValue(mockField as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/teams/t1/fields', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
config: { name: 'New Field', type: 'text' },
|
||||
aiAutofill: true,
|
||||
description: 'desc',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('newfield')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/fields', async () => {
|
||||
const mockField = {
|
||||
key: 'field1',
|
||||
scope: 'PROJECT',
|
||||
config: { name: 'Project Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: false,
|
||||
}
|
||||
|
||||
vi.mocked(metadataService.listProjectFields).mockResolvedValue([
|
||||
{ field: mockField, visible: true } as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
])
|
||||
|
||||
const res = await app.request('/projects/p1/fields')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json).toHaveLength(1)
|
||||
expect(json[0].id).toBe('field1')
|
||||
expect(json[0].visible).toBe(true)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /projects/:projectId/fields/order', async () => {
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(metadataService.updateProjectFieldsOrder).mockResolvedValue(undefined as any)
|
||||
|
||||
const res = await app.request('/projects/p1/fields/order', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify([{ fieldId: 'field1', visible: true }]),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.updateProjectFieldsOrder).toHaveBeenCalledWith('user1', 'p1', [
|
||||
{ fieldId: 'field1', visible: true },
|
||||
])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /fields/:fieldId', async () => {
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(metadataService.getFieldByKey).mockResolvedValue({
|
||||
key: 'f1',
|
||||
teamId: 't1',
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(metadataService.deleteTeamField).mockResolvedValue(undefined as any)
|
||||
|
||||
const res = await app.request('/fields/f1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(metadataService.deleteTeamField).toHaveBeenCalledWith('t1', 'f1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: 'f1',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /fields/:fieldId', async () => {
|
||||
const mockField = {
|
||||
key: 'f1',
|
||||
scope: 'TEAM',
|
||||
config: { name: 'Updated Field', type: 'text' },
|
||||
readOnly: false,
|
||||
description: 'desc',
|
||||
aiAutofill: true,
|
||||
teamId: 't1',
|
||||
}
|
||||
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(metadataService.getFieldByKey).mockResolvedValue(mockField as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
vi.mocked(metadataService.updateTeamField).mockResolvedValue(mockField as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/fields/f1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
config: { name: 'Updated Field', type: 'text' },
|
||||
aiAutofill: true,
|
||||
description: 'desc',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('f1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: 'f1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,163 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
createFieldRequestSchema,
|
||||
updateFieldRequestSchema,
|
||||
updateProjectFieldsOrderRequestSchema,
|
||||
FieldInfo,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
function toFieldInfo(
|
||||
f: Prisma.MetadataFieldGetPayload<Record<string, never>>,
|
||||
visible = false,
|
||||
): FieldInfo {
|
||||
return {
|
||||
id: f.key,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: f.config as any,
|
||||
scope: f.scope ?? '',
|
||||
readOnly: f.readOnly,
|
||||
visible: visible,
|
||||
description: f.description,
|
||||
aiAutofill: f.aiAutofill,
|
||||
}
|
||||
}
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const field = await metadataService.createTeamField(teamId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
})
|
||||
.get('/teams/:teamId/fields', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const fields = await metadataService.listTeamFields(teamId)
|
||||
return c.json(fields.map((f) => toFieldInfo(f)))
|
||||
})
|
||||
.put('/fields/:fieldId', zValidator('json', updateFieldRequestSchema), async (c) => {
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: fieldId,
|
||||
})
|
||||
|
||||
// We need teamId/projectId for metadataService. But we can get them from the field itself.
|
||||
// Or we can refactor metadataService to not require them if we already have the field.
|
||||
// For now, let's just fetch it once to get the context for the service call.
|
||||
const field = await metadataService.getFieldByKey(fieldId)
|
||||
if (!field) throw new Error('Field not found')
|
||||
|
||||
let updated
|
||||
if (field.projectId) {
|
||||
updated = await metadataService.updateProjectField(field.projectId, fieldId, req)
|
||||
} else if (field.teamId) {
|
||||
updated = await metadataService.updateTeamField(field.teamId, fieldId, req)
|
||||
} else {
|
||||
throw new Error('Field has no context')
|
||||
}
|
||||
|
||||
return c.json(toFieldInfo(updated))
|
||||
})
|
||||
.delete('/fields/:fieldId', async (c) => {
|
||||
const fieldId = c.req.param('fieldId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.MetadataField,
|
||||
id: fieldId,
|
||||
})
|
||||
|
||||
const field = await metadataService.getFieldByKey(fieldId)
|
||||
if (!field) throw new Error('Field not found')
|
||||
|
||||
if (field.projectId) {
|
||||
await metadataService.deleteProjectField(field.projectId, fieldId)
|
||||
} else if (field.teamId) {
|
||||
await metadataService.deleteTeamField(field.teamId, fieldId)
|
||||
} else {
|
||||
throw new Error('Field has no context')
|
||||
}
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.post('/projects/:projectId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const field = await metadataService.createProjectField(projectId, req)
|
||||
return c.json(toFieldInfo(field))
|
||||
})
|
||||
.get('/projects/:projectId/fields', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const fields = await metadataService.listProjectFields(user.id, projectId)
|
||||
return c.json(fields.map((f) => toFieldInfo(f.field, f.visible)))
|
||||
})
|
||||
.patch(
|
||||
'/projects/:projectId/fields/order',
|
||||
zValidator('json', updateProjectFieldsOrderRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
await metadataService.updateProjectFieldsOrder(user.id, projectId, req)
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { createMiddleware } from 'hono/factory'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
export const authMiddleware = createMiddleware<{
|
||||
Variables: {
|
||||
user: User
|
||||
}
|
||||
}>(async (c, next) => {
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
|
||||
if (!session) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
return c.json({ error: 'User not found' }, 401)
|
||||
}
|
||||
|
||||
c.set('user', user)
|
||||
await next()
|
||||
} catch {
|
||||
return c.json({ error: 'Authentication failed' }, 401)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import notificationRoute from './notification'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (
|
||||
c: Context<{ Variables: { user: { id: string; name: string } } }>,
|
||||
next: Next,
|
||||
) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/core/src/notification/notification')
|
||||
vi.mock('@shumai/core/src/user-metadata/user-metadata')
|
||||
|
||||
describe('notification api', () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', notificationRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/notifications', async () => {
|
||||
vi.mocked(notificationService.list).mockResolvedValue({
|
||||
data: [{ id: 'n1', type: 'comment_created' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
pageInfo: { total: 1, cursor: 'abc' },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/notifications?unreadOnly=true&pageSize=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.pageInfo.total).toBe(1)
|
||||
expect(json.pageInfo.cursor).toBe('abc')
|
||||
|
||||
expect(notificationService.list).toHaveBeenCalledWith('t1', 'user1', {
|
||||
unreadOnly: true,
|
||||
after: undefined,
|
||||
pageSize: 10,
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/notifications/read', async () => {
|
||||
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(notificationService.markRead).mockResolvedValue(undefined as any)
|
||||
|
||||
const res = await app.request('/teams/t1/notifications/read', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ notificationId: 'n1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(notificationService.markRead).toHaveBeenCalledWith('t1', 'user1', 'n1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/notifications/settings - returns default settings', async () => {
|
||||
vi.mocked(userMetadataService.getMetadata).mockResolvedValue(null)
|
||||
|
||||
const res = await app.request('/teams/t1/notifications/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.comments).toBe(true)
|
||||
expect(json.yourUploads).toBe(false)
|
||||
|
||||
expect(userMetadataService.getMetadata).toHaveBeenCalledWith(
|
||||
'user1',
|
||||
't1',
|
||||
'notification_settings',
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/notifications/settings - returns saved settings', async () => {
|
||||
vi.mocked(userMetadataService.getMetadata).mockResolvedValue({
|
||||
key: 'notification_settings',
|
||||
value: {
|
||||
comments: false,
|
||||
replies: false,
|
||||
mentions: true,
|
||||
yourUploads: true,
|
||||
otherUploads: false,
|
||||
statusUpdates: true,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/notifications/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.comments).toBe(false)
|
||||
expect(json.yourUploads).toBe(true)
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/notifications/settings - saves settings', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.mocked(userMetadataService.upsertMetadata).mockResolvedValue(undefined as any)
|
||||
|
||||
const res = await app.request('/teams/t1/notifications/settings', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
comments: false,
|
||||
replies: false,
|
||||
mentions: true,
|
||||
yourUploads: true,
|
||||
otherUploads: false,
|
||||
statusUpdates: true,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.success).toBe(true)
|
||||
|
||||
expect(userMetadataService.upsertMetadata).toHaveBeenCalledWith(
|
||||
'user1',
|
||||
't1',
|
||||
'notification_settings',
|
||||
{
|
||||
comments: false,
|
||||
replies: false,
|
||||
mentions: true,
|
||||
yourUploads: true,
|
||||
otherUploads: false,
|
||||
statusUpdates: true,
|
||||
},
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,113 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import {
|
||||
listNotificationsRequestSchema,
|
||||
markNotificationReadRequestSchema,
|
||||
notificationSettingsSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get(
|
||||
'/teams/:teamId/notifications',
|
||||
zValidator('query', listNotificationsRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('query')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const res = await notificationService.list(teamId, user.id, {
|
||||
unreadOnly: req.unreadOnly,
|
||||
after: req.after,
|
||||
pageSize: req.pageSize,
|
||||
})
|
||||
|
||||
// To align with Go struct casing, map pageInfo to page_info
|
||||
return c.json({
|
||||
data: res.data,
|
||||
pageInfo: {
|
||||
total: res.pageInfo.total,
|
||||
cursor: res.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/notifications/read',
|
||||
zValidator('json', markNotificationReadRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
await notificationService.markRead(teamId, user.id, req.notificationId)
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/notifications/settings', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.getMetadata(user.id, teamId, 'notification_settings')
|
||||
const settings = metadata
|
||||
? metadata.value
|
||||
: {
|
||||
comments: true,
|
||||
replies: true,
|
||||
mentions: true,
|
||||
yourUploads: false,
|
||||
otherUploads: true,
|
||||
statusUpdates: true,
|
||||
}
|
||||
|
||||
return c.json(settings)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/notifications/settings',
|
||||
zValidator('json', notificationSettingsSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
await userMetadataService.upsertMetadata(user.id, teamId, 'notification_settings', req)
|
||||
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,180 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import projectRoute from './project'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (
|
||||
c: Context<{ Variables: { user: { id: string; name: string } } }>,
|
||||
next: Next,
|
||||
) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/core/src/project/project')
|
||||
vi.mock('@shumai/core/src/asset/asset')
|
||||
|
||||
describe('project api', () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', projectRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/projects', async () => {
|
||||
vi.mocked(projectService.listProjects).mockResolvedValue({
|
||||
data: [{ id: 'foo', name: 'foo.png', rootFolder: 'uid' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
pageInfo: { total: 100, cursor: 'abc' },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t/projects?page_size=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.data).toHaveLength(1)
|
||||
expect(json.pageInfo.total).toBe(100)
|
||||
expect(json.data[0].id).toBe('foo')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: 't',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/projects', async () => {
|
||||
vi.mocked(projectService.createProject).mockResolvedValue({
|
||||
id: 'foo',
|
||||
name: 'foo.png',
|
||||
coverImage: 'http://s3/bucket/key',
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/teams/t/projects', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'foo.png', coverImageKey: 'key' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.id).toBe('foo')
|
||||
expect(json.name).toBe('foo.png')
|
||||
expect(json.coverImage).toBe('http://s3/bucket/key')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Team,
|
||||
id: 't',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /projects/:projectId', async () => {
|
||||
vi.mocked(projectService.updateProject).mockResolvedValue({
|
||||
id: 'foo',
|
||||
name: 'updated',
|
||||
coverImage: 'http://s3/bucket/key',
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/projects/foo', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'updated' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.name).toBe('updated')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: 'foo',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId', async () => {
|
||||
vi.mocked(projectService.getProject).mockResolvedValue({
|
||||
id: 'p',
|
||||
name: 'foo.png',
|
||||
rootFolder: 'root_folder_id',
|
||||
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
const res = await app.request('/projects/p')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.rootFolder).toBe('root_folder_id')
|
||||
expect(json.id).toBe('p')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: 'p',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /projects/:projectId/team', async () => {
|
||||
vi.mocked(projectService.getProjectTeam).mockResolvedValue('teamId')
|
||||
|
||||
const res = await app.request('/projects/p/team')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const json = await res.json()
|
||||
expect(json.teamId).toBe('teamId')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: 'p',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /projects/:projectId/reparent', async () => {
|
||||
vi.mocked(assetService.reparentAssets).mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/projects/p/reparent', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
newParentId: 'new_parent_id',
|
||||
assetIds: ['asset_1', 'asset_2'],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'new_parent_id',
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'asset_1',
|
||||
})
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: 'asset_2',
|
||||
})
|
||||
expect(assetService.reparentAssets).toHaveBeenCalledWith({
|
||||
newParentId: 'new_parent_id',
|
||||
assetIds: ['asset_1', 'asset_2'],
|
||||
creatorId: 'user1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,248 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { reparentAssetsRequestSchema, copyAssetsRequestSchema } from '@shumai/dtos'
|
||||
import {
|
||||
createProjectRequestSchema,
|
||||
updateProjectRequestSchema,
|
||||
listProjectsRequestSchema,
|
||||
recentlyDeletedRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { listMembersQuerySchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams/:teamId/projects', zValidator('json', createProjectRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const newProject = await projectService.createProject(user, {
|
||||
teamId,
|
||||
...req,
|
||||
})
|
||||
|
||||
return c.json(newProject)
|
||||
})
|
||||
.put('/projects/:projectId', zValidator('json', updateProjectRequestSchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const updatedProject = await projectService.updateProject({
|
||||
projectId,
|
||||
...req,
|
||||
})
|
||||
|
||||
return c.json(updatedProject)
|
||||
})
|
||||
.get(
|
||||
'/projects/:projectId/recently-deleted',
|
||||
zValidator('query', recentlyDeletedRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const resp = await assetService.listChildren({
|
||||
projectId,
|
||||
assetType: req.assetType,
|
||||
showDeleted: true,
|
||||
after: req.after,
|
||||
first: req.first,
|
||||
})
|
||||
return c.json(resp)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/projects', zValidator('query', listProjectsRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const res = await projectService.listProjects({
|
||||
teamId,
|
||||
userId: user.id,
|
||||
sortBy: req.sortBy,
|
||||
sortDirection: req.sortDirection,
|
||||
pagination: req,
|
||||
})
|
||||
|
||||
return c.json({
|
||||
data: res.data,
|
||||
pageInfo: {
|
||||
total: res.pageInfo.total,
|
||||
cursor: res.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
})
|
||||
.get('/projects/:projectId', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const p = await projectService.getProject(projectId)
|
||||
return c.json(p)
|
||||
})
|
||||
.delete('/projects/:projectId', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
await projectService.deleteProject(projectId)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/projects/:projectId/team', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const teamId = await projectService.getProjectTeam(projectId)
|
||||
return c.json({ teamId })
|
||||
})
|
||||
.get('/projects/:projectId/members', zValidator('query', listMembersQuerySchema), async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const { includeAgents } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const members = await projectService.listProjectMembers({
|
||||
projectId,
|
||||
includeAgents: includeAgents,
|
||||
})
|
||||
return c.json(members)
|
||||
})
|
||||
.get('/projects/:projectId/bots', async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
// STUB: AgentService is not migrated yet.
|
||||
return c.json([])
|
||||
})
|
||||
|
||||
.post(
|
||||
'/projects/:projectId/reparent',
|
||||
zValidator('json', reparentAssetsRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
// Check Edit permission on target folder/project
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.newParentId,
|
||||
})
|
||||
|
||||
// Check Edit permission on all source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.reparentAssets({
|
||||
...req,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
return c.body(null, 204)
|
||||
},
|
||||
)
|
||||
.post('/projects/:projectId/copy', zValidator('json', copyAssetsRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
// Check Edit permission on target folder/project
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.newParentId,
|
||||
})
|
||||
|
||||
// Check Read permission on all source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.copyAssets({
|
||||
...req,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
return c.body(null, 204)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,192 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono, type Context, type Next } from 'hono'
|
||||
import providerRoute from './provider'
|
||||
import { providerService } from '@shumai/core/src/provider/provider'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
authMiddleware: async (
|
||||
c: Context<{ Variables: { user: { id: string; name: string } } }>,
|
||||
next: Next,
|
||||
) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz')
|
||||
vi.mock('@shumai/core/src/provider/provider')
|
||||
|
||||
describe('provider api', () => {
|
||||
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
|
||||
.use('*', async (c, next) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
})
|
||||
.route('/', providerRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/providers returns providers', async () => {
|
||||
vi.mocked(providerService.listByTeam).mockResolvedValue([
|
||||
{ id: 'p1', name: 'openai', config: { api: 'openai' } },
|
||||
] as unknown as Awaited<ReturnType<typeof providerService.listByTeam>>)
|
||||
|
||||
const res = await app.request('/teams/t1/providers')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].id).toBe('p1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /providers/:id/models returns models', async () => {
|
||||
vi.mocked(providerService.getById).mockResolvedValue({
|
||||
id: 'p1',
|
||||
teamId: 't1',
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.getById>>)
|
||||
vi.mocked(providerService.listModelsByProvider).mockResolvedValue([
|
||||
{ modelId: 'm1', name: 'model1' },
|
||||
] as unknown as Awaited<ReturnType<typeof providerService.listModelsByProvider>>)
|
||||
|
||||
const res = await app.request('/providers/p1/models')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].modelId).toBe('m1')
|
||||
expect(providerService.listModelsByProvider).toHaveBeenCalledWith('t1', 'p1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/providers creates provider', async () => {
|
||||
const config = {
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
api: 'openai-completions',
|
||||
}
|
||||
const models = [
|
||||
{
|
||||
modelId: 'gpt-4',
|
||||
name: 'GPT-4',
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
reasoning: false,
|
||||
input: ['text' as const],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
]
|
||||
vi.mocked(providerService.create).mockResolvedValue({
|
||||
id: 'p1',
|
||||
name: 'openai',
|
||||
config,
|
||||
models,
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.create>>)
|
||||
|
||||
const res = await app.request('/teams/t1/providers', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'openai', config, models }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('openai')
|
||||
expect(providerService.create).toHaveBeenCalledWith('t1', 'openai', config, models)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
})
|
||||
})
|
||||
|
||||
it('PUT /providers/:id updates provider', async () => {
|
||||
const config = {
|
||||
baseUrl: 'https://new-url.com',
|
||||
api: 'openai-completions',
|
||||
}
|
||||
const models = [
|
||||
{
|
||||
modelId: 'gpt-4',
|
||||
name: 'GPT-4',
|
||||
config: {
|
||||
api: 'openai-completions',
|
||||
reasoning: false,
|
||||
input: ['text' as const],
|
||||
contextWindow: 128000,
|
||||
maxTokens: 4096,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
},
|
||||
},
|
||||
]
|
||||
vi.mocked(providerService.getById).mockResolvedValue({
|
||||
id: 'p1',
|
||||
teamId: 't1',
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.getById>>)
|
||||
vi.mocked(providerService.update).mockResolvedValue({
|
||||
id: 'p1',
|
||||
name: 'openai',
|
||||
config,
|
||||
models,
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.update>>)
|
||||
|
||||
const res = await app.request('/providers/p1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ config, models }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.config.baseUrl).toBe('https://new-url.com')
|
||||
expect(providerService.update).toHaveBeenCalledWith('t1', 'p1', config, models)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETE /providers/:id deletes provider', async () => {
|
||||
vi.mocked(providerService.getById).mockResolvedValue({
|
||||
id: 'p1',
|
||||
teamId: 't1',
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.getById>>)
|
||||
vi.mocked(providerService.delete).mockResolvedValue({
|
||||
id: 'p1',
|
||||
} as unknown as Awaited<ReturnType<typeof providerService.delete>>)
|
||||
|
||||
const res = await app.request('/providers/p1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.success).toBe(true)
|
||||
expect(providerService.delete).toHaveBeenCalledWith('t1', 'p1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: expect.anything(),
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id: 'p1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { Hono } from 'hono'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { providerService } from '@shumai/core/src/provider/provider'
|
||||
import { createProviderRequestSchema, updateProviderRequestSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/providers', async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const providers = await providerService.listByTeam(teamId)
|
||||
return c.json(providers)
|
||||
})
|
||||
|
||||
.get('/providers/:id/models', async (c) => {
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id,
|
||||
})
|
||||
|
||||
const provider = await providerService.getById(id)
|
||||
if (!provider) throw new Error('Provider not found')
|
||||
|
||||
const models = await providerService.listModelsByProvider(provider.teamId, id)
|
||||
return c.json(models)
|
||||
})
|
||||
|
||||
.post('/teams/:teamId/providers', zValidator('json', createProviderRequestSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const { name, config, models } = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const provider = await providerService.create(teamId, name, config, models)
|
||||
return c.json(provider)
|
||||
})
|
||||
|
||||
.put('/providers/:id', zValidator('json', updateProviderRequestSchema), async (c) => {
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
const { config, models } = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id,
|
||||
})
|
||||
|
||||
const providerBefore = await providerService.getById(id)
|
||||
if (!providerBefore) throw new Error('Provider not found')
|
||||
|
||||
const provider = await providerService.update(providerBefore.teamId, id, config, models)
|
||||
return c.json(provider)
|
||||
})
|
||||
|
||||
.delete('/providers/:id', async (c) => {
|
||||
const id = c.req.param('id')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Provider,
|
||||
id,
|
||||
})
|
||||
|
||||
const providerBefore = await providerService.getById(id)
|
||||
if (!providerBefore) throw new Error('Provider not found')
|
||||
|
||||
await providerService.delete(providerBefore.teamId, id)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Hono } from 'hono'
|
||||
import { inviteService } from '@shumai/core/src/invite/invite'
|
||||
import { InviteInfo } from '@shumai/dtos'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const mapToInviteInfo = (inv: any): InviteInfo => {
|
||||
const info: InviteInfo = {
|
||||
code: inv.code,
|
||||
role: inv.role!,
|
||||
teamId: inv.teamId,
|
||||
teamName: inv.team.name,
|
||||
inviterName: inv.inviter.name,
|
||||
isUsed: inv.used,
|
||||
}
|
||||
|
||||
if (inv.project) {
|
||||
info.projectId = inv.project.id
|
||||
info.projectName = inv.project.name
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
const route = app.get('/invite/:code', async (c) => {
|
||||
const code = c.req.param('code')
|
||||
try {
|
||||
const inv = await inviteService.getInvite(code)
|
||||
return c.json(mapToInviteInfo(inv))
|
||||
} catch {
|
||||
return c.json({ error: 'Not found' }, 404)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,250 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { paginationParamsSchema } from '@shumai/dtos'
|
||||
import { z } from 'zod'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { FieldInfo } from '@shumai/dtos'
|
||||
import type { Prisma as PrismaType } from '@shumai/db'
|
||||
import { auth } from '@shumai/core/src/auth/auth'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { createCommentRequestSchema } from '@shumai/dtos'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
function toFieldInfo(
|
||||
f: PrismaType.MetadataFieldGetPayload<Record<string, never>>,
|
||||
visible = false,
|
||||
): FieldInfo {
|
||||
return {
|
||||
id: f.key,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: f.config as any,
|
||||
scope: f.scope ?? '',
|
||||
readOnly: f.readOnly,
|
||||
visible: visible,
|
||||
description: f.description,
|
||||
aiAutofill: f.aiAutofill,
|
||||
}
|
||||
}
|
||||
|
||||
const sharedChildrenRequestSchema = paginationParamsSchema.extend({
|
||||
assetType: z.string().optional(),
|
||||
})
|
||||
|
||||
const route = app
|
||||
.get('/shares/:shareId/info', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
return c.json({
|
||||
id: shareLink.id,
|
||||
name: shareLink.name,
|
||||
expireAt: shareLink.expireAt,
|
||||
isDisabled: shareLink.isDisabled,
|
||||
isExpired: shareLink.isExpired,
|
||||
hasPassword: shareLink.hasPassword,
|
||||
rootFolderId: shareLink.rootFolderId,
|
||||
projectId: shareLink.projectId,
|
||||
})
|
||||
} catch (err) {
|
||||
return c.json({ error: (err as Error).message }, 404)
|
||||
}
|
||||
})
|
||||
.get('/shares/:shareId/fields', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const password = c.req.header('x-share-password')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(shareLink.rootFolderId, password)
|
||||
|
||||
const fields = await metadataService.listProjectFields(null, shareLink.projectId)
|
||||
const fieldVisibility = (shareLink.fieldVisibility || {}) as Record<string, boolean>
|
||||
|
||||
return c.json(
|
||||
fields
|
||||
.filter((f) => fieldVisibility[f.field.key])
|
||||
.map((f) => toFieldInfo(f.field, f.visible)),
|
||||
)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
})
|
||||
.get(
|
||||
'/shares/:shareId/folders/:folderId/children',
|
||||
zValidator('query', sharedChildrenRequestSchema),
|
||||
async (c) => {
|
||||
const folderId = c.req.param('folderId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.verifyPublicAccess(folderId, password)
|
||||
|
||||
let sort: string | undefined
|
||||
let order: string | undefined
|
||||
|
||||
if (shareLink.defaultSortOrder) {
|
||||
const parts = shareLink.defaultSortOrder.split(':')
|
||||
sort = parts[0]
|
||||
order = parts[1]
|
||||
}
|
||||
|
||||
const res = await assetService.listChildren({
|
||||
...req,
|
||||
assetId: folderId,
|
||||
assetType: req.assetType || 'file',
|
||||
sort,
|
||||
order,
|
||||
})
|
||||
|
||||
return c.json(res)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
.get('/shares/:shareId/files/:fileId', async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
|
||||
try {
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const asset = await assetService.getAsset({ assetId: fileId })
|
||||
return c.json(asset)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
})
|
||||
.get(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('query', paginationParamsSchema),
|
||||
async (c) => {
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
try {
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
const res = await assetService.listComments(targetFileId, req)
|
||||
return c.json(res)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/shares/:shareId/files/:fileId/comments',
|
||||
zValidator('json', createCommentRequestSchema.omit({ assetId: true, userId: true })),
|
||||
async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const fileId = c.req.param('fileId')
|
||||
const password = c.req.header('x-share-password')
|
||||
const guestUserId = c.req.header('x-guest-user-id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
try {
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
await shareService.verifyPublicAccess(fileId, password)
|
||||
|
||||
const targetFileId = await assetService.resolveTargetAssetId(fileId)
|
||||
|
||||
const project = await prisma.project.findUnique({
|
||||
where: { id: shareLink.projectId },
|
||||
select: { teamId: true },
|
||||
})
|
||||
|
||||
if (!project) {
|
||||
throw new Error('Project not found')
|
||||
}
|
||||
|
||||
// Identify user
|
||||
let userId: string | null = null
|
||||
const session = await auth.api.getSession({
|
||||
headers: c.req.raw.headers,
|
||||
})
|
||||
|
||||
if (session?.user) {
|
||||
userId = session.user.id
|
||||
} else if (guestUserId) {
|
||||
const guestUser = await prisma.user.findUnique({
|
||||
where: { id: guestUserId },
|
||||
})
|
||||
if (guestUser) {
|
||||
userId = guestUser.id
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
|
||||
const comment = await assetService.createComment({
|
||||
assetId: targetFileId,
|
||||
userId: userId,
|
||||
replyToId: req.replyToId,
|
||||
message: req.message,
|
||||
annotations: req.annotations,
|
||||
second: req.second,
|
||||
attachmentIds: req.attachmentIds,
|
||||
})
|
||||
|
||||
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
|
||||
|
||||
notificationService.create({
|
||||
type: notifType,
|
||||
teamId: project.teamId,
|
||||
creatorId: userId,
|
||||
assetId: targetFileId,
|
||||
commentMessage: req.message,
|
||||
})
|
||||
|
||||
return c.json(comment, 201)
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message
|
||||
if (msg === 'Invalid password for share link') {
|
||||
return c.json({ error: 'Unauthorized' }, 401)
|
||||
}
|
||||
if (msg === 'Share link has expired' || msg === 'Share link is disabled') {
|
||||
return c.json({ error: msg }, 403)
|
||||
}
|
||||
return c.json({ error: msg }, 500)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { Hono } from 'hono'
|
||||
|
||||
const { mockServeStatic } = vi.hoisted(() => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
mockServeStatic: vi.fn<(args: any) => any>(() => (c: any) => c.text('static-file')),
|
||||
}))
|
||||
|
||||
vi.mock('hono/bun', () => ({
|
||||
serveStatic: mockServeStatic,
|
||||
}))
|
||||
|
||||
describe('S3 API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('GET /files/* calls serveStatic with correct options', async () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
|
||||
const res = await app.request('/files/b1/test.webp')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toBe('static-file')
|
||||
expect(mockServeStatic).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
root: './data',
|
||||
rewriteRequestPath: expect.any(Function),
|
||||
}),
|
||||
)
|
||||
|
||||
// Verify rewriteRequestPath logic
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const options = vi.mocked(mockServeStatic).mock.calls[0][0] as any
|
||||
if (options && options.rewriteRequestPath) {
|
||||
expect(options.rewriteRequestPath('/files/b1/test.webp')).toBe('b1/test.webp')
|
||||
}
|
||||
})
|
||||
|
||||
it('PUT /files/:bucket/:key calls s3Service.putObject', async () => {
|
||||
const { default: route } = await import('./s3')
|
||||
const app = new Hono().route('/files', route)
|
||||
const mockPut = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined)
|
||||
const body = new TextEncoder().encode('test-data')
|
||||
|
||||
const res = await app.request('/files/b1/test.webp', {
|
||||
method: 'PUT',
|
||||
body,
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toBe('OK')
|
||||
expect(mockPut).toHaveBeenCalledWith('b1', 'test.webp', expect.any(Buffer), body.byteLength)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Hono } from 'hono'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { serveStatic } from 'hono/bun'
|
||||
|
||||
const route = new Hono()
|
||||
.get(
|
||||
'/*',
|
||||
serveStatic({
|
||||
root: './data',
|
||||
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
|
||||
}),
|
||||
)
|
||||
.put('/:bucket/:key{.+}', async (c) => {
|
||||
const bucket = c.req.param('bucket')
|
||||
const key = c.req.param('key')
|
||||
const body = await c.req.arrayBuffer()
|
||||
|
||||
try {
|
||||
await s3Service.putObject(bucket, key, Buffer.from(body), body.byteLength)
|
||||
return c.text('OK')
|
||||
} catch (e: unknown) {
|
||||
const error = e as Error
|
||||
return c.text(error.message || 'Internal Server Error', 500)
|
||||
}
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,244 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import shareRoute from './share'
|
||||
import publicShareRoute from './public-share'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Project: 'project',
|
||||
Share: 'share',
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Share API', () => {
|
||||
const app = new Hono()
|
||||
.route('/', publicShareRoute)
|
||||
.use('*', authMiddleware)
|
||||
.route('/', shareRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
// Public Routes
|
||||
describe('GET /shares/:shareId/info', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'Public Share',
|
||||
isDisabled: false,
|
||||
isExpired: false,
|
||||
hasPassword: true,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1/info', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.name).toBe('Public Share')
|
||||
expect(body.hasPassword).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /shares/:shareId/folders/:folderId/children', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'My Share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'folder1',
|
||||
projectId: 'project1',
|
||||
password: null,
|
||||
expireAt: null,
|
||||
defaultSortOrder: 'name:asc',
|
||||
fieldVisibility: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
vi.spyOn(assetService, 'listChildren').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: { total: 0, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1/folders/folder1/children?assetType=file', {
|
||||
method: 'GET',
|
||||
headers: { 'x-share-password': 'pass' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('folder1', 'pass')
|
||||
expect(assetService.listChildren).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
assetId: 'folder1',
|
||||
assetType: 'file',
|
||||
sort: 'name',
|
||||
order: 'asc',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
// Protected Routes
|
||||
describe('POST /projects/:projectId/shares', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'createShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/projects/project1/shares', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'My Share' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.id).toBe('share1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Project,
|
||||
id: 'project1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(shareService.createShareLink).toHaveBeenCalledWith('project1', { name: 'My Share' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /projects/:projectId/shares', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'listProjectShareLinks').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: { total: 0, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/projects/project1/shares', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Project,
|
||||
id: 'project1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(shareService.listProjectShareLinks).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
projectId: 'project1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /shares/:shareId', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
const res = await app.request('/shares/share1', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Share,
|
||||
id: 'share1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(shareService.getShareLink).toHaveBeenCalledWith('share1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /shares/:shareId/assets', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
|
||||
id: 'share1',
|
||||
name: 'test-share',
|
||||
isDisabled: false,
|
||||
rootFolderId: 'root1',
|
||||
projectId: 'project1',
|
||||
isExpired: false,
|
||||
hasPassword: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
vi.spyOn(shareService, 'addAssetToShare').mockResolvedValue(1)
|
||||
|
||||
const res = await app.request('/shares/share1/assets', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ assetIds: ['asset1'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.addedCount).toBe(1)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Share,
|
||||
id: 'share1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'asset1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(shareService.addAssetToShare).toHaveBeenCalledWith('share1', { assetIds: ['asset1'] })
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,142 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import {
|
||||
createShareLinkRequestSchema,
|
||||
updateShareLinkRequestSchema,
|
||||
listShareLinksRequestSchema,
|
||||
addAssetToShareRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post(
|
||||
'/projects/:projectId/shares',
|
||||
zValidator('json', createShareLinkRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const shareLink = await shareService.createShareLink(projectId, req)
|
||||
return c.json(shareLink)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
'/projects/:projectId/shares',
|
||||
zValidator('query', listShareLinksRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const res = await shareService.listProjectShareLinks({
|
||||
...req,
|
||||
projectId,
|
||||
})
|
||||
|
||||
return c.json(res)
|
||||
},
|
||||
)
|
||||
.get('/shares/:shareId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
const shareLink = await shareService.getShareLink(shareId)
|
||||
return c.json(shareLink)
|
||||
})
|
||||
.put('/shares/:shareId', zValidator('json', updateShareLinkRequestSchema), async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
const updated = await shareService.updateShareLink(shareId, req)
|
||||
return c.json(updated)
|
||||
})
|
||||
.delete('/shares/:shareId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
await shareService.deleteShareLink(shareId)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.post('/shares/:shareId/assets', zValidator('json', addAssetToShareRequestSchema), async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
// Also check if user has read permission on the source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: assetId,
|
||||
})
|
||||
}
|
||||
|
||||
const addedCount = await shareService.addAssetToShare(shareId, req)
|
||||
return c.json({ addedCount })
|
||||
})
|
||||
.delete('/shares/:shareId/assets/:assetId', async (c) => {
|
||||
const shareId = c.req.param('shareId')
|
||||
const assetId = c.req.param('assetId') // symlink asset id
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Share,
|
||||
id: shareId,
|
||||
})
|
||||
|
||||
await shareService.removeAssetFromShare(shareId, assetId)
|
||||
return c.body(null, 204)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,200 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import skillRoute from './skill'
|
||||
import { skillService } from '@shumai/core/src/skill/skill'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
Skill: 'skill',
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Skill API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', skillRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('GET /teams/:teamId/skills', () => {
|
||||
test('Success', async () => {
|
||||
const mockSkills = [
|
||||
{
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
]
|
||||
vi.spyOn(skillService, 'listSkills').mockResolvedValue(mockSkills)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'GET',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ skills: mockSkills })
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /teams/:teamId/skills', () => {
|
||||
test('Success with assetId', async () => {
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'upsertSkill').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ assetId: 'asset1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', { assetId: 'asset1' })
|
||||
})
|
||||
|
||||
test('Success with githubUrl', async () => {
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: null,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'upsertSkill').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ githubUrl: 'https://github.com/test/repo' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', {
|
||||
githubUrl: 'https://github.com/test/repo',
|
||||
})
|
||||
})
|
||||
|
||||
test('Forbidden without Admin permission', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Forbidden'))
|
||||
|
||||
const res = await app.request('/teams/team1/skills', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ assetId: 'asset1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(500) // The app uses a global error handler that returns 500 for thrown errors in these tests
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /skills/:id', () => {
|
||||
test('Success', async () => {
|
||||
vi.spyOn(skillService, 'deleteSkill').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/skills/skill1', {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Skill,
|
||||
id: 'skill1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(skillService.deleteSkill).toHaveBeenCalledWith('skill1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /skills/:id/config', () => {
|
||||
test('Success', async () => {
|
||||
const mockConfig = {
|
||||
environmentVariables: [{ name: 'TEST_VAR', default: 'test_val' }],
|
||||
}
|
||||
const mockSkill = {
|
||||
id: 'skill1',
|
||||
name: 'Skill 1',
|
||||
description: 'Desc 1',
|
||||
config: mockConfig,
|
||||
assetId: 'asset1',
|
||||
hash: 'hash1',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
vi.spyOn(skillService, 'updateSkillConfig').mockResolvedValue(mockSkill)
|
||||
|
||||
const res = await app.request('/skills/skill1/config', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({ config: mockConfig }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual(mockSkill)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Skill,
|
||||
id: 'skill1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(skillService.updateSkillConfig).toHaveBeenCalledWith('skill1', mockConfig)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { skillService } from '@shumai/core/src/skill/skill'
|
||||
import { upsertSkillRequestSchema, updateSkillConfigRequestSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.get('/teams/:teamId/skills', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const skills = await skillService.listSkills(teamId)
|
||||
return c.json({ skills })
|
||||
})
|
||||
.post('/teams/:teamId/skills', zValidator('json', upsertSkillRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
try {
|
||||
const skill = await skillService.upsertSkill(teamId, req)
|
||||
return c.json(skill)
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error && err.name === 'ConflictError') {
|
||||
return c.json({ error: err.message }, 409)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
})
|
||||
.delete('/skills/:id', async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Skill,
|
||||
id,
|
||||
})
|
||||
|
||||
await skillService.deleteSkill(id)
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.patch('/skills/:id/config', zValidator('json', updateSkillConfigRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const id = c.req.param('id')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Skill,
|
||||
id,
|
||||
})
|
||||
|
||||
const skill = await skillService.updateSkillConfig(id, req.config)
|
||||
return c.json(skill)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,278 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import teamRoute from './team'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('team api', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
|
||||
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetUserTeams: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockJoinTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetMe: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetTeamMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockListUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpsertUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockCreateNotification: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateTeam = vi.spyOn(teamService, 'createTeam')
|
||||
mockGetUserTeams = vi.spyOn(teamService, 'getUserTeams')
|
||||
mockJoinTeam = vi.spyOn(teamService, 'joinTeam')
|
||||
mockGetMe = vi.spyOn(teamService, 'getMe')
|
||||
mockGetTeamMembers = vi.spyOn(teamService, 'getTeamMembers')
|
||||
mockGetSettings = vi.spyOn(teamService, 'getSettings')
|
||||
mockUpdateSettings = vi.spyOn(teamService, 'updateSettings')
|
||||
mockListUserMetadata = vi.spyOn(userMetadataService, 'listMetadata')
|
||||
mockUpsertUserMetadata = vi.spyOn(userMetadataService, 'upsertMetadata')
|
||||
mockCreateNotification = vi.spyOn(notificationService, 'create').mockResolvedValue()
|
||||
mockGetSandboxSettings = vi.spyOn(teamService, 'getSandboxSettings')
|
||||
mockUpdateSandboxSettings = vi.spyOn(teamService, 'updateSandboxSettings')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('POST /teams creates a new team', async () => {
|
||||
const mockTeam = { id: 't1', name: 'New Team', updatedAt: new Date() }
|
||||
mockCreateTeam.mockResolvedValue(mockTeam)
|
||||
|
||||
const res = await app.request('/teams', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'New Team',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.id).toBe('t1')
|
||||
expect(mockCreateTeam).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'user1' }),
|
||||
expect.objectContaining({ name: 'New Team' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams returns user teams', async () => {
|
||||
mockGetUserTeams.mockResolvedValue({
|
||||
data: [{ id: 't1', name: 'User Team', updatedAt: new Date() }],
|
||||
pageInfo: { total: 1, cursor: undefined },
|
||||
})
|
||||
|
||||
const res = await app.request('/teams?first=10')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.data[0].id).toBe('t1')
|
||||
expect(mockGetUserTeams).toHaveBeenCalledWith(expect.objectContaining({ userId: 'user1' }))
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/members joins team and sends notification', async () => {
|
||||
mockJoinTeam.mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/t1/members', { method: 'POST' })
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
expect(mockJoinTeam).toHaveBeenCalledWith({ teamId: 't1', userId: 'user1' })
|
||||
expect(mockCreateNotification).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'new_user_join_team',
|
||||
teamId: 't1',
|
||||
userId: 'user1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/me returns user role in team', async () => {
|
||||
mockGetMe.mockResolvedValue({ id: 'user1', name: 'Test User', role: 'owner' })
|
||||
|
||||
const res = await app.request('/teams/t1/me')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.role).toBe('owner')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetMe).toHaveBeenCalledWith({ teamId: 't1', user: expect.any(Object) })
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/members returns members', async () => {
|
||||
mockGetTeamMembers.mockResolvedValue([{ id: 'user1', name: 'Test User', role: 'owner' }])
|
||||
|
||||
const res = await app.request('/teams/t1/members')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetTeamMembers).toHaveBeenCalledWith({ teamId: 't1', includeAgents: false })
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/settings returns settings', async () => {
|
||||
mockGetSettings.mockResolvedValue({ someKey: 'some_value' })
|
||||
|
||||
const res = await app.request('/teams/t1/settings')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.someKey).toBe('some_value')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetSettings).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/settings updates settings', async () => {
|
||||
mockUpdateSettings.mockResolvedValue({ someKey: 'new_value' })
|
||||
|
||||
const res = await app.request('/teams/t1/settings', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: 'someKey', value: 'new_value' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.someKey).toBe('new_value')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(mockUpdateSettings).toHaveBeenCalledWith('t1', 'someKey', 'new_value')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/user-metadata returns all metadata for the user in the team', async () => {
|
||||
mockListUserMetadata.mockResolvedValue([
|
||||
{ key: 'key1', value: 'value1' },
|
||||
{ key: 'key2', value: 'value2' },
|
||||
])
|
||||
|
||||
const res = await app.request('/teams/t1/user-metadata')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(2)
|
||||
expect(data[0].key).toBe('key1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockListUserMetadata).toHaveBeenCalledWith('user1', 't1')
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/user-metadata/:key upserts the metadata', async () => {
|
||||
mockUpsertUserMetadata.mockResolvedValue({ key: 'key1', value: 'value1' })
|
||||
|
||||
const res = await app.request('/teams/t1/user-metadata/key1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ value: 'value1' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.key).toBe('key1')
|
||||
expect(data.value).toBe('value1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockUpsertUserMetadata).toHaveBeenCalledWith('user1', 't1', 'key1', 'value1')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/sandbox returns sandbox settings', async () => {
|
||||
mockGetSandboxSettings.mockResolvedValue({ allowedDomains: ['example.com'] })
|
||||
|
||||
const res = await app.request('/teams/t1/sandbox')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.allowedDomains).toEqual(['example.com'])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetSandboxSettings).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/sandbox updates sandbox settings', async () => {
|
||||
mockUpdateSandboxSettings.mockResolvedValue({ allowedDomains: ['new.com'] })
|
||||
|
||||
const res = await app.request('/teams/t1/sandbox', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ allowedDomains: ['new.com'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.allowedDomains).toEqual(['new.com'])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(mockUpdateSandboxSettings).toHaveBeenCalledWith('t1', { allowedDomains: ['new.com'] })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,200 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import {
|
||||
createTeamRequestSchema,
|
||||
getUserTeamsRequestSchema,
|
||||
updateTeamSettingsRequestSchema,
|
||||
listMembersQuerySchema,
|
||||
updateSandboxSettingsRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { updateUserMetadataRequestSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.post('/teams', zValidator('json', createTeamRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
const newTeam = await teamService.createTeam(user, req)
|
||||
return c.json(newTeam)
|
||||
})
|
||||
.get('/teams', zValidator('query', getUserTeamsRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const pg = c.req.valid('query')
|
||||
|
||||
const teams = await teamService.getUserTeams({
|
||||
userId: user.id,
|
||||
pagination: pg,
|
||||
})
|
||||
|
||||
return c.json({
|
||||
data: teams.data,
|
||||
pageInfo: {
|
||||
total: teams.pageInfo.total,
|
||||
cursor: teams.pageInfo.cursor,
|
||||
},
|
||||
})
|
||||
})
|
||||
.post('/teams/:teamId/members', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await teamService.joinTeam({
|
||||
teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
await notificationService.create({
|
||||
type: NotificationType.new_user_join_team,
|
||||
teamId,
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
.get('/teams/:teamId/me', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const me = await teamService.getMe({
|
||||
teamId,
|
||||
user,
|
||||
})
|
||||
|
||||
return c.json(me)
|
||||
})
|
||||
.get('/teams/:teamId/members', zValidator('query', listMembersQuerySchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const { includeAgents } = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const members = await teamService.getTeamMembers({
|
||||
teamId,
|
||||
includeAgents: includeAgents,
|
||||
})
|
||||
|
||||
return c.json(members)
|
||||
})
|
||||
.get('/teams/:teamId/settings', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const settings = await teamService.getSettings(teamId)
|
||||
return c.json(settings)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/settings',
|
||||
zValidator('json', updateTeamSettingsRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const settings = await teamService.updateSettings(teamId, req.key, req.value)
|
||||
return c.json(settings)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/sandbox', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const sandbox = await teamService.getSandboxSettings(teamId)
|
||||
return c.json(sandbox)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/sandbox',
|
||||
zValidator('json', updateSandboxSettingsRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const sandbox = await teamService.updateSandboxSettings(teamId, req)
|
||||
return c.json(sandbox)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/user-metadata', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.listMetadata(user.id, teamId)
|
||||
return c.json(metadata)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/user-metadata/:key',
|
||||
zValidator('json', updateUserMetadataRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const key = c.req.param('key')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const metadata = await userMetadataService.upsertMetadata(user.id, teamId, key, req.value)
|
||||
return c.json({ key: metadata.key, value: metadata.value })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import uploadRoute from './upload'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import type { CreateUploadTaskResponse, TaskInfo } from '@shumai/dtos'
|
||||
import type { PaginatedData } from '@shumai/core/src/pagination'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// We use any here because mocking Hono context and middleware
|
||||
// with full type safety is overly complex for these unit tests.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
c.set('user', { id: 'user1', name: 'Test User' } as any)
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Team: 'team',
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/notification/notification', () => ({
|
||||
notificationService: {
|
||||
create: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Upload API', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', uploadRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/upload/tasks', async () => {
|
||||
// We mock the return value as it is only used for checking the call
|
||||
vi.spyOn(uploadService, 'listUploadTasks').mockResolvedValue({
|
||||
data: [],
|
||||
pageInfo: {},
|
||||
} as unknown as PaginatedData<TaskInfo[]>)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks', {
|
||||
headers: { Authorization: 'Bearer test' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 'team1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(uploadService.listUploadTasks).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/upload/tasks', async () => {
|
||||
// We mock the return value as it is only used for checking the call
|
||||
vi.spyOn(uploadService, 'createUploadTask').mockResolvedValue({
|
||||
taskId: 'task1',
|
||||
presignedUrls: [],
|
||||
} as unknown as CreateUploadTaskResponse)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
parentId: 'parent1',
|
||||
files: [],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'parent1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(uploadService.createUploadTask).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('PATCH /teams/:teamId/upload/tasks/:taskId', async () => {
|
||||
vi.spyOn(uploadService, 'confirmFileUpload').mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/team1/upload/tasks/task1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' },
|
||||
body: JSON.stringify({
|
||||
fileId: 'file1',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'file1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(uploadService.confirmFileUpload).toHaveBeenCalledWith('user1', 'task1', {
|
||||
fileId: 'file1',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import {
|
||||
confirmFileUploadRequestSchema,
|
||||
createUploadTaskRequestSchema,
|
||||
localUploadQuerySchema,
|
||||
} from '@shumai/dtos'
|
||||
import { paginationParamsSchema } from '@shumai/dtos'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
import { s3Service, verifyLocalUrlSignature } from '@shumai/core/src/s3/s3'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const route = new Hono<{ Variables: { user: User } }>()
|
||||
.put('/upload/local', zValidator('query', localUploadQuerySchema), async (c) => {
|
||||
const { bucket, key, Signature } = c.req.valid('query')
|
||||
|
||||
if (!verifyLocalUrlSignature(bucket, key, Signature)) {
|
||||
return c.text('Invalid signature', 403)
|
||||
}
|
||||
|
||||
const contentType = c.req.header('Content-Type')
|
||||
let buffer: Buffer
|
||||
let size: number
|
||||
let finalContentType = contentType
|
||||
|
||||
if (contentType?.includes('multipart/form-data')) {
|
||||
const body = await c.req.parseBody()
|
||||
const file = body['file'] as File
|
||||
if (!file) {
|
||||
return c.text('No file uploaded', 400)
|
||||
}
|
||||
buffer = Buffer.from(await file.arrayBuffer())
|
||||
size = file.size
|
||||
finalContentType = file.type || 'application/octet-stream'
|
||||
} else {
|
||||
const arrayBuffer = await c.req.arrayBuffer()
|
||||
buffer = Buffer.from(arrayBuffer)
|
||||
size = arrayBuffer.byteLength
|
||||
}
|
||||
|
||||
await s3Service.putObject(bucket, key, buffer, size, finalContentType)
|
||||
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/teams/:teamId/upload/tasks', zValidator('query', paginationParamsSchema), async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const user = c.get('user')
|
||||
const params = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const tasks = await uploadService.listUploadTasks(user.id, params)
|
||||
return c.json(tasks)
|
||||
})
|
||||
.post(
|
||||
'/teams/:teamId/upload/tasks',
|
||||
zValidator('json', createUploadTaskRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.parentId,
|
||||
})
|
||||
|
||||
const resp = await uploadService.createUploadTask(user.id, req)
|
||||
return c.json(resp)
|
||||
},
|
||||
)
|
||||
.patch(
|
||||
'/teams/:teamId/upload/tasks/:taskId',
|
||||
zValidator('json', confirmFileUploadRequestSchema),
|
||||
async (c) => {
|
||||
const teamId = c.req.param('teamId')
|
||||
const taskId = c.req.param('taskId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: req.fileId,
|
||||
})
|
||||
|
||||
await uploadService.confirmFileUpload(user.id, taskId, req)
|
||||
|
||||
if (!req.errorMessage) {
|
||||
await notificationService.create({
|
||||
type: NotificationType.successful_file_uploaded,
|
||||
teamId: teamId,
|
||||
creatorId: user.id,
|
||||
assetId: req.fileId,
|
||||
taskId: taskId,
|
||||
})
|
||||
}
|
||||
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import versionStackRoute from './versionStack'
|
||||
import { authMiddleware } from './middleware/auth'
|
||||
import { versionStackService } from '@shumai/core/src/versionStack/versionStack'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: {
|
||||
Read: 'Read',
|
||||
Edit: 'Edit',
|
||||
Admin: 'Admin',
|
||||
},
|
||||
ResourceType: {
|
||||
Project: 'project',
|
||||
Asset: 'asset',
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./middleware/auth', () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
authMiddleware: async (c: any, next: any) => {
|
||||
c.set('user', { id: 'user1', name: 'Test User' })
|
||||
await next()
|
||||
},
|
||||
}))
|
||||
|
||||
describe('versionStack api', () => {
|
||||
let mockCreateVersionStack: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockChangeStackFileVersion: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetAsset: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetStackVersions: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
mockCreateVersionStack = vi.spyOn(versionStackService, 'createVersionStack')
|
||||
mockChangeStackFileVersion = vi.spyOn(versionStackService, 'changeStackFileVersion')
|
||||
mockGetAsset = vi.spyOn(assetService, 'getAsset')
|
||||
mockGetStackVersions = vi.spyOn(assetService, 'getStackVersions')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('POST /projects/:projectID/version_stacks', () => {
|
||||
it('should create a version stack and return asset info', async () => {
|
||||
const mockStack = { id: 'stack1' }
|
||||
const mockAssetInfo = { id: 'stack1', type: 'version_stack', name: 'v1' }
|
||||
|
||||
mockCreateVersionStack.mockResolvedValue(mockStack)
|
||||
mockGetAsset.mockResolvedValue(mockAssetInfo)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/projects/p1/version_stacks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileIds: ['f1', 'f2'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toEqual(mockAssetInfo)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Project,
|
||||
id: 'p1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(mockCreateVersionStack).toHaveBeenCalledWith({
|
||||
projectId: 'p1',
|
||||
creatorId: 'user1',
|
||||
fileIds: ['f1', 'f2'],
|
||||
})
|
||||
expect(mockGetAsset).toHaveBeenCalledWith({ assetId: 'stack1' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /version_stacks/:stackID/order', () => {
|
||||
it('should change order and return 200', async () => {
|
||||
mockChangeStackFileVersion.mockResolvedValue()
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/version_stacks/stack1/order', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ fileId: 'f1', beforeId: 'f2' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'stack1',
|
||||
permission: Permission.Edit,
|
||||
}),
|
||||
)
|
||||
expect(mockChangeStackFileVersion).toHaveBeenCalledWith({
|
||||
stackId: 'stack1',
|
||||
fileId: 'f1',
|
||||
beforeId: 'f2',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /version_stacks/:stackID/versions', () => {
|
||||
it('should return stack versions', async () => {
|
||||
const mockVersions = [
|
||||
{
|
||||
id: 'v1',
|
||||
version: 1,
|
||||
name: 'version1.png',
|
||||
previewUrl: 'http://preview1',
|
||||
creator: { id: 'u1', name: 'User 1' },
|
||||
},
|
||||
]
|
||||
|
||||
mockGetStackVersions.mockResolvedValue(mockVersions)
|
||||
|
||||
const app = new Hono().use('*', authMiddleware).route('/', versionStackRoute)
|
||||
|
||||
const res = await app.request('/version_stacks/stack1/versions', {
|
||||
method: 'GET',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toEqual(mockVersions)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Asset,
|
||||
id: 'stack1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetStackVersions).toHaveBeenCalledWith('stack1')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { versionStackService } from '@shumai/core/src/versionStack/versionStack'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { createVersionStackRequestSchema, changeStackFileVersionRequestSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const app = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
const route = app
|
||||
.post(
|
||||
'/projects/:projectId/version_stacks',
|
||||
zValidator('json', createVersionStackRequestSchema),
|
||||
async (c) => {
|
||||
const projectId = c.req.param('projectId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
const stack = await versionStackService.createVersionStack({
|
||||
fileIds: req.fileIds,
|
||||
projectId,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
const stackInfo = await assetService.getAsset({ assetId: stack.id })
|
||||
|
||||
return c.json(stackInfo)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/version_stacks/:stackId/order',
|
||||
zValidator('json', changeStackFileVersionRequestSchema),
|
||||
async (c) => {
|
||||
const stackId = c.req.param('stackId')
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: stackId,
|
||||
})
|
||||
|
||||
await versionStackService.changeStackFileVersion({
|
||||
stackId,
|
||||
fileId: req.fileId,
|
||||
beforeId: req.beforeId,
|
||||
})
|
||||
|
||||
return new Response(null, { status: 200 })
|
||||
},
|
||||
)
|
||||
.get('/version_stacks/:stackId/versions', async (c) => {
|
||||
const stackId = c.req.param('stackId')
|
||||
const user = c.get('user')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: stackId,
|
||||
})
|
||||
|
||||
const versions = await assetService.getStackVersions(stackId)
|
||||
return c.json(versions)
|
||||
})
|
||||
|
||||
export default route
|
||||
@@ -0,0 +1,22 @@
|
||||
import { loadEnvConfig } from '@shumai/core/src/env-loader'
|
||||
loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production')
|
||||
|
||||
const command = process.argv[2]
|
||||
|
||||
if (command === 'worker') {
|
||||
const { run } = await import('./worker')
|
||||
run().catch((err) => {
|
||||
console.error(err)
|
||||
process.exit(1)
|
||||
})
|
||||
} else {
|
||||
// Default or 'serve' command
|
||||
const { run } = await import('./serve')
|
||||
run().catch((err) => {
|
||||
console.error(err)
|
||||
process.exit(1)
|
||||
})
|
||||
}
|
||||
|
||||
// Re-export AppType for frontend client.ts usage (type-only)
|
||||
export type { AppType } from './serve'
|
||||
@@ -0,0 +1,128 @@
|
||||
import index from '../../webui/index.html'
|
||||
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { Hono } from 'hono'
|
||||
import agentRoute from './api/agent'
|
||||
import attachmentRoute from './api/attachment'
|
||||
import authnRoute from './api/authn'
|
||||
import collectionRoute from './api/collection'
|
||||
import fileRoute from './api/file'
|
||||
import folderRoute from './api/folder'
|
||||
import inviteRoute from './api/invite'
|
||||
import metadataRoute from './api/metadata'
|
||||
import { authMiddleware } from './api/middleware/auth'
|
||||
import notificationRoute from './api/notification'
|
||||
import projectRoute from './api/project'
|
||||
import providerRoute from './api/provider'
|
||||
import publicInviteRoute from './api/public-invite'
|
||||
import publicShareRoute from './api/public-share'
|
||||
import s3Route from './api/s3'
|
||||
import shareRoute from './api/share'
|
||||
import skillRoute from './api/skill'
|
||||
import teamRoute from './api/team'
|
||||
import uploadRoute from './api/upload'
|
||||
import versionStackRoute from './api/versionStack'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { initDbWorkflows } from '@shumai/worker-db'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
const apiRoute = new Hono<{ Variables: { user: User } }>()
|
||||
// Public Routes
|
||||
.route('/', authnRoute)
|
||||
.route('/', publicInviteRoute)
|
||||
.route('/', publicShareRoute)
|
||||
|
||||
// Protected Routes
|
||||
.use('*', authMiddleware)
|
||||
.route('/', inviteRoute)
|
||||
.route('/', providerRoute)
|
||||
.route('/', notificationRoute)
|
||||
.route('/', metadataRoute)
|
||||
.route('/', projectRoute)
|
||||
.route('/', collectionRoute)
|
||||
.route('/', teamRoute)
|
||||
.route('/', versionStackRoute)
|
||||
.route('/', fileRoute)
|
||||
.route('/', folderRoute)
|
||||
.route('/', agentRoute)
|
||||
.route('/', attachmentRoute)
|
||||
.route('/', uploadRoute)
|
||||
.route('/', shareRoute)
|
||||
.route('/', skillRoute)
|
||||
|
||||
app.route('/files', s3Route)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const apiAppRoute = app.route('/api', apiRoute)
|
||||
|
||||
export type AppType = typeof apiAppRoute
|
||||
|
||||
export async function run() {
|
||||
// Initialize workflows and activities for local executor mode
|
||||
initAgentWorkflows()
|
||||
initTranscodeWorkflows()
|
||||
initDbWorkflows()
|
||||
|
||||
// Start services
|
||||
await metadataService.syncSystemFields().catch(console.error)
|
||||
assetService.startCleanupJob()
|
||||
workflowService.start()
|
||||
if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
|
||||
const args = process.argv.slice(2)
|
||||
let workersOption = ''
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '--workers') {
|
||||
workersOption = args[i + 1] || ''
|
||||
} else if (args[i].startsWith('--workers=')) {
|
||||
workersOption = args[i].split('=')[1]
|
||||
}
|
||||
}
|
||||
|
||||
const queuesToStart = ['db_queue']
|
||||
if (workersOption === 'agent' || workersOption === 'ai') {
|
||||
queuesToStart.push('agent_queue')
|
||||
} else if (workersOption === 'transcode') {
|
||||
queuesToStart.push('transcode_queue')
|
||||
} else if (workersOption === 'all') {
|
||||
queuesToStart.push('agent_queue', 'transcode_queue')
|
||||
}
|
||||
|
||||
Promise.all(queuesToStart.map((q) => workflowService.startWorkers(q))).catch(console.error)
|
||||
}
|
||||
|
||||
const server = Bun.serve({
|
||||
port: 3000,
|
||||
fetch: app.fetch,
|
||||
routes: {
|
||||
// Serve index.html for root
|
||||
'/': index,
|
||||
|
||||
// Proxy API requests to Hono
|
||||
'/api/*': app.fetch,
|
||||
'/files/*': app.fetch,
|
||||
|
||||
// Catch-all for SPA routing (fallback to index.html)
|
||||
'/*': index,
|
||||
},
|
||||
development: process.env.NODE_ENV !== 'production',
|
||||
})
|
||||
|
||||
console.log(`🚀 Server running at ${server.url}`)
|
||||
|
||||
const shutdown = () => {
|
||||
console.log('\nShutting down gracefully...')
|
||||
assetService.stopCleanupJob()
|
||||
server.stop(true)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
process.on('SIGINT', shutdown)
|
||||
process.on('SIGTERM', shutdown)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { initDbWorkflows } from '@shumai/worker-db'
|
||||
|
||||
export async function run() {
|
||||
// Initialize workflows and activities
|
||||
initAgentWorkflows()
|
||||
initTranscodeWorkflows()
|
||||
initDbWorkflows()
|
||||
|
||||
const domain = process.argv[3]
|
||||
|
||||
if (!domain) {
|
||||
console.error('Please specify a worker domain.')
|
||||
console.log('Available domains: agent, transcode, all')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
switch (domain) {
|
||||
case 'agent':
|
||||
case 'ai':
|
||||
await workflowService.startWorkers(TaskQueueAgent)
|
||||
break
|
||||
case 'transcode':
|
||||
await workflowService.startWorkers(TaskQueueTranscode)
|
||||
break
|
||||
case 'all':
|
||||
await Promise.all([
|
||||
workflowService.startWorkers(TaskQueueAgent),
|
||||
workflowService.startWorkers(TaskQueueTranscode),
|
||||
])
|
||||
break
|
||||
default:
|
||||
console.error('Unknown domain: ' + domain)
|
||||
console.log('Available domains: agent, transcode, all')
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"ignoreDeprecations": "6.0"
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
AssetUserInfo,
|
||||
} from '@shumai/dtos'
|
||||
import { type Asset, AssetStatus, AssetType, Prisma, type StorageKey } from '@shumai/db'
|
||||
import { logger } from '@/logger'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import * as dotenv from 'dotenv'
|
||||
import { expand as dotenvExpand } from 'dotenv-expand'
|
||||
|
||||
export type Env = { [key: string]: string | undefined }
|
||||
export type LoadedEnvFiles = Array<{
|
||||
path: string
|
||||
contents: string
|
||||
env: Env
|
||||
}>
|
||||
|
||||
let initialEnv: Env | undefined = undefined
|
||||
let combinedEnv: Env | undefined = undefined
|
||||
let cachedLoadedEnvFiles: LoadedEnvFiles = []
|
||||
|
||||
type Log = {
|
||||
info: (...args: unknown[]) => void
|
||||
error: (...args: unknown[]) => void
|
||||
}
|
||||
|
||||
function replaceProcessEnv(sourceEnv: Env) {
|
||||
Object.keys(process.env).forEach((key) => {
|
||||
if (sourceEnv[key] === undefined || sourceEnv[key] === '') {
|
||||
delete process.env[key]
|
||||
}
|
||||
})
|
||||
|
||||
Object.entries(sourceEnv).forEach(([key, value]) => {
|
||||
process.env[key] = value
|
||||
})
|
||||
}
|
||||
|
||||
export function processEnv(loadedEnvFiles: LoadedEnvFiles, dir?: string, log: Log = console) {
|
||||
if (!initialEnv) {
|
||||
initialEnv = Object.assign({}, process.env)
|
||||
}
|
||||
|
||||
const origEnv = Object.assign({}, initialEnv)
|
||||
const parsed: dotenv.DotenvParseOutput = {}
|
||||
|
||||
for (const envFile of loadedEnvFiles) {
|
||||
try {
|
||||
const result: dotenv.DotenvConfigOutput = {}
|
||||
result.parsed = dotenv.parse(envFile.contents)
|
||||
|
||||
const expandResult = dotenvExpand(result)
|
||||
const parsedResult = expandResult.parsed
|
||||
if (parsedResult) {
|
||||
for (const key of Object.keys(parsedResult)) {
|
||||
if (typeof parsed[key] === 'undefined' && typeof origEnv[key] === 'undefined') {
|
||||
parsed[key] = parsedResult[key]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
envFile.env = result.parsed || {}
|
||||
} catch (err) {
|
||||
log.error(`Failed to load env from ${path.join(dir || '', envFile.path)}`, err)
|
||||
}
|
||||
}
|
||||
|
||||
return Object.assign(process.env, parsed)
|
||||
}
|
||||
|
||||
export function loadEnvConfig(
|
||||
dir: string,
|
||||
dev?: boolean,
|
||||
log: Log = console,
|
||||
): {
|
||||
combinedEnv: Env
|
||||
loadedEnvFiles: LoadedEnvFiles
|
||||
} {
|
||||
if (!initialEnv) {
|
||||
initialEnv = Object.assign({}, process.env)
|
||||
}
|
||||
|
||||
if (combinedEnv) {
|
||||
return { combinedEnv, loadedEnvFiles: cachedLoadedEnvFiles }
|
||||
}
|
||||
|
||||
replaceProcessEnv(initialEnv)
|
||||
cachedLoadedEnvFiles = []
|
||||
|
||||
const isTest = process.env.NODE_ENV === 'test'
|
||||
const mode = isTest ? 'test' : dev ? 'development' : 'production'
|
||||
const dotenvFiles = [
|
||||
`.env.${mode}.local`,
|
||||
mode !== 'test' && `.env.local`,
|
||||
`.env.${mode}`,
|
||||
'.env',
|
||||
].filter(Boolean) as string[]
|
||||
|
||||
for (const envFile of dotenvFiles) {
|
||||
const dotEnvPath = path.join(dir, envFile)
|
||||
|
||||
try {
|
||||
const stats = fs.statSync(dotEnvPath)
|
||||
|
||||
if (!stats.isFile() && !stats.isFIFO()) {
|
||||
continue
|
||||
}
|
||||
|
||||
const contents = fs.readFileSync(dotEnvPath, 'utf8')
|
||||
cachedLoadedEnvFiles.push({
|
||||
path: envFile,
|
||||
contents,
|
||||
env: {},
|
||||
})
|
||||
} catch (err: unknown) {
|
||||
if (err && typeof err === 'object' && 'code' in err && err.code !== 'ENOENT') {
|
||||
log.error(`Failed to load env from ${envFile}`, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
combinedEnv = processEnv(cachedLoadedEnvFiles, dir, log)
|
||||
|
||||
return { combinedEnv, loadedEnvFiles: cachedLoadedEnvFiles }
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
import pino from 'pino'
|
||||
|
||||
const LOG_LEVEL = process.env.LOG_LEVEL || 'info'
|
||||
const LOG_FORMAT = process.env.LOG_FORMAT || 'json'
|
||||
|
||||
const transport =
|
||||
LOG_FORMAT === 'console'
|
||||
? {
|
||||
target: 'pino-pretty',
|
||||
options: {
|
||||
colorize: true,
|
||||
},
|
||||
}
|
||||
: undefined
|
||||
|
||||
export const logger = pino({
|
||||
level: LOG_LEVEL,
|
||||
transport,
|
||||
})
|
||||
@@ -3,7 +3,7 @@ import { teamService } from '@shumai/core/src/team/team'
|
||||
import { providerService } from './provider'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
|
||||
import { builtinProviders } from '@/generated/providers.generated'
|
||||
import { builtinProviders } from '@shumai/core/src/generated/providers.generated'
|
||||
import { z } from 'zod'
|
||||
|
||||
type ProviderModel = z.infer<typeof providerModelSchema>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
|
||||
import { builtinProviders } from '@/generated/providers.generated'
|
||||
import { builtinProviders } from '@shumai/core/src/generated/providers.generated'
|
||||
import { z } from 'zod'
|
||||
|
||||
type ProviderModel = z.infer<typeof providerModelSchema>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { AssetService, assetService } from '@shumai/core/src/asset/asset'
|
||||
import { AssetInfo } from '@shumai/dtos'
|
||||
import { SearchRequest } from '@shumai/dtos'
|
||||
import { PaginatedData, decodeCursor, encodeCursor, PageInfo } from '@shumai/core/src/pagination'
|
||||
import { generateSearchNgrams } from '@/utils/ngram'
|
||||
import { generateSearchNgrams } from '@shumai/core/src/utils/ngram'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { SqlQueryBuilder } from './sql-query-builder'
|
||||
|
||||
@@ -4,7 +4,7 @@ import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import AdmZip from 'adm-zip'
|
||||
import * as crypto from 'crypto'
|
||||
import { ulid } from 'ulid'
|
||||
import { parseFrontmatter } from '@/utils/frontmatter'
|
||||
import { parseFrontmatter } from '@shumai/core/src/utils/frontmatter'
|
||||
|
||||
interface SkillFrontmatter extends Record<string, unknown> {
|
||||
name?: string
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseFrontmatter } from './frontmatter'
|
||||
|
||||
describe('frontmatter parser', () => {
|
||||
it('should parse content with frontmatter', () => {
|
||||
const content = `---
|
||||
name: test-skill
|
||||
description: simple skill
|
||||
---
|
||||
# Body
|
||||
Hello world`
|
||||
const { frontmatter, body } = parseFrontmatter<{ name: string; description: string }>(content)
|
||||
expect(frontmatter.name).toBe('test-skill')
|
||||
expect(frontmatter.description).toBe('simple skill')
|
||||
expect(body).toBe('# Body\nHello world')
|
||||
})
|
||||
|
||||
it('should handle content without frontmatter', () => {
|
||||
const content = '# No Frontmatter\nJust text'
|
||||
const { frontmatter, body } = parseFrontmatter(content)
|
||||
expect(frontmatter).toEqual({})
|
||||
expect(body).toBe(content)
|
||||
})
|
||||
|
||||
it('should handle invalid frontmatter delimiters', () => {
|
||||
const content = `---
|
||||
no-end-delimiter
|
||||
# Body`
|
||||
const { frontmatter, body } = parseFrontmatter(content)
|
||||
expect(frontmatter).toEqual({})
|
||||
expect(body).toBe(content)
|
||||
})
|
||||
|
||||
it('should normalize newlines', () => {
|
||||
const content = '---\r\nname: win\r\n---\r\n# Body'
|
||||
const { frontmatter, body } = parseFrontmatter<{ name: string }>(content)
|
||||
expect(frontmatter.name).toBe('win')
|
||||
expect(body).toBe('# Body')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import { parse } from 'yaml'
|
||||
|
||||
export type ParsedFrontmatter<T extends Record<string, unknown>> = {
|
||||
frontmatter: T
|
||||
body: string
|
||||
}
|
||||
|
||||
const normalizeNewlines = (value: string): string =>
|
||||
value.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
|
||||
|
||||
const extractFrontmatter = (content: string): { yamlString: string | null; body: string } => {
|
||||
const normalized = normalizeNewlines(content)
|
||||
|
||||
if (!normalized.startsWith('---')) {
|
||||
return { yamlString: null, body: normalized }
|
||||
}
|
||||
|
||||
const endIndex = normalized.indexOf('\n---', 3)
|
||||
if (endIndex === -1) {
|
||||
return { yamlString: null, body: normalized }
|
||||
}
|
||||
|
||||
return {
|
||||
yamlString: normalized.slice(4, endIndex),
|
||||
body: normalized.slice(endIndex + 4).trim(),
|
||||
}
|
||||
}
|
||||
|
||||
export const parseFrontmatter = <T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
content: string,
|
||||
): ParsedFrontmatter<T> => {
|
||||
const { yamlString, body } = extractFrontmatter(content)
|
||||
if (!yamlString) {
|
||||
return { frontmatter: {} as T, body }
|
||||
}
|
||||
const parsed = parse(yamlString)
|
||||
return { frontmatter: (parsed ?? {}) as T, body }
|
||||
}
|
||||
|
||||
export const stripFrontmatter = (content: string): string => parseFrontmatter(content).body
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { detectSupportedMimeType } from './mime'
|
||||
|
||||
describe('detectSupportedMimeType', () => {
|
||||
it('should detect JPEG', () => {
|
||||
const buffer = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46])
|
||||
expect(detectSupportedMimeType(buffer)).toBe('image/jpeg')
|
||||
})
|
||||
|
||||
it('should detect PNG', () => {
|
||||
const buffer = new Uint8Array([
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,
|
||||
0x52,
|
||||
])
|
||||
expect(detectSupportedMimeType(buffer)).toBe('image/png')
|
||||
})
|
||||
|
||||
it('should detect GIF', () => {
|
||||
const buffer = new Uint8Array([0x47, 0x49, 0x46, 0x38, 0x39, 0x61])
|
||||
expect(detectSupportedMimeType(buffer)).toBe('image/gif')
|
||||
})
|
||||
|
||||
it('should detect WEBP', () => {
|
||||
const buffer = new Uint8Array([
|
||||
0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50,
|
||||
])
|
||||
expect(detectSupportedMimeType(buffer)).toBe('image/webp')
|
||||
})
|
||||
|
||||
it('should detect MP4', () => {
|
||||
const buffer = new Uint8Array([
|
||||
0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d,
|
||||
])
|
||||
expect(detectSupportedMimeType(buffer)).toBe('video/mp4')
|
||||
})
|
||||
|
||||
it('should return null for unknown type', () => {
|
||||
const buffer = new Uint8Array([0x00, 0x00, 0x00, 0x00])
|
||||
expect(detectSupportedMimeType(buffer)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
|
||||
export function detectSupportedMimeType(buffer: Uint8Array): string | null {
|
||||
if (startsWith(buffer, [0xff, 0xd8, 0xff])) {
|
||||
return buffer[3] === 0xf7 ? null : 'image/jpeg'
|
||||
}
|
||||
if (startsWith(buffer, PNG_SIGNATURE)) {
|
||||
return isPng(buffer) && !isAnimatedPng(buffer) ? 'image/png' : null
|
||||
}
|
||||
if (startsWithAscii(buffer, 0, 'GIF')) {
|
||||
return 'image/gif'
|
||||
}
|
||||
if (startsWithAscii(buffer, 0, 'RIFF') && startsWithAscii(buffer, 8, 'WEBP')) {
|
||||
return 'image/webp'
|
||||
}
|
||||
if (startsWithAscii(buffer, 4, 'ftyp')) {
|
||||
return 'video/mp4'
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function isPng(buffer: Uint8Array): boolean {
|
||||
return (
|
||||
buffer.length >= 16 &&
|
||||
readUint32Be(buffer, PNG_SIGNATURE.length) === 13 &&
|
||||
startsWithAscii(buffer, 12, 'IHDR')
|
||||
)
|
||||
}
|
||||
|
||||
function isAnimatedPng(buffer: Uint8Array): boolean {
|
||||
let offset = PNG_SIGNATURE.length
|
||||
while (offset + 8 <= buffer.length) {
|
||||
const chunkLength = readUint32Be(buffer, offset)
|
||||
const chunkTypeOffset = offset + 4
|
||||
if (startsWithAscii(buffer, chunkTypeOffset, 'acTL')) return true
|
||||
if (startsWithAscii(buffer, chunkTypeOffset, 'IDAT')) return false
|
||||
|
||||
const nextOffset = offset + 8 + chunkLength + 4
|
||||
if (nextOffset <= offset || nextOffset > buffer.length) return false
|
||||
offset = nextOffset
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function readUint32Be(buffer: Uint8Array, offset: number): number {
|
||||
return (
|
||||
(buffer[offset] ?? 0) * 0x1000000 +
|
||||
((buffer[offset + 1] ?? 0) << 16) +
|
||||
((buffer[offset + 2] ?? 0) << 8) +
|
||||
(buffer[offset + 3] ?? 0)
|
||||
)
|
||||
}
|
||||
|
||||
function startsWith(buffer: Uint8Array, bytes: number[]): boolean {
|
||||
if (buffer.length < bytes.length) return false
|
||||
return bytes.every((byte, index) => buffer[index] === byte)
|
||||
}
|
||||
|
||||
function startsWithAscii(buffer: Uint8Array, offset: number, text: string): boolean {
|
||||
if (buffer.length < offset + text.length) return false
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
if (buffer[offset + index] !== text.charCodeAt(index)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { generateNgrams } from './ngram'
|
||||
|
||||
describe('generateNgrams', () => {
|
||||
it('should generate 1-3 grams for simple English words', () => {
|
||||
const tokens = generateNgrams('apple')
|
||||
const expected = ['a', 'p', 'l', 'e', 'ap', 'pp', 'pl', 'le', 'app', 'ppl', 'ple']
|
||||
expect(tokens.sort()).toEqual(expected.sort())
|
||||
})
|
||||
|
||||
it('should handle multiple words and separators as single stream', () => {
|
||||
const tokens = generateNgrams('foo-bar')
|
||||
// f, o, o, -, b, a, r
|
||||
// fo, oo, o-, -b, ba, ar
|
||||
// foo, oo-, o-b, -ba, bar
|
||||
const expected = [
|
||||
'f',
|
||||
'o',
|
||||
'-',
|
||||
'b',
|
||||
'a',
|
||||
'r',
|
||||
'fo',
|
||||
'oo',
|
||||
'o-',
|
||||
'-b',
|
||||
'ba',
|
||||
'ar',
|
||||
'foo',
|
||||
'oo-',
|
||||
'o-b',
|
||||
'-ba',
|
||||
'bar',
|
||||
]
|
||||
expect(tokens.sort()).toEqual(expected.sort())
|
||||
})
|
||||
|
||||
it('should handle CJK characters correctly', () => {
|
||||
const tokens = generateNgrams('北京大学')
|
||||
// 北, 京, 大, 学
|
||||
// 北京, 京大, 大学
|
||||
// 北京大, 京大学
|
||||
const expected = ['北', '京', '大', '学', '北京', '京大', '大学', '北京大', '京大学']
|
||||
expect(tokens.sort()).toEqual(expected.sort())
|
||||
})
|
||||
|
||||
it('should be case-insensitive', () => {
|
||||
const tokens = generateNgrams('Apple')
|
||||
expect(tokens).toEqual(generateNgrams('apple'))
|
||||
})
|
||||
|
||||
it('should NOT ignore non-alphanumeric characters', () => {
|
||||
const tokens = generateNgrams('apple!!!')
|
||||
expect(tokens).toContain('e!!')
|
||||
expect(tokens).toContain('!!!')
|
||||
})
|
||||
|
||||
it('should return empty array for empty input', () => {
|
||||
expect(generateNgrams('')).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Generates 1-gram, 2-gram, and 3-gram tokens for a given text.
|
||||
* Used for optimizing substring searches (especially for CJK characters).
|
||||
*
|
||||
* Examples:
|
||||
* "apple" -> a, p, l, e, ap, pp, pl, le, app, ppl, ple
|
||||
* "foo-bar" -> f, o, -, b, a, r, fo, oo, o-, -b, ba, ar, foo, oo-, o-b, -ba, bar
|
||||
*/
|
||||
export function generateNgrams(text: string): string[] {
|
||||
if (!text) return []
|
||||
|
||||
const normalized = text.toLowerCase()
|
||||
const tokens = new Set<string>()
|
||||
const chars = Array.from(normalized) // Unicode-aware character splitting
|
||||
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
// 1-gram
|
||||
tokens.add(chars[i])
|
||||
|
||||
// 2-gram
|
||||
if (i + 1 < chars.length) {
|
||||
tokens.add(chars[i] + chars[i + 1])
|
||||
}
|
||||
|
||||
// 3-gram
|
||||
if (i + 2 < chars.length) {
|
||||
tokens.add(chars[i] + chars[i + 1] + chars[i + 2])
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(tokens)
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates only the longest possible n-grams for a search query.
|
||||
* If the word is 3+ chars, only return 3-grams.
|
||||
* If 2 chars, return 2-grams.
|
||||
* If 1 char, return 1-grams.
|
||||
*
|
||||
* This significantly improves search performance by reducing GIN index intersection overhead.
|
||||
*/
|
||||
export function generateSearchNgrams(text: string): string[] {
|
||||
if (!text) return []
|
||||
|
||||
const normalized = text.toLowerCase()
|
||||
const tokens = new Set<string>()
|
||||
const chars = Array.from(normalized)
|
||||
const len = chars.length
|
||||
|
||||
if (len >= 3) {
|
||||
for (let i = 0; i <= len - 3; i++) {
|
||||
tokens.add(chars[i] + chars[i + 1] + chars[i + 2])
|
||||
}
|
||||
} else if (len === 2) {
|
||||
tokens.add(chars[0] + chars[1])
|
||||
} else if (len === 1) {
|
||||
tokens.add(chars[0])
|
||||
}
|
||||
|
||||
return Array.from(tokens)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { PostgreSqlContainer } from '@testcontainers/postgresql'
|
||||
import { exec } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import { Wait } from 'testcontainers'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
let dbContainer: import('@testcontainers/postgresql').StartedPostgreSqlContainer
|
||||
|
||||
export async function globalTestSetup() {
|
||||
console.log('Starting Testcontainers for global setup...')
|
||||
dbContainer = await new PostgreSqlContainer('pgvector/pgvector:pg18')
|
||||
.withWaitStrategy(
|
||||
// casting to any due to testcontainers wait strategy type mismatch
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
Wait.forLogMessage('database system is ready to accept connections', 1) as any,
|
||||
)
|
||||
.start()
|
||||
|
||||
const databaseUrl = dbContainer.getConnectionUri()
|
||||
console.log('Database started at:', databaseUrl)
|
||||
|
||||
process.env.DATABASE_URL = databaseUrl
|
||||
|
||||
console.log('Applying Prisma Migrations...')
|
||||
await execAsync('bun run prisma migrate deploy', {
|
||||
env: {
|
||||
...process.env,
|
||||
DATABASE_URL: databaseUrl,
|
||||
},
|
||||
})
|
||||
console.log('Prisma Migrations completed.')
|
||||
}
|
||||
|
||||
export async function setup() {
|
||||
await globalTestSetup()
|
||||
}
|
||||
|
||||
export async function teardown() {
|
||||
await dbContainer?.stop()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pnpm-lock.yaml
|
||||
src/api/api.ts
|
||||
src/routeTree.gen.ts
|
||||
@@ -0,0 +1,29 @@
|
||||
import { hc } from 'hono/client'
|
||||
import type { AppType } from '@shumai/api'
|
||||
import { useAuthStore } from '@/ui/stores/auth'
|
||||
|
||||
const customFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const response = await fetch(input, init)
|
||||
|
||||
if (response.status === 401) {
|
||||
const url = input.toString()
|
||||
// Don't redirect if we are already on login page, it's an auth request, or we are on a public share page
|
||||
if (
|
||||
!window.location.pathname.includes('/login') &&
|
||||
!window.location.pathname.startsWith('/share/') &&
|
||||
!url.includes('/api/authn')
|
||||
) {
|
||||
useAuthStore.getState().clearAuth()
|
||||
window.location.href = '/login'
|
||||
}
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
export const client = hc<AppType>('/', {
|
||||
fetch: customFetch,
|
||||
init: {
|
||||
credentials: 'include',
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,294 @@
|
||||
import type { AncestorFolder } from '@shumai/dtos'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSeparator,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import {
|
||||
DockToLeft,
|
||||
DockToLeftFilled,
|
||||
DockToRight,
|
||||
DockToRightFilled,
|
||||
} from '@/ui/components/ui/icons'
|
||||
import { Link, useNavigate } from '@tanstack/react-router'
|
||||
import { ChevronDown, LayoutGrid, List, History, Check, FileIcon } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
|
||||
interface BreadcrumbNavProps {
|
||||
teamId: string
|
||||
projectId: string
|
||||
projectName: string
|
||||
ancestorFolders: AncestorFolder[]
|
||||
currentAsset: {
|
||||
name?: string
|
||||
type: 'file' | 'folder'
|
||||
version?: number
|
||||
}
|
||||
isRootFolder: boolean
|
||||
displayStyle?: 'card' | 'list'
|
||||
onDisplayStyleChange?: (style: 'card' | 'list') => void
|
||||
isLeftSidebarCollapsed?: boolean
|
||||
onLeftSidebarToggle?: () => void
|
||||
isRightSidebarCollapsed: boolean
|
||||
onRightSidebarToggle: () => void
|
||||
isPublic?: boolean
|
||||
shareId?: string
|
||||
onFolderClick?: (folderId: string) => void
|
||||
fileId?: string
|
||||
versions?: Array<{
|
||||
id: string
|
||||
version: number
|
||||
name?: string | null
|
||||
previewUrl?: string | null
|
||||
creator?: { id: string; name: string | null } | null
|
||||
}>
|
||||
}
|
||||
|
||||
export function BreadcrumbNav({
|
||||
teamId,
|
||||
projectId,
|
||||
projectName,
|
||||
ancestorFolders,
|
||||
currentAsset,
|
||||
isRootFolder,
|
||||
displayStyle,
|
||||
onDisplayStyleChange,
|
||||
isLeftSidebarCollapsed,
|
||||
onLeftSidebarToggle,
|
||||
isRightSidebarCollapsed,
|
||||
onRightSidebarToggle,
|
||||
isPublic = false,
|
||||
onFolderClick,
|
||||
fileId,
|
||||
versions,
|
||||
}: BreadcrumbNavProps) {
|
||||
const navigate = useNavigate()
|
||||
|
||||
const handleVersionClick = (versionId: string) => {
|
||||
if (!projectId || !fileId) return
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId },
|
||||
search: (prev: Record<string, unknown>) => ({ ...prev, version: versionId }),
|
||||
})
|
||||
}
|
||||
|
||||
const breadcrumbs: { name: string; path?: string; id?: string; isMuted?: boolean }[] = isPublic
|
||||
? [
|
||||
{
|
||||
name: projectName,
|
||||
id: 'root', // Special ID for share root
|
||||
},
|
||||
...ancestorFolders
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((folder) => ({
|
||||
name: folder.name || '',
|
||||
id: folder.id,
|
||||
})),
|
||||
]
|
||||
: [
|
||||
{ name: 'All Projects', path: `/teams/${teamId}`, isMuted: true },
|
||||
{ name: projectName, path: `/projects/${projectId}` },
|
||||
...ancestorFolders
|
||||
.slice()
|
||||
.reverse()
|
||||
.map((folder) => ({
|
||||
name: folder.name || '',
|
||||
path: `/projects/${projectId}/folders/${folder.id}`,
|
||||
})),
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="flex h-14 flex-wrap items-center justify-between gap-2 border-b border-border bg-card px-4 py-2">
|
||||
<div className="flex min-w-0 flex-shrink items-center gap-1">
|
||||
{breadcrumbs.map((breadcrumb, index) => (
|
||||
<div key={index} className="flex items-center gap-1">
|
||||
{index > 0 && <span className="text-muted-foreground">/</span>}
|
||||
{breadcrumb.path ? (
|
||||
<Link
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
to={breadcrumb.path as any}
|
||||
className={cn(
|
||||
'truncate rounded px-2 py-1 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground',
|
||||
breadcrumb.isMuted ? 'text-muted-foreground' : 'text-foreground',
|
||||
)}
|
||||
>
|
||||
{breadcrumb.name}
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => breadcrumb.id && onFolderClick?.(breadcrumb.id)}
|
||||
className="truncate rounded px-2 py-1 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground text-foreground"
|
||||
>
|
||||
{breadcrumb.name}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{!isRootFolder && (
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-muted-foreground">/</span>
|
||||
{currentAsset.type === 'folder' ? (
|
||||
<span className="truncate rounded px-2 py-1 text-sm font-medium text-foreground">
|
||||
{currentAsset.name}
|
||||
</span>
|
||||
) : (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger className="flex items-center gap-1 truncate rounded px-2 py-1 text-sm font-medium text-foreground transition-colors hover:bg-accent hover:text-accent-foreground">
|
||||
<span>{currentAsset.name}</span>
|
||||
{currentAsset.version !== undefined && (
|
||||
<Badge variant="outline" className="px-1 py-0 text-xs">
|
||||
v{currentAsset.version}
|
||||
</Badge>
|
||||
)}
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56">
|
||||
<DropdownMenuItem onClick={() => console.log('Download')}>
|
||||
Download
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => console.log('Rename')}>Rename</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => console.log('Delete')}>Delete</DropdownMenuItem>
|
||||
|
||||
{versions && versions.length > 0 && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger className="flex items-center gap-2">
|
||||
<History className="h-4 w-4" />
|
||||
<span>Versions</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuSubContent className="w-80 p-1">
|
||||
<div className="flex flex-col gap-1 max-h-96 overflow-y-auto">
|
||||
{versions.map((v) => {
|
||||
const isActive = currentAsset.version === v.version
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={v.id}
|
||||
onClick={() => handleVersionClick(v.id)}
|
||||
className="flex items-center gap-3 py-2 px-3 rounded-md cursor-pointer focus:bg-accent focus:text-accent-foreground"
|
||||
>
|
||||
<div className="flex-shrink-0 flex items-center justify-center bg-muted dark:bg-muted-foreground/20 text-muted-foreground dark:text-muted-foreground rounded-full px-2 py-0.5 text-xs font-semibold select-none min-w-[2rem]">
|
||||
v{v.version}
|
||||
</div>
|
||||
|
||||
<div className="h-10 w-16 flex-shrink-0 overflow-hidden rounded-md border border-border bg-muted flex items-center justify-center">
|
||||
{v.previewUrl ? (
|
||||
<img
|
||||
src={v.previewUrl}
|
||||
alt={v.name || undefined}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<FileIcon className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col flex-1 min-w-0 text-left">
|
||||
<span className="truncate text-sm font-semibold text-foreground">
|
||||
{v.name}
|
||||
</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{v.creator?.name || 'Unknown'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{isActive && (
|
||||
<Check className="h-4 w-4 text-primary ml-auto flex-shrink-0" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<DropdownMenuSeparator />
|
||||
<div className="p-1">
|
||||
<button
|
||||
className="w-full text-center text-xs font-medium py-2 px-3 rounded-md bg-muted/80 hover:bg-muted text-foreground transition-colors"
|
||||
onClick={() => console.log('Manage versions')}
|
||||
>
|
||||
Manage versions...
|
||||
</button>
|
||||
</div>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenuSub>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-shrink-0 items-center gap-1 rounded-md border border-border bg-background p-1">
|
||||
{/* Left Sidebar Toggle */}
|
||||
{!isPublic && onLeftSidebarToggle && (
|
||||
<button
|
||||
onClick={onLeftSidebarToggle}
|
||||
className="rounded p-1.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
|
||||
title={isLeftSidebarCollapsed ? 'Show Left Sidebar' : 'Hide Left Sidebar'}
|
||||
>
|
||||
{isLeftSidebarCollapsed ? (
|
||||
<DockToLeft className="h-4 w-4" />
|
||||
) : (
|
||||
<DockToLeftFilled className="h-4 w-4 fill-primary stroke-0" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Card View */}
|
||||
{!isPublic && displayStyle && onDisplayStyleChange && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => onDisplayStyleChange('card')}
|
||||
className={`rounded p-1.5 transition-colors ${
|
||||
displayStyle === 'card'
|
||||
? 'bg-accent text-accent-foreground'
|
||||
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
|
||||
}`}
|
||||
title="Card View"
|
||||
>
|
||||
<LayoutGrid className="h-4 w-4" />
|
||||
</button>
|
||||
|
||||
{/* List View */}
|
||||
<button
|
||||
onClick={() => onDisplayStyleChange('list')}
|
||||
className={`rounded p-1.5 transition-colors ${
|
||||
displayStyle === 'list'
|
||||
? 'bg-accent text-accent-foreground'
|
||||
: 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
|
||||
}`}
|
||||
title="List View"
|
||||
>
|
||||
<List className="h-4 w-4" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Right Sidebar Toggle */}
|
||||
<button
|
||||
onClick={onRightSidebarToggle}
|
||||
className="rounded p-1.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
|
||||
title={isRightSidebarCollapsed ? 'Show Right Sidebar' : 'Hide Right Sidebar'}
|
||||
>
|
||||
{isRightSidebarCollapsed ? (
|
||||
<DockToRight className="h-4 w-4" />
|
||||
) : (
|
||||
<DockToRightFilled className="h-4 w-4 fill-primary stroke-0" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,577 @@
|
||||
import type { AttachmentInfo, CommentInfo } from '@shumai/dtos'
|
||||
import type { UserInfo } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Separator } from '@/ui/components/ui/separator'
|
||||
import { formatTimeAgo } from '@/ui/lib/time'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Download, File, Terminal } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import Markdown from 'react-markdown'
|
||||
import { Avatar, AvatarFallback } from '../ui/avatar'
|
||||
import { DrawAnnotation } from '../ui/icons'
|
||||
import { Skeleton } from '../ui/skeleton'
|
||||
import { formatTimestamp } from '../viewers/utils'
|
||||
|
||||
interface MessageCardProps {
|
||||
teamId?: string
|
||||
message: CommentInfo
|
||||
isReply?: boolean
|
||||
hasReplies?: boolean
|
||||
isLastReply?: boolean
|
||||
getUser: (id: string) => UserInfo
|
||||
onReply: (message: CommentInfo) => void
|
||||
onViewAttachment: (attachment: AttachmentInfo) => void
|
||||
isSelected?: boolean
|
||||
onSelect?: () => void
|
||||
frameRate?: number
|
||||
rootParentId?: string
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
const AI_PLACEHOLDERS: Record<string, string> = {
|
||||
__CHAT__: 'Generating...',
|
||||
__AUTOFILL__: 'Autofilling metadata...',
|
||||
__EMBEDDING__: 'Generating embeddings...',
|
||||
__RUNNING__: 'Generating...',
|
||||
}
|
||||
|
||||
export const MessageCard: React.FC<MessageCardProps> = ({
|
||||
teamId,
|
||||
message: initialMessage,
|
||||
isReply,
|
||||
hasReplies,
|
||||
isLastReply,
|
||||
getUser,
|
||||
onReply,
|
||||
onViewAttachment,
|
||||
isSelected,
|
||||
onSelect,
|
||||
frameRate,
|
||||
}) => {
|
||||
const message = initialMessage
|
||||
const hasDrawInfo =
|
||||
!!message.annotations && Array.isArray(message.annotations) && message.annotations.length > 0
|
||||
const creator = message.creator
|
||||
const showSkeleton =
|
||||
!!message.sessionId && !!message.message && message.message in AI_PLACEHOLDERS
|
||||
const loadingText = (message.message && AI_PLACEHOLDERS[message.message]) || 'Generating...'
|
||||
|
||||
const [isLogsOpen, setIsLogsOpen] = React.useState(false)
|
||||
|
||||
const { data: me } = useQuery({
|
||||
queryKey: ['teams', teamId, 'me'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].me.$get({
|
||||
param: { teamId: teamId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch current member info')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId,
|
||||
staleTime: 300000,
|
||||
})
|
||||
|
||||
const isAdmin = me?.role === 'owner'
|
||||
|
||||
const { data: logs, isLoading: isLogsLoading } = useQuery({
|
||||
queryKey: ['agent-sessions', message.sessionId, 'entries'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api['agent-sessions'][':sessionId'].entries.$get({
|
||||
param: { sessionId: message.sessionId! },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch session logs')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: isLogsOpen && !!message.sessionId,
|
||||
})
|
||||
|
||||
const renderFormattedMessage = (text: string) => {
|
||||
const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g)
|
||||
return parts.map((part, index) => {
|
||||
if (part.match(/^<@[a-zA-Z0-9_-]+>$/)) {
|
||||
const userId = part.slice(2, -1)
|
||||
const mentionedUser = message.mentions?.find((m) => m.id === userId) || getUser(userId)
|
||||
return (
|
||||
<span key={index} className="text-primary font-medium hover:underline cursor-pointer">
|
||||
@{mentionedUser?.name || 'Unknown'}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return <span key={index}>{part}</span>
|
||||
})
|
||||
}
|
||||
|
||||
const preprocessMarkdown = (text: string): string => {
|
||||
return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:')
|
||||
}
|
||||
|
||||
const handleReply = () => {
|
||||
onReply(message)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={onSelect}
|
||||
className={`relative flex gap-4 ${isReply ? 'mt-[-1px]' : 'mt-3'} mr-3 group p-3 py-4 border transition-all duration-200 cursor-pointer ${
|
||||
isReply
|
||||
? isLastReply
|
||||
? 'rounded-b-xl rounded-t-none'
|
||||
: 'rounded-none'
|
||||
: hasReplies
|
||||
? 'rounded-t-xl rounded-b-none'
|
||||
: 'rounded-xl'
|
||||
} ${
|
||||
isSelected
|
||||
? 'z-20 border-blue-500/40 dark:border-blue-400/40 bg-blue-500/10 dark:bg-blue-400/10 shadow-sm'
|
||||
: 'z-10 border-transparent bg-foreground/2 dark:bg-foreground/10 hover:bg-foreground/4 dark:hover:bg-foreground/15'
|
||||
}`}
|
||||
>
|
||||
{/* Left Column: Avatar & Thread Lines */}
|
||||
<div className="flex flex-col items-center shrink-0 w-8 relative">
|
||||
{/* Thread line above avatar (for replies) */}
|
||||
{isReply && (
|
||||
<div className="absolute top-[-1rem] h-8 w-0.5 bg-foreground/10 left-1/2 -translate-x-1/2 z-0" />
|
||||
)}
|
||||
|
||||
{/* Thread line under avatar (for parent comments with replies, or intermediate replies) */}
|
||||
{((hasReplies && !isReply) || (isReply && !isLastReply)) && (
|
||||
<div className="absolute top-4 bottom-[-1rem] w-0.5 bg-foreground/10 left-1/2 -translate-x-1/2 z-0" />
|
||||
)}
|
||||
|
||||
<Avatar className="z-10 relative">
|
||||
<AvatarFallback className="bg-rose-400 text-black">
|
||||
{creator?.name?.[0]?.toUpperCase() || 'U'}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="font-semibold text-sm">{creator?.name || 'Unknown'}</span>
|
||||
<span className="text-xs text-gray-400">
|
||||
{new Date(message.createdAt!).toLocaleTimeString([], {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flow-root mt-1">
|
||||
{message.second !== null && message.second !== undefined && frameRate && (
|
||||
<div className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-2.5 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-mono font-bold flex items-center gap-1">
|
||||
{formatTimestamp(message.second, frameRate)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hasDrawInfo && (
|
||||
<div
|
||||
className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-1 py-1 mt-[2px] mr-2 rounded-sm text-xs leading-none font-bold flex items-center gap-1"
|
||||
title="Contains drawing annotations"
|
||||
>
|
||||
<DrawAnnotation className="w-3.5 h-3.5" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showSkeleton ? (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
<span className="text-xs text-muted-foreground animate-pulse">{loadingText}</span>
|
||||
</div>
|
||||
) : message.sessionId ? (
|
||||
<div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words">
|
||||
<Markdown>{preprocessMarkdown(message.message!)}</Markdown>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm leading-relaxed whitespace-pre-wrap break-words text-wrap break-all">
|
||||
{renderFormattedMessage(message.message!)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Attachments */}
|
||||
{message.attachments && message.attachments.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 mt-3">
|
||||
{message.attachments.map((att) => {
|
||||
const isImage = att.mediaType?.startsWith('image/')
|
||||
const name = att.url?.split('/').pop()?.split('?')[0] || 'file'
|
||||
return (
|
||||
<div
|
||||
key={att.id}
|
||||
className="relative group rounded-lg overflow-hidden border bg-white shadow-sm hover:shadow-md transition-shadow w-48 h-32"
|
||||
onClick={() => isImage && onViewAttachment(att)}
|
||||
>
|
||||
{isImage ? (
|
||||
<img
|
||||
src={att.url}
|
||||
alt={name}
|
||||
className="w-full h-full object-cover cursor-pointer"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full bg-gray-100 flex flex-col items-center justify-center p-2 text-center">
|
||||
<File className="w-8 h-8 text-gray-500 mb-2" />
|
||||
<span className="text-xs font-medium text-gray-700 break-all line-clamp-2">
|
||||
{name}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<a
|
||||
href={att.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
download={name}
|
||||
className="absolute right-2 bottom-2 bg-black/60 text-white hover:bg-black/80 p-1.5 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
</a>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Agent Footer */}
|
||||
{message.sessionId && (
|
||||
<div className="mt-3 pt-2 border-t border-foreground/5 flex items-center justify-between text-xs text-muted-foreground/60">
|
||||
<span className="flex items-center gap-1.5 font-medium text-muted-foreground/80">
|
||||
Created by Agent
|
||||
</span>
|
||||
{isAdmin && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
onClick={() => setIsLogsOpen(true)}
|
||||
className="cursor-pointer border-violet-500/20 text-violet-600 dark:text-violet-400 hover:bg-violet-500/10 hover:text-violet-700 hover:border-violet-500/30 font-semibold"
|
||||
>
|
||||
Logs
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="mt-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center gap-4">
|
||||
<button
|
||||
onClick={handleReply}
|
||||
className="text-xs font-medium text-gray-500 hover:text-blue-600 flex items-center gap-1 cursor-pointer"
|
||||
>
|
||||
Reply
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Logs Dialog */}
|
||||
<Dialog open={isLogsOpen} onOpenChange={setIsLogsOpen}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[80vh] flex flex-col p-6 overflow-hidden bg-background/95 backdrop-blur-md border border-foreground/15 shadow-2xl">
|
||||
<DialogHeader className="pb-4 border-b border-foreground/15">
|
||||
<DialogTitle className="flex items-center gap-2 text-xl font-bold">
|
||||
<Terminal className="w-5 h-5 text-violet-500" />
|
||||
Agent Session Logs
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Step-by-step execution trace of the agent's background tasks and tool calls.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto pr-1 py-4 space-y-4 min-h-0 select-text">
|
||||
{isLogsLoading ? (
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-4">
|
||||
<Skeleton className="h-5 w-5 rounded-full shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-1/4" />
|
||||
<Skeleton className="h-20 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
<Skeleton className="h-5 w-5 rounded-full shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-1/4" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : logs && logs.length > 0 ? (
|
||||
<div className="flex flex-col">
|
||||
{logs.map((entry) => {
|
||||
const piEntry = entry.entry as Record<string, unknown> | null
|
||||
const timestampStr =
|
||||
piEntry?.timestamp || (entry as Record<string, unknown>).timestamp
|
||||
let timestamp = ''
|
||||
if (typeof timestampStr === 'string' || typeof timestampStr === 'number') {
|
||||
const dateObj = new Date(timestampStr)
|
||||
if (!isNaN(dateObj.getTime())) {
|
||||
timestamp = formatTimeAgo(dateObj.toISOString())
|
||||
}
|
||||
}
|
||||
|
||||
if (piEntry && typeof piEntry === 'object') {
|
||||
if (piEntry.type === 'message' && piEntry.message) {
|
||||
const msg = piEntry.message as Record<string, unknown>
|
||||
let badgeColor =
|
||||
'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200'
|
||||
let roleName: string = String(msg.role || '')
|
||||
|
||||
if (msg.role === 'user') {
|
||||
badgeColor =
|
||||
'bg-slate-100 text-slate-800 dark:bg-slate-900/30 dark:text-slate-300'
|
||||
roleName = 'User'
|
||||
} else if (msg.role === 'assistant') {
|
||||
badgeColor =
|
||||
'bg-violet-100 text-violet-800 dark:bg-violet-900/30 dark:text-violet-300'
|
||||
roleName = 'Agent'
|
||||
} else if (msg.role === 'toolResult') {
|
||||
badgeColor = msg.isError
|
||||
? 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300'
|
||||
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300'
|
||||
roleName = `Tool Result: ${String(msg.toolName || 'Unknown')}`
|
||||
} else if (msg.role === 'thought') {
|
||||
badgeColor =
|
||||
'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300'
|
||||
roleName = 'Thinking'
|
||||
}
|
||||
|
||||
const renderToolCallArguments = (args: unknown) => {
|
||||
let parsedArgs: unknown = args
|
||||
if (typeof args === 'string') {
|
||||
try {
|
||||
parsedArgs = JSON.parse(args)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
parsedArgs &&
|
||||
typeof parsedArgs === 'object' &&
|
||||
!Array.isArray(parsedArgs)
|
||||
) {
|
||||
const obj = parsedArgs as Record<string, unknown>
|
||||
return (
|
||||
<div className="mt-1 space-y-1.5 pt-3">
|
||||
{Object.entries(obj).map(([key, value]) => {
|
||||
let valueStr = ''
|
||||
if (value && typeof value === 'object') {
|
||||
valueStr = JSON.stringify(value, null, 2)
|
||||
} else {
|
||||
valueStr = String(value)
|
||||
}
|
||||
return (
|
||||
<div key={key} className="text-xs leading-relaxed break-words">
|
||||
<span className="font-semibold text-violet-600 dark:text-violet-400">
|
||||
{key}:
|
||||
</span>{' '}
|
||||
<span className="text-foreground/90 font-mono whitespace-pre-wrap">
|
||||
{valueStr}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-xs font-mono whitespace-pre-wrap">
|
||||
{String(args)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const renderMessageContent = () => {
|
||||
const content = msg.content
|
||||
if (!content) return null
|
||||
|
||||
if (typeof content === 'string') {
|
||||
if (!content.trim()) return null
|
||||
return (
|
||||
<div className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words">
|
||||
<Markdown>{preprocessMarkdown(content)}</Markdown>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
const renderedBlocks: React.ReactNode[] = []
|
||||
|
||||
content.forEach((item, idx) => {
|
||||
if (!item) return
|
||||
|
||||
if (typeof item === 'string') {
|
||||
if (!item.trim()) return
|
||||
renderedBlocks.push(
|
||||
<div
|
||||
key={`str-${idx}`}
|
||||
className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words"
|
||||
>
|
||||
<Markdown>{preprocessMarkdown(item)}</Markdown>
|
||||
</div>,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof item === 'object') {
|
||||
const itemObj = item as Record<string, unknown>
|
||||
const type = itemObj.type
|
||||
if (type === 'text') {
|
||||
const text = itemObj.text
|
||||
if (typeof text !== 'string' || !text.trim()) return
|
||||
renderedBlocks.push(
|
||||
<div
|
||||
key={`txt-${idx}`}
|
||||
className="text-xs text-foreground/80 dark:text-foreground/95 leading-relaxed prose prose-sm dark:prose-invert max-w-none break-words"
|
||||
>
|
||||
<Markdown>{preprocessMarkdown(text)}</Markdown>
|
||||
</div>,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (type === 'toolCall') {
|
||||
const toolName = String(
|
||||
itemObj.name || itemObj.toolName || 'Unknown',
|
||||
)
|
||||
const toolArgs = itemObj.arguments || itemObj.args
|
||||
renderedBlocks.push(
|
||||
<div key={`tool-${idx}`} className="text-xs space-y-2 py-1">
|
||||
<div className="font-semibold text-violet-600 dark:text-violet-400 flex items-center gap-1.5">
|
||||
Calling Tool:{' '}
|
||||
<span className="font-mono bg-violet-500/10 px-1 py-0.5 rounded text-[11px]">
|
||||
{toolName}
|
||||
</span>
|
||||
</div>
|
||||
{!!toolArgs && (
|
||||
<div className="space-y-1 pt-3">
|
||||
<div className="text-[10px] text-muted-foreground/60 uppercase font-bold tracking-wider">
|
||||
Arguments
|
||||
</div>
|
||||
{renderToolCallArguments(toolArgs)}
|
||||
</div>
|
||||
)}
|
||||
</div>,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (type === 'image') {
|
||||
renderedBlocks.push(
|
||||
<div
|
||||
key={`img-${idx}`}
|
||||
className="text-xs text-muted-foreground italic flex items-center gap-1.5 py-1"
|
||||
>
|
||||
[Image Object]
|
||||
</div>,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Fallback for other object types
|
||||
const stringified = JSON.stringify(item, null, 2)
|
||||
if (stringified === '{}') return
|
||||
renderedBlocks.push(
|
||||
<pre
|
||||
key={`other-${idx}`}
|
||||
className="text-xs text-foreground/80 font-mono whitespace-pre-wrap break-words bg-muted/20 p-2 rounded"
|
||||
>
|
||||
{stringified}
|
||||
</pre>,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
if (renderedBlocks.length === 0) return null
|
||||
|
||||
return (
|
||||
<div className="space-y-3 w-full">
|
||||
{renderedBlocks.map((block, index) => (
|
||||
<React.Fragment key={index}>
|
||||
{index > 0 && <Separator className="my-3 opacity-50" />}
|
||||
{block}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={entry.id} className="relative pl-6 pb-6 last:pb-0">
|
||||
{/* Timeline Line */}
|
||||
<div className="absolute left-[9px] top-2 bottom-0 w-0.5 bg-foreground/10 last:hidden" />
|
||||
|
||||
{/* Timeline Node */}
|
||||
<div
|
||||
className={`absolute left-0 top-1.5 h-5 w-5 rounded-full border-4 border-background flex items-center justify-center ${
|
||||
msg.role === 'user'
|
||||
? 'bg-slate-500'
|
||||
: msg.role === 'assistant'
|
||||
? 'bg-violet-500'
|
||||
: msg.role === 'toolResult'
|
||||
? msg.isError
|
||||
? 'bg-red-500'
|
||||
: 'bg-emerald-500'
|
||||
: 'bg-amber-500'
|
||||
}`}
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-1.5 bg-muted/30 dark:bg-muted/10 p-3 rounded-lg border border-foreground/5 backdrop-blur-xs w-full">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span
|
||||
className={`text-[10px] px-2 py-0.5 rounded-full font-semibold uppercase tracking-wider ${badgeColor}`}
|
||||
>
|
||||
{roleName}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground/60">
|
||||
{timestamp}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{renderMessageContent()}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for non-message entries or arbitrary entries
|
||||
return (
|
||||
<div key={entry.id} className="relative pl-6 pb-6 last:pb-0">
|
||||
<div className="absolute left-[9px] top-2 bottom-0 w-0.5 bg-foreground/10 last:hidden" />
|
||||
<div className="absolute left-0 top-1.5 h-5 w-5 rounded-full border-4 border-background bg-gray-400" />
|
||||
<div className="bg-muted/30 p-3 rounded-lg border border-foreground/5">
|
||||
<div className="text-[10px] text-muted-foreground/60">{timestamp}</div>
|
||||
<pre className="text-xs text-foreground/80 font-mono whitespace-pre-wrap break-words">
|
||||
{JSON.stringify(entry.entry, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center text-muted-foreground">
|
||||
<Terminal className="w-8 h-8 text-muted-foreground/40 mb-2 animate-pulse" />
|
||||
<p className="text-sm font-medium">No logs found for this session.</p>
|
||||
<p className="text-xs text-muted-foreground/60 mt-1">
|
||||
The session might have been initialized but has not produced any entries yet.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,784 @@
|
||||
import type { CommentInfo, PostAttachmentRequest, PostAttachmentResponse } from '@shumai/dtos'
|
||||
import type { BotInfo } from '@shumai/dtos'
|
||||
import type { UserInfo } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import {
|
||||
ArrowLeft,
|
||||
ArrowUp,
|
||||
Brush,
|
||||
ChevronDown,
|
||||
Clock,
|
||||
FileIcon,
|
||||
Minus,
|
||||
Paperclip,
|
||||
Redo,
|
||||
Square,
|
||||
Undo,
|
||||
XIcon,
|
||||
} from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react'
|
||||
import { Button } from '../ui/button'
|
||||
import { DrawAnnotation } from '../ui/icons'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'
|
||||
import { ProgressCircle } from '../ui/progress-circle'
|
||||
import { formatTimestamp } from '../viewers/utils'
|
||||
|
||||
type UploadingFile = {
|
||||
id: string // A unique ID for the file, e.g., timestamp + name
|
||||
file: File
|
||||
progress: number
|
||||
attachmentId?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
interface ChatInputProps {
|
||||
projectId: string
|
||||
onSendMessage: (
|
||||
text: string,
|
||||
attachmentIds: string[],
|
||||
annotations?: Annotation[],
|
||||
replyToId?: string | null,
|
||||
second?: number | null,
|
||||
) => void
|
||||
replyingTo?: CommentInfo | null
|
||||
onCancelReply?: () => void
|
||||
users?: UserInfo[]
|
||||
bots?: BotInfo[]
|
||||
initialText?: string
|
||||
hideAnnotationControl?: boolean
|
||||
disableMentions?: boolean
|
||||
currentTime?: number
|
||||
frameRate?: number
|
||||
onTyping?: () => void
|
||||
}
|
||||
|
||||
const PREDEFINED_COLORS = [
|
||||
'#ef4444', // Red
|
||||
'#f97316', // Orange
|
||||
'#eab308', // Yellow
|
||||
'#22c55e', // Green
|
||||
'#3b82f6', // Blue
|
||||
'#a855f7', // Purple
|
||||
'#ec4899', // Pink
|
||||
'#000000', // Black
|
||||
'#ffffff', // White
|
||||
]
|
||||
|
||||
type MentionEntity = { type: 'user'; data: UserInfo } | { type: 'bot'; data: BotInfo }
|
||||
|
||||
export const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
|
||||
(
|
||||
{
|
||||
projectId,
|
||||
onSendMessage,
|
||||
replyingTo,
|
||||
onCancelReply,
|
||||
users = [],
|
||||
bots = [],
|
||||
initialText = '',
|
||||
hideAnnotationControl = false,
|
||||
disableMentions = false,
|
||||
currentTime,
|
||||
frameRate,
|
||||
onTyping,
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([])
|
||||
const [viewingFile, setViewingFile] = useState<File | null>(null)
|
||||
const [isTimestampEnabled, setIsTimestampEnabled] = useState(true)
|
||||
|
||||
// Annotation Store
|
||||
const {
|
||||
isDrawing,
|
||||
setIsDrawing,
|
||||
currentTool,
|
||||
setTool,
|
||||
currentColor,
|
||||
setColor,
|
||||
undo,
|
||||
redo,
|
||||
history,
|
||||
historyIndex,
|
||||
annotations,
|
||||
reset: resetAnnotations,
|
||||
} = useAnnotationStore()
|
||||
|
||||
const [showMentionList, setShowMentionList] = useState(false)
|
||||
const [mentionQuery, setMentionQuery] = useState('')
|
||||
const [highlightedIndex, setHighlightedIndex] = useState(0)
|
||||
const [collapsedSections, setCollapsedSections] = useState({ bots: false, users: false })
|
||||
const [hasContent, setHasContent] = useState(false)
|
||||
|
||||
const editorRef = useRef<HTMLDivElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const mentionRangeRef = useRef<Range | null>(null)
|
||||
|
||||
const { mutateAsync: uploadAttachment } = useMutation({
|
||||
mutationFn: async ({
|
||||
projectId,
|
||||
data,
|
||||
}: {
|
||||
projectId: string
|
||||
data: PostAttachmentRequest
|
||||
}) => {
|
||||
const res = await client.api.projects[':projectId'].attachments.$post({
|
||||
param: { projectId: projectId },
|
||||
json: data,
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to create attachment')
|
||||
return (await res.json()) as PostAttachmentResponse
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (initialText && editorRef.current) {
|
||||
editorRef.current.innerText = initialText
|
||||
setHasContent(!!initialText.trim())
|
||||
// Focus and move cursor to end
|
||||
editorRef.current.focus()
|
||||
const range = document.createRange()
|
||||
const sel = window.getSelection()
|
||||
range.selectNodeContents(editorRef.current)
|
||||
range.collapse(false)
|
||||
sel?.removeAllRanges()
|
||||
sel?.addRange(range)
|
||||
}
|
||||
}, [initialText])
|
||||
|
||||
// Focus editor when replyingTo becomes truthy
|
||||
useEffect(() => {
|
||||
if (replyingTo && editorRef.current) {
|
||||
editorRef.current.focus()
|
||||
// Focus and move cursor to end
|
||||
const range = document.createRange()
|
||||
const sel = window.getSelection()
|
||||
range.selectNodeContents(editorRef.current)
|
||||
range.collapse(false)
|
||||
sel?.removeAllRanges()
|
||||
sel?.addRange(range)
|
||||
}
|
||||
}, [replyingTo])
|
||||
|
||||
// Clean up drawing mode on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setIsDrawing(false)
|
||||
}
|
||||
}, [setIsDrawing])
|
||||
|
||||
const filteredAgents = [
|
||||
...users
|
||||
.filter(
|
||||
(u) => u.type === 'agent' && u.name?.toLowerCase().startsWith(mentionQuery.toLowerCase()),
|
||||
)
|
||||
.map((u) => ({ type: 'user' as const, data: u })),
|
||||
...bots
|
||||
.filter((b) => b.name?.toLowerCase().startsWith(mentionQuery.toLowerCase()))
|
||||
.map((b) => ({ type: 'bot' as const, data: b })),
|
||||
]
|
||||
|
||||
const filteredHumans = users
|
||||
.filter(
|
||||
(u) => u.type !== 'agent' && u.name?.toLowerCase().startsWith(mentionQuery.toLowerCase()),
|
||||
)
|
||||
.map((u) => ({ type: 'user' as const, data: u }))
|
||||
|
||||
const filteredEntities: MentionEntity[] = [
|
||||
...(collapsedSections.bots ? [] : filteredAgents),
|
||||
...(collapsedSections.users ? [] : filteredHumans),
|
||||
]
|
||||
|
||||
useEffect(() => {
|
||||
setHighlightedIndex(0)
|
||||
}, [mentionQuery, showMentionList, collapsedSections])
|
||||
|
||||
const handleInput = () => {
|
||||
if (!editorRef.current) return
|
||||
setHasContent(!!editorRef.current.innerText.trim())
|
||||
onTyping?.()
|
||||
|
||||
if (disableMentions) {
|
||||
setShowMentionList(false)
|
||||
mentionRangeRef.current = null
|
||||
return
|
||||
}
|
||||
|
||||
const sel = window.getSelection()
|
||||
if (!sel || sel.rangeCount === 0) return
|
||||
|
||||
const range = sel.getRangeAt(0)
|
||||
const node = range.startContainer
|
||||
const offset = range.startOffset
|
||||
|
||||
if (node.nodeType === Node.TEXT_NODE) {
|
||||
const textContent = node.textContent || ''
|
||||
const textBeforeCursor = textContent.slice(0, offset)
|
||||
const lastAtPos = textBeforeCursor.lastIndexOf('@')
|
||||
|
||||
if (lastAtPos !== -1) {
|
||||
const isStartOfLine = lastAtPos === 0
|
||||
const charBeforeAt = textBeforeCursor[lastAtPos - 1]
|
||||
const hasSpaceBefore = isStartOfLine || /\s/.test(charBeforeAt)
|
||||
|
||||
if (hasSpaceBefore) {
|
||||
const query = textBeforeCursor.slice(lastAtPos + 1)
|
||||
if (!/\s/.test(query)) {
|
||||
setMentionQuery(query)
|
||||
setShowMentionList(true)
|
||||
|
||||
// Save the range for later insertion
|
||||
const mentionRange = document.createRange()
|
||||
mentionRange.setStart(node, lastAtPos)
|
||||
mentionRange.setEnd(node, offset)
|
||||
mentionRangeRef.current = mentionRange
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
setShowMentionList(false)
|
||||
mentionRangeRef.current = null
|
||||
}
|
||||
|
||||
const handleSelectEntity = (entity: MentionEntity) => {
|
||||
if (!mentionRangeRef.current || !editorRef.current) return
|
||||
|
||||
const range = mentionRangeRef.current
|
||||
range.deleteContents()
|
||||
|
||||
const mentionNode = document.createElement('span')
|
||||
mentionNode.contentEditable = 'false'
|
||||
mentionNode.dataset.type = 'mention'
|
||||
mentionNode.dataset.id = entity.data.id
|
||||
mentionNode.className =
|
||||
'inline-block bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-sm font-medium align-middle select-none mx-0.5'
|
||||
mentionNode.innerText = `@${entity.data.name}`
|
||||
|
||||
range.insertNode(mentionNode)
|
||||
|
||||
// Insert a space after the mention
|
||||
const spaceNode = document.createTextNode('\u00A0')
|
||||
mentionNode.after(spaceNode)
|
||||
|
||||
// Move cursor after the space
|
||||
const newRange = document.createRange()
|
||||
const sel = window.getSelection()
|
||||
newRange.setStartAfter(spaceNode)
|
||||
newRange.collapse(true)
|
||||
sel?.removeAllRanges()
|
||||
sel?.addRange(newRange)
|
||||
|
||||
setShowMentionList(false)
|
||||
mentionRangeRef.current = null
|
||||
setHasContent(true)
|
||||
editorRef.current.focus()
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (showMentionList && filteredEntities.length > 0) {
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
setHighlightedIndex((prev) => (prev > 0 ? prev - 1 : filteredEntities.length - 1))
|
||||
return
|
||||
}
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
setHighlightedIndex((prev) => (prev < filteredEntities.length - 1 ? prev + 1 : 0))
|
||||
return
|
||||
}
|
||||
if (e.key === 'Enter' || e.key === 'Tab') {
|
||||
e.preventDefault()
|
||||
handleSelectEntity(filteredEntities[highlightedIndex])
|
||||
return
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
setShowMentionList(false)
|
||||
return
|
||||
}
|
||||
}
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
handleSend()
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileSelect = useCallback(
|
||||
async (e: ChangeEvent<HTMLInputElement>) => {
|
||||
if (!e.target.files) return
|
||||
const newFiles = Array.from(e.target.files)
|
||||
|
||||
for (const file of newFiles) {
|
||||
const tempId = `${Date.now()}-${file.name}`
|
||||
const newUploadingFile: UploadingFile = {
|
||||
id: tempId,
|
||||
file,
|
||||
progress: 0,
|
||||
}
|
||||
setUploadingFiles((prev) => [...prev, newUploadingFile])
|
||||
|
||||
try {
|
||||
const data: PostAttachmentResponse = await uploadAttachment({
|
||||
projectId,
|
||||
data: {
|
||||
fileName: file.name,
|
||||
contentType: file.type,
|
||||
size: file.size,
|
||||
},
|
||||
})
|
||||
|
||||
if (data.uploadUrl && data.id) {
|
||||
await fetch(data.uploadUrl, {
|
||||
method: 'PUT',
|
||||
body: file,
|
||||
headers: {
|
||||
'Content-Type': file.type,
|
||||
},
|
||||
})
|
||||
|
||||
setUploadingFiles((prev) =>
|
||||
prev.map((uf) =>
|
||||
uf.id === tempId ? { ...uf, progress: 100, attachmentId: data.id } : uf,
|
||||
),
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
setUploadingFiles((prev) =>
|
||||
prev.map((uf) =>
|
||||
uf.id === tempId
|
||||
? {
|
||||
...uf,
|
||||
error: error instanceof Error ? error.message : 'Upload failed',
|
||||
}
|
||||
: uf,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ''
|
||||
}
|
||||
},
|
||||
[projectId, uploadAttachment],
|
||||
)
|
||||
|
||||
const removeFile = (id: string) => {
|
||||
setUploadingFiles((prev) => prev.filter((f) => f.id !== id))
|
||||
}
|
||||
|
||||
const handleSend = () => {
|
||||
if (!editorRef.current) return
|
||||
const isUploading = uploadingFiles.some((f) => !f.attachmentId && !f.error)
|
||||
if (isUploading) return
|
||||
|
||||
const successfulAttachmentIds = uploadingFiles
|
||||
.map((f) => f.attachmentId)
|
||||
.filter((id): id is string => !!id)
|
||||
|
||||
// Serialize content
|
||||
let processedText = ''
|
||||
editorRef.current.childNodes.forEach((node) => {
|
||||
if (node.nodeType === Node.TEXT_NODE) {
|
||||
processedText += node.textContent
|
||||
} else if (node.nodeType === Node.ELEMENT_NODE) {
|
||||
const el = node as HTMLElement
|
||||
if (el.dataset.type === 'mention') {
|
||||
processedText += `<@${el.dataset.id}>`
|
||||
} else if (el.tagName === 'BR') {
|
||||
processedText += '\n'
|
||||
} else if (el.tagName === 'DIV' || el.tagName === 'P') {
|
||||
// contentEditable often uses div/p for new lines
|
||||
processedText += '\n' + el.innerText
|
||||
} else {
|
||||
processedText += el.innerText
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
processedText = processedText.trim()
|
||||
|
||||
// Allow sending if annotations exist, even if text is empty
|
||||
if (!processedText && successfulAttachmentIds.length === 0 && annotations.length === 0) return
|
||||
|
||||
onSendMessage(
|
||||
processedText,
|
||||
successfulAttachmentIds,
|
||||
annotations,
|
||||
replyingTo?.id,
|
||||
isTimestampEnabled ? currentTime : undefined,
|
||||
)
|
||||
|
||||
// Reset editor
|
||||
editorRef.current.innerHTML = ''
|
||||
setHasContent(false)
|
||||
setUploadingFiles([])
|
||||
setViewingFile(null)
|
||||
setIsDrawing(false)
|
||||
resetAnnotations()
|
||||
setShowMentionList(false)
|
||||
if (onCancelReply) onCancelReply()
|
||||
}
|
||||
|
||||
const isUploading = uploadingFiles.some((f) => !f.attachmentId && !f.error)
|
||||
const hasSuccessfulUploads = uploadingFiles.some((f) => !!f.attachmentId)
|
||||
const canSend = hasContent || hasSuccessfulUploads || annotations.length > 0
|
||||
const showUpperPart = uploadingFiles.length > 0 || !!replyingTo
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className="relative flex flex-col w-full border border-foreground/35 rounded-3xl shadow-sm transition-all duration-200"
|
||||
>
|
||||
<style>{`
|
||||
[contenteditable]:empty:before {
|
||||
content: attr(data-placeholder);
|
||||
color: #9ca3af;
|
||||
cursor: text;
|
||||
}
|
||||
`}</style>
|
||||
{showMentionList && (filteredAgents.length > 0 || filteredHumans.length > 0) && (
|
||||
<div className="absolute bottom-full left-4 mb-2 w-64 rounded-xl shadow-lg border border-border overflow-hidden z-20 bg-popover text-popover-foreground animate-in fade-in slide-in-from-bottom-2 duration-200">
|
||||
<div className="h-64 overflow-y-auto">
|
||||
{filteredAgents.length > 0 && (
|
||||
<>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setCollapsedSections((prev) => ({ ...prev, bots: !prev.bots }))
|
||||
}}
|
||||
className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border sticky top-0 flex items-center justify-between hover:bg-muted transition-colors"
|
||||
>
|
||||
<span>Agents</span>
|
||||
<ChevronDown
|
||||
className={`w-3 h-3 transition-transform ${collapsedSections.bots ? '-rotate-90' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
{!collapsedSections.bots &&
|
||||
filteredAgents.map((item, index) => {
|
||||
const actualIndex = index
|
||||
return (
|
||||
<button
|
||||
key={item.data.id}
|
||||
onClick={() => handleSelectEntity(item)}
|
||||
onMouseEnter={() => setHighlightedIndex(actualIndex)}
|
||||
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left ${
|
||||
actualIndex === highlightedIndex
|
||||
? 'bg-accent text-accent-foreground'
|
||||
: 'hover:bg-accent/50'
|
||||
}`}
|
||||
>
|
||||
<div className="w-6 h-6 rounded-full bg-purple-100 dark:bg-purple-900/40 flex items-center justify-center text-xs font-bold text-purple-600 dark:text-purple-300">
|
||||
{item.data.name?.[0]}
|
||||
</div>
|
||||
<span className="text-sm">{item.data.name}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
|
||||
{filteredHumans.length > 0 && (
|
||||
<>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setCollapsedSections((prev) => ({ ...prev, users: !prev.users }))
|
||||
}}
|
||||
className="w-full text-xs font-semibold text-muted-foreground px-3 py-2 bg-muted/50 border-b border-border sticky top-0 flex items-center justify-between hover:bg-muted transition-colors"
|
||||
>
|
||||
<span>Members</span>
|
||||
<ChevronDown
|
||||
className={`w-3 h-3 transition-transform ${collapsedSections.users ? '-rotate-90' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
{!collapsedSections.users &&
|
||||
filteredHumans.map((item, index) => {
|
||||
const actualIndex =
|
||||
(collapsedSections.bots ? 0 : filteredAgents.length) + index
|
||||
return (
|
||||
<button
|
||||
key={item.data.id}
|
||||
onClick={() => handleSelectEntity(item)}
|
||||
onMouseEnter={() => setHighlightedIndex(actualIndex)}
|
||||
className={`w-full flex items-center gap-2 px-3 py-2 transition-colors text-left ${
|
||||
actualIndex === highlightedIndex
|
||||
? 'bg-accent text-accent-foreground'
|
||||
: 'hover:bg-accent/50'
|
||||
}`}
|
||||
>
|
||||
<div className="w-6 h-6 rounded-full bg-blue-100 dark:bg-blue-900/40 flex items-center justify-center text-xs font-bold text-blue-600 dark:text-blue-300">
|
||||
{item.data.name?.[0]}
|
||||
</div>
|
||||
<span className="text-sm">{item.data.name}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showUpperPart && (
|
||||
<div className="flex flex-col gap-2 p-3 pb-0 animate-in fade-in slide-in-from-bottom-2 duration-200">
|
||||
{replyingTo && (
|
||||
<div className="flex items-center justify-between bg-muted p-2 px-3 rounded-lg border border-border">
|
||||
<div className="text-xs text-muted-foreground truncate mr-2">
|
||||
reply to: {replyingTo.message}
|
||||
</div>
|
||||
<button
|
||||
onClick={onCancelReply}
|
||||
className="text-muted-foreground hover:text-foreground p-1 rounded-full hover:bg-muted-foreground/10 shrink-0"
|
||||
>
|
||||
<XIcon className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{uploadingFiles.length > 0 && (
|
||||
<div className="flex gap-3 overflow-x-auto py-2 px-1 scrollbar-hide">
|
||||
{uploadingFiles.map((upload) => (
|
||||
<div key={upload.id} className="relative group flex-shrink-0">
|
||||
<div className="w-16 h-16 rounded-lg border border-gray-200 overflow-hidden bg-gray-50 flex items-center justify-center">
|
||||
{upload.file.type.startsWith('image/') ? (
|
||||
<img
|
||||
src={URL.createObjectURL(upload.file)}
|
||||
alt="preview"
|
||||
onClick={() => setViewingFile(upload.file)}
|
||||
className={`w-full h-full object-cover ${
|
||||
!upload.attachmentId ? 'opacity-50' : ''
|
||||
}`}
|
||||
/>
|
||||
) : (
|
||||
<FileIcon className="w-8 h-8 text-gray-400" />
|
||||
)}
|
||||
{isUploading && !upload.attachmentId && !upload.error && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/50">
|
||||
<ProgressCircle progress={upload.progress} className="w-10 h-10" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => removeFile(upload.id)}
|
||||
className="absolute -top-1.5 -right-1.5 bg-gray-500 text-white rounded-full p-0.5 shadow-md opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-500 z-10"
|
||||
>
|
||||
<XIcon className="w-3 h-3" />
|
||||
</button>
|
||||
<span className="text-[10px] text-gray-500 mt-1 block max-w-[4rem] truncate text-center">
|
||||
{upload.file.name}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
onClick={() => editorRef.current?.focus()}
|
||||
className="w-full px-4 pt-1 pb-1 cursor-text flow-root max-h-60 overflow-y-auto"
|
||||
>
|
||||
{isTimestampEnabled && currentTime !== undefined && frameRate !== undefined && (
|
||||
<div
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
editorRef.current?.focus()
|
||||
}}
|
||||
className="float-left select-none bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-300 px-2.5 py-0.5 mt-3 mr-2 rounded-sm text-xs font-mono font-bold flex items-center gap-1 cursor-text"
|
||||
>
|
||||
{formatTimestamp(currentTime, frameRate)}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
ref={editorRef}
|
||||
contentEditable
|
||||
suppressContentEditableWarning
|
||||
onInput={handleInput}
|
||||
onKeyDown={handleKeyDown}
|
||||
data-placeholder={replyingTo ? 'Reply...' : 'Message...'}
|
||||
className={`bg-transparent border-none focus:ring-0 resize-none min-h-[40px] leading-relaxed py-2 focus:outline-none block ${isTimestampEnabled && currentTime !== undefined && frameRate !== undefined && !hasContent ? 'pl-[120px]' : ''}`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between items-center px-2 pb-2">
|
||||
{isDrawing ? (
|
||||
<div className="flex items-center gap-2 overflow-x-auto scrollbar-hide w-full mr-2">
|
||||
<Button
|
||||
onClick={() => {
|
||||
setIsDrawing(false)
|
||||
resetAnnotations() // Cancel drawing
|
||||
}}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="p-2 rounded-full cursor-pointer text-gray-500 hover:text-gray-700 hover:bg-gray-100 mr-2"
|
||||
title="Back"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</Button>
|
||||
|
||||
<div className="h-4 w-px bg-gray-300 mx-1"></div>
|
||||
|
||||
<button
|
||||
onClick={() => setTool('arrow')}
|
||||
className={`p-1.5 rounded hover:bg-gray-100 ${currentTool === 'arrow' ? 'text-blue-500 bg-blue-50' : 'text-gray-500'}`}
|
||||
title="Arrow"
|
||||
>
|
||||
<ArrowUp size={16} className="rotate-45" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTool('line')}
|
||||
className={`p-1.5 rounded hover:bg-gray-100 ${currentTool === 'line' ? 'text-blue-500 bg-blue-50' : 'text-gray-500'}`}
|
||||
title="Line"
|
||||
>
|
||||
<Minus size={16} className="-rotate-45" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTool('box')}
|
||||
className={`p-1.5 rounded hover:bg-gray-100 ${currentTool === 'box' ? 'text-blue-500 bg-blue-50' : 'text-gray-500'}`}
|
||||
title="Box"
|
||||
>
|
||||
<Square size={16} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTool('freehand')}
|
||||
className={`p-1.5 rounded hover:bg-gray-100 ${currentTool === 'freehand' ? 'text-blue-500 bg-blue-50' : 'text-gray-500'}`}
|
||||
title="Freehand"
|
||||
>
|
||||
<Brush size={16} />
|
||||
</button>
|
||||
|
||||
<div className="h-4 w-px bg-gray-300 mx-1"></div>
|
||||
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<button className="flex items-center gap-1 p-1 rounded hover:bg-gray-100">
|
||||
<div
|
||||
className="w-4 h-4 rounded-full border border-gray-200"
|
||||
style={{ backgroundColor: currentColor }}
|
||||
/>
|
||||
<ChevronDown size={12} className="text-gray-500" />
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-2" align="center" side="top">
|
||||
<div className="flex items-center gap-1">
|
||||
{PREDEFINED_COLORS.map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
onClick={() => setColor(c)}
|
||||
className={`w-6 h-6 rounded-full border border-gray-200 transition-transform hover:scale-110 ${currentColor === c ? 'ring-2 ring-blue-500 ring-offset-1' : ''}`}
|
||||
style={{ backgroundColor: c }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<div className="h-4 w-px bg-gray-300 mx-1"></div>
|
||||
|
||||
<button
|
||||
onClick={undo}
|
||||
disabled={historyIndex <= 0}
|
||||
className="p-1.5 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed text-gray-500"
|
||||
>
|
||||
<Undo size={16} />
|
||||
</button>
|
||||
<button
|
||||
onClick={redo}
|
||||
disabled={historyIndex >= history.length - 1}
|
||||
className="p-1.5 rounded hover:bg-gray-100 disabled:opacity-30 disabled:cursor-not-allowed text-gray-500"
|
||||
>
|
||||
<Redo size={16} />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-1">
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
className="hidden"
|
||||
multiple
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
{currentTime !== undefined && frameRate !== undefined && (
|
||||
<Button
|
||||
onClick={() => setIsTimestampEnabled(!isTimestampEnabled)}
|
||||
variant={isTimestampEnabled ? 'secondary' : 'ghost'}
|
||||
size="icon"
|
||||
className={`p-2 rounded-full cursor-pointer ${isTimestampEnabled ? 'text-blue-600 bg-blue-50 dark:bg-blue-900/20' : ''}`}
|
||||
title={isTimestampEnabled ? 'Disable Timestamp' : 'Enable Timestamp'}
|
||||
>
|
||||
<Clock className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="p-2 rounded-full cursor-pointer"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
title="Attach files"
|
||||
>
|
||||
<Paperclip className="w-4 h-4" />
|
||||
</Button>
|
||||
{!hideAnnotationControl && (
|
||||
<Button
|
||||
onClick={() => setIsDrawing(true)}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="p-2 rounded-full cursor-pointer"
|
||||
title="Toggle Annotation"
|
||||
>
|
||||
<DrawAnnotation className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={handleSend}
|
||||
disabled={!canSend || isUploading}
|
||||
className={`p-2 rounded-full transition-all duration-200 flex items-center justify-center shrink-0 ${
|
||||
canSend && !isUploading
|
||||
? 'bg-blue-600 text-white shadow-md hover:bg-blue-700 hover:shadow-lg transform hover:-translate-y-0.5'
|
||||
: 'bg-gray-400 cursor-not-allowed'
|
||||
}`}
|
||||
>
|
||||
<ArrowUp className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{viewingFile && (
|
||||
<div
|
||||
className="fixed inset-0 z-[100] bg-black/95 flex flex-col items-center justify-center p-4 animate-in fade-in duration-200"
|
||||
onClick={() => setViewingFile(null)}
|
||||
>
|
||||
<button className="absolute top-4 right-4 text-white/70 hover:text-white hover:bg-white/20 rounded-full p-2 transition-colors z-50">
|
||||
<XIcon className="w-8 h-8" />
|
||||
</button>
|
||||
<div className="w-full h-full flex items-center justify-center p-2">
|
||||
<img
|
||||
src={URL.createObjectURL(viewingFile)}
|
||||
alt="Enlarged view"
|
||||
className="max-w-full max-h-[85vh] object-contain rounded shadow-2xl cursor-zoom-out"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setViewingFile(null)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="absolute bottom-6 text-white text-sm font-medium bg-black/50 px-4 py-2 rounded-full backdrop-blur-sm">
|
||||
{viewingFile.name}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
ChatInput.displayName = 'ChatInput'
|
||||
@@ -0,0 +1,179 @@
|
||||
'use client'
|
||||
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Calendar } from '@/ui/components/ui/calendar'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
|
||||
import { ScrollArea, ScrollBar } from '@/ui/components/ui/scroll-area'
|
||||
import { Separator } from '@/ui/components/ui/separator'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { addHours, addWeeks, format } from 'date-fns'
|
||||
import { CalendarIcon } from 'lucide-react'
|
||||
import * as React from 'react'
|
||||
|
||||
interface DateTimePickerProps {
|
||||
value?: Date
|
||||
onChange?: (date: Date | undefined) => void
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function DateTimePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = 'Pick a date',
|
||||
disabled,
|
||||
className,
|
||||
}: DateTimePickerProps) {
|
||||
const [isOpen, setIsOpen] = React.useState(false)
|
||||
const [tempValue, setTempValue] = React.useState<Date | undefined>(value)
|
||||
|
||||
// Sync tempValue with value when popover opens
|
||||
React.useEffect(() => {
|
||||
if (isOpen) {
|
||||
setTempValue(value)
|
||||
}
|
||||
}, [isOpen, value])
|
||||
|
||||
const hours = Array.from({ length: 24 }, (_, i) => i)
|
||||
const minutes = Array.from({ length: 12 }, (_, i) => i * 5) // 5-minute increments
|
||||
|
||||
const handleDateSelect = (selectedDate: Date | undefined) => {
|
||||
if (selectedDate) {
|
||||
const newDate = tempValue ? new Date(tempValue) : new Date()
|
||||
newDate.setFullYear(selectedDate.getFullYear())
|
||||
newDate.setMonth(selectedDate.getMonth())
|
||||
newDate.setDate(selectedDate.getDate())
|
||||
setTempValue(newDate)
|
||||
} else {
|
||||
setTempValue(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
const handleTimeChange = (type: 'hour' | 'minute', timeValue: number) => {
|
||||
const newDate = tempValue ? new Date(tempValue) : new Date()
|
||||
if (type === 'hour') {
|
||||
newDate.setHours(timeValue)
|
||||
} else {
|
||||
newDate.setMinutes(timeValue)
|
||||
}
|
||||
setTempValue(newDate)
|
||||
}
|
||||
|
||||
const handleQuickSelect = (type: '24h' | '1w' | '2w') => {
|
||||
let newDate = new Date()
|
||||
if (type === '24h') {
|
||||
newDate = addHours(newDate, 24)
|
||||
} else if (type === '1w') {
|
||||
newDate = addWeeks(newDate, 1)
|
||||
} else if (type === '2w') {
|
||||
newDate = addWeeks(newDate, 2)
|
||||
}
|
||||
setTempValue(newDate)
|
||||
}
|
||||
|
||||
const handleSave = () => {
|
||||
onChange?.(tempValue)
|
||||
setIsOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
'w-full justify-start text-left font-normal h-9',
|
||||
!value && 'text-muted-foreground',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{value ? format(value, 'yyyy/MM/dd HH:mm') : <span>{placeholder}</span>}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[22rem] p-0" align="start">
|
||||
<div className="flex flex-col w-full">
|
||||
<div className="flex w-full">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={tempValue}
|
||||
onSelect={handleDateSelect}
|
||||
className="grow"
|
||||
/>
|
||||
<div className="flex flex-col sm:flex-row sm:h-[300px] divide-y sm:divide-y-0 sm:divide-x border-t sm:border-t-0 border-l">
|
||||
{/* Hours Column */}
|
||||
<ScrollArea className="w-64 sm:w-auto [&_[data-orientation=vertical]]:hidden">
|
||||
<div className="flex sm:flex-col p-2">
|
||||
{hours.map((hour) => (
|
||||
<Button
|
||||
key={hour}
|
||||
size="icon"
|
||||
variant={tempValue && tempValue.getHours() === hour ? 'default' : 'ghost'}
|
||||
className="sm:w-full shrink-0 aspect-square text-xs h-8 w-8"
|
||||
onClick={() => handleTimeChange('hour', hour)}
|
||||
>
|
||||
{hour.toString().padStart(2, '0')}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
||||
</ScrollArea>
|
||||
|
||||
{/* Minutes Column */}
|
||||
<ScrollArea className="w-64 sm:w-auto [&_[data-orientation=vertical]]:hidden">
|
||||
<div className="flex sm:flex-col p-2">
|
||||
{minutes.map((minute) => (
|
||||
<Button
|
||||
key={minute}
|
||||
size="icon"
|
||||
variant={tempValue && tempValue.getMinutes() === minute ? 'default' : 'ghost'}
|
||||
className="sm:w-full shrink-0 aspect-square text-xs h-8 w-8"
|
||||
onClick={() => handleTimeChange('minute', minute)}
|
||||
>
|
||||
{minute.toString().padStart(2, '0')}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" className="sm:hidden" />
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="p-2 flex items-center justify-between bg-muted/50">
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-[10px] h-7 px-2"
|
||||
onClick={() => handleQuickSelect('24h')}
|
||||
>
|
||||
24 Hours
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-[10px] h-7 px-2"
|
||||
onClick={() => handleQuickSelect('1w')}
|
||||
>
|
||||
1 Week
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-[10px] h-7 px-2"
|
||||
onClick={() => handleQuickSelect('2w')}
|
||||
>
|
||||
2 Weeks
|
||||
</Button>
|
||||
</div>
|
||||
<Button size="sm" className="h-7 px-4" onClick={handleSave}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Modifier, configurator } from '@dnd-kit/abstract'
|
||||
import type { DragOperation } from '@dnd-kit/abstract'
|
||||
import type { DragDropManager } from '@dnd-kit/dom'
|
||||
|
||||
interface Anchor {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
interface Options {
|
||||
anchor?: Anchor
|
||||
}
|
||||
|
||||
const DEFAULT_ANCHOR: Anchor = { x: 0.5, y: 0.5 }
|
||||
|
||||
export class SnapToPointer extends Modifier<DragDropManager, Options> {
|
||||
apply({ activatorEvent, shape, transform }: DragOperation) {
|
||||
if (!shape || !(activatorEvent instanceof PointerEvent)) {
|
||||
return transform
|
||||
}
|
||||
|
||||
const anchor = this.options?.anchor ?? DEFAULT_ANCHOR
|
||||
const { boundingRectangle } = shape.initial
|
||||
|
||||
const anchorX = boundingRectangle.left + boundingRectangle.width * anchor.x
|
||||
const anchorY = boundingRectangle.top + boundingRectangle.height * anchor.y
|
||||
|
||||
return {
|
||||
x: transform.x + activatorEvent.clientX - anchorX,
|
||||
y: transform.y + activatorEvent.clientY - anchorY,
|
||||
}
|
||||
}
|
||||
|
||||
static configure = configurator(SnapToPointer)
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export interface DragState {
|
||||
isActive: boolean
|
||||
draggedIds: Set<string>
|
||||
hasFolders: boolean
|
||||
itemCount: number
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
import Konva from 'konva'
|
||||
import type { KonvaEventObject } from 'konva/lib/Node'
|
||||
import type {
|
||||
Annotation,
|
||||
BoxAnnotation,
|
||||
LineAnnotation,
|
||||
ArrowAnnotation,
|
||||
FreehandAnnotation,
|
||||
} from '@/ui/types'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { Stage, Layer, Image as KonvaImage, Rect, Arrow, Line, Group } from 'react-konva'
|
||||
import useImage from 'use-image'
|
||||
import type { DrawingTool } from '@/ui/stores/annotation-store'
|
||||
|
||||
interface DrawingCanvasProps {
|
||||
width: number
|
||||
height: number
|
||||
mediaDimensions: { width: number; height: number }
|
||||
imageUrl?: string
|
||||
videoElement?: HTMLVideoElement
|
||||
annotations: Annotation[]
|
||||
scale: number
|
||||
offset: { x: number; y: number }
|
||||
onPan?: (newOffset: { x: number; y: number }) => void
|
||||
onClick?: () => void
|
||||
className?: string
|
||||
|
||||
// Drawing Props
|
||||
isDrawing?: boolean
|
||||
currentTool?: DrawingTool
|
||||
currentColor?: string
|
||||
onAddAnnotation?: (annotation: Annotation) => void
|
||||
}
|
||||
|
||||
const DrawingCanvas = ({
|
||||
width,
|
||||
height,
|
||||
mediaDimensions,
|
||||
imageUrl,
|
||||
videoElement,
|
||||
annotations,
|
||||
scale,
|
||||
offset,
|
||||
onPan,
|
||||
onClick,
|
||||
className,
|
||||
isDrawing = false,
|
||||
currentTool = 'arrow',
|
||||
currentColor = '#ef4444',
|
||||
onAddAnnotation,
|
||||
}: DrawingCanvasProps) => {
|
||||
const [loadedImage] = useImage(imageUrl || '', 'anonymous')
|
||||
const imageRef = useRef<Konva.Image>(null)
|
||||
const isDragging = useRef(false)
|
||||
const lastPos = useRef({ x: 0, y: 0 })
|
||||
const startPointRef = useRef<{ x: number; y: number } | null>(null)
|
||||
|
||||
// Draft shapes for drawing
|
||||
const currentLineRef = useRef<Konva.Line>(null)
|
||||
const currentRectRef = useRef<Konva.Rect>(null)
|
||||
const currentArrowRef = useRef<Konva.Arrow>(null)
|
||||
|
||||
// Handle Video Redraw
|
||||
useEffect(() => {
|
||||
if (videoElement && imageRef.current) {
|
||||
const layer = imageRef.current.getLayer()
|
||||
if (!layer) return
|
||||
|
||||
const anim = new Konva.Animation(() => {
|
||||
// Force redraw to update video frame
|
||||
}, layer)
|
||||
anim.start()
|
||||
return () => {
|
||||
anim.stop()
|
||||
}
|
||||
}
|
||||
}, [videoElement])
|
||||
|
||||
// -- Helpers --
|
||||
const getRelativePointerPosition = (
|
||||
node: Konva.Node,
|
||||
clamp = false,
|
||||
customPos?: { x: number; y: number },
|
||||
) => {
|
||||
// the function will return pointer position relative to the passed node
|
||||
const transform = node.getAbsoluteTransform().copy()
|
||||
// to detect relative position we need to invert transform
|
||||
transform.invert()
|
||||
|
||||
// get pointer (say mouse or touch) position
|
||||
const pos = customPos || node.getStage()?.getPointerPosition()
|
||||
if (pos) {
|
||||
const point = transform.point(pos)
|
||||
if (clamp) {
|
||||
return {
|
||||
x: Math.max(0, Math.min(mediaDimensions.width, point.x)),
|
||||
y: Math.max(0, Math.min(mediaDimensions.height, point.y)),
|
||||
}
|
||||
}
|
||||
return point
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Ref to hold current props for global listeners to avoid stale closures
|
||||
const stateRef = useRef({
|
||||
isDrawing,
|
||||
currentTool,
|
||||
currentColor,
|
||||
onPan,
|
||||
offset,
|
||||
scale,
|
||||
mediaDimensions,
|
||||
onAddAnnotation,
|
||||
})
|
||||
stateRef.current = {
|
||||
isDrawing,
|
||||
currentTool,
|
||||
currentColor,
|
||||
onPan,
|
||||
offset,
|
||||
scale,
|
||||
mediaDimensions,
|
||||
onAddAnnotation,
|
||||
}
|
||||
|
||||
const finalizeDrawing = () => {
|
||||
if (!isDragging.current) return
|
||||
isDragging.current = false
|
||||
|
||||
const {
|
||||
isDrawing: activeDrawing,
|
||||
onAddAnnotation: addAnn,
|
||||
mediaDimensions: dims,
|
||||
currentTool: tool,
|
||||
currentColor: color,
|
||||
} = stateRef.current
|
||||
|
||||
if (activeDrawing && addAnn) {
|
||||
const w = dims.width
|
||||
const h = dims.height
|
||||
|
||||
// Helper to normalize
|
||||
const norm = (val: number, dim: number) => val / dim
|
||||
|
||||
// Capture shape
|
||||
if (tool === 'freehand' && currentLineRef.current) {
|
||||
currentLineRef.current.visible(false)
|
||||
const rawPoints = currentLineRef.current.points()
|
||||
const points: [number, number][] = []
|
||||
for (let i = 0; i < rawPoints.length; i += 2) {
|
||||
points.push([norm(rawPoints[i], w), norm(rawPoints[i + 1], h)])
|
||||
}
|
||||
if (points.length > 1) {
|
||||
const ann: FreehandAnnotation = {
|
||||
type: 'freehand',
|
||||
color,
|
||||
points,
|
||||
}
|
||||
addAnn(ann)
|
||||
}
|
||||
} else if (tool === 'line' && currentLineRef.current) {
|
||||
currentLineRef.current.visible(false)
|
||||
const pts = currentLineRef.current.points()
|
||||
const ann: LineAnnotation = {
|
||||
type: 'line',
|
||||
color,
|
||||
points: [
|
||||
[norm(pts[0], w), norm(pts[1], h)],
|
||||
[norm(pts[2], w), norm(pts[3], h)],
|
||||
],
|
||||
}
|
||||
addAnn(ann)
|
||||
} else if (tool === 'box' && currentRectRef.current) {
|
||||
currentRectRef.current.visible(false)
|
||||
const x = currentRectRef.current.x()
|
||||
const y = currentRectRef.current.y()
|
||||
const boxW = currentRectRef.current.width()
|
||||
const boxH = currentRectRef.current.height()
|
||||
// Convert to start/end points
|
||||
const start: [number, number] = [norm(x, w), norm(y, h)]
|
||||
const end: [number, number] = [norm(x + boxW, w), norm(y + boxH, h)]
|
||||
const ann: BoxAnnotation = {
|
||||
type: 'box',
|
||||
color,
|
||||
points: [start, end],
|
||||
}
|
||||
addAnn(ann)
|
||||
} else if (tool === 'arrow' && currentArrowRef.current) {
|
||||
currentArrowRef.current.visible(false)
|
||||
const pts = currentArrowRef.current.points()
|
||||
const ann: ArrowAnnotation = {
|
||||
type: 'arrow',
|
||||
color,
|
||||
points: [
|
||||
[norm(pts[0], w), norm(pts[1], h)],
|
||||
[norm(pts[2], w), norm(pts[3], h)],
|
||||
],
|
||||
}
|
||||
addAnn(ann)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const handleGlobalMove = (e: MouseEvent | TouchEvent) => {
|
||||
if (!isDragging.current) return
|
||||
|
||||
const stage = imageRef.current?.getStage()
|
||||
if (!stage) return
|
||||
const container = stage.container()
|
||||
const rect = container.getBoundingClientRect()
|
||||
|
||||
let clientX, clientY
|
||||
if ('clientX' in e) {
|
||||
clientX = e.clientX
|
||||
clientY = e.clientY
|
||||
} else {
|
||||
clientX = e.touches[0].clientX
|
||||
clientY = e.touches[0].clientY
|
||||
}
|
||||
|
||||
const stagePos = {
|
||||
x: clientX - rect.left,
|
||||
y: clientY - rect.top,
|
||||
}
|
||||
|
||||
const {
|
||||
isDrawing: activeDrawing,
|
||||
currentTool: tool,
|
||||
onPan: panFn,
|
||||
offset: currentOffset,
|
||||
} = stateRef.current
|
||||
|
||||
if (activeDrawing) {
|
||||
if (tool === 'select') return
|
||||
|
||||
const pos = getRelativePointerPosition(imageRef.current!, true, stagePos)
|
||||
if (!pos || !startPointRef.current) return
|
||||
const start = startPointRef.current
|
||||
|
||||
const layer = imageRef.current?.getLayer()
|
||||
|
||||
if (tool === 'freehand' && currentLineRef.current) {
|
||||
const newPoints = currentLineRef.current.points().concat([pos.x, pos.y])
|
||||
currentLineRef.current.points(newPoints)
|
||||
} else if (tool === 'line' && currentLineRef.current) {
|
||||
currentLineRef.current.points([start.x, start.y, pos.x, pos.y])
|
||||
} else if (tool === 'box' && currentRectRef.current) {
|
||||
currentRectRef.current.width(pos.x - start.x)
|
||||
currentRectRef.current.height(pos.y - start.y)
|
||||
} else if (tool === 'arrow' && currentArrowRef.current) {
|
||||
currentArrowRef.current.points([start.x, start.y, pos.x, pos.y])
|
||||
}
|
||||
|
||||
layer?.batchDraw()
|
||||
} else {
|
||||
// Panning
|
||||
if (!panFn) return
|
||||
|
||||
const dx = stagePos.x - lastPos.current.x
|
||||
const dy = stagePos.y - lastPos.current.y
|
||||
lastPos.current = stagePos
|
||||
|
||||
panFn({
|
||||
x: currentOffset.x + dx,
|
||||
y: currentOffset.y + dy,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleGlobalUp = () => {
|
||||
finalizeDrawing()
|
||||
}
|
||||
|
||||
window.addEventListener('mousemove', handleGlobalMove)
|
||||
window.addEventListener('mouseup', handleGlobalUp)
|
||||
window.addEventListener('touchmove', handleGlobalMove)
|
||||
window.addEventListener('touchend', handleGlobalUp)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('mousemove', handleGlobalMove)
|
||||
window.removeEventListener('mouseup', handleGlobalUp)
|
||||
window.removeEventListener('touchmove', handleGlobalMove)
|
||||
window.removeEventListener('touchend', handleGlobalUp)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleMouseDown = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
|
||||
if (isDrawing) {
|
||||
// Drawing Logic
|
||||
if (currentTool === 'select') return
|
||||
|
||||
const stage = e.target.getStage()
|
||||
if (!stage) return
|
||||
|
||||
// Use imageRef to get coordinates relative to the image (handling zoom/pan)
|
||||
const pos = getRelativePointerPosition(imageRef.current!)
|
||||
if (!pos) return
|
||||
|
||||
// Only start drawing if within media bounds
|
||||
if (
|
||||
pos.x < 0 ||
|
||||
pos.x > mediaDimensions.width ||
|
||||
pos.y < 0 ||
|
||||
pos.y > mediaDimensions.height
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
isDragging.current = true
|
||||
startPointRef.current = pos
|
||||
|
||||
const layer = imageRef.current?.getLayer()
|
||||
if (!layer) return
|
||||
|
||||
if (currentTool === 'freehand' && currentLineRef.current) {
|
||||
currentLineRef.current.points([pos.x, pos.y])
|
||||
currentLineRef.current.stroke(currentColor)
|
||||
currentLineRef.current.visible(true)
|
||||
} else if (currentTool === 'line' && currentLineRef.current) {
|
||||
currentLineRef.current.points([pos.x, pos.y, pos.x, pos.y])
|
||||
currentLineRef.current.stroke(currentColor)
|
||||
currentLineRef.current.visible(true)
|
||||
} else if (currentTool === 'box' && currentRectRef.current) {
|
||||
currentRectRef.current.position(pos)
|
||||
currentRectRef.current.width(0)
|
||||
currentRectRef.current.height(0)
|
||||
currentRectRef.current.stroke(currentColor)
|
||||
currentRectRef.current.visible(true)
|
||||
} else if (currentTool === 'arrow' && currentArrowRef.current) {
|
||||
currentArrowRef.current.points([pos.x, pos.y, pos.x, pos.y])
|
||||
currentArrowRef.current.stroke(currentColor)
|
||||
currentArrowRef.current.fill(currentColor)
|
||||
currentArrowRef.current.visible(true)
|
||||
}
|
||||
|
||||
layer.batchDraw()
|
||||
} else {
|
||||
// Panning Logic
|
||||
if (!onPan) return
|
||||
isDragging.current = true
|
||||
const stage = e.target.getStage()
|
||||
if (stage) {
|
||||
const pointer = stage.getPointerPosition()
|
||||
if (pointer) {
|
||||
lastPos.current = pointer
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const renderAnnotation = (annotation: Annotation, i: number) => {
|
||||
const w = mediaDimensions.width
|
||||
const h = mediaDimensions.height
|
||||
// We add a key suffix to force re-render if updated? No, index is fine for this list.
|
||||
// Actually, we might want stable IDs if we were editing existing ones.
|
||||
|
||||
// Stroke Width Logic:
|
||||
// We want the stroke to be visible regardless of zoom.
|
||||
// If we use `strokeScaleEnabled={false}`, Konva handles it!
|
||||
// Wait, `strokeScaleEnabled` defaults to true.
|
||||
// If false, stroke width is in screen pixels.
|
||||
// Let's try `strokeScaleEnabled={false}` and `strokeWidth={2}`.
|
||||
|
||||
switch (annotation.type) {
|
||||
case 'box': {
|
||||
const [start, end] = annotation.points
|
||||
const x = Math.min(start[0], end[0]) * w
|
||||
const y = Math.min(start[1], end[1]) * h
|
||||
const boxWidth = Math.abs(end[0] - start[0]) * w
|
||||
const boxHeight = Math.abs(end[1] - start[1]) * h
|
||||
|
||||
return (
|
||||
<Rect
|
||||
key={i}
|
||||
x={x}
|
||||
y={y}
|
||||
width={boxWidth}
|
||||
height={boxHeight}
|
||||
stroke={annotation.color}
|
||||
strokeWidth={2.6 / scale}
|
||||
listening={false}
|
||||
/>
|
||||
)
|
||||
}
|
||||
case 'arrow': {
|
||||
const points = annotation.points.flat().map((p, idx) => (idx % 2 === 0 ? p * w : p * h))
|
||||
return (
|
||||
<Arrow
|
||||
key={i}
|
||||
points={points}
|
||||
stroke={annotation.color}
|
||||
strokeWidth={2.6 / scale}
|
||||
fill={annotation.color}
|
||||
pointerLength={10 / scale}
|
||||
pointerWidth={10 / scale}
|
||||
listening={false}
|
||||
/>
|
||||
)
|
||||
}
|
||||
case 'line':
|
||||
case 'freehand': {
|
||||
const points = annotation.points.flat().map((p, idx) => (idx % 2 === 0 ? p * w : p * h))
|
||||
return (
|
||||
<Line
|
||||
key={i}
|
||||
points={points}
|
||||
stroke={annotation.color}
|
||||
strokeWidth={2.6 / scale}
|
||||
tension={0.5}
|
||||
lineCap="round"
|
||||
lineJoin="round"
|
||||
listening={false}
|
||||
/>
|
||||
)
|
||||
}
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={className}
|
||||
style={{
|
||||
width,
|
||||
height,
|
||||
overflow: 'hidden',
|
||||
pointerEvents: !isDrawing && !onPan ? 'none' : 'auto',
|
||||
cursor:
|
||||
isDrawing && currentTool !== 'select'
|
||||
? 'crosshair'
|
||||
: onPan
|
||||
? isDragging.current
|
||||
? 'grabbing'
|
||||
: 'grab'
|
||||
: 'default',
|
||||
}}
|
||||
>
|
||||
<Stage
|
||||
width={width}
|
||||
height={height}
|
||||
scaleX={scale}
|
||||
scaleY={scale}
|
||||
x={offset.x}
|
||||
y={offset.y}
|
||||
onMouseDown={handleMouseDown}
|
||||
onClick={!isDrawing ? onClick : undefined}
|
||||
onTap={!isDrawing ? onClick : undefined}
|
||||
onTouchStart={handleMouseDown}
|
||||
>
|
||||
<Layer>
|
||||
<KonvaImage
|
||||
ref={imageRef}
|
||||
image={videoElement || loadedImage}
|
||||
width={mediaDimensions.width}
|
||||
height={mediaDimensions.height}
|
||||
/>
|
||||
{annotations.map(renderAnnotation)}
|
||||
|
||||
{/* Draft Shapes */}
|
||||
<Group listening={false}>
|
||||
<Line
|
||||
ref={currentLineRef}
|
||||
strokeWidth={2.6 / scale}
|
||||
lineCap="round"
|
||||
lineJoin="round"
|
||||
visible={false}
|
||||
/>
|
||||
<Rect ref={currentRectRef} strokeWidth={2.6 / scale} visible={false} />
|
||||
<Arrow
|
||||
ref={currentArrowRef}
|
||||
points={[]}
|
||||
strokeWidth={2.6 / scale}
|
||||
pointerLength={10 / scale}
|
||||
pointerWidth={10 / scale}
|
||||
visible={false}
|
||||
/>
|
||||
</Group>
|
||||
</Layer>
|
||||
</Stage>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default DrawingCanvas
|
||||
@@ -0,0 +1,161 @@
|
||||
import { Menu } from 'lucide-react'
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import { Button } from './ui/button'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip'
|
||||
import { UserMenu } from './user-menu'
|
||||
|
||||
interface DualSidebarItemProps {
|
||||
icon: React.ReactNode
|
||||
label: string
|
||||
badge?: React.ReactNode
|
||||
children?: React.ReactNode
|
||||
onItemClick?: () => void
|
||||
}
|
||||
|
||||
// A declarative component that holds props for a sidebar item. It doesn't render anything itself.
|
||||
export const DualSidebarItem: React.FC<DualSidebarItemProps> = () => {
|
||||
return null
|
||||
}
|
||||
|
||||
interface DualSidebarProps {
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
export const DualSidebar: React.FC<DualSidebarProps> = ({ children }) => {
|
||||
const [activeItem, setActiveItem] = useState<number | null>(null)
|
||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
|
||||
|
||||
const sidebarItems = useMemo(
|
||||
() =>
|
||||
React.Children.toArray(children).filter(
|
||||
(child): child is React.ReactElement<DualSidebarItemProps> =>
|
||||
React.isValidElement(child) && child.type === DualSidebarItem,
|
||||
),
|
||||
[children],
|
||||
)
|
||||
|
||||
const activeItemContent = activeItem !== null ? sidebarItems[activeItem]?.props : null
|
||||
|
||||
const handleItemClick = (index: number) => {
|
||||
const item = sidebarItems[index]
|
||||
|
||||
if (!item.props.children) {
|
||||
setActiveItem(null)
|
||||
item.props.onItemClick?.()
|
||||
return
|
||||
}
|
||||
|
||||
setActiveItem((prev) => {
|
||||
if (prev === index) {
|
||||
return null
|
||||
}
|
||||
if (item && item.props.onItemClick) {
|
||||
item.props.onItemClick()
|
||||
}
|
||||
return index
|
||||
})
|
||||
}
|
||||
|
||||
const toggleMobileMenu = () => {
|
||||
setIsMobileMenuOpen((prev) => !prev)
|
||||
}
|
||||
|
||||
const closeMobileMenu = () => {
|
||||
setIsMobileMenuOpen(false)
|
||||
setActiveItem(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Mobile Hamburger Button */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleMobileMenu}
|
||||
className="md:hidden fixed top-4 left-4 z-50 rounded-md bg-sidebar/50 backdrop-blur-sm text-sidebar-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-ring"
|
||||
aria-label="Open navigation menu"
|
||||
aria-expanded={isMobileMenuOpen}
|
||||
>
|
||||
<Menu />
|
||||
</Button>
|
||||
|
||||
{/* Mobile Overlay */}
|
||||
{isMobileMenuOpen && (
|
||||
<div
|
||||
onClick={closeMobileMenu}
|
||||
className="fixed inset-0 bg-black/60 z-30 md:hidden"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Desktop Overlay for Child Sidebar */}
|
||||
{activeItem !== null && (
|
||||
<div
|
||||
onClick={() => setActiveItem(null)}
|
||||
className="hidden md:block fixed inset-0 bg-black/20 z-30"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
|
||||
<aside
|
||||
className={`fixed inset-y-0 left-0 z-40 flex transition-transform duration-300 ease-in-out ${isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'} md:translate-x-0`}
|
||||
>
|
||||
<div className="absolute bottom-0 w-full h-[70dvh] bg-linear-to-t from-sidebar-primary/10 to-transparent"></div>
|
||||
{/* Level 1: Icon Bar */}
|
||||
<nav className="w-16 bg-sidebar border-r border-sidebar-border flex flex-col items-center pb-4 pt-0 space-y-2 flex-shrink-0">
|
||||
<div className="flex-1 w-full flex flex-col items-center space-y-5 pt-1">
|
||||
<TooltipProvider>
|
||||
{sidebarItems.map((item, index) => (
|
||||
<Tooltip key={item.props.label}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-lg"
|
||||
onClick={() => handleItemClick(index)}
|
||||
aria-label={item.props.label}
|
||||
aria-expanded={activeItem === index}
|
||||
className={`relative w-12 h-12 [&_svg:not([class*='size-'])]:size-6 transition-all duration-200 ${
|
||||
activeItem === index
|
||||
? 'bg-sidebar-primary text-sidebar-primary-foreground shadow-lg hover:bg-sidebar-primary hover:text-sidebar-primary-foreground'
|
||||
: 'text-sidebar-foreground/60 hover:text-sidebar-foreground hover:bg-sidebar-accent'
|
||||
}`}
|
||||
>
|
||||
{item.props.icon}
|
||||
{item.props.badge}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">
|
||||
<p>{item.props.label}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
))}
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
<div className="mt-auto w-full flex flex-col items-center pb-2">
|
||||
<UserMenu />
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Level 2: Content Panel */}
|
||||
<div
|
||||
className={`transition-all duration-300 ease-in-out bg-sidebar/95 backdrop-blur-sm shadow-lg overflow-hidden ${
|
||||
activeItem !== null
|
||||
? 'w-[calc(100vw-4rem)] md:w-100 border-r border-sidebar-border'
|
||||
: 'w-0'
|
||||
}`}
|
||||
>
|
||||
<div className="w-[calc(100vw-4rem)] md:w-100 h-full flex flex-col">
|
||||
{activeItemContent && (
|
||||
<>
|
||||
<header className="h-16 flex items-center px-4 font-bold text-lg border-b border-sidebar-border flex-shrink-0">
|
||||
<h2>{activeItemContent.label}</h2>
|
||||
</header>
|
||||
<div className="flex-1 overflow-y-auto p-2">{activeItemContent.children}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { FieldInfo as FieldInfo } from '@shumai/dtos'
|
||||
import React from 'react'
|
||||
import DateField from './fields/date-field'
|
||||
import LongTextField from './fields/long-text-field'
|
||||
import NumberField from './fields/number-field'
|
||||
import RatingField from './fields/rating-field'
|
||||
import SelectField from './fields/select-field'
|
||||
import SelectMultiField from './fields/select-multi-field'
|
||||
import TextField from './fields/text-field'
|
||||
import ToggleField from './fields/toggle-field'
|
||||
|
||||
interface FieldRendererProps {
|
||||
config: FieldInfo['config']
|
||||
value: unknown
|
||||
onSave: (value: unknown) => void
|
||||
readOnly?: boolean
|
||||
}
|
||||
|
||||
const FieldRenderer: React.FC<FieldRendererProps> = (props) => {
|
||||
if (!props.config) {
|
||||
return <div>Unknown Field Type</div>
|
||||
}
|
||||
switch (props.config.type) {
|
||||
case 'text':
|
||||
return (
|
||||
<TextField
|
||||
{...props}
|
||||
value={props.value as string}
|
||||
onSave={props.onSave as (value: string) => void}
|
||||
/>
|
||||
)
|
||||
case 'longText':
|
||||
return (
|
||||
<LongTextField
|
||||
{...props}
|
||||
value={props.value as string}
|
||||
onSave={props.onSave as (value: string) => void}
|
||||
/>
|
||||
)
|
||||
case 'select':
|
||||
return (
|
||||
<SelectField
|
||||
{...props}
|
||||
value={props.value as string}
|
||||
onSave={props.onSave as (value: string) => void}
|
||||
/>
|
||||
)
|
||||
case 'selectMulti':
|
||||
return (
|
||||
<SelectMultiField
|
||||
{...props}
|
||||
value={props.value as string[]}
|
||||
onSave={props.onSave as (value: string[]) => void}
|
||||
/>
|
||||
)
|
||||
case 'rating':
|
||||
return (
|
||||
<RatingField
|
||||
{...props}
|
||||
value={props.value as number}
|
||||
onSave={props.onSave as (value: number) => void}
|
||||
/>
|
||||
)
|
||||
case 'number':
|
||||
return (
|
||||
<NumberField
|
||||
{...props}
|
||||
value={props.value as number}
|
||||
onSave={props.onSave as (value: number | undefined) => void}
|
||||
/>
|
||||
)
|
||||
case 'toggle':
|
||||
return (
|
||||
<ToggleField
|
||||
{...props}
|
||||
value={props.value as boolean}
|
||||
onSave={props.onSave as (value: boolean) => void}
|
||||
/>
|
||||
)
|
||||
case 'date':
|
||||
return (
|
||||
<DateField
|
||||
{...props}
|
||||
value={props.value as string}
|
||||
onSave={props.onSave as (value: string) => void}
|
||||
/>
|
||||
)
|
||||
default:
|
||||
return <div>Unknown Field Type</div>
|
||||
}
|
||||
}
|
||||
|
||||
export default FieldRenderer
|
||||
@@ -0,0 +1,303 @@
|
||||
import { FieldType, type FieldInfo, type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useFieldStore } from '@/ui/stores/fields'
|
||||
import { DragDropProvider, KeyboardSensor, PointerSensor, type DragEndEvent } from '@dnd-kit/react'
|
||||
import { useSortable } from '@dnd-kit/react/sortable'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { InferRequestType, InferResponseType } from 'hono/client'
|
||||
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { arrayMove } from '@/ui/lib/dnd-utils'
|
||||
import { PointerActivationConstraints } from '@dnd-kit/dom'
|
||||
import { ChevronDown, GripVertical, Plus, Search, Settings, Sparkles } from 'lucide-react'
|
||||
import { useMemo, useState } from 'react'
|
||||
|
||||
type SortableFieldItemProps = {
|
||||
field: FieldInfo
|
||||
index: number
|
||||
onVisibilityChange: (fieldId: string, visible: boolean) => void
|
||||
}
|
||||
|
||||
function SortableFieldItem({ field, index, onVisibilityChange }: SortableFieldItemProps) {
|
||||
const { ref, handleRef } = useSortable({
|
||||
id: field.id!,
|
||||
index,
|
||||
})
|
||||
|
||||
return (
|
||||
<div ref={ref} className="flex items-center justify-between p-2 rounded-md hover:bg-muted">
|
||||
<div className="flex items-center gap-2">
|
||||
<div ref={handleRef} className="cursor-grab">
|
||||
<GripVertical className="h-4 w-4 text-muted-foreground" />
|
||||
</div>
|
||||
{field.aiAutofill && <Sparkles className="h-4 w-4 text-muted-foreground" />}
|
||||
<span className="text-sm">{field.config?.name}</span>
|
||||
</div>
|
||||
<Switch
|
||||
checked={field.visible}
|
||||
onCheckedChange={(checked: boolean) => onVisibilityChange(field.id!, checked)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type FieldsManagerProps = {
|
||||
projectId: string
|
||||
onManageFields: () => void
|
||||
onSave?: () => void
|
||||
}
|
||||
|
||||
export function FieldsManager({ projectId, onManageFields, onSave }: FieldsManagerProps) {
|
||||
const { fields, updateFields } = useFieldStore()
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [view, setView] = useState<'list' | 'create'>('list')
|
||||
const [newFieldName, setNewFieldName] = useState('')
|
||||
const [newFieldType, setNewFieldType] = useState<FieldType | ''>('')
|
||||
const [newAiAutofill, setNewAiAutofill] = useState(false)
|
||||
const [newDescription, setNewDescription] = useState('')
|
||||
|
||||
const $patchOrder = client.api.projects[':projectId'].fields.order.$patch
|
||||
const { mutate: updateFieldsOrder } = useMutation<
|
||||
InferResponseType<typeof $patchOrder>,
|
||||
Error,
|
||||
InferRequestType<typeof $patchOrder>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $patchOrder(request)
|
||||
if (!res.ok) throw new Error('Failed to update fields order')
|
||||
return null as unknown as InferResponseType<typeof $patchOrder>
|
||||
},
|
||||
})
|
||||
const $post = client.api.projects[':projectId'].fields.$post
|
||||
const { mutate: createField } = useMutation<
|
||||
InferResponseType<typeof $post>,
|
||||
Error,
|
||||
InferRequestType<typeof $post>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $post(request)
|
||||
if (!res.ok) throw new Error('Failed to create field')
|
||||
return (await res.json()) as MetadataFieldInfo
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
const newField: MetadataFieldInfo = {
|
||||
...(data as MetadataFieldInfo),
|
||||
visible: true,
|
||||
}
|
||||
const newFieldsList = [...fields, newField]
|
||||
updateFields(newFieldsList)
|
||||
setNewFieldName('')
|
||||
|
||||
updateFieldsOrder({
|
||||
param: { projectId: projectId },
|
||||
json: newFieldsList.map((f) => ({
|
||||
fieldId: f.id!,
|
||||
visible: f.visible || false,
|
||||
})),
|
||||
})
|
||||
onSave?.()
|
||||
},
|
||||
})
|
||||
|
||||
const filteredFields = useMemo(
|
||||
() =>
|
||||
fields.filter((field) =>
|
||||
field.config?.name?.toLowerCase().includes(searchQuery.toLowerCase()),
|
||||
),
|
||||
[fields, searchQuery],
|
||||
)
|
||||
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
const { source, target } = event.operation
|
||||
if (source && target && source.id !== target.id) {
|
||||
const oldIndex = fields.findIndex((f) => f.id === source.id)
|
||||
const newIndex = fields.findIndex((f) => f.id === target.id)
|
||||
const newFields = arrayMove(fields, oldIndex, newIndex)
|
||||
updateFields(newFields)
|
||||
updateFieldsOrder({
|
||||
param: { projectId: projectId },
|
||||
json: newFields.map((f: MetadataFieldInfo) => ({
|
||||
fieldId: f.id!,
|
||||
visible: f.visible || false,
|
||||
})),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleVisibilityChange = (fieldId: string, visible: boolean) => {
|
||||
const newFields = fields.map((f) => (f.id === fieldId ? { ...f, visible } : f))
|
||||
updateFields(newFields)
|
||||
updateFieldsOrder({
|
||||
param: { projectId: projectId },
|
||||
json: newFields.map((f) => ({
|
||||
fieldId: f.id!,
|
||||
visible: f.visible || false,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
const handleCreateField = () => {
|
||||
if (!newFieldName || !newFieldType) return
|
||||
createField({
|
||||
param: { projectId: projectId },
|
||||
json: {
|
||||
config: {
|
||||
name: newFieldName,
|
||||
type: newFieldType,
|
||||
},
|
||||
label: newFieldName,
|
||||
aiAutofill: newAiAutofill,
|
||||
description: newDescription,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const visibleCount = fields.filter((f) => f.visible).length
|
||||
|
||||
if (view === 'create') {
|
||||
return (
|
||||
<div className="w-80 p-4">
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="field-name">Name</Label>
|
||||
<Input
|
||||
id="field-name"
|
||||
placeholder="New Field"
|
||||
value={newFieldName}
|
||||
onChange={(e) => setNewFieldName(e.target.value)}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Type</Label>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="w-full justify-between font-normal">
|
||||
{newFieldType ? (
|
||||
<span className="capitalize">{newFieldType.replace(/_/g, ' ')}</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground border-dashed">Select field type</span>
|
||||
)}
|
||||
<ChevronDown className="ml-2 h-4 w-4 opacity-50" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-[--radix-dropdown-menu-trigger-width]">
|
||||
{Object.values(FieldType).map((type) => (
|
||||
<DropdownMenuItem
|
||||
key={type}
|
||||
onClick={() => setNewFieldType(type)}
|
||||
className="capitalize"
|
||||
>
|
||||
{type.replace(/_/g, ' ')}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="field-desc">Description</Label>
|
||||
<Input
|
||||
id="field-desc"
|
||||
placeholder="Description (Optional)"
|
||||
value={newDescription}
|
||||
onChange={(e) => setNewDescription(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch id="ai-autofill" checked={newAiAutofill} onCheckedChange={setNewAiAutofill} />
|
||||
<Label htmlFor="ai-autofill">AI Autofill</Label>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="flex-1"
|
||||
onClick={() => {
|
||||
setView('list')
|
||||
setNewFieldName('')
|
||||
setNewFieldType('')
|
||||
setNewAiAutofill(false)
|
||||
setNewDescription('')
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
className="flex-1"
|
||||
onClick={handleCreateField}
|
||||
disabled={!newFieldName || !newFieldType}
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-80 p-4">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="font-semibold">
|
||||
Fields{' '}
|
||||
<span className="text-muted-foreground text-sm font-normal">
|
||||
({visibleCount} visible)
|
||||
</span>
|
||||
</h3>
|
||||
</div>
|
||||
<div className="relative mb-4">
|
||||
<Search className="absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search fields"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="max-h-60 overflow-y-auto pr-2">
|
||||
<DragDropProvider
|
||||
sensors={[
|
||||
PointerSensor.configure({
|
||||
activationConstraints: [new PointerActivationConstraints.Distance({ value: 8 })],
|
||||
}),
|
||||
KeyboardSensor,
|
||||
]}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
{filteredFields.map((field, index) => (
|
||||
<SortableFieldItem
|
||||
key={field.id}
|
||||
field={field}
|
||||
index={index}
|
||||
onVisibilityChange={handleVisibilityChange}
|
||||
/>
|
||||
))}
|
||||
</DragDropProvider>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 space-y-2">
|
||||
<Button variant="secondary" className="w-full" onClick={onManageFields}>
|
||||
<Settings className="h-4 w-4 mr-2" />
|
||||
Manage Fields
|
||||
</Button>
|
||||
<Button className="w-full" onClick={() => setView('create')}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New Field
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import {
|
||||
addMonths,
|
||||
eachDayOfInterval,
|
||||
endOfMonth,
|
||||
format,
|
||||
getDate,
|
||||
getDay,
|
||||
getHours,
|
||||
getMinutes,
|
||||
getMonth,
|
||||
getYear,
|
||||
isValid,
|
||||
} from 'date-fns'
|
||||
import { ChevronLeft, ChevronRight, Clock } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import type { FieldProps } from './field-types'
|
||||
|
||||
const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOnly }) => {
|
||||
const dateConfig = config?.date
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Parse value or default to today
|
||||
// Replaced parseISO with new Date() to avoid import errors
|
||||
const parsedDate = value ? new Date(value) : new Date()
|
||||
const safeDate = isValid(parsedDate) ? parsedDate : new Date()
|
||||
|
||||
// Calendar State
|
||||
const [viewDate, setViewDate] = useState(safeDate)
|
||||
|
||||
useEffect(() => {
|
||||
if (isEditing && value) {
|
||||
const d = new Date(value)
|
||||
if (isValid(d)) setViewDate(d)
|
||||
}
|
||||
}, [isEditing, value])
|
||||
|
||||
// Click outside to close
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
|
||||
if (isEditing) {
|
||||
setIsEditing(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
}, [isEditing])
|
||||
|
||||
const handleStartEdit = () => {
|
||||
if (!readOnly) {
|
||||
setIsEditing(true)
|
||||
}
|
||||
}
|
||||
|
||||
const getDisplayValue = (isoString: string) => {
|
||||
if (!isoString) return ''
|
||||
const date = new Date(isoString)
|
||||
if (!isValid(date)) return 'Invalid Date'
|
||||
|
||||
let formatStr = 'PPP' // Default Friendly
|
||||
|
||||
if (dateConfig?.displayFormat === 'usa') formatStr = 'MM/dd/yyyy'
|
||||
else if (dateConfig?.displayFormat === 'euro') formatStr = 'dd/MM/yyyy'
|
||||
else if (dateConfig?.displayFormat === 'iso') formatStr = 'yyyy-MM-dd'
|
||||
|
||||
if (dateConfig?.includeTime) {
|
||||
if (dateConfig?.timeFormat === 'twenty_four_hour') {
|
||||
formatStr += ' HH:mm'
|
||||
} else {
|
||||
formatStr += ' p'
|
||||
}
|
||||
}
|
||||
|
||||
let display = format(date, formatStr)
|
||||
if (dateConfig?.displayTimezone) {
|
||||
display += ` (${Intl.DateTimeFormat().resolvedOptions().timeZone})`
|
||||
}
|
||||
return display
|
||||
}
|
||||
|
||||
// Calendar Logic
|
||||
// Replaced startOfMonth with native Date manipulation
|
||||
const monthStart = new Date(viewDate.getFullYear(), viewDate.getMonth(), 1)
|
||||
const monthEnd = endOfMonth(viewDate)
|
||||
const daysInMonth = eachDayOfInterval({ start: monthStart, end: monthEnd })
|
||||
const startDayOfWeek = getDay(monthStart) // 0 = Sunday
|
||||
|
||||
const handleDateClick = (day: Date) => {
|
||||
// Preserve time from current value if exists
|
||||
const newDate = new Date(day)
|
||||
if (dateConfig?.includeTime) {
|
||||
// Replaced setHours/setMinutes with native methods
|
||||
newDate.setHours(getHours(safeDate))
|
||||
newDate.setMinutes(getMinutes(safeDate))
|
||||
}
|
||||
const isoString = newDate.toISOString()
|
||||
onSave(isoString)
|
||||
if (!dateConfig?.includeTime) {
|
||||
setIsEditing(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleTimeChange = (type: 'hour' | 'minute', val: number) => {
|
||||
const newDate = value ? new Date(value) : new Date()
|
||||
if (!isValid(newDate)) newDate.setTime(new Date().getTime())
|
||||
|
||||
if (type === 'hour') newDate.setHours(val)
|
||||
if (type === 'minute') newDate.setMinutes(val)
|
||||
|
||||
const isoString = newDate.toISOString()
|
||||
onSave(isoString)
|
||||
}
|
||||
|
||||
const hours = Array.from({ length: 24 }, (_, i) => i)
|
||||
const minutes = Array.from({ length: 12 }, (_, i) => i * 5) // 0, 5, 10...
|
||||
|
||||
if (isEditing) {
|
||||
return (
|
||||
<div className="relative w-full" ref={containerRef}>
|
||||
<div className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm shadow-sm min-h-[28px] flex items-center">
|
||||
{value ? getDisplayValue(value) : <span className="text-gray-400">Select date...</span>}
|
||||
</div>
|
||||
|
||||
<div className="absolute z-50 top-full left-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-xl flex flex-col md:flex-row overflow-hidden min-w-[280px]">
|
||||
{/* Date Picker */}
|
||||
<div className="p-4 w-64">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
{/* Replaced subMonths with addMonths(-1) */}
|
||||
<button
|
||||
onClick={() => setViewDate(addMonths(viewDate, -1))}
|
||||
className="p-1 hover:bg-gray-100 rounded"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
</button>
|
||||
<span className="font-semibold text-sm">{format(viewDate, 'MMMM yyyy')}</span>
|
||||
<button
|
||||
onClick={() => setViewDate(addMonths(viewDate, 1))}
|
||||
className="p-1 hover:bg-gray-100 rounded"
|
||||
>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-1 text-center text-xs mb-2 text-gray-500">
|
||||
{['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((d) => (
|
||||
<div key={d}>{d}</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-1 text-center text-sm">
|
||||
{Array.from({ length: startDayOfWeek }).map((_, i) => (
|
||||
<div key={`empty-${i}`} />
|
||||
))}
|
||||
{daysInMonth.map((date) => {
|
||||
const valDate = value ? new Date(value) : null
|
||||
const isSelected =
|
||||
valDate &&
|
||||
isValid(valDate) &&
|
||||
getDate(valDate) === getDate(date) &&
|
||||
getMonth(valDate) === getMonth(date) &&
|
||||
getYear(valDate) === getYear(date)
|
||||
|
||||
return (
|
||||
<button
|
||||
key={date.toString()}
|
||||
onClick={() => handleDateClick(date)}
|
||||
className={`w-8 h-8 rounded-full flex items-center justify-center hover:bg-blue-50 transition-colors ${
|
||||
isSelected ? 'bg-blue-50 text-white hover:bg-blue-600' : 'text-gray-700'
|
||||
}`}
|
||||
>
|
||||
{getDate(date)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Time Picker */}
|
||||
{dateConfig?.includeTime && (
|
||||
<div className="border-l border-gray-200 bg-gray-50 w-32 flex flex-col">
|
||||
<div className="p-2 border-b border-gray-200 text-xs font-semibold text-gray-500 flex items-center justify-center gap-1">
|
||||
<Clock className="w-3 h-3" /> Time
|
||||
</div>
|
||||
<div className="flex flex-1 h-64">
|
||||
<div className="flex-1 overflow-y-auto scrollbar-hide border-r border-gray-200">
|
||||
{hours.map((h) => (
|
||||
<div
|
||||
key={h}
|
||||
onClick={() => handleTimeChange('hour', h)}
|
||||
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-gray-200 ${getHours(safeDate) === h ? 'bg-blue-100 font-medium text-blue-700' : ''}`}
|
||||
>
|
||||
{h.toString().padStart(2, '0')}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto scrollbar-hide">
|
||||
{minutes.map((m) => (
|
||||
<div
|
||||
key={m}
|
||||
onClick={() => handleTimeChange('minute', m)}
|
||||
className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-gray-200 ${getMinutes(safeDate) === m ? 'bg-blue-100 font-medium text-blue-700' : ''}`}
|
||||
>
|
||||
{m.toString().padStart(2, '0')}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={handleStartEdit}
|
||||
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded border border-transparent transition-colors ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
|
||||
}`}
|
||||
>
|
||||
{value ? getDisplayValue(value) : <span className="text-gray-400 italic">Empty</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default DateField
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
|
||||
export type FieldConfig = MetadataFieldInfo['config']
|
||||
|
||||
export interface FieldProps<T = unknown> {
|
||||
value: T
|
||||
config: FieldConfig
|
||||
onSave: (value: T) => void
|
||||
readOnly?: boolean
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import type { FieldProps } from './field-types'
|
||||
|
||||
const LongTextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) => {
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const [localValue, setLocalValue] = useState(value || '')
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setLocalValue(value || '')
|
||||
}, [value])
|
||||
|
||||
useEffect(() => {
|
||||
if (isEditing && textareaRef.current) {
|
||||
textareaRef.current.focus()
|
||||
setExpanded(false)
|
||||
}
|
||||
}, [isEditing])
|
||||
|
||||
// Handle click outside to close expanded state
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (
|
||||
expanded &&
|
||||
containerRef.current &&
|
||||
!containerRef.current.contains(event.target as Node)
|
||||
) {
|
||||
setExpanded(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (expanded) {
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
}
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handleClickOutside)
|
||||
}
|
||||
}, [expanded])
|
||||
|
||||
const handleBlur = () => {
|
||||
setIsEditing(false)
|
||||
onSave(localValue)
|
||||
}
|
||||
|
||||
const handlePlaceholderClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
setExpanded(true)
|
||||
}
|
||||
|
||||
const handleOverlayClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (!readOnly) {
|
||||
setIsEditing(true)
|
||||
}
|
||||
}
|
||||
|
||||
if (isEditing) {
|
||||
return (
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={localValue}
|
||||
onChange={(e) => setLocalValue(e.target.value)}
|
||||
onBlur={handleBlur}
|
||||
className="w-full min-h-[80px] p-2 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm resize-none"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="relative w-full text-sm">
|
||||
{/* Placeholder */}
|
||||
<div
|
||||
onClick={handlePlaceholderClick}
|
||||
className={`w-full text-gray-800 rounded border border-transparent transition-all px-2 py-1 line-clamp-2 max-h-[3rem] overflow-hidden ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : 'cursor-pointer'
|
||||
}`}
|
||||
title="Click to expand"
|
||||
>
|
||||
{value ? value : <span className="text-gray-400 italic">Empty</span>}
|
||||
</div>
|
||||
|
||||
{/* Expanded Overlay */}
|
||||
{expanded && (
|
||||
<div
|
||||
onClick={handleOverlayClick}
|
||||
className={`absolute top-0 left-0 w-full min-h-full h-auto z-50 bg-white border border-blue-500 rounded shadow-lg px-2 py-1 whitespace-pre-wrap ${
|
||||
!readOnly ? 'cursor-text' : ''
|
||||
}`}
|
||||
>
|
||||
{value ? value : <span className="text-gray-400 italic">Empty</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default LongTextField
|
||||
@@ -0,0 +1,87 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import type { FieldProps } from './field-types'
|
||||
|
||||
const NumberField: React.FC<FieldProps<number | undefined>> = ({
|
||||
value,
|
||||
config,
|
||||
onSave,
|
||||
readOnly,
|
||||
}) => {
|
||||
const numberConfig = config?.number
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
// Store as string to allow intermediate states like "1." or empty
|
||||
const [localValue, setLocalValue] = useState('')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
setLocalValue(value !== undefined && value !== null ? value.toString() : '')
|
||||
}, [value])
|
||||
|
||||
useEffect(() => {
|
||||
if (isEditing && inputRef.current) {
|
||||
inputRef.current.focus()
|
||||
}
|
||||
}, [isEditing])
|
||||
|
||||
const handleStartEdit = () => {
|
||||
if (!readOnly) {
|
||||
setIsEditing(true)
|
||||
}
|
||||
}
|
||||
|
||||
const handleBlur = () => {
|
||||
setIsEditing(false)
|
||||
if (localValue === '') {
|
||||
onSave(undefined) // Handle empty
|
||||
} else {
|
||||
const num = parseFloat(localValue)
|
||||
onSave(isNaN(num) ? undefined : num)
|
||||
}
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.stopPropagation()
|
||||
inputRef.current?.blur()
|
||||
}
|
||||
}
|
||||
|
||||
const formatNumber = (val: number | undefined) => {
|
||||
if (val === undefined || val === null || isNaN(val)) return ''
|
||||
return val.toFixed(numberConfig?.scale)
|
||||
}
|
||||
|
||||
if (isEditing) {
|
||||
return (
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="number"
|
||||
step={1 / Math.pow(10, numberConfig?.scale || 0)}
|
||||
value={localValue}
|
||||
onChange={(e) => setLocalValue(e.target.value)}
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
onDoubleClick={(e) => e.stopPropagation()}
|
||||
className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm text-left font-mono"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={handleStartEdit}
|
||||
onDoubleClick={(e) => e.stopPropagation()}
|
||||
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded border border-transparent transition-colors text-left font-mono ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
|
||||
}`}
|
||||
>
|
||||
{value !== undefined && value !== null ? (
|
||||
formatNumber(value)
|
||||
) : (
|
||||
<span className="text-gray-400 italic font-sans text-left block">Empty</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default NumberField
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Star } from 'lucide-react'
|
||||
import React, { useState } from 'react'
|
||||
import type { FieldProps } from './field-types'
|
||||
|
||||
const RatingField: React.FC<FieldProps<number>> = ({ value, config, onSave, readOnly }) => {
|
||||
const ratingConfig = config?.rating
|
||||
const max = Math.max(2, Math.min(6, ratingConfig?.maxValue || 5)) // Clamp 2-6
|
||||
const [hoverValue, setHoverValue] = useState<number | null>(null)
|
||||
|
||||
const handleClick = (e: React.MouseEvent, rating: number) => {
|
||||
e.stopPropagation()
|
||||
if (readOnly) return
|
||||
|
||||
let newValue
|
||||
if (value === rating) {
|
||||
newValue = 0 // Toggle off
|
||||
} else {
|
||||
newValue = rating
|
||||
}
|
||||
onSave(newValue)
|
||||
}
|
||||
|
||||
const stars = Array.from({ length: max }, (_, i) => i + 1)
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex items-center gap-1 h-[28px]"
|
||||
onMouseLeave={() => !readOnly && setHoverValue(null)}
|
||||
onDoubleClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{stars.map((star) => {
|
||||
const isFilled = hoverValue !== null ? star <= hoverValue : star <= (value || 0)
|
||||
return (
|
||||
<button
|
||||
key={star}
|
||||
onClick={(e) => handleClick(e, star)}
|
||||
onMouseEnter={() => !readOnly && setHoverValue(star)}
|
||||
className={`focus:outline-none transition-transform ${
|
||||
!readOnly ? 'cursor-pointer hover:scale-110' : 'cursor-default'
|
||||
}`}
|
||||
type="button"
|
||||
disabled={readOnly}
|
||||
>
|
||||
<Star
|
||||
className={`w-5 h-5 transition-colors ${
|
||||
isFilled ? 'fill-yellow-400 text-yellow-400' : 'fill-gray-100 text-gray-300'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default RatingField
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { SelectOption } from '@shumai/dtos'
|
||||
import { ChevronDown, X } from 'lucide-react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import type { FieldProps } from './field-types'
|
||||
|
||||
const SelectField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOnly }) => {
|
||||
const selectConfig = config?.select
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const selectedOption = selectConfig?.options?.find((opt: SelectOption) => opt.id === value)
|
||||
|
||||
// Click outside handler
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
|
||||
if (isEditing) {
|
||||
setIsEditing(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
}, [isEditing])
|
||||
|
||||
const handleStartEdit = () => {
|
||||
if (!readOnly) {
|
||||
setIsEditing(true)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSelect = (optionId: string) => {
|
||||
onSave(optionId)
|
||||
setIsEditing(false)
|
||||
}
|
||||
|
||||
const renderOptionBadge = (option: SelectOption | undefined) => {
|
||||
if (!option) return <span className="text-gray-400 italic">Select an option</span>
|
||||
return (
|
||||
<span
|
||||
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
|
||||
style={{
|
||||
backgroundColor: `${option.color}33`,
|
||||
color: option.color || undefined,
|
||||
}} // 33 is approx 20% opacity hex
|
||||
>
|
||||
{option.displayName}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative w-full" ref={containerRef}>
|
||||
<div
|
||||
onClick={handleStartEdit}
|
||||
className={`flex items-center justify-between w-full min-h-[28px] px-2 py-1 rounded border border-transparent transition-colors ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200 group' : ''
|
||||
}`}
|
||||
>
|
||||
{renderOptionBadge(selectedOption)}
|
||||
{!readOnly && (
|
||||
<ChevronDown className="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isEditing && (
|
||||
<div className="absolute z-50 top-full left-0 mt-1 w-full min-w-[150px] bg-white border border-gray-200 rounded-lg shadow-lg py-1 max-h-60 overflow-auto">
|
||||
<div
|
||||
onClick={() => handleSelect('')}
|
||||
className="px-3 py-2 text-sm text-gray-500 hover:bg-gray-50 cursor-pointer flex items-center gap-2"
|
||||
>
|
||||
<X className="w-3 h-3" /> Clear
|
||||
</div>
|
||||
{selectConfig?.options?.map((option: SelectOption) => (
|
||||
<div
|
||||
key={option.id}
|
||||
onClick={() => handleSelect(option.id)}
|
||||
className="px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center"
|
||||
>
|
||||
<span
|
||||
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
|
||||
style={{
|
||||
backgroundColor: `${option.color}33`,
|
||||
color: option.color || undefined,
|
||||
}}
|
||||
>
|
||||
{option.displayName}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SelectField
|
||||
@@ -0,0 +1,221 @@
|
||||
import { Check } from 'lucide-react'
|
||||
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import type { FieldProps } from './field-types'
|
||||
import type { SelectOption } from '@shumai/dtos'
|
||||
|
||||
const SelectMultiField: React.FC<FieldProps<string[]>> = ({
|
||||
value = [],
|
||||
config,
|
||||
onSave,
|
||||
readOnly,
|
||||
}) => {
|
||||
const selectConfig = config?.selectMulti
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const dropdownRef = useRef<HTMLDivElement>(null)
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const [visibleCount, setVisibleCount] = useState(value.length)
|
||||
|
||||
const selectedOptions =
|
||||
selectConfig?.options?.filter((opt: SelectOption) => (value || []).includes(opt.id)) || []
|
||||
|
||||
// Dynamic calculation for how many items fit in one line
|
||||
useLayoutEffect(() => {
|
||||
if (isEditing || expanded) {
|
||||
// When editing or expanded, we technically don't use visibleCount for rendering
|
||||
// (we render all), but keeping state clean is good.
|
||||
setVisibleCount(selectedOptions.length)
|
||||
return
|
||||
}
|
||||
|
||||
if (containerRef.current) {
|
||||
const containerWidth = containerRef.current.offsetWidth
|
||||
const canvas = document.createElement('canvas')
|
||||
const context = canvas.getContext('2d')
|
||||
if (context) {
|
||||
context.font = '12px ui-sans-serif, system-ui, sans-serif'
|
||||
|
||||
let currentWidth = 0
|
||||
let count = 0
|
||||
const moreBadgeWidth = 28
|
||||
// We use a small buffer to be safe
|
||||
const maxAvailableWidth = containerWidth - moreBadgeWidth
|
||||
|
||||
for (let i = 0; i < selectedOptions.length; i++) {
|
||||
const textWidth = context.measureText(selectedOptions[i].displayName).width
|
||||
const badgeWidth = textWidth + 16 + 4 // 16px padding, 4px gap
|
||||
|
||||
if (currentWidth + badgeWidth > maxAvailableWidth && i < selectedOptions.length - 1) {
|
||||
break
|
||||
}
|
||||
if (i === selectedOptions.length - 1) {
|
||||
if (currentWidth + badgeWidth <= containerWidth) {
|
||||
count++
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
currentWidth += badgeWidth
|
||||
count++
|
||||
}
|
||||
setVisibleCount(count)
|
||||
}
|
||||
}
|
||||
}, [selectedOptions, isEditing, expanded, value])
|
||||
|
||||
// Click outside to close dropdown or expanded view
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
// Check if click is outside both the main container and the dropdown
|
||||
const isOutsideDropdown =
|
||||
!dropdownRef.current || !dropdownRef.current.contains(event.target as Node)
|
||||
const isOutsideContainer =
|
||||
!containerRef.current || !containerRef.current.contains(event.target as Node)
|
||||
|
||||
if (isOutsideDropdown && isOutsideContainer) {
|
||||
if (isEditing) {
|
||||
setIsEditing(false)
|
||||
}
|
||||
if (expanded) {
|
||||
setExpanded(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
}, [isEditing, expanded])
|
||||
|
||||
const toggleOption = (optionId: string) => {
|
||||
const currentVal = value || []
|
||||
let newVal
|
||||
if (currentVal.includes(optionId)) {
|
||||
newVal = currentVal.filter((id) => id !== optionId)
|
||||
} else {
|
||||
newVal = [...currentVal, optionId]
|
||||
}
|
||||
onSave(newVal)
|
||||
}
|
||||
|
||||
const handlePlaceholderClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (isEditing) return
|
||||
|
||||
// "if there is hidden items, first click will expand"
|
||||
const hiddenCount = selectedOptions.length - visibleCount
|
||||
if (!expanded && hiddenCount > 0) {
|
||||
setExpanded(true)
|
||||
} else {
|
||||
// "if there is no hidden items, will change to edit mode"
|
||||
if (!readOnly) {
|
||||
setIsEditing(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleOverlayClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
// "second click (on expanded) will change to edit mode"
|
||||
if (!readOnly) {
|
||||
setIsEditing(true)
|
||||
}
|
||||
}
|
||||
|
||||
const hiddenCount = selectedOptions.length - visibleCount
|
||||
|
||||
return (
|
||||
<div className="relative w-full">
|
||||
{/* Placeholder Display Mode */}
|
||||
<div
|
||||
ref={containerRef}
|
||||
onClick={handlePlaceholderClick}
|
||||
className={`w-full px-1 py-1 flex flex-wrap gap-1 rounded border border-transparent transition-all box-border h-[32px] overflow-hidden ${
|
||||
!readOnly || hiddenCount > 0
|
||||
? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200'
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
{selectedOptions.length === 0 && (
|
||||
<span className="text-gray-400 text-sm italic px-1 pt-0.5">Empty</span>
|
||||
)}
|
||||
|
||||
{/* Render visible items */}
|
||||
{selectedOptions.slice(0, visibleCount).map((option: SelectOption) => (
|
||||
<span
|
||||
key={option.id}
|
||||
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border border-transparent whitespace-nowrap h-[22px]"
|
||||
style={{
|
||||
backgroundColor: `${option.color}33`,
|
||||
color: option.color || undefined,
|
||||
}}
|
||||
>
|
||||
{option.displayName}
|
||||
</span>
|
||||
))}
|
||||
|
||||
{hiddenCount > 0 && (
|
||||
<span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-gray-200 text-gray-600 h-[22px]">
|
||||
+{hiddenCount}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Expanded Overlay Mode */}
|
||||
{expanded && !isEditing && (
|
||||
<div
|
||||
onClick={handleOverlayClick}
|
||||
className={`absolute top-0 left-0 w-full px-1 py-1 flex flex-wrap gap-1 bg-white rounded border border-blue-500 shadow-lg z-50 min-h-[32px] h-auto ${
|
||||
!readOnly ? 'cursor-pointer' : ''
|
||||
}`}
|
||||
>
|
||||
{selectedOptions.length === 0 && (
|
||||
<span className="text-gray-400 text-sm italic px-1 pt-0.5">Empty</span>
|
||||
)}
|
||||
{selectedOptions.map((option: SelectOption) => (
|
||||
<span
|
||||
key={option.id}
|
||||
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border border-transparent whitespace-nowrap h-[22px]"
|
||||
style={{
|
||||
backgroundColor: `${option.color}33`,
|
||||
color: option.color || undefined,
|
||||
}}
|
||||
>
|
||||
{option.displayName}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Edit Mode Dropdown */}
|
||||
{isEditing && (
|
||||
<div
|
||||
ref={dropdownRef}
|
||||
className="absolute z-50 top-full left-0 mt-1 w-64 bg-white border border-gray-200 rounded-lg shadow-xl max-h-60 overflow-auto"
|
||||
>
|
||||
{selectConfig?.options?.map((option: SelectOption) => {
|
||||
const isSelected = (value || []).includes(option.id)
|
||||
return (
|
||||
<div
|
||||
key={option.id}
|
||||
onClick={() => toggleOption(option.id)}
|
||||
className="px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center justify-between"
|
||||
>
|
||||
<span
|
||||
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
|
||||
style={{
|
||||
backgroundColor: `${option.color}33`,
|
||||
color: option.color || undefined,
|
||||
}}
|
||||
>
|
||||
{option.displayName}
|
||||
</span>
|
||||
{isSelected && <Check className="w-4 h-4 text-blue-500" />}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default SelectMultiField
|
||||
@@ -0,0 +1,63 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import type { FieldProps } from './field-types'
|
||||
|
||||
const TextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) => {
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const [localValue, setLocalValue] = useState(value || '')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// Sync with prop updates
|
||||
useEffect(() => {
|
||||
setLocalValue(value || '')
|
||||
}, [value])
|
||||
|
||||
useEffect(() => {
|
||||
if (isEditing && inputRef.current) {
|
||||
inputRef.current.focus()
|
||||
}
|
||||
}, [isEditing])
|
||||
|
||||
const handleStartEdit = () => {
|
||||
if (!readOnly) {
|
||||
setIsEditing(true)
|
||||
}
|
||||
}
|
||||
|
||||
const handleBlur = () => {
|
||||
setIsEditing(false)
|
||||
onSave(localValue)
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
inputRef.current?.blur()
|
||||
}
|
||||
}
|
||||
|
||||
if (isEditing) {
|
||||
return (
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={localValue}
|
||||
onChange={(e) => setLocalValue(e.target.value)}
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={handleStartEdit}
|
||||
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded truncate border border-transparent transition-colors ${
|
||||
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : ''
|
||||
}`}
|
||||
>
|
||||
{value || <span className="text-gray-400 italic">Empty</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default TextField
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
import React from 'react'
|
||||
|
||||
interface FieldProps {
|
||||
value: boolean
|
||||
config: MetadataFieldInfo['config']
|
||||
onSave: (value: boolean) => void
|
||||
readOnly?: boolean
|
||||
}
|
||||
|
||||
const ToggleField: React.FC<FieldProps> = ({ value, onSave, readOnly }) => {
|
||||
// Toggle is instant edit, doesn't really have a separate "Edit mode" UI structure other than interaction.
|
||||
const handleToggle = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
if (!readOnly) {
|
||||
const newValue = !value
|
||||
onSave(newValue)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={handleToggle}
|
||||
className={`flex items-center h-[28px] w-full ${!readOnly ? 'cursor-pointer' : ''}`}
|
||||
>
|
||||
<div
|
||||
className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 ${
|
||||
value ? 'bg-green-500' : 'bg-gray-300'
|
||||
} ${readOnly ? 'opacity-70' : ''}`}
|
||||
>
|
||||
<span
|
||||
className={`inline-block h-3.5 w-3.5 transform rounded-full bg-white transition duration-200 ease-in-out ${
|
||||
value ? 'translate-x-4.5' : 'translate-x-1'
|
||||
}`}
|
||||
style={{ transform: value ? 'translateX(18px)' : 'translateX(4px)' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ToggleField
|
||||
@@ -0,0 +1,288 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import type { ShareLinkInfo } from '@shumai/dtos'
|
||||
import {
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuPortal,
|
||||
} from '@/ui/components/ui/context-menu'
|
||||
import {
|
||||
Download,
|
||||
Edit,
|
||||
FolderPlus,
|
||||
Trash2,
|
||||
UploadCloud,
|
||||
History,
|
||||
FileText,
|
||||
Link,
|
||||
Plus,
|
||||
ArrowRight,
|
||||
Copy,
|
||||
} from 'lucide-react'
|
||||
|
||||
interface FileBrowserContextMenuProps {
|
||||
item: AssetInfo | null
|
||||
selectedIds: Set<string>
|
||||
onRename: (item: AssetInfo) => void
|
||||
onDelete: (items: AssetInfo[]) => void
|
||||
onDownload: (items: AssetInfo[]) => void
|
||||
onRestore: (items: AssetInfo[]) => void
|
||||
onNewFolder: (name: string) => void
|
||||
onUploadFile: () => void
|
||||
onUploadFolder: () => void
|
||||
onNewVersion: (item: AssetInfo) => void
|
||||
onMoveTo: (items: AssetInfo[]) => void
|
||||
onCopyTo: (items: AssetInfo[]) => void
|
||||
folders: AssetInfo[]
|
||||
files: AssetInfo[]
|
||||
isRecentlyDeleted?: boolean
|
||||
onOpenAgentsMd?: (item: AssetInfo | null) => void
|
||||
isShareView?: boolean
|
||||
onRemoveFromShare?: (items: AssetInfo[]) => void
|
||||
shareLinks?: ShareLinkInfo[]
|
||||
onCreateShareLink?: (items: AssetInfo[]) => void
|
||||
onAddToShareLink?: (shareId: string, items: AssetInfo[]) => void
|
||||
}
|
||||
|
||||
export function FileBrowserContextMenu({
|
||||
item,
|
||||
selectedIds,
|
||||
onRename,
|
||||
onDelete,
|
||||
onDownload,
|
||||
onRestore,
|
||||
onNewFolder,
|
||||
onUploadFile,
|
||||
onUploadFolder,
|
||||
onNewVersion,
|
||||
onMoveTo,
|
||||
onCopyTo,
|
||||
folders,
|
||||
files,
|
||||
isRecentlyDeleted,
|
||||
onOpenAgentsMd,
|
||||
isShareView,
|
||||
onRemoveFromShare,
|
||||
shareLinks = [],
|
||||
onCreateShareLink,
|
||||
onAddToShareLink,
|
||||
}: FileBrowserContextMenuProps) {
|
||||
const allItems = [...folders, ...files]
|
||||
const selectedItems = allItems.filter((i) => selectedIds.has(i.id!))
|
||||
const isItemSelected = item && selectedIds.has(item.id!)
|
||||
const itemsToModify = isItemSelected ? selectedItems : item ? [item] : []
|
||||
const itemsToDelete = itemsToModify
|
||||
const itemsToRestore = itemsToModify
|
||||
|
||||
const handleRename = () => {
|
||||
if (item) {
|
||||
onRename(item)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = () => {
|
||||
onDelete(itemsToDelete)
|
||||
}
|
||||
|
||||
const handleDownload = () => {
|
||||
if (isItemSelected) {
|
||||
onDownload(selectedItems)
|
||||
} else if (item) {
|
||||
onDownload([item])
|
||||
}
|
||||
}
|
||||
|
||||
const handleRestore = () => {
|
||||
onRestore(itemsToRestore)
|
||||
}
|
||||
|
||||
if (isShareView) {
|
||||
if (!item) return null
|
||||
return (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem
|
||||
onSelect={() => onRemoveFromShare?.(itemsToModify)}
|
||||
className="text-destructive"
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
<span>Remove from Share</span>
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
)
|
||||
}
|
||||
|
||||
if (isRecentlyDeleted) {
|
||||
if (!item) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onSelect={handleRestore}>
|
||||
<History className="mr-2 h-4 w-4" />
|
||||
<span>Restore</span>
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
)
|
||||
}
|
||||
|
||||
if (!item) {
|
||||
// Right-click on empty area
|
||||
return (
|
||||
<ContextMenuContent
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
}}
|
||||
>
|
||||
<ContextMenuItem onSelect={onUploadFile}>
|
||||
<UploadCloud className="mr-2 h-4 w-4" />
|
||||
<span>Upload File</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={onUploadFolder}>
|
||||
<UploadCloud className="mr-2 h-4 w-4" />
|
||||
<span>Upload Folder</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem
|
||||
onSelect={() => {
|
||||
onNewFolder('New Folder')
|
||||
}}
|
||||
>
|
||||
<FolderPlus className="mr-2 h-4 w-4" />
|
||||
<span>New Folder</span>
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
)
|
||||
}
|
||||
|
||||
const contextMenuContent =
|
||||
isItemSelected && selectedIds.size > 1 ? (
|
||||
<ContextMenuContent
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
}}
|
||||
>
|
||||
<ContextMenuItem onSelect={handleDownload}>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>Download</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
||||
<ArrowRight className="mr-2 h-4 w-4" />
|
||||
<span>Move to</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => onCopyTo(itemsToModify)}>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
<span>Copy to</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={handleDelete} className="text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
<span>Delete</span>
|
||||
</ContextMenuItem>
|
||||
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onSelect={() => onCreateShareLink?.(itemsToModify)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<span>Create Share Link</span>
|
||||
</ContextMenuItem>
|
||||
|
||||
{shareLinks.length > 0 && (
|
||||
<ContextMenuSub>
|
||||
<ContextMenuSubTrigger>
|
||||
<Link className="mr-2 h-4 w-4" />
|
||||
<span>Add to Share Links</span>
|
||||
</ContextMenuSubTrigger>
|
||||
<ContextMenuPortal>
|
||||
<ContextMenuSubContent className="w-48">
|
||||
{shareLinks.map((share) => (
|
||||
<ContextMenuItem
|
||||
key={share.id}
|
||||
onSelect={() => onAddToShareLink?.(share.id, itemsToModify)}
|
||||
>
|
||||
<span className="truncate">{share.name}</span>
|
||||
</ContextMenuItem>
|
||||
))}
|
||||
</ContextMenuSubContent>
|
||||
</ContextMenuPortal>
|
||||
</ContextMenuSub>
|
||||
)}
|
||||
</ContextMenuContent>
|
||||
) : (
|
||||
<ContextMenuContent
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
}}
|
||||
>
|
||||
<ContextMenuItem
|
||||
onSelect={() => {
|
||||
handleRename()
|
||||
}}
|
||||
>
|
||||
<Edit className="mr-2 h-4 w-4" />
|
||||
<span>Rename</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={handleDownload}>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>Download</span>
|
||||
</ContextMenuItem>
|
||||
|
||||
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
||||
<ArrowRight className="mr-2 h-4 w-4" />
|
||||
<span>Move to</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => onCopyTo(itemsToModify)}>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
<span>Copy to</span>
|
||||
</ContextMenuItem>
|
||||
|
||||
{(item.type === 'file' || item.type === 'version_stack') && (
|
||||
<ContextMenuItem onSelect={() => onNewVersion(item)}>
|
||||
<UploadCloud className="mr-2 h-4 w-4" />
|
||||
<span>Create new version</span>
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
|
||||
{item.type === 'folder' && onOpenAgentsMd && (
|
||||
<ContextMenuItem onSelect={() => onOpenAgentsMd(item)}>
|
||||
<FileText className="mr-2 h-4 w-4" />
|
||||
<span>AGENTS.md</span>
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onSelect={handleDelete} className="text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
<span>Delete</span>
|
||||
</ContextMenuItem>
|
||||
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onSelect={() => onCreateShareLink?.(itemsToModify)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<span>Create Share Link</span>
|
||||
</ContextMenuItem>
|
||||
|
||||
{shareLinks.length > 0 && (
|
||||
<ContextMenuSub>
|
||||
<ContextMenuSubTrigger>
|
||||
<Link className="mr-2 h-4 w-4" />
|
||||
<span>Add to Share Links</span>
|
||||
</ContextMenuSubTrigger>
|
||||
<ContextMenuPortal>
|
||||
<ContextMenuSubContent className="w-48">
|
||||
{shareLinks.map((share) => (
|
||||
<ContextMenuItem
|
||||
key={share.id}
|
||||
onSelect={() => onAddToShareLink?.(share.id, itemsToModify)}
|
||||
>
|
||||
<span className="truncate">{share.name}</span>
|
||||
</ContextMenuItem>
|
||||
))}
|
||||
</ContextMenuSubContent>
|
||||
</ContextMenuPortal>
|
||||
</ContextMenuSub>
|
||||
)}
|
||||
</ContextMenuContent>
|
||||
)
|
||||
|
||||
return <>{contextMenuContent}</>
|
||||
}
|
||||
@@ -0,0 +1,960 @@
|
||||
'use client'
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import type { CollectionInfo } from '@shumai/dtos'
|
||||
import type { SearchCondition, SearchSort } from '@shumai/dtos'
|
||||
import type { ShareLinkInfo } from '@shumai/dtos'
|
||||
import type { CreateUploadTaskRequest } from '@shumai/dtos'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import { useFieldStore } from '@/ui/stores/fields'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Download } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { toast } from 'sonner'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import { MoveCopyDialog } from '../move-copy-dialog'
|
||||
import { FileBrowserContextMenu } from './context-menu'
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '../ui/alert-dialog'
|
||||
import { Button } from '../ui/button'
|
||||
import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu'
|
||||
import { FileCard } from './file-card'
|
||||
import { FileListItem } from './file-list-item'
|
||||
import { FolderCard } from './folder-card'
|
||||
import { FileBrowserGridView } from './grid-view'
|
||||
import { FileBrowserListView } from './list-view'
|
||||
import { FileBrowserToolbar } from './toolbar'
|
||||
import { useFileActions } from './use-file-actions'
|
||||
|
||||
interface FileBrowserProps {
|
||||
teamId: string
|
||||
projectId: string
|
||||
assetId: string
|
||||
folders: AssetInfo[]
|
||||
files: AssetInfo[]
|
||||
totalFolders?: number
|
||||
totalFiles?: number
|
||||
selectedItem: AssetInfo | null
|
||||
selectedIds: Set<string>
|
||||
onItemSelect: (item: AssetInfo, event: React.MouseEvent) => void
|
||||
onItemDoubleClick: (item: AssetInfo) => void
|
||||
onSaveField: (fileId: string, fieldId: string, value: unknown) => void
|
||||
displayStyle: 'card' | 'list'
|
||||
onClearSelection: () => void
|
||||
fetchNextFoldersPage: () => void
|
||||
hasNextFoldersPage: boolean
|
||||
isFetchingNextFoldersPage: boolean
|
||||
fetchNextFilesPage: () => void
|
||||
hasNextFilesPage: boolean
|
||||
isFetchingNextFilesPage: boolean
|
||||
isRecentlyDeleted?: boolean
|
||||
filterConditions?: SearchCondition[]
|
||||
onFilterChange?: (conditions: SearchCondition[]) => void
|
||||
sort?: SearchSort
|
||||
onSortChange?: (sort?: SearchSort) => void
|
||||
dragState?: DragState
|
||||
isShareView?: boolean
|
||||
isPublic?: boolean
|
||||
onRemoveFromShare?: (items: AssetInfo[]) => void
|
||||
fieldVisibility?: Record<string, boolean>
|
||||
collection?: CollectionInfo
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
onUpdateCollection?: (updates: { name?: string; filter?: any }) => void
|
||||
rootFolderId?: string
|
||||
}
|
||||
|
||||
type FileWithId = {
|
||||
file: File
|
||||
id: string
|
||||
}
|
||||
|
||||
let filesToUpload: FileWithId[] = []
|
||||
|
||||
export function FileBrowser({
|
||||
teamId,
|
||||
projectId,
|
||||
assetId,
|
||||
folders,
|
||||
files,
|
||||
totalFolders,
|
||||
totalFiles,
|
||||
selectedItem,
|
||||
selectedIds,
|
||||
onItemSelect,
|
||||
onItemDoubleClick,
|
||||
onSaveField,
|
||||
displayStyle,
|
||||
onClearSelection,
|
||||
fetchNextFoldersPage,
|
||||
hasNextFoldersPage,
|
||||
isFetchingNextFoldersPage,
|
||||
fetchNextFilesPage,
|
||||
hasNextFilesPage,
|
||||
isFetchingNextFilesPage,
|
||||
isRecentlyDeleted,
|
||||
filterConditions,
|
||||
onFilterChange,
|
||||
sort,
|
||||
onSortChange,
|
||||
dragState,
|
||||
isShareView,
|
||||
isPublic,
|
||||
onRemoveFromShare,
|
||||
fieldVisibility,
|
||||
collection,
|
||||
onUpdateCollection,
|
||||
rootFolderId,
|
||||
}: FileBrowserProps) {
|
||||
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
|
||||
const [moveCopyMode, setMoveCopyMode] = useState<'move' | 'copy' | null>(null)
|
||||
const [itemsToMoveCopy, setItemsToMoveCopy] = useState<AssetInfo[]>([])
|
||||
const queryClient = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const { data: shareLinksData } = useQuery({
|
||||
queryKey: ['shares', teamId, projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].shares.$get({
|
||||
param: { projectId },
|
||||
query: { first: '100' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch share links')
|
||||
return (await res.json()) as unknown as { data: ShareLinkInfo[] }
|
||||
},
|
||||
enabled: !!teamId && !!projectId && !isPublic,
|
||||
})
|
||||
|
||||
const $reparent = client.api.projects[':projectId'].reparent.$post
|
||||
const { mutate: reparentAssets } = useMutation<
|
||||
InferResponseType<typeof $reparent, 204>,
|
||||
Error,
|
||||
InferRequestType<typeof $reparent>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $reparent(request)
|
||||
if (!res.ok) throw new Error('Failed to move assets')
|
||||
return null as unknown as InferResponseType<typeof $reparent, 204>
|
||||
},
|
||||
})
|
||||
|
||||
const $copy = client.api.projects[':projectId'].copy.$post
|
||||
const { mutate: copyAssets } = useMutation<
|
||||
InferResponseType<typeof $copy, 204>,
|
||||
Error,
|
||||
InferRequestType<typeof $copy>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $copy(request)
|
||||
if (!res.ok) throw new Error('Failed to copy assets')
|
||||
return null as unknown as InferResponseType<typeof $copy, 204>
|
||||
},
|
||||
})
|
||||
|
||||
const handleMoveCopyConfirm = async (targetFolderId: string, withComments: boolean) => {
|
||||
const assetIds = itemsToMoveCopy.map((i) => i.id!)
|
||||
if (moveCopyMode === 'move') {
|
||||
reparentAssets(
|
||||
{
|
||||
param: { projectId },
|
||||
json: { newParentId: targetFolderId, assetIds },
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success(`Successfully moved ${assetIds.length} item(s)`, {
|
||||
action: {
|
||||
label: 'Go to folder',
|
||||
onClick: () => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
params: { projectId, folderId: targetFolderId },
|
||||
})
|
||||
},
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders', teamId] })
|
||||
setMoveCopyMode(null)
|
||||
setItemsToMoveCopy([])
|
||||
onClearSelection()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
},
|
||||
)
|
||||
} else {
|
||||
copyAssets(
|
||||
{
|
||||
param: { projectId },
|
||||
json: { newParentId: targetFolderId, assetIds, withComments },
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success(`Successfully copied ${assetIds.length} item(s)`, {
|
||||
action: {
|
||||
label: 'Go to folder',
|
||||
onClick: () => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
params: { projectId, folderId: targetFolderId },
|
||||
})
|
||||
},
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders', teamId] })
|
||||
setMoveCopyMode(null)
|
||||
setItemsToMoveCopy([])
|
||||
onClearSelection()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const { mutate: createShareLink } = useMutation({
|
||||
mutationFn: async (items: AssetInfo[]) => {
|
||||
const name =
|
||||
items.length === 1
|
||||
? items[0].name
|
||||
: new Date().toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
})
|
||||
|
||||
const res = await client.api.projects[':projectId'].shares.$post({
|
||||
param: { projectId },
|
||||
json: { name },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to create share link')
|
||||
const share = await res.json()
|
||||
|
||||
// Add assets to the new share link
|
||||
const assetsRes = await client.api.shares[':shareId'].assets.$post({
|
||||
param: { shareId: share.id },
|
||||
json: { assetIds: items.map((i) => i.id!) },
|
||||
})
|
||||
if (!assetsRes.ok) throw new Error('Failed to add assets to share link')
|
||||
|
||||
return share
|
||||
},
|
||||
onSuccess: (share) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shares', teamId, projectId] })
|
||||
toast.success('Share link created', {
|
||||
action: {
|
||||
label: 'View',
|
||||
onClick: () =>
|
||||
navigate({
|
||||
to: '/projects/$projectId/shares/$shareId',
|
||||
params: { projectId, shareId: share.id },
|
||||
}),
|
||||
},
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const { mutate: addToShareLink } = useMutation({
|
||||
mutationFn: async ({ shareId, items }: { shareId: string; items: AssetInfo[] }) => {
|
||||
const res = await client.api.shares[':shareId'].assets.$post({
|
||||
param: { shareId },
|
||||
json: { assetIds: items.map((i) => i.id!) },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to add assets')
|
||||
return { shareId }
|
||||
},
|
||||
onSuccess: ({ shareId }) => {
|
||||
toast.success('Added to share link', {
|
||||
action: {
|
||||
label: 'View',
|
||||
onClick: () =>
|
||||
navigate({
|
||||
to: '/projects/$projectId/shares/$shareId',
|
||||
params: { projectId, shareId },
|
||||
}),
|
||||
},
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const handleCreateShareLink = (items: AssetInfo[]) => {
|
||||
createShareLink(items)
|
||||
}
|
||||
|
||||
const handleAddToShareLink = (shareId: string, items: AssetInfo[]) => {
|
||||
addToShareLink({ shareId, items })
|
||||
}
|
||||
|
||||
const {
|
||||
editingItemId,
|
||||
setEditingItemId,
|
||||
handleNewFolder,
|
||||
handleDelete,
|
||||
handleRename,
|
||||
handleRestore,
|
||||
handleDownload,
|
||||
handleAction,
|
||||
onRenameSubmit,
|
||||
isDeleteDialogOpen,
|
||||
setIsDeleteDialogOpen,
|
||||
confirmDelete,
|
||||
} = useFileActions({
|
||||
teamId,
|
||||
projectId,
|
||||
assetId,
|
||||
folders,
|
||||
files,
|
||||
selectedIds,
|
||||
})
|
||||
|
||||
const $confirmUpload = client.api.teams[':teamId'].upload.tasks[':taskId'].$patch
|
||||
const { mutateAsync: confirmUpload } = useMutation<
|
||||
InferResponseType<typeof $confirmUpload>,
|
||||
Error,
|
||||
InferRequestType<typeof $confirmUpload>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $confirmUpload(request)
|
||||
if (!res.ok) throw new Error('Failed to confirm upload')
|
||||
return (await res.json()) as InferResponseType<typeof $confirmUpload>
|
||||
},
|
||||
})
|
||||
|
||||
const $createUploadTask = client.api.teams[':teamId'].upload.tasks.$post
|
||||
const { mutate: createUploadTaskMutation } = useMutation<
|
||||
InferResponseType<typeof $createUploadTask>,
|
||||
Error,
|
||||
InferRequestType<typeof $createUploadTask>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $createUploadTask(request)
|
||||
if (!res.ok) throw new Error('Failed to create upload task')
|
||||
return (await res.json()) as InferResponseType<typeof $createUploadTask>
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
// The RPC client returns an object that we cast to the expected type
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await uploadFiles(filesToUpload, data.presignedUrls as any, data.taskId!)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const incrementUploading = useUploadStore((state) => state.increment)
|
||||
const decrementUploading = useUploadStore((state) => state.decrement)
|
||||
const { fields } = useFieldStore()
|
||||
const displayedFields = useMemo(() => {
|
||||
if (!isShareView) return fields.filter((f) => f.visible)
|
||||
return fields.filter((f) => fieldVisibility?.[f.id!])
|
||||
}, [fields, isShareView, fieldVisibility])
|
||||
|
||||
const [foldersExpanded, setFoldersExpanded] = React.useState(true)
|
||||
const [filesExpanded, setFilesExpanded] = React.useState(true)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const folderInputRef = useRef<HTMLInputElement>(null)
|
||||
const newVersionInputRef = useRef<HTMLInputElement>(null)
|
||||
const [targetVersionFileId, setTargetVersionFileId] = useState<string | null>(null)
|
||||
const fileContextMenu = useRef(false)
|
||||
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const { ref: foldersRef, inView: foldersInView } = useInView()
|
||||
const { ref: filesRef, inView: filesInView } = useInView()
|
||||
|
||||
useEffect(() => {
|
||||
if (foldersInView && hasNextFoldersPage && !isFetchingNextFoldersPage) {
|
||||
fetchNextFoldersPage()
|
||||
}
|
||||
}, [foldersInView, hasNextFoldersPage, isFetchingNextFoldersPage, fetchNextFoldersPage])
|
||||
|
||||
useEffect(() => {
|
||||
if (filesInView && hasNextFilesPage && !isFetchingNextFilesPage) {
|
||||
fetchNextFilesPage()
|
||||
}
|
||||
}, [filesInView, hasNextFilesPage, isFetchingNextFilesPage, fetchNextFilesPage])
|
||||
|
||||
const foldersSize = folders.reduce((acc, f) => acc + (f.sizeByte || 0), 0)
|
||||
const filesSize = files.reduce((acc, f) => acc + (f.sizeByte || 0), 0)
|
||||
|
||||
const formatCount = (count: number, isFile: boolean) => {
|
||||
const isNameFilter = filterConditions?.some(
|
||||
(c) => c.field === 'name' && c.operator === 'contains',
|
||||
)
|
||||
if (isNameFilter && count === 10001) {
|
||||
return `10000+ ${isFile ? 'Asset' : 'Folder'}s`
|
||||
}
|
||||
return `${count} ${isFile ? 'Asset' : 'Folder'}${count !== 1 ? 's' : ''}`
|
||||
}
|
||||
|
||||
const handleEmptyAreaClick = (e: React.MouseEvent) => {
|
||||
const target = e.target as HTMLElement
|
||||
// Clear selection if we didn't click on a card/row, button, or other interactive element
|
||||
// Also ignore clicks on context menu items (which might bubble via React portals)
|
||||
if (target.closest('[role="menuitem"]') || target.closest('[data-radix-menu-content]')) {
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
target === e.currentTarget ||
|
||||
target.closest('.empty-area') ||
|
||||
(!target.closest('.group') &&
|
||||
!target.closest('button') &&
|
||||
!target.closest('a') &&
|
||||
!target.closest('input'))
|
||||
) {
|
||||
onClearSelection()
|
||||
setEditingItemId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const onContextMenu = (_e: React.MouseEvent, item?: AssetInfo) => {
|
||||
if (item === undefined) {
|
||||
// Two possibilities when item is undefined:
|
||||
// 1. User right-clicked on empty space → fileContextMenu should be false.
|
||||
// 2. A right-click on a file/folder was already handled above → fileContextMenu is true.
|
||||
// In that case, toggle it off; otherwise clear the selected item.
|
||||
if (fileContextMenu.current) {
|
||||
fileContextMenu.current = false
|
||||
} else {
|
||||
setContextMenuItem(null)
|
||||
}
|
||||
} else {
|
||||
// User right-clicked a file or folder.
|
||||
// Mark that this click is for a file context menu, store the item,
|
||||
// and let the event bubble so the empty-area handler manages positioning.
|
||||
fileContextMenu.current = true
|
||||
setContextMenuItem(item ?? null)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const renderItem = (item: AssetInfo, columnSizing?: Record<string, number>) => {
|
||||
const effectiveType = item.type === 'symlink' ? item.targetType || 'file' : item.type
|
||||
const props = {
|
||||
teamId,
|
||||
item: item,
|
||||
isSelected: selectedItem?.id === item.id,
|
||||
isChecked: selectedIds.has(item.id!),
|
||||
isEditing: editingItemId === item.id,
|
||||
onSelect: onItemSelect,
|
||||
onDoubleClick: onItemDoubleClick,
|
||||
onContextMenu: onContextMenu,
|
||||
onDragStart: () => {}, // Handled by dnd-kit
|
||||
onDrop: () => {}, // Handled by dnd-kit
|
||||
onRename: (newName: string) => onRenameSubmit(item, newName),
|
||||
onFinishEditing: () => setEditingItemId(null),
|
||||
onSaveField: (fieldId: string, value: unknown) => {
|
||||
onSaveField(item.id!, fieldId, value)
|
||||
},
|
||||
dragState,
|
||||
onAction: (action: string, item: AssetInfo) => {
|
||||
if (isShareView) {
|
||||
if (action === 'remove-from-share') {
|
||||
const isSelected = selectedIds.has(item.id!)
|
||||
const targetItems = isSelected
|
||||
? [...folders, ...files].filter((i) => selectedIds.has(i.id!))
|
||||
: [item]
|
||||
onRemoveFromShare?.(targetItems)
|
||||
}
|
||||
return
|
||||
}
|
||||
handleAction(action as 'rename' | 'delete' | 'download' | 'restore', item)
|
||||
},
|
||||
isRecentlyDeleted,
|
||||
selectedCount: selectedIds.size,
|
||||
isShareView,
|
||||
fields: displayedFields,
|
||||
}
|
||||
if (displayStyle === 'card') {
|
||||
if (effectiveType === 'folder') return <FolderCard key={item.id} {...props} />
|
||||
if (effectiveType === 'file' || effectiveType === 'version_stack')
|
||||
return <FileCard key={item.id} {...props} />
|
||||
}
|
||||
return <FileListItem key={item.id} {...props} columnSizing={columnSizing} />
|
||||
}
|
||||
|
||||
const selectedCount = selectedIds.size
|
||||
const selectedFolders = Array.from(selectedIds).filter((id) =>
|
||||
folders.find((item) => item.id === id),
|
||||
).length
|
||||
const selectedFiles = Array.from(selectedIds).filter((id) =>
|
||||
files.find((item) => item.id === id),
|
||||
).length
|
||||
|
||||
const handleUploadFilesClick = () => {
|
||||
fileInputRef.current?.click()
|
||||
}
|
||||
|
||||
const handleUploadFolderClick = () => {
|
||||
folderInputRef.current?.click()
|
||||
}
|
||||
|
||||
const uploadFiles = async (
|
||||
files: FileWithId[],
|
||||
presignedUrls: { id?: string; url?: string; fileId?: string }[],
|
||||
taskId: string,
|
||||
) => {
|
||||
const uploadUrlMap = presignedUrls?.reduce(
|
||||
(
|
||||
acc: Record<string, { url: string; fileId: string }>,
|
||||
item: { id?: string; url?: string; fileId?: string },
|
||||
) => {
|
||||
if (item.id) {
|
||||
acc[item.id] = {
|
||||
url: item.url || '',
|
||||
fileId: item.fileId || '',
|
||||
}
|
||||
}
|
||||
return acc
|
||||
},
|
||||
{},
|
||||
)
|
||||
if (!uploadUrlMap) return
|
||||
|
||||
const concurrencyLimit = 5
|
||||
const filesToUpload = [...files]
|
||||
|
||||
const uploadNext = async () => {
|
||||
while (filesToUpload.length > 0) {
|
||||
const file = filesToUpload.shift()
|
||||
if (file) {
|
||||
const uploadInfo = uploadUrlMap[file.id]
|
||||
if (uploadInfo && uploadInfo.url) {
|
||||
incrementUploading()
|
||||
try {
|
||||
try {
|
||||
const resp = await fetch(uploadInfo.url, {
|
||||
method: 'PUT',
|
||||
body: file.file,
|
||||
headers: {
|
||||
'Content-Type': file.file.type,
|
||||
},
|
||||
})
|
||||
|
||||
if (resp.ok) {
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
},
|
||||
})
|
||||
} else {
|
||||
toast.error(`Failed to upload file: ${file.file.name}`)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
errorMessage: `upload failed with status: ${resp.status}`,
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(`Failed to upload file: ${file.file.name}`)
|
||||
await confirmUpload({
|
||||
param: { teamId: teamId, taskId: taskId },
|
||||
json: {
|
||||
fileId: uploadInfo.fileId,
|
||||
errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`,
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
return
|
||||
}
|
||||
} finally {
|
||||
decrementUploading()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const activeUploaders = Array(concurrencyLimit)
|
||||
.fill(null)
|
||||
.map(() => uploadNext())
|
||||
await Promise.all(activeUploaders)
|
||||
}
|
||||
|
||||
const processAndUploadFiles = useCallback(
|
||||
(files: FileList | File[], overrideParentId?: string) => {
|
||||
if (!files || files.length === 0) return
|
||||
|
||||
const fileWithIds: FileWithId[] = []
|
||||
const root: CreateUploadTaskRequest['files'] = []
|
||||
const directories = new Map<string, CreateUploadTaskRequest['files']>()
|
||||
|
||||
for (const file of files) {
|
||||
const path = (file.webkitRelativePath || file.name).split('/')
|
||||
if (path.some((part) => part.startsWith('.'))) {
|
||||
continue
|
||||
}
|
||||
const fileName = path.pop()!
|
||||
let currentLevel = root
|
||||
let currentPath = ''
|
||||
for (const dir of path) {
|
||||
currentPath = `${currentPath}/${dir}`
|
||||
if (!directories.has(currentPath)) {
|
||||
const newDir: CreateUploadTaskRequest['files'] = []
|
||||
const parentDir = {
|
||||
name: dir,
|
||||
type: 'folder' as const,
|
||||
id: crypto.randomUUID(),
|
||||
children: newDir,
|
||||
size: 0,
|
||||
}
|
||||
currentLevel.push(parentDir)
|
||||
directories.set(currentPath, newDir)
|
||||
currentLevel = newDir
|
||||
} else {
|
||||
currentLevel = directories.get(currentPath)!
|
||||
}
|
||||
}
|
||||
const fileWithId = { file, id: crypto.randomUUID() }
|
||||
fileWithIds.push(fileWithId)
|
||||
currentLevel.push({
|
||||
name: fileName,
|
||||
size: file.size,
|
||||
type: 'file',
|
||||
id: fileWithId.id,
|
||||
children: [],
|
||||
mediaType: file.type,
|
||||
})
|
||||
}
|
||||
filesToUpload = fileWithIds
|
||||
createUploadTaskMutation({
|
||||
param: { teamId: teamId },
|
||||
json: {
|
||||
parentId: overrideParentId || assetId,
|
||||
files: root,
|
||||
},
|
||||
})
|
||||
},
|
||||
[assetId, createUploadTaskMutation, teamId],
|
||||
)
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
processAndUploadFiles(event.target.files!)
|
||||
}
|
||||
|
||||
const handleNewVersionClick = (item: AssetInfo) => {
|
||||
setTargetVersionFileId(item.id!)
|
||||
newVersionInputRef.current?.click()
|
||||
}
|
||||
|
||||
const handleNewVersionFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
if (event.target.files && targetVersionFileId) {
|
||||
processAndUploadFiles(event.target.files, targetVersionFileId)
|
||||
setTargetVersionFileId(null)
|
||||
// Reset input
|
||||
event.target.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const handlePaste = useCallback(
|
||||
(e: React.ClipboardEvent | ClipboardEvent) => {
|
||||
if (isShareView) return
|
||||
if (!e.clipboardData) return
|
||||
const items = e.clipboardData.items
|
||||
const files: File[] = []
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]
|
||||
if (item.kind === 'file') {
|
||||
const file = item.getAsFile()
|
||||
if (file) {
|
||||
// If it's a raw image without a real name (e.g. "image.png" from clipboard image)
|
||||
if (file.name === 'image.png' && file.type.startsWith('image/')) {
|
||||
const timestamp = new Date()
|
||||
.toISOString()
|
||||
.replace(/[:.]/g, '')
|
||||
.replace('T', '_')
|
||||
.substring(0, 15)
|
||||
const ext = file.type.split('/')[1] || 'png'
|
||||
const newFile = new File([file], `pasted_image_${timestamp}.${ext}`, {
|
||||
type: file.type,
|
||||
})
|
||||
files.push(newFile)
|
||||
} else {
|
||||
files.push(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (files.length > 0) {
|
||||
processAndUploadFiles(files)
|
||||
}
|
||||
},
|
||||
[processAndUploadFiles],
|
||||
)
|
||||
|
||||
// Add global paste listener if browser is active
|
||||
useEffect(() => {
|
||||
const onGlobalPaste = (e: ClipboardEvent) => {
|
||||
if (isShareView) return
|
||||
// Don't intercept if user is typing in an input
|
||||
if (
|
||||
document.activeElement &&
|
||||
(document.activeElement.tagName === 'INPUT' ||
|
||||
document.activeElement.tagName === 'TEXTAREA' ||
|
||||
(document.activeElement as HTMLElement).isContentEditable)
|
||||
) {
|
||||
return
|
||||
}
|
||||
handlePaste(e)
|
||||
}
|
||||
|
||||
window.addEventListener('paste', onGlobalPaste)
|
||||
return () => {
|
||||
window.removeEventListener('paste', onGlobalPaste)
|
||||
}
|
||||
}, [handlePaste, isShareView])
|
||||
|
||||
const renderContent = () => {
|
||||
return (
|
||||
<ContextMenu modal={false}>
|
||||
<ContextMenuTrigger asChild disabled={isShareView || isPublic}>
|
||||
<div
|
||||
className="flex-1 bg-background relative flex flex-col min-h-0 overflow-hidden"
|
||||
onContextMenu={(e) => onContextMenu(e)}
|
||||
>
|
||||
{!isShareView && !isPublic && onFilterChange && onSortChange && (
|
||||
<FileBrowserToolbar
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
assetId={assetId}
|
||||
fields={fields || []}
|
||||
filterConditions={filterConditions || []}
|
||||
onFilterChange={onFilterChange}
|
||||
sort={sort}
|
||||
onSortChange={onSortChange}
|
||||
isRecentlyDeleted={isRecentlyDeleted}
|
||||
collection={collection}
|
||||
onUpdateCollection={onUpdateCollection}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
ref={scrollContainerRef}
|
||||
className="flex-1 overflow-y-auto min-h-0 relative flex flex-col"
|
||||
>
|
||||
{displayStyle === 'list' ? (
|
||||
<FileBrowserListView
|
||||
folders={folders}
|
||||
files={files}
|
||||
totalFolders={totalFolders}
|
||||
totalFiles={totalFiles}
|
||||
selectedItem={selectedItem}
|
||||
selectedIds={selectedIds}
|
||||
displayedFields={displayedFields}
|
||||
onItemSelect={onItemSelect}
|
||||
onItemDoubleClick={onItemDoubleClick}
|
||||
renderItem={renderItem}
|
||||
foldersExpanded={foldersExpanded}
|
||||
setFoldersExpanded={setFoldersExpanded}
|
||||
filesExpanded={filesExpanded}
|
||||
setFilesExpanded={setFilesExpanded}
|
||||
foldersRef={foldersRef}
|
||||
filesRef={filesRef}
|
||||
hasNextFoldersPage={hasNextFoldersPage}
|
||||
hasNextFilesPage={hasNextFilesPage}
|
||||
formatCount={formatCount}
|
||||
formatSize={formatSize}
|
||||
foldersSize={foldersSize}
|
||||
filesSize={filesSize}
|
||||
handleEmptyAreaClick={handleEmptyAreaClick}
|
||||
dragState={dragState}
|
||||
sort={sort}
|
||||
/>
|
||||
) : (
|
||||
<FileBrowserGridView
|
||||
folders={folders}
|
||||
files={files}
|
||||
totalFolders={totalFolders}
|
||||
totalFiles={totalFiles}
|
||||
renderItem={renderItem}
|
||||
foldersExpanded={foldersExpanded}
|
||||
setFoldersExpanded={setFoldersExpanded}
|
||||
filesExpanded={filesExpanded}
|
||||
setFilesExpanded={setFilesExpanded}
|
||||
foldersRef={foldersRef}
|
||||
filesRef={filesRef}
|
||||
hasNextFoldersPage={hasNextFoldersPage}
|
||||
hasNextFilesPage={hasNextFilesPage}
|
||||
formatCount={formatCount}
|
||||
formatSize={formatSize}
|
||||
foldersSize={foldersSize}
|
||||
filesSize={filesSize}
|
||||
handleEmptyAreaClick={handleEmptyAreaClick}
|
||||
dragState={dragState}
|
||||
sort={sort}
|
||||
/>
|
||||
)}
|
||||
|
||||
{(isFetchingNextFoldersPage || isFetchingNextFilesPage) && (
|
||||
<div className="flex justify-center items-center p-4">
|
||||
<p>Loading more...</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{folders.length === 0 &&
|
||||
files.length === 0 &&
|
||||
!isFetchingNextFoldersPage &&
|
||||
!isFetchingNextFilesPage && (
|
||||
<div className="empty-area flex h-full items-center justify-center text-sm text-muted-foreground">
|
||||
This folder is empty
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{selectedCount > 0 && (
|
||||
<div className="border-t border-border bg-card px-4 py-3 flex items-center justify-between shrink-0">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{selectedFolders > 0 && selectedFiles > 0 && (
|
||||
<span>
|
||||
{selectedFolders} folder
|
||||
{selectedFolders !== 1 ? 's' : ''}, {selectedFiles} file
|
||||
{selectedFiles !== 1 ? 's' : ''} selected
|
||||
</span>
|
||||
)}
|
||||
{selectedFolders > 0 && selectedFiles === 0 && (
|
||||
<span>
|
||||
{selectedFolders} folder
|
||||
{selectedFolders !== 1 ? 's' : ''} selected
|
||||
</span>
|
||||
)}
|
||||
{selectedFolders === 0 && selectedFiles > 0 && (
|
||||
<span>
|
||||
{selectedFiles} file{selectedFiles !== 1 ? 's' : ''} selected
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
handleDownload([...folders, ...files].filter((i) => selectedIds.has(i.id!)))
|
||||
}
|
||||
className="gap-2"
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
Download
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
<FileBrowserContextMenu
|
||||
item={contextMenuItem}
|
||||
selectedIds={selectedIds}
|
||||
folders={folders}
|
||||
files={files}
|
||||
onRename={handleRename}
|
||||
onDelete={handleDelete}
|
||||
onDownload={handleDownload}
|
||||
onNewFolder={handleNewFolder}
|
||||
onUploadFile={handleUploadFilesClick}
|
||||
onUploadFolder={handleUploadFolderClick}
|
||||
onNewVersion={handleNewVersionClick}
|
||||
onMoveTo={(items) => {
|
||||
setItemsToMoveCopy(items)
|
||||
setMoveCopyMode('move')
|
||||
}}
|
||||
onCopyTo={(items) => {
|
||||
setItemsToMoveCopy(items)
|
||||
setMoveCopyMode('copy')
|
||||
}}
|
||||
onRestore={handleRestore}
|
||||
isRecentlyDeleted={isRecentlyDeleted}
|
||||
shareLinks={shareLinksData?.data ?? []}
|
||||
onCreateShareLink={handleCreateShareLink}
|
||||
onAddToShareLink={handleAddToShareLink}
|
||||
/>
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
multiple
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
<input
|
||||
type="file"
|
||||
ref={folderInputRef}
|
||||
multiple
|
||||
/* @ts-expect-error - webkitdirectory is not in the type definition */
|
||||
webkitdirectory="true"
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
<input
|
||||
type="file"
|
||||
ref={newVersionInputRef}
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleNewVersionFileChange}
|
||||
/>
|
||||
{renderContent()}
|
||||
|
||||
{moveCopyMode && (
|
||||
<MoveCopyDialog
|
||||
isOpen={!!moveCopyMode}
|
||||
onClose={() => setMoveCopyMode(null)}
|
||||
onConfirm={handleMoveCopyConfirm}
|
||||
mode={moveCopyMode}
|
||||
teamId={teamId}
|
||||
currentProjectId={projectId}
|
||||
/>
|
||||
)}
|
||||
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Asset?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Deleted items can be recovered for 30 days before being permanently deleted.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => {
|
||||
confirmDelete()
|
||||
}}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
import type { AssetInfo, FieldValueInfo } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { formatTimeAgo } from '@/ui/lib/time'
|
||||
import { useDraggable, useDroppable } from '@dnd-kit/react'
|
||||
import { Download, Edit, History, MoreHorizontal, Trash2 } from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import FieldRenderer from '../field-renderer'
|
||||
import { FilePreview } from './file-preview'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import { EditableText } from '@/ui/components/ui/editable-text'
|
||||
import { Skeleton } from '@/ui/components/ui/skeleton'
|
||||
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
|
||||
interface FileCardProps {
|
||||
teamId?: string
|
||||
item: AssetInfo
|
||||
isSelected: boolean
|
||||
isChecked: boolean
|
||||
isEditing: boolean
|
||||
onSelect: (item: AssetInfo, event: React.MouseEvent) => void
|
||||
onDoubleClick: (item: AssetInfo) => void
|
||||
onContextMenu: (e: React.MouseEvent, item: AssetInfo) => void
|
||||
// Deprecated manual drag handlers replaced by dnd-kit
|
||||
onDragStart: (item: AssetInfo) => void
|
||||
onDrop: (target: AssetInfo) => void
|
||||
onRename: (newName: string) => void
|
||||
onFinishEditing: () => void
|
||||
onSaveField: (fieldId: string, value: unknown) => void
|
||||
dragState?: DragState
|
||||
disabled?: boolean
|
||||
onAction?: (
|
||||
action: 'rename' | 'delete' | 'download' | 'restore' | 'remove-from-share',
|
||||
item: AssetInfo,
|
||||
) => void
|
||||
isRecentlyDeleted?: boolean
|
||||
selectedCount?: number
|
||||
fields: MetadataFieldInfo[]
|
||||
isShareView?: boolean
|
||||
}
|
||||
|
||||
export function FileCard({
|
||||
teamId,
|
||||
item,
|
||||
isSelected,
|
||||
isChecked,
|
||||
isEditing,
|
||||
onSelect,
|
||||
onDoubleClick,
|
||||
onContextMenu,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
onDragStart: _onDragStart,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
onDrop: _onDrop,
|
||||
onRename,
|
||||
onFinishEditing,
|
||||
onSaveField,
|
||||
dragState,
|
||||
disabled,
|
||||
onAction,
|
||||
isRecentlyDeleted,
|
||||
selectedCount,
|
||||
fields,
|
||||
isShareView,
|
||||
}: FileCardProps) {
|
||||
const [name, setName] = useState(item.name)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const shouldPoll =
|
||||
(item.type === 'file' || item.type === 'version_stack') &&
|
||||
!!teamId &&
|
||||
(item.status === 'uploading' || item.status === 'uploaded' || item.status === 'processing')
|
||||
|
||||
const { data: polledItem } = useQuery({
|
||||
queryKey: ['file', teamId, item.id],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.files[':fileId'].$get({
|
||||
param: { fileId: item.id || '' },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch file')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
},
|
||||
enabled: shouldPoll,
|
||||
refetchInterval: (query: unknown) => {
|
||||
const data = (query as { state: { data: { status?: string } } }).state.data
|
||||
return data?.status === 'processed' ? false : 1000
|
||||
},
|
||||
})
|
||||
|
||||
const displayItem = polledItem || item
|
||||
|
||||
// dnd-kit hooks
|
||||
const { ref: setDraggableRef, isDragging: isDraggableDragging } = useDraggable({
|
||||
id: `browser:${displayItem.id!}`,
|
||||
data: {
|
||||
type: 'file',
|
||||
id: displayItem.id,
|
||||
item: displayItem,
|
||||
},
|
||||
disabled: disabled,
|
||||
})
|
||||
|
||||
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
|
||||
id: `browser:${displayItem.id!}`,
|
||||
data: {
|
||||
type: 'file',
|
||||
id: displayItem.id,
|
||||
item: displayItem,
|
||||
},
|
||||
})
|
||||
|
||||
// Combine refs
|
||||
const setNodeRef = (node: HTMLElement | null) => {
|
||||
setDraggableRef(node)
|
||||
setDroppableRef(node)
|
||||
}
|
||||
|
||||
// Determine if this item is being dragged (either directly or as part of selection)
|
||||
const isBeingDragged =
|
||||
isDraggableDragging || (dragState?.draggedIds.has(displayItem.id!) ?? false)
|
||||
|
||||
// Determine if this is a valid drop target
|
||||
// File target is valid ONLY if dragging 1 item AND it is a file (version stack)
|
||||
// And strictly, we shouldn't drop on ourselves
|
||||
const isValidDropTarget = useMemo(() => {
|
||||
if (!dragState?.isActive) return false
|
||||
if (dragState.draggedIds.has(displayItem.id!)) return false // Can't drop on self
|
||||
if (dragState.hasFolders) return false // Can't drag folders onto file
|
||||
if (dragState.itemCount !== 1) return false // Can't drag multiple files onto file
|
||||
return true
|
||||
}, [dragState, displayItem.id])
|
||||
|
||||
const showDropFeedback = isOver && isValidDropTarget
|
||||
|
||||
// We only gray out the original item, drag overlay will show the "ghost"
|
||||
const opacity = isBeingDragged ? 0.5 : 1
|
||||
|
||||
const itemFieldValueMap = useMemo(() => {
|
||||
return (displayItem.fieldValues || []).reduce(
|
||||
(acc: Record<string, FieldValueInfo>, val: FieldValueInfo) => {
|
||||
acc[val.fieldId!] = val
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, FieldValueInfo>,
|
||||
)
|
||||
}, [displayItem.fieldValues])
|
||||
|
||||
useEffect(() => {
|
||||
if (isEditing) {
|
||||
// Use a longer timeout to ensure the context menu has closed and
|
||||
// the DOM has stabilized before focusing. Radix focus restoration
|
||||
// can sometimes conflict with immediate focus calls.
|
||||
const timeoutId = setTimeout(() => {
|
||||
inputRef.current?.focus()
|
||||
inputRef.current?.select()
|
||||
}, 150)
|
||||
return () => clearTimeout(timeoutId)
|
||||
}
|
||||
}, [isEditing])
|
||||
|
||||
// Reset name if item changes
|
||||
useEffect(() => {
|
||||
setName(displayItem.name)
|
||||
}, [displayItem.name])
|
||||
|
||||
const handleClick = (e: React.MouseEvent) => {
|
||||
onSelect(displayItem, e)
|
||||
}
|
||||
|
||||
const handleRename = () => {
|
||||
if (name !== displayItem.name) {
|
||||
onRename(name || '')
|
||||
}
|
||||
onFinishEditing()
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleRename()
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
setName(displayItem.name || '')
|
||||
onFinishEditing()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={{ opacity }}
|
||||
onClick={handleClick}
|
||||
onDoubleClick={() => onDoubleClick(displayItem)}
|
||||
onContextMenu={(e) => onContextMenu(e, displayItem)}
|
||||
onMouseDown={(e) => {
|
||||
if (e.shiftKey) {
|
||||
e.preventDefault()
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
'group relative flex cursor-pointer select-none flex-col overflow-hidden rounded-xl border border-border bg-card transition-all hover:border-primary/50 h-full',
|
||||
isSelected && 'ring-2 ring-primary',
|
||||
showDropFeedback && 'border-primary ring-2 ring-primary',
|
||||
)}
|
||||
>
|
||||
<div className="absolute left-2 top-2 z-10">
|
||||
<Checkbox
|
||||
checked={isChecked}
|
||||
onCheckedChange={() => {}}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onSelect(displayItem, e)
|
||||
}}
|
||||
className="h-4 w-4 bg-white/20 dark:bg-white/20 border-2 data-[state=checked]:bg-primary data-[state=checked]:border-primary border-foreground/15"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{displayItem.versionStack && (
|
||||
<Badge className="absolute right-2 top-2 z-10">
|
||||
v
|
||||
{displayItem.versionStack.versions.find((v) => v.id === displayItem.id)?.version ??
|
||||
displayItem.versionStack.versions.length}
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
<div className="relative aspect-square overflow-hidden bg-muted/30">
|
||||
{displayItem.status === 'uploading' ||
|
||||
displayItem.status === 'processing' ||
|
||||
displayItem.status === 'uploaded' ? (
|
||||
<div className="flex h-full w-full items-center justify-center bg-background/50">
|
||||
<Skeleton className="absolute inset-0 h-full w-full" />
|
||||
<span className="z-10 font-medium capitalize text-muted-foreground">
|
||||
{displayItem.status === 'uploaded' ? 'Processing' : displayItem.status}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<FilePreview item={displayItem} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-2 p-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<EditableText
|
||||
ref={inputRef}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onBlur={handleRename}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={!isEditing}
|
||||
className="h-auto p-0 text-sm text-foreground"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{displayItem.createdAt && formatTimeAgo(displayItem.createdAt)} by{' '}
|
||||
{displayItem.creator?.name}
|
||||
</p>
|
||||
</div>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
className="cursor-pointer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4 text-foreground" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{isShareView ? (
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onAction?.('remove-from-share', item)
|
||||
}}
|
||||
className="text-destructive"
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
<span>Remove from Share</span>
|
||||
</DropdownMenuItem>
|
||||
) : isRecentlyDeleted ? (
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onAction?.('restore', item)
|
||||
}}
|
||||
>
|
||||
<History className="mr-2 h-4 w-4" />
|
||||
<span>Restore</span>
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<>
|
||||
{(!isChecked || (selectedCount || 0) <= 1) && (
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onAction?.('rename', item)
|
||||
}}
|
||||
>
|
||||
<Edit className="mr-2 h-4 w-4" />
|
||||
<span>Rename</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onAction?.('download', item)
|
||||
}}
|
||||
>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>Download</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onAction?.('delete', item)
|
||||
}}
|
||||
className="text-destructive"
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
<span>Delete</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{fields && fields.length > 0 && (
|
||||
<div className="space-y-2 border-t p-3 mx-2">
|
||||
{fields.map((field) => (
|
||||
<div key={field.id} className="space-y-1">
|
||||
<label className="text-xs text-muted-foreground tracking-wide">
|
||||
{field.config?.name}
|
||||
</label>
|
||||
<div className="min-h-[28px]">
|
||||
<FieldRenderer
|
||||
config={field.config}
|
||||
value={itemFieldValueMap[field.id!]?.value}
|
||||
onSave={(val) => onSaveField(field.id!, val)}
|
||||
readOnly={field.readOnly}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
import type { AssetInfo, FieldValueInfo } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
|
||||
import { useDraggable } from '@dnd-kit/react'
|
||||
import { File, Folder, MoreVertical } from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import FieldRenderer from '../field-renderer'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import { EditableText } from '@/ui/components/ui/editable-text'
|
||||
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
|
||||
interface FileListItemProps {
|
||||
teamId?: string
|
||||
item: AssetInfo
|
||||
isSelected: boolean
|
||||
isChecked: boolean
|
||||
isEditing: boolean
|
||||
onSelect: (item: AssetInfo, event: React.MouseEvent) => void
|
||||
onDoubleClick: (item: AssetInfo) => void
|
||||
onContextMenu: (e: React.MouseEvent, item: AssetInfo) => void
|
||||
onDragStart: (item: AssetInfo) => void
|
||||
onDrop: (target: AssetInfo) => void
|
||||
onRename: (newName: string) => void
|
||||
onFinishEditing: () => void
|
||||
onSaveField: (fieldId: string, value: unknown) => void
|
||||
dragState?: DragState
|
||||
disabled?: boolean
|
||||
fields: MetadataFieldInfo[]
|
||||
columnSizing?: Record<string, number>
|
||||
}
|
||||
|
||||
export function FileListItem({
|
||||
teamId,
|
||||
item,
|
||||
isSelected,
|
||||
isChecked,
|
||||
isEditing,
|
||||
onSelect,
|
||||
onDoubleClick,
|
||||
onContextMenu,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
onDragStart: _onDragStart,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
onDrop: _onDrop,
|
||||
onRename,
|
||||
onFinishEditing,
|
||||
onSaveField,
|
||||
dragState,
|
||||
disabled,
|
||||
fields,
|
||||
columnSizing,
|
||||
}: FileListItemProps) {
|
||||
const [name, setName] = useState(item.name)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const shouldPoll =
|
||||
(item.type === 'file' || item.type === 'version_stack') &&
|
||||
!!teamId &&
|
||||
(item.status === 'uploading' || item.status === 'uploaded' || item.status === 'processing')
|
||||
|
||||
const { data: polledItem } = useQuery({
|
||||
queryKey: ['file', teamId, item.id],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.files[':fileId'].$get({
|
||||
param: { fileId: item.id || '' },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch file')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
},
|
||||
enabled: shouldPoll,
|
||||
refetchInterval: (query: unknown) => {
|
||||
const data = (query as { state: { data: { status?: string } } }).state.data
|
||||
return data?.status === 'processed' ? false : 1000
|
||||
},
|
||||
})
|
||||
|
||||
const displayItem = polledItem || item
|
||||
|
||||
// dnd-kit hooks
|
||||
const { ref: setDraggableRef, isDragging: isDraggableDragging } = useDraggable({
|
||||
id: `browser:${displayItem.id!}`,
|
||||
data: {
|
||||
type: displayItem.type === 'folder' ? 'folder' : 'file',
|
||||
id: displayItem.id,
|
||||
item: displayItem,
|
||||
},
|
||||
disabled: disabled,
|
||||
})
|
||||
|
||||
const isBeingDragged =
|
||||
isDraggableDragging || (dragState?.draggedIds.has(displayItem.id!) ?? false)
|
||||
|
||||
const opacity = isBeingDragged ? 0.5 : 1
|
||||
|
||||
const itemFieldValueMap = useMemo(() => {
|
||||
return (displayItem.fieldValues || []).reduce(
|
||||
(acc: Record<string, FieldValueInfo>, val: FieldValueInfo) => {
|
||||
acc[val.fieldId!] = val
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, FieldValueInfo>,
|
||||
)
|
||||
}, [displayItem.fieldValues])
|
||||
|
||||
useEffect(() => {
|
||||
if (isEditing) {
|
||||
// Use a longer timeout to ensure the context menu has closed and
|
||||
// the DOM has stabilized before focusing. Radix focus restoration
|
||||
// can sometimes conflict with immediate focus calls.
|
||||
const timeoutId = setTimeout(() => {
|
||||
inputRef.current?.focus()
|
||||
inputRef.current?.select()
|
||||
}, 150)
|
||||
return () => clearTimeout(timeoutId)
|
||||
}
|
||||
}, [isEditing])
|
||||
|
||||
useEffect(() => {
|
||||
setName(displayItem.name)
|
||||
}, [displayItem.name])
|
||||
|
||||
const formatSize = (size?: number) => {
|
||||
if (!size) return '-'
|
||||
if (size < 1024) return `${size} B`
|
||||
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
|
||||
return `${(size / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
const formatDate = (date?: string) => {
|
||||
if (!date) return '-'
|
||||
return new Date(date).toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
})
|
||||
}
|
||||
|
||||
const handleClick = (e: React.MouseEvent) => {
|
||||
onSelect(displayItem, e)
|
||||
}
|
||||
const handleRename = () => {
|
||||
if (name !== displayItem.name) {
|
||||
onRename(name || '')
|
||||
}
|
||||
onFinishEditing()
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleRename()
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
setName(displayItem.name || '')
|
||||
onFinishEditing()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<tr
|
||||
ref={setDraggableRef}
|
||||
style={{ opacity }}
|
||||
onClick={handleClick}
|
||||
onDoubleClick={() => onDoubleClick(displayItem)}
|
||||
onContextMenu={(e) => onContextMenu(e, displayItem)}
|
||||
onMouseDown={(e) => {
|
||||
if (e.shiftKey) {
|
||||
e.preventDefault()
|
||||
}
|
||||
}}
|
||||
className="group cursor-pointer select-none transition-colors whitespace-nowrap"
|
||||
>
|
||||
<td
|
||||
className={cn(
|
||||
'px-4 py-2 sticky left-0 z-10 transition-colors border-r',
|
||||
isSelected ? 'bg-muted' : 'bg-card group-hover:bg-muted',
|
||||
)}
|
||||
style={{
|
||||
width: columnSizing?.['name'] || 300,
|
||||
minWidth: columnSizing?.['name'] || 300,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-2 overflow-hidden">
|
||||
<Checkbox
|
||||
checked={isChecked}
|
||||
onCheckedChange={() => {}}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onSelect(displayItem, e)
|
||||
}}
|
||||
className="h-4 w-4 shrink-0 data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
||||
/>
|
||||
<div className="w-8 h-8 shrink-0 flex items-center justify-center bg-muted rounded overflow-hidden">
|
||||
{displayItem.preview?.thumbnailUrl ? (
|
||||
<img
|
||||
src={displayItem.preview.thumbnailUrl}
|
||||
alt=""
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : displayItem.type === 'folder' ? (
|
||||
<Folder className="h-4 w-4 text-primary" />
|
||||
) : (
|
||||
<File className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<EditableText
|
||||
ref={inputRef}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onBlur={handleRename}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={!isEditing}
|
||||
className="h-auto p-0 text-sm font-medium text-foreground truncate"
|
||||
/>
|
||||
{displayItem.versionStack && (
|
||||
<Badge variant="outline" className="px-1 py-0 text-xs shrink-0">
|
||||
v
|
||||
{displayItem.versionStack.versions.find((v) => v.id === displayItem.id)?.version ??
|
||||
displayItem.versionStack.versions.length}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
className="px-4 py-2 text-sm text-muted-foreground truncate"
|
||||
style={{
|
||||
width: columnSizing?.['size'] || 100,
|
||||
minWidth: columnSizing?.['size'] || 100,
|
||||
}}
|
||||
>
|
||||
{displayItem.type === 'folder' ? '-' : formatSize(displayItem.sizeByte)}
|
||||
</td>
|
||||
<td
|
||||
className="px-4 py-2"
|
||||
style={{
|
||||
width: columnSizing?.['modified'] || 200,
|
||||
minWidth: columnSizing?.['modified'] || 200,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between overflow-hidden">
|
||||
<span className="text-sm text-muted-foreground truncate">
|
||||
{formatDate(displayItem.updatedAt)}
|
||||
</span>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
const rect = (e.target as HTMLElement).getBoundingClientRect()
|
||||
const contextEvent = new MouseEvent(e.nativeEvent.type, {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: rect.left,
|
||||
clientY: rect.bottom,
|
||||
}) as unknown as React.MouseEvent<Element, MouseEvent>
|
||||
onContextMenu(contextEvent, displayItem)
|
||||
}}
|
||||
className="opacity-0 shrink-0 transition-opacity group-hover:opacity-100 ml-2"
|
||||
>
|
||||
<MoreVertical className="h-4 w-4 text-muted-foreground hover:text-foreground" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
{displayItem.type === 'file' &&
|
||||
fields.map((field) => (
|
||||
<td
|
||||
key={field.id}
|
||||
className="px-4 py-2 truncate"
|
||||
style={{
|
||||
width: columnSizing?.[field.id!] || 150,
|
||||
minWidth: columnSizing?.[field.id!] || 150,
|
||||
}}
|
||||
>
|
||||
<FieldRenderer
|
||||
config={field.config}
|
||||
value={itemFieldValueMap[field.id!]?.value}
|
||||
onSave={(val) => onSaveField(field.id!, val)}
|
||||
readOnly={field.readOnly}
|
||||
/>
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { File, Folder } from 'lucide-react'
|
||||
import { SpriteScrubber } from '../sprite-scrubber'
|
||||
|
||||
type FilePreviewItem = {
|
||||
type?: string | null
|
||||
preview?: {
|
||||
mediaType?: string | null
|
||||
spriteUrl?: string
|
||||
thumbnailUrl?: string
|
||||
originalWidth?: number
|
||||
originalHeight?: number
|
||||
} | null
|
||||
}
|
||||
|
||||
interface FilePreviewProps {
|
||||
item: FilePreviewItem
|
||||
}
|
||||
|
||||
export const FilePreview = ({ item }: FilePreviewProps) => {
|
||||
const isVideoWithSprite =
|
||||
item.preview?.mediaType?.startsWith('video/') &&
|
||||
item.preview.spriteUrl &&
|
||||
item.preview.thumbnailUrl &&
|
||||
item.preview.originalWidth &&
|
||||
item.preview.originalHeight
|
||||
|
||||
if (isVideoWithSprite && item.preview) {
|
||||
return (
|
||||
<SpriteScrubber
|
||||
spriteUrl={item.preview.spriteUrl!}
|
||||
thumbnailUrl={item.preview.thumbnailUrl!}
|
||||
videoWidth={item.preview.originalWidth!}
|
||||
videoHeight={item.preview.originalHeight!}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (item.preview?.thumbnailUrl) {
|
||||
return (
|
||||
<img
|
||||
src={item.preview.thumbnailUrl}
|
||||
alt="Preview"
|
||||
className="w-full h-full object-contain bg-black"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Assumption: folders in latestChildren have no media type.
|
||||
if (!item.type) {
|
||||
return (
|
||||
<div className="w-full h-full flex items-center justify-center bg-linear-to-t from-black/5 to-black/0">
|
||||
<Folder className="w-8 h-8 fill-primary/60 stroke-0" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full h-full flex items-center justify-center">
|
||||
<File className="w-8 h-8 fill-primary/60 stroke-0" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
import type { AssetInfo, ChildPreview } from '@shumai/dtos'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { EditableText } from '@/ui/components/ui/editable-text'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useDraggable, useDroppable } from '@dnd-kit/react'
|
||||
import { Download, Edit, History, MoreHorizontal, Trash2 } from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import { FilePreview } from './file-preview'
|
||||
|
||||
interface FolderCardProps {
|
||||
item: AssetInfo
|
||||
isSelected: boolean
|
||||
isChecked: boolean
|
||||
isEditing: boolean
|
||||
onSelect: (item: AssetInfo, event: React.MouseEvent) => void
|
||||
onDoubleClick: (item: AssetInfo) => void
|
||||
onContextMenu: (e: React.MouseEvent, item: AssetInfo) => void
|
||||
// Deprecated manual drag props replaced by dnd-kit
|
||||
onDragStart: (item: AssetInfo) => void
|
||||
onDrop: (target: AssetInfo) => void
|
||||
onRename: (newName: string) => void
|
||||
onFinishEditing: () => void
|
||||
dragState?: DragState
|
||||
disabled?: boolean
|
||||
onAction?: (action: 'rename' | 'delete' | 'download' | 'restore', item: AssetInfo) => void
|
||||
isRecentlyDeleted?: boolean
|
||||
selectedCount?: number
|
||||
}
|
||||
|
||||
const FolderPreviewGrid = ({ items }: { items: ChildPreview[] }) => {
|
||||
const latestChildren = items as NonNullable<AssetInfo['latestChildren']>
|
||||
const safeChildren = latestChildren ? latestChildren.slice(0, 3) : []
|
||||
const count = safeChildren.length
|
||||
|
||||
const renderItem = (child: ChildPreview) => {
|
||||
if (!child) return null
|
||||
return <FilePreview item={child} />
|
||||
}
|
||||
|
||||
if (count === 0) {
|
||||
return <div></div>
|
||||
}
|
||||
|
||||
// 1 Item
|
||||
if (count === 1) {
|
||||
return <div className="w-full h-full bg-muted/50 rounded-sm">{renderItem(safeChildren[0])}</div>
|
||||
}
|
||||
|
||||
// 2 Items
|
||||
if (count === 2) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-0.5 h-full w-full">
|
||||
<div className="overflow-hidden h-full bg-muted/50 rounded-sm">
|
||||
{renderItem(safeChildren[0])}
|
||||
</div>
|
||||
<div className="overflow-hidden h-full bg-muted/50 rounded-sm">
|
||||
{renderItem(safeChildren[1])}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// 3 Items
|
||||
return (
|
||||
<div className="grid grid-cols-3 gap-0.5 h-full w-full">
|
||||
<div className="col-span-1 overflow-hidden h-full relative bg-muted/50 rounded-sm col-span-2">
|
||||
<div className="absolute inset-0 w-full h-full">{renderItem(safeChildren[0])}</div>
|
||||
</div>
|
||||
<div className="col-span-1 grid grid-rows-2 gap-0.5 h-full col-span-1">
|
||||
<div className="overflow-hidden h-full relative bg-muted/50 rounded-sm">
|
||||
<div className="absolute inset-0 w-full h-full">{renderItem(safeChildren[1])}</div>
|
||||
</div>
|
||||
<div className="overflow-hidden h-full relative bg-muted/50 rounded-sm">
|
||||
<div className="absolute inset-0 w-full h-full">{renderItem(safeChildren[2])}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function FolderCard({
|
||||
item,
|
||||
isSelected,
|
||||
isChecked,
|
||||
isEditing,
|
||||
onSelect,
|
||||
onDoubleClick,
|
||||
onContextMenu,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
onDragStart: _onDragStart,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
onDrop: _onDrop,
|
||||
onRename,
|
||||
onFinishEditing,
|
||||
dragState,
|
||||
disabled,
|
||||
onAction,
|
||||
isRecentlyDeleted,
|
||||
selectedCount,
|
||||
}: FolderCardProps) {
|
||||
const [name, setName] = useState(item.name || '')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// dnd-kit hooks
|
||||
const { ref: setDraggableRef, isDragging: isDraggableDragging } = useDraggable({
|
||||
id: `browser:${item.id!}`,
|
||||
data: {
|
||||
type: 'folder',
|
||||
id: item.id,
|
||||
item: item,
|
||||
},
|
||||
disabled: disabled,
|
||||
})
|
||||
|
||||
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
|
||||
id: `browser:${item.id!}`,
|
||||
data: {
|
||||
type: 'folder',
|
||||
id: item.id,
|
||||
item: item,
|
||||
},
|
||||
})
|
||||
|
||||
const setNodeRef = (node: HTMLElement | null) => {
|
||||
setDraggableRef(node)
|
||||
setDroppableRef(node)
|
||||
}
|
||||
|
||||
const isBeingDragged = isDraggableDragging || (dragState?.draggedIds.has(item.id!) ?? false)
|
||||
|
||||
const isValidDropTarget = useMemo(() => {
|
||||
if (!dragState?.isActive) return false
|
||||
if (dragState.draggedIds.has(item.id!)) return false // Can't drop on self
|
||||
|
||||
// Folder is always valid drop target unless self/descendant
|
||||
return true
|
||||
}, [dragState, item.id])
|
||||
|
||||
const showDropFeedback = isOver && isValidDropTarget
|
||||
const opacity = isBeingDragged ? 0.5 : 1
|
||||
|
||||
useEffect(() => {
|
||||
if (isEditing) {
|
||||
// Use a longer timeout to ensure the context menu has closed and
|
||||
// the DOM has stabilized before focusing. Radix focus restoration
|
||||
// can sometimes conflict with immediate focus calls.
|
||||
const timeoutId = setTimeout(() => {
|
||||
inputRef.current?.focus()
|
||||
inputRef.current?.select()
|
||||
}, 150)
|
||||
return () => clearTimeout(timeoutId)
|
||||
}
|
||||
}, [isEditing])
|
||||
|
||||
useEffect(() => {
|
||||
setName(item.name || '')
|
||||
}, [item.name])
|
||||
|
||||
const handleClick = (e: React.MouseEvent) => {
|
||||
onSelect(item, e)
|
||||
}
|
||||
|
||||
const handleRename = () => {
|
||||
if (name !== item.name) {
|
||||
onRename(name || '')
|
||||
}
|
||||
onFinishEditing()
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleRename()
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
setName(item.name || '')
|
||||
onFinishEditing()
|
||||
}
|
||||
}
|
||||
|
||||
// SVG background logic from fancy card
|
||||
const width = 300
|
||||
const height = 220
|
||||
const tabHeight = 8
|
||||
const config = {
|
||||
cornerRadius: 4,
|
||||
tabRadius: 0,
|
||||
tabSlope: 15,
|
||||
tabBaseWidth: 150,
|
||||
}
|
||||
const folderPath = useMemo(() => {
|
||||
const { cornerRadius: cr, tabRadius: tr, tabSlope: ts, tabBaseWidth: tbw } = config
|
||||
const s = 1
|
||||
return `M ${s}, ${tabHeight + s} L ${s}, ${s + tr} A ${tr} ${tr} 0 0 1 ${s + tr} ${s} L ${tbw - ts + s - tr} ${s} Q ${tbw - ts + s} ${s} ${tbw - ts + s + tr} ${s + tr} L ${tbw + s} ${tabHeight + s} L ${width - cr - s} ${tabHeight + s} A ${cr} ${cr} 0 0 1 ${width - s} ${tabHeight + cr + s} L ${width - s} ${height - cr - s} A ${cr} ${cr} 0 0 1 ${width - cr - s} ${height - s} L ${cr + s} ${height - s} A ${cr} ${cr} 0 0 1 ${s} ${height - cr - s} Z`
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={{ opacity }}
|
||||
onClick={handleClick}
|
||||
onDoubleClick={() => onDoubleClick(item)}
|
||||
onContextMenu={(e) => onContextMenu(e, item)}
|
||||
onMouseDown={(e) => {
|
||||
if (e.shiftKey) {
|
||||
e.preventDefault()
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
'group relative w-full max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full',
|
||||
)}
|
||||
>
|
||||
<div className="absolute inset-0 z-10 pointer-events-none">
|
||||
<svg
|
||||
width="100%"
|
||||
height="100%"
|
||||
viewBox={`0 0 ${width} ${height}`}
|
||||
preserveAspectRatio="none"
|
||||
className="overflow-visible"
|
||||
>
|
||||
<path
|
||||
d={folderPath}
|
||||
vectorEffect="non-scaling-stroke"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={showDropFeedback ? 3 : 1}
|
||||
className={cn(
|
||||
'transition-colors duration-200 fill-none group-hover:stroke-primary',
|
||||
(isSelected || isChecked || showDropFeedback) && 'stroke-primary',
|
||||
)}
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div className="absolute inset-0 -z-10 drop-shadow-sm pointer-events-none">
|
||||
<svg
|
||||
width="100%"
|
||||
height="100%"
|
||||
viewBox={`0 0 ${width} ${height}`}
|
||||
preserveAspectRatio="none"
|
||||
className="overflow-visible"
|
||||
>
|
||||
<path
|
||||
d={folderPath}
|
||||
vectorEffect="non-scaling-stroke"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={showDropFeedback ? 3 : 1}
|
||||
className={cn('transition-colors duration-200 fill-foreground/15')}
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<div className="relative w-full flex flex-1 flex-col p-2 mt-5 bg-muted dark:bg-card rounded-sm">
|
||||
<div className="relative w-full aspect-video shrink-0 overflow-hidden">
|
||||
<div className="absolute top-1 left-1 z-30 transition-all duration-200">
|
||||
<Checkbox
|
||||
checked={isChecked}
|
||||
onClick={(e) => e.stopPropagation()} // Let parent handler deal with it
|
||||
className="w-5 h-5 border-1 border-foreground/20 bg-background/50 data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{item.latestChildren && item.latestChildren.length > 0 && (
|
||||
<FolderPreviewGrid items={item.latestChildren} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1 mt-2 px-1">
|
||||
<EditableText
|
||||
ref={inputRef}
|
||||
value={name || ''}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onBlur={handleRename}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={!isEditing}
|
||||
className="font-semibold text-foreground text-lg leading-tight truncate h-auto p-0 !bg-transparent"
|
||||
title={name}
|
||||
/>
|
||||
|
||||
<div className="flex items-center justify-between text-muted-foreground">
|
||||
<span className="text-xs tracking-wide opacity-80">
|
||||
{item.fileCount || 0} {(item.fileCount || 0) === 1 ? 'Item' : 'Items'}
|
||||
</span>
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="p-1.5 -mr-2 rounded-full hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
|
||||
>
|
||||
<MoreHorizontal size={18} />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{isRecentlyDeleted ? (
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onAction?.('restore', item)
|
||||
}}
|
||||
>
|
||||
<History className="mr-2 h-4 w-4" />
|
||||
<span>Restore</span>
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<>
|
||||
{(!isChecked || (selectedCount || 0) <= 1) && (
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onAction?.('rename', item)
|
||||
}}
|
||||
>
|
||||
<Edit className="mr-2 h-4 w-4" />
|
||||
<span>Rename</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onAction?.('download', item)
|
||||
}}
|
||||
>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>Download</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onAction?.('delete', item)
|
||||
}}
|
||||
className="text-destructive"
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
<span>Delete</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
'use client'
|
||||
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import type { SearchSort } from '@shumai/dtos'
|
||||
import { useDroppable } from '@dnd-kit/react'
|
||||
import { ChevronDown, ChevronRight } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { cn } from '../../lib/utils'
|
||||
import type { DragState } from '../dnd-types'
|
||||
|
||||
interface ReorderIndicatorProps {
|
||||
id: string
|
||||
item: AssetInfo
|
||||
position: 'before' | 'after'
|
||||
active: boolean
|
||||
className?: string
|
||||
dragState?: DragState
|
||||
isNextItemDragging?: boolean
|
||||
}
|
||||
|
||||
function ReorderIndicator({
|
||||
id,
|
||||
item,
|
||||
position,
|
||||
active,
|
||||
className,
|
||||
dragState,
|
||||
isNextItemDragging,
|
||||
}: ReorderIndicatorProps) {
|
||||
const isDraggingItem = dragState?.draggedIds.has(item.id!)
|
||||
const isDraggingAny = dragState?.isActive
|
||||
const { ref: setNodeRef, isDropTarget: isOver } = useDroppable({
|
||||
id,
|
||||
data: {
|
||||
type: 'reorder',
|
||||
item,
|
||||
position,
|
||||
},
|
||||
disabled: !active || isDraggingItem || !isDraggingAny,
|
||||
})
|
||||
|
||||
if (isDraggingItem || isNextItemDragging) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
className={cn(
|
||||
'absolute top-0 bottom-0 w-4 flex-shrink-0 flex items-center justify-center pointer-events-auto z-50',
|
||||
position === 'before' ? '-left-2 -translate-x-1/2' : '-right-2 translate-x-1/2',
|
||||
position === 'before' && [
|
||||
'hidden',
|
||||
'max-md:[.group-reorder:nth-child(2n+1)_&]:flex',
|
||||
'md:max-lg:[.group-reorder:nth-child(3n+1)_&]:flex',
|
||||
'lg:max-xl:[.group-reorder:nth-child(4n+1)_&]:flex',
|
||||
'xl:[.group-reorder:nth-child(5n+1)_&]:flex',
|
||||
],
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'h-full w-[3px] rounded-full transition-colors',
|
||||
isOver && active && !isDraggingItem && isDraggingAny ? 'bg-primary' : 'bg-transparent',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface FileBrowserGridViewProps {
|
||||
folders: AssetInfo[]
|
||||
files: AssetInfo[]
|
||||
totalFolders?: number
|
||||
totalFiles?: number
|
||||
renderItem: (item: AssetInfo) => React.ReactNode
|
||||
foldersExpanded: boolean
|
||||
setFoldersExpanded: (expanded: boolean) => void
|
||||
filesExpanded: boolean
|
||||
setFilesExpanded: (expanded: boolean) => void
|
||||
foldersRef: (node?: Element | null) => void
|
||||
filesRef: (node?: Element | null) => void
|
||||
hasNextFoldersPage: boolean
|
||||
hasNextFilesPage: boolean
|
||||
formatCount: (count: number, isFile: boolean) => string
|
||||
formatSize: (bytes: number) => string
|
||||
foldersSize: number
|
||||
filesSize: number
|
||||
handleEmptyAreaClick: (e: React.MouseEvent) => void
|
||||
dragState?: DragState
|
||||
sort?: SearchSort
|
||||
}
|
||||
|
||||
export function FileBrowserGridView({
|
||||
folders,
|
||||
files,
|
||||
totalFolders,
|
||||
totalFiles,
|
||||
renderItem,
|
||||
foldersExpanded,
|
||||
setFoldersExpanded,
|
||||
filesExpanded,
|
||||
setFilesExpanded,
|
||||
foldersRef,
|
||||
filesRef,
|
||||
hasNextFoldersPage,
|
||||
hasNextFilesPage,
|
||||
formatCount,
|
||||
formatSize,
|
||||
foldersSize,
|
||||
filesSize,
|
||||
handleEmptyAreaClick,
|
||||
dragState,
|
||||
sort,
|
||||
}: FileBrowserGridViewProps) {
|
||||
return (
|
||||
<div className="flex-1 p-4" onClick={handleEmptyAreaClick}>
|
||||
{folders.length > 0 && (
|
||||
<div className="mb-8">
|
||||
<button
|
||||
onClick={() => setFoldersExpanded(!foldersExpanded)}
|
||||
className="mb-3 flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{foldersExpanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
<span>
|
||||
{formatCount(totalFolders ?? folders.length, false)} • {formatSize(foldersSize)}
|
||||
</span>
|
||||
</button>
|
||||
{foldersExpanded && (
|
||||
<>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
|
||||
{folders.map((item, index) => (
|
||||
<div key={item.id} className="group-reorder relative flex">
|
||||
<ReorderIndicator
|
||||
id={`reorder-before-folder-${item.id}`}
|
||||
item={item}
|
||||
position="before"
|
||||
active={sort?.field === 'custom'}
|
||||
dragState={dragState}
|
||||
/>
|
||||
<div className="flex-1 min-w-0">{renderItem(item)}</div>
|
||||
<ReorderIndicator
|
||||
id={`reorder-after-folder-${item.id}`}
|
||||
item={item}
|
||||
position="after"
|
||||
active={sort?.field === 'custom'}
|
||||
dragState={dragState}
|
||||
isNextItemDragging={
|
||||
folders[index + 1] && dragState?.draggedIds.has(folders[index + 1].id!)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{hasNextFoldersPage && <div ref={foldersRef} className="h-1" />}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{files.length > 0 && (
|
||||
<div>
|
||||
<button
|
||||
onClick={() => setFilesExpanded(!filesExpanded)}
|
||||
className="mb-3 flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{filesExpanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
<span>
|
||||
{formatCount(totalFiles ?? files.length, true)} • {formatSize(filesSize)}
|
||||
</span>
|
||||
</button>
|
||||
{filesExpanded && (
|
||||
<>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
|
||||
{files.map((item, index) => (
|
||||
<div key={item.id} className="group-reorder relative flex">
|
||||
<ReorderIndicator
|
||||
id={`reorder-before-file-${item.id}`}
|
||||
item={item}
|
||||
position="before"
|
||||
active={sort?.field === 'custom'}
|
||||
dragState={dragState}
|
||||
/>
|
||||
<div className="flex-1 min-w-0">{renderItem(item)}</div>
|
||||
<ReorderIndicator
|
||||
id={`reorder-after-file-${item.id}`}
|
||||
item={item}
|
||||
position="after"
|
||||
active={sort?.field === 'custom'}
|
||||
dragState={dragState}
|
||||
isNextItemDragging={
|
||||
files[index + 1] && dragState?.draggedIds.has(files[index + 1].id!)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{hasNextFilesPage && <div ref={filesRef} className="h-1" />}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
'use client'
|
||||
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import type { FieldInfo } from '@shumai/dtos'
|
||||
import type { SearchSort } from '@shumai/dtos'
|
||||
import { useDroppable } from '@dnd-kit/react'
|
||||
import { flexRender, getCoreRowModel, useReactTable, type ColumnDef } from '@tanstack/react-table'
|
||||
import { ChevronDown, ChevronRight } from 'lucide-react'
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import { cn } from '../../lib/utils'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import { Checkbox } from '../ui/checkbox'
|
||||
|
||||
interface ListRowProps {
|
||||
item: AssetInfo
|
||||
renderItem: (item: AssetInfo, columnSizing?: Record<string, number>) => React.ReactNode
|
||||
active: boolean
|
||||
dragState?: DragState
|
||||
isSelected?: boolean
|
||||
columnSizing?: Record<string, number>
|
||||
}
|
||||
|
||||
function ListRow({ item, renderItem, active, dragState, isSelected, columnSizing }: ListRowProps) {
|
||||
const isDraggingItem = dragState?.draggedIds.has(item.id!)
|
||||
const isDraggingAny = dragState?.isActive
|
||||
|
||||
const { ref: setTopRef, isDropTarget: isTopOver } = useDroppable({
|
||||
id: `reorder-before-${item.id}`,
|
||||
data: {
|
||||
type: 'reorder',
|
||||
item,
|
||||
position: 'before',
|
||||
},
|
||||
disabled: !active || isDraggingItem || !isDraggingAny,
|
||||
})
|
||||
|
||||
const { ref: setBottomRef, isDropTarget: isBottomOver } = useDroppable({
|
||||
id: `reorder-after-${item.id}`,
|
||||
data: {
|
||||
type: 'reorder',
|
||||
item,
|
||||
position: 'after',
|
||||
},
|
||||
disabled: !active || isDraggingItem || !isDraggingAny,
|
||||
})
|
||||
|
||||
const { ref: setRowRef, isDropTarget: isRowOver } = useDroppable({
|
||||
id: `browser:${item.id!}`,
|
||||
data: {
|
||||
type: item.type === 'folder' ? 'folder' : 'file',
|
||||
id: item.id,
|
||||
item: item,
|
||||
},
|
||||
disabled: !isDraggingAny,
|
||||
})
|
||||
|
||||
const isValidDropTarget = useMemo(() => {
|
||||
if (!dragState?.isActive) return false
|
||||
if (dragState.draggedIds.has(item.id!)) return false
|
||||
|
||||
if (item.type === 'folder') return true
|
||||
|
||||
if (item.type === 'file') {
|
||||
if (dragState.hasFolders) return false
|
||||
if (dragState.itemCount !== 1) return false
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}, [dragState, item.id, item.type])
|
||||
|
||||
const showDropFeedback = isRowOver && isValidDropTarget
|
||||
|
||||
return (
|
||||
<tbody
|
||||
ref={setRowRef}
|
||||
className={cn(
|
||||
'group border-b border-border transition-colors hover:bg-primary/20 relative',
|
||||
isSelected && 'bg-primary/10',
|
||||
showDropFeedback && 'bg-primary/10',
|
||||
isTopOver && 'border-t-2 border-t-primary',
|
||||
isBottomOver && 'border-b-2 border-b-primary',
|
||||
)}
|
||||
>
|
||||
<tr
|
||||
ref={setTopRef}
|
||||
className="p-0 m-0 leading-none bg-transparent pointer-events-auto h-[2px]"
|
||||
>
|
||||
<td colSpan={100} className="p-0 m-0 border-0" />
|
||||
</tr>
|
||||
{renderItem(item, columnSizing)}
|
||||
<tr
|
||||
ref={setBottomRef}
|
||||
className="p-0 m-0 leading-none bg-transparent pointer-events-auto h-[2px]"
|
||||
>
|
||||
<td colSpan={100} className="p-0 m-0 border-0" />
|
||||
</tr>
|
||||
</tbody>
|
||||
)
|
||||
}
|
||||
|
||||
interface FileBrowserListViewProps {
|
||||
folders: AssetInfo[]
|
||||
files: AssetInfo[]
|
||||
totalFolders?: number
|
||||
totalFiles?: number
|
||||
selectedItem: AssetInfo | null
|
||||
selectedIds: Set<string>
|
||||
displayedFields: FieldInfo[]
|
||||
onItemSelect: (item: AssetInfo, event: React.MouseEvent) => void
|
||||
onItemDoubleClick: (item: AssetInfo) => void
|
||||
renderItem: (item: AssetInfo, columnSizing?: Record<string, number>) => React.ReactNode
|
||||
foldersExpanded: boolean
|
||||
setFoldersExpanded: (expanded: boolean) => void
|
||||
filesExpanded: boolean
|
||||
setFilesExpanded: (expanded: boolean) => void
|
||||
foldersRef: (node?: Element | null) => void
|
||||
filesRef: (node?: Element | null) => void
|
||||
hasNextFoldersPage: boolean
|
||||
hasNextFilesPage: boolean
|
||||
formatCount: (count: number, isFile: boolean) => string
|
||||
formatSize: (bytes: number) => string
|
||||
foldersSize: number
|
||||
filesSize: number
|
||||
handleEmptyAreaClick: (e: React.MouseEvent) => void
|
||||
dragState?: DragState
|
||||
sort?: SearchSort
|
||||
}
|
||||
|
||||
export function FileBrowserListView({
|
||||
folders,
|
||||
files,
|
||||
totalFolders,
|
||||
totalFiles,
|
||||
selectedItem,
|
||||
selectedIds,
|
||||
displayedFields,
|
||||
renderItem,
|
||||
foldersExpanded,
|
||||
setFoldersExpanded,
|
||||
filesExpanded,
|
||||
setFilesExpanded,
|
||||
foldersRef,
|
||||
filesRef,
|
||||
hasNextFoldersPage,
|
||||
hasNextFilesPage,
|
||||
formatCount,
|
||||
formatSize,
|
||||
foldersSize,
|
||||
filesSize,
|
||||
handleEmptyAreaClick,
|
||||
dragState,
|
||||
sort,
|
||||
}: FileBrowserListViewProps) {
|
||||
const [columnSizing, setColumnSizing] = useState<Record<string, number>>({})
|
||||
|
||||
const columns = useMemo<ColumnDef<AssetInfo>[]>(() => {
|
||||
const cols: ColumnDef<AssetInfo>[] = [
|
||||
{
|
||||
id: 'name',
|
||||
header: 'Name',
|
||||
size: 300,
|
||||
minSize: 150,
|
||||
},
|
||||
{
|
||||
id: 'size',
|
||||
header: 'Size',
|
||||
size: 100,
|
||||
minSize: 80,
|
||||
},
|
||||
{
|
||||
id: 'modified',
|
||||
header: 'Modified',
|
||||
size: 200,
|
||||
minSize: 150,
|
||||
},
|
||||
]
|
||||
|
||||
displayedFields.forEach((field) => {
|
||||
cols.push({
|
||||
id: field.id,
|
||||
header: field.config?.name || field.id,
|
||||
size: 150,
|
||||
minSize: 100,
|
||||
})
|
||||
})
|
||||
|
||||
return cols
|
||||
}, [displayedFields])
|
||||
|
||||
const table = useReactTable({
|
||||
data: [], // We don't use the table's data model for rows yet to keep our custom grouping logic
|
||||
columns,
|
||||
columnResizeMode: 'onChange',
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
state: {
|
||||
columnSizing,
|
||||
},
|
||||
onColumnSizingChange: setColumnSizing,
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex-1 overflow-x-auto" onClick={handleEmptyAreaClick}>
|
||||
<table
|
||||
className="w-full border-collapse"
|
||||
style={{
|
||||
tableLayout: 'fixed',
|
||||
width: table.getTotalSize(),
|
||||
minWidth: '100%',
|
||||
}}
|
||||
>
|
||||
<thead className="sticky top-0 z-30 bg-background border-b border-border">
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<tr key={headerGroup.id} className="bg-muted/50 whitespace-nowrap">
|
||||
{headerGroup.headers.map((header) => (
|
||||
<th
|
||||
key={header.id}
|
||||
className={cn(
|
||||
'px-4 py-2 text-left text-xs font-medium text-muted-foreground relative border-r',
|
||||
header.id === 'name' && 'sticky left-0 z-40 bg-muted',
|
||||
)}
|
||||
style={{
|
||||
width: header.getSize(),
|
||||
}}
|
||||
>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(header.column.columnDef.header, header.getContext())}
|
||||
<div
|
||||
onMouseDown={header.getResizeHandler()}
|
||||
onTouchStart={header.getResizeHandler()}
|
||||
className={cn(
|
||||
'absolute right-0 top-0 bottom-0 w-1 cursor-col-resize user-select-none touch-none z-50 hover:bg-primary/50 transition-colors',
|
||||
header.column.getIsResizing() && 'bg-primary w-1',
|
||||
)}
|
||||
/>
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
|
||||
{folders.length > 0 && (
|
||||
<>
|
||||
<tbody className="bg-card">
|
||||
<tr
|
||||
className="border-b border-border hover:bg-muted/50 transition-colors cursor-pointer group"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setFoldersExpanded(!foldersExpanded)
|
||||
}}
|
||||
>
|
||||
<td
|
||||
className="px-4 py-2 sticky left-0 z-10 bg-card border-r"
|
||||
style={{
|
||||
width: columnSizing?.['name'] || 300,
|
||||
minWidth: columnSizing?.['name'] || 300,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
checked={folders.length > 0 && folders.every((f) => selectedIds.has(f.id!))}
|
||||
onCheckedChange={() => {
|
||||
// Batch selection logic
|
||||
}}
|
||||
onClick={(e: React.MouseEvent) => e.stopPropagation()}
|
||||
className="h-4 w-4"
|
||||
/>
|
||||
<div className="p-1 rounded hover:bg-muted">
|
||||
{foldersExpanded ? (
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<span className="text-sm font-medium text-muted-foreground whitespace-nowrap">
|
||||
{formatCount(totalFolders ?? folders.length, false)} •{' '}
|
||||
{formatSize(foldersSize)}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td colSpan={columns.length - 1} className="bg-card" />
|
||||
</tr>
|
||||
</tbody>
|
||||
{foldersExpanded &&
|
||||
folders.map((item) => (
|
||||
<ListRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
renderItem={renderItem}
|
||||
active={sort?.field === 'custom'}
|
||||
dragState={dragState}
|
||||
isSelected={selectedItem?.id === item.id}
|
||||
columnSizing={columnSizing}
|
||||
/>
|
||||
))}
|
||||
{hasNextFoldersPage && (
|
||||
<tbody className="bg-transparent">
|
||||
<tr>
|
||||
<td colSpan={columns.length}>
|
||||
<div ref={foldersRef} className="h-1" />
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{files.length > 0 && (
|
||||
<>
|
||||
<tbody className="bg-card">
|
||||
<tr
|
||||
className="border-b border-border hover:bg-muted/50 transition-colors cursor-pointer group"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setFilesExpanded(!filesExpanded)
|
||||
}}
|
||||
>
|
||||
<td
|
||||
className="px-4 py-2 sticky left-0 z-10 bg-card border-r"
|
||||
style={{
|
||||
width: columnSizing?.['name'] || 300,
|
||||
minWidth: columnSizing?.['name'] || 300,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
checked={files.length > 0 && files.every((f) => selectedIds.has(f.id!))}
|
||||
onCheckedChange={() => {
|
||||
// Batch selection logic
|
||||
}}
|
||||
onClick={(e: React.MouseEvent) => e.stopPropagation()}
|
||||
className="h-4 w-4"
|
||||
/>
|
||||
<div className="p-1 rounded hover:bg-muted">
|
||||
{filesExpanded ? (
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<span className="text-sm font-medium text-muted-foreground whitespace-nowrap">
|
||||
{formatCount(totalFiles ?? files.length, true)} • {formatSize(filesSize)}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td colSpan={columns.length - 1} className="bg-card" />
|
||||
</tr>
|
||||
</tbody>
|
||||
{filesExpanded &&
|
||||
files.map((item) => (
|
||||
<ListRow
|
||||
key={item.id}
|
||||
item={item}
|
||||
renderItem={renderItem}
|
||||
active={sort?.field === 'custom'}
|
||||
dragState={dragState}
|
||||
isSelected={selectedItem?.id === item.id}
|
||||
columnSizing={columnSizing}
|
||||
/>
|
||||
))}
|
||||
{hasNextFilesPage && (
|
||||
<tbody className="bg-transparent">
|
||||
<tr>
|
||||
<td colSpan={columns.length}>
|
||||
<div ref={filesRef} className="h-1" />
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import type { CollectionInfo } from '@shumai/dtos'
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
import type { SearchCondition, SearchSort } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useMutation, useQuery } from '@tanstack/react-query'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import { useState } from 'react'
|
||||
import { FieldsManager } from '../fields-manager'
|
||||
import { FolderTree } from '../folder-tree'
|
||||
import { ManageFieldsDialog } from '../manage-fields-dialog'
|
||||
import { MembersDialog } from '../members-dialog'
|
||||
import { FilterPanel } from '../search/filter-panel'
|
||||
import { SearchFilterDialog } from '../search/search-filter-dialog'
|
||||
import { SortControl } from '../search/sort-control'
|
||||
import { Avatar, AvatarFallback } from '../ui/avatar'
|
||||
import { Button } from '../ui/button'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'
|
||||
import { Separator } from '../ui/separator'
|
||||
|
||||
type FileBrowserToolbarProps = {
|
||||
teamId: string
|
||||
projectId: string
|
||||
assetId: string
|
||||
fields: MetadataFieldInfo[]
|
||||
filterConditions: SearchCondition[]
|
||||
onFilterChange: (conditions: SearchCondition[]) => void
|
||||
sort?: SearchSort
|
||||
onSortChange: (sort?: SearchSort) => void
|
||||
isRecentlyDeleted?: boolean
|
||||
collection?: CollectionInfo
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
onUpdateCollection?: (updates: { name?: string; filter?: any }) => void
|
||||
rootFolderId?: string
|
||||
}
|
||||
|
||||
export function FileBrowserToolbar({
|
||||
teamId,
|
||||
projectId,
|
||||
assetId,
|
||||
fields,
|
||||
filterConditions,
|
||||
onFilterChange,
|
||||
sort,
|
||||
onSortChange,
|
||||
isRecentlyDeleted,
|
||||
collection,
|
||||
onUpdateCollection,
|
||||
rootFolderId,
|
||||
}: FileBrowserToolbarProps) {
|
||||
const [popoverOpen, setPopoverOpen] = useState(false)
|
||||
const [searchDialogOpen, setSearchDialogOpen] = useState(false)
|
||||
const [manageDialogOpen, setManageDialogOpen] = useState(false)
|
||||
const [isMembersDialogOpen, setIsMembersDialogOpen] = useState(false)
|
||||
const [isFolderSelectorOpen, setIsFolderSelectorOpen] = useState(false)
|
||||
|
||||
const activeFiltersCount = filterConditions.length
|
||||
const isCollection = !!collection
|
||||
|
||||
const { data: folderInfo } = useQuery({
|
||||
queryKey: ['folders', assetId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: assetId },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch folder')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
},
|
||||
enabled: isCollection && !!assetId,
|
||||
})
|
||||
|
||||
const { data: members } = useQuery({
|
||||
queryKey: ['projects', projectId, 'members'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].members.$get({
|
||||
param: { projectId: projectId },
|
||||
query: {},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch members')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const { data: teamInfo } = useQuery({
|
||||
queryKey: ['projects', projectId, 'team'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].team.$get({
|
||||
param: { projectId: projectId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch team info')
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const { data: me } = useQuery({
|
||||
queryKey: ['teams', teamInfo?.teamId, 'me'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].me.$get({
|
||||
param: { teamId: teamInfo?.teamId || '' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch me')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamInfo?.teamId,
|
||||
})
|
||||
|
||||
const $inviteProject = client.api.projects[':projectId'].invite.$post
|
||||
const inviteMutation = useMutation<
|
||||
InferResponseType<typeof $inviteProject>,
|
||||
Error,
|
||||
InferRequestType<typeof $inviteProject>
|
||||
>({
|
||||
mutationFn: async (args) => {
|
||||
const res = await $inviteProject(args)
|
||||
if (!res.ok) {
|
||||
throw new Error('Failed to invite')
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const handleManageFields = () => {
|
||||
setPopoverOpen(false)
|
||||
setManageDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleInvite = async (role: 'editor' | 'reviewer') => {
|
||||
const res = await inviteMutation.mutateAsync({
|
||||
param: { projectId: projectId },
|
||||
json: { role },
|
||||
})
|
||||
return res.code
|
||||
}
|
||||
|
||||
const getInitials = (name?: string) => {
|
||||
if (!name) return '??'
|
||||
return name
|
||||
.split(' ')
|
||||
.map((n) => n[0])
|
||||
.slice(0, 2)
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between p-2 border-b sticky top-0 bg-background z-10">
|
||||
<div className="flex items-center gap-2 h-full">
|
||||
<Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<div>
|
||||
<Button variant="ghost" size="sm">
|
||||
Fields
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<FieldsManager
|
||||
projectId={projectId}
|
||||
onManageFields={handleManageFields}
|
||||
onSave={() => setPopoverOpen(false)}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<Separator orientation="vertical" />
|
||||
<SortControl
|
||||
fields={fields}
|
||||
sort={sort}
|
||||
onSortChange={onSortChange}
|
||||
disabled={isRecentlyDeleted}
|
||||
/>
|
||||
|
||||
<Separator orientation="vertical" />
|
||||
|
||||
{isCollection ? (
|
||||
<>
|
||||
<Popover open={isFolderSelectorOpen} onOpenChange={setIsFolderSelectorOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="inline-flex items-center gap-2 px-3 py-2 hover:bg-primary/10 font-semibold rounded-xl cursor-pointer h-8 text-muted-foreground"
|
||||
>
|
||||
<span className="truncate max-w-[150px]">{folderInfo?.name || 'Loading...'}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[300px] p-0" align="start">
|
||||
<div className="h-[400px] flex flex-col">
|
||||
<div className="p-2 border-b text-xs font-semibold text-muted-foreground uppercase tracking-wider">
|
||||
Select Source Folder
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<FolderTree
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName="Assets"
|
||||
rootFolderId={rootFolderId!}
|
||||
onSelect={(folder: AssetInfo) => {
|
||||
onUpdateCollection?.({
|
||||
filter: {
|
||||
...collection.filter,
|
||||
sourceFolderId: folder.id,
|
||||
},
|
||||
})
|
||||
setIsFolderSelectorOpen(false)
|
||||
}}
|
||||
selectedFolderId={collection.filter.sourceFolderId}
|
||||
hideCollections
|
||||
hideShares
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<Separator orientation="vertical" />
|
||||
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant={activeFiltersCount > 0 ? 'secondary' : 'ghost'}
|
||||
size="sm"
|
||||
className="inline-flex items-center gap-2 px-4 py-2 hover:bg-primary/10 font-semibold rounded-xl cursor-pointer h-8"
|
||||
>
|
||||
<span>Filter</span>
|
||||
{activeFiltersCount > 0 && (
|
||||
<span className="ml-1 px-1.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-primary/50 border border-primary-foreground/20">
|
||||
{activeFiltersCount}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[500px] p-0 overflow-hidden" align="start">
|
||||
<div className="max-h-[80vh] overflow-y-auto">
|
||||
<FilterPanel
|
||||
fields={fields}
|
||||
conditions={filterConditions}
|
||||
onChange={(newConditions) => {
|
||||
onFilterChange(newConditions)
|
||||
onUpdateCollection?.({
|
||||
filter: {
|
||||
...collection.filter,
|
||||
searchFilter: {
|
||||
...collection.filter.searchFilter,
|
||||
conditions: newConditions,
|
||||
},
|
||||
},
|
||||
})
|
||||
}}
|
||||
excludeFields={[]}
|
||||
hidePrefix
|
||||
/>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
onClick={() => setSearchDialogOpen(true)}
|
||||
disabled={isRecentlyDeleted}
|
||||
variant={activeFiltersCount > 0 ? 'secondary' : 'ghost'}
|
||||
size="sm"
|
||||
className="inline-flex items-center gap-2 px-4 py-2 hover:bg-primary/10 font-semibold rounded-xl cursor-pointer h-8"
|
||||
>
|
||||
<span>Search</span>
|
||||
{activeFiltersCount > 0 && (
|
||||
<span className="ml-1 px-1.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-primary/50 border border-primary-foreground/20">
|
||||
{activeFiltersCount}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{!isRecentlyDeleted && (
|
||||
<div
|
||||
className="flex items-center -space-x-2 cursor-pointer hover:opacity-90"
|
||||
onClick={() => setIsMembersDialogOpen(true)}
|
||||
>
|
||||
{members?.slice(0, 3).map((member) => (
|
||||
<Avatar key={member.id} className="border-2 border-background w-8 h-8">
|
||||
<AvatarFallback className="text-[10px]">{getInitials(member.name)}</AvatarFallback>
|
||||
</Avatar>
|
||||
))}
|
||||
{members && members.length > 3 && (
|
||||
<div className="flex items-center justify-center w-8 h-8 rounded-full border-2 border-background bg-muted text-[10px] font-medium">
|
||||
+{members.length - 3}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ManageFieldsDialog
|
||||
projectId={projectId}
|
||||
open={manageDialogOpen}
|
||||
onOpenChange={setManageDialogOpen}
|
||||
/>
|
||||
|
||||
<MembersDialog
|
||||
open={isMembersDialogOpen}
|
||||
onOpenChange={setIsMembersDialogOpen}
|
||||
title="Project Members"
|
||||
members={members || []}
|
||||
isOwner={me?.role === 'owner'}
|
||||
onInvite={handleInvite}
|
||||
/>
|
||||
|
||||
<SearchFilterDialog
|
||||
open={searchDialogOpen}
|
||||
onOpenChange={setSearchDialogOpen}
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
assetId={assetId}
|
||||
fields={fields}
|
||||
initialConditions={filterConditions}
|
||||
onApply={onFilterChange}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
'use client'
|
||||
|
||||
import { client } from '@/ui/api/client'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import { useState } from 'react'
|
||||
|
||||
interface UseFileActionsProps {
|
||||
teamId: string
|
||||
projectId: string
|
||||
assetId: string
|
||||
folders: AssetInfo[]
|
||||
files: AssetInfo[]
|
||||
selectedIds: Set<string>
|
||||
}
|
||||
|
||||
export function useFileActions({
|
||||
teamId,
|
||||
projectId,
|
||||
assetId,
|
||||
folders,
|
||||
files,
|
||||
selectedIds,
|
||||
}: UseFileActionsProps) {
|
||||
const [editingItemId, setEditingItemId] = useState<string | null>(null)
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false)
|
||||
const [itemsToDelete, setItemsToDelete] = useState<AssetInfo[]>([])
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const $createFolder = client.api.folders.$post
|
||||
const { mutate: createFolder } = useMutation<
|
||||
InferResponseType<typeof $createFolder, 200>,
|
||||
Error,
|
||||
InferRequestType<typeof $createFolder>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $createFolder(request)
|
||||
if (!res.ok) throw new Error('Failed to create')
|
||||
return (await res.json()) as unknown as InferResponseType<typeof $createFolder, 200>
|
||||
},
|
||||
})
|
||||
|
||||
const $renameFolder = client.api.folders[':folderId'].$put
|
||||
const { mutate: renameFolder } = useMutation<
|
||||
InferResponseType<typeof $renameFolder, 200>,
|
||||
Error,
|
||||
InferRequestType<typeof $renameFolder>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $renameFolder(request)
|
||||
if (!res.ok) throw new Error('Failed to rename')
|
||||
return (await res.json()) as unknown as InferResponseType<typeof $renameFolder, 200>
|
||||
},
|
||||
})
|
||||
|
||||
const $renameFile = client.api.files[':fileId'].$put
|
||||
const { mutate: renameFile } = useMutation<
|
||||
InferResponseType<typeof $renameFile, 200>,
|
||||
Error,
|
||||
InferRequestType<typeof $renameFile>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $renameFile(request)
|
||||
if (!res.ok) throw new Error('Failed to rename')
|
||||
return (await res.json()) as unknown as InferResponseType<typeof $renameFile, 200>
|
||||
},
|
||||
})
|
||||
|
||||
const $deleteFiles = client.api.files.$delete
|
||||
const { mutate: deleteFiles } = useMutation<void, Error, InferRequestType<typeof $deleteFiles>>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $deleteFiles(request)
|
||||
if (!res.ok) throw new Error('Failed to delete')
|
||||
},
|
||||
})
|
||||
|
||||
const $deleteFolders = client.api.folders.$delete
|
||||
const { mutate: deleteFolders } = useMutation<
|
||||
InferResponseType<typeof $deleteFolders>,
|
||||
Error,
|
||||
InferRequestType<typeof $deleteFolders>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $deleteFolders(request)
|
||||
if (!res.ok) throw new Error('Failed to delete')
|
||||
return null as unknown as InferResponseType<typeof $deleteFolders>
|
||||
},
|
||||
})
|
||||
|
||||
const $restoreFiles = client.api.files.restore.$post
|
||||
const { mutate: restoreFiles } = useMutation<void, Error, InferRequestType<typeof $restoreFiles>>(
|
||||
{
|
||||
mutationFn: async (request) => {
|
||||
const res = await $restoreFiles(request)
|
||||
if (!res.ok) throw new Error('Failed to restore')
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const $restoreFolders = client.api.folders.restore.$post
|
||||
const { mutate: restoreFolders } = useMutation<
|
||||
InferResponseType<typeof $restoreFolders>,
|
||||
Error,
|
||||
InferRequestType<typeof $restoreFolders>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $restoreFolders(request)
|
||||
if (!res.ok) throw new Error('Failed to restore')
|
||||
return null as unknown as InferResponseType<typeof $restoreFolders>
|
||||
},
|
||||
})
|
||||
|
||||
const handleRename = (item: AssetInfo) => {
|
||||
setEditingItemId(item.id!)
|
||||
}
|
||||
|
||||
const confirmDelete = () => {
|
||||
const fileIds = itemsToDelete.filter((i) => i.type === 'file').map((i) => i.id!)
|
||||
const folderIds = itemsToDelete.filter((i) => i.type === 'folder').map((i) => i.id!)
|
||||
|
||||
if (fileIds.length > 0) {
|
||||
deleteFiles(
|
||||
{ json: { ids: fileIds } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (folderIds.length > 0) {
|
||||
deleteFolders(
|
||||
{ json: { ids: folderIds } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
setIsDeleteDialogOpen(false)
|
||||
setItemsToDelete([])
|
||||
}
|
||||
|
||||
const handleDelete = (items: AssetInfo[]) => {
|
||||
setItemsToDelete(items)
|
||||
setIsDeleteDialogOpen(true)
|
||||
}
|
||||
|
||||
const handleRestore = (items: AssetInfo[]) => {
|
||||
const fileIds = items.filter((i) => i.type === 'file').map((i) => i.id!)
|
||||
const folderIds = items.filter((i) => i.type === 'folder').map((i) => i.id!)
|
||||
|
||||
if (fileIds.length > 0) {
|
||||
restoreFiles(
|
||||
{ json: { ids: fileIds } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['projects', projectId, 'recently-deleted', 'file'],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (folderIds.length > 0) {
|
||||
restoreFolders(
|
||||
{ json: { ids: folderIds } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['projects', projectId, 'recently-deleted', 'folder'],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDownload = (items: AssetInfo[]) => {
|
||||
alert(
|
||||
`Download functionality - Would download ${
|
||||
items.length
|
||||
} item(s): ${items.map((i) => i.name).join(', ')}`,
|
||||
)
|
||||
}
|
||||
|
||||
const handleNewFolder = (name: string) => {
|
||||
createFolder(
|
||||
{ json: { name, parentId: assetId } },
|
||||
{
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['folders', teamId],
|
||||
})
|
||||
if (data?.id) {
|
||||
setEditingItemId(data.id)
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const onRenameSubmit = (item: AssetInfo, newName: string) => {
|
||||
if (item.type === 'folder') {
|
||||
renameFolder(
|
||||
{ param: { folderId: item.id! }, json: { name: newName } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['folders', teamId],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
} else {
|
||||
renameFile(
|
||||
{
|
||||
param: { fileId: item.id! },
|
||||
json: { name: newName },
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['folders', teamId],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const handleAction = (action: 'rename' | 'delete' | 'download' | 'restore', item: AssetInfo) => {
|
||||
const isSelected = selectedIds.has(item.id!)
|
||||
const targetItems = isSelected
|
||||
? [...folders, ...files].filter((i) => selectedIds.has(i.id!))
|
||||
: [item]
|
||||
|
||||
switch (action) {
|
||||
case 'rename':
|
||||
handleRename(item)
|
||||
break
|
||||
case 'delete':
|
||||
handleDelete(targetItems)
|
||||
break
|
||||
case 'download':
|
||||
handleDownload(targetItems)
|
||||
break
|
||||
case 'restore':
|
||||
handleRestore(targetItems)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
editingItemId,
|
||||
setEditingItemId,
|
||||
handleRename,
|
||||
handleDelete,
|
||||
handleRestore,
|
||||
handleDownload,
|
||||
handleNewFolder,
|
||||
handleAction,
|
||||
onRenameSubmit,
|
||||
isDeleteDialogOpen,
|
||||
setIsDeleteDialogOpen,
|
||||
itemsToDelete,
|
||||
confirmDelete,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
import type { AssetInfo, AssetInfoPaginatedList } from '@shumai/dtos'
|
||||
import type { CollectionInfo } from '@shumai/dtos'
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
import type { SearchCondition, SearchSort } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { InferRequestType, InferResponseType } from 'hono/client'
|
||||
|
||||
import { useFieldStore } from '@/ui/stores/fields'
|
||||
import { useMemberStore } from '@/ui/stores/members'
|
||||
import { useTopNavStore } from '@/ui/stores/top-nav'
|
||||
import { useUiStore } from '@/ui/stores/ui'
|
||||
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
|
||||
import { PointerActivationConstraints } from '@dnd-kit/dom'
|
||||
import { DragDropProvider, DragOverlay, KeyboardSensor, PointerSensor } from '@dnd-kit/react'
|
||||
import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { cn } from '../lib/utils'
|
||||
import { SnapToPointer } from './dnd-modifiers'
|
||||
import { FileBrowser } from './file-browser/file-browser'
|
||||
import { FileViewerRightSidebar } from './file-viewer-right-sidebar'
|
||||
import { FolderTree } from './folder-tree'
|
||||
import { ResizeHandle } from './resize-handle'
|
||||
import { useFileSystemDnd } from './use-file-system-dnd'
|
||||
|
||||
type FileSystemManagerProps = {
|
||||
teamId: string
|
||||
projectId: string
|
||||
projectName: string
|
||||
assetId: string
|
||||
rootFolderId: string
|
||||
collection?: CollectionInfo
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
onUpdateCollection?: (updates: { name?: string; filter?: any }) => void
|
||||
}
|
||||
|
||||
export default function FileSystemManager({
|
||||
teamId,
|
||||
projectId,
|
||||
projectName,
|
||||
assetId,
|
||||
rootFolderId,
|
||||
collection,
|
||||
onUpdateCollection,
|
||||
}: FileSystemManagerProps) {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const { loadedProjectId, setFields } = useFieldStore()
|
||||
const $patchMetadata = client.api.files[':fileId'].metadata.$patch
|
||||
const { mutate: patchMetadata } = useMutation<
|
||||
InferResponseType<typeof $patchMetadata>,
|
||||
Error,
|
||||
InferRequestType<typeof $patchMetadata>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $patchMetadata(request)
|
||||
if (!res.ok) throw new Error('Failed to patch metadata')
|
||||
return null as unknown as InferResponseType<typeof $patchMetadata>
|
||||
},
|
||||
})
|
||||
|
||||
const { data: fields } = useQuery({
|
||||
queryKey: ['fields', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].fields.$get({
|
||||
param: { projectId: projectId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch fields')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!projectId,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (fields && projectId !== loadedProjectId) {
|
||||
setFields(fields as unknown as MetadataFieldInfo[], projectId)
|
||||
}
|
||||
}, [fields, projectId, loadedProjectId, setFields])
|
||||
|
||||
const isRecentlyDeleted = assetId === 'recently-deleted'
|
||||
const [selectedItem, setSelectedItem] = useState<AssetInfo | null>(null)
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
|
||||
const [lastSelectedId, setLastSelectedId] = useState<string | null>(null)
|
||||
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
|
||||
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
|
||||
|
||||
const { members, fetchMembers } = useMemberStore()
|
||||
const { metadata, fetchMetadata, setMetadata: setUserMetadata } = useUserMetadataStore()
|
||||
|
||||
useEffect(() => {
|
||||
if (teamId) {
|
||||
fetchMembers(teamId)
|
||||
fetchMetadata(teamId)
|
||||
}
|
||||
}, [teamId, fetchMembers, fetchMetadata])
|
||||
|
||||
const initialFilterConditions = useMemo(() => {
|
||||
return collection?.filter?.searchFilter?.conditions || []
|
||||
}, [collection])
|
||||
|
||||
const [filterConditions, setFilterConditions] =
|
||||
useState<SearchCondition[]>(initialFilterConditions)
|
||||
|
||||
useEffect(() => {
|
||||
setFilterConditions(initialFilterConditions)
|
||||
}, [initialFilterConditions])
|
||||
|
||||
const sortKey = `project:${projectId}:sort`
|
||||
const sort = (metadata[sortKey] as SearchSort | undefined) || { field: 'custom', order: 'asc' }
|
||||
const setSort = (newSort: SearchSort | undefined) => {
|
||||
if (newSort) {
|
||||
setUserMetadata(teamId, sortKey, newSort)
|
||||
}
|
||||
}
|
||||
|
||||
const isCollection = !!collection
|
||||
const isFiltering = filterConditions.length > 0 || isCollection
|
||||
|
||||
const {
|
||||
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
|
||||
setFileListLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
|
||||
fileListRightSidebarCollapsed: isRightSidebarCollapsed,
|
||||
setFileListRightSidebarCollapsed: setIsRightSidebarCollapsed,
|
||||
viewModes,
|
||||
} = useUiStore()
|
||||
|
||||
const displayStyle = viewModes[projectId] ?? 'card'
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const { data: folderInfo } = isRecentlyDeleted
|
||||
? { data: undefined }
|
||||
: useQuery({
|
||||
queryKey: ['folders', assetId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.folders[':folderId'].$get({
|
||||
param: { folderId: assetId },
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch folder')
|
||||
return (await res.json()) as unknown as AssetInfo
|
||||
},
|
||||
})
|
||||
|
||||
const { setProjectState, clearProjectState } = useTopNavStore()
|
||||
|
||||
useEffect(() => {
|
||||
setProjectState({
|
||||
teamId,
|
||||
projectId,
|
||||
projectName,
|
||||
ancestorFolders: folderInfo?.ancestorFolders ?? [],
|
||||
currentAsset: isRecentlyDeleted
|
||||
? { name: 'Recently Deleted', type: 'folder' }
|
||||
: isCollection
|
||||
? { name: collection.name, type: 'folder' }
|
||||
: { name: folderInfo?.name, type: 'folder' },
|
||||
isRootFolder: !isRecentlyDeleted && !isCollection && assetId === rootFolderId,
|
||||
onFolderClick: (id: string) => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
params: { projectId, folderId: id },
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
return () => clearProjectState()
|
||||
}, [
|
||||
teamId,
|
||||
projectId,
|
||||
projectName,
|
||||
folderInfo,
|
||||
isRecentlyDeleted,
|
||||
assetId,
|
||||
rootFolderId,
|
||||
setProjectState,
|
||||
clearProjectState,
|
||||
navigate,
|
||||
])
|
||||
|
||||
const {
|
||||
data: foldersData,
|
||||
fetchNextPage: fetchNextFoldersPage,
|
||||
hasNextPage: hasNextPageFolders,
|
||||
isFetchingNextPage: isFetchingNextFoldersPage,
|
||||
} = useInfiniteQuery<AssetInfoPaginatedList>({
|
||||
queryKey: isRecentlyDeleted
|
||||
? ['projects', projectId, 'recently-deleted', 'folder']
|
||||
: ['search', teamId, assetId, 'folder', filterConditions, sort, isCollection],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
if (isRecentlyDeleted || isCollection) {
|
||||
if (isRecentlyDeleted) {
|
||||
const res = await client.api.projects[':projectId']['recently-deleted'].$get({
|
||||
param: { projectId: projectId },
|
||||
query: {
|
||||
assetType: 'folder',
|
||||
after: pageParam as string,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch recently deleted folders')
|
||||
return (await res.json()) as unknown as AssetInfoPaginatedList
|
||||
}
|
||||
return { data: [], pageInfo: { total: 0 } }
|
||||
}
|
||||
if (isFiltering) {
|
||||
return { data: [], pageInfo: { total: 0 } }
|
||||
}
|
||||
|
||||
const res = await client.api.folders[':folderId'].search.$post({
|
||||
param: { folderId: assetId },
|
||||
json: {
|
||||
assetType: 'folder',
|
||||
after: pageParam as string,
|
||||
recursively: false,
|
||||
sort,
|
||||
conditions: [],
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to search folders')
|
||||
return (await res.json()) as unknown as AssetInfoPaginatedList
|
||||
},
|
||||
enabled: !isFiltering, // Disable folders when filtering
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => {
|
||||
return lastPage.pageInfo?.cursor || undefined
|
||||
},
|
||||
})
|
||||
|
||||
const {
|
||||
data: filesData,
|
||||
fetchNextPage: fetchNextFilesPage,
|
||||
hasNextPage: hasNextPageFiles,
|
||||
isFetchingNextPage: isFetchingNextFilesPage,
|
||||
} = useInfiniteQuery<AssetInfoPaginatedList>({
|
||||
queryKey: isRecentlyDeleted
|
||||
? ['projects', projectId, 'recently-deleted', 'file']
|
||||
: ['search', teamId, assetId, 'file', filterConditions, sort, isCollection],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
if (isRecentlyDeleted) {
|
||||
const res = await client.api.projects[':projectId']['recently-deleted'].$get({
|
||||
param: { projectId: projectId },
|
||||
query: {
|
||||
assetType: 'file',
|
||||
after: pageParam as string,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch recently deleted files')
|
||||
return (await res.json()) as unknown as AssetInfoPaginatedList
|
||||
}
|
||||
|
||||
const res = await client.api.folders[':folderId'].search.$post({
|
||||
param: { folderId: assetId },
|
||||
json: {
|
||||
assetType: 'file',
|
||||
after: pageParam as string,
|
||||
recursively: isFiltering || isCollection,
|
||||
conditions: filterConditions,
|
||||
sort,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to search files')
|
||||
return (await res.json()) as unknown as AssetInfoPaginatedList
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => {
|
||||
return lastPage.pageInfo?.cursor || undefined
|
||||
},
|
||||
})
|
||||
|
||||
const folders = foldersData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||
const files = filesData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||
|
||||
const totalFolders = foldersData?.pages[0]?.pageInfo?.total
|
||||
const totalFiles = filesData?.pages[0]?.pageInfo?.total
|
||||
|
||||
const handleClearSelection = () => {
|
||||
setSelectedIds(new Set())
|
||||
setSelectedItem(null)
|
||||
setLastSelectedId(null)
|
||||
}
|
||||
|
||||
const { dragState, handleDragStart, handleDragEnd } = useFileSystemDnd({
|
||||
teamId,
|
||||
projectId,
|
||||
assetId,
|
||||
folders,
|
||||
files,
|
||||
selectedIds,
|
||||
onClearSelection: handleClearSelection,
|
||||
})
|
||||
|
||||
const singleSelectedFile = useMemo(() => {
|
||||
if (selectedIds.size !== 1) return null
|
||||
const id = Array.from(selectedIds)[0]
|
||||
const file = files.find((f) => f.id === id)
|
||||
return file || null
|
||||
}, [selectedIds, files])
|
||||
|
||||
const handleItemDoubleClick = (item: AssetInfo) => {
|
||||
if (item.type === 'folder') {
|
||||
if (isRecentlyDeleted) {
|
||||
return
|
||||
}
|
||||
setFilterConditions([])
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
params: { projectId, folderId: item.id },
|
||||
})
|
||||
} else {
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
params: { projectId, fileId: item.versionStack ? item.versionStack.id : item.id },
|
||||
search: { version: undefined },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const handleItemSelect = (item: AssetInfo, event: React.MouseEvent) => {
|
||||
const isCtrlOrCmd = event.metaKey || event.ctrlKey
|
||||
const isShift = event.shiftKey
|
||||
|
||||
if (isShift && lastSelectedId) {
|
||||
// Find the last selected item
|
||||
const allItems = [...folders, ...files]
|
||||
const lastSelectedItem = allItems.find((i) => i.id === lastSelectedId)
|
||||
|
||||
if (lastSelectedItem) {
|
||||
if (lastSelectedItem.type === item.type) {
|
||||
// Only select range if they are the same type
|
||||
const typeItems = item.type === 'folder' ? folders : files
|
||||
const lastIndex = typeItems.findIndex((i) => i.id === lastSelectedId)
|
||||
const currentIndex = typeItems.findIndex((i) => i.id === item.id)
|
||||
|
||||
if (lastIndex !== -1 && currentIndex !== -1) {
|
||||
const start = Math.min(lastIndex, currentIndex)
|
||||
const end = Math.max(lastIndex, currentIndex)
|
||||
const rangeItems = typeItems.slice(start, end + 1)
|
||||
|
||||
const newSelectedIds = new Set(selectedIds)
|
||||
rangeItems.forEach((rangeItem) => {
|
||||
newSelectedIds.add(rangeItem.id)
|
||||
})
|
||||
setSelectedIds(newSelectedIds)
|
||||
setSelectedItem(item)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// If types are different, do nothing (as requested by user)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isCtrlOrCmd) {
|
||||
const newSelectedIds = new Set(selectedIds)
|
||||
if (newSelectedIds.has(item.id)) {
|
||||
newSelectedIds.delete(item.id)
|
||||
} else {
|
||||
newSelectedIds.add(item.id)
|
||||
}
|
||||
setSelectedIds(newSelectedIds)
|
||||
} else {
|
||||
setSelectedIds(new Set([item.id]))
|
||||
}
|
||||
|
||||
setLastSelectedId(item.id)
|
||||
setSelectedItem(item)
|
||||
}
|
||||
|
||||
const handleSaveField = (fileId: string, fieldId: string, value: unknown) => {
|
||||
patchMetadata(
|
||||
{
|
||||
param: { fileId: fileId },
|
||||
json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'],
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: [
|
||||
'folders',
|
||||
assetId,
|
||||
'children',
|
||||
{
|
||||
assetType: 'file',
|
||||
},
|
||||
],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DragDropProvider
|
||||
modifiers={[SnapToPointer.configure({ anchor: { x: 0, y: 0 } })]}
|
||||
sensors={
|
||||
isRecentlyDeleted
|
||||
? []
|
||||
: [
|
||||
PointerSensor.configure({
|
||||
activationConstraints: [new PointerActivationConstraints.Distance({ value: 10 })],
|
||||
}),
|
||||
KeyboardSensor,
|
||||
]
|
||||
}
|
||||
onDragStart={handleDragStart}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<div className="flex flex-1 flex-col bg-background min-h-0">
|
||||
<div ref={containerRef} className="flex flex-1 overflow-hidden relative">
|
||||
{!isLeftSidebarCollapsed && (
|
||||
<div
|
||||
className="md:hidden fixed inset-0 bg-black/50 z-40"
|
||||
onClick={() => setIsLeftSidebarCollapsed(true)}
|
||||
/>
|
||||
)}
|
||||
{!isRightSidebarCollapsed && (
|
||||
<div
|
||||
className="md:hidden fixed inset-0 bg-black/50 z-40"
|
||||
onClick={() => setIsRightSidebarCollapsed(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isLeftSidebarCollapsed && (
|
||||
<>
|
||||
<div className="bg-background" style={{ width: leftSidebarWidth }}>
|
||||
<FolderTree
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
rootFolderId={rootFolderId}
|
||||
dragState={dragState}
|
||||
/>
|
||||
</div>
|
||||
<ResizeHandle
|
||||
onResize={(delta) => {
|
||||
setLeftSidebarWidth((prev) => Math.max(180, Math.min(400, prev + delta)))
|
||||
}}
|
||||
className="hidden md:block"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<FileBrowser
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
assetId={assetId}
|
||||
folders={folders}
|
||||
files={files}
|
||||
totalFolders={totalFolders}
|
||||
totalFiles={totalFiles}
|
||||
selectedItem={selectedItem}
|
||||
selectedIds={selectedIds}
|
||||
onItemSelect={handleItemSelect}
|
||||
onItemDoubleClick={handleItemDoubleClick}
|
||||
onSaveField={handleSaveField}
|
||||
displayStyle={displayStyle}
|
||||
onClearSelection={handleClearSelection}
|
||||
fetchNextFoldersPage={fetchNextFoldersPage}
|
||||
hasNextFoldersPage={hasNextPageFolders || false}
|
||||
isFetchingNextFoldersPage={isFetchingNextFoldersPage}
|
||||
fetchNextFilesPage={fetchNextFilesPage}
|
||||
hasNextFilesPage={hasNextPageFiles || false}
|
||||
isFetchingNextFilesPage={isFetchingNextFilesPage}
|
||||
isRecentlyDeleted={isRecentlyDeleted}
|
||||
filterConditions={filterConditions}
|
||||
onFilterChange={setFilterConditions}
|
||||
sort={sort}
|
||||
onSortChange={setSort}
|
||||
dragState={dragState}
|
||||
collection={collection}
|
||||
onUpdateCollection={onUpdateCollection}
|
||||
rootFolderId={rootFolderId}
|
||||
/>
|
||||
|
||||
{!isRightSidebarCollapsed && (
|
||||
<>
|
||||
<ResizeHandle
|
||||
onResize={(delta) => {
|
||||
setRightSidebarWidth((prev) => Math.max(240, Math.min(600, prev - delta)))
|
||||
}}
|
||||
className="hidden md:block"
|
||||
/>
|
||||
<div
|
||||
style={{ width: rightSidebarWidth }}
|
||||
className="bg-background border-l border-border flex flex-col flex-shrink-0"
|
||||
>
|
||||
{singleSelectedFile ? (
|
||||
<FileViewerRightSidebar
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
file={singleSelectedFile}
|
||||
onSaveField={(fieldId, value) =>
|
||||
handleSaveField(singleSelectedFile.id, fieldId, value)
|
||||
}
|
||||
members={members}
|
||||
hideAnnotationControl={true}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground">
|
||||
Select an asset to view details
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<DragOverlay>
|
||||
{dragState?.isActive ? (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center gap-2 rounded-md bg-popover px-3 py-2 text-sm font-medium text-popover-foreground shadow-md ring-1 ring-border cursor-grabbing',
|
||||
displayStyle === 'list' &&
|
||||
'w-30 h-[40px] px-0 flex-none overflow-hidden justify-center',
|
||||
)}
|
||||
style={{ transform: 'translate(0px, 0px)' }}
|
||||
>
|
||||
<span>
|
||||
Moving {dragState.itemCount} item{dragState.itemCount !== 1 ? 's' : ''}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
</DragOverlay>
|
||||
</DragDropProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { useInfiniteQuery } from '@tanstack/react-query'
|
||||
import { Loader2, PanelLeftClose } from 'lucide-react'
|
||||
import type { FC } from 'react'
|
||||
import type { AssetInfoPaginatedList } from '@shumai/dtos'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { SidebarFileCard } from './sidebar-file-card'
|
||||
import { Button } from './ui/button'
|
||||
import { ScrollArea } from './ui/scroll-area'
|
||||
|
||||
interface FileViewerLeftSidebarProps {
|
||||
projectId: string
|
||||
currentAssetId: string
|
||||
parentFolderId: string
|
||||
onCollapse: () => void
|
||||
}
|
||||
|
||||
export const FileViewerLeftSidebar: FC<FileViewerLeftSidebarProps> = ({
|
||||
projectId,
|
||||
currentAssetId,
|
||||
parentFolderId,
|
||||
onCollapse,
|
||||
}) => {
|
||||
const { ref, inView } = useInView({
|
||||
threshold: 0,
|
||||
rootMargin: '200px',
|
||||
})
|
||||
const activeItemRef = useRef<HTMLDivElement>(null)
|
||||
const hasScrolledRef = useRef(false)
|
||||
|
||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } = useInfiniteQuery({
|
||||
queryKey: [
|
||||
'folders',
|
||||
parentFolderId,
|
||||
'children',
|
||||
{
|
||||
assetType: 'file',
|
||||
},
|
||||
],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: parentFolderId },
|
||||
query: {
|
||||
assetType: 'file',
|
||||
after: pageParam,
|
||||
first: '20',
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch folder children')
|
||||
return (await res.json()) as unknown as AssetInfoPaginatedList
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
|
||||
})
|
||||
|
||||
const files = data?.pages.flatMap((page) => page.data) ?? []
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
|
||||
// Reset scroll lock when current asset changes
|
||||
useEffect(() => {
|
||||
hasScrolledRef.current = false
|
||||
}, [currentAssetId])
|
||||
|
||||
// Scroll the active item into view
|
||||
useEffect(() => {
|
||||
const activeFileInView = files.some((f) => f?.id === currentAssetId)
|
||||
if (activeFileInView && activeItemRef.current && !hasScrolledRef.current) {
|
||||
activeItemRef.current.scrollIntoView({
|
||||
block: 'center',
|
||||
})
|
||||
hasScrolledRef.current = true
|
||||
}
|
||||
}, [files, currentAssetId])
|
||||
|
||||
return (
|
||||
<div className="h-full w-full bg-card border-r border-border flex flex-col">
|
||||
<div className="p-2 border-b flex items-center justify-between">
|
||||
<h3 className="text-sm font-semibold px-2">Current Folder</h3>
|
||||
<Button variant="ghost" size="icon-sm" onClick={onCollapse}>
|
||||
<PanelLeftClose className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="flex-1 [&>div>div]:block! px-2">
|
||||
<div className="p-2 space-y-2">
|
||||
{isLoading && (
|
||||
<div className="flex justify-center items-center p-4">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
{files.map(
|
||||
(file) =>
|
||||
file && (
|
||||
<SidebarFileCard
|
||||
ref={file.id === currentAssetId ? activeItemRef : null}
|
||||
key={file.id}
|
||||
projectId={projectId}
|
||||
item={file}
|
||||
isActive={file.id === currentAssetId}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
<div ref={ref}>
|
||||
{isFetchingNextPage && (
|
||||
<div className="flex justify-center items-center p-4">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
import type { AssetInfo, AttachmentInfo, CommentInfo, FieldValueInfo } from '@shumai/dtos'
|
||||
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
import type { UserInfo } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
|
||||
import { useFieldStore } from '@/ui/stores/fields'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { XIcon } from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { MessageCard } from './chat/message-card'
|
||||
import { ChatInput } from './chat/message-input'
|
||||
import FieldRenderer from './field-renderer'
|
||||
import { GuestIdentityPopup } from './guest-identity-popup'
|
||||
import { ScrollArea } from './ui/scroll-area'
|
||||
|
||||
interface FileViewerRightSidebarProps {
|
||||
teamId: string
|
||||
projectId: string
|
||||
file: AssetInfo | null
|
||||
onSaveField: (fieldId: string, value: unknown) => void
|
||||
members: UserInfo[]
|
||||
onCommentSelect?: (comment: CommentInfo) => void
|
||||
hideAnnotationControl?: boolean
|
||||
readOnly?: boolean
|
||||
publicFields?: MetadataFieldInfo[]
|
||||
isPublic?: boolean
|
||||
shareId?: string
|
||||
currentTime?: number
|
||||
onTyping?: () => void
|
||||
selectedCommentId?: string | null
|
||||
}
|
||||
|
||||
export function FileViewerRightSidebar({
|
||||
teamId,
|
||||
projectId,
|
||||
file,
|
||||
onSaveField,
|
||||
members,
|
||||
onCommentSelect,
|
||||
hideAnnotationControl = false,
|
||||
readOnly = false,
|
||||
publicFields,
|
||||
isPublic = false,
|
||||
shareId,
|
||||
currentTime,
|
||||
onTyping,
|
||||
selectedCommentId,
|
||||
}: FileViewerRightSidebarProps) {
|
||||
const { fields, setFields } = useFieldStore()
|
||||
const queryClient = useQueryClient()
|
||||
const { ref, inView } = useInView()
|
||||
const [replyingTo, setReplyingTo] = useState<CommentInfo | null>(null)
|
||||
const [viewingAttachment, setViewingAttachment] = useState<AttachmentInfo | null>(null)
|
||||
const [isGuestPopupOpen, setIsGuestPopupOpen] = useState(false)
|
||||
const [pendingComment, setPendingComment] = useState<{
|
||||
text: string
|
||||
attachmentIds: string[]
|
||||
annotations?: Annotation[]
|
||||
replyToId?: string | null
|
||||
second?: number | null
|
||||
} | null>(null)
|
||||
|
||||
const { data: apiFields } = useQuery({
|
||||
queryKey: ['fields', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].fields.$get({
|
||||
param: { projectId: projectId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch fields')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!projectId && !publicFields,
|
||||
})
|
||||
|
||||
const { data: bots } = useQuery({
|
||||
queryKey: ['projects', projectId, 'bots'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].bots.$get({
|
||||
param: { projectId: projectId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch bots')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!projectId && !readOnly,
|
||||
})
|
||||
|
||||
const isAiEnabled = file?.mediaType?.startsWith('image/') || file?.mediaType?.startsWith('video/')
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const enabledBots = isAiEnabled ? (bots as any[]) || [] : []
|
||||
|
||||
useEffect(() => {
|
||||
if (publicFields) {
|
||||
setFields(publicFields, projectId)
|
||||
} else if (apiFields) {
|
||||
setFields(apiFields as unknown as MetadataFieldInfo[], projectId)
|
||||
}
|
||||
}, [apiFields, publicFields, projectId, setFields])
|
||||
|
||||
const {
|
||||
data: commentsData,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: isPublic
|
||||
? ['shares', shareId, 'files', file?.id, 'comments']
|
||||
: ['files', file?.id, 'comments'],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
if (isPublic) {
|
||||
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||
const res = await client.api.shares[':shareId'].files[':fileId'].comments.$get(
|
||||
{
|
||||
param: { shareId: shareId!, fileId: file!.id! },
|
||||
query: { after: pageParam as string },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'x-share-password': password,
|
||||
},
|
||||
},
|
||||
)
|
||||
if (!res.ok) throw new Error('Failed to fetch comments')
|
||||
return await res.json()
|
||||
} else {
|
||||
const res = await client.api.files[':fileId'].comments.$get({
|
||||
param: { fileId: file!.id! },
|
||||
query: { after: pageParam as string },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch comments')
|
||||
return await res.json()
|
||||
}
|
||||
},
|
||||
enabled: !!file?.id && (!isPublic || !!shareId),
|
||||
initialPageParam: '',
|
||||
refetchInterval: 2000,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
getNextPageParam: (lastPage: any) => lastPage.pageInfo?.cursor || undefined,
|
||||
})
|
||||
|
||||
const { mutate: createComment } = useMutation({
|
||||
mutationFn: async ({
|
||||
text,
|
||||
attachmentIds,
|
||||
annotations,
|
||||
replyToId,
|
||||
guestUserId,
|
||||
second,
|
||||
}: {
|
||||
text: string
|
||||
attachmentIds: string[]
|
||||
annotations?: Annotation[]
|
||||
replyToId?: string | null
|
||||
guestUserId?: string
|
||||
second?: number | null
|
||||
}) => {
|
||||
if (isPublic) {
|
||||
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
|
||||
const res = await client.api.shares[':shareId'].files[':fileId'].comments.$post(
|
||||
{
|
||||
param: { shareId: shareId!, fileId: file!.id! },
|
||||
json: {
|
||||
message: text,
|
||||
attachmentIds: attachmentIds,
|
||||
replyToId: replyToId ?? undefined,
|
||||
annotations: annotations,
|
||||
second: second ?? undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'x-share-password': password,
|
||||
...(guestUserId ? { 'x-guest-user-id': guestUserId } : {}),
|
||||
},
|
||||
},
|
||||
)
|
||||
if (!res.ok) throw new Error('Failed to create comment')
|
||||
return await res.json()
|
||||
} else {
|
||||
const res = await client.api.files[':fileId'].comments.$post({
|
||||
param: { fileId: file!.id! },
|
||||
json: {
|
||||
message: text,
|
||||
attachmentIds: attachmentIds,
|
||||
replyToId: replyToId ?? undefined,
|
||||
annotations: annotations,
|
||||
second: second ?? undefined,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to create comment')
|
||||
return await res.json()
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: isPublic
|
||||
? ['shares', shareId, 'files', file?.id, 'comments']
|
||||
: ['files', file?.id, 'comments'],
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
React.useEffect(() => {
|
||||
if (inView && hasNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, fetchNextPage, hasNextPage])
|
||||
|
||||
const itemFieldValueMap = useMemo(() => {
|
||||
return (file?.fieldValues || []).reduce(
|
||||
(acc: Record<string, FieldValueInfo>, val: FieldValueInfo) => {
|
||||
acc[val.fieldId!] = val
|
||||
return acc
|
||||
},
|
||||
{},
|
||||
)
|
||||
}, [file?.fieldValues])
|
||||
|
||||
const sortedFields = useMemo(() => {
|
||||
return [...fields].sort((a, b) => {
|
||||
const nameA = a.config?.name?.toLowerCase() || ''
|
||||
const nameB = b.config?.name?.toLowerCase() || ''
|
||||
if (nameA < nameB) return -1
|
||||
if (nameA > nameB) return 1
|
||||
return 0
|
||||
})
|
||||
}, [fields])
|
||||
|
||||
const comments =
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(commentsData?.pages.flatMap((page: any) => page.data ?? []) as CommentInfo[]) ?? []
|
||||
|
||||
const handleSendMessage = async (
|
||||
text: string,
|
||||
attachmentIds: string[],
|
||||
annotations?: Annotation[],
|
||||
replyToId?: string | null,
|
||||
second?: number | null,
|
||||
) => {
|
||||
if (!file?.id) return
|
||||
|
||||
if (isPublic) {
|
||||
// Check if logged in
|
||||
console.log('[handleSendMessage] checking auth status')
|
||||
const meRes = await client.api.me.$get()
|
||||
const { id: loggedInUserId } = await meRes.json()
|
||||
console.log('[handleSendMessage] loggedInUserId:', loggedInUserId)
|
||||
|
||||
if (!loggedInUserId) {
|
||||
const guestUserId = localStorage.getItem('guest_user_id')
|
||||
console.log('[handleSendMessage] guestUserId from storage:', guestUserId)
|
||||
if (!guestUserId) {
|
||||
console.log('[handleSendMessage] no guest ID, opening popup')
|
||||
setPendingComment({ text, attachmentIds, annotations, replyToId, second })
|
||||
setIsGuestPopupOpen(true)
|
||||
return
|
||||
}
|
||||
createComment({ text, attachmentIds, annotations, replyToId, guestUserId, second })
|
||||
} else {
|
||||
createComment({ text, attachmentIds, annotations, replyToId, second })
|
||||
}
|
||||
} else {
|
||||
createComment({ text, attachmentIds, annotations, replyToId, second })
|
||||
}
|
||||
setReplyingTo(null)
|
||||
}
|
||||
|
||||
const handleGuestSuccess = (guestUserId: string) => {
|
||||
console.log('[handleGuestSuccess] guestUserId:', guestUserId)
|
||||
if (pendingComment) {
|
||||
createComment({ ...pendingComment, guestUserId })
|
||||
setPendingComment(null)
|
||||
setReplyingTo(null)
|
||||
}
|
||||
}
|
||||
|
||||
const getUser = (id: string): UserInfo => {
|
||||
const member = members.find((m) => m.id === id)
|
||||
if (member) {
|
||||
return member
|
||||
}
|
||||
|
||||
if (bots) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const bot = (bots as any[]).find((b) => b.id === id)
|
||||
if (bot) {
|
||||
return { id: bot.id, name: bot.name, role: 'bot' }
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: 'unknown',
|
||||
name: 'Unknown',
|
||||
role: 'unknown',
|
||||
}
|
||||
}
|
||||
|
||||
if (!file) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center p-8 text-center bg-background">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium text-foreground">No item selected</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Select a file to view its details and comments.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-background h-full flex flex-col overflow-hidden">
|
||||
{/* Lightbox */}
|
||||
{viewingAttachment && viewingAttachment.mediaType?.startsWith('image/') && (
|
||||
<div
|
||||
className="fixed inset-0 z-[100] bg-black/95 flex flex-col items-center justify-center p-4 animate-in fade-in duration-200"
|
||||
onClick={() => setViewingAttachment(null)}
|
||||
>
|
||||
<button className="absolute top-4 right-4 text-white/70 hover:text-white bg-white/10 hover:bg-white/20 rounded-full p-2 transition-colors z-50">
|
||||
<XIcon className="w-8 h-8" />
|
||||
</button>
|
||||
|
||||
<div className="w-full h-full flex items-center justify-center p-2">
|
||||
<img
|
||||
src={viewingAttachment.url}
|
||||
alt="Enlarged view"
|
||||
className="max-w-full max-h-[85vh] object-contain rounded shadow-2xl cursor-zoom-out"
|
||||
onClick={() => setViewingAttachment(null)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Tabs defaultValue="comments" className="p-1 flex-1 flex flex-col px-2 min-h-0">
|
||||
<TabsList className="w-full shrink-0">
|
||||
<TabsTrigger value="comments" className="flex-1">
|
||||
Comments
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="fields" className="flex-1">
|
||||
Fields
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="comments" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-0">
|
||||
<ScrollArea className="flex-1 min-h-0 [&>div>div]:block!">
|
||||
<div className="space-y-4">
|
||||
{comments.map((comment) => (
|
||||
<div key={comment.id}>
|
||||
<MessageCard
|
||||
teamId={teamId}
|
||||
message={comment}
|
||||
getUser={getUser}
|
||||
onReply={setReplyingTo}
|
||||
onViewAttachment={setViewingAttachment}
|
||||
hasReplies={!!comment.replies?.length}
|
||||
frameRate={
|
||||
file?.mediaType?.startsWith('video/')
|
||||
? file?.media?.metadata?.frameRate || 30
|
||||
: undefined
|
||||
}
|
||||
isSelected={selectedCommentId === comment.id}
|
||||
onSelect={() => {
|
||||
onCommentSelect?.(comment)
|
||||
}}
|
||||
/>
|
||||
{comment.replies?.map((reply, index) => (
|
||||
<div key={reply.id}>
|
||||
<MessageCard
|
||||
teamId={teamId}
|
||||
isReply={true}
|
||||
message={reply}
|
||||
getUser={getUser}
|
||||
onReply={setReplyingTo}
|
||||
onViewAttachment={setViewingAttachment}
|
||||
hasReplies={false}
|
||||
isLastReply={index === (comment.replies?.length ?? 0) - 1}
|
||||
frameRate={
|
||||
file?.mediaType?.startsWith('video/')
|
||||
? file?.media?.metadata?.frameRate || 30
|
||||
: undefined
|
||||
}
|
||||
isSelected={selectedCommentId === reply.id}
|
||||
onSelect={() => {
|
||||
onCommentSelect?.(reply)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
<div ref={ref} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
{(!readOnly || isPublic) && (
|
||||
<div className="mt-4 shrink-0">
|
||||
<GuestIdentityPopup
|
||||
isOpen={isGuestPopupOpen}
|
||||
onClose={() => setIsGuestPopupOpen(false)}
|
||||
onSuccess={handleGuestSuccess}
|
||||
>
|
||||
<ChatInput
|
||||
projectId={projectId}
|
||||
onSendMessage={handleSendMessage}
|
||||
replyingTo={replyingTo}
|
||||
onCancelReply={() => setReplyingTo(null)}
|
||||
users={members}
|
||||
bots={enabledBots}
|
||||
hideAnnotationControl={hideAnnotationControl}
|
||||
disableMentions={isPublic}
|
||||
currentTime={file?.mediaType?.startsWith('video/') ? currentTime : undefined}
|
||||
frameRate={
|
||||
file?.mediaType?.startsWith('video/')
|
||||
? file?.media?.metadata?.frameRate || 30
|
||||
: undefined
|
||||
}
|
||||
onTyping={onTyping}
|
||||
/>
|
||||
</GuestIdentityPopup>
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="fields" className="flex-1 flex flex-col overflow-hidden min-h-0 mt-4">
|
||||
<ScrollArea className="flex-1 px-4 min-h-0 [&>div>div]:block!">
|
||||
{sortedFields && sortedFields.length > 0 && (
|
||||
<div className="space-y-4 pb-4">
|
||||
{sortedFields.map((field) => (
|
||||
<div key={field.id} className="space-y-1">
|
||||
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
{field.config?.name}
|
||||
</label>
|
||||
<div className="min-h-[28px]">
|
||||
<FieldRenderer
|
||||
config={field.config}
|
||||
value={itemFieldValueMap[field.id!]?.value}
|
||||
onSave={(val) => onSaveField(field.id!, val)}
|
||||
readOnly={readOnly || field.readOnly}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { useScreenSize } from '@/ui/hooks/useScreenSize'
|
||||
import { getBestTranscode } from '@/ui/lib/media'
|
||||
import { Minus, Plus, Copy, Download, Check } from 'lucide-react'
|
||||
import type { RefObject } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type Player from 'video.js/dist/types/player'
|
||||
import DrawingCanvas from './drawing-canvas'
|
||||
import VideoPlayer from './viewers/video-player'
|
||||
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
|
||||
type FileViewerProps = {
|
||||
file: AssetInfo
|
||||
videoRef?: RefObject<Player | null>
|
||||
onPlay?: () => void
|
||||
onPause?: () => void
|
||||
onTimeUpdate?: (time: number) => void
|
||||
annotations?: Annotation[]
|
||||
}
|
||||
|
||||
export function FileViewer({
|
||||
file,
|
||||
videoRef,
|
||||
onPlay,
|
||||
onPause,
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
}: FileViewerProps) {
|
||||
const { width: screenWidth } = useScreenSize()
|
||||
const isImage = file.mediaType?.startsWith('image/')
|
||||
const isVideo = file.mediaType?.startsWith('video/')
|
||||
|
||||
// Annotation Store
|
||||
const {
|
||||
isDrawing,
|
||||
currentTool,
|
||||
currentColor,
|
||||
addAnnotation,
|
||||
annotations: draftAnnotations,
|
||||
reset: resetAnnotations,
|
||||
} = useAnnotationStore()
|
||||
|
||||
// Reset annotations when file changes
|
||||
useEffect(() => {
|
||||
resetAnnotations()
|
||||
}, [file.id, resetAnnotations])
|
||||
|
||||
// State for Image Viewer
|
||||
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [zoom, setZoom] = useState(1)
|
||||
const [pan, setPan] = useState({ x: 0, y: 0 })
|
||||
const [copied, setCopied] = useState(false)
|
||||
|
||||
const imgW = file.media?.metadata?.originalWidth ?? 1920
|
||||
const imgH = file.media?.metadata?.originalHeight ?? 1080
|
||||
const conW = containerSize.width
|
||||
const conH = containerSize.height
|
||||
|
||||
let baseScale = 1
|
||||
|
||||
if (conW > 0 && conH > 0) {
|
||||
baseScale = Math.min(conW / imgW, conH / imgH)
|
||||
}
|
||||
|
||||
// Reset/Fit logic
|
||||
useEffect(() => {
|
||||
if (conW > 0 && conH > 0 && isImage) {
|
||||
setZoom(baseScale)
|
||||
// Center
|
||||
const x = (conW - imgW * baseScale) / 2
|
||||
const y = (conH - imgH * baseScale) / 2
|
||||
setPan({ x, y })
|
||||
}
|
||||
}, [file.id, conW, conH, isImage, baseScale, imgW, imgH])
|
||||
|
||||
// Resize Observer
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
const entry = entries[0]
|
||||
if (entry) {
|
||||
setContainerSize({
|
||||
width: entry.contentRect.width,
|
||||
height: entry.contentRect.height,
|
||||
})
|
||||
}
|
||||
})
|
||||
observer.observe(containerRef.current)
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
const handleZoom = (factor: number) => {
|
||||
const cx = conW / 2
|
||||
const cy = conH / 2
|
||||
|
||||
// Limit min/max zoom if needed?
|
||||
const newZoom = zoom * factor
|
||||
if (newZoom < 0.01 || newZoom > 50) return
|
||||
|
||||
const newPanX = cx - (cx - pan.x) * (newZoom / zoom)
|
||||
const newPanY = cy - (cy - pan.y) * (newZoom / zoom)
|
||||
|
||||
setZoom(newZoom)
|
||||
setPan({ x: newPanX, y: newPanY })
|
||||
}
|
||||
|
||||
const handleFit = () => {
|
||||
setZoom(baseScale)
|
||||
const x = (conW - imgW * baseScale) / 2
|
||||
const y = (conH - imgH * baseScale) / 2
|
||||
setPan({ x, y })
|
||||
}
|
||||
|
||||
let bestUrl = file.media?.original?.downloadUrl
|
||||
|
||||
if (isImage) {
|
||||
const bestTranscode = getBestTranscode(file.media?.imageTranscodes, screenWidth)
|
||||
if (bestTranscode?.url) {
|
||||
bestUrl = bestTranscode.url
|
||||
}
|
||||
}
|
||||
|
||||
const handleDownload = () => {
|
||||
const url = file.media?.original?.downloadUrl
|
||||
if (!url) return
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = file.name || 'image'
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
}
|
||||
|
||||
const handleCopy = async () => {
|
||||
const webpUrl = bestUrl
|
||||
if (!webpUrl) return
|
||||
try {
|
||||
// To support Safari and iOS, we must invoke navigator.clipboard.write
|
||||
// synchronously inside the click handler. We can pass a promise to ClipboardItem
|
||||
// which resolves to the Blob asynchronously.
|
||||
const copyPromise = (async () => {
|
||||
const response = await fetch(webpUrl)
|
||||
const blob = await response.blob()
|
||||
|
||||
const img = new Image()
|
||||
img.crossOrigin = 'anonymous'
|
||||
const objectUrl = URL.createObjectURL(blob)
|
||||
img.src = objectUrl
|
||||
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
img.onload = resolve
|
||||
img.onerror = (e) => reject(new Error('Failed to load image: ' + String(e)))
|
||||
})
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = img.width
|
||||
canvas.height = img.height
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) throw new Error('Could not get canvas context')
|
||||
ctx.drawImage(img, 0, 0)
|
||||
|
||||
const pngBlob = await new Promise<Blob | null>((resolve) => {
|
||||
canvas.toBlob(resolve, 'image/png')
|
||||
})
|
||||
|
||||
if (!pngBlob) throw new Error('Failed to convert image to PNG')
|
||||
return pngBlob
|
||||
} finally {
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
})()
|
||||
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
'image/png': copyPromise,
|
||||
}),
|
||||
])
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
} catch (err) {
|
||||
console.error('Failed to copy image to clipboard:', err)
|
||||
}
|
||||
}
|
||||
|
||||
if (!bestUrl) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-muted-foreground">Preview unavailable</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Combine saved annotations and draft annotations
|
||||
const displayAnnotations = [...(annotations || []), ...draftAnnotations]
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative">
|
||||
{isImage && (
|
||||
<>
|
||||
<div ref={containerRef} className="flex-1 relative overflow-hidden">
|
||||
<DrawingCanvas
|
||||
width={conW}
|
||||
height={conH}
|
||||
mediaDimensions={{
|
||||
width: imgW,
|
||||
height: imgH,
|
||||
}}
|
||||
imageUrl={bestUrl}
|
||||
annotations={displayAnnotations}
|
||||
scale={zoom}
|
||||
offset={pan}
|
||||
onPan={setPan}
|
||||
className="absolute inset-0 z-0"
|
||||
// Drawing Props
|
||||
isDrawing={isDrawing}
|
||||
currentTool={currentTool}
|
||||
currentColor={currentColor}
|
||||
onAddAnnotation={addAnnotation}
|
||||
/>
|
||||
</div>
|
||||
{/* Zoom Toolbar */}
|
||||
<div className="relative px-4 py-3 bg-gray-50 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
|
||||
<div className="flex items-center gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5 mr-auto">
|
||||
<button
|
||||
onClick={() => handleZoom(0.8)}
|
||||
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
|
||||
title="Zoom Out"
|
||||
>
|
||||
<Minus size={16} />
|
||||
</button>
|
||||
<span className="w-12 text-center text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none">
|
||||
{Math.round(zoom * 100)}%
|
||||
</span>
|
||||
<button
|
||||
onClick={() => handleZoom(1.2)}
|
||||
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
|
||||
title="Zoom In"
|
||||
>
|
||||
<Plus size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleFit}
|
||||
className="text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent animate-in fade-in zoom-in-95 duration-200"
|
||||
>
|
||||
Fit
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
disabled={!bestUrl}
|
||||
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
|
||||
title="Copy optimized image to clipboard"
|
||||
>
|
||||
{copied ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDownload}
|
||||
disabled={!file.media?.original?.downloadUrl}
|
||||
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
|
||||
title="Download original image"
|
||||
>
|
||||
<Download size={14} />
|
||||
Download
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{isVideo && (
|
||||
<VideoPlayer
|
||||
data={file}
|
||||
playerRef={videoRef}
|
||||
onPlay={onPlay}
|
||||
onPause={onPause}
|
||||
onTimeUpdate={onTimeUpdate}
|
||||
annotations={displayAnnotations}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,593 @@
|
||||
import type { AssetInfoPaginatedList, AssetInfo } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useMatch, useNavigate, useParams } from '@tanstack/react-router'
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronsDownUp,
|
||||
ChevronsUpDown,
|
||||
ChevronRight,
|
||||
Clapperboard,
|
||||
Folder,
|
||||
Loader2,
|
||||
Trash2,
|
||||
Plus,
|
||||
Share2,
|
||||
LayoutGrid,
|
||||
Bookmark,
|
||||
} from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { useDraggable, useDroppable } from '@dnd-kit/react'
|
||||
import type { DragState } from './dnd-types'
|
||||
import { toast } from 'sonner'
|
||||
import type { ShareLinkInfo } from '@shumai/dtos'
|
||||
import type { CollectionInfo } from '@shumai/dtos'
|
||||
|
||||
interface FolderTreeProps {
|
||||
teamId: string
|
||||
projectId: string
|
||||
projectName: string
|
||||
rootFolderId: string
|
||||
dragState?: DragState
|
||||
onSelect?: (folder: AssetInfo) => void
|
||||
selectedFolderId?: string
|
||||
hideCollections?: boolean
|
||||
hideShares?: boolean
|
||||
}
|
||||
|
||||
export function FolderTree({
|
||||
teamId,
|
||||
projectId,
|
||||
projectName,
|
||||
rootFolderId,
|
||||
dragState,
|
||||
onSelect,
|
||||
selectedFolderId,
|
||||
hideCollections,
|
||||
hideShares,
|
||||
}: FolderTreeProps) {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const isRecentlyDeleted = useMatch({
|
||||
from: '/projects/$projectId/recently-deleted',
|
||||
shouldThrow: false,
|
||||
})
|
||||
|
||||
const [isAssetsExpanded, setIsAssetsExpanded] = useState(true)
|
||||
const [isCollectionsExpanded, setIsCollectionsExpanded] = useState(true)
|
||||
const [isSharesExpanded, setIsSharesExpanded] = useState(true)
|
||||
|
||||
const { data: shareLinksData } = useQuery({
|
||||
queryKey: ['shares', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].shares.$get({
|
||||
param: { projectId },
|
||||
query: { first: '100' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch share links')
|
||||
return (await res.json()) as unknown as { data: ShareLinkInfo[] }
|
||||
},
|
||||
enabled: !!projectId,
|
||||
})
|
||||
|
||||
const { data: collectionsData } = useQuery({
|
||||
queryKey: ['collections', projectId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].collections.$get({
|
||||
param: { projectId },
|
||||
query: { first: '100' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch collections')
|
||||
return (await res.json()) as unknown as { data: CollectionInfo[] }
|
||||
},
|
||||
enabled: !!projectId,
|
||||
})
|
||||
|
||||
const { mutate: createCollection } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].collections.$post({
|
||||
param: { projectId },
|
||||
json: {
|
||||
name: 'Untitled Collection',
|
||||
filter: {
|
||||
sourceFolderId: rootFolderId,
|
||||
searchFilter: {
|
||||
conditions: [],
|
||||
recursively: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to create collection')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['collections', projectId] })
|
||||
toast.success('Collection created')
|
||||
navigate({
|
||||
to: '/projects/$projectId/collections/$collectionId',
|
||||
params: { projectId, collectionId: data.id },
|
||||
})
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const { mutate: createShareLink } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.projects[':projectId'].shares.$post({
|
||||
param: { projectId },
|
||||
json: {
|
||||
name: new Date().toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
}),
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to create share link')
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
|
||||
toast.success('Share link created')
|
||||
navigate({
|
||||
to: '/projects/$projectId/shares/$shareId',
|
||||
params: { projectId, shareId: data.id },
|
||||
})
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
})
|
||||
|
||||
const shareLinks = shareLinksData?.data ?? []
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full overflow-hidden p-3 gap-4 bg-background">
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col overflow-hidden transition-all duration-300 ease-in-out border-b border-border pb-4',
|
||||
isAssetsExpanded ? 'flex-1 min-h-[50%] h-full' : 'flex-none h-[44px] max-h-[44px]',
|
||||
)}
|
||||
>
|
||||
<header className="group flex items-center justify-between px-2 mb-1 flex-none">
|
||||
<div
|
||||
className="flex-1 flex items-center gap-1.5 cursor-pointer select-none text-muted-foreground hover:text-foreground transition-colors"
|
||||
onClick={() => setIsAssetsExpanded(!isAssetsExpanded)}
|
||||
>
|
||||
<h3 className="text-xs font-semibold uppercase tracking-wider">Assets</h3>
|
||||
{isAssetsExpanded ? (
|
||||
<ChevronsDownUp className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
|
||||
) : (
|
||||
<ChevronsUpDown className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
|
||||
)}
|
||||
</div>
|
||||
<button className="text-muted-foreground hover:text-foreground flex-none">
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'flex-1 overflow-y-auto min-h-0 space-y-0.5 pr-1 transition-all duration-300 ease-in-out',
|
||||
isAssetsExpanded
|
||||
? 'opacity-100 visible pointer-events-auto'
|
||||
: 'opacity-0 invisible pointer-events-none h-0',
|
||||
)}
|
||||
>
|
||||
<FolderTreeItem
|
||||
key={rootFolderId}
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
folder={{
|
||||
id: rootFolderId,
|
||||
name: projectName,
|
||||
type: 'folder',
|
||||
sizeByte: 0,
|
||||
fileCount: 0,
|
||||
status: 'processed',
|
||||
mediaType: null,
|
||||
createdAt: '',
|
||||
updatedAt: '',
|
||||
}}
|
||||
level={0}
|
||||
isRoot={true}
|
||||
dragState={dragState}
|
||||
onSelect={onSelect}
|
||||
selectedFolderId={selectedFolderId}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
'group flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
isRecentlyDeleted && 'bg-sidebar-accent text-sidebar-accent-foreground font-medium',
|
||||
)}
|
||||
onClick={() =>
|
||||
navigate({
|
||||
to: '/projects/$projectId/recently-deleted',
|
||||
params: { projectId },
|
||||
})
|
||||
}
|
||||
>
|
||||
<div className="flex h-4 w-4 items-center justify-center">
|
||||
<Trash2 className="h-4 w-4 text-sidebar-primary" />
|
||||
</div>
|
||||
<span className="flex-1 truncate text-sidebar-foreground">Recently Deleted</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!hideCollections && (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col overflow-hidden transition-all duration-300 ease-in-out border-b border-border pb-4',
|
||||
isCollectionsExpanded ? 'flex-1 min-h-0 h-full' : 'flex-none h-[44px] max-h-[44px]',
|
||||
)}
|
||||
>
|
||||
<header className="group flex items-center justify-between px-2 mb-1 flex-none">
|
||||
<div
|
||||
className="flex-1 flex items-center gap-1.5 cursor-pointer select-none text-muted-foreground hover:text-foreground transition-colors"
|
||||
onClick={() => setIsCollectionsExpanded(!isCollectionsExpanded)}
|
||||
>
|
||||
<h3 className="text-xs font-semibold uppercase tracking-wider">Collections</h3>
|
||||
{isCollectionsExpanded ? (
|
||||
<ChevronsDownUp className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
|
||||
) : (
|
||||
<ChevronsUpDown className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => createCollection()}
|
||||
className="text-muted-foreground hover:text-foreground flex-none"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'flex-1 overflow-y-auto min-h-0 space-y-0.5 pr-1 transition-all duration-300 ease-in-out',
|
||||
isCollectionsExpanded
|
||||
? 'opacity-100 visible pointer-events-auto'
|
||||
: 'opacity-0 invisible pointer-events-none h-0',
|
||||
)}
|
||||
>
|
||||
{collectionsData?.data.map((collection) => (
|
||||
<div
|
||||
key={collection.id}
|
||||
className="group flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
|
||||
onClick={() =>
|
||||
navigate({
|
||||
to: '/projects/$projectId/collections/$collectionId',
|
||||
params: { projectId, collectionId: collection.id },
|
||||
})
|
||||
}
|
||||
>
|
||||
<div className="flex h-4 w-4 items-center justify-center">
|
||||
<Bookmark className="h-4 w-4 text-sidebar-primary" />
|
||||
</div>
|
||||
<span className="flex-1 truncate text-sidebar-foreground">{collection.name}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!hideShares && (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col overflow-hidden transition-all duration-300 ease-in-out border-b border-border pb-4',
|
||||
isSharesExpanded ? 'flex-1 min-h-0 h-full' : 'flex-none h-[44px] max-h-[44px]',
|
||||
)}
|
||||
>
|
||||
<header className="group flex items-center justify-between px-2 mb-1 flex-none">
|
||||
<div
|
||||
className="flex-1 flex items-center gap-1.5 cursor-pointer select-none text-muted-foreground hover:text-foreground transition-colors"
|
||||
onClick={() => setIsSharesExpanded(!isSharesExpanded)}
|
||||
>
|
||||
<h3 className="text-xs font-semibold uppercase tracking-wider">Share Links</h3>
|
||||
{isSharesExpanded ? (
|
||||
<ChevronsDownUp className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
|
||||
) : (
|
||||
<ChevronsUpDown className="h-3.5 w-3.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 flex-none">
|
||||
<button
|
||||
onClick={() => createShareLink()}
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'flex-1 overflow-y-auto min-h-0 space-y-0.5 pr-1 transition-all duration-300 ease-in-out',
|
||||
isSharesExpanded
|
||||
? 'opacity-100 visible pointer-events-auto'
|
||||
: 'opacity-0 invisible pointer-events-none h-0',
|
||||
)}
|
||||
>
|
||||
<div className="group flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground">
|
||||
<div className="flex h-4 w-4 items-center justify-center">
|
||||
<LayoutGrid className="h-4 w-4 text-sidebar-primary" />
|
||||
</div>
|
||||
<span className="flex-1 truncate text-sidebar-foreground">
|
||||
All Share Links ({shareLinks.length})
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{shareLinks.map((link) => (
|
||||
<ShareLinkItem
|
||||
key={link.id}
|
||||
link={link}
|
||||
projectId={projectId}
|
||||
dragState={dragState}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ShareLinkItem({
|
||||
link,
|
||||
projectId,
|
||||
dragState,
|
||||
}: {
|
||||
link: ShareLinkInfo
|
||||
projectId: string
|
||||
dragState?: DragState
|
||||
}) {
|
||||
const navigate = useNavigate()
|
||||
const params = useParams({
|
||||
from: '/projects/$projectId/shares/$shareId',
|
||||
shouldThrow: false,
|
||||
})
|
||||
const isActive = params?.shareId === link.id
|
||||
|
||||
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
|
||||
id: `share:${link.id}`,
|
||||
data: {
|
||||
type: 'share-link',
|
||||
id: link.id,
|
||||
},
|
||||
})
|
||||
|
||||
const isValidDropTarget = !!dragState?.isActive
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setDroppableRef}
|
||||
className={cn(
|
||||
'group flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
isActive && 'bg-sidebar-accent text-sidebar-accent-foreground font-medium',
|
||||
isOver && isValidDropTarget && 'bg-sidebar-accent ring-2 ring-primary ring-inset',
|
||||
)}
|
||||
onClick={() =>
|
||||
navigate({
|
||||
to: '/projects/$projectId/shares/$shareId',
|
||||
params: { projectId, shareId: link.id },
|
||||
})
|
||||
}
|
||||
>
|
||||
<div className="flex h-4 w-4 items-center justify-center">
|
||||
<Share2 className="h-4 w-4 text-sidebar-primary" />
|
||||
</div>
|
||||
<span className="flex-1 truncate text-sidebar-foreground">{link.name}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface FolderTreeItemProps {
|
||||
teamId: string
|
||||
projectId: string
|
||||
folder: AssetInfo
|
||||
level: number
|
||||
isRoot?: boolean
|
||||
dragState?: DragState
|
||||
onSelect?: (folder: AssetInfo) => void
|
||||
selectedFolderId?: string
|
||||
}
|
||||
|
||||
function FolderTreeItem({
|
||||
teamId,
|
||||
projectId,
|
||||
folder,
|
||||
level,
|
||||
isRoot,
|
||||
dragState,
|
||||
onSelect,
|
||||
selectedFolderId,
|
||||
}: FolderTreeItemProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(isRoot || false)
|
||||
const navigate = useNavigate()
|
||||
const params = useParams({
|
||||
from: '/projects/$projectId/folders/$folderId',
|
||||
select: (p) => ({ folderId: p.folderId }),
|
||||
shouldThrow: false,
|
||||
})
|
||||
const rootParams = useParams({
|
||||
from: '/projects/$projectId/',
|
||||
shouldThrow: false,
|
||||
})
|
||||
const isActive = isRoot ? !!rootParams : params?.folderId === folder.id
|
||||
|
||||
const {
|
||||
data: childrenData,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
isLoading,
|
||||
} = useInfiniteQuery<AssetInfoPaginatedList>({
|
||||
queryKey: [
|
||||
'folders',
|
||||
folder.id,
|
||||
'children',
|
||||
{
|
||||
assetType: 'folder',
|
||||
},
|
||||
],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.folders[':folderId'].children.$get({
|
||||
param: { folderId: folder.id },
|
||||
query: {
|
||||
assetType: 'folder',
|
||||
after: pageParam as string,
|
||||
first: '20',
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to fetch folder children')
|
||||
return (await res.json()) as unknown as AssetInfoPaginatedList
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => {
|
||||
return lastPage.pageInfo?.cursor || undefined
|
||||
},
|
||||
enabled: isExpanded || !!isRoot,
|
||||
})
|
||||
|
||||
const { ref, inView } = useInView()
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
|
||||
const childrenFolders = childrenData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||
|
||||
const handleToggleExpand = (e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
setIsExpanded(!isExpanded)
|
||||
}
|
||||
|
||||
const handleFolderClick = () => {
|
||||
if (onSelect) {
|
||||
onSelect(folder)
|
||||
return
|
||||
}
|
||||
|
||||
if (isRoot) {
|
||||
navigate({
|
||||
to: '/projects/$projectId',
|
||||
params: { projectId },
|
||||
})
|
||||
} else {
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
params: { projectId, folderId: folder.id! },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const { ref: setDraggableRef, isDragging } = useDraggable({
|
||||
id: `tree:${folder.id!}`,
|
||||
data: {
|
||||
type: 'folder',
|
||||
item: folder,
|
||||
},
|
||||
disabled: !!isRoot || !!onSelect,
|
||||
})
|
||||
|
||||
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
|
||||
id: `tree:${folder.id!}`,
|
||||
data: {
|
||||
type: 'folder',
|
||||
item: folder,
|
||||
},
|
||||
disabled: dragState?.draggedIds.has(folder.id!) || !!onSelect,
|
||||
})
|
||||
|
||||
const setNodeRef = (node: HTMLDivElement | null) => {
|
||||
setDraggableRef(node)
|
||||
setDroppableRef(node)
|
||||
}
|
||||
|
||||
const isValidDropTarget = useMemo(() => {
|
||||
if (onSelect) return false
|
||||
if (!dragState?.isActive) return false
|
||||
if (dragState.draggedIds.has(folder.id!)) return false
|
||||
return true
|
||||
}, [dragState, folder.id, onSelect])
|
||||
|
||||
const showDropFeedback = isOver && isValidDropTarget
|
||||
|
||||
const isSelected = selectedFolderId === folder.id
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
className={cn(
|
||||
'group flex cursor-pointer items-center gap-1 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
(isActive || isSelected) &&
|
||||
'bg-sidebar-accent text-sidebar-accent-foreground font-medium',
|
||||
isDragging && 'opacity-50',
|
||||
showDropFeedback && 'bg-sidebar-accent ring-2 ring-primary ring-inset',
|
||||
)}
|
||||
style={{
|
||||
...(isRoot ? {} : { paddingLeft: `${level * 12 + 8}px` }),
|
||||
}}
|
||||
onClick={handleFolderClick}
|
||||
>
|
||||
{!isRoot && (
|
||||
<button onClick={handleToggleExpand} className="flex h-4 w-4 items-center justify-center">
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
) : (
|
||||
<ChevronRight className="h-3 w-3" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
{isRoot ? (
|
||||
<Clapperboard className="h-4 w-4 text-sidebar-primary" />
|
||||
) : (
|
||||
<Folder className="h-4 w-4 text-sidebar-primary" />
|
||||
)}
|
||||
<span className="flex-1 truncate text-sidebar-foreground">{folder.name}</span>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div>
|
||||
{isLoading && (
|
||||
<div
|
||||
className="flex items-center justify-center p-2"
|
||||
style={{ paddingLeft: `${(level + 1) * 12 + 8}px` }}
|
||||
>
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
{childrenFolders.map((child) => (
|
||||
<FolderTreeItem
|
||||
key={child.id}
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
folder={child}
|
||||
level={level + 1}
|
||||
dragState={dragState}
|
||||
onSelect={onSelect}
|
||||
selectedFolderId={selectedFolderId}
|
||||
/>
|
||||
))}
|
||||
{hasNextPage && (
|
||||
<div
|
||||
ref={ref}
|
||||
className="flex items-center justify-center p-2"
|
||||
style={{ paddingLeft: `${(level + 1) * 12 + 8}px` }}
|
||||
>
|
||||
{isFetchingNextPage && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
|
||||
interface GuestIdentityPopupProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onSuccess: (guestUserId: string) => void
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
export function GuestIdentityPopup({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSuccess,
|
||||
children,
|
||||
}: GuestIdentityPopupProps) {
|
||||
console.log('[GuestIdentityPopup] isOpen:', isOpen)
|
||||
const [name, setName] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const res = await client.api.identify.$post({
|
||||
json: { username: name, email: email },
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const data = (await res.json()) as { error?: string }
|
||||
throw new Error(data.error || 'Failed to identify')
|
||||
}
|
||||
|
||||
const { id } = await res.json()
|
||||
localStorage.setItem('guest_user_id', id)
|
||||
onSuccess(id)
|
||||
onClose()
|
||||
} catch (err) {
|
||||
setError((err as Error).message)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<PopoverTrigger asChild>{children}</PopoverTrigger>
|
||||
<PopoverContent className="w-80" align="end" side="top">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<h4 className="font-medium leading-none">Enter your details</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Please provide your name and email to add a comment.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<div className="grid gap-1">
|
||||
<Label htmlFor="name">Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="John Doe"
|
||||
size={32}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-1">
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="john@example.com"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && <p className="text-xs text-destructive">{error}</p>}
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" size="sm" disabled={isLoading}>
|
||||
{isLoading && <Loader2 className="mr-2 h-3 w-3 animate-spin" />}
|
||||
Confirm
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import {
|
||||
SELECTION_CHANGE_COMMAND,
|
||||
FORMAT_TEXT_COMMAND,
|
||||
$getSelection,
|
||||
$isRangeSelection,
|
||||
COMMAND_PRIORITY_CRITICAL,
|
||||
$createParagraphNode,
|
||||
} from 'lexical'
|
||||
import {
|
||||
$isListNode,
|
||||
ListNode,
|
||||
INSERT_ORDERED_LIST_COMMAND,
|
||||
INSERT_UNORDERED_LIST_COMMAND,
|
||||
REMOVE_LIST_COMMAND,
|
||||
} from '@lexical/list'
|
||||
import {
|
||||
$createHeadingNode,
|
||||
$createQuoteNode,
|
||||
$isHeadingNode,
|
||||
type HeadingTagType,
|
||||
} from '@lexical/rich-text'
|
||||
import { $createCodeNode } from '@lexical/code'
|
||||
import { $setBlocksType } from '@lexical/selection'
|
||||
import { $getNearestNodeOfType } from '@lexical/utils'
|
||||
import {
|
||||
Bold,
|
||||
Italic,
|
||||
Underline,
|
||||
Strikethrough,
|
||||
Code,
|
||||
Quote,
|
||||
List,
|
||||
ListOrdered,
|
||||
Type,
|
||||
Heading1,
|
||||
Heading2,
|
||||
Heading3,
|
||||
} from 'lucide-react'
|
||||
import { Toggle } from '@/ui/components/ui/toggle'
|
||||
import { Separator } from '@/ui/components/ui/separator'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
|
||||
const blockTypeToBlockName = {
|
||||
paragraph: 'Normal',
|
||||
h1: 'Heading 1',
|
||||
h2: 'Heading 2',
|
||||
h3: 'Heading 3',
|
||||
bullet: 'Bullet List',
|
||||
number: 'Numbered List',
|
||||
quote: 'Quote',
|
||||
code: 'Code Block',
|
||||
}
|
||||
|
||||
export function ToolbarPlugin() {
|
||||
const [editor] = useLexicalComposerContext()
|
||||
const [activeEditor, setActiveEditor] = useState(editor)
|
||||
const [isBold, setIsBold] = useState(false)
|
||||
const [isItalic, setIsItalic] = useState(false)
|
||||
const [isUnderline, setIsUnderline] = useState(false)
|
||||
const [isStrikethrough, setIsStrikethrough] = useState(false)
|
||||
const [isCode, setIsCode] = useState(false)
|
||||
const [blockType, setBlockType] = useState<keyof typeof blockTypeToBlockName>('paragraph')
|
||||
|
||||
const $updateToolbar = useCallback(() => {
|
||||
const selection = $getSelection()
|
||||
if ($isRangeSelection(selection)) {
|
||||
setIsBold(selection.hasFormat('bold'))
|
||||
setIsItalic(selection.hasFormat('italic'))
|
||||
setIsUnderline(selection.hasFormat('underline'))
|
||||
setIsStrikethrough(selection.hasFormat('strikethrough'))
|
||||
setIsCode(selection.hasFormat('code'))
|
||||
|
||||
const anchorNode = selection.anchor.getNode()
|
||||
const element =
|
||||
anchorNode.getKey() === 'root' ? anchorNode : anchorNode.getTopLevelElementOrThrow()
|
||||
const elementKey = element.getKey()
|
||||
const elementDom = activeEditor.getElementByKey(elementKey)
|
||||
|
||||
if (elementDom !== null) {
|
||||
if ($isListNode(element)) {
|
||||
const parentList = $getNearestNodeOfType(anchorNode, ListNode)
|
||||
const type = parentList ? parentList.getListType() : element.getListType()
|
||||
setBlockType(type as keyof typeof blockTypeToBlockName)
|
||||
} else {
|
||||
const type = $isHeadingNode(element) ? element.getTag() : element.getType()
|
||||
if (type in blockTypeToBlockName) {
|
||||
setBlockType(type as keyof typeof blockTypeToBlockName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [activeEditor])
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerCommand(
|
||||
SELECTION_CHANGE_COMMAND,
|
||||
(_payload, newEditor) => {
|
||||
$updateToolbar()
|
||||
setActiveEditor(newEditor)
|
||||
return false
|
||||
},
|
||||
COMMAND_PRIORITY_CRITICAL,
|
||||
)
|
||||
}, [editor, $updateToolbar])
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerUpdateListener(({ editorState }) => {
|
||||
editorState.read(() => {
|
||||
$updateToolbar()
|
||||
})
|
||||
})
|
||||
}, [editor, $updateToolbar])
|
||||
|
||||
const formatParagraph = () => {
|
||||
if (blockType !== 'paragraph') {
|
||||
activeEditor.update(() => {
|
||||
const selection = $getSelection()
|
||||
if ($isRangeSelection(selection)) {
|
||||
$setBlocksType(selection, () => $createParagraphNode())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const formatHeading = (headingSize: HeadingTagType) => {
|
||||
if (blockType !== headingSize) {
|
||||
activeEditor.update(() => {
|
||||
const selection = $getSelection()
|
||||
if ($isRangeSelection(selection)) {
|
||||
$setBlocksType(selection, () => $createHeadingNode(headingSize))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const formatBulletList = () => {
|
||||
if (blockType !== 'bullet') {
|
||||
activeEditor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined)
|
||||
} else {
|
||||
activeEditor.dispatchCommand(REMOVE_LIST_COMMAND, undefined)
|
||||
}
|
||||
}
|
||||
|
||||
const formatNumberedList = () => {
|
||||
if (blockType !== 'number') {
|
||||
activeEditor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined)
|
||||
} else {
|
||||
activeEditor.dispatchCommand(REMOVE_LIST_COMMAND, undefined)
|
||||
}
|
||||
}
|
||||
|
||||
const formatQuote = () => {
|
||||
if (blockType !== 'quote') {
|
||||
activeEditor.update(() => {
|
||||
const selection = $getSelection()
|
||||
if ($isRangeSelection(selection)) {
|
||||
$setBlocksType(selection, () => $createQuoteNode())
|
||||
}
|
||||
})
|
||||
} else {
|
||||
formatParagraph()
|
||||
}
|
||||
}
|
||||
|
||||
const formatCode = () => {
|
||||
if (blockType !== 'code') {
|
||||
activeEditor.update(() => {
|
||||
const selection = $getSelection()
|
||||
if ($isRangeSelection(selection)) {
|
||||
$setBlocksType(selection, () => $createCodeNode())
|
||||
}
|
||||
})
|
||||
} else {
|
||||
formatParagraph()
|
||||
}
|
||||
}
|
||||
|
||||
const handleBlockTypeChange = (value: string) => {
|
||||
switch (value) {
|
||||
case 'paragraph':
|
||||
formatParagraph()
|
||||
break
|
||||
case 'h1':
|
||||
formatHeading('h1')
|
||||
break
|
||||
case 'h2':
|
||||
formatHeading('h2')
|
||||
break
|
||||
case 'h3':
|
||||
formatHeading('h3')
|
||||
break
|
||||
case 'bullet':
|
||||
formatBulletList()
|
||||
break
|
||||
case 'number':
|
||||
formatNumberedList()
|
||||
break
|
||||
case 'quote':
|
||||
formatQuote()
|
||||
break
|
||||
case 'code':
|
||||
formatCode()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="toolbar bg-background border-b border-border flex items-center p-1 gap-1 sticky top-0 z-10 flex-wrap">
|
||||
<Select value={blockType} onValueChange={handleBlockTypeChange}>
|
||||
<SelectTrigger className="h-8 w-[140px] border-none shadow-none focus:ring-0">
|
||||
<SelectValue placeholder="Normal" />
|
||||
</SelectTrigger>
|
||||
<SelectContent
|
||||
onCloseAutoFocus={(e) => {
|
||||
e.preventDefault()
|
||||
activeEditor.focus()
|
||||
}}
|
||||
>
|
||||
<SelectItem value="paragraph">
|
||||
<div className="flex items-center gap-2">
|
||||
<Type className="h-4 w-4" /> Normal
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="h1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Heading1 className="h-4 w-4" /> Heading 1
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="h2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Heading2 className="h-4 w-4" /> Heading 2
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="h3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Heading3 className="h-4 w-4" /> Heading 3
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="number">
|
||||
<div className="flex items-center gap-2">
|
||||
<ListOrdered className="h-4 w-4" /> Numbered List
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="bullet">
|
||||
<div className="flex items-center gap-2">
|
||||
<List className="h-4 w-4" /> Bullet List
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="quote">
|
||||
<div className="flex items-center gap-2">
|
||||
<Quote className="h-4 w-4" /> Quote
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="code">
|
||||
<div className="flex items-center gap-2">
|
||||
<Code className="h-4 w-4" /> Code Block
|
||||
</div>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Separator orientation="vertical" className="h-6 mx-1" />
|
||||
|
||||
<Toggle
|
||||
size="sm"
|
||||
pressed={isBold}
|
||||
onPressedChange={() => {
|
||||
activeEditor.dispatchCommand(FORMAT_TEXT_COMMAND, 'bold')
|
||||
}}
|
||||
aria-label="Format Bold"
|
||||
>
|
||||
<Bold className="h-4 w-4" />
|
||||
</Toggle>
|
||||
<Toggle
|
||||
size="sm"
|
||||
pressed={isItalic}
|
||||
onPressedChange={() => {
|
||||
activeEditor.dispatchCommand(FORMAT_TEXT_COMMAND, 'italic')
|
||||
}}
|
||||
aria-label="Format Italic"
|
||||
>
|
||||
<Italic className="h-4 w-4" />
|
||||
</Toggle>
|
||||
<Toggle
|
||||
size="sm"
|
||||
pressed={isUnderline}
|
||||
onPressedChange={() => {
|
||||
activeEditor.dispatchCommand(FORMAT_TEXT_COMMAND, 'underline')
|
||||
}}
|
||||
aria-label="Format Underline"
|
||||
>
|
||||
<Underline className="h-4 w-4" />
|
||||
</Toggle>
|
||||
<Toggle
|
||||
size="sm"
|
||||
pressed={isStrikethrough}
|
||||
onPressedChange={() => {
|
||||
activeEditor.dispatchCommand(FORMAT_TEXT_COMMAND, 'strikethrough')
|
||||
}}
|
||||
aria-label="Format Strikethrough"
|
||||
>
|
||||
<Strikethrough className="h-4 w-4" />
|
||||
</Toggle>
|
||||
<Toggle
|
||||
size="sm"
|
||||
pressed={isCode}
|
||||
onPressedChange={() => {
|
||||
activeEditor.dispatchCommand(FORMAT_TEXT_COMMAND, 'code')
|
||||
}}
|
||||
aria-label="Insert Code"
|
||||
>
|
||||
<Code className="h-4 w-4" />
|
||||
</Toggle>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user