Compare commits

...
63 Commits
Author SHA1 Message Date
yiling 7753721731 Release v0.0.8 2026-06-19 20:42:48 +08:00
Yiling-J ef86cc2713 Merge pull request #138 from shumaiOne/feat/upload-progress-xhr
feat(upload): track byte-level progress with XMLHttpRequest
2026-06-19 20:11:28 +08:00
yiling cc79be7e34 fix(upload): resolve filesToUpload mutation race condition
Capture the files list snapshot at the time the mutation is triggered via React Query's onMutate context, and retrieve it in onSuccess via the context parameter to prevent race conditions during rapid upload successions.
2026-06-19 20:05:02 +08:00
yiling a9c5a3d9fd fix(ui): resolve Cannot access 'displayItem' before initialization ReferenceError
Use item.id directly since it is available at the start of the component from props.
2026-06-19 19:49:30 +08:00
yiling 0d9545f0b5 feat(upload): track byte-level progress with XMLHttpRequest
- Replace fetch uploads with XMLHttpRequest to capture upload progress
- Track active upload tasks and file progress in Zustand store
- Show byte-level uploader progress in the sidebar list
- Replace plain 'Uploading' card status text with a circular percentage animation
- Replace plain document icon in file list view rows with a mini progress circle
2026-06-19 19:44:35 +08:00
Yiling-J 2925fb6bf6 Merge pull request #137 from shumaiOne/feature/switch-and-rating-filter
feat(webui): use Shadcn Switch in toggle field and Rating component in search filter panel
2026-06-19 15:58:41 +08:00
yiling 7ae34a4bc0 feat(webui): use Shadcn Switch in toggle field and Rating component in search filter panel 2026-06-19 15:49:54 +08:00
Yiling-J f645c8fefa Merge pull request #136 from shumaiOne/fix-ui-issues
fix(webui): resolve folder tree sync, search dialog reset, and sidebar actions issues
2026-06-19 15:17:46 +08:00
yiling 1835016a9b fix(webui): use poster field instead of thumbnail for video notifications 2026-06-19 13:34:14 +08:00
yiling 5e92660d1c fix(webui): render sprite image scrubber for video upload notifications 2026-06-19 13:25:00 +08:00
yiling 6cb3ca6874 fix(webui): resolve folder tree sync, search dialog reset, and sidebar actions issues
- Change query key invalidation of folders to the generic ['folders'] key to update the sidebar tree on create/rename/delete/move
- Separate search box from custom filters reset button in search dialog
- Remove unused plus icon from Assets sidebar header
- Add dropdown menu (rename, download, delete) to subfolder tree items in the sidebar
2026-06-19 12:55:30 +08:00
Yiling-J 5d14f4fff1 Merge pull request #135 from shumaiOne/fix/search-dialog-ui-improvements
style(webui): fix search dialog layout height, scroll areas, and restrict filter toggle click
2026-06-19 12:32:30 +08:00
yiling 009566d42f style(webui): add min-h-0 to search results scroll area to allow scrolling 2026-06-19 12:23:15 +08:00
yiling 50777d332b style(webui): fix search dialog layout height, scroll areas, and restrict filter toggle click 2026-06-19 12:11:19 +08:00
Yiling-J 852a9873dc Merge pull request #134 from shumaiOne/fix/search-has-any
fix(search): fix hasAny and hasNone operators on metadata filter
2026-06-19 11:37:35 +08:00
yiling aa265c5322 fix(search): fix hasAny and hasNone operators on metadata filter 2026-06-19 11:29:26 +08:00
Yiling-J 01ab254c21 Merge pull request #133 from shumaiOne/ui/default-right-sidebar-collapsed
feat(webui): default right sidebar to collapsed for new users
2026-06-19 11:03:27 +08:00
yiling ca5ca5e080 feat(share): default right sidebar to collapsed on public share list page and expanded on detail page 2026-06-19 10:58:38 +08:00
yiling 3f27439733 feat(share): show right sidebar toggle in public share topnav and make collapse state local 2026-06-19 10:53:01 +08:00
yiling 2a611f9b5a fix(share): sync layout options and support right sidebar collapse on public page 2026-06-19 10:44:22 +08:00
yiling 7137e00911 fix(share): resolve share link drag-and-drop error and public view render loop 2026-06-19 10:32:21 +08:00
yiling 59db97aedf fix(share): fix right sidebar layout overflow and button cutoff under topnav 2026-06-19 10:24:58 +08:00
yiling a76dbdfc22 feat(share): improve share config page sidebars, layout options, and sorting 2026-06-19 10:22:20 +08:00
yiling 61e2a3c53a feat(webui): add separate sidebar configs for share config pages 2026-06-19 09:57:29 +08:00
yiling 7707498916 feat(webui): default right sidebar to collapsed for new users 2026-06-19 09:50:02 +08:00
Yiling-J 91c8af86db Merge pull request #132 from shumaiOne/feat/demo-mode-refinement
feat(auth): refine demo mode support
2026-06-19 00:44:00 +08:00
Yiling-Jandgemini-code-assist[bot] 286d71133f Update packages/webui/routes/signup.tsx
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-06-19 00:39:02 +08:00
yiling 53c132e41d feat(auth): refine demo mode support using SHUMAI_DEMO_MODE API 2026-06-19 00:36:23 +08:00
Yiling-J 5c285b172b Merge pull request #131 from shumaiOne/feat/demo-mode-support
feat(auth): add demo mode support
2026-06-19 00:22:26 +08:00
yiling f1d52ac44e feat(auth): add demo mode support using PUBLIC_DEMO_MODE 2026-06-19 00:17:14 +08:00
Yiling-J ec6736b452 Merge pull request #130 from shumaiOne/fix/field-colors-and-filter-selects
fix(webui): use system colors for fields and improve search filter select options
2026-06-18 23:27:48 +08:00
yiling 46c975836a fix(webui): render selectMulti 'is exactly' operator as single-select 2026-06-18 23:22:36 +08:00
yiling 5d7ea7d118 refactor(webui): use Popover instead of Combobox for search dialog MultiSelect 2026-06-18 23:18:17 +08:00
yiling 5065346e8a fix(webui): support fallback options for selectMulti fields in filter panel 2026-06-18 23:13:51 +08:00
yiling 60d469c91b fix(webui): use system colors for fields and improve search filter select options 2026-06-18 23:03:57 +08:00
Yiling-J f68c1c56e1 Merge pull request #129 from shumaiOne/fix/project-updated-at-asset-hook
fix(db): automatically update project updatedAt on asset modification
2026-06-18 22:44:20 +08:00
yiling 08cf90477a fix(db): inline project updatedAt touch on asset update 2026-06-18 22:39:23 +08:00
yiling e01c348fde fix(db): automatically update project updatedAt on asset modification 2026-06-18 21:53:16 +08:00
Yiling-J b0eb5b1eef Merge pull request #128 from shumaiOne/feat/video-search-jump-timestamp
feat(webui): support jumping to video timestamp from search results
2026-06-18 21:06:58 +08:00
yiling 3b7fc410b2 feat(webui): support jumping to video timestamp from search results 2026-06-18 20:35:50 +08:00
Yiling-J 4c7ff6f58f Merge pull request #127 from shumaiOne/feat/semantic-search-chunk-overlap
feat(agent): implement overlapping video chunks for semantic search
2026-06-18 20:02:26 +08:00
yiling a197c83580 fix(agent): prevent redundant final video chunks in embedding workflow 2026-06-18 19:57:01 +08:00
yiling 718d9d5b51 feat(transcode): optimize video chunks for embedding by forcing 1 FPS and dropping audio 2026-06-18 19:53:19 +08:00
yiling 212ac3bc0e docs(search): add detail about video chunking and configuration to semantic search docs 2026-06-18 19:46:50 +08:00
yiling eaf2c867b3 feat(agent): implement overlapping video chunks for semantic search and update docs 2026-06-18 19:45:58 +08:00
Yiling-J 570d95fa6f Merge pull request #126 from shumaiOne/feat/external-drag-drop
feat(webui): add external drag-and-drop file and folder upload support
2026-06-18 16:21:23 +08:00
yiling 32892a21c1 fix(webui): guard external drag and drop in share, public, and collection views 2026-06-18 16:13:40 +08:00
yiling 7819a2034e fix(webui): clear external drag state synchronously on folder drops 2026-06-18 15:58:34 +08:00
yiling e0f2698a66 feat(webui): add external drag-and-drop file and folder upload support 2026-06-18 15:39:08 +08:00
Yiling-J 72c50ffd73 Merge pull request #125 from shumaiOne/improve-embedding-workflow
feat(embedding): defer embedding workflow, use transcoded assets, and execute chunks in separate activities
2026-06-18 15:02:21 +08:00
yiling d84950d372 feat(transcode): set loglevel to warning for all ffmpeg commands 2026-06-18 11:57:38 +08:00
yiling 46815736e2 feat(embedding): decouple video chunk transcode and embedding generation 2026-06-18 11:54:30 +08:00
yiling 9d1e8378f7 fix(embedding): resolve transcoded MIME type and validate EMBEDDING_CHUNK_DURATION positive limits 2026-06-18 11:14:09 +08:00
yiling f399d2c469 feat(embedding): defer embedding workflow, use transcoded assets, and execute chunks in separate activities 2026-06-18 10:57:22 +08:00
Yiling-J 4af081f128 Merge pull request #124 from shumaiOne/feat/custom-server-port
feat(server): allow customizing server port via SHUMAI_SERVER_PORT
2026-06-18 10:32:36 +08:00
yiling ce457e1161 fix(s3): remove port from AWS_ENDPOINT_URL_S3 and sync with server port in local mode 2026-06-18 10:22:16 +08:00
yiling a69dd6a660 feat(server): allow customizing server port via SHUMAI_SERVER_PORT 2026-06-18 10:08:31 +08:00
Yiling-J 62d7061cb3 Merge pull request #123 from shumaiOne/fix/fps-transcode-failure
fix(transcode): handle high-precision FPS using rational fractions
2026-06-18 09:24:11 +08:00
yiling 1ad5720f42 fix(transcode): handle high-precision FPS using rational fractions 2026-06-17 22:55:01 +08:00
Yiling-J 0be74dd4ab Merge pull request #122 from shumaiOne/feat/read-only-mode
feat(api): implement read-only mode for reviewers
2026-06-17 22:35:25 +08:00
yiling f4276a19aa feat(api): allow search API in read-only mode 2026-06-17 22:30:09 +08:00
yiling d81fc275f4 fix(api): correct lint errors in authMiddleware tests 2026-06-17 22:19:44 +08:00
yiling ead91455d8 feat(api): implement read-only mode for reviewers controlled by REVIEWER_READ_ONLY env 2026-06-17 21:51:34 +08:00
91 changed files with 2895 additions and 560 deletions
+1
View File
@@ -396,6 +396,7 @@ To prevent Temporal from indefinitely retrying fatal, expected business validati
## Radix UI / Shadcn UI Patterns ## Radix UI / Shadcn UI Patterns
- **Modal Overlays**: When triggering a dialog (e.g., `Dialog`, `AlertDialog`) from inside a `DropdownMenu`, you must set `modal={false}` on the `<DropdownMenu>` component. Failing to do so will cause the UI to freeze due to conflicting focus management between the two modal components. - **Modal Overlays**: When triggering a dialog (e.g., `Dialog`, `AlertDialog`) from inside a `DropdownMenu`, you must set `modal={false}` on the `<DropdownMenu>` component. Failing to do so will cause the UI to freeze due to conflicting focus management between the two modal components.
- **Scrollable Content**: Always use the Shadcn `ScrollArea` component (`@/ui/components/ui/scroll-area`) for scrollable content containers to ensure consistent custom scrollbar UI across the application.
## Logging ## Logging
+5 -4
View File
@@ -44,7 +44,7 @@ The easiest way to run Shumai is using Docker Compose. You do not need to clone
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose.yaml curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose.yaml
``` ```
2. Configure environment variables (if deploying remotely): 2. Configure environment variables (if deploying remotely):
If you are deploying Shumai to a remote server (e.g., AWS ECS, EC2, VPS), you must edit `docker-compose.yaml`, set `AWS_ENDPOINT_URL_S3` to your server's public IP or domain name (e.g., `http://12.345.567.789:3000`). If you are deploying Shumai to a remote server (e.g., AWS ECS, EC2, VPS), you must edit `docker-compose.yaml`, set `AWS_ENDPOINT_URL_S3` to your server's public IP or domain name (e.g., `http://12.345.567.789`).
3. Start the services: 3. Start the services:
```bash ```bash
docker compose up -d docker compose up -d
@@ -102,11 +102,12 @@ Create a `.env` file in this folder and add the following configuration (which a
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw= BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
STORAGE_BACKEND=local STORAGE_BACKEND=local
AWS_ENDPOINT_URL_S3=http://localhost:3000 SHUMAI_SERVER_PORT=3000
AWS_ENDPOINT_URL_S3=http://localhost
``` ```
> [!NOTE] > [!NOTE]
> If you are deploying on a remote server, make sure to change `AWS_ENDPOINT_URL_S3` from `http://localhost:3000` to your server's public IP address or domain name. > If you are deploying on a remote server, make sure to change `AWS_ENDPOINT_URL_S3` from `http://localhost` to your server's public IP address or domain name. `SHUMAI_SERVER_PORT` defaults to `3000` if not set.
#### Step 4: Run Shumai #### Step 4: Run Shumai
@@ -189,7 +190,7 @@ DATABASE_URL=postgresql://shumai:shumai_password@<host-ip>:5432/shumai_db?schema
WORKFLOW_EXECUTOR=temporal WORKFLOW_EXECUTOR=temporal
TEMPORAL_ADDRESS=<host-ip>:7233 TEMPORAL_ADDRESS=<host-ip>:7233
STORAGE_BACKEND=s3 STORAGE_BACKEND=s3
AWS_ENDPOINT_URL_S3=http://<host-ip>:3000 # Or your public S3/R2 endpoint URL AWS_ENDPOINT_URL_S3=http://<host-ip> # Or your public S3/R2 endpoint URL
S3_REGION=us-east-1 S3_REGION=us-east-1
S3_BUCKET=shumai S3_BUCKET=shumai
S3_ACCESS_KEY_ID=your-access-key-id S3_ACCESS_KEY_ID=your-access-key-id
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/agent-app", "name": "@shumai/agent-app",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"bin": { "bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/transcode-app", "name": "@shumai/transcode-app",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"bin": { "bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/web-app", "name": "@shumai/web-app",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"dependencies": { "dependencies": {
+4 -2
View File
@@ -44,10 +44,12 @@ if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
const isProd = process.env.NODE_ENV === 'production' const isProd = process.env.NODE_ENV === 'production'
const port = process.env.SHUMAI_SERVER_PORT ? parseInt(process.env.SHUMAI_SERVER_PORT) : 3000
const server = Bun.serve( const server = Bun.serve(
isProd isProd
? { ? {
port: 3000, port,
maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE
? parseInt(process.env.MAX_REQUEST_BODY_SIZE) ? parseInt(process.env.MAX_REQUEST_BODY_SIZE)
: 1024 * 1024 * 1024 * 10, // Default 10GB : 1024 * 1024 * 1024 * 10, // Default 10GB
@@ -88,7 +90,7 @@ const server = Bun.serve(
}, },
} }
: { : {
port: 3000, port,
maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE
? parseInt(process.env.MAX_REQUEST_BODY_SIZE) ? parseInt(process.env.MAX_REQUEST_BODY_SIZE)
: 1024 * 1024 * 1024 * 10, // Default 10GB : 1024 * 1024 * 1024 * 10, // Default 10GB
+29 -18
View File
@@ -15,12 +15,21 @@ Shumai is configured via environment variables. You can define these variables i
--- ---
## Server Config
| Variable | Description | Example / Default |
| :---------------------- | :------------------------------------------------------------------------------------------------ | :---------------- |
| `SHUMAI_SERVER_PORT` | The port on which the Shumai web server will listen. | `3000` (default) |
| `MAX_REQUEST_BODY_SIZE` | Maximum allowed size for request bodies (e.g., for large file uploads). Default is 10GB in bytes. | `10737418240` |
---
## Authentication Config ## Authentication Config
| Variable | Description | Example / Default | | Variable | Description | Example / Default |
| :------------------- | :--------------------------------------------------------------------- | :-------------------------------------- | | :------------------- | :--------------------------------------------------------------------- | :--------------------------------------------------------------- |
| `BETTER_AUTH_SECRET` | A secure, random 32-byte secret used to sign session cookies and JWTs. | Generate with `openssl rand -base64 32` | | `BETTER_AUTH_SECRET` | A secure, random 32-byte secret used to sign session cookies and JWTs. | Generate with `openssl rand -base64 32` |
| `BETTER_AUTH_URL` | The public URL of your Hono backend API. Used for redirect flows. | `http://localhost:3000` | | `BETTER_AUTH_URL` | The public URL of your Hono backend API. Used for redirect flows. | `http://localhost:3000` (respects `SHUMAI_SERVER_PORT` fallback) |
--- ---
@@ -28,16 +37,16 @@ Shumai is configured via environment variables. You can define these variables i
Shumai supports storing files locally or on S3-compatible endpoints. Shumai supports storing files locally or on S3-compatible endpoints.
| Variable | Description | Example / Default | | Variable | Description | Example / Default |
| :------------------------- | :------------------------------------------------------------------------------------------------ | :-------------------------------- | | :------------------------- | :------------------------------------------------------------------------------------------------ | :--------------------------- |
| `STORAGE_BACKEND` | Storage type. Use `local` for local file system storage, or `s3` for S3-compatible cloud storage. | `local` (default) or `s3` | | `STORAGE_BACKEND` | Storage type. Use `local` for local file system storage, or `s3` for S3-compatible cloud storage. | `local` (default) or `s3` |
| `AWS_ENDPOINT_URL_S3` | Custom endpoint for S3 storage. Must change to public domain/IP if deploying remotely. | `http://localhost:3000` (default) | | `AWS_ENDPOINT_URL_S3` | Custom endpoint for S3 storage. Must change to public domain/IP if deploying remotely. | `http://localhost` (default) |
| `S3_BUCKET` | S3 bucket name. | `shumai` (default) | | `S3_BUCKET` | S3 bucket name. | `shumai` (default) |
| `S3_ACCESS_KEY_ID` | Access key credentials for S3. | `minioadmin` (default) | | `S3_ACCESS_KEY_ID` | Access key credentials for S3. | `minioadmin` (default) |
| `S3_SECRET_ACCESS_KEY` | Secret key credentials for S3. | `minioadmin` (default) | | `S3_SECRET_ACCESS_KEY` | Secret key credentials for S3. | `minioadmin` (default) |
| `S3_REGION` | S3 storage region. | `auto` (default) | | `S3_REGION` | S3 storage region. | `auto` (default) |
| `S3_USE_SSL` | Set to `true` to use HTTPS for S3 endpoints. | `false` (default) | | `S3_USE_SSL` | Set to `true` to use HTTPS for S3 endpoints. | `false` (default) |
| `PRESIGNED_URL_EXPIRES_IN` | Number of hours for which generated presigned download/upload links are valid. | `5` (default) | | `PRESIGNED_URL_EXPIRES_IN` | Number of hours for which generated presigned download/upload links are valid. | `5` (default) |
--- ---
@@ -45,10 +54,12 @@ Shumai supports storing files locally or on S3-compatible endpoints.
Configures whether background transcoding and AI agents are executed locally or offloaded to a Temporal cluster. Configures whether background transcoding and AI agents are executed locally or offloaded to a Temporal cluster.
| Variable | Description | Example / Default | | Variable | Description | Example / Default |
| :------------------ | :------------------------------------------------------------------------------------------------- | :------------------------------ | | :------------------------- | :------------------------------------------------------------------------------------------------- | :------------------------------ |
| `WORKFLOW_EXECUTOR` | Engine choice. Use `local` for in-process database polling, or `temporal` for distributed workers. | `local` (default) or `temporal` | | `WORKFLOW_EXECUTOR` | Engine choice. Use `local` for in-process database polling, or `temporal` for distributed workers. | `local` (default) or `temporal` |
| `TEMPORAL_ADDRESS` | Host and port of the Temporal cluster gRPC service. | `localhost:7233` (default) | | `TEMPORAL_ADDRESS` | Host and port of the Temporal cluster gRPC service. | `localhost:7233` (default) |
| `EMBEDDING_CHUNK_DURATION` | The duration in seconds for each video chunk when generating video embeddings. | `60.0` (default) |
| `EMBEDDING_CHUNK_OVERLAP` | The duration in seconds to overlap video chunks when generating video embeddings. | `5.0` (default) |
--- ---
+1 -1
View File
@@ -69,7 +69,7 @@ To handle media processing and security isolation, the host machine must have th
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
BETTER_AUTH_SECRET=your-random-32-character-secret-key BETTER_AUTH_SECRET=your-random-32-character-secret-key
STORAGE_BACKEND=local STORAGE_BACKEND=local
AWS_ENDPOINT_URL_S3=http://localhost:3000 AWS_ENDPOINT_URL_S3=http://localhost
``` ```
4. **Start Shumai**: 4. **Start Shumai**:
```bash ```bash
+1
View File
@@ -34,6 +34,7 @@ A specialized utility agent that processes assets to generate search indexes. Yo
- Once created and enabled, Shumai automatically runs embedding generation for new file uploads if the file type is supported (image or video). - Once created and enabled, Shumai automatically runs embedding generation for new file uploads if the file type is supported (image or video).
- These search indexes are saved to power Shumai's natural language semantic search capabilities. - These search indexes are saved to power Shumai's natural language semantic search capabilities.
- **Note:** The Embedding Agent is hardcoded to use `google-embedding-2` as the LLM model. Because of this, you cannot choose a provider or model. Make sure you set the `GEMINI_API_KEY` environment variable to make it work. - **Note:** The Embedding Agent is hardcoded to use `google-embedding-2` as the LLM model. Because of this, you cannot choose a provider or model. Make sure you set the `GEMINI_API_KEY` environment variable to make it work.
- **Chunk Duration:** You can configure the duration of chunks used for long video indexing via the `EMBEDDING_CHUNK_DURATION` environment variable (defaults to 60 seconds).
--- ---
+13
View File
@@ -12,9 +12,22 @@ Traditional search relies on matching exact characters (e.g., searching "dog" wi
Semantic search translates text queries and file contents into conceptual profiles. Similar ideas and visuals are mapped near each other. Semantic search translates text queries and file contents into conceptual profiles. Similar ideas and visuals are mapped near each other.
1. **Index Generation**: When you upload an asset, Shumai's background agent scans the file's visual elements, text contents, or descriptions, translating them into a concept profile. 1. **Index Generation**: When you upload an asset, Shumai's background agent scans the file's visual elements, text contents, or descriptions, translating them into a concept profile.
- **Video Processing**: Shumai uses **gemini-embedding-2** for video indexing.
- **Chunking**: For long videos, Shumai breaks them into chunks to ensure high-quality indexing. By default, chunks are **60 seconds** long with a **5-second overlap** to ensure no context is lost at the boundaries.
- **Sampling**: The model processes a maximum of 32 frames per chunk: short chunks (≤32s) are sampled at 1 fps, while longer chunks are uniformly sampled to 32 frames.
- **Optimization**: To optimize processing, Shumai automatically transcodes each chunk to **1 FPS** and **removes the audio track** before sending it to the embedding agent.
- **Configuration**: Administrators can customize these settings using the `EMBEDDING_CHUNK_DURATION` and `EMBEDDING_CHUNK_OVERLAP` environment variables.
2. **Concept Matching**: When you search with the "Semantic" toggle enabled, Shumai matches the conceptual meaning of your query against your assets. 2. **Concept Matching**: When you search with the "Semantic" toggle enabled, Shumai matches the conceptual meaning of your query against your assets.
3. **Result**: Searching "sunset at the beach" will successfully find a video file of ocean waves at dusk, even if the filename is `IMG_4029.mp4`. 3. **Result**: Searching "sunset at the beach" will successfully find a video file of ocean waves at dusk, even if the filename is `IMG_4029.mp4`.
### Understanding Search Results
Semantic search works differently than traditional keyword filtering:
- **Sort vs. Filter**: Semantic search acts more like a **sort** than a strict filter. While the most relevant results will appear at the top, less related content may still be present further down the list, ranked lower. If you need to exclude specific types of files, use the **Filter** panel in conjunction with semantic search.
- **Video Chunks**: Because Shumai indexes videos in chunks, a single long video may appear multiple times in your search results. Each result corresponds to a specific segment of the video where the match was found.
- **Match Timestamps**: When a search result comes from a video chunk, Shumai displays the matching start and end time. Clicking on these results will open the video and automatically jump to the relevant timestamp.
--- ---
## Activating Semantic Search ## Activating Semantic Search
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "shumai", "name": "shumai",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"repository": { "repository": {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/agent", "name": "@shumai/agent",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
+70 -28
View File
@@ -1,16 +1,16 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { import {
generateEmbeddingActivity,
generateTextEmbeddingActivity, generateTextEmbeddingActivity,
extractAiMetadataActivity, extractAiMetadataActivity,
getEmbeddingContextActivity, getEmbeddingContextActivity,
saveAssetEmbeddingsActivity, saveAssetEmbeddingsActivity,
generateImageEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
} from './ai' } from './ai'
import { s3Service } from '@shumai/core/src/s3/s3' import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core' import { transcodeService } from '@shumai/core'
import { prisma, AssetType, AssetStatus } from '@shumai/db' import { prisma, AssetType, AssetStatus } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test' import { setupTestDbHooks } from '@shumai/db/test'
import * as fs from 'fs'
vi.mock('fs', async (importOriginal) => { vi.mock('fs', async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- importOriginal returns the raw fs module, typed dynamically as any here // eslint-disable-next-line @typescript-eslint/no-explicit-any -- importOriginal returns the raw fs module, typed dynamically as any here
@@ -93,19 +93,13 @@ describe('AI Activities Unit Tests', () => {
contentType: 'image/png', contentType: 'image/png',
} as unknown as { buffer: Buffer; contentType: string }) } as unknown as { buffer: Buffer; contentType: string })
const context = { const res = await generateImageEmbeddingActivity({
agent: { config: { provider: 'google', model: 'gemini' } },
asset: { id: 'a1', mediaType: 'image/png', storageKey: { key: 'test.png' } },
}
const res = await generateEmbeddingActivity({
teamId: 't1', teamId: 't1',
assetId: 'a1', assetKey: 'test.png',
context, mediaType: 'image/png',
}) })
expect(res.embeddings.length).toBe(1) expect(res.embedding).toEqual([0.1, 0.2, 0.3])
expect(res.embeddings[0].embedding).toEqual([0.1, 0.2, 0.3])
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'test.png') expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'test.png')
}) })
@@ -115,25 +109,16 @@ describe('AI Activities Unit Tests', () => {
contentType: 'video/mp4', contentType: 'video/mp4',
} as unknown as { buffer: Buffer; contentType: string }) } as unknown as { buffer: Buffer; contentType: string })
const context = { const res = await generateVideoChunkEmbeddingActivity({
agent: { config: { provider: 'google', model: 'gemini' } },
asset: { id: 'a2', mediaType: 'video/mp4', storageKey: { key: 'test.mp4' } },
}
const res = await generateEmbeddingActivity({
teamId: 't1', teamId: 't1',
assetId: 'a2', chunkKey: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
context,
}) })
// Duration is 120s, chunks are 60s, so it should generate 2 chunks (0-60, 60-120) expect(res.embedding).toEqual([0.1, 0.2, 0.3])
expect(res.embeddings.length).toBe(2) expect(s3Service.getObject).toHaveBeenCalledWith(
expect(res.embeddings[0]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 0, endTime: 60 }) 'shumai',
expect(res.embeddings[1]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 60, endTime: 120 }) 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
)
expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalled()
expect(vi.mocked(fs.readFileSync)).toHaveBeenCalled()
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalled()
}) })
it('should generate text embedding successfully', async () => { it('should generate text embedding successfully', async () => {
@@ -291,6 +276,63 @@ describe('AI Database Activities Integration', () => {
expect(ctx.asset.id).toBe(asset.id) expect(ctx.asset.id).toBe(asset.id)
expect(ctx.asset.mediaType).toBe('video/mp4') expect(ctx.asset.mediaType).toBe('video/mp4')
}) })
it('should parse valid positive chunk duration and fallback on invalid or negative ones', async () => {
// Create embedding agent if not already present
const existingAgent = await prisma.agent.findUnique({ where: { id: user.id } })
if (!existingAgent) {
await prisma.agent.create({
data: {
id: user.id,
teamId: team.id,
type: 'embedding',
enabled: true,
config: {
provider: 'openai',
model: 'gpt-4',
},
},
})
}
// Test default/fallback
delete process.env.EMBEDDING_CHUNK_DURATION
let ctx = await getEmbeddingContextActivity({
teamId: team.id,
assetId: asset.id,
})
expect(ctx.chunkDuration).toBe(60.0)
expect(ctx.chunkOverlap).toBe(5.0)
// Test valid positive
process.env.EMBEDDING_CHUNK_DURATION = '45.5'
process.env.EMBEDDING_CHUNK_OVERLAP = '10.0'
ctx = await getEmbeddingContextActivity({
teamId: team.id,
assetId: asset.id,
})
expect(ctx.chunkDuration).toBe(45.5)
expect(ctx.chunkOverlap).toBe(10.0)
// Test negative/invalid for overlap
process.env.EMBEDDING_CHUNK_OVERLAP = '-5.0'
ctx = await getEmbeddingContextActivity({
teamId: team.id,
assetId: asset.id,
})
expect(ctx.chunkOverlap).toBe(5.0)
process.env.EMBEDDING_CHUNK_OVERLAP = 'invalid'
ctx = await getEmbeddingContextActivity({
teamId: team.id,
assetId: asset.id,
})
expect(ctx.chunkOverlap).toBe(5.0)
// Cleanup env
delete process.env.EMBEDDING_CHUNK_DURATION
delete process.env.EMBEDDING_CHUNK_OVERLAP
})
}) })
describe('saveAssetEmbeddingsActivity', () => { describe('saveAssetEmbeddingsActivity', () => {
+99
View File
@@ -140,6 +140,8 @@ export async function generateEmbeddingActivity(params: GenerateEmbeddingParams)
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`) const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`)
await execFileAsync('ffmpeg', [ await execFileAsync('ffmpeg', [
'-y', '-y',
'-loglevel',
'warning',
'-i', '-i',
tmpFile, tmpFile,
'-ss', '-ss',
@@ -309,9 +311,18 @@ export async function getEmbeddingContextActivity(params: { teamId: string; asse
throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true }) throw ApplicationFailure.create({ message: 'asset has no media type', nonRetryable: true })
} }
const parsedDuration = parseFloat(process.env.EMBEDDING_CHUNK_DURATION || '')
const chunkDuration =
Number.isFinite(parsedDuration) && parsedDuration > 0 ? parsedDuration : 60.0
const parsedOverlap = parseFloat(process.env.EMBEDDING_CHUNK_OVERLAP || '')
const chunkOverlap = Number.isFinite(parsedOverlap) && parsedOverlap >= 0 ? parsedOverlap : 5.0
return { return {
agent, agent,
asset, asset,
chunkDuration,
chunkOverlap,
} }
} }
@@ -338,3 +349,91 @@ export async function saveAssetEmbeddingsActivity(params: {
} }
} }
} }
export interface GenerateImageEmbeddingParams {
teamId: string
assetKey: string
mediaType: string
}
export async function generateImageEmbeddingActivity(
params: GenerateImageEmbeddingParams,
): Promise<{
embedding: number[]
usage: Usage
}> {
const apiKey = process.env.GEMINI_API_KEY
if (!apiKey) {
throw ApplicationFailure.create({
message: 'GEMINI_API_KEY environment variable is not configured',
nonRetryable: true,
})
}
const resolvedApiKey = process.env[apiKey] || apiKey
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
const usage: Usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
const { buffer: data } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
params.assetKey,
)
const embVec = await generateMultimodalEmbedding(ai, data, params.mediaType)
return {
embedding: embVec,
usage,
}
}
export interface GenerateVideoChunkEmbeddingParams {
teamId: string
chunkKey: string
}
export async function generateVideoChunkEmbeddingActivity(
params: GenerateVideoChunkEmbeddingParams,
): Promise<{
embedding: number[]
usage: Usage
}> {
const apiKey = process.env.GEMINI_API_KEY
if (!apiKey) {
throw ApplicationFailure.create({
message: 'GEMINI_API_KEY environment variable is not configured',
nonRetryable: true,
})
}
const resolvedApiKey = process.env[apiKey] || apiKey
const ai = new GoogleGenAI({ apiKey: resolvedApiKey })
const usage: Usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
try {
const { buffer: data } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
params.chunkKey,
)
const embVec = await generateMultimodalEmbedding(ai, data, 'video/mp4')
return {
embedding: embVec,
usage,
}
} catch (err) {
throw ApplicationFailure.create({
message: `Failed to generate video chunk embedding for key ${params.chunkKey}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
})
}
}
+2
View File
@@ -380,6 +380,8 @@ export {
generateTextEmbeddingActivity, generateTextEmbeddingActivity,
type ExtractAiMetadataParams, type ExtractAiMetadataParams,
extractAiMetadataActivity, extractAiMetadataActivity,
generateImageEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
} from './activities/ai' } from './activities/ai'
export * from './workflows/agent-autofill' export * from './workflows/agent-autofill'
export * from './workflows/agent-chat' export * from './workflows/agent-chat'
@@ -29,8 +29,11 @@ describe('Agent Embedding Workflow', () => {
getEmbeddingContextActivity: Object.assign(vi.fn(), { getEmbeddingContextActivity: Object.assign(vi.fn(), {
_activityName: 'getEmbeddingContextActivity', _activityName: 'getEmbeddingContextActivity',
}), }),
generateEmbeddingActivity: Object.assign(vi.fn(), { generateImageEmbeddingActivity: Object.assign(vi.fn(), {
_activityName: 'generateEmbeddingActivity', _activityName: 'generateImageEmbeddingActivity',
}),
generateVideoChunkEmbeddingActivity: Object.assign(vi.fn(), {
_activityName: 'generateVideoChunkEmbeddingActivity',
}), }),
saveAssetEmbeddingsActivity: Object.assign(vi.fn(), { saveAssetEmbeddingsActivity: Object.assign(vi.fn(), {
_activityName: 'saveAssetEmbeddingsActivity', _activityName: 'saveAssetEmbeddingsActivity',
@@ -41,20 +44,58 @@ describe('Agent Embedding Workflow', () => {
getAgentWorkerQueueActivity: Object.assign(vi.fn(), { getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getAgentWorkerQueueActivity', _activityName: 'getAgentWorkerQueueActivity',
}), }),
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getTranscodeWorkerQueueActivity',
}),
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
_activityName: 'downloadMediaToTmpActivity',
}),
cleanupTmpDirActivity: Object.assign(vi.fn(), {
_activityName: 'cleanupTmpDirActivity',
}),
transcodeVideoChunkActivity: Object.assign(vi.fn(), {
_activityName: 'transcodeVideoChunkActivity',
}),
deleteS3ObjectActivity: Object.assign(vi.fn(), {
_activityName: 'deleteS3ObjectActivity',
}),
} }
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
mockActivities.updateTaskStatusActivity.mockResolvedValue({}) mockActivities.updateTaskStatusActivity.mockResolvedValue({})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' }) mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.getEmbeddingContextActivity.mockResolvedValue({ mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' }, agent: { id: 'b1' },
asset: { id: 'a1' }, asset: {
dbProvider: { name: 'google' }, id: 'a1',
mediaType: 'image/png',
storageKey: { key: 'test.png' },
},
chunkDuration: 60.0,
chunkOverlap: 5.0,
}) })
mockActivities.generateEmbeddingActivity.mockResolvedValue({ mockActivities.generateImageEmbeddingActivity.mockResolvedValue({
embeddings: [{ embedding: [0.1, 0.2] }], embedding: [0.1, 0.2],
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' }, usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
}) })
mockActivities.generateVideoChunkEmbeddingActivity.mockResolvedValue({
embedding: [0.3, 0.4],
usage: { inputTokens: 3, outputTokens: 3, model: 'gpt' },
})
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
filePath: '/tmp/test.mp4',
tmpDir: '/tmp/test-dir',
})
mockActivities.transcodeVideoChunkActivity.mockImplementation(
async (params: { assetId: string; startTime: number; endTime: number }) => {
return {
chunkKey: `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}.mp4`,
}
},
)
mockActivities.deleteS3ObjectActivity.mockResolvedValue(undefined)
mockActivities.cleanupTmpDirActivity.mockResolvedValue(undefined)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any) vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
@@ -64,7 +105,7 @@ describe('Agent Embedding Workflow', () => {
}) })
}) })
it('should run agent embedding workflow successfully', async () => { it('should run agent embedding workflow successfully for image', async () => {
const task = await prisma.workflowTask.create({ const task = await prisma.workflowTask.create({
data: { data: {
type: 'ai_embedding', type: 'ai_embedding',
@@ -103,15 +144,11 @@ describe('Agent Embedding Workflow', () => {
assetId: 'a1', assetId: 'a1',
}) })
// Verify embedding generation // Verify image embedding generation
expect(mockActivities.generateEmbeddingActivity).toHaveBeenCalledWith({ expect(mockActivities.generateImageEmbeddingActivity).toHaveBeenCalledWith({
teamId: 't1', teamId: 't1',
assetId: 'a1', assetKey: 'test.png',
context: { mediaType: 'image/png',
agent: { id: 'b1' },
asset: { id: 'a1' },
dbProvider: { name: 'google' },
},
}) })
// Verify embeddings saved // Verify embeddings saved
@@ -125,7 +162,7 @@ describe('Agent Embedding Workflow', () => {
taskId: task.id, taskId: task.id,
inputTokens: 5, inputTokens: 5,
outputTokens: 5, outputTokens: 5,
model: 'gpt', model: 'gemini-embedding-2',
}) })
// Verify placeholder comment updated // Verify placeholder comment updated
@@ -141,6 +178,142 @@ describe('Agent Embedding Workflow', () => {
}) })
}) })
it('should run agent embedding workflow successfully for image with transcoded format', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
id: 'a1',
mediaType: 'image/png',
storageKey: { key: 'test.png' },
media: {
imageTranscodes: [{ key: 'test-transcoded.webp', isRaw: false, format: 'webp' }],
},
},
chunkDuration: 60.0,
chunkOverlap: 5.0,
})
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
status: 'pending',
assetId: 'a1',
teamId: 't1',
},
})
await agentEmbeddingMedia(task)
expect(mockActivities.generateImageEmbeddingActivity).toHaveBeenCalledWith({
teamId: 't1',
assetKey: 'test-transcoded.webp',
mediaType: 'image/webp',
})
})
it('should run agent embedding workflow successfully for video in chunks', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
id: 'a1',
mediaType: 'video/mp4',
storageKey: { key: 'test.mp4' },
media: {
duration: 150.0,
videoTranscodes: [{ key: 'test-transcoded.mp4', isRaw: false }],
},
},
chunkDuration: 60.0,
chunkOverlap: 5.0,
})
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
status: 'pending',
assetId: 'a1',
teamId: 't1',
payload: {
projectId: 'p1',
agent: { sessionId: 's1', agentId: 'agent-1' },
},
},
})
await agentEmbeddingMedia(task)
// Verify video transcode queue discovery & download
expect(mockActivities.getTranscodeWorkerQueueActivity).toHaveBeenCalled()
expect(mockActivities.downloadMediaToTmpActivity).toHaveBeenCalledWith({
assetKey: 'test-transcoded.mp4',
})
// Verify video chunk slicing activity called 3 times on transcode queue
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(1, {
assetId: 'a1',
filePath: '/tmp/test.mp4',
startTime: 0,
endTime: 60,
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(2, {
assetId: 'a1',
filePath: '/tmp/test.mp4',
startTime: 55,
endTime: 115,
})
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(3, {
assetId: 'a1',
filePath: '/tmp/test.mp4',
startTime: 110,
endTime: 150,
})
// Verify video chunk embedding generation (3 chunks) on agent queue
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenNthCalledWith(1, {
teamId: 't1',
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
})
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenNthCalledWith(2, {
teamId: 't1',
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-55-115.mp4',
})
expect(mockActivities.generateVideoChunkEmbeddingActivity).toHaveBeenNthCalledWith(3, {
teamId: 't1',
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-110-150.mp4',
})
// Verify deletion of temporary chunks from S3
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenCalledTimes(3)
expect(mockActivities.deleteS3ObjectActivity).toHaveBeenNthCalledWith(1, {
key: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
})
// Verify temp directory cleanup on transcode queue
expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({
tmpDir: '/tmp/test-dir',
})
// Verify usage update (3 chunks * 3 tokens = 9)
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
taskId: task.id,
inputTokens: 9,
outputTokens: 9,
model: 'gemini-embedding-2',
})
// Verify embeddings saved
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalledWith({
assetId: 'a1',
embeddings: [
{ embedding: [0.3, 0.4], startTime: 0, endTime: 60 },
{ embedding: [0.3, 0.4], startTime: 55, endTime: 115 },
{ embedding: [0.3, 0.4], startTime: 110, endTime: 150 },
],
})
})
it('should throw if task has no teamId', async () => { it('should throw if task has no teamId', async () => {
const task = await prisma.workflowTask.create({ const task = await prisma.workflowTask.create({
data: { data: {
@@ -160,10 +333,19 @@ describe('Agent Embedding Workflow', () => {
}) })
}) })
it('should skip saving embeddings if none are returned', async () => { it('should skip saving embeddings if none are returned (video duration 0)', async () => {
mockActivities.generateEmbeddingActivity.mockResolvedValue({ mockActivities.getEmbeddingContextActivity.mockResolvedValue({
embeddings: [], agent: { id: 'b1' },
usage: null, asset: {
id: 'a1',
mediaType: 'video/mp4',
storageKey: { key: 'test.mp4' },
media: {
duration: 0.0,
},
},
chunkDuration: 60.0,
chunkOverlap: 5.0,
}) })
const task = await prisma.workflowTask.create({ const task = await prisma.workflowTask.create({
@@ -178,7 +360,6 @@ describe('Agent Embedding Workflow', () => {
await agentEmbeddingMedia(task) await agentEmbeddingMedia(task)
expect(mockActivities.saveAssetEmbeddingsActivity).not.toHaveBeenCalled() expect(mockActivities.saveAssetEmbeddingsActivity).not.toHaveBeenCalled()
expect(mockActivities.updateTaskUsageActivity).not.toHaveBeenCalled()
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: task.id, taskId: task.id,
status: 'completed', status: 'completed',
@@ -186,7 +367,9 @@ describe('Agent Embedding Workflow', () => {
}) })
it('should handle failures, update placeholder with error, and set status to failed', async () => { it('should handle failures, update placeholder with error, and set status to failed', async () => {
mockActivities.generateEmbeddingActivity.mockRejectedValue(new Error('AI Service Unavailable')) mockActivities.generateImageEmbeddingActivity.mockRejectedValue(
new Error('AI Service Unavailable'),
)
const task = await prisma.workflowTask.create({ const task = await prisma.workflowTask.create({
data: { data: {
@@ -212,4 +395,40 @@ describe('Agent Embedding Workflow', () => {
output: { error: 'AI Service Unavailable' }, output: { error: 'AI Service Unavailable' },
}) })
}) })
it('should not create redundant chunks when video exactly matches chunk duration', async () => {
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
agent: { id: 'b1' },
asset: {
id: 'a1',
mediaType: 'video/mp4',
storageKey: { key: 'test.mp4' },
media: {
duration: 60.0,
},
},
chunkDuration: 60.0,
chunkOverlap: 5.0,
})
const task = await prisma.workflowTask.create({
data: {
type: 'ai_embedding',
status: 'pending',
assetId: 'a1',
teamId: 't1',
},
})
await agentEmbeddingMedia(task)
// Verify only 1 chunk was created instead of 2 (0-60 and 55-60)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(1)
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledWith(
expect.objectContaining({
startTime: 0,
endTime: 60,
}),
)
})
}) })
+173 -19
View File
@@ -1,25 +1,48 @@
import { ApplicationFailure } from '@temporalio/workflow' import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db' import type { WorkflowTask } from '@shumai/db'
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core' import {
getActivities,
executeActivity,
TaskQueueAgent,
TaskQueueTranscode,
} from '@shumai/workflow-core'
export interface GeneratedEmbedding {
embedding: number[]
startTime?: number
endTime?: number
}
export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> { export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
const { const {
updateTaskStatusActivity, updateTaskStatusActivity,
getEmbeddingContextActivity, getEmbeddingContextActivity,
generateEmbeddingActivity, generateImageEmbeddingActivity,
generateVideoChunkEmbeddingActivity,
saveAssetEmbeddingsActivity, saveAssetEmbeddingsActivity,
updateTaskUsageActivity, updateTaskUsageActivity,
createCommentActivity, createCommentActivity,
updateCommentActivity, updateCommentActivity,
getAgentWorkerQueueActivity, getAgentWorkerQueueActivity,
getTranscodeWorkerQueueActivity,
downloadMediaToTmpActivity,
cleanupTmpDirActivity,
transcodeVideoChunkActivity,
deleteS3ObjectActivity,
} = getActivities() } = getActivities()
let placeholderCommentId: string | undefined let placeholderCommentId: string | undefined
let agentWorkerQueue = '' let agentWorkerQueue = ''
let transcodeWorkerQueue = ''
let tmpDir: string | undefined
try { try {
// 0. Discover queue // 0. Discover queues
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity) agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
transcodeWorkerQueue = await executeActivity(
TaskQueueTranscode,
getTranscodeWorkerQueueActivity,
)
// Update status to processing // Update status to processing
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, { await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
@@ -47,30 +70,153 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
assetId: task.assetId, assetId: task.assetId,
}) })
// Call the activity to generate embeddings // eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = await executeActivity(agentWorkerQueue, generateEmbeddingActivity, { const { asset, chunkDuration, chunkOverlap } = context as any
teamId: task.teamId,
assetId: task.assetId, const isImage = asset.mediaType?.startsWith('image/')
context, const isVideo = asset.mediaType?.startsWith('video/')
})
if (!isImage && !isVideo) {
throw ApplicationFailure.create({
message: `unsupported media type for embeddings: ${asset.mediaType}`,
nonRetryable: true,
})
}
// Resolve the S3 key to use for embedding (preferring transcoded version)
let embeddingKey = asset.storageKey?.key
let embeddingMediaType = asset.mediaType
if (asset.media) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const media = asset.media as any
if (isVideo) {
if (media.videoTranscodes && media.videoTranscodes.length > 0) {
// Find first non-raw transcode or fallback to first transcode
const transcode =
media.videoTranscodes.find((t: PrismaJson.VideoTranscode) => !t.isRaw) ||
media.videoTranscodes[0]
if (transcode?.key) {
embeddingKey = transcode.key
}
}
} else if (isImage) {
if (media.imageTranscodes && media.imageTranscodes.length > 0) {
// Find first non-raw transcode or fallback to first transcode
const transcode =
media.imageTranscodes.find((t: PrismaJson.ImageTranscode) => !t.isRaw) ||
media.imageTranscodes[0]
if (transcode?.key) {
embeddingKey = transcode.key
if (transcode.format) {
embeddingMediaType = `image/${transcode.format}`
}
}
}
}
}
if (!embeddingKey) {
throw ApplicationFailure.create({ message: 'asset has no key', nonRetryable: true })
}
const results: GeneratedEmbedding[] = []
const usage = {
model: 'gemini-embedding-2',
inputTokens: 0,
outputTokens: 0,
}
if (isImage) {
const result = await executeActivity(agentWorkerQueue, generateImageEmbeddingActivity, {
teamId: task.teamId,
assetKey: embeddingKey,
mediaType: embeddingMediaType,
})
results.push({ embedding: result.embedding })
if (result.usage) {
usage.inputTokens += result.usage.inputTokens || 0
usage.outputTokens += result.usage.outputTokens || 0
}
} else if (isVideo) {
// 1. Download full video to transcode worker temp space
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
assetKey: embeddingKey,
})
const { filePath } = download
tmpDir = download.tmpDir
// Get video duration
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const duration = (asset.media as any)?.duration || 0
const limit = chunkDuration || 60.0
const overlap = chunkOverlap ?? 5.0
const step = Math.max(1, limit - overlap)
for (let start = 0.0; start < duration; start += step) {
let end = start + limit
if (end >= duration) {
end = duration
}
// Step A: Slice chunk on transcode worker and upload to S3
const chunkRes = await executeActivity(transcodeWorkerQueue, transcodeVideoChunkActivity, {
assetId: asset.id,
filePath,
startTime: start,
endTime: end,
})
const { chunkKey } = chunkRes
try {
// Step B: Generate embedding on agent worker
const chunkResult = await executeActivity(
agentWorkerQueue,
generateVideoChunkEmbeddingActivity,
{
teamId: task.teamId,
chunkKey,
},
)
results.push({
embedding: chunkResult.embedding,
startTime: start,
endTime: end,
})
if (chunkResult.usage) {
usage.inputTokens += chunkResult.usage.inputTokens || 0
usage.outputTokens += chunkResult.usage.outputTokens || 0
}
} finally {
// Step C: Delete temporary chunk from S3
await executeActivity(transcodeWorkerQueue, deleteS3ObjectActivity, {
key: chunkKey,
})
}
// If this chunk reached the end of the video, stop to avoid redundant overlapping chunks
if (end >= duration) {
break
}
}
}
// Save computed embeddings // Save computed embeddings
if (result.embeddings.length > 0) { if (results.length > 0) {
await executeActivity(agentWorkerQueue, saveAssetEmbeddingsActivity, { await executeActivity(agentWorkerQueue, saveAssetEmbeddingsActivity, {
assetId: task.assetId, assetId: task.assetId,
embeddings: result.embeddings, embeddings: results,
}) })
} }
// Update Usage // Update Usage
if (result.usage) { await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, { taskId: task.id,
taskId: task.id, inputTokens: usage.inputTokens,
inputTokens: result.usage.inputTokens, outputTokens: usage.outputTokens,
outputTokens: result.usage.outputTokens, model: usage.model,
model: result.usage.model, })
})
}
// 7. Update Placeholder Comment // 7. Update Placeholder Comment
if (placeholderCommentId) { if (placeholderCommentId) {
@@ -109,6 +255,14 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
}) })
} }
throw err throw err
} finally {
if (tmpDir && transcodeWorkerQueue) {
try {
await executeActivity(transcodeWorkerQueue, cleanupTmpDirActivity, { tmpDir })
} catch (cleanupErr) {
console.error('Failed to cleanup transcode worker tmp dir:', cleanupErr)
}
}
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/api", "name": "@shumai/api",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
+4 -2
View File
@@ -17,7 +17,8 @@ describe('authn api', () => {
it('GET /signup-info', async () => { it('GET /signup-info', async () => {
mockGetSignupInfo.mockResolvedValue({ mockGetSignupInfo.mockResolvedValue({
userCount: 5, initialized: true,
demoMode: false,
}) })
const app = new Hono().route('/', authnRoute) const app = new Hono().route('/', authnRoute)
@@ -25,7 +26,8 @@ describe('authn api', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(await res.json()).toEqual({ expect(await res.json()).toEqual({
userCount: 5, initialized: true,
demoMode: false,
}) })
}) })
}) })
+2 -1
View File
@@ -17,7 +17,8 @@ const route = app
.get('/signup-info', async (c) => { .get('/signup-info', async (c) => {
const info = await teamService.getSignupInfo() const info = await teamService.getSignupInfo()
return c.json({ return c.json({
userCount: info.userCount, initialized: info.initialized,
demoMode: info.demoMode,
}) })
}) })
.get('/me', async (c) => { .get('/me', async (c) => {
+122
View File
@@ -0,0 +1,122 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import { authMiddleware } from './auth'
import { auth } from '@shumai/core/src/auth/auth'
import { prisma } from '@shumai/db'
vi.mock('@shumai/core/src/auth/auth', () => ({
auth: {
api: {
getSession: vi.fn(),
},
},
}))
vi.mock('@shumai/db', () => ({
prisma: {
user: {
findUnique: vi.fn(),
},
teamMember: {
findFirst: vi.fn(),
},
},
}))
describe('authMiddleware', () => {
const app = new Hono()
.use('*', authMiddleware)
.get('/test', (c) => c.text('ok'))
.post('/test', (c) => c.text('ok'))
.post('/test/search', (c) => c.text('ok'))
beforeEach(() => {
vi.resetAllMocks()
delete process.env.SHUMAI_DEMO_MODE
})
it('allows access when authenticated', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
const res = await app.request('/test')
expect(res.status).toBe(200)
})
it('rejects when not authenticated', async () => {
vi.mocked(auth.api.getSession).mockResolvedValue(null)
const res = await app.request('/test')
expect(res.status).toBe(401)
})
describe('read-only mode', () => {
beforeEach(() => {
process.env.SHUMAI_DEMO_MODE = '1'
})
it('allows GET for reviewer', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
const res = await app.request('/test')
expect(res.status).toBe(200)
})
it('rejects POST for reviewer', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue(null) // No owner/editor role
const res = await app.request('/test', { method: 'POST' })
expect(res.status).toBe(403)
expect(await res.json()).toEqual({ error: 'System is in read-only mode' })
})
it('allows POST /search for reviewer', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
const res = await app.request('/test/search', { method: 'POST' })
expect(res.status).toBe(200)
})
it('allows POST for owner', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue({
id: 'member1',
role: 'owner',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
const res = await app.request('/test', { method: 'POST' })
expect(res.status).toBe(200)
})
it('allows POST for editor', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(auth.api.getSession).mockResolvedValue({ user: { id: 'user1' } } as any)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user1' } as any)
vi.mocked(prisma.teamMember.findFirst).mockResolvedValue({
id: 'member1',
role: 'editor',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
const res = await app.request('/test', { method: 'POST' })
expect(res.status).toBe(200)
})
})
})
+18
View File
@@ -28,6 +28,24 @@ export const authMiddleware = createMiddleware<{
} }
c.set('user', user) c.set('user', user)
if (process.env.SHUMAI_DEMO_MODE === '1') {
const method = c.req.method.toUpperCase()
const path = c.req.path
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && !path.endsWith('/search')) {
const member = await prisma.teamMember.findFirst({
where: {
userId: user.id,
role: { in: ['owner', 'editor'] },
},
})
if (!member) {
return c.json({ error: 'System is in read-only mode' }, 403)
}
}
}
await next() await next()
} catch { } catch {
return c.json({ error: 'Authentication failed' }, 401) return c.json({ error: 'Authentication failed' }, 401)
+2
View File
@@ -48,6 +48,8 @@ const route = app
hasPassword: shareLink.hasPassword, hasPassword: shareLink.hasPassword,
rootFolderId: shareLink.rootFolderId, rootFolderId: shareLink.rootFolderId,
projectId: shareLink.projectId, projectId: shareLink.projectId,
viewMode: shareLink.viewMode,
defaultSortOrder: shareLink.defaultSortOrder,
}) })
} catch (err) { } catch (err) {
return c.json({ error: (err as Error).message }, 404) return c.json({ error: (err as Error).message }, 404)
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/core", "name": "@shumai/core",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
+7 -3
View File
@@ -15,9 +15,13 @@ export const auth = betterAuth({
}, },
secret: process.env.BETTER_AUTH_SECRET, secret: process.env.BETTER_AUTH_SECRET,
// eslint-disable-next-line @typescript-eslint/naming-convention // eslint-disable-next-line @typescript-eslint/naming-convention
baseURL: process.env.BETTER_AUTH_URL || 'http://localhost:3000', baseURL:
process.env.BETTER_AUTH_URL || `http://localhost:${process.env.SHUMAI_SERVER_PORT || '3000'}`,
basePath: '/api/auth', basePath: '/api/auth',
trustedOrigins: ['http://localhost:3000', 'http://127.0.0.1:3000'], trustedOrigins: [
`http://localhost:${process.env.SHUMAI_SERVER_PORT || '3000'}`,
`http://127.0.0.1:${process.env.SHUMAI_SERVER_PORT || '3000'}`,
],
advanced: { advanced: {
disableCSRFCheck: true, disableCSRFCheck: true,
}, },
@@ -30,7 +34,7 @@ export const auth = betterAuth({
const info = await teamService.getSignupInfo() const info = await teamService.getSignupInfo()
if (info.userCount > 0) { if (info.initialized) {
if (!inviteCode) { if (!inviteCode) {
console.log('[Better Auth Hook] Public signup is disabled') console.log('[Better Auth Hook] Public signup is disabled')
return ctx.json( return ctx.json(
@@ -362,4 +362,70 @@ describe('NotificationService', () => {
count = await notificationService.getUnreadCount(tm.id, u1.id) count = await notificationService.getUnreadCount(tm.id, u1.id)
expect(count).toBe(0) expect(count).toBe(0)
}) })
it('toNotificationInfo maps video sprite and poster urls', async () => {
const tm = await prisma.team.create({ data: { name: 'Team 1' } })
const asset = await prisma.asset.create({
data: {
name: 'test-video.mp4',
type: 'file',
mediaType: 'video/mp4',
status: 'processed',
media: {
duration: 10,
filesize: 1024,
fps: 24,
frames: 240,
videoPreview: { width: 640, height: 360 },
videoTranscodes: [],
imageTranscodes: [],
sprite: { key: 'sprites/test-video.jpg', tileX: 10, tileY: 10, frames: 100 },
poster: { key: 'posters/test-video.jpg' },
thumbnail: {
key: 'thumbnails/test-video.jpg',
width: 120,
height: 90,
format: 'jpg',
quality: 80,
},
metadata: {
originalWidth: 1280,
originalHeight: 720,
duration: 10,
bitRate: 1000,
frameRate: 24,
hasAudio: false,
format: {},
},
finishedAt: new Date().toISOString(),
mimeType: 'video/mp4',
original: null,
},
},
})
const n = await prisma.notification.create({
data: {
teamId: tm.id,
type: NotificationType.comment_created,
assetId: asset.id,
},
})
const svc = notificationService
const info = await svc['toNotificationInfo'](
await prisma.notification.findUniqueOrThrow({
where: { id: n.id },
include: { creator: true, team: true, project: true, asset: true, user: true },
}),
null,
)
expect(info.asset?.preview).toBeDefined()
expect(info.asset?.thumbnailUrl).toBeDefined()
expect(info.asset?.thumbnailUrl).toContain('posters/test-video.jpg')
expect(info.asset?.originalWidth).toBe(1280)
expect(info.asset?.originalHeight).toBe(720)
})
}) })
@@ -371,6 +371,9 @@ export class NotificationService {
if (n.asset) { if (n.asset) {
const a = n.asset const a = n.asset
let previewUrl = '' let previewUrl = ''
let thumbnailUrl = ''
let originalWidth = 0
let originalHeight = 0
const media = a.media as PrismaJson.MediaInfo | null const media = a.media as PrismaJson.MediaInfo | null
@@ -379,8 +382,16 @@ export class NotificationService {
try { try {
if (media.sprite) { if (media.sprite) {
previewUrl = await s3Service.presign(bucket, media.sprite.key, 'GET') previewUrl = await s3Service.presign(bucket, media.sprite.key, 'GET')
if (media.poster) {
thumbnailUrl = await s3Service.presign(bucket, media.poster.key || '', 'GET')
}
if (media.metadata) {
originalWidth = media.metadata.originalWidth
originalHeight = media.metadata.originalHeight
}
} else if (media.thumbnail) { } else if (media.thumbnail) {
previewUrl = await s3Service.presign(bucket, media.thumbnail.key || '', 'GET') previewUrl = await s3Service.presign(bucket, media.thumbnail.key || '', 'GET')
thumbnailUrl = previewUrl
} }
} catch (e) { } catch (e) {
console.error('Failed to generate presigned url for notification asset preview:', e) console.error('Failed to generate presigned url for notification asset preview:', e)
@@ -392,6 +403,9 @@ export class NotificationService {
name: a.name, name: a.name,
mediaType: a.mediaType || undefined, mediaType: a.mediaType || undefined,
preview: previewUrl || undefined, preview: previewUrl || undefined,
thumbnailUrl: thumbnailUrl || undefined,
originalWidth: originalWidth || undefined,
originalHeight: originalHeight || undefined,
} }
} }
+3 -2
View File
@@ -451,7 +451,8 @@ export class LocalStorageService implements S3Service {
} }
const storageBackend = process.env.STORAGE_BACKEND || 'local' const storageBackend = process.env.STORAGE_BACKEND || 'local'
const s3Endpoint = process.env.AWS_ENDPOINT_URL_S3 || 'http://localhost:3000' const port = process.env.SHUMAI_SERVER_PORT || '3000'
const s3Endpoint = process.env.AWS_ENDPOINT_URL_S3 || 'http://localhost'
export const s3Service: S3Service = export const s3Service: S3Service =
storageBackend === 's3' storageBackend === 's3'
@@ -463,4 +464,4 @@ export const s3Service: S3Service =
process.env.S3_USE_SSL === 'true', process.env.S3_USE_SSL === 'true',
process.env.S3_REGION || 'auto', process.env.S3_REGION || 'auto',
) )
: new LocalStorageService(s3Endpoint) : new LocalStorageService(`${s3Endpoint}:${port}`)
+18
View File
@@ -303,6 +303,7 @@ describe('SearchService', () => {
// SelectMulti Metadata // SelectMulti Metadata
{ field: 'multi', op: 'hasAny', val: ['a'], expected: ['multi-a-b'] }, { field: 'multi', op: 'hasAny', val: ['a'], expected: ['multi-a-b'] },
{ field: 'multi', op: 'hasAny', val: ['b'], expected: ['multi-a-b', 'multi-b-c'] }, { field: 'multi', op: 'hasAny', val: ['b'], expected: ['multi-a-b', 'multi-b-c'] },
{ field: 'multi', op: 'hasAny', val: ['a', 'c'], expected: ['multi-a-b', 'multi-b-c'] },
{ field: 'multi', op: 'hasAll', val: ['a', 'b'], expected: ['multi-a-b'] }, { field: 'multi', op: 'hasAll', val: ['a', 'b'], expected: ['multi-a-b'] },
{ field: 'multi', op: 'hasAll', val: ['a', 'c'], expected: [] }, { field: 'multi', op: 'hasAll', val: ['a', 'c'], expected: [] },
{ {
@@ -323,6 +324,23 @@ describe('SearchService', () => {
'nothing', 'nothing',
], ],
}, },
{
field: 'multi',
op: 'hasNone',
val: ['a', 'c'],
expected: [
'str-apple',
'str-banana',
'num-10',
'num-20',
'bool-true',
'bool-false',
'date-today',
'date-yesterday',
'name-contains-test',
'nothing',
],
},
{ field: 'multi', op: 'eq', val: ['a', 'b'], expected: ['multi-a-b'] }, { field: 'multi', op: 'eq', val: ['a', 'b'], expected: ['multi-a-b'] },
// Date Metadata // Date Metadata
@@ -355,11 +355,16 @@ export class SqlQueryBuilder {
const valNumArr = valArr.map((v) => Number(v)).filter((v) => !isNaN(v)) const valNumArr = valArr.map((v) => Number(v)).filter((v) => !isNaN(v))
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (string_value = ANY(${valArr}) OR number_value = ANY(${valNumArr}::double precision[])))` return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND (string_value = ANY(${valArr}) OR number_value = ANY(${valNumArr}::double precision[])))`
} }
case 'hasAny':
case 'hasAll': case 'hasAll':
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND json_value @> ${JSON.stringify(value)}::jsonb)` return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND json_value @> ${JSON.stringify(value)}::jsonb)`
case 'hasNone': case 'hasAny': {
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND json_value @> ${JSON.stringify(value)}::jsonb)` const valArr = (Array.isArray(value) ? value : [value]).map(String)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND jsonb_exists_any(json_value, ${valArr}::text[]))`
}
case 'hasNone': {
const valArr = (Array.isArray(value) ? value : [value]).map(String)
return Prisma.sql`a.id NOT IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND jsonb_exists_any(json_value, ${valArr}::text[]))`
}
case 'isWithin': { case 'isWithin': {
const range = this.parseDateRange(value) const range = this.parseDateRange(value)
return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND date_value >= ${range.start} AND date_value <= ${range.end})` return Prisma.sql`a.id IN (SELECT asset_id FROM asset_metadata_values WHERE field_key = ${field} AND date_value >= ${range.start} AND date_value <= ${range.end})`
+5 -1
View File
@@ -224,17 +224,21 @@ describe('ShareService', () => {
) )
}) })
it('updates a share link including fieldVisibility', async () => { it('updates a share link including fieldVisibility, viewMode, and defaultSortOrder', async () => {
const shareLink = await shareService.createShareLink(projectId, { name: 'Old Name' }) const shareLink = await shareService.createShareLink(projectId, { name: 'Old Name' })
const updated = await shareService.updateShareLink(shareLink.id, { const updated = await shareService.updateShareLink(shareLink.id, {
name: 'New Name', name: 'New Name',
password: 'new-password', password: 'new-password',
fieldVisibility: { field1: true, field2: false }, fieldVisibility: { field1: true, field2: false },
viewMode: 'list',
defaultSortOrder: 'name:desc',
}) })
expect(updated.name).toBe('New Name') expect(updated.name).toBe('New Name')
expect(updated.hasPassword).toBe(true) expect(updated.hasPassword).toBe(true)
expect(updated.fieldVisibility).toEqual({ field1: true, field2: false }) expect(updated.fieldVisibility).toEqual({ field1: true, field2: false })
expect(updated.viewMode).toBe('list')
expect(updated.defaultSortOrder).toBe('name:desc')
const rootAsset = await prisma.asset.findUnique({ where: { id: shareLink.rootFolderId } }) const rootAsset = await prisma.asset.findUnique({ where: { id: shareLink.rootFolderId } })
expect(rootAsset?.name).toBe('New Name') expect(rootAsset?.name).toBe('New Name')
+3
View File
@@ -58,6 +58,7 @@ export class ShareService {
password: req.password, password: req.password,
isDisabled: req.isDisabled ?? false, isDisabled: req.isDisabled ?? false,
defaultSortOrder: req.defaultSortOrder, defaultSortOrder: req.defaultSortOrder,
viewMode: req.viewMode,
projectId: projectId, projectId: projectId,
rootFolderId: shareFolder.id, rootFolderId: shareFolder.id,
creatorId, creatorId,
@@ -84,6 +85,7 @@ export class ShareService {
password: req.password, password: req.password,
isDisabled: req.isDisabled, isDisabled: req.isDisabled,
defaultSortOrder: req.defaultSortOrder, defaultSortOrder: req.defaultSortOrder,
viewMode: req.viewMode,
fieldVisibility: (req.fieldVisibility as PrismaJson.ShareLinkFieldVisibility) ?? undefined, fieldVisibility: (req.fieldVisibility as PrismaJson.ShareLinkFieldVisibility) ?? undefined,
}, },
include: { creator: true }, include: { creator: true },
@@ -300,6 +302,7 @@ export class ShareService {
isDisabled: l.isDisabled, isDisabled: l.isDisabled,
hasPassword: !!l.password, hasPassword: !!l.password,
defaultSortOrder: l.defaultSortOrder, defaultSortOrder: l.defaultSortOrder,
viewMode: l.viewMode,
fieldVisibility: l.fieldVisibility as Record<string, boolean> | undefined, fieldVisibility: l.fieldVisibility as Record<string, boolean> | undefined,
rootFolderId: l.rootFolderId, rootFolderId: l.rootFolderId,
projectId: l.projectId, projectId: l.projectId,
+2
View File
@@ -349,7 +349,9 @@ export class TeamService {
const count = await prisma.user.count() const count = await prisma.user.count()
return { return {
initialized: count > 0,
userCount: count, userCount: count,
demoMode: process.env.SHUMAI_DEMO_MODE === '1',
} }
} }
@@ -145,6 +145,29 @@ describe('TranscodeService', () => {
) )
}) })
it('should handle rational fraction frame rate for video transcoding', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation((file: string, args: string[], cb: any) => {
cb(null, { stdout: '', stderr: '' })
})
const outputFile = path.join(tempDir, 'output_rational.mp4')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
frameRate: '160000/142512',
disableAudio: true,
})
expect(child_process.execFile).toHaveBeenCalledWith(
'ffmpeg',
expect.arrayContaining(['-filter_complex', expect.stringContaining('fps=160000/142512')]),
expect.any(Function),
)
})
it('should use sharp for image transcoding', async () => { it('should use sharp for image transcoding', async () => {
const outputFile = path.join(tempDir, 'output.webp') const outputFile = path.join(tempDir, 'output.webp')
await transcodeService.transcodeImage('input.png', outputFile, 480, 80) await transcodeService.transcodeImage('input.png', outputFile, 480, 80)
+6 -6
View File
@@ -32,7 +32,7 @@ export interface TranscodeVideoParams {
outputFile: string outputFile: string
width: number width: number
height: number height: number
frameRate?: number frameRate?: number | string
disableAudio?: boolean disableAudio?: boolean
} }
@@ -154,7 +154,7 @@ export class TranscodeService {
args.push('-movflags', '+faststart', '-max_muxing_queue_size', '1024', params.outputFile) args.push('-movflags', '+faststart', '-max_muxing_queue_size', '1024', params.outputFile)
await execFileAsync('ffmpeg', ['-y', ...args]) await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
} }
async transcodeImage( async transcodeImage(
@@ -222,12 +222,12 @@ export class TranscodeService {
'1024', '1024',
outputPoster, outputPoster,
] ]
await execFileAsync('ffmpeg', ['-y', ...args]) await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
} }
async extractAudio(inputFile: string, outputFile: string, bitrate: string): Promise<void> { async extractAudio(inputFile: string, outputFile: string, bitrate: string): Promise<void> {
const args = ['-i', inputFile, '-vn', '-acodec', 'libmp3lame', '-b:a', bitrate, outputFile] const args = ['-i', inputFile, '-vn', '-acodec', 'libmp3lame', '-b:a', bitrate, outputFile]
await execFileAsync('ffmpeg', ['-y', ...args]) await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
} }
async extractVideoFrames(params: ExtractVideoFramesParams): Promise<string[]> { async extractVideoFrames(params: ExtractVideoFramesParams): Promise<string[]> {
@@ -252,7 +252,7 @@ export class TranscodeService {
'80', '80',
outputPattern, outputPattern,
] ]
await execFileAsync('ffmpeg', ['-y', ...args]) await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
const files = fs.readdirSync(params.outputDir) const files = fs.readdirSync(params.outputDir)
return files return files
@@ -370,7 +370,7 @@ export class TranscodeService {
'80', '80',
localShotPath, localShotPath,
] ]
await execFileAsync('ffmpeg', ['-y', ...args]) await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
// 5. Overlay annotations if timestamp matches commentTimestamp exactly // 5. Overlay annotations if timestamp matches commentTimestamp exactly
if ( if (
-27
View File
@@ -294,33 +294,6 @@ export class UploadService {
}) })
} }
// Ai Embedding if enabled via agent
const embeddingAgent = await tx.agent.findFirst({
where: {
type: 'embedding',
enabled: true,
user: { teamMembers: { some: { teamId: team.id } } },
},
})
if (embeddingAgent) {
if (asset.mediaType?.startsWith('video/') || asset.mediaType?.startsWith('image/')) {
await tx.workflowTask.create({
data: {
assetId: asset.id,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId: team.id,
projectId,
payload: {
projectId,
agent: { agentId: embeddingAgent.id },
},
},
})
}
}
const isVideo = asset.mediaType?.startsWith('video/') const isVideo = asset.mediaType?.startsWith('video/')
const isImage = asset.mediaType?.startsWith('image/') const isImage = asset.mediaType?.startsWith('image/')
if (!isVideo && !isImage) { if (!isVideo && !isImage) {
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/db", "name": "@shumai/db",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "share_links" ADD COLUMN "view_mode" TEXT;
+1
View File
@@ -338,6 +338,7 @@ model ShareLink {
password String? password String?
isDisabled Boolean @default(false) @map("is_disabled") isDisabled Boolean @default(false) @map("is_disabled")
defaultSortOrder String? @map("default_sort_order") defaultSortOrder String? @map("default_sort_order")
viewMode String? @map("view_mode")
/// [ShareLinkFieldVisibility] /// [ShareLinkFieldVisibility]
fieldVisibility Json? @map("field_visibility") fieldVisibility Json? @map("field_visibility")
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
File diff suppressed because one or more lines are too long
@@ -3038,6 +3038,7 @@ export const ShareLinkScalarFieldEnum = {
password: 'password', password: 'password',
isDisabled: 'isDisabled', isDisabled: 'isDisabled',
defaultSortOrder: 'defaultSortOrder', defaultSortOrder: 'defaultSortOrder',
viewMode: 'viewMode',
fieldVisibility: 'fieldVisibility', fieldVisibility: 'fieldVisibility',
createdAt: 'createdAt', createdAt: 'createdAt',
updatedAt: 'updatedAt', updatedAt: 'updatedAt',
@@ -253,6 +253,7 @@ export const ShareLinkScalarFieldEnum = {
password: 'password', password: 'password',
isDisabled: 'isDisabled', isDisabled: 'isDisabled',
defaultSortOrder: 'defaultSortOrder', defaultSortOrder: 'defaultSortOrder',
viewMode: 'viewMode',
fieldVisibility: 'fieldVisibility', fieldVisibility: 'fieldVisibility',
createdAt: 'createdAt', createdAt: 'createdAt',
updatedAt: 'updatedAt', updatedAt: 'updatedAt',
@@ -32,6 +32,7 @@ export type ShareLinkMinAggregateOutputType = {
password: string | null password: string | null
isDisabled: boolean | null isDisabled: boolean | null
defaultSortOrder: string | null defaultSortOrder: string | null
viewMode: string | null
createdAt: Date | null createdAt: Date | null
updatedAt: Date | null updatedAt: Date | null
projectId: string | null projectId: string | null
@@ -46,6 +47,7 @@ export type ShareLinkMaxAggregateOutputType = {
password: string | null password: string | null
isDisabled: boolean | null isDisabled: boolean | null
defaultSortOrder: string | null defaultSortOrder: string | null
viewMode: string | null
createdAt: Date | null createdAt: Date | null
updatedAt: Date | null updatedAt: Date | null
projectId: string | null projectId: string | null
@@ -60,6 +62,7 @@ export type ShareLinkCountAggregateOutputType = {
password: number password: number
isDisabled: number isDisabled: number
defaultSortOrder: number defaultSortOrder: number
viewMode: number
fieldVisibility: PrismaJson.ShareLinkFieldVisibility fieldVisibility: PrismaJson.ShareLinkFieldVisibility
createdAt: number createdAt: number
updatedAt: number updatedAt: number
@@ -76,6 +79,7 @@ export type ShareLinkMinAggregateInputType = {
password?: true password?: true
isDisabled?: true isDisabled?: true
defaultSortOrder?: true defaultSortOrder?: true
viewMode?: true
createdAt?: true createdAt?: true
updatedAt?: true updatedAt?: true
projectId?: true projectId?: true
@@ -90,6 +94,7 @@ export type ShareLinkMaxAggregateInputType = {
password?: true password?: true
isDisabled?: true isDisabled?: true
defaultSortOrder?: true defaultSortOrder?: true
viewMode?: true
createdAt?: true createdAt?: true
updatedAt?: true updatedAt?: true
projectId?: true projectId?: true
@@ -104,6 +109,7 @@ export type ShareLinkCountAggregateInputType = {
password?: true password?: true
isDisabled?: true isDisabled?: true
defaultSortOrder?: true defaultSortOrder?: true
viewMode?: true
fieldVisibility?: true fieldVisibility?: true
createdAt?: true createdAt?: true
updatedAt?: true updatedAt?: true
@@ -195,6 +201,7 @@ export type ShareLinkGroupByOutputType = {
password: string | null password: string | null
isDisabled: boolean isDisabled: boolean
defaultSortOrder: string | null defaultSortOrder: string | null
viewMode: string | null
fieldVisibility: PrismaJson.ShareLinkFieldVisibility | null fieldVisibility: PrismaJson.ShareLinkFieldVisibility | null
createdAt: Date createdAt: Date
updatedAt: Date updatedAt: Date
@@ -228,6 +235,7 @@ export type ShareLinkWhereInput = {
password?: Prisma.StringNullableFilter<'ShareLink'> | string | null password?: Prisma.StringNullableFilter<'ShareLink'> | string | null
isDisabled?: Prisma.BoolFilter<'ShareLink'> | boolean isDisabled?: Prisma.BoolFilter<'ShareLink'> | boolean
defaultSortOrder?: Prisma.StringNullableFilter<'ShareLink'> | string | null defaultSortOrder?: Prisma.StringNullableFilter<'ShareLink'> | string | null
viewMode?: Prisma.StringNullableFilter<'ShareLink'> | string | null
fieldVisibility?: Prisma.JsonNullableFilter<'ShareLink'> fieldVisibility?: Prisma.JsonNullableFilter<'ShareLink'>
createdAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string createdAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
updatedAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string updatedAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
@@ -246,6 +254,7 @@ export type ShareLinkOrderByWithRelationInput = {
password?: Prisma.SortOrderInput | Prisma.SortOrder password?: Prisma.SortOrderInput | Prisma.SortOrder
isDisabled?: Prisma.SortOrder isDisabled?: Prisma.SortOrder
defaultSortOrder?: Prisma.SortOrderInput | Prisma.SortOrder defaultSortOrder?: Prisma.SortOrderInput | Prisma.SortOrder
viewMode?: Prisma.SortOrderInput | Prisma.SortOrder
fieldVisibility?: Prisma.SortOrderInput | Prisma.SortOrder fieldVisibility?: Prisma.SortOrderInput | Prisma.SortOrder
createdAt?: Prisma.SortOrder createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder updatedAt?: Prisma.SortOrder
@@ -269,6 +278,7 @@ export type ShareLinkWhereUniqueInput = Prisma.AtLeast<
password?: Prisma.StringNullableFilter<'ShareLink'> | string | null password?: Prisma.StringNullableFilter<'ShareLink'> | string | null
isDisabled?: Prisma.BoolFilter<'ShareLink'> | boolean isDisabled?: Prisma.BoolFilter<'ShareLink'> | boolean
defaultSortOrder?: Prisma.StringNullableFilter<'ShareLink'> | string | null defaultSortOrder?: Prisma.StringNullableFilter<'ShareLink'> | string | null
viewMode?: Prisma.StringNullableFilter<'ShareLink'> | string | null
fieldVisibility?: Prisma.JsonNullableFilter<'ShareLink'> fieldVisibility?: Prisma.JsonNullableFilter<'ShareLink'>
createdAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string createdAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
updatedAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string updatedAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
@@ -288,6 +298,7 @@ export type ShareLinkOrderByWithAggregationInput = {
password?: Prisma.SortOrderInput | Prisma.SortOrder password?: Prisma.SortOrderInput | Prisma.SortOrder
isDisabled?: Prisma.SortOrder isDisabled?: Prisma.SortOrder
defaultSortOrder?: Prisma.SortOrderInput | Prisma.SortOrder defaultSortOrder?: Prisma.SortOrderInput | Prisma.SortOrder
viewMode?: Prisma.SortOrderInput | Prisma.SortOrder
fieldVisibility?: Prisma.SortOrderInput | Prisma.SortOrder fieldVisibility?: Prisma.SortOrderInput | Prisma.SortOrder
createdAt?: Prisma.SortOrder createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder updatedAt?: Prisma.SortOrder
@@ -313,6 +324,7 @@ export type ShareLinkScalarWhereWithAggregatesInput = {
password?: Prisma.StringNullableWithAggregatesFilter<'ShareLink'> | string | null password?: Prisma.StringNullableWithAggregatesFilter<'ShareLink'> | string | null
isDisabled?: Prisma.BoolWithAggregatesFilter<'ShareLink'> | boolean isDisabled?: Prisma.BoolWithAggregatesFilter<'ShareLink'> | boolean
defaultSortOrder?: Prisma.StringNullableWithAggregatesFilter<'ShareLink'> | string | null defaultSortOrder?: Prisma.StringNullableWithAggregatesFilter<'ShareLink'> | string | null
viewMode?: Prisma.StringNullableWithAggregatesFilter<'ShareLink'> | string | null
fieldVisibility?: Prisma.JsonNullableWithAggregatesFilter<'ShareLink'> fieldVisibility?: Prisma.JsonNullableWithAggregatesFilter<'ShareLink'>
createdAt?: Prisma.DateTimeWithAggregatesFilter<'ShareLink'> | Date | string createdAt?: Prisma.DateTimeWithAggregatesFilter<'ShareLink'> | Date | string
updatedAt?: Prisma.DateTimeWithAggregatesFilter<'ShareLink'> | Date | string updatedAt?: Prisma.DateTimeWithAggregatesFilter<'ShareLink'> | Date | string
@@ -328,6 +340,7 @@ export type ShareLinkCreateInput = {
password?: string | null password?: string | null
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: string | null defaultSortOrder?: string | null
viewMode?: string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Date | string createdAt?: Date | string
updatedAt?: Date | string updatedAt?: Date | string
@@ -343,6 +356,7 @@ export type ShareLinkUncheckedCreateInput = {
password?: string | null password?: string | null
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: string | null defaultSortOrder?: string | null
viewMode?: string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Date | string createdAt?: Date | string
updatedAt?: Date | string updatedAt?: Date | string
@@ -358,6 +372,7 @@ export type ShareLinkUpdateInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -373,6 +388,7 @@ export type ShareLinkUncheckedUpdateInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -388,6 +404,7 @@ export type ShareLinkCreateManyInput = {
password?: string | null password?: string | null
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: string | null defaultSortOrder?: string | null
viewMode?: string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Date | string createdAt?: Date | string
updatedAt?: Date | string updatedAt?: Date | string
@@ -403,6 +420,7 @@ export type ShareLinkUpdateManyMutationInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -415,6 +433,7 @@ export type ShareLinkUncheckedUpdateManyInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -440,6 +459,7 @@ export type ShareLinkCountOrderByAggregateInput = {
password?: Prisma.SortOrder password?: Prisma.SortOrder
isDisabled?: Prisma.SortOrder isDisabled?: Prisma.SortOrder
defaultSortOrder?: Prisma.SortOrder defaultSortOrder?: Prisma.SortOrder
viewMode?: Prisma.SortOrder
fieldVisibility?: Prisma.SortOrder fieldVisibility?: Prisma.SortOrder
createdAt?: Prisma.SortOrder createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder updatedAt?: Prisma.SortOrder
@@ -455,6 +475,7 @@ export type ShareLinkMaxOrderByAggregateInput = {
password?: Prisma.SortOrder password?: Prisma.SortOrder
isDisabled?: Prisma.SortOrder isDisabled?: Prisma.SortOrder
defaultSortOrder?: Prisma.SortOrder defaultSortOrder?: Prisma.SortOrder
viewMode?: Prisma.SortOrder
createdAt?: Prisma.SortOrder createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder updatedAt?: Prisma.SortOrder
projectId?: Prisma.SortOrder projectId?: Prisma.SortOrder
@@ -469,6 +490,7 @@ export type ShareLinkMinOrderByAggregateInput = {
password?: Prisma.SortOrder password?: Prisma.SortOrder
isDisabled?: Prisma.SortOrder isDisabled?: Prisma.SortOrder
defaultSortOrder?: Prisma.SortOrder defaultSortOrder?: Prisma.SortOrder
viewMode?: Prisma.SortOrder
createdAt?: Prisma.SortOrder createdAt?: Prisma.SortOrder
updatedAt?: Prisma.SortOrder updatedAt?: Prisma.SortOrder
projectId?: Prisma.SortOrder projectId?: Prisma.SortOrder
@@ -716,6 +738,7 @@ export type ShareLinkCreateWithoutCreatorInput = {
password?: string | null password?: string | null
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: string | null defaultSortOrder?: string | null
viewMode?: string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Date | string createdAt?: Date | string
updatedAt?: Date | string updatedAt?: Date | string
@@ -730,6 +753,7 @@ export type ShareLinkUncheckedCreateWithoutCreatorInput = {
password?: string | null password?: string | null
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: string | null defaultSortOrder?: string | null
viewMode?: string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Date | string createdAt?: Date | string
updatedAt?: Date | string updatedAt?: Date | string
@@ -788,6 +812,7 @@ export type ShareLinkScalarWhereInput = {
password?: Prisma.StringNullableFilter<'ShareLink'> | string | null password?: Prisma.StringNullableFilter<'ShareLink'> | string | null
isDisabled?: Prisma.BoolFilter<'ShareLink'> | boolean isDisabled?: Prisma.BoolFilter<'ShareLink'> | boolean
defaultSortOrder?: Prisma.StringNullableFilter<'ShareLink'> | string | null defaultSortOrder?: Prisma.StringNullableFilter<'ShareLink'> | string | null
viewMode?: Prisma.StringNullableFilter<'ShareLink'> | string | null
fieldVisibility?: Prisma.JsonNullableFilter<'ShareLink'> fieldVisibility?: Prisma.JsonNullableFilter<'ShareLink'>
createdAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string createdAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
updatedAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string updatedAt?: Prisma.DateTimeFilter<'ShareLink'> | Date | string
@@ -803,6 +828,7 @@ export type ShareLinkCreateWithoutProjectInput = {
password?: string | null password?: string | null
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: string | null defaultSortOrder?: string | null
viewMode?: string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Date | string createdAt?: Date | string
updatedAt?: Date | string updatedAt?: Date | string
@@ -817,6 +843,7 @@ export type ShareLinkUncheckedCreateWithoutProjectInput = {
password?: string | null password?: string | null
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: string | null defaultSortOrder?: string | null
viewMode?: string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Date | string createdAt?: Date | string
updatedAt?: Date | string updatedAt?: Date | string
@@ -872,6 +899,7 @@ export type ShareLinkCreateWithoutRootFolderInput = {
password?: string | null password?: string | null
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: string | null defaultSortOrder?: string | null
viewMode?: string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Date | string createdAt?: Date | string
updatedAt?: Date | string updatedAt?: Date | string
@@ -886,6 +914,7 @@ export type ShareLinkUncheckedCreateWithoutRootFolderInput = {
password?: string | null password?: string | null
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: string | null defaultSortOrder?: string | null
viewMode?: string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Date | string createdAt?: Date | string
updatedAt?: Date | string updatedAt?: Date | string
@@ -928,6 +957,7 @@ export type ShareLinkUpdateWithoutRootFolderInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -942,6 +972,7 @@ export type ShareLinkUncheckedUpdateWithoutRootFolderInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -956,6 +987,7 @@ export type ShareLinkCreateManyCreatorInput = {
password?: string | null password?: string | null
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: string | null defaultSortOrder?: string | null
viewMode?: string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Date | string createdAt?: Date | string
updatedAt?: Date | string updatedAt?: Date | string
@@ -970,6 +1002,7 @@ export type ShareLinkUpdateWithoutCreatorInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -984,6 +1017,7 @@ export type ShareLinkUncheckedUpdateWithoutCreatorInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -998,6 +1032,7 @@ export type ShareLinkUncheckedUpdateManyWithoutCreatorInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -1012,6 +1047,7 @@ export type ShareLinkCreateManyProjectInput = {
password?: string | null password?: string | null
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: string | null defaultSortOrder?: string | null
viewMode?: string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Date | string createdAt?: Date | string
updatedAt?: Date | string updatedAt?: Date | string
@@ -1026,6 +1062,7 @@ export type ShareLinkUpdateWithoutProjectInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -1040,6 +1077,7 @@ export type ShareLinkUncheckedUpdateWithoutProjectInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -1054,6 +1092,7 @@ export type ShareLinkUncheckedUpdateManyWithoutProjectInput = {
password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null password?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean isDisabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null defaultSortOrder?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
viewMode?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput fieldVisibility?: PrismaJson.ShareLinkFieldVisibility | Prisma.NullableJsonNullValueInput
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
@@ -1071,6 +1110,7 @@ export type ShareLinkSelect<
password?: boolean password?: boolean
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: boolean defaultSortOrder?: boolean
viewMode?: boolean
fieldVisibility?: boolean fieldVisibility?: boolean
createdAt?: boolean createdAt?: boolean
updatedAt?: boolean updatedAt?: boolean
@@ -1094,6 +1134,7 @@ export type ShareLinkSelectCreateManyAndReturn<
password?: boolean password?: boolean
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: boolean defaultSortOrder?: boolean
viewMode?: boolean
fieldVisibility?: boolean fieldVisibility?: boolean
createdAt?: boolean createdAt?: boolean
updatedAt?: boolean updatedAt?: boolean
@@ -1117,6 +1158,7 @@ export type ShareLinkSelectUpdateManyAndReturn<
password?: boolean password?: boolean
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: boolean defaultSortOrder?: boolean
viewMode?: boolean
fieldVisibility?: boolean fieldVisibility?: boolean
createdAt?: boolean createdAt?: boolean
updatedAt?: boolean updatedAt?: boolean
@@ -1137,6 +1179,7 @@ export type ShareLinkSelectScalar = {
password?: boolean password?: boolean
isDisabled?: boolean isDisabled?: boolean
defaultSortOrder?: boolean defaultSortOrder?: boolean
viewMode?: boolean
fieldVisibility?: boolean fieldVisibility?: boolean
createdAt?: boolean createdAt?: boolean
updatedAt?: boolean updatedAt?: boolean
@@ -1154,6 +1197,7 @@ export type ShareLinkOmit<
| 'password' | 'password'
| 'isDisabled' | 'isDisabled'
| 'defaultSortOrder' | 'defaultSortOrder'
| 'viewMode'
| 'fieldVisibility' | 'fieldVisibility'
| 'createdAt' | 'createdAt'
| 'updatedAt' | 'updatedAt'
@@ -1201,6 +1245,7 @@ export type $ShareLinkPayload<
password: string | null password: string | null
isDisabled: boolean isDisabled: boolean
defaultSortOrder: string | null defaultSortOrder: string | null
viewMode: string | null
/** /**
* [ShareLinkFieldVisibility] * [ShareLinkFieldVisibility]
*/ */
@@ -1823,6 +1868,7 @@ export interface ShareLinkFieldRefs {
readonly password: Prisma.FieldRef<'ShareLink', 'String'> readonly password: Prisma.FieldRef<'ShareLink', 'String'>
readonly isDisabled: Prisma.FieldRef<'ShareLink', 'Boolean'> readonly isDisabled: Prisma.FieldRef<'ShareLink', 'Boolean'>
readonly defaultSortOrder: Prisma.FieldRef<'ShareLink', 'String'> readonly defaultSortOrder: Prisma.FieldRef<'ShareLink', 'String'>
readonly viewMode: Prisma.FieldRef<'ShareLink', 'String'>
readonly fieldVisibility: Prisma.FieldRef<'ShareLink', 'Json'> readonly fieldVisibility: Prisma.FieldRef<'ShareLink', 'Json'>
readonly createdAt: Prisma.FieldRef<'ShareLink', 'DateTime'> readonly createdAt: Prisma.FieldRef<'ShareLink', 'DateTime'>
readonly updatedAt: Prisma.FieldRef<'ShareLink', 'DateTime'> readonly updatedAt: Prisma.FieldRef<'ShareLink', 'DateTime'>
+12 -4
View File
@@ -1,7 +1,7 @@
import { PrismaClient, WorkflowTask } from './generated/prisma/client'
import { PrismaTestingHelper } from './prisma-testing-helper'
import { PrismaPg } from '@prisma/adapter-pg' import { PrismaPg } from '@prisma/adapter-pg'
import { Pool } from 'pg' import { Pool } from 'pg'
import { PrismaClient, WorkflowTask } from './generated/prisma/client'
import { PrismaTestingHelper } from './prisma-testing-helper'
import { generateNgrams } from './utils/ngram' import { generateNgrams } from './utils/ngram'
// Global callback for workflow task creation (decouples db package from workflow engine) // Global callback for workflow task creation (decouples db package from workflow engine)
@@ -26,6 +26,7 @@ function createPrismaClient() {
const pool = new Pool({ connectionString }) const pool = new Pool({ connectionString })
const adapter = new PrismaPg(pool) const adapter = new PrismaPg(pool)
const client = new PrismaClient({ adapter, log: ['error'] }) const client = new PrismaClient({ adapter, log: ['error'] })
return client.$extends({ return client.$extends({
query: { query: {
workflowTask: { workflowTask: {
@@ -48,7 +49,14 @@ function createPrismaClient() {
if (typeof args.data.name === 'string') { if (typeof args.data.name === 'string') {
args.data.nameNgram = generateNgrams(args.data.name) args.data.nameNgram = generateNgrams(args.data.name)
} }
return query(args) const result = await query(args)
if (args.where) {
await client.project.updateMany({
where: { assets: { some: args.where } },
data: { updatedAt: new Date() },
})
}
return result
}, },
async upsert({ args, query }) { async upsert({ args, query }) {
if (typeof args.create.name === 'string') { if (typeof args.create.name === 'string') {
@@ -95,5 +103,5 @@ export function getPrismaTestingHelper() {
return prismaTestingHelper return prismaTestingHelper
} }
export * from './utils/ngram'
export * from './generated/prisma/client' export * from './generated/prisma/client'
export * from './utils/ngram'
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/dtos", "name": "@shumai/dtos",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
+3
View File
@@ -21,6 +21,9 @@ export const assetPreviewSchema = z.object({
mediaType: z.string().optional(), mediaType: z.string().optional(),
name: z.string().optional(), name: z.string().optional(),
preview: z.string().optional(), preview: z.string().optional(),
thumbnailUrl: z.string().optional(),
originalWidth: z.number().optional(),
originalHeight: z.number().optional(),
}) })
export type AssetPreview = z.infer<typeof assetPreviewSchema> export type AssetPreview = z.infer<typeof assetPreviewSchema>
+3
View File
@@ -8,6 +8,7 @@ export interface ShareLinkInfo {
isDisabled: boolean isDisabled: boolean
hasPassword: boolean hasPassword: boolean
defaultSortOrder?: string defaultSortOrder?: string
viewMode?: string
fieldVisibility?: Record<string, boolean> fieldVisibility?: Record<string, boolean>
rootFolderId: string rootFolderId: string
projectId: string projectId: string
@@ -23,6 +24,7 @@ export const createShareLinkRequestSchema = z.object({
password: z.string().optional(), password: z.string().optional(),
isDisabled: z.boolean().optional(), isDisabled: z.boolean().optional(),
defaultSortOrder: z.string().optional(), defaultSortOrder: z.string().optional(),
viewMode: z.string().optional(),
}) })
export type CreateShareLinkRequest = z.infer<typeof createShareLinkRequestSchema> export type CreateShareLinkRequest = z.infer<typeof createShareLinkRequestSchema>
@@ -33,6 +35,7 @@ export const updateShareLinkRequestSchema = z.object({
password: z.string().optional().nullable(), password: z.string().optional().nullable(),
isDisabled: z.boolean().optional(), isDisabled: z.boolean().optional(),
defaultSortOrder: z.string().optional().nullable(), defaultSortOrder: z.string().optional().nullable(),
viewMode: z.string().optional().nullable(),
fieldVisibility: z.record(z.string(), z.boolean()).optional().nullable(), fieldVisibility: z.record(z.string(), z.boolean()).optional().nullable(),
}) })
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/transcode", "name": "@shumai/transcode",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",
@@ -4,6 +4,11 @@ import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test' import { setupTestDbHooks } from '@shumai/db/test'
import { beforeEach, describe, expect, it, vi } from 'vitest' import { beforeEach, describe, expect, it, vi } from 'vitest'
import { transcodeService } from '@shumai/core' import { transcodeService } from '@shumai/core'
import * as child_process from 'child_process'
vi.mock('child_process', () => ({
execFile: vi.fn(),
}))
import { import {
getMediaInfoActivity, getMediaInfoActivity,
overlayAnnotationsActivity, overlayAnnotationsActivity,
@@ -13,6 +18,8 @@ import {
downloadMediaToTmpActivity, downloadMediaToTmpActivity,
transcodeImageActivity, transcodeImageActivity,
generateSpriteActivity, generateSpriteActivity,
transcodeVideoChunkActivity,
deleteS3ObjectActivity,
} from './transcode' } from './transcode'
vi.mock('@shumai/core/src/s3/s3', () => ({ vi.mock('@shumai/core/src/s3/s3', () => ({
@@ -22,6 +29,7 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
headObject: vi.fn(), headObject: vi.fn(),
presign: vi.fn(), presign: vi.fn(),
downloadToFile: vi.fn(), downloadToFile: vi.fn(),
deleteObject: vi.fn(),
}, },
})) }))
@@ -365,4 +373,67 @@ describe('Transcode Activities', () => {
).rejects.toThrowError(/Overlay annotations failed/) ).rejects.toThrowError(/Overlay annotations failed/)
}) })
}) })
describe('Video Chunk Activities', () => {
it('should transcode video chunk using ffmpeg and upload to S3', async () => {
// Mock child_process.execFile to simulate ffmpeg succeeding
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation(
(
file: string,
args: string[],
cb: (err: Error | null, result: { stdout: string; stderr: string }) => void,
) => {
cb(null, { stdout: '', stderr: '' })
},
)
const res = await transcodeVideoChunkActivity({
assetId: 'asset-abc',
filePath: '/tmp/full-video.mp4',
startTime: 10,
endTime: 25,
})
// Verify ffmpeg command args
expect(child_process.execFile).toHaveBeenCalledWith(
'ffmpeg',
expect.arrayContaining([
'-y',
'-i',
'/tmp/full-video.mp4',
'-ss',
'10',
'-t',
'15',
'-vf',
'fps=1',
'-c:v',
'libx264',
'-preset',
'ultrafast',
'-crf',
'28',
'-an',
]),
expect.any(Function),
)
// Verify S3 upload
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
expect.stringMatching(/^files\/asset-abc\/tmp-embedding-chunks\/chunk-10-25-.*\.mp4$/),
expect.any(Buffer),
expect.any(Number),
'video/mp4',
)
expect(res.chunkKey).toMatch(/^files\/asset-abc\/tmp-embedding-chunks\/chunk-10-25-.*\.mp4$/)
})
it('should delete S3 object successfully', async () => {
await deleteS3ObjectActivity({ key: 'files/test-key.mp4' })
expect(s3Service.deleteObject).toHaveBeenCalledWith('shumai', 'files/test-key.mp4')
})
})
}) })
+146 -4
View File
@@ -1,10 +1,16 @@
import { prisma } from '@shumai/db' import { prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3' import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core' import { transcodeService } from '@shumai/core'
import { metadataService } from '@shumai/core/src/metadata/metadata' import { metadataService } from '@shumai/core/src/metadata/metadata'
import { ApplicationFailure } from '@temporalio/activity' import { ApplicationFailure } from '@temporalio/activity'
import * as path from 'path' import * as path from 'path'
import * as fs from 'fs' import * as fs from 'fs'
import * as os from 'os'
import { execFile } from 'child_process'
import { promisify } from 'util'
import { ulid } from 'ulid'
const execFileAsync = promisify(execFile)
export interface GetMediaInfoActivityParams { export interface GetMediaInfoActivityParams {
assetId: string assetId: string
@@ -166,7 +172,7 @@ export async function transcodeVideoActivity(
const outputFile = path.join(tmpDir, `video-${params.videoSpec.height}p.mp4`) const outputFile = path.join(tmpDir, `video-${params.videoSpec.height}p.mp4`)
try { try {
let targetFps = 0 let targetFps: number | string = 0
let disableAudio = false let disableAudio = false
if (params.videoSpec.resolution === '180p') { if (params.videoSpec.resolution === '180p') {
@@ -175,8 +181,8 @@ export async function transcodeVideoActivity(
if (params.originalFps > 0 && params.originalFps < 24.0) { if (params.originalFps > 0 && params.originalFps < 24.0) {
targetFps = params.originalFps targetFps = params.originalFps
} }
if (params.duration * targetFps > 1600) { if (params.duration * (targetFps as number) > 1600) {
targetFps = 1600 / params.duration targetFps = `160000/${Math.floor(params.duration * 100)}`
} }
} }
@@ -468,3 +474,139 @@ export async function overlayAnnotationsActivity(params: {
throw err throw err
} }
} }
export interface CreateEmbeddingTaskIfEnabledParams {
assetId: string
teamId: string | null
projectId: string | null
}
export async function createEmbeddingTaskIfEnabledActivity(
params: CreateEmbeddingTaskIfEnabledParams,
): Promise<void> {
let teamId = params.teamId
let projectId = params.projectId
// Resolve teamId and projectId from asset if missing
if (!teamId || !projectId) {
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
include: {
project: true,
},
})
if (asset) {
projectId = projectId || asset.projectId
teamId = teamId || asset.project?.teamId || null
}
}
if (!teamId) {
return
}
// Check if there is an active embedding agent for the team
const embeddingAgent = await prisma.agent.findFirst({
where: {
type: 'embedding',
enabled: true,
user: { teamMembers: { some: { teamId } } },
},
})
if (!embeddingAgent) {
return
}
// Check if a pending/processing embedding task already exists for this asset to avoid duplicates
const existing = await prisma.workflowTask.findFirst({
where: {
assetId: params.assetId,
type: WorkflowTaskType.ai_embedding,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
})
if (existing) {
return
}
// Create embedding task
await prisma.workflowTask.create({
data: {
assetId: params.assetId,
type: WorkflowTaskType.ai_embedding,
status: WorkflowTaskStatus.pending,
teamId,
projectId,
payload: {
projectId: projectId ?? '',
agent: { agentId: embeddingAgent.id },
},
},
})
}
export interface TranscodeVideoChunkParams {
assetId: string
filePath: string
startTime: number
endTime: number
}
export async function transcodeVideoChunkActivity(
params: TranscodeVideoChunkParams,
): Promise<{ chunkKey: string }> {
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}.mp4`)
try {
// Slice video segment using ffmpeg, force 1fps and remove audio for gemini-embedding-2 optimization
await execFileAsync('ffmpeg', [
'-y',
'-loglevel',
'warning',
'-i',
params.filePath,
'-ss',
params.startTime.toString(),
'-t',
(params.endTime - params.startTime).toString(),
'-vf',
'fps=1',
'-c:v',
'libx264',
'-preset',
'ultrafast',
'-crf',
'28',
'-an',
chunkTmp,
])
const chunkData = fs.readFileSync(chunkTmp)
// Upload to S3
const bucket = process.env.S3_BUCKET || 'shumai'
const key = `files/${params.assetId}/tmp-embedding-chunks/chunk-${params.startTime}-${params.endTime}-${ulid()}.mp4`
await s3Service.putObject(bucket, key, chunkData, chunkData.length, 'video/mp4')
return { chunkKey: key }
} catch (err) {
throw ApplicationFailure.create({
message: `Failed to transcode video chunk for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
nonRetryable: false,
})
} finally {
if (fs.existsSync(chunkTmp)) {
try {
fs.unlinkSync(chunkTmp)
} catch (e) {
console.error('Failed to cleanup local chunk file:', e)
}
}
}
}
export async function deleteS3ObjectActivity(params: { key: string }): Promise<void> {
const bucket = process.env.S3_BUCKET || 'shumai'
await s3Service.deleteObject(bucket, params.key)
}
@@ -41,6 +41,9 @@ describe('Transcode Workflow', () => {
overlayAnnotationsActivity: Object.assign(vi.fn(), { overlayAnnotationsActivity: Object.assign(vi.fn(), {
_activityName: 'overlayAnnotationsActivity', _activityName: 'overlayAnnotationsActivity',
}), }),
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
_activityName: 'createEmbeddingTaskIfEnabledActivity',
}),
} }
beforeEach(() => { beforeEach(() => {
@@ -134,6 +137,12 @@ describe('Transcode Workflow', () => {
status: AssetStatus.processed, status: AssetStatus.processed,
}) })
expect(mockActivities.createEmbeddingTaskIfEnabledActivity).toHaveBeenCalledWith({
assetId: 'asset-1',
teamId: 'team-1',
projectId: 'proj-1',
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
taskId: 'task-1', taskId: 'task-1',
status: WorkflowTaskStatus.completed, status: WorkflowTaskStatus.completed,
@@ -205,6 +214,12 @@ describe('Transcode Workflow', () => {
assetId: 'asset-image', assetId: 'asset-image',
status: AssetStatus.processed, status: AssetStatus.processed,
}) })
expect(mockActivities.createEmbeddingTaskIfEnabledActivity).toHaveBeenCalledWith({
assetId: 'asset-image',
teamId: 'team-1',
projectId: 'proj-1',
})
}) })
it('should handle failures and update task status with error', async () => { it('should handle failures and update task status with error', async () => {
@@ -18,6 +18,7 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
cleanupTmpDirActivity, cleanupTmpDirActivity,
takeScreenshotsActivity, takeScreenshotsActivity,
overlayAnnotationsActivity, overlayAnnotationsActivity,
createEmbeddingTaskIfEnabledActivity,
} = getActivities() } = getActivities()
let tmpDir: string | undefined let tmpDir: string | undefined
@@ -245,6 +246,13 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
status: 'processed', status: 'processed',
}) })
// 11.5 Create AI embedding task if enabled
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
assetId: asset.id,
teamId: task.teamId,
projectId: task.projectId,
})
// 12. Update Task Status // 12. Update Task Status
await executeActivity(workerQueue, updateTaskStatusActivity, { await executeActivity(workerQueue, updateTaskStatusActivity, {
taskId: task.id, taskId: task.id,
+8 -8
View File
@@ -1,16 +1,14 @@
import type { AncestorFolder } from '@shumai/dtos'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { Badge } from '@/ui/components/ui/badge' import { Badge } from '@/ui/components/ui/badge'
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
DropdownMenuItem, DropdownMenuItem,
DropdownMenuTrigger,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
DropdownMenuPortal, DropdownMenuPortal,
DropdownMenuSeparator, DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu' } from '@/ui/components/ui/dropdown-menu'
import { import {
DockToLeft, DockToLeft,
@@ -18,9 +16,11 @@ import {
DockToRight, DockToRight,
DockToRightFilled, DockToRightFilled,
} from '@/ui/components/ui/icons' } from '@/ui/components/ui/icons'
import { Link, useNavigate } from '@tanstack/react-router' import { usePermissions } from '@/ui/hooks/use-permissions'
import { ChevronDown, LayoutGrid, List, History, Check, FileIcon } from 'lucide-react'
import { cn } from '@/ui/lib/utils' import { cn } from '@/ui/lib/utils'
import type { AncestorFolder } from '@shumai/dtos'
import { Link, useNavigate } from '@tanstack/react-router'
import { Check, ChevronDown, FileIcon, History, LayoutGrid, List } from 'lucide-react'
interface BreadcrumbNavProps { interface BreadcrumbNavProps {
teamId: string teamId: string
+22 -16
View File
@@ -119,31 +119,35 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
if (isEditing) { if (isEditing) {
return ( return (
<div className="relative w-full" ref={containerRef}> <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"> <div className="w-full px-2 py-1 border border-ring rounded bg-background text-sm shadow-sm min-h-[28px] flex items-center">
{value ? getDisplayValue(value) : <span className="text-gray-400">Select date...</span>} {value ? (
getDisplayValue(value)
) : (
<span className="text-muted-foreground">Select date...</span>
)}
</div> </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]"> <div className="absolute z-50 top-full left-0 mt-1 bg-popover border border-border rounded-lg shadow-xl flex flex-col md:flex-row overflow-hidden min-w-[280px]">
{/* Date Picker */} {/* Date Picker */}
<div className="p-4 w-64"> <div className="p-4 w-64">
<div className="flex justify-between items-center mb-4"> <div className="flex justify-between items-center mb-4">
{/* Replaced subMonths with addMonths(-1) */} {/* Replaced subMonths with addMonths(-1) */}
<button <button
onClick={() => setViewDate(addMonths(viewDate, -1))} onClick={() => setViewDate(addMonths(viewDate, -1))}
className="p-1 hover:bg-gray-100 rounded" className="p-1 hover:bg-accent rounded"
> >
<ChevronLeft className="w-4 h-4" /> <ChevronLeft className="w-4 h-4" />
</button> </button>
<span className="font-semibold text-sm">{format(viewDate, 'MMMM yyyy')}</span> <span className="font-semibold text-sm">{format(viewDate, 'MMMM yyyy')}</span>
<button <button
onClick={() => setViewDate(addMonths(viewDate, 1))} onClick={() => setViewDate(addMonths(viewDate, 1))}
className="p-1 hover:bg-gray-100 rounded" className="p-1 hover:bg-accent rounded"
> >
<ChevronRight className="w-4 h-4" /> <ChevronRight className="w-4 h-4" />
</button> </button>
</div> </div>
<div className="grid grid-cols-7 gap-1 text-center text-xs mb-2 text-gray-500"> <div className="grid grid-cols-7 gap-1 text-center text-xs mb-2 text-muted-foreground">
{['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((d) => ( {['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map((d) => (
<div key={d}>{d}</div> <div key={d}>{d}</div>
))} ))}
@@ -166,8 +170,10 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
<button <button
key={date.toString()} key={date.toString()}
onClick={() => handleDateClick(date)} onClick={() => handleDateClick(date)}
className={`w-8 h-8 rounded-full flex items-center justify-center hover:bg-blue-50 transition-colors ${ className={`w-8 h-8 rounded-full flex items-center justify-center hover:bg-accent transition-colors ${
isSelected ? 'bg-blue-50 text-white hover:bg-blue-600' : 'text-gray-700' isSelected
? 'bg-primary text-primary-foreground hover:bg-primary/90'
: 'text-foreground'
}`} }`}
> >
{getDate(date)} {getDate(date)}
@@ -179,17 +185,17 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
{/* Time Picker */} {/* Time Picker */}
{dateConfig?.includeTime && ( {dateConfig?.includeTime && (
<div className="border-l border-gray-200 bg-gray-50 w-32 flex flex-col"> <div className="border-l border-border bg-muted 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"> <div className="p-2 border-b border-border text-xs font-semibold text-muted-foreground flex items-center justify-center gap-1">
<Clock className="w-3 h-3" /> Time <Clock className="w-3 h-3" /> Time
</div> </div>
<div className="flex flex-1 h-64"> <div className="flex flex-1 h-64">
<div className="flex-1 overflow-y-auto scrollbar-hide border-r border-gray-200"> <div className="flex-1 overflow-y-auto scrollbar-hide border-r border-border">
{hours.map((h) => ( {hours.map((h) => (
<div <div
key={h} key={h}
onClick={() => handleTimeChange('hour', 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' : ''}`} className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-accent ${getHours(safeDate) === h ? 'bg-primary/10 font-medium text-primary' : ''}`}
> >
{h.toString().padStart(2, '0')} {h.toString().padStart(2, '0')}
</div> </div>
@@ -200,7 +206,7 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
<div <div
key={m} key={m}
onClick={() => handleTimeChange('minute', 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' : ''}`} className={`px-2 py-1 text-center text-sm cursor-pointer hover:bg-accent ${getMinutes(safeDate) === m ? 'bg-primary/10 font-medium text-primary' : ''}`}
> >
{m.toString().padStart(2, '0')} {m.toString().padStart(2, '0')}
</div> </div>
@@ -217,11 +223,11 @@ const DateField: React.FC<FieldProps<string>> = ({ value, config, onSave, readOn
return ( return (
<div <div
onClick={handleStartEdit} onClick={handleStartEdit}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded border border-transparent transition-colors ${ className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded border border-transparent transition-colors ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : '' !readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''
}`} }`}
> >
{value ? getDisplayValue(value) : <span className="text-gray-400 italic">Empty</span>} {value ? getDisplayValue(value) : <span className="text-muted-foreground italic">Empty</span>}
</div> </div>
) )
} }
@@ -63,7 +63,7 @@ const LongTextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }
value={localValue} value={localValue}
onChange={(e) => setLocalValue(e.target.value)} onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur} 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" className="w-full min-h-[80px] p-2 border border-ring rounded bg-background text-sm outline-none shadow-sm resize-none"
/> />
) )
} }
@@ -73,23 +73,23 @@ const LongTextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }
{/* Placeholder */} {/* Placeholder */}
<div <div
onClick={handlePlaceholderClick} 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 ${ className={`w-full text-foreground 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' !readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : 'cursor-pointer'
}`} }`}
title="Click to expand" title="Click to expand"
> >
{value ? value : <span className="text-gray-400 italic">Empty</span>} {value ? value : <span className="text-muted-foreground italic">Empty</span>}
</div> </div>
{/* Expanded Overlay */} {/* Expanded Overlay */}
{expanded && ( {expanded && (
<div <div
onClick={handleOverlayClick} 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 ${ className={`absolute top-0 left-0 w-full min-h-full h-auto z-50 bg-background border border-ring rounded shadow-lg px-2 py-1 whitespace-pre-wrap ${
!readOnly ? 'cursor-text' : '' !readOnly ? 'cursor-text' : ''
}`} }`}
> >
{value ? value : <span className="text-gray-400 italic">Empty</span>} {value ? value : <span className="text-muted-foreground italic">Empty</span>}
</div> </div>
)} )}
</div> </div>
@@ -62,7 +62,7 @@ const NumberField: React.FC<FieldProps<number | undefined>> = ({
onBlur={handleBlur} onBlur={handleBlur}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
onDoubleClick={(e) => e.stopPropagation()} 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" className="w-full px-2 py-1 border border-ring rounded bg-background text-sm outline-none shadow-sm text-left font-mono"
/> />
) )
} }
@@ -71,14 +71,14 @@ const NumberField: React.FC<FieldProps<number | undefined>> = ({
<div <div
onClick={handleStartEdit} onClick={handleStartEdit}
onDoubleClick={(e) => e.stopPropagation()} 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 ${ className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded border border-transparent transition-colors text-left font-mono ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : '' !readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''
}`} }`}
> >
{value !== undefined && value !== null ? ( {value !== undefined && value !== null ? (
formatNumber(value) formatNumber(value)
) : ( ) : (
<span className="text-gray-400 italic font-sans text-left block">Empty</span> <span className="text-muted-foreground italic font-sans text-left block">Empty</span>
)} )}
</div> </div>
) )
@@ -43,7 +43,7 @@ const RatingField: React.FC<FieldProps<number>> = ({ value, config, onSave, read
> >
<Star <Star
className={`w-5 h-5 transition-colors ${ className={`w-5 h-5 transition-colors ${
isFilled ? 'fill-yellow-400 text-yellow-400' : 'fill-gray-100 text-gray-300' isFilled ? 'fill-yellow-400 text-yellow-400' : 'fill-muted text-muted-foreground/30'
}`} }`}
/> />
</button> </button>
@@ -28,7 +28,7 @@ const SelectField: React.FC<FieldProps<string>> = ({ value, config, onSave, read
} }
const renderOptionBadge = (option: SelectOption | undefined) => { const renderOptionBadge = (option: SelectOption | undefined) => {
if (!option) return <span className="text-gray-400 italic">Select an option</span> if (!option) return <span className="text-muted-foreground italic">Select an option</span>
return ( return (
<span <span
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium" className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
@@ -46,23 +46,23 @@ const SelectField: React.FC<FieldProps<string>> = ({ value, config, onSave, read
<div <div
onClick={handleStartEdit} onClick={handleStartEdit}
className={`flex items-center justify-between w-full min-h-[28px] px-2 py-1 rounded border border-transparent transition-colors ${ 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' : '' !readOnly ? 'cursor-pointer hover:bg-accent hover:border-border group' : ''
}`} }`}
> >
{renderOptionBadge(selectedOption)} {renderOptionBadge(selectedOption)}
{!readOnly && ( {!readOnly && (
<ChevronDown className="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100" /> <ChevronDown className="w-4 h-4 text-muted-foreground opacity-0 group-hover:opacity-100" />
)} )}
</div> </div>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent <PopoverContent
className="p-1 w-[--radix-popover-trigger-width] min-w-[150px] max-h-60 overflow-auto bg-white border border-gray-200 rounded-lg shadow-lg" className="p-1 w-[--radix-popover-trigger-width] min-w-[150px] max-h-60 overflow-auto bg-popover border border-border rounded-lg shadow-lg"
align="start" align="start"
> >
<div <div
onClick={() => handleSelect('')} onClick={() => handleSelect('')}
className="px-3 py-2 text-sm text-gray-500 hover:bg-gray-50 cursor-pointer flex items-center gap-2" className="px-3 py-2 text-sm text-muted-foreground hover:bg-accent cursor-pointer flex items-center gap-2"
> >
<X className="w-3 h-3" /> Clear <X className="w-3 h-3" /> Clear
</div> </div>
@@ -70,7 +70,7 @@ const SelectField: React.FC<FieldProps<string>> = ({ value, config, onSave, read
<div <div
key={option.id} key={option.id}
onClick={() => handleSelect(option.id)} onClick={() => handleSelect(option.id)}
className="px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center" className="px-3 py-2 hover:bg-accent cursor-pointer flex items-center"
> >
<span <span
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium" className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
@@ -120,12 +120,12 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
onClick={handlePlaceholderClick} 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 ${ 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 !readOnly || hiddenCount > 0
? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' ? 'cursor-pointer hover:bg-accent hover:border-border'
: '' : ''
}`} }`}
> >
{selectedOptions.length === 0 && ( {selectedOptions.length === 0 && (
<span className="text-gray-400 text-sm italic px-1 pt-0.5">Empty</span> <span className="text-muted-foreground text-sm italic px-1 pt-0.5">Empty</span>
)} )}
{/* Render visible items */} {/* Render visible items */}
@@ -140,7 +140,7 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
))} ))}
{hiddenCount > 0 && ( {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]"> <span className="inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-muted text-muted-foreground h-[22px]">
+{hiddenCount} +{hiddenCount}
</span> </span>
)} )}
@@ -148,10 +148,10 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
</PopoverTrigger> </PopoverTrigger>
<PopoverContent <PopoverContent
className={`p-1 bg-white border rounded-lg shadow-xl max-h-60 overflow-auto ${ className={`p-1 bg-popover border rounded-lg shadow-xl max-h-60 overflow-auto ${
expanded && !isEditing expanded && !isEditing
? 'w-[--radix-popover-trigger-width] min-w-[200px] flex flex-wrap gap-1 border-blue-500 min-h-[32px] h-auto cursor-pointer' ? 'w-[--radix-popover-trigger-width] min-w-[200px] flex flex-wrap gap-1 border-ring min-h-[32px] h-auto cursor-pointer'
: 'w-64 border-gray-200' : 'w-64 border-border'
}`} }`}
align="start" align="start"
onClick={expanded && !isEditing ? handleOverlayClick : undefined} onClick={expanded && !isEditing ? handleOverlayClick : undefined}
@@ -159,7 +159,7 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
{expanded && !isEditing ? ( {expanded && !isEditing ? (
<> <>
{selectedOptions.length === 0 && ( {selectedOptions.length === 0 && (
<span className="text-gray-400 text-sm italic px-1 pt-0.5">Empty</span> <span className="text-muted-foreground text-sm italic px-1 pt-0.5">Empty</span>
)} )}
{selectedOptions.map((option: SelectOption) => ( {selectedOptions.map((option: SelectOption) => (
<span <span
@@ -178,7 +178,7 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
<div <div
key={option.id} key={option.id}
onClick={() => toggleOption(option.id)} onClick={() => toggleOption(option.id)}
className="px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center justify-between" className="px-3 py-2 hover:bg-accent cursor-pointer flex items-center justify-between"
> >
<span <span
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium" className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
@@ -186,7 +186,7 @@ const SelectMultiField: React.FC<FieldProps<string[]>> = ({
> >
{option.displayName} {option.displayName}
</span> </span>
{isSelected && <Check className="w-4 h-4 text-blue-500" />} {isSelected && <Check className="w-4 h-4 text-primary" />}
</div> </div>
) )
}) })
@@ -43,7 +43,7 @@ const TextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) =>
onChange={(e) => setLocalValue(e.target.value)} onChange={(e) => setLocalValue(e.target.value)}
onBlur={handleBlur} onBlur={handleBlur}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
className="w-full px-2 py-1 border border-blue-500 rounded bg-white text-sm outline-none shadow-sm" className="w-full px-2 py-1 border border-ring rounded bg-background text-sm outline-none shadow-sm"
/> />
) )
} }
@@ -51,11 +51,11 @@ const TextField: React.FC<FieldProps<string>> = ({ value, onSave, readOnly }) =>
return ( return (
<div <div
onClick={handleStartEdit} onClick={handleStartEdit}
className={`w-full min-h-[28px] px-2 py-1 text-sm text-gray-800 rounded truncate border border-transparent transition-colors ${ className={`w-full min-h-[28px] px-2 py-1 text-sm text-foreground rounded truncate border border-transparent transition-colors ${
!readOnly ? 'cursor-pointer hover:bg-gray-100 hover:border-gray-200' : '' !readOnly ? 'cursor-pointer hover:bg-accent hover:border-border' : ''
}`} }`}
> >
{value || <span className="text-gray-400 italic">Empty</span>} {value || <span className="text-muted-foreground italic">Empty</span>}
</div> </div>
) )
} }
@@ -1,3 +1,4 @@
import { Switch } from '@/ui/components/ui/switch'
import type { FieldInfo as MetadataFieldInfo } from '@shumai/dtos' import type { FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import React from 'react' import React from 'react'
@@ -9,32 +10,20 @@ interface FieldProps {
} }
const ToggleField: React.FC<FieldProps> = ({ value, onSave, readOnly }) => { 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 = (checked: boolean) => {
const handleToggle = (e: React.MouseEvent) => {
e.stopPropagation()
if (!readOnly) { if (!readOnly) {
const newValue = !value onSave(checked)
onSave(newValue)
} }
} }
return ( return (
<div <div className="flex items-center h-[28px] w-full" onClick={(e) => e.stopPropagation()}>
onClick={handleToggle} <Switch
className={`flex items-center h-[28px] w-full ${!readOnly ? 'cursor-pointer' : ''}`} checked={value}
> onCheckedChange={handleToggle}
<div disabled={readOnly}
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 ${ className="cursor-pointer"
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> </div>
) )
} }
@@ -2,21 +2,25 @@
import { client } from '@/ui/api/client' import { client } from '@/ui/api/client'
import type { InferRequestType, InferResponseType } from 'hono/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 { ulid } from 'ulid'
import { usePermissions } from '@/ui/hooks/use-permissions' import { usePermissions } from '@/ui/hooks/use-permissions'
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
import { formatSize } from '@/ui/lib/format'
import { useFieldStore } from '@/ui/stores/fields' import { useFieldStore } from '@/ui/stores/fields'
import { useUploadStore } from '@/ui/stores/upload' import { useUploadStore } from '@/ui/stores/upload'
import type {
AssetInfo,
CollectionInfo,
CreateUploadTaskRequest,
SearchCondition,
SearchSort,
ShareLinkInfo,
} from '@shumai/dtos'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router' import { useNavigate } from '@tanstack/react-router'
import { Download, AlertTriangle, Loader2 } from 'lucide-react' import { AlertTriangle, Download, Loader2 } from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner' import { toast } from 'sonner'
import { ulid } from 'ulid'
import type { DragState } from '../dnd-types' import type { DragState } from '../dnd-types'
import { MoveCopyDialog } from '../move-copy-dialog' import { MoveCopyDialog } from '../move-copy-dialog'
import { FileBrowserContextMenu } from './context-menu' import { FileBrowserContextMenu } from './context-menu'
@@ -31,6 +35,8 @@ import {
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
} from '../ui/alert-dialog' } from '../ui/alert-dialog'
import { Button } from '../ui/button'
import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu'
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
@@ -39,8 +45,6 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from '../ui/dialog' } from '../ui/dialog'
import { Button } from '../ui/button'
import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu'
import { FileCard } from './file-card' import { FileCard } from './file-card'
import { FileListItem } from './file-list-item' import { FileListItem } from './file-list-item'
import { FolderCard } from './folder-card' import { FolderCard } from './folder-card'
@@ -138,6 +142,70 @@ export function FileBrowser({
const queryClient = useQueryClient() const queryClient = useQueryClient()
const navigate = useNavigate() const navigate = useNavigate()
const [isExternalDragging, setIsExternalDragging] = useState(false)
const [externalOverFolderId, setExternalOverFolderId] = useState<string | null>(null)
const dragCounter = useRef(0)
const resetExternalDragState = useCallback(() => {
setIsExternalDragging(false)
setExternalOverFolderId(null)
dragCounter.current = 0
}, [])
// Prevent default window behavior to avoid browser replacing page on accidental drops
useEffect(() => {
const preventDefault = (e: DragEvent) => {
e.preventDefault()
}
window.addEventListener('dragover', preventDefault)
window.addEventListener('drop', preventDefault)
return () => {
window.removeEventListener('dragover', preventDefault)
window.removeEventListener('drop', preventDefault)
}
}, [])
const handleGlobalDragEnter = (e: React.DragEvent) => {
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
e.preventDefault()
if (e.dataTransfer.types.includes('Files')) {
dragCounter.current++
setIsExternalDragging(true)
}
}
const handleGlobalDragLeave = (e: React.DragEvent) => {
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
e.preventDefault()
if (e.dataTransfer.types.includes('Files')) {
dragCounter.current--
if (dragCounter.current <= 0) {
dragCounter.current = 0
setIsExternalDragging(false)
setExternalOverFolderId(null)
}
}
}
const handleGlobalDragOver = (e: React.DragEvent) => {
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
e.preventDefault()
}
const handleGlobalDrop = async (e: React.DragEvent) => {
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
e.preventDefault()
e.stopPropagation()
const files = await getAllFilesFromEntries(e.dataTransfer)
resetExternalDragState()
if (files.length > 0) {
processAndUploadFiles(files)
}
}
const [localUploadingFiles, setLocalUploadingFiles] = useState<AssetInfo[]>([]) const [localUploadingFiles, setLocalUploadingFiles] = useState<AssetInfo[]>([])
const displayedFiles = useMemo(() => { const displayedFiles = useMemo(() => {
@@ -147,7 +215,7 @@ export function FileBrowser({
}, [files, localUploadingFiles]) }, [files, localUploadingFiles])
const { data: shareLinksData } = useQuery({ const { data: shareLinksData } = useQuery({
queryKey: ['shares', projectId], queryKey: ['shares', projectId, 'list'],
queryFn: async () => { queryFn: async () => {
const res = await client.api.projects[':projectId'].shares.$get({ const res = await client.api.projects[':projectId'].shares.$get({
param: { projectId }, param: { projectId },
@@ -207,7 +275,7 @@ export function FileBrowser({
}, },
}) })
queryClient.invalidateQueries({ queryKey: ['search', teamId] }) queryClient.invalidateQueries({ queryKey: ['search', teamId] })
queryClient.invalidateQueries({ queryKey: ['folders', teamId] }) queryClient.invalidateQueries({ queryKey: ['folders'] })
setMoveCopyMode(null) setMoveCopyMode(null)
setItemsToMoveCopy([]) setItemsToMoveCopy([])
onClearSelection() onClearSelection()
@@ -237,7 +305,7 @@ export function FileBrowser({
}, },
}) })
queryClient.invalidateQueries({ queryKey: ['search', teamId] }) queryClient.invalidateQueries({ queryKey: ['search', teamId] })
queryClient.invalidateQueries({ queryKey: ['folders', teamId] }) queryClient.invalidateQueries({ queryKey: ['folders'] })
setMoveCopyMode(null) setMoveCopyMode(null)
setItemsToMoveCopy([]) setItemsToMoveCopy([])
onClearSelection() onClearSelection()
@@ -389,18 +457,45 @@ export function FileBrowser({
const { mutate: createUploadTaskMutation } = useMutation< const { mutate: createUploadTaskMutation } = useMutation<
InferResponseType<typeof $createUploadTask>, InferResponseType<typeof $createUploadTask>,
Error, Error,
InferRequestType<typeof $createUploadTask> InferRequestType<typeof $createUploadTask>,
{ files: FileWithId[] }
>({ >({
mutationFn: async (request) => { mutationFn: async (request) => {
const res = await $createUploadTask(request) const res = await $createUploadTask(request)
if (!res.ok) throw new Error('Failed to create upload task') if (!res.ok) throw new Error('Failed to create upload task')
return (await res.json()) as InferResponseType<typeof $createUploadTask> return (await res.json()) as InferResponseType<typeof $createUploadTask>
}, },
onSuccess: async (data, variables) => { onMutate: () => {
return { files: [...filesToUpload] }
},
onSuccess: async (data, variables, context) => {
const currentFiles = context?.files || []
const isCurrentFolderUpload = variables.json.parentId === assetId const isCurrentFolderUpload = variables.json.parentId === assetId
// Register task and files in the store for real-time progress tracking
const filesProgressInfo = currentFiles
.map((f) => {
const urlInfo = (
data.presignedUrls as { id?: string; url?: string; fileId?: string }[] | undefined
)?.find((p) => p.id === f.id)
return {
fileId: urlInfo?.fileId || f.id,
name: f.file.name,
size: f.file.size,
}
})
.filter((info) => !!info.fileId)
const visibleFiles = currentFiles.filter((f) => !f.file.name.startsWith('.'))
const taskName =
visibleFiles.length === 1 ? visibleFiles[0].file.name : `${visibleFiles.length} Items`
if (data.taskId) {
startTask(data.taskId, taskName, filesProgressInfo)
}
if (isCurrentFolderUpload) { if (isCurrentFolderUpload) {
const newLocalFiles: AssetInfo[] = filesToUpload const newLocalFiles: AssetInfo[] = currentFiles
.filter((f) => { .filter((f) => {
const path = (f.file.webkitRelativePath || f.file.name).split('/') const path = (f.file.webkitRelativePath || f.file.name).split('/')
return path.length === 1 return path.length === 1
@@ -432,7 +527,7 @@ export function FileBrowser({
// The RPC client returns an object that we cast to the expected type // The RPC client returns an object that we cast to the expected type
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
await uploadFiles(filesToUpload, data.presignedUrls as any, data.taskId!) await uploadFiles(currentFiles, data.presignedUrls as any, data.taskId!)
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId], queryKey: ['search', teamId, assetId],
}) })
@@ -441,6 +536,10 @@ export function FileBrowser({
const incrementUploading = useUploadStore((state) => state.increment) const incrementUploading = useUploadStore((state) => state.increment)
const decrementUploading = useUploadStore((state) => state.decrement) const decrementUploading = useUploadStore((state) => state.decrement)
const startTask = useUploadStore((state) => state.startTask)
const updateFileProgress = useUploadStore((state) => state.updateFileProgress)
const completeFile = useUploadStore((state) => state.completeFile)
const failFile = useUploadStore((state) => state.failFile)
const { fields } = useFieldStore() const { fields } = useFieldStore()
const displayedFields = useMemo(() => { const displayedFields = useMemo(() => {
if (!isShareView) return fields.filter((f) => f.visible) if (!isShareView) return fields.filter((f) => f.visible)
@@ -550,6 +649,13 @@ export function FileBrowser({
isShareView, isShareView,
fields: displayedFields, fields: displayedFields,
canEdit, canEdit,
isExternalDragging,
externalOverFolderId,
setExternalOverFolderId,
resetExternalDragState,
onExternalDrop: (files: File[], folderId: string) => {
processAndUploadFiles(files, folderId)
},
} }
if (displayStyle === 'card') { if (displayStyle === 'card') {
if (effectiveType === 'folder') return <FolderCard key={item.id} {...props} /> if (effectiveType === 'folder') return <FolderCard key={item.id} {...props} />
@@ -613,25 +719,53 @@ export function FileBrowser({
incrementUploading() incrementUploading()
try { try {
try { try {
const resp = await fetch(uploadInfo.url, { const xhr = new XMLHttpRequest()
method: 'PUT', const uploadPromise = new Promise<{ ok: boolean; status: number }>(
body: file.file, (resolve, reject) => {
headers: { xhr.open('PUT', uploadInfo.url)
'Content-Type': file.file.type, xhr.setRequestHeader('Content-Type', file.file.type)
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
updateFileProgress(taskId, uploadInfo.fileId, event.loaded)
}
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({ ok: true, status: xhr.status })
} else {
resolve({ ok: false, status: xhr.status })
}
}
xhr.onerror = () => {
reject(new Error('Network error'))
}
xhr.onabort = () => {
reject(new Error('Upload aborted'))
}
xhr.send(file.file)
}, },
}) )
const resp = await uploadPromise
if (resp.ok) { if (resp.ok) {
completeFile(taskId, uploadInfo.fileId)
await confirmUpload({ await confirmUpload({
param: { teamId: teamId, taskId: taskId }, param: { teamId: teamId!, taskId: taskId },
json: { json: {
fileId: uploadInfo.fileId, fileId: uploadInfo.fileId,
}, },
}) })
} else { } else {
failFile(taskId, uploadInfo.fileId)
toast.error(`Failed to upload file: ${file.file.name}`) toast.error(`Failed to upload file: ${file.file.name}`)
await confirmUpload({ await confirmUpload({
param: { teamId: teamId, taskId: taskId }, param: { teamId: teamId!, taskId: taskId },
json: { json: {
fileId: uploadInfo.fileId, fileId: uploadInfo.fileId,
errorMessage: `upload failed with status: ${resp.status}`, errorMessage: `upload failed with status: ${resp.status}`,
@@ -640,9 +774,10 @@ export function FileBrowser({
return return
} }
} catch (error) { } catch (error) {
failFile(taskId, uploadInfo.fileId)
toast.error(`Failed to upload file: ${file.file.name}`) toast.error(`Failed to upload file: ${file.file.name}`)
await confirmUpload({ await confirmUpload({
param: { teamId: teamId, taskId: taskId }, param: { teamId: teamId!, taskId: taskId },
json: { json: {
fileId: uploadInfo.fileId, fileId: uploadInfo.fileId,
errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`, errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`,
@@ -812,6 +947,10 @@ export function FileBrowser({
<div <div
className="flex-1 bg-background relative flex flex-col min-h-0 overflow-hidden" className="flex-1 bg-background relative flex flex-col min-h-0 overflow-hidden"
onContextMenu={(e) => onContextMenu(e)} onContextMenu={(e) => onContextMenu(e)}
onDragEnter={handleGlobalDragEnter}
onDragLeave={handleGlobalDragLeave}
onDragOver={handleGlobalDragOver}
onDrop={handleGlobalDrop}
> >
{!isShareView && !isPublic && onFilterChange && onSortChange && ( {!isShareView && !isPublic && onFilterChange && onSortChange && (
<FileBrowserToolbar <FileBrowserToolbar
@@ -886,6 +1025,11 @@ export function FileBrowser({
handleEmptyAreaClick={handleEmptyAreaClick} handleEmptyAreaClick={handleEmptyAreaClick}
dragState={dragState} dragState={dragState}
sort={sort} sort={sort}
isExternalDragging={isExternalDragging}
externalOverFolderId={externalOverFolderId}
setExternalOverFolderId={setExternalOverFolderId}
resetExternalDragState={resetExternalDragState}
onExternalDrop={(files, folderId) => processAndUploadFiles(files, folderId)}
/> />
) : ( ) : (
<FileBrowserGridView <FileBrowserGridView
@@ -970,6 +1114,13 @@ export function FileBrowser({
</Button> </Button>
</div> </div>
)} )}
{isExternalDragging && !externalOverFolderId && (
<div className="absolute bottom-6 left-1/2 -translate-x-1/2 z-50 pointer-events-none animate-in fade-in slide-in-from-bottom-4 duration-300">
<div className="flex items-center gap-3 px-6 py-3 rounded-full bg-primary/80 text-primary-foreground shadow-lg shadow-primary/20 border border-primary/20 backdrop-blur-md">
<span className="font-medium text-sm">Drop files here to upload</span>
</div>
</div>
)}
</div> </div>
</ContextMenuTrigger> </ContextMenuTrigger>
<FileBrowserContextMenu <FileBrowserContextMenu
@@ -22,6 +22,8 @@ import React, { useEffect, useMemo, useRef, useState } from 'react'
import type { DragState } from '../dnd-types' import type { DragState } from '../dnd-types'
import FieldRenderer from '../field-renderer' import FieldRenderer from '../field-renderer'
import { FilePreview } from './file-preview' import { FilePreview } from './file-preview'
import { useUploadStore } from '@/ui/stores/upload'
import { ProgressCircle } from '@/ui/components/ui/progress-circle'
import { FieldType, type FieldInfo as MetadataFieldInfo } from '@shumai/dtos' import { FieldType, type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
import { FIELD_TYPE_ICONS } from '../fields-manager' import { FIELD_TYPE_ICONS } from '../fields-manager'
@@ -82,6 +84,13 @@ export function FileCard({
const [name, setName] = useState(item.name) const [name, setName] = useState(item.name)
const inputRef = useRef<HTMLInputElement>(null) const inputRef = useRef<HTMLInputElement>(null)
const fileUploadState = useUploadStore((state) => state.fileProgress[item.id || ''])
const uploadPercent = fileUploadState
? fileUploadState.total > 0
? (fileUploadState.loaded / fileUploadState.total) * 100
: 0
: 0
const shouldPoll = const shouldPoll =
(item.type === 'file' || item.type === 'version_stack') && (item.type === 'file' || item.type === 'version_stack') &&
!!teamId && !!teamId &&
@@ -247,20 +256,24 @@ export function FileCard({
{displayItem.status !== 'error' && ( {displayItem.status !== 'error' && (
<Skeleton className="absolute inset-0 h-full w-full" /> <Skeleton className="absolute inset-0 h-full w-full" />
)} )}
<span {displayItem.status === 'uploading' ? (
className={cn( <ProgressCircle progress={uploadPercent} className="w-16 h-16 z-10" />
'z-10 font-medium px-2 text-center text-sm', ) : (
displayItem.status === 'error' <span
? 'text-destructive font-semibold' className={cn(
: 'text-muted-foreground capitalize', 'z-10 font-medium px-2 text-center text-sm',
)} displayItem.status === 'error'
> ? 'text-destructive font-semibold'
{displayItem.status === 'uploaded' : 'text-muted-foreground capitalize',
? 'Processing' )}
: displayItem.status === 'error' >
? 'Failed to upload' {displayItem.status === 'uploaded'
: displayItem.status} ? 'Processing'
</span> : displayItem.status === 'error'
? 'Failed to upload'
: displayItem.status}
</span>
)}
</div> </div>
) : ( ) : (
<FilePreview item={displayItem} /> <FilePreview item={displayItem} />
@@ -372,13 +385,13 @@ export function FileCard({
</DropdownMenu> </DropdownMenu>
</div> </div>
{fields && fields.length > 0 && ( {fields && fields.length > 0 && (
<div className="space-y-2 border-t p-3 mx-2"> <div className="space-y-2 border-t p-1 pt-3 mx-2">
{fields.map((field) => { {fields.map((field) => {
const Icon = field.config?.type const Icon = field.config?.type
? FIELD_TYPE_ICONS[field.config.type as FieldType] ? FIELD_TYPE_ICONS[field.config.type as FieldType]
: null : null
return ( return (
<div key={field.id} className="space-y-1"> <div key={field.id} className="space-y-1 bg-muted/50 p-1 rounded border">
<label className="text-xs text-muted-foreground tracking-wide flex items-center gap-1"> <label className="text-xs text-muted-foreground tracking-wide flex items-center gap-1">
{Icon && <Icon className="h-3.5 w-3.5 text-muted-foreground shrink-0" />} {Icon && <Icon className="h-3.5 w-3.5 text-muted-foreground shrink-0" />}
<span>{field.config?.name}</span> <span>{field.config?.name}</span>
@@ -11,6 +11,8 @@ import FieldRenderer from '../field-renderer'
import { Badge } from '@/ui/components/ui/badge' import { Badge } from '@/ui/components/ui/badge'
import { Checkbox } from '@/ui/components/ui/checkbox' import { Checkbox } from '@/ui/components/ui/checkbox'
import { EditableText } from '@/ui/components/ui/editable-text' import { EditableText } from '@/ui/components/ui/editable-text'
import { useUploadStore } from '@/ui/stores/upload'
import { ProgressCircle } from '@/ui/components/ui/progress-circle'
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos' import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
@@ -60,6 +62,13 @@ export function FileListItem({
const [name, setName] = useState(item.name) const [name, setName] = useState(item.name)
const inputRef = useRef<HTMLInputElement>(null) const inputRef = useRef<HTMLInputElement>(null)
const fileUploadState = useUploadStore((state) => state.fileProgress[item.id || ''])
const uploadPercent = fileUploadState
? fileUploadState.total > 0
? (fileUploadState.loaded / fileUploadState.total) * 100
: 0
: 0
const shouldPoll = const shouldPoll =
(item.type === 'file' || item.type === 'version_stack') && (item.type === 'file' || item.type === 'version_stack') &&
!!teamId && !!teamId &&
@@ -197,7 +206,9 @@ export function FileListItem({
className="h-4 w-4 shrink-0 data-[state=checked]:bg-primary data-[state=checked]:border-primary" 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"> <div className="w-8 h-8 shrink-0 flex items-center justify-center bg-muted rounded overflow-hidden">
{displayItem.preview?.thumbnailUrl ? ( {displayItem.status === 'uploading' ? (
<ProgressCircle progress={uploadPercent} className="w-7 h-7" />
) : displayItem.preview?.thumbnailUrl ? (
<img <img
src={displayItem.preview.thumbnailUrl} src={displayItem.preview.thumbnailUrl}
alt="" alt=""
@@ -14,6 +14,7 @@ import { Download, Edit, History, MoreHorizontal, Trash2 } from 'lucide-react'
import React, { useEffect, useMemo, useRef, useState } from 'react' import React, { useEffect, useMemo, useRef, useState } from 'react'
import type { DragState } from '../dnd-types' import type { DragState } from '../dnd-types'
import { FilePreview } from './file-preview' import { FilePreview } from './file-preview'
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
interface FolderCardProps { interface FolderCardProps {
item: AssetInfo item: AssetInfo
@@ -38,6 +39,11 @@ interface FolderCardProps {
selectedCount?: number selectedCount?: number
canEdit?: boolean canEdit?: boolean
isShareView?: boolean isShareView?: boolean
isExternalDragging?: boolean
externalOverFolderId?: string | null
setExternalOverFolderId?: (id: string | null) => void
resetExternalDragState?: () => void
onExternalDrop?: (files: File[], folderId: string) => void
} }
const FolderPreviewGrid = ({ items }: { items: ChildPreview[] }) => { const FolderPreviewGrid = ({ items }: { items: ChildPreview[] }) => {
@@ -114,6 +120,11 @@ export function FolderCard({
selectedCount, selectedCount,
canEdit = true, canEdit = true,
isShareView, isShareView,
isExternalDragging,
externalOverFolderId,
setExternalOverFolderId,
resetExternalDragState,
onExternalDrop,
}: FolderCardProps) { }: FolderCardProps) {
const [name, setName] = useState(item.name || '') const [name, setName] = useState(item.name || '')
const inputRef = useRef<HTMLInputElement>(null) const inputRef = useRef<HTMLInputElement>(null)
@@ -153,7 +164,8 @@ export function FolderCard({
return true return true
}, [dragState, item.id]) }, [dragState, item.id])
const showDropFeedback = isOver && isValidDropTarget const isExternalOver = isExternalDragging && externalOverFolderId === item.id
const showDropFeedback = (isOver && isValidDropTarget) || isExternalOver
const opacity = isBeingDragged ? 0.5 : 1 const opacity = isBeingDragged ? 0.5 : 1
useEffect(() => { useEffect(() => {
@@ -224,6 +236,40 @@ export function FolderCard({
e.preventDefault() e.preventDefault()
} }
}} }}
onDragEnter={
isExternalDragging
? () => {
setExternalOverFolderId?.(item.id!)
}
: undefined
}
onDragLeave={
isExternalDragging
? (e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
setExternalOverFolderId?.(null)
}
}
: undefined
}
onDragOver={
isExternalDragging
? (e) => {
e.preventDefault()
}
: undefined
}
onDrop={
isExternalDragging
? async (e) => {
e.preventDefault()
e.stopPropagation()
resetExternalDragState?.()
const files = await getAllFilesFromEntries(e.dataTransfer)
onExternalDrop?.(files, item.id!)
}
: undefined
}
className={cn( className={cn(
'group relative w-full max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full', 'group relative w-full max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full',
)} )}
@@ -13,6 +13,7 @@ import React, { useMemo, useState, useEffect } from 'react'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import type { DragState } from '../dnd-types' import type { DragState } from '../dnd-types'
import { Checkbox } from '../ui/checkbox' import { Checkbox } from '../ui/checkbox'
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
interface ListRowProps { interface ListRowProps {
item: AssetInfo item: AssetInfo
@@ -23,6 +24,11 @@ interface ListRowProps {
columnSizing?: Record<string, number> columnSizing?: Record<string, number>
virtualRow: { start: number; index: number } virtualRow: { start: number; index: number }
measureElement: (el: HTMLElement | null) => void measureElement: (el: HTMLElement | null) => void
isExternalDragging?: boolean
externalOverFolderId?: string | null
setExternalOverFolderId?: (id: string | null) => void
resetExternalDragState?: () => void
onExternalDrop?: (files: File[], folderId: string) => void
} }
function ListRow({ function ListRow({
@@ -34,6 +40,11 @@ function ListRow({
columnSizing, columnSizing,
virtualRow, virtualRow,
measureElement, measureElement,
isExternalDragging,
externalOverFolderId,
setExternalOverFolderId,
resetExternalDragState,
onExternalDrop,
}: ListRowProps) { }: ListRowProps) {
const isDraggingItem = dragState?.draggedIds.has(item.id!) const isDraggingItem = dragState?.draggedIds.has(item.id!)
const isDraggingAny = dragState?.isActive const isDraggingAny = dragState?.isActive
@@ -83,7 +94,8 @@ function ListRow({
return false return false
}, [dragState, item.id, item.type]) }, [dragState, item.id, item.type])
const showDropFeedback = isRowOver && isValidDropTarget const isExternalOver = isExternalDragging && externalOverFolderId === item.id
const showDropFeedback = (isRowOver && isValidDropTarget) || isExternalOver
return ( return (
<div <div
@@ -92,6 +104,40 @@ function ListRow({
measureElement(node) measureElement(node)
}} }}
data-index={virtualRow.index} data-index={virtualRow.index}
onDragEnter={
isExternalDragging && item.type === 'folder'
? () => {
setExternalOverFolderId?.(item.id!)
}
: undefined
}
onDragLeave={
isExternalDragging && item.type === 'folder'
? (e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
setExternalOverFolderId?.(null)
}
}
: undefined
}
onDragOver={
isExternalDragging && item.type === 'folder'
? (e) => {
e.preventDefault()
}
: undefined
}
onDrop={
isExternalDragging && item.type === 'folder'
? async (e) => {
e.preventDefault()
e.stopPropagation()
resetExternalDragState?.()
const files = await getAllFilesFromEntries(e.dataTransfer)
onExternalDrop?.(files, item.id!)
}
: undefined
}
className={cn( className={cn(
'group border-b border-border transition-colors hover:bg-primary/20 absolute top-0 left-0 w-full flex flex-col', 'group border-b border-border transition-colors hover:bg-primary/20 absolute top-0 left-0 w-full flex flex-col',
isSelected && 'bg-primary/10', isSelected && 'bg-primary/10',
@@ -146,6 +192,11 @@ interface FileBrowserListViewProps {
handleEmptyAreaClick: (e: React.MouseEvent) => void handleEmptyAreaClick: (e: React.MouseEvent) => void
dragState?: DragState dragState?: DragState
sort?: SearchSort sort?: SearchSort
isExternalDragging?: boolean
externalOverFolderId?: string | null
setExternalOverFolderId?: (id: string | null) => void
resetExternalDragState?: () => void
onExternalDrop?: (files: File[], folderId: string) => void
} }
export function FileBrowserListView({ export function FileBrowserListView({
@@ -174,6 +225,11 @@ export function FileBrowserListView({
handleEmptyAreaClick, handleEmptyAreaClick,
dragState, dragState,
sort, sort,
isExternalDragging,
externalOverFolderId,
setExternalOverFolderId,
resetExternalDragState,
onExternalDrop,
}: FileBrowserListViewProps) { }: FileBrowserListViewProps) {
const [columnSizing, setColumnSizing] = useState<Record<string, number>>({}) const [columnSizing, setColumnSizing] = useState<Record<string, number>>({})
@@ -459,6 +515,11 @@ export function FileBrowserListView({
columnSizing={columnSizing} columnSizing={columnSizing}
virtualRow={virtualRow} virtualRow={virtualRow}
measureElement={rowVirtualizer.measureElement} measureElement={rowVirtualizer.measureElement}
isExternalDragging={isExternalDragging}
externalOverFolderId={externalOverFolderId}
setExternalOverFolderId={setExternalOverFolderId}
resetExternalDragState={resetExternalDragState}
onExternalDrop={onExternalDrop}
/> />
) )
})} })}
@@ -159,6 +159,9 @@ export function useFileActions({
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ['search', teamId, assetId], queryKey: ['search', teamId, assetId],
}) })
queryClient.invalidateQueries({
queryKey: ['folders'],
})
}, },
}, },
) )
@@ -273,7 +276,7 @@ export function useFileActions({
queryKey: ['search', teamId], queryKey: ['search', teamId],
}) })
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ['folders', teamId], queryKey: ['folders'],
}) })
if (data?.id) { if (data?.id) {
setEditingItemId(data.id) setEditingItemId(data.id)
@@ -293,7 +296,7 @@ export function useFileActions({
queryKey: ['search', teamId], queryKey: ['search', teamId],
}) })
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ['folders', teamId], queryKey: ['folders'],
}) })
}, },
}, },
@@ -310,7 +313,7 @@ export function useFileActions({
queryKey: ['search', teamId], queryKey: ['search', teamId],
}) })
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ['folders', teamId], queryKey: ['folders'],
}) })
}, },
}, },
@@ -18,6 +18,7 @@ type FileViewerProps = {
onPause?: () => void onPause?: () => void
onTimeUpdate?: (time: number) => void onTimeUpdate?: (time: number) => void
annotations?: Annotation[] annotations?: Annotation[]
startTime?: number
children?: ReactNode children?: ReactNode
} }
@@ -28,6 +29,7 @@ export function FileViewer({
onPause, onPause,
onTimeUpdate, onTimeUpdate,
annotations, annotations,
startTime,
children, children,
}: FileViewerProps) { }: FileViewerProps) {
const { width: screenWidth } = useScreenSize() const { width: screenWidth } = useScreenSize()
@@ -308,6 +310,7 @@ export function FileViewer({
onPause={onPause} onPause={onPause}
onTimeUpdate={onTimeUpdate} onTimeUpdate={onTimeUpdate}
annotations={displayAnnotations} annotations={displayAnnotations}
startTime={startTime}
> >
{children} {children}
</VideoPlayer> </VideoPlayer>
+281 -12
View File
@@ -13,6 +13,7 @@ import { Button } from '@/ui/components/ui/button'
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogDescription,
DialogFooter, DialogFooter,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
@@ -22,6 +23,7 @@ import {
DropdownMenuContent, DropdownMenuContent,
DropdownMenuItem, DropdownMenuItem,
DropdownMenuTrigger, DropdownMenuTrigger,
DropdownMenuSeparator,
} from '@/ui/components/ui/dropdown-menu' } from '@/ui/components/ui/dropdown-menu'
import { Input } from '@/ui/components/ui/input' import { Input } from '@/ui/components/ui/input'
import { usePermissions } from '@/ui/hooks/use-permissions' import { usePermissions } from '@/ui/hooks/use-permissions'
@@ -31,12 +33,15 @@ import type { AssetInfo, AssetInfoPaginatedList, CollectionInfo, ShareLinkInfo }
import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useMatch, useNavigate, useParams } from '@tanstack/react-router' import { useMatch, useNavigate, useParams } from '@tanstack/react-router'
import { import {
AlertTriangle,
Bookmark, Bookmark,
ChevronDown, ChevronDown,
ChevronRight, ChevronRight,
ChevronsDownUp, ChevronsDownUp,
ChevronsUpDown, ChevronsUpDown,
Clapperboard, Clapperboard,
Download,
Edit,
Folder, Folder,
LayoutGrid, LayoutGrid,
Loader2, Loader2,
@@ -222,16 +227,129 @@ export function FolderTree({
from: '/projects/$projectId/shares/$shareId', from: '/projects/$projectId/shares/$shareId',
shouldThrow: false, shouldThrow: false,
}) })
const folderParams = useParams({
from: '/projects/$projectId/folders/$folderId',
shouldThrow: false,
})
const [renameId, setRenameId] = useState<string | null>(null) const [renameId, setRenameId] = useState<string | null>(null)
const [renameType, setRenameType] = useState<'collection' | 'share'>('collection') const [renameType, setRenameType] = useState<'collection' | 'share' | 'folder'>('collection')
const [renameName, setRenameName] = useState('') const [renameName, setRenameName] = useState('')
const [isRenameOpen, setIsRenameOpen] = useState(false) const [isRenameOpen, setIsRenameOpen] = useState(false)
const [deleteId, setDeleteId] = useState<string | null>(null) const [deleteId, setDeleteId] = useState<string | null>(null)
const [deleteType, setDeleteType] = useState<'collection' | 'share'>('collection') const [deleteType, setDeleteType] = useState<'collection' | 'share' | 'folder'>('collection')
const [isDeleteOpen, setIsDeleteOpen] = useState(false) const [isDeleteOpen, setIsDeleteOpen] = useState(false)
const { mutate: renameFolder } = useMutation({
mutationFn: async ({ id, name }: { id: string; name: string }) => {
const res = await client.api.folders[':folderId'].$put({
param: { folderId: id },
json: { name },
})
if (!res.ok) throw new Error('Failed to rename folder')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
queryClient.invalidateQueries({ queryKey: ['folders'] })
toast.success('Folder renamed')
setIsRenameOpen(false)
},
onError: (err) => {
toast.error(`Error: ${err.message}`)
},
})
const { mutate: deleteFolder } = useMutation({
mutationFn: async (id: string) => {
const res = await client.api.folders.$delete({
json: { ids: [id] },
})
if (!res.ok) throw new Error('Failed to delete folder')
return id
},
onSuccess: (deletedId) => {
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
queryClient.invalidateQueries({ queryKey: ['folders'] })
toast.success('Folder deleted')
setIsDeleteOpen(false)
if (folderParams?.folderId === deletedId) {
navigate({
to: '/projects/$projectId',
params: { projectId },
})
}
},
onError: (err) => {
toast.error(`Error: ${err.message}`)
},
})
const [isDownloadOpen, setIsDownloadOpen] = useState(false)
const [isLoadingLinks, setIsLoadingLinks] = useState(false)
const [resolvedFiles, setResolvedFiles] = useState<
Array<{ id: string; name: string; url: string }>
>([])
const handleDownloadFolder = async (folderId: string) => {
setIsDownloadOpen(true)
setIsLoadingLinks(true)
setResolvedFiles([])
try {
const res = await client.api.files['download-links'].$post({
json: { ids: [folderId] },
})
if (!res.ok) throw new Error('Failed to prepare download links')
const data = await res.json()
setResolvedFiles(data.files)
} catch (error) {
toast.error('Failed to prepare download links')
setIsDownloadOpen(false)
console.error(error)
} finally {
setIsLoadingLinks(false)
}
}
const startDownload = () => {
const files = [...resolvedFiles]
setIsDownloadOpen(false)
if (files.length === 0) return
toast.info(
`Starting download of ${files.length} files. Please allow multiple downloads if prompted by your browser.`,
{
duration: 5000,
},
)
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
const runQueue = async () => {
const batchSize = 5
for (let i = 0; i < files.length; i += batchSize) {
const chunk = files.slice(i, i + batchSize)
for (const file of chunk) {
const a = document.createElement('a')
a.href = file.url
a.download = file.name
a.target = '_blank'
document.body.appendChild(a)
a.click()
a.remove()
}
await delay(1000)
}
}
runQueue().catch((err) => {
console.error('Background downloads failed:', err)
toast.error('Some downloads could not be started')
})
}
const { mutate: renameCollection } = useMutation({ const { mutate: renameCollection } = useMutation({
mutationFn: async ({ id, name }: { id: string; name: string }) => { mutationFn: async ({ id, name }: { id: string; name: string }) => {
const res = await client.api.collections[':collectionId'].$patch({ const res = await client.api.collections[':collectionId'].$patch({
@@ -338,9 +456,6 @@ export function FolderTree({
<ChevronsUpDown 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>
<button className="text-muted-foreground hover:text-foreground flex-none">
<Plus className="h-3.5 w-3.5" />
</button>
</header> </header>
<div <div
@@ -372,6 +487,20 @@ export function FolderTree({
onSelect={onSelect} onSelect={onSelect}
selectedFolderId={selectedFolderId} selectedFolderId={selectedFolderId}
canEdit={canEdit} canEdit={canEdit}
onRenameTrigger={(id, currentName) => {
setRenameId(id)
setRenameType('folder')
setRenameName(currentName)
setIsRenameOpen(true)
}}
onDeleteTrigger={(id) => {
setDeleteId(id)
setDeleteType('folder')
setIsDeleteOpen(true)
}}
onDownloadTrigger={(id) => {
handleDownloadFolder(id)
}}
/> />
{canEdit && ( {canEdit && (
@@ -619,7 +748,12 @@ export function FolderTree({
<DialogContent onClick={(e) => e.stopPropagation()}> <DialogContent onClick={(e) => e.stopPropagation()}>
<DialogHeader> <DialogHeader>
<DialogTitle> <DialogTitle>
Rename {renameType === 'collection' ? 'Collection' : 'Share Link'} Rename{' '}
{renameType === 'collection'
? 'Collection'
: renameType === 'share'
? 'Share Link'
: 'Folder'}
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
<div className="py-4"> <div className="py-4">
@@ -631,8 +765,10 @@ export function FolderTree({
if (e.key === 'Enter' && renameName.trim()) { if (e.key === 'Enter' && renameName.trim()) {
if (renameType === 'collection') { if (renameType === 'collection') {
renameCollection({ id: renameId!, name: renameName }) renameCollection({ id: renameId!, name: renameName })
} else { } else if (renameType === 'share') {
renameShareLink({ id: renameId!, name: renameName }) renameShareLink({ id: renameId!, name: renameName })
} else if (renameType === 'folder') {
renameFolder({ id: renameId!, name: renameName })
} }
} }
}} }}
@@ -647,8 +783,10 @@ export function FolderTree({
onClick={() => { onClick={() => {
if (renameType === 'collection') { if (renameType === 'collection') {
renameCollection({ id: renameId!, name: renameName }) renameCollection({ id: renameId!, name: renameName })
} else { } else if (renameType === 'share') {
renameShareLink({ id: renameId!, name: renameName }) renameShareLink({ id: renameId!, name: renameName })
} else if (renameType === 'folder') {
renameFolder({ id: renameId!, name: renameName })
} }
}} }}
> >
@@ -663,12 +801,22 @@ export function FolderTree({
<AlertDialogContent onClick={(e) => e.stopPropagation()}> <AlertDialogContent onClick={(e) => e.stopPropagation()}>
<AlertDialogHeader> <AlertDialogHeader>
<AlertDialogTitle> <AlertDialogTitle>
Delete {deleteType === 'collection' ? 'Collection' : 'Share Link'}? Delete{' '}
{deleteType === 'collection'
? 'Collection'
: deleteType === 'share'
? 'Share Link'
: 'Folder'}
?
</AlertDialogTitle> </AlertDialogTitle>
<AlertDialogDescription> <AlertDialogDescription>
Are you sure you want to delete this{' '} Are you sure you want to delete this{' '}
{deleteType === 'collection' ? 'collection' : 'share link'}? This action cannot be {deleteType === 'collection'
undone. ? 'collection'
: deleteType === 'share'
? 'share link'
: 'folder'}
? This action cannot be undone.
</AlertDialogDescription> </AlertDialogDescription>
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
@@ -678,8 +826,10 @@ export function FolderTree({
onClick={() => { onClick={() => {
if (deleteType === 'collection') { if (deleteType === 'collection') {
deleteCollection(deleteId!) deleteCollection(deleteId!)
} else { } else if (deleteType === 'share') {
deleteShareLink(deleteId!) deleteShareLink(deleteId!)
} else if (deleteType === 'folder') {
deleteFolder(deleteId!)
} }
}} }}
> >
@@ -688,6 +838,69 @@ export function FolderTree({
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
{/* Folder Download Dialog */}
<Dialog open={isDownloadOpen} onOpenChange={setIsDownloadOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{isLoadingLinks ? 'Preparing Download' : 'Confirm Download'}</DialogTitle>
<DialogDescription>
{isLoadingLinks
? 'Resolving all files and folders. Please wait...'
: 'Selected folder files will be prepared for download.'}
</DialogDescription>
</DialogHeader>
{isLoadingLinks ? (
<div className="space-y-4 py-6 flex flex-col items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<span className="text-sm font-medium text-muted-foreground mt-2">
Preparing download links...
</span>
</div>
) : (
<div className="space-y-4 py-2">
<div className="text-sm text-muted-foreground">
This download will include{' '}
<span className="font-semibold text-foreground">{resolvedFiles.length}</span>{' '}
file(s).
</div>
<div className="flex items-start gap-3 p-3 text-sm rounded-lg bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-300 border border-amber-200 dark:border-amber-900/30">
<AlertTriangle className="h-5 w-5 shrink-0 mt-0.5" />
<div>
<p className="font-semibold">No Folder Structure</p>
<p className="mt-0.5 text-xs text-amber-700/90 dark:text-amber-400/90">
Folder hierarchy will be flattened. All nested files will be downloaded directly
into your default download folder.
</p>
</div>
</div>
</div>
)}
<DialogFooter>
{!isLoadingLinks ? (
<>
<Button variant="outline" onClick={() => setIsDownloadOpen(false)}>
Cancel
</Button>
<Button
onClick={startDownload}
className="gap-2"
disabled={resolvedFiles.length === 0}
>
<Download className="h-4 w-4" />
Start Download
</Button>
</>
) : (
<Button disabled variant="outline">
Cancel
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
</div> </div>
) )
} }
@@ -795,6 +1008,9 @@ interface FolderTreeItemProps {
onSelect?: (folder: AssetInfo) => void onSelect?: (folder: AssetInfo) => void
selectedFolderId?: string selectedFolderId?: string
canEdit?: boolean canEdit?: boolean
onRenameTrigger: (id: string, name: string) => void
onDeleteTrigger: (id: string) => void
onDownloadTrigger: (id: string) => void
} }
function FolderTreeItem({ function FolderTreeItem({
@@ -807,6 +1023,9 @@ function FolderTreeItem({
onSelect, onSelect,
selectedFolderId, selectedFolderId,
canEdit, canEdit,
onRenameTrigger,
onDeleteTrigger,
onDownloadTrigger,
}: FolderTreeItemProps) { }: FolderTreeItemProps) {
const [isExpanded, setIsExpanded] = useState(isRoot || false) const [isExpanded, setIsExpanded] = useState(isRoot || false)
const navigate = useNavigate() const navigate = useNavigate()
@@ -954,6 +1173,53 @@ function FolderTreeItem({
<Folder 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> <span className="flex-1 truncate text-sidebar-foreground">{folder.name}</span>
{canEdit && !isRoot && (
<div
className="opacity-0 group-hover:opacity-100 transition-opacity"
onClick={(e) => e.stopPropagation()}
>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon-sm"
className="h-6 w-6 shrink-0 hover:bg-muted hover:text-muted-foreground p-0"
>
<MoreHorizontal className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-32">
<DropdownMenuItem
onClick={() => {
onRenameTrigger(folder.id!, folder.name)
}}
>
<Edit className="mr-2 h-4 w-4" />
Rename
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
onDownloadTrigger(folder.id!)
}}
>
<Download className="mr-2 h-4 w-4" />
Download
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
className="text-destructive focus:text-destructive focus:bg-destructive/10"
onClick={() => {
onDeleteTrigger(folder.id!)
}}
>
<Trash2 className="mr-2 h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
</div> </div>
{isExpanded && ( {isExpanded && (
@@ -977,6 +1243,9 @@ function FolderTreeItem({
onSelect={onSelect} onSelect={onSelect}
selectedFolderId={selectedFolderId} selectedFolderId={selectedFolderId}
canEdit={canEdit} canEdit={canEdit}
onRenameTrigger={onRenameTrigger}
onDeleteTrigger={onDeleteTrigger}
onDownloadTrigger={onDownloadTrigger}
/> />
))} ))}
{hasNextPage && ( {hasNextPage && (
@@ -1,6 +1,7 @@
import type { NotificationInfo } from '@shumai/dtos' import type { NotificationInfo } from '@shumai/dtos'
import { formatTimeAgo } from '@/ui/lib/time' import { formatTimeAgo } from '@/ui/lib/time'
import { cn } from '@/ui/lib/utils' import { cn } from '@/ui/lib/utils'
import { SpriteScrubber } from './sprite-scrubber'
interface NotificationCardProps { interface NotificationCardProps {
notification: NotificationInfo notification: NotificationInfo
@@ -76,6 +77,13 @@ export const NotificationCard = ({ notification }: NotificationCardProps) => {
} }
})() })()
const isVideoWithSprite =
asset?.mediaType?.startsWith('video/') &&
asset.preview &&
asset.thumbnailUrl &&
asset.originalWidth &&
asset.originalHeight
const hasPreview = const hasPreview =
asset?.preview && (asset.mediaType?.startsWith('image') || asset.mediaType?.startsWith('video')) asset?.preview && (asset.mediaType?.startsWith('image') || asset.mediaType?.startsWith('video'))
@@ -98,7 +106,16 @@ export const NotificationCard = ({ notification }: NotificationCardProps) => {
{hasPreview && ( {hasPreview && (
<div className="w-18 h-18 ml-2 rounded-md overflow-hidden flex-shrink-0 bg-muted border border-border flex items-center justify-center mt-0.5"> <div className="w-18 h-18 ml-2 rounded-md overflow-hidden flex-shrink-0 bg-muted border border-border flex items-center justify-center mt-0.5">
<img src={asset!.preview} alt={asset!.name} className="w-full h-full object-cover" /> {isVideoWithSprite ? (
<SpriteScrubber
spriteUrl={asset.preview!}
thumbnailUrl={asset.thumbnailUrl!}
videoWidth={asset.originalWidth!}
videoHeight={asset.originalHeight!}
/>
) : (
<img src={asset!.preview} alt={asset!.name} className="w-full h-full object-cover" />
)}
</div> </div>
)} )}
</div> </div>
@@ -30,15 +30,19 @@ interface PublicShareManagerProps {
hasPassword: boolean hasPassword: boolean
rootFolderId: string rootFolderId: string
projectId: string projectId: string
viewMode?: string | null
defaultSortOrder?: string | null
} }
initialFolderId?: string initialFolderId?: string
initialFileId?: string initialFileId?: string
startTime?: number
} }
export function PublicShareManager({ export function PublicShareManager({
shareInfo, shareInfo,
initialFolderId, initialFolderId,
initialFileId, initialFileId,
startTime,
}: PublicShareManagerProps) { }: PublicShareManagerProps) {
const navigate = useNavigate() const navigate = useNavigate()
const [password, setPassword] = useState(() => { const [password, setPassword] = useState(() => {
@@ -86,7 +90,7 @@ export function PublicShareManager({
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set()) const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [rightSidebarWidth, setRightSidebarWidth] = useState(360) const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const [isRightSidebarCollapsed] = useState(false) const [isRightSidebarCollapsed, setIsRightSidebarCollapsed] = useState(() => !initialFileId)
const videoRef = useRef<Player | null>(null) const videoRef = useRef<Player | null>(null)
const [annotations, setAnnotations] = useState<Annotation[]>([]) const [annotations, setAnnotations] = useState<Annotation[]>([])
const [currentTime, setCurrentTime] = useState(0) const [currentTime, setCurrentTime] = useState(0)
@@ -203,8 +207,14 @@ export function PublicShareManager({
} }
}, [foldersError, shareInfo.id]) }, [foldersError, shareInfo.id])
const folders = foldersData?.pages.flatMap((page) => page.data ?? []) ?? [] const folders = useMemo(
const files = filesData?.pages.flatMap((page) => page.data ?? []) ?? [] () => foldersData?.pages.flatMap((page) => page.data ?? []) ?? [],
[foldersData],
)
const files = useMemo(
() => filesData?.pages.flatMap((page) => page.data ?? []) ?? [],
[filesData],
)
const currentSelectedItem = useMemo(() => { const currentSelectedItem = useMemo(() => {
if (viewingFileData) return viewingFileData if (viewingFileData) return viewingFileData
@@ -306,7 +316,10 @@ export function PublicShareManager({
isRootFolder: currentFolderId === shareInfo.rootFolderId && !viewingFileId, isRootFolder: currentFolderId === shareInfo.rootFolderId && !viewingFileId,
isPublic: true, isPublic: true,
shareId: shareInfo.id, shareId: shareInfo.id,
fileId: viewingFileId || undefined,
onFolderClick: handleBreadcrumbClick, onFolderClick: handleBreadcrumbClick,
isRightSidebarCollapsed,
onRightSidebarToggle: () => setIsRightSidebarCollapsed((prev) => !prev),
}) })
} }
@@ -321,6 +334,7 @@ export function PublicShareManager({
ancestorFolders, ancestorFolders,
setProjectState, setProjectState,
clearProjectState, clearProjectState,
isRightSidebarCollapsed,
]) ])
let content let content
@@ -387,6 +401,7 @@ export function PublicShareManager({
onPlay={handlePlay} onPlay={handlePlay}
onTimeUpdate={setCurrentTime} onTimeUpdate={setCurrentTime}
annotations={annotations} annotations={annotations}
startTime={startTime}
/> />
)} )}
</div> </div>
@@ -411,7 +426,7 @@ export function PublicShareManager({
}} }}
onItemDoubleClick={handleItemDoubleClick} onItemDoubleClick={handleItemDoubleClick}
onSaveField={() => {}} onSaveField={() => {}}
displayStyle="card" displayStyle={(shareInfo.viewMode as 'card' | 'list') ?? 'card'}
onClearSelection={() => setSelectedIds(new Set())} onClearSelection={() => setSelectedIds(new Set())}
fetchNextFoldersPage={fetchNextFoldersPage} fetchNextFoldersPage={fetchNextFoldersPage}
hasNextFoldersPage={hasNextPageFolders} hasNextFoldersPage={hasNextPageFolders}
+163 -48
View File
@@ -1,8 +1,7 @@
import type { SearchCondition, SearchConditionOperator } from '@shumai/dtos'
import { type FieldInfo } from '@shumai/dtos'
import { Button } from '@/ui/components/ui/button' import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { DebouncedInput } from '@/ui/components/ui/debounced-input' import { DebouncedInput } from '@/ui/components/ui/debounced-input'
import { Input } from '@/ui/components/ui/input'
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
import { import {
Select, Select,
SelectContent, SelectContent,
@@ -11,7 +10,11 @@ import {
SelectValue, SelectValue,
} from '@/ui/components/ui/select' } from '@/ui/components/ui/select'
import { cn } from '@/ui/lib/utils' import { cn } from '@/ui/lib/utils'
import { Trash2 } from 'lucide-react' import type { SearchCondition, SearchConditionOperator } from '@shumai/dtos'
import { type FieldInfo } from '@shumai/dtos'
import { Check, ChevronDown, Trash2 } from 'lucide-react'
import { getOptionStyle } from '../fields-manager'
import RatingField from '../fields/rating-field'
interface FilterPanelProps { interface FilterPanelProps {
fields: FieldInfo[] fields: FieldInfo[]
@@ -43,7 +46,8 @@ export function FilterPanel({
id: f.id!, id: f.id!,
label: f.config?.name || f.description || 'Unknown', label: f.config?.name || f.description || 'Unknown',
type: getFieldType(f), type: getFieldType(f),
options: f.config?.select?.options, options: f.config?.select?.options || f.config?.selectMulti?.options,
config: f.config,
})), })),
].filter((f) => !excludeFields?.includes(f.id)) ].filter((f) => !excludeFields?.includes(f.id))
@@ -77,6 +81,29 @@ export function FilterPanel({
} }
} }
// Convert value format when switching between single/multi-select operators
if (key === 'operator') {
const field = allFields.find((f) => f.id === newConditions[index].field)
if (field && (field.type === 'select' || field.type === 'selectMulti')) {
const oldOperator = conditions[index].operator
const newOperator = value as SearchConditionOperator
const wasMulti = isMultiSelectOperator(field.type, oldOperator)
const isMulti = isMultiSelectOperator(field.type, newOperator)
if (wasMulti && !isMulti) {
// Multi -> Single: take first item or empty string
const arr = Array.isArray(newConditions[index].value)
? (newConditions[index].value as string[])
: []
newConditions[index].value = arr[0] || ''
} else if (!wasMulti && isMulti) {
// Single -> Multi: wrap in array if non-empty
const str = newConditions[index].value as string
newConditions[index].value = str ? [str] : []
}
}
}
onChange(newConditions) onChange(newConditions)
} }
@@ -132,6 +159,7 @@ export function FilterPanel({
{condition.operator !== 'isEmpty' && condition.operator !== 'isNotEmpty' && ( {condition.operator !== 'isEmpty' && condition.operator !== 'isNotEmpty' && (
<ConditionValueInput <ConditionValueInput
field={allFields.find((f) => f.id === condition.field)} field={allFields.find((f) => f.id === condition.field)}
operator={condition.operator}
value={condition.value} value={condition.value}
onChange={(val) => handleConditionChange(index, 'value', val)} onChange={(val) => handleConditionChange(index, 'value', val)}
/> />
@@ -163,7 +191,7 @@ function getFieldType(field: FieldInfo): string {
if (field.config?.type === 'selectMulti') return 'selectMulti' if (field.config?.type === 'selectMulti') return 'selectMulti'
if (field.config?.type === 'number') return 'number' if (field.config?.type === 'number') return 'number'
if (field.config?.type === 'date') return 'date' if (field.config?.type === 'date') return 'date'
if (field.config?.type === 'rating') return 'number' if (field.config?.type === 'rating') return 'rating'
if (field.config?.type === 'toggle') return 'toggle' if (field.config?.type === 'toggle') return 'toggle'
return 'text' return 'text'
} }
@@ -173,6 +201,7 @@ function getDefaultOperator(type: string): SearchConditionOperator {
case 'selectMulti': case 'selectMulti':
return 'hasAny' as SearchConditionOperator return 'hasAny' as SearchConditionOperator
case 'number': case 'number':
case 'rating':
case 'date': case 'date':
return 'eq' return 'eq'
default: default:
@@ -207,6 +236,7 @@ function getOperators(field: { id: string; label: string; type: string }): {
{ value: 'isNotEmpty' as SearchConditionOperator, label: 'is not empty' }, { value: 'isNotEmpty' as SearchConditionOperator, label: 'is not empty' },
] ]
case 'number': case 'number':
case 'rating':
return [ return [
{ value: 'eq' as SearchConditionOperator, label: '=' }, { value: 'eq' as SearchConditionOperator, label: '=' },
{ value: 'neq' as SearchConditionOperator, label: '≠' }, { value: 'neq' as SearchConditionOperator, label: '≠' },
@@ -254,67 +284,142 @@ function getOperators(field: { id: string; label: string; type: string }): {
} }
} }
// eslint-disable-next-line @typescript-eslint/no-explicit-any interface SelectOptionItem {
type FieldType = any id: string
displayName: string
color?: string
}
interface FilterField {
id: string
label: string
type: string
options?: SelectOptionItem[]
config?: FieldInfo['config']
}
function isMultiSelectOperator(fieldType: string, operator: SearchConditionOperator): boolean {
if (fieldType === 'select') {
return operator === 'in' || operator === 'notIn'
}
if (fieldType === 'selectMulti') {
return operator !== 'eq'
}
return false
}
function MultiSelectValueInput({
options,
selected,
onChange,
}: {
options: SelectOptionItem[]
selected: string[]
onChange: (val: string[]) => void
}) {
const selectedOptions = options.filter((opt) => selected.includes(opt.id))
const toggleOption = (optionId: string) => {
let newVal
if (selected.includes(optionId)) {
newVal = selected.filter((id) => id !== optionId)
} else {
newVal = [...selected, optionId]
}
onChange(newVal)
}
return (
<Popover>
<PopoverTrigger asChild>
<button
type="button"
className="flex min-h-9 w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-1.5 text-sm shadow-xs hover:bg-accent/50 focus:outline-hidden focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 text-left"
>
<div className="flex flex-wrap gap-1 items-center max-w-[90%]">
{selectedOptions.length === 0 ? (
<span className="text-muted-foreground">Select options...</span>
) : (
selectedOptions.map((option) => (
<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-[20px]"
style={getOptionStyle(option.color)}
>
{option.displayName}
</span>
))
)}
</div>
<ChevronDown className="h-4 w-4 shrink-0 opacity-50 ml-2" />
</button>
</PopoverTrigger>
<PopoverContent
className="w-64 p-1 bg-popover border border-border rounded-lg shadow-xl max-h-60 overflow-auto"
align="start"
>
{options.map((option) => {
const isSelected = selected.includes(option.id)
return (
<div
key={option.id}
onClick={() => toggleOption(option.id)}
className="px-3 py-2 hover:bg-accent cursor-pointer flex items-center justify-between rounded-sm"
>
<span
className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
style={getOptionStyle(option.color)}
>
{option.displayName}
</span>
{isSelected && <Check className="w-4 h-4 text-primary" />}
</div>
)
})}
</PopoverContent>
</Popover>
)
}
function ConditionValueInput({ function ConditionValueInput({
field, field,
operator,
value, value,
onChange, onChange,
}: { }: {
field: FieldType field: FilterField | undefined
operator: SearchConditionOperator
value: unknown value: unknown
onChange: (val: unknown) => void onChange: (val: unknown) => void
}) { }) {
if (!field) return <Input disabled /> if (!field) return <Input disabled />
if (field.type === 'select' && field.options) { if ((field.type === 'select' || field.type === 'selectMulti') && field.options) {
if (isMultiSelectOperator(field.type, operator)) {
const selected = Array.isArray(value) ? (value as string[]) : []
return (
<MultiSelectValueInput
options={field.options}
selected={selected}
onChange={(val) => onChange(val)}
/>
)
}
// Single-select
return ( return (
<Select value={value as string} onValueChange={onChange}> <Select value={value as string} onValueChange={onChange}>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Select option" /> <SelectValue placeholder="Select option" />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{field.options.map((opt: FieldType) => ( {field.options.map((opt) => (
<SelectItem key={opt.id} value={opt.id}> <SelectItem key={opt.id} value={opt.id}>
{opt.displayName} <span
</SelectItem> className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
))} style={getOptionStyle(opt.color)}
</SelectContent> >
</Select>
)
}
if (field.type === 'selectMulti' && field.options) {
const selected = Array.isArray(value) ? value : []
return (
<Select
value={selected[0] || ''}
onValueChange={(val) => {
if (selected.includes(val)) {
onChange(selected.filter((v) => v !== val))
} else {
onChange([...selected, val])
}
}}
>
<SelectTrigger>
<SelectValue
placeholder={selected.length > 0 ? `${selected.length} selected` : 'Select options'}
/>
</SelectTrigger>
<SelectContent>
{field.options.map((opt: FieldType) => (
<SelectItem key={opt.id} value={opt.id}>
<div className="flex items-center gap-2">
<input
type="checkbox"
checked={selected.includes(opt.id)}
readOnly
className="pointer-events-none"
/>
{opt.displayName} {opt.displayName}
</div> </span>
</SelectItem> </SelectItem>
))} ))}
</SelectContent> </SelectContent>
@@ -378,6 +483,16 @@ function ConditionValueInput({
) )
} }
if (field.type === 'rating') {
return (
<RatingField
value={Number(value) || 0}
config={field.config || { name: field.label, type: 'rating' }}
onSave={onChange}
/>
)
}
if (field.type === 'toggle') { if (field.type === 'toggle') {
return ( return (
<Select <Select
@@ -4,6 +4,7 @@ import type { SearchCondition } from '@shumai/dtos'
import { client } from '@/ui/api/client' import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button' import { Button } from '@/ui/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import { Input } from '@/ui/components/ui/input' import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label' import { Label } from '@/ui/components/ui/label'
import { Switch } from '@/ui/components/ui/switch' import { Switch } from '@/ui/components/ui/switch'
@@ -221,9 +222,6 @@ export function SearchFilterDialog({
const handleClearFilters = () => { const handleClearFilters = () => {
setConditions([]) setConditions([])
setSearchInput('')
setTriggerQuery('')
setIsSemantic(false)
} }
const formatTimestamp = (seconds: number) => { const formatTimestamp = (seconds: number) => {
@@ -242,7 +240,10 @@ export function SearchFilterDialog({
navigate({ navigate({
to: '/projects/$projectId/files/$fileId', to: '/projects/$projectId/files/$fileId',
params: { projectId, fileId: item.versionStack ? item.versionStack.id : item.id! }, params: { projectId, fileId: item.versionStack ? item.versionStack.id : item.id! },
search: { version: undefined }, search: {
version: undefined,
start: item.startTime && item.startTime > 0 ? item.startTime : undefined,
},
}) })
} }
onOpenChange(false) onOpenChange(false)
@@ -252,7 +253,7 @@ export function SearchFilterDialog({
return ( return (
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[900px] p-0 gap-0 overflow-hidden bg-background border-border rounded-2xl shadow-2xl flex flex-col max-h-[90vh]"> <DialogContent className="sm:max-w-[900px] p-0 gap-0 overflow-hidden bg-background border-border rounded-2xl shadow-2xl flex flex-col h-[85vh]">
<DialogHeader className="px-6 pt-3 pb-0 text-left"> <DialogHeader className="px-6 pt-3 pb-0 text-left">
<DialogTitle className="text-lg font-bold">Search</DialogTitle> <DialogTitle className="text-lg font-bold">Search</DialogTitle>
</DialogHeader> </DialogHeader>
@@ -325,17 +326,20 @@ export function SearchFilterDialog({
</div> </div>
</form> </form>
<div <div className="flex items-center justify-between py-1.5 px-1 mt-1 select-none">
onClick={() => setIsFiltersExpanded(!isFiltersExpanded)}
className="flex items-center justify-between py-1.5 px-1 mt-1 rounded-lg hover:bg-accent/50 cursor-pointer select-none transition-colors group"
>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{isFiltersExpanded ? ( <button
<ChevronUp className="w-4 h-4 text-muted-foreground group-hover:text-foreground" /> type="button"
) : ( onClick={() => setIsFiltersExpanded(!isFiltersExpanded)}
<ChevronDown className="w-4 h-4 text-muted-foreground group-hover:text-foreground" /> className="flex items-center gap-2 py-1 px-1.5 rounded-lg hover:bg-accent/50 cursor-pointer transition-colors group text-left"
)} >
<span className="text-xs font-semibold text-foreground/80">Filters</span> {isFiltersExpanded ? (
<ChevronUp className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />
) : (
<ChevronDown className="w-4 h-4 text-muted-foreground group-hover:text-foreground" />
)}
<span className="text-xs font-semibold text-foreground/80">Filters</span>
</button>
{activeFiltersCount > 0 && ( {activeFiltersCount > 0 && (
<span className="px-1.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-primary/10 text-primary border border-primary/20"> <span className="px-1.5 py-0.5 rounded-full text-[10px] font-mono font-bold bg-primary/10 text-primary border border-primary/20">
@@ -344,7 +348,7 @@ export function SearchFilterDialog({
)} )}
</div> </div>
{(activeFiltersCount > 0 || searchInput) && ( {activeFiltersCount > 0 && (
<button <button
type="button" type="button"
onClick={(e) => { onClick={(e) => {
@@ -359,148 +363,155 @@ export function SearchFilterDialog({
</div> </div>
{isFiltersExpanded && ( {isFiltersExpanded && (
<div className="mt-1 p-4 bg-muted/40 border border-border rounded-xl flex flex-col gap-3 animate-in slide-in-from-top-1 duration-200"> <ScrollArea className="mt-1 max-h-[28vh] rounded-xl border border-border bg-muted/40">
<FilterPanel <div className="p-4 flex flex-col gap-3 animate-in slide-in-from-top-1 duration-200">
fields={fields} <FilterPanel
conditions={conditions} fields={fields}
onChange={setConditions} conditions={conditions}
excludeFields={['name']} onChange={setConditions}
hidePrefix={true} excludeFields={['name']}
className="p-0 bg-transparent space-y-2" hidePrefix={true}
/> className="p-0 bg-transparent space-y-2"
</div> />
</div>
</ScrollArea>
)} )}
</div> </div>
{/* Results Body ported from Demo */} {/* Results Body ported from Demo */}
<div className="flex-1 overflow-y-auto p-4 md:p-5 bg-background"> <ScrollArea className="flex-1 min-h-0 bg-background">
<div className="flex items-center justify-between mb-3 px-1"> <div className="p-4 md:p-5">
<span className="text-[11px] font-bold uppercase tracking-wider text-muted-foreground/60 font-mono"> <div className="flex items-center justify-between mb-3 px-1">
Search Results <span className="text-[11px] font-bold uppercase tracking-wider text-muted-foreground/60 font-mono">
</span> Search Results
{isLoading && (
<span className="inline-flex items-center gap-1.5 text-xs text-primary">
<Loader2 className="h-3 w-3 animate-spin" />
{isSemantic
? 'Semantic search using media intelligence might be slow...'
: 'Querying database...'}
</span> </span>
)} {isLoading && (
</div> <span className="inline-flex items-center gap-1.5 text-xs text-primary">
<Loader2 className="h-3 w-3 animate-spin" />
{isSemantic
? 'Semantic search using media intelligence might be slow...'
: 'Querying database...'}
</span>
)}
</div>
<div className="flex flex-col border border-border rounded-xl divide-y divide-border overflow-hidden"> <div className="flex flex-col border border-border rounded-xl divide-y divide-border overflow-hidden">
{!hasActiveCriteria ? ( {!hasActiveCriteria ? (
<div className="py-20 text-center flex flex-col items-center justify-center bg-muted/20 px-4"> <div className="py-20 text-center flex flex-col items-center justify-center bg-muted/20 px-4">
<Search className="w-10 h-10 text-muted-foreground/30 mb-2" /> <Search className="w-10 h-10 text-muted-foreground/30 mb-2" />
<h3 className="text-sm font-semibold text-foreground/80">Ready to Search</h3> <h3 className="text-sm font-semibold text-foreground/80">Ready to Search</h3>
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto"> <p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
Type your query above and click the Search button to display results. Type your query above and click the Search button to display results.
</p>
{isSemantic && (
<p className="text-xs text-muted-foreground/80 max-w-md mt-4 mx-auto border-t border-border/60 pt-3">
Semantic search results will be ordered by their relevance to the search query
text, but won't be strictly filtered. If you need accurate filtering, please add
filter conditions to control that.
</p> </p>
)} {isSemantic && (
</div> <p className="text-xs text-muted-foreground/80 max-w-md mt-4 mx-auto border-t border-border/60 pt-3">
) : searchError ? ( Semantic search results will be ordered by their relevance to the search query
<div className="py-12 px-4 text-center flex flex-col items-center justify-center bg-muted/20"> text, but won't be strictly filtered. If you need accurate filtering, please
<AlertCircle className="w-10 h-10 text-destructive/50 mb-2" /> add filter conditions to control that.
<h3 className="text-sm font-semibold text-foreground/80">Search failed</h3> </p>
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto"> )}
{searchError.message.includes('Embedding agent not configured')
? 'Please create and enable an embedding agent in the team settings to use semantic search.'
: searchError.message}
</p>
</div>
) : isLoading ? (
Array.from({ length: 3 }).map((_, idx) => (
<div key={idx} className="p-3.5 flex items-center gap-3 animate-pulse bg-muted/10">
<div className="w-11 h-11 rounded-xl bg-muted shrink-0" />
<div className="flex-1 space-y-2">
<div className="h-4 bg-muted rounded w-1/3" />
<div className="h-3 bg-muted/50 rounded w-1/4" />
</div>
</div> </div>
)) ) : searchError ? (
) : flattenedResults.length === 0 ? ( <div className="py-12 px-4 text-center flex flex-col items-center justify-center bg-muted/20">
<div className="py-12 px-4 text-center flex flex-col items-center justify-center bg-muted/20"> <AlertCircle className="w-10 h-10 text-destructive/50 mb-2" />
<AlertCircle className="w-10 h-10 text-muted-foreground/30 mb-2" /> <h3 className="text-sm font-semibold text-foreground/80">Search failed</h3>
<h3 className="text-sm font-semibold text-foreground/80"> <p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
No records matched your criteria {searchError.message.includes('Embedding agent not configured')
</h3> ? 'Please create and enable an embedding agent in the team settings to use semantic search.'
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto"> : searchError.message}
Try adjusting spelling or removing filter rows. </p>
</p> </div>
</div> ) : isLoading ? (
) : ( Array.from({ length: 3 }).map((_, idx) => (
<>
{flattenedResults.map((record) => (
<div <div
key={record.id} key={idx}
onClick={() => handleResultClick(record)} className="p-3.5 flex items-center gap-3 animate-pulse bg-muted/10"
className="p-3.5 flex items-center gap-3 hover:bg-muted/40 transition-colors group/record cursor-pointer"
> >
<div <div className="w-11 h-11 rounded-xl bg-muted shrink-0" />
className={cn( <div className="flex-1 space-y-2">
'shrink-0 w-11 h-11 rounded-xl shadow-xs flex items-center justify-center text-white font-bold relative group-hover/record:scale-105 transition-transform bg-muted overflow-hidden', <div className="h-4 bg-muted rounded w-1/3" />
record.type === 'folder' ? 'bg-primary/5' : '', <div className="h-3 bg-muted/50 rounded w-1/4" />
)}
>
{record.preview?.thumbnailUrl ? (
<img
src={record.preview.thumbnailUrl}
alt=""
className="w-full h-full object-cover rounded-xl"
/>
) : record.type === 'folder' ? (
<FolderIcon className="h-6 w-6 text-primary/70" />
) : (
<FileIcon className="h-6 w-6 text-muted-foreground" />
)}
</div> </div>
</div>
))
) : flattenedResults.length === 0 ? (
<div className="py-12 px-4 text-center flex flex-col items-center justify-center bg-muted/20">
<AlertCircle className="w-10 h-10 text-muted-foreground/30 mb-2" />
<h3 className="text-sm font-semibold text-foreground/80">
No records matched your criteria
</h3>
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
Try adjusting spelling or removing filter rows.
</p>
</div>
) : (
<>
{flattenedResults.map((record) => (
<div
key={record.id}
onClick={() => handleResultClick(record)}
className="p-3.5 flex items-center gap-3 hover:bg-muted/40 transition-colors group/record cursor-pointer"
>
<div
className={cn(
'shrink-0 w-11 h-11 rounded-xl shadow-xs flex items-center justify-center text-white font-bold relative group-hover/record:scale-105 transition-transform bg-muted overflow-hidden',
record.type === 'folder' ? 'bg-primary/5' : '',
)}
>
{record.preview?.thumbnailUrl ? (
<img
src={record.preview.thumbnailUrl}
alt=""
className="w-full h-full object-cover rounded-xl"
/>
) : record.type === 'folder' ? (
<FolderIcon className="h-6 w-6 text-primary/70" />
) : (
<FileIcon className="h-6 w-6 text-muted-foreground" />
)}
</div>
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
<div className="truncate"> <div className="truncate">
<span className="font-medium text-sm text-foreground group-hover/record:text-primary transition-colors block truncate"> <span className="font-medium text-sm text-foreground group-hover/record:text-primary transition-colors block truncate">
{record.name} {record.name}
</span>
<span className="text-xs text-muted-foreground block mt-0.5 truncate">
{record.type === 'folder'
? 'Folder'
: `Size: ${formatSize(record.sizeByte || 0)}`}
</span>
{record.startTime !== undefined &&
record.startTime !== null &&
record.endTime !== undefined &&
record.endTime !== null && (
<span className="text-[10px] font-semibold text-primary bg-primary/10 border border-primary/20 px-1.5 py-0.5 rounded mt-1 inline-block">
Match found at {formatTimestamp(record.startTime)} -{' '}
{formatTimestamp(record.endTime)}
</span>
)}
</div>
<span className="text-xs text-muted-foreground font-mono shrink-0">
{new Date(record.createdAt).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
})}
</span> </span>
<span className="text-xs text-muted-foreground block mt-0.5 truncate">
{record.type === 'folder'
? 'Folder'
: `Size: ${formatSize(record.sizeByte || 0)}`}
</span>
{record.startTime !== undefined &&
record.startTime !== null &&
record.endTime !== undefined &&
record.endTime !== null && (
<span className="text-[10px] font-semibold text-primary bg-primary/10 border border-primary/20 px-1.5 py-0.5 rounded mt-1 inline-block">
Match found at {formatTimestamp(record.startTime)} -{' '}
{formatTimestamp(record.endTime)}
</span>
)}
</div> </div>
<span className="text-xs text-muted-foreground font-mono shrink-0">
{new Date(record.createdAt).toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
})}
</span>
</div> </div>
</div> </div>
</div> ))}
))} {(hasNextPage || isFetchingNextPage) && (
{(hasNextPage || isFetchingNextPage) && ( <div ref={ref} className="p-4 flex justify-center items-center">
<div ref={ref} className="p-4 flex justify-center items-center"> <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /> </div>
</div> )}
)} </>
</> )}
)} </div>
</div> </div>
</div> </ScrollArea>
{/* Footer ported from Demo */} {/* Footer ported from Demo */}
<div className="p-4 border-t border-border bg-muted/30 flex items-center justify-between shrink-0"> <div className="p-4 border-t border-border bg-muted/30 flex items-center justify-between shrink-0">
+49 -10
View File
@@ -1,4 +1,9 @@
import type { AncestorFolder, AssetInfo, AssetInfoPaginatedList } from '@shumai/dtos' import type {
AncestorFolder,
AssetInfo,
AssetInfoPaginatedList,
UpdateShareLinkRequest,
} from '@shumai/dtos'
import { client } from '@/ui/api/client' import { client } from '@/ui/api/client'
import { useMutation, useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useState, useMemo } from 'react' import { useEffect, useState, useMemo } from 'react'
@@ -86,12 +91,20 @@ export default function ShareManager({
const [rightSidebarWidth, setRightSidebarWidth] = useState(360) const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const { const {
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed, shareConfigLeftSidebarCollapsed: isLeftSidebarCollapsed,
fileListRightSidebarCollapsed: isRightSidebarCollapsed, shareConfigRightSidebarCollapsed: isRightSidebarCollapsed,
viewModes,
} = useUiStore() } = useUiStore()
const displayStyle = viewModes[projectId] ?? 'card' const defaultSortOrder = shareLink?.defaultSortOrder || null
let sort: string | undefined
let order: string | undefined
if (defaultSortOrder) {
const parts = defaultSortOrder.split(':')
sort = parts[0]
order = parts[1]
}
const displayStyle = (shareLink?.viewMode as 'card' | 'list') ?? 'card'
const { const {
data: foldersData, data: foldersData,
@@ -99,13 +112,15 @@ export default function ShareManager({
hasNextPage: hasNextPageFolders, hasNextPage: hasNextPageFolders,
isFetchingNextPage: isFetchingNextFoldersPage, isFetchingNextPage: isFetchingNextFoldersPage,
} = useInfiniteQuery<AssetInfoPaginatedList>({ } = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: ['folder-children', teamId, currentFolderId, 'folder'], queryKey: ['folder-children', teamId, currentFolderId, 'folder', sort, order],
queryFn: async ({ pageParam }) => { queryFn: async ({ pageParam }) => {
const res = await client.api.folders[':folderId'].children.$get({ const res = await client.api.folders[':folderId'].children.$get({
param: { folderId: currentFolderId! }, param: { folderId: currentFolderId! },
query: { query: {
assetType: 'folder', assetType: 'folder',
after: pageParam as string, after: pageParam as string,
sort,
order,
}, },
}) })
if (!res.ok) throw new Error('Failed to fetch folders') if (!res.ok) throw new Error('Failed to fetch folders')
@@ -122,13 +137,15 @@ export default function ShareManager({
hasNextPage: hasNextPageFiles, hasNextPage: hasNextPageFiles,
isFetchingNextPage: isFetchingNextFilesPage, isFetchingNextPage: isFetchingNextFilesPage,
} = useInfiniteQuery<AssetInfoPaginatedList>({ } = useInfiniteQuery<AssetInfoPaginatedList>({
queryKey: ['folder-children', teamId, currentFolderId, 'file'], queryKey: ['folder-children', teamId, currentFolderId, 'file', sort, order],
queryFn: async ({ pageParam }) => { queryFn: async ({ pageParam }) => {
const res = await client.api.folders[':folderId'].children.$get({ const res = await client.api.folders[':folderId'].children.$get({
param: { folderId: currentFolderId! }, param: { folderId: currentFolderId! },
query: { query: {
assetType: 'file', assetType: 'file',
after: pageParam as string, after: pageParam as string,
sort,
order,
}, },
}) })
if (!res.ok) throw new Error('Failed to fetch files') if (!res.ok) throw new Error('Failed to fetch files')
@@ -212,6 +229,22 @@ export default function ShareManager({
}, },
}) })
const $updateShare = client.api.shares[':shareId'].$put
const { mutate: updateShare } = useMutation({
mutationFn: async (json: UpdateShareLinkRequest) => {
const res = await $updateShare({
param: { shareId },
json,
})
if (!res.ok) throw new Error('Failed to update')
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['share', shareId] })
toast.success('Settings updated')
},
})
const handleItemDoubleClick = (item: AssetInfo) => { const handleItemDoubleClick = (item: AssetInfo) => {
if (item.type === 'folder' || item.targetType === 'folder') { if (item.type === 'folder' || item.targetType === 'folder') {
const currentFolderName = const currentFolderName =
@@ -239,7 +272,7 @@ export default function ShareManager({
onDragStart={handleDragStart} onDragStart={handleDragStart}
onDragEnd={handleDragEnd} onDragEnd={handleDragEnd}
> >
<div className="flex h-screen flex-col bg-background"> <div className="flex flex-1 flex-col bg-background min-h-0">
<div className="flex flex-1 overflow-hidden relative"> <div className="flex flex-1 overflow-hidden relative">
{!isLeftSidebarCollapsed && ( {!isLeftSidebarCollapsed && (
<> <>
@@ -305,8 +338,14 @@ export default function ShareManager({
setRightSidebarWidth((p) => Math.max(240, Math.min(600, p - delta))) setRightSidebarWidth((p) => Math.max(240, Math.min(600, p - delta)))
} }
/> />
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0"> <div style={{ width: rightSidebarWidth }} className="flex-shrink-0 h-full">
<ShareSettingsSidebar shareLink={shareLink} /> <ShareSettingsSidebar
shareLink={shareLink}
viewMode={displayStyle}
onViewModeChange={(mode) => updateShare({ viewMode: mode })}
defaultSortOrder={defaultSortOrder}
onSortOrderChange={(sortOrder) => updateShare({ defaultSortOrder: sortOrder })}
/>
</div> </div>
</> </>
)} )}
@@ -11,19 +11,39 @@ import {
Copy, Copy,
ExternalLink, ExternalLink,
Shield, Shield,
Settings2,
Palette, Palette,
ListFilter, ListFilter,
SortAsc, SortAsc,
LayoutGrid,
List,
ArrowDownUp,
} from 'lucide-react' } from 'lucide-react'
import React, { useState } from 'react' import React, { useState } from 'react'
import { toast } from 'sonner' import { toast } from 'sonner'
import { DateTimePicker } from '@/ui/components/datetime-picker' import { DateTimePicker } from '@/ui/components/datetime-picker'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/ui/components/ui/select'
interface ShareSettingsSidebarProps { interface ShareSettingsSidebarProps {
shareLink: ShareLinkInfo shareLink: ShareLinkInfo
viewMode: 'card' | 'list'
onViewModeChange: (mode: 'card' | 'list') => void
defaultSortOrder: string | null
onSortOrderChange: (sortOrder: string | null) => void
} }
export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) { export function ShareSettingsSidebar({
shareLink,
viewMode,
onViewModeChange,
defaultSortOrder,
onSortOrderChange,
}: ShareSettingsSidebarProps) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const [expireAt, setExpireAt] = useState<Date | undefined>( const [expireAt, setExpireAt] = useState<Date | undefined>(
@@ -74,6 +94,15 @@ export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
updateShare({ fieldVisibility: next }) updateShare({ fieldVisibility: next })
} }
// Parse current sort field and order
let currentSortField = 'index'
let currentSortOrder = 'asc'
if (defaultSortOrder) {
const parts = defaultSortOrder.split(':')
currentSortField = parts[0]
currentSortOrder = parts[1] || 'asc'
}
return ( return (
<div className="flex flex-col h-full bg-background border-l border-border"> <div className="flex flex-col h-full bg-background border-l border-border">
<div className="flex-1 overflow-y-auto"> <div className="flex-1 overflow-y-auto">
@@ -87,29 +116,20 @@ export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
/> />
</div> </div>
<div className="flex gap-2"> <div className="relative w-full">
<div className="relative flex-1"> <Input value={shareUrl} readOnly className="pr-10 bg-muted/50 text-xs" />
<Input value={shareUrl} readOnly className="pr-10 bg-muted/50 text-xs" /> <Button
<Button variant="ghost"
variant="ghost" size="icon"
size="icon" className="absolute right-0 top-0 h-full"
className="absolute right-0 top-0 h-full" onClick={() => copyToClipboard(shareUrl)}
onClick={() => copyToClipboard(shareUrl)} >
> <Copy className="h-4 w-4" />
<Copy className="h-4 w-4" />
</Button>
</div>
<Button variant="outline" className="px-3">
<Settings2 className="h-4 w-4 mr-2" />
Public
</Button> </Button>
</div> </div>
<Input placeholder="Send to name or email" className="text-sm" />
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<SidebarAccordionItem title="Permissions" icon={<Settings2 className="h-4 w-4" />} />
<SidebarAccordionItem title="Security" icon={<Shield className="h-4 w-4" />}> <SidebarAccordionItem title="Security" icon={<Shield className="h-4 w-4" />}>
<div className="p-3 space-y-4 pt-0"> <div className="p-3 space-y-4 pt-0">
<div className="space-y-2"> <div className="space-y-2">
@@ -167,7 +187,28 @@ export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
</div> </div>
</div> </div>
</SidebarAccordionItem> </SidebarAccordionItem>
<SidebarAccordionItem title="Appearance" icon={<Palette className="h-4 w-4" />} /> <SidebarAccordionItem title="Appearance" icon={<Palette className="h-4 w-4" />}>
<div className="p-3 space-y-3 pt-0 flex gap-2">
<Button
variant={viewMode === 'card' ? 'secondary' : 'outline'}
size="sm"
className="flex-1 gap-2 text-xs"
onClick={() => onViewModeChange('card')}
>
<LayoutGrid className="h-4 w-4" />
Grid
</Button>
<Button
variant={viewMode === 'list' ? 'secondary' : 'outline'}
size="sm"
className="flex-1 gap-2 text-xs"
onClick={() => onViewModeChange('list')}
>
<List className="h-4 w-4" />
List
</Button>
</div>
</SidebarAccordionItem>
<SidebarAccordionItem title="Fields" icon={<ListFilter className="h-4 w-4" />}> <SidebarAccordionItem title="Fields" icon={<ListFilter className="h-4 w-4" />}>
<div className="p-3 space-y-3 pt-0"> <div className="p-3 space-y-3 pt-0">
{(fields as MetadataFieldInfo[])?.map((field) => ( {(fields as MetadataFieldInfo[])?.map((field) => (
@@ -181,7 +222,65 @@ export function ShareSettingsSidebar({ shareLink }: ShareSettingsSidebarProps) {
))} ))}
</div> </div>
</SidebarAccordionItem> </SidebarAccordionItem>
<SidebarAccordionItem title="Sort by" icon={<SortAsc className="h-4 w-4" />} /> <SidebarAccordionItem title="Sort by" icon={<SortAsc className="h-4 w-4" />}>
<div className="p-3 space-y-4 pt-0">
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">Field</Label>
<Select
value={currentSortField}
onValueChange={(val) => {
if (val === 'index') {
onSortOrderChange(null)
} else {
onSortOrderChange(`${val}:${currentSortOrder}`)
}
}}
>
<SelectTrigger className="w-full text-xs h-9">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="index">Custom</SelectItem>
<SelectItem value="name">Name</SelectItem>
<SelectItem value="createdAt">Date Created</SelectItem>
<SelectItem value="size">Size</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">Order</Label>
<Button
variant="outline"
className="w-full justify-between font-normal text-xs h-9"
disabled={currentSortField === 'index'}
onClick={() => {
const nextOrder = currentSortOrder === 'asc' ? 'desc' : 'asc'
onSortOrderChange(`${currentSortField}:${nextOrder}`)
}}
>
<span>
{currentSortField === 'name'
? currentSortOrder === 'asc'
? 'A → Z'
: 'Z → A'
: currentSortField === 'createdAt'
? currentSortOrder === 'asc'
? 'Oldest → Newest'
: 'Newest → Oldest'
: currentSortField === 'size'
? currentSortOrder === 'asc'
? 'Smallest → Largest'
: 'Largest → Smallest'
: currentSortOrder === 'asc'
? 'Ascending'
: 'Descending'}
</span>
<ArrowDownUp className="h-4 w-4 opacity-50" />
</Button>
</div>
</div>
</SidebarAccordionItem>
</div> </div>
</div> </div>
</div> </div>
+29 -11
View File
@@ -27,23 +27,41 @@ export function TopNav() {
const isFileView = !!fileId const isFileView = !!fileId
const isShareConfig = !!shareId && !isFileView
const isLeftSidebarCollapsed = isFileView const isLeftSidebarCollapsed = isFileView
? uiStore.fileViewLeftSidebarCollapsed ? uiStore.fileViewLeftSidebarCollapsed
: uiStore.fileListLeftSidebarCollapsed : isShareConfig
? uiStore.shareConfigLeftSidebarCollapsed
: uiStore.fileListLeftSidebarCollapsed
const onLeftSidebarToggle = isPublic const onLeftSidebarToggle = isPublic
? undefined ? undefined
: () => : () =>
isFileView isFileView
? uiStore.setFileViewLeftSidebarCollapsed(!uiStore.fileViewLeftSidebarCollapsed) ? uiStore.setFileViewLeftSidebarCollapsed(!uiStore.fileViewLeftSidebarCollapsed)
: uiStore.setFileListLeftSidebarCollapsed(!uiStore.fileListLeftSidebarCollapsed) : isShareConfig
? uiStore.setShareConfigLeftSidebarCollapsed(!uiStore.shareConfigLeftSidebarCollapsed)
: uiStore.setFileListLeftSidebarCollapsed(!uiStore.fileListLeftSidebarCollapsed)
const isRightSidebarCollapsed = isFileView const isRightSidebarCollapsed =
? uiStore.fileViewRightSidebarCollapsed isPublic && projectState.isRightSidebarCollapsed !== undefined
: uiStore.fileListRightSidebarCollapsed ? projectState.isRightSidebarCollapsed
const onRightSidebarToggle = () => : isFileView
isFileView ? uiStore.fileViewRightSidebarCollapsed
? uiStore.setFileViewRightSidebarCollapsed(!uiStore.fileViewRightSidebarCollapsed) : isShareConfig
: uiStore.setFileListRightSidebarCollapsed(!uiStore.fileListRightSidebarCollapsed) ? uiStore.shareConfigRightSidebarCollapsed
: uiStore.fileListRightSidebarCollapsed
const onRightSidebarToggle =
isPublic && projectState.onRightSidebarToggle
? projectState.onRightSidebarToggle
: () =>
isFileView
? uiStore.setFileViewRightSidebarCollapsed(!uiStore.fileViewRightSidebarCollapsed)
: isShareConfig
? uiStore.setShareConfigRightSidebarCollapsed(
!uiStore.shareConfigRightSidebarCollapsed,
)
: uiStore.setFileListRightSidebarCollapsed(!uiStore.fileListRightSidebarCollapsed)
const displayStyle = projectId ? (uiStore.viewModes[projectId] ?? 'card') : 'card' const displayStyle = projectId ? (uiStore.viewModes[projectId] ?? 'card') : 'card'
const onDisplayStyleChange = isPublic const onDisplayStyleChange = isPublic
@@ -60,8 +78,8 @@ export function TopNav() {
ancestorFolders={ancestorFolders} ancestorFolders={ancestorFolders}
currentAsset={currentAsset} currentAsset={currentAsset}
isRootFolder={isRootFolder} isRootFolder={isRootFolder}
displayStyle={isFileView ? undefined : displayStyle} displayStyle={isFileView || isShareConfig ? undefined : displayStyle}
onDisplayStyleChange={isFileView ? undefined : onDisplayStyleChange} onDisplayStyleChange={isFileView || isShareConfig ? undefined : onDisplayStyleChange}
isLeftSidebarCollapsed={isLeftSidebarCollapsed} isLeftSidebarCollapsed={isLeftSidebarCollapsed}
onLeftSidebarToggle={onLeftSidebarToggle} onLeftSidebarToggle={onLeftSidebarToggle}
isRightSidebarCollapsed={isRightSidebarCollapsed} isRightSidebarCollapsed={isRightSidebarCollapsed}
@@ -1,4 +1,5 @@
import React from 'react' import React from 'react'
import { cn } from '@/ui/lib/utils'
interface ProgressCircleProps { interface ProgressCircleProps {
progress: number progress: number
@@ -8,15 +9,15 @@ interface ProgressCircleProps {
export const ProgressCircle: React.FC<ProgressCircleProps> = ({ progress, className }) => { export const ProgressCircle: React.FC<ProgressCircleProps> = ({ progress, className }) => {
const radius = 20 const radius = 20
const circumference = 2 * Math.PI * radius const circumference = 2 * Math.PI * radius
const offset = circumference - (progress / 100) * circumference const offset = circumference - (Math.min(100, Math.max(0, progress)) / 100) * circumference
return ( return (
<svg width="50" height="50" viewBox="0 0 50 50" className={className}> <svg viewBox="0 0 50 50" className={cn('w-12 h-12', className)}>
<circle <circle
cx="25" cx="25"
cy="25" cy="25"
r={radius} r={radius}
className="stroke-current text-gray-200" className="stroke-muted"
strokeWidth="4" strokeWidth="4"
fill="transparent" fill="transparent"
/> />
@@ -24,12 +25,11 @@ export const ProgressCircle: React.FC<ProgressCircleProps> = ({ progress, classN
cx="25" cx="25"
cy="25" cy="25"
r={radius} r={radius}
className="stroke-current text-blue-600" className="stroke-primary transition-all duration-300 ease-out"
strokeWidth="4" strokeWidth="4"
fill="transparent" fill="transparent"
strokeDasharray={circumference} strokeDasharray={circumference}
strokeDashoffset={offset} strokeDashoffset={offset}
style={{ transition: 'stroke-dashoffset 0.3s' }}
transform="rotate(-90 25 25)" transform="rotate(-90 25 25)"
/> />
<text <text
@@ -37,7 +37,7 @@ export const ProgressCircle: React.FC<ProgressCircleProps> = ({ progress, classN
y="50%" y="50%"
textAnchor="middle" textAnchor="middle"
dy=".3em" dy=".3em"
className="text-xs font-semibold text-gray-700" className="fill-foreground text-[10px] font-bold"
> >
{`${Math.round(progress)}%`} {`${Math.round(progress)}%`}
</text> </text>
+49 -6
View File
@@ -4,7 +4,7 @@ import { useTeamId } from '@/ui/hooks/use-team-id'
import { useInfiniteQuery } from '@tanstack/react-query' import { useInfiniteQuery } from '@tanstack/react-query'
import { useUploadStore } from '@/ui/stores/upload' import { useUploadStore } from '@/ui/stores/upload'
import { Loader2, CheckCircle2, Clock, UploadCloud } from 'lucide-react' import { Loader2, CheckCircle2, Clock, UploadCloud } from 'lucide-react'
import { useEffect } from 'react' import { useEffect, useMemo } from 'react'
import { useInView } from 'react-intersection-observer' import { useInView } from 'react-intersection-observer'
import { format, parseISO, isToday, isYesterday } from 'date-fns' import { format, parseISO, isToday, isYesterday } from 'date-fns'
import { Progress } from '@/ui/components/ui/progress' import { Progress } from '@/ui/components/ui/progress'
@@ -24,9 +24,28 @@ function formatDayHeader(dateString: string): string {
return format(date, 'MMMM d, yyyy') return format(date, 'MMMM d, yyyy')
} }
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}
function UploadTaskItem({ task }: { task: TaskInfo }) { function UploadTaskItem({ task }: { task: TaskInfo }) {
const isCompleted = task.uploaded === task.total const clientProgress = useUploadStore((state) => state.tasks[task.id])
const percent = task.total > 0 ? (task.uploaded / task.total) * 100 : 0
const isCompleted = clientProgress
? clientProgress.loaded === clientProgress.total && task.uploaded === task.total
: task.uploaded === task.total
const percent = clientProgress
? clientProgress.total > 0
? (clientProgress.loaded / clientProgress.total) * 100
: 0
: task.total > 0
? (task.uploaded / task.total) * 100
: 0
let formattedTime: string let formattedTime: string
try { try {
@@ -72,7 +91,9 @@ function UploadTaskItem({ task }: { task: TaskInfo }) {
<div className="space-y-1.5 mt-auto"> <div className="space-y-1.5 mt-auto">
<div className="flex items-center justify-between text-xs font-semibold"> <div className="flex items-center justify-between text-xs font-semibold">
<span className="text-muted-foreground/80"> <span className="text-muted-foreground/80">
{task.uploaded} / {task.total} {task.total === 1 ? 'file' : 'files'} {clientProgress
? `${formatBytes(clientProgress.loaded)} / ${formatBytes(clientProgress.total)} (${task.uploaded} / ${task.total} ${task.total === 1 ? 'file' : 'files'})`
: `${task.uploaded} / ${task.total} ${task.total === 1 ? 'file' : 'files'}`}
</span> </span>
{!isCompleted && ( {!isCompleted && (
<span className="text-sidebar-primary font-mono font-bold">{Math.round(percent)}%</span> <span className="text-sidebar-primary font-mono font-bold">{Math.round(percent)}%</span>
@@ -92,6 +113,7 @@ interface TaskGroup {
export function UploadTasks() { export function UploadTasks() {
const teamId = useTeamId() const teamId = useTeamId()
const uploading = useUploadStore((state) => state.uploading) const uploading = useUploadStore((state) => state.uploading)
const clientActiveTasks = useUploadStore((state) => state.tasks)
const { const {
data: tasksData, data: tasksData,
fetchNextPage, fetchNextPage,
@@ -126,6 +148,27 @@ export function UploadTasks() {
const tasks = tasksData?.pages.flatMap((page) => page.data ?? []) ?? [] const tasks = tasksData?.pages.flatMap((page) => page.data ?? []) ?? []
const combinedTasks = useMemo(() => {
const serverTaskIds = new Set(tasks.map((t) => t.id))
const clientOnlyTasks: TaskInfo[] = Object.values(clientActiveTasks)
.filter((ct) => !serverTaskIds.has(ct.taskId))
.map((ct) => {
const completedCount = Object.values(ct.files).filter(
(f) => f.status === 'completed' || f.status === 'failed',
).length
return {
id: ct.taskId,
name: ct.name,
total: Object.keys(ct.files).length,
uploaded: completedCount,
createdAt: new Date().toISOString(),
}
})
return [...clientOnlyTasks, ...tasks].sort((a, b) => b.id.localeCompare(a.id))
}, [tasks, clientActiveTasks])
if (isLoading) { if (isLoading) {
return ( return (
<div className="flex items-center justify-center p-8"> <div className="flex items-center justify-center p-8">
@@ -134,7 +177,7 @@ export function UploadTasks() {
) )
} }
if (tasks.length === 0) { if (combinedTasks.length === 0) {
return ( return (
<div className="flex flex-col items-center justify-center p-8 text-center border border-dashed border-border rounded-xl bg-muted/10 my-4"> <div className="flex flex-col items-center justify-center p-8 text-center border border-dashed border-border rounded-xl bg-muted/10 my-4">
<UploadCloud className="h-8 w-8 text-muted-foreground/50 mb-3" /> <UploadCloud className="h-8 w-8 text-muted-foreground/50 mb-3" />
@@ -148,7 +191,7 @@ export function UploadTasks() {
// Group tasks by day (maintaining desc ordering) // Group tasks by day (maintaining desc ordering)
const taskGroups: TaskGroup[] = [] const taskGroups: TaskGroup[] = []
tasks.forEach((task) => { combinedTasks.forEach((task) => {
const day = formatDayHeader(task.createdAt) const day = formatDayHeader(task.createdAt)
let group = taskGroups.find((g) => g.day === day) let group = taskGroups.find((g) => g.day === day)
if (!group) { if (!group) {
@@ -299,7 +299,7 @@ export function useFileSystemDnd({
queryKey: ['search', teamId, assetId], queryKey: ['search', teamId, assetId],
}) })
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ['folders', teamId], queryKey: ['folders'],
}) })
// Clear selection after move // Clear selection after move
onClearSelection() onClearSelection()
@@ -53,6 +53,7 @@ interface VideoPlayerProps {
onPause?: () => void onPause?: () => void
onTimeUpdate?: (time: number) => void onTimeUpdate?: (time: number) => void
annotations?: Annotation[] annotations?: Annotation[]
startTime?: number
children?: React.ReactNode children?: React.ReactNode
} }
@@ -311,6 +312,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
onPause, onPause,
onTimeUpdate, onTimeUpdate,
annotations, annotations,
startTime,
children, children,
}) => { }) => {
const localPlayerRef = useRef<Player | null>(null) const localPlayerRef = useRef<Player | null>(null)
@@ -550,6 +552,13 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
// Set initial state // Set initial state
player.volume(state.volume) player.volume(state.volume)
// Seek to startTime if provided
if (startTime && startTime > 0) {
player.ready(() => {
player.currentTime(startTime)
})
}
// 4. Cleanup // 4. Cleanup
return () => { return () => {
if (player && !player.isDisposed()) { if (player && !player.isDisposed()) {
@@ -559,6 +568,18 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
} }
}, [data]) }, [data])
// Handle changes to startTime (e.g., clicking different chunks in search results)
useEffect(() => {
const player = playerRef.current
if (player && startTime !== undefined && startTime !== null && startTime > 0) {
// Only seek if the difference is significant (e.g., > 1s) to avoid jumping due to small precision differences
const current = player.currentTime() || 0
if (Math.abs(current - startTime) > 1) {
player.currentTime(startTime)
}
}
}, [startTime, playerRef])
// Smooth progress updates using requestAnimationFrame when playing // Smooth progress updates using requestAnimationFrame when playing
useEffect(() => { useEffect(() => {
let animationFrameId: number let animationFrameId: number
+111
View File
@@ -3,3 +3,114 @@ export function arrayMove<T>(array: T[], from: number, to: number): T[] {
newArray.splice(to, 0, newArray.splice(from, 1)[0]) newArray.splice(to, 0, newArray.splice(from, 1)[0])
return newArray return newArray
} }
interface SafeFileSystemEntry {
name: string
isFile: boolean
isDirectory: boolean
}
interface SafeFileSystemFileEntry extends SafeFileSystemEntry {
file(successCallback: (file: File) => void, errorCallback?: (err: unknown) => void): void
}
interface SafeFileSystemDirectoryEntry extends SafeFileSystemEntry {
createReader(): SafeFileSystemDirectoryReader
}
interface SafeFileSystemDirectoryReader {
readEntries(
successCallback: (entries: SafeFileSystemEntry[]) => void,
errorCallback?: (err: unknown) => void,
): void
}
/**
* Recursively retrieves all files from a DataTransfer object, traversing directories.
* Preserves the directory structure using the non-standard `webkitRelativePath` property on File objects.
*/
export async function getAllFilesFromEntries(dataTransfer: DataTransfer): Promise<File[]> {
const files: File[] = []
interface QueueItem {
entry: SafeFileSystemEntry
path: string
}
const queue: QueueItem[] = []
const items = dataTransfer.items
if (items) {
for (let i = 0; i < items.length; i++) {
const item = items[i]
if (item.kind === 'file') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const entry = (item as any).webkitGetAsEntry?.() as SafeFileSystemEntry | null
if (entry) {
queue.push({ entry, path: '' })
}
}
}
} else {
// Fallback if dataTransfer.items is not supported (only dataTransfer.files is available)
return Array.from(dataTransfer.files)
}
const readEntries = (
dirReader: SafeFileSystemDirectoryReader,
): Promise<SafeFileSystemEntry[]> => {
return new Promise((resolve) => {
dirReader.readEntries(
(entries) => resolve(entries),
() => resolve([]),
)
})
}
const getFile = (fileEntry: SafeFileSystemFileEntry): Promise<File> => {
return new Promise((resolve, reject) => {
fileEntry.file(
(file) => resolve(file),
(err) => reject(err),
)
})
}
while (queue.length > 0) {
const next = queue.shift()
if (!next) continue
const { entry, path } = next
if (entry.isFile) {
try {
const file = await getFile(entry as SafeFileSystemFileEntry)
const relativePath = path ? `${path}/${file.name}` : file.name
// Define webkitRelativePath dynamically so processAndUploadFiles can read the structure
Object.defineProperty(file, 'webkitRelativePath', {
value: relativePath,
writable: false,
configurable: true,
})
files.push(file)
} catch (e) {
console.error('Error reading file entry:', e)
}
} else if (entry.isDirectory) {
const dirReader = (entry as SafeFileSystemDirectoryEntry).createReader()
let entries: SafeFileSystemEntry[] = []
let readBatch = await readEntries(dirReader)
while (readBatch.length > 0) {
entries = entries.concat(readBatch)
readBatch = await readEntries(dirReader)
}
const newPath = path ? `${path}/${entry.name}` : entry.name
for (const childEntry of entries) {
queue.push({ entry: childEntry, path: newPath })
}
}
}
return files
}
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/webui", "name": "@shumai/webui",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./index.html", "main": "./index.html",
+17 -6
View File
@@ -1,18 +1,18 @@
import { client } from '@/ui/api/client' import { client } from '@/ui/api/client'
import { useQuery } from '@tanstack/react-query' import { AuthLayout } from '@/ui/components/auth-layout'
import { Button } from '@/ui/components/ui/button' import { Button } from '@/ui/components/ui/button'
import { ShumaiLogo } from '@/ui/components/ui/icons'
import { Input } from '@/ui/components/ui/input' import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label' import { Label } from '@/ui/components/ui/label'
import { signIn } from '@/ui/lib/auth-client'
import { useAuthStore } from '@/ui/stores/auth' import { useAuthStore } from '@/ui/stores/auth'
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from '@hookform/resolvers/zod'
import { useQuery } from '@tanstack/react-query'
import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router' import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router'
import { ArrowRight, Loader2, Lock, LogIn, Mail } from 'lucide-react'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form' import { useForm } from 'react-hook-form'
import { z } from 'zod' import { z } from 'zod'
import { signIn } from '@/ui/lib/auth-client'
import { Loader2, Mail, Lock, ArrowRight, LogIn } from 'lucide-react'
import { ShumaiLogo } from '@/ui/components/ui/icons'
import { AuthLayout } from '@/ui/components/auth-layout'
const loginSchema = z.object({ const loginSchema = z.object({
email: z.string().email('Invalid email address'), email: z.string().email('Invalid email address'),
@@ -37,11 +37,13 @@ function LoginPage() {
}) })
useEffect(() => { useEffect(() => {
if (signupInfo?.userCount === 0) { if (signupInfo && !signupInfo.initialized) {
navigate({ to: '/signup', search: { inviteCode: '' } }) navigate({ to: '/signup', search: { inviteCode: '' } })
} }
}, [signupInfo, navigate]) }, [signupInfo, navigate])
const isDemoEnv = signupInfo?.demoMode === true
const form = useForm<LoginSchema>({ const form = useForm<LoginSchema>({
resolver: zodResolver(loginSchema), resolver: zodResolver(loginSchema),
}) })
@@ -88,6 +90,15 @@ function LoginPage() {
</p> </p>
</div> </div>
{isDemoEnv && (
<div className="mb-6 p-4 bg-blue-500/10 border border-blue-500/20 text-blue-700 dark:text-blue-400 rounded-xl text-sm leading-relaxed">
<p>
<strong>Demo Access:</strong> Use <strong>"foo@bar.com"</strong> as the email and{' '}
<strong>"foo"</strong> as the password to login.
</p>
</div>
)}
{error && ( {error && (
<div className="mb-6 p-3 bg-red-500/10 border border-red-500/20 text-red-600 dark:text-red-400 rounded-xl text-sm text-center font-medium"> <div className="mb-6 p-3 bg-red-500/10 border border-red-500/20 text-red-600 dark:text-red-400 rounded-xl text-sm text-center font-medium">
{error} {error}
@@ -21,7 +21,8 @@ import type Player from 'video.js/dist/types/player'
function FileViewPage() { function FileViewPage() {
const { projectId, fileId } = Route.useParams() const { projectId, fileId } = Route.useParams()
const search = Route.useSearch() const search = Route.useSearch()
const versionAssetId = (search as { version?: string }).version const versionAssetId = search.version
const startTime = search.start
const activeFileId = versionAssetId || fileId const activeFileId = versionAssetId || fileId
const videoRef = useRef<Player | null>(null) const videoRef = useRef<Player | null>(null)
@@ -328,6 +329,7 @@ function FileViewPage() {
onPlay={handlePlay} onPlay={handlePlay}
onTimeUpdate={setCurrentTime} onTimeUpdate={setCurrentTime}
annotations={annotations} annotations={annotations}
startTime={startTime}
> >
{carouselState.show && ( {carouselState.show && (
<FileViewerLeftSidebar <FileViewerLeftSidebar
@@ -373,6 +375,7 @@ export const Route = createFileRoute('/projects/$projectId/files/$fileId')({
validateSearch: (search: Record<string, unknown>) => { validateSearch: (search: Record<string, unknown>) => {
return { return {
version: (search.version as string) || undefined, version: (search.version as string) || undefined,
} start: search.start ? Number(search.start) : undefined,
} as { version?: string; start?: number }
}, },
}) })
@@ -65,8 +65,8 @@ function SharesPage() {
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240) const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
const { const {
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed, shareConfigLeftSidebarCollapsed: isLeftSidebarCollapsed,
setFileListLeftSidebarCollapsed: setIsLeftSidebarCollapsed, setShareConfigLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
} = useUiStore() } = useUiStore()
const { const {
@@ -5,6 +5,7 @@ import { createFileRoute } from '@tanstack/react-router'
function PublicShareFilePage() { function PublicShareFilePage() {
const { shareId, fileId } = Route.useParams() const { shareId, fileId } = Route.useParams()
const { start } = Route.useSearch()
const { data: shareInfo } = useQuery({ const { data: shareInfo } = useQuery({
queryKey: ['share-info', shareId], queryKey: ['share-info', shareId],
@@ -27,10 +28,16 @@ function PublicShareFilePage() {
isDisabled: shareInfo.isDisabled ?? false, isDisabled: shareInfo.isDisabled ?? false,
}} }}
initialFileId={fileId} initialFileId={fileId}
startTime={start}
/> />
) )
} }
export const Route = createFileRoute('/share/$shareId/files/$fileId')({ export const Route = createFileRoute('/share/$shareId/files/$fileId')({
component: PublicShareFilePage, component: PublicShareFilePage,
validateSearch: (search: Record<string, unknown>) => {
return {
start: search.start ? Number(search.start) : undefined,
} as { start?: number }
},
}) })
+1 -1
View File
@@ -96,7 +96,7 @@ function SignupPage() {
) )
} }
const isFirstUser = signupInfo?.userCount === 0 const isFirstUser = signupInfo?.initialized === false
const isPublicSignupDisabled = !isFirstUser && !inviteCode const isPublicSignupDisabled = !isFirstUser && !inviteCode
if (isPublicSignupDisabled) { if (isPublicSignupDisabled) {
+2
View File
@@ -23,6 +23,8 @@ export interface TopNavProjectState {
isPublic?: boolean isPublic?: boolean
shareId?: string shareId?: string
onFolderClick?: (folderId: string) => void onFolderClick?: (folderId: string) => void
isRightSidebarCollapsed?: boolean
onRightSidebarToggle?: () => void
} }
interface TopNavStore { interface TopNavStore {
+15 -1
View File
@@ -14,6 +14,12 @@ interface UiState {
fileListRightSidebarCollapsed: boolean fileListRightSidebarCollapsed: boolean
setFileListRightSidebarCollapsed: (collapsed: boolean) => void setFileListRightSidebarCollapsed: (collapsed: boolean) => void
shareConfigLeftSidebarCollapsed: boolean
setShareConfigLeftSidebarCollapsed: (collapsed: boolean) => void
shareConfigRightSidebarCollapsed: boolean
setShareConfigRightSidebarCollapsed: (collapsed: boolean) => void
viewModes: { [projectId: string]: 'card' | 'list' } viewModes: { [projectId: string]: 'card' | 'list' }
setViewMode: (projectId: string, mode: 'card' | 'list') => void setViewMode: (projectId: string, mode: 'card' | 'list') => void
} }
@@ -33,10 +39,18 @@ export const useUiStore = create<UiState>()(
setFileListLeftSidebarCollapsed: (collapsed) => setFileListLeftSidebarCollapsed: (collapsed) =>
set({ fileListLeftSidebarCollapsed: collapsed }), set({ fileListLeftSidebarCollapsed: collapsed }),
fileListRightSidebarCollapsed: false, fileListRightSidebarCollapsed: true,
setFileListRightSidebarCollapsed: (collapsed) => setFileListRightSidebarCollapsed: (collapsed) =>
set({ fileListRightSidebarCollapsed: collapsed }), set({ fileListRightSidebarCollapsed: collapsed }),
shareConfigLeftSidebarCollapsed: false,
setShareConfigLeftSidebarCollapsed: (collapsed) =>
set({ shareConfigLeftSidebarCollapsed: collapsed }),
shareConfigRightSidebarCollapsed: false,
setShareConfigRightSidebarCollapsed: (collapsed) =>
set({ shareConfigRightSidebarCollapsed: collapsed }),
viewModes: {}, viewModes: {},
setViewMode: (projectId, mode) => setViewMode: (projectId, mode) =>
set((state) => ({ set((state) => ({
+153
View File
@@ -1,13 +1,166 @@
import { create } from 'zustand' import { create } from 'zustand'
export interface FileUploadState {
fileId: string
name: string
loaded: number
total: number
status: 'uploading' | 'completed' | 'failed'
}
export interface TaskUploadState {
taskId: string
name: string
loaded: number
total: number
files: Record<string, FileUploadState>
}
type UploadStore = { type UploadStore = {
uploading: number uploading: number
tasks: Record<string, TaskUploadState>
fileProgress: Record<string, FileUploadState>
increment: () => void increment: () => void
decrement: () => void decrement: () => void
startTask: (
taskId: string,
taskName: string,
files: Array<{ fileId: string; name: string; size: number }>,
) => void
updateFileProgress: (taskId: string, fileId: string, loaded: number) => void
completeFile: (taskId: string, fileId: string) => void
failFile: (taskId: string, fileId: string) => void
} }
export const useUploadStore = create<UploadStore>((set) => ({ export const useUploadStore = create<UploadStore>((set) => ({
uploading: 0, uploading: 0,
tasks: {},
fileProgress: {},
increment: () => set((state) => ({ uploading: state.uploading + 1 })), increment: () => set((state) => ({ uploading: state.uploading + 1 })),
decrement: () => set((state) => ({ uploading: state.uploading - 1 })), decrement: () => set((state) => ({ uploading: state.uploading - 1 })),
startTask: (taskId, taskName, files) =>
set((state) => {
const taskFiles: Record<string, FileUploadState> = {}
let totalBytes = 0
files.forEach((f) => {
taskFiles[f.fileId] = {
fileId: f.fileId,
name: f.name,
loaded: 0,
total: f.size,
status: 'uploading',
}
totalBytes += f.size
})
const newTasks = {
...state.tasks,
[taskId]: {
taskId,
name: taskName,
loaded: 0,
total: totalBytes,
files: taskFiles,
},
}
const newFileProgress = { ...state.fileProgress }
files.forEach((f) => {
newFileProgress[f.fileId] = taskFiles[f.fileId]
})
return {
tasks: newTasks,
fileProgress: newFileProgress,
}
}),
updateFileProgress: (taskId, fileId, loaded) =>
set((state) => {
const task = state.tasks[taskId]
if (!task) return {}
const file = task.files[fileId]
if (!file) return {}
const updatedFile = { ...file, loaded }
const updatedFiles = { ...task.files, [fileId]: updatedFile }
const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0)
return {
tasks: {
...state.tasks,
[taskId]: {
...task,
loaded: loadedBytes,
files: updatedFiles,
},
},
fileProgress: {
...state.fileProgress,
[fileId]: updatedFile,
},
}
}),
completeFile: (taskId, fileId) =>
set((state) => {
const task = state.tasks[taskId]
if (!task) return {}
const file = task.files[fileId]
if (!file) return {}
const updatedFile: FileUploadState = { ...file, status: 'completed', loaded: file.total }
const updatedFiles = { ...task.files, [fileId]: updatedFile }
const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0)
return {
tasks: {
...state.tasks,
[taskId]: {
...task,
loaded: loadedBytes,
files: updatedFiles,
},
},
fileProgress: {
...state.fileProgress,
[fileId]: updatedFile,
},
}
}),
failFile: (taskId, fileId) =>
set((state) => {
const task = state.tasks[taskId]
if (!task) return {}
const file = task.files[fileId]
if (!file) return {}
const updatedFile: FileUploadState = { ...file, status: 'failed' }
const updatedFiles = { ...task.files, [fileId]: updatedFile }
const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0)
return {
tasks: {
...state.tasks,
[taskId]: {
...task,
loaded: loadedBytes,
files: updatedFiles,
},
},
fileProgress: {
...state.fileProgress,
[fileId]: updatedFile,
},
}
}),
})) }))
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@shumai/workflow-core", "name": "@shumai/workflow-core",
"version": "0.0.7", "version": "0.0.8",
"private": true, "private": true,
"type": "module", "type": "module",
"main": "./src/index.ts", "main": "./src/index.ts",