72 Commits
0.0.6 ... 0.0.8

Author SHA1 Message Date
keven
52af187fe9 feat(config): add example configuration file with settings for sharing, uploading, redis, and site information 2025-10-19 18:58:45 +08:00
keven
9fff65d0d7 Revert "feat(front): add TextInlineAIDrawer and BubbleMenuView components for enhanced AI interaction and text formatting options"
This reverts commit d294027463.
2025-10-19 18:45:01 +08:00
keven
da58c53909 feat(front): add AboutVersionView component and enhance AboutBaseInfo with object-fit styling 2025-10-19 18:38:00 +08:00
keven
07fc182ccb feat(front): enhance About page components to support shares and downloads statistics, improve layout, and add loading state 2025-10-19 18:20:38 +08:00
keven
028d0c10fe refactor(backend): update statistics handling in GetStat function to include shares and downloads, and rename related data structures 2025-10-19 16:47:51 +08:00
keven
b4f577e758 feat(backend): implement statistics tracking for file uploads, shares, and downloads 2025-10-19 16:34:17 +08:00
keven
84c104be90 feat(backend, worker): add config watching and simplify error handling in InitEnv function 2025-10-19 15:23:42 +08:00
keven
a4b3dad85e feat(front): enhance localization support in AboutBaseInfo, useSeo, and default layout for improved SEO and user experience 2025-10-19 15:21:39 +08:00
keven
6238897c18 feat(front): add AboutBaseInfo and AboutChartView components for enhanced About page functionality and data visualization 2025-10-19 15:05:29 +08:00
keven
c931d10485 fix(backend): skip processing of queue items with zero processed and failed counts in GetStat function 2025-10-19 14:43:12 +08:00
keven
dd05510d27 feat(backend): implement About and Config endpoints, enhance GetStat with queue data and file size metrics 2025-10-19 14:39:46 +08:00
keven
5de6ed9eea Merge branch 'dev' of https://gitea.fudaoyuan.icu/keven/015 into dev 2025-10-19 14:07:17 +08:00
keven1024
7166ec5cb3 Merge branch 'dev' of https://gitea.fudaoyuan.icu/keven/015 into dev 2025-10-19 14:05:17 +08:00
keven1024
8676b12a66 feat(front): implement Accordion component and its subcomponents for enhanced UI interactivity and organization 2025-10-19 14:05:13 +08:00
keven
d8c9491a99 feat(front): enhance app configuration fetching and add localization support for "powered by" text 2025-10-19 13:33:55 +08:00
keven
e6cc1b0229 feat(backend): add About and Config controllers for dynamic environment variable retrieval 2025-10-19 10:19:28 +08:00
keven
50c0a14cc6 feat(front): implement dynamic API base URL retrieval and enhance SEO metadata handling 2025-10-19 00:26:12 +08:00
keven
1ed154913d refactor(backend,worker): update environment variable key for upload path to enhance consistency across modules 2025-10-19 00:10:09 +08:00
keven
12efc10e0e refactor(backend): standardize environment variable names for download and password handling, enhancing consistency and clarity 2025-10-19 00:05:56 +08:00
keven
b80cb0c2d8 refactor(backend,worker): update environment variable keys for consistency and improve configuration handling across backend and worker modules 2025-10-18 23:54:11 +08:00
keven
d294027463 feat(front): add TextInlineAIDrawer and BubbleMenuView components for enhanced AI interaction and text formatting options 2025-10-18 13:36:04 +08:00
keven1024
a66c5a26b0 Merge branch 'main' of https://gitea.fudaoyuan.icu/keven/015 2025-10-18 13:06:17 +08:00
keven1024
27fcfd73d9 feat(front): add Menubar component and its subcomponents for improved UI navigation and organization 2025-10-18 13:06:11 +08:00
keven
f525f48a8a Merge branch 'main' of https://gitea.fudaoyuan.icu/keven/015 2025-10-18 12:57:33 +08:00
keven1024
9961609e64 feat(front): implement DropdownMenu component and its subcomponents for enhanced UI interactivity and organization 2025-10-18 12:15:41 +08:00
keven
ff58262725 feat(vscode): add i18n-ally configuration for localization support in Vue projects 2025-10-18 11:00:04 +08:00
keven
80a01a2849 feat(front): add internationalization support to TextShareResult component, localizing titles and messages for enhanced user experience 2025-10-18 10:54:47 +08:00
keven
8924de58c0 feat(front): integrate GlobalDayjs component for dynamic date localization and formatting 2025-10-18 10:46:07 +08:00
keven
41b0076464 feat(front): add dayjs integration for date formatting in dev page, showcasing language pack rendering 2025-10-18 10:45:21 +08:00
keven
fa17009695 feat(front): enhance FileShareResult and FileUploadField components with internationalization support, adding localized text for file sharing success and related UI elements 2025-10-18 10:43:57 +08:00
keven
8fad0a4163 feat(front): implement internationalization for share options in FileShareHandle and TextShareHandle components, update layout in GlobalDrawer, and enhance FileUploadField with localized text 2025-10-18 09:41:45 +08:00
keven
836a3c866a feat(front): enhance PickupShareBtn and PickupShareDrawer components with internationalization support and improved user feedback for pickup code submission 2025-10-18 09:22:14 +08:00
keven
045031dd3c chore(front): update dependency versions for Tiptap and Vue Query to enhance functionality and compatibility 2025-10-18 00:13:17 +08:00
keven
3e8c782315 refactor(front): update MarkdownInputField import path and enhance TextUploadInputTextView component structure for improved readability 2025-10-17 23:57:51 +08:00
keven1024
77667024fd Merge branch 'main' of https://gitea.fudaoyuan.icu/keven/015 2025-10-17 23:01:26 +08:00
keven1024
9902f46c7a feat(front): add Tooltip component and related subcomponents for enhanced UI functionality 2025-10-17 23:01:21 +08:00
keven
164d07b8e0 style(front): enhance Markdown and Tiptap components with improved styling for blockquotes and selection background 2025-10-17 09:11:23 +08:00
keven1024
b59aec2d97 chore(front): update dependency versions for improved compatibility and stability, including upgrades to Tiptap, Tailwind CSS, Vue, and Pixi.js 2025-10-16 15:47:32 +08:00
keven1024
0df8ee0a8d Revert "refactor(front): replace MarkdownInputField with RichInputField for improved JSON handling in text uploads, update Tiptap component to support JSONContent, and increment dependency versions for better compatibility"
This reverts commit e959a0bc3e.
2025-10-16 15:43:55 +08:00
keven1024
083005dac3 fix(front): handle potential undefined values in file sharing logic to prevent runtime errors 2025-10-13 22:03:03 +08:00
keven1024
e959a0bc3e refactor(front): replace MarkdownInputField with RichInputField for improved JSON handling in text uploads, update Tiptap component to support JSONContent, and increment dependency versions for better compatibility 2025-10-13 21:27:28 +08:00
keven1024
6bd008f119 refactor(front): improve file upload progress handling by adding async wait to prevent UI freezing during upload tasks 2025-09-29 17:59:09 +08:00
keven
d306581e34 fix(front): 更新依赖项版本,将nuxt从3.18.0升级至4.1.2,以提高项目的稳定性和兼容性,同时更新pnpm-lock.yaml中的相关依赖项版本。 2025-09-23 09:28:19 +08:00
keven
f34ea51725 更新依赖项版本,包括@nuxt/image、@nuxtjs/i18n、@pinia/nuxt、@tailwindcss/postcss、@tailwindcss/vite、@tanstack/vue-query等,以提高项目的稳定性和兼容性。同时,更新了其他相关库的版本,确保与最新的Vue和TypeScript版本兼容。 2025-09-23 09:19:06 +08:00
keven
218387151f 更新后端和工作器的Dockerfile,升级Go版本至1.24.3,并更新相关依赖项的版本以提高稳定性和安全性 2025-09-23 00:50:25 +08:00
keven
427d958a41 feat(docs): 添加中文README文件,更新英文README中的图片路径,优化项目结构和环境配置说明 2025-09-23 00:28:54 +08:00
keven
8b0d90cdc3 refactor(front): 优化文件上传进度视图,改进文件ID和任务队列的处理逻辑,确保上传任务的有效性 2025-09-23 00:02:11 +08:00
keven1024
0a9d414751 refactor(backend): optimize file upload chunk size calculation and improve MD5 hash verification process 2025-09-22 14:15:10 +08:00
keven1024
f1c2e1a3d7 refactor(front): replace filesize library with custom getFileSize function for consistent file size formatting across components 2025-09-22 14:14:36 +08:00
keven1024
cfe166e8c9 refactor(front): update file handling components to use typed props for better type safety and maintainability 2025-09-22 10:41:55 +08:00
keven
29300a9448 feat(front): 增强文件上传组件,支持上传速度显示和动态进度更新,优化文件分块处理逻辑 2025-09-21 23:45:02 +08:00
keven
2a24f713cb fix(front): 调整 GlobalDrawer 组件的样式,增加内边距以改善布局 2025-09-21 16:56:01 +08:00
keven
427f1f6456 feat(front): 重构文件上传进度视图,支持多文件上传和动态状态更新,优化上传任务管理 2025-09-19 09:18:53 +08:00
keven
c8f36e6f8e feat(front): 添加文件上传进度视图和热图视图组件,支持动态渲染上传状态 2025-09-14 11:48:46 +08:00
keven
03ccd13f8f chore(front): 更新依赖项并添加异步重试和超时功能 2025-09-14 10:38:59 +08:00
keven
b2c0e85844 fix(front): 使用 useDevicePixelRatio 优化 Pixi 组件的分辨率计算 2025-09-14 10:36:43 +08:00
keven1024
c1ec2aee5b chore: update .env.example for Redis configuration and add docker-compose file for app, worker, and Redis services 2025-08-30 18:26:35 +08:00
keven1024
3d173d0321 refactor(front): update FileShareDrawer and FileUploadField components to handle multiple files and improve file type checks 2025-08-14 16:50:43 +08:00
keven1024
4d0a6f0a49 test(backend): add unit tests for HTTP result handlers and password hashing functionality 2025-08-14 14:40:03 +08:00
keven1024
e41d7a6305 fix(front): pass width and height props to slot in Pixi component for better flexibility 2025-08-14 11:53:34 +08:00
keven1024
60af6d2023 chore(front): update logo image in public assets 2025-08-14 11:53:05 +08:00
keven1024
dc16661fff chore: add docker-compose configuration for app, worker, and redis services 2025-08-14 11:52:50 +08:00
keven1024
f36221de05 feat(front): add development page with form components and button interactions 2025-08-09 00:20:48 +08:00
keven1024
e556b0f39d chore(front): update nuxt to 3.18.0 2025-08-08 17:14:56 +08:00
keven1024
13cbf5e5ed fix(front): set backgroundAlpha to 0 in Pixi component for improved rendering 2025-07-28 18:22:36 +08:00
keven1024
8392b26455 feat(front): add Pixi component integration and update dependencies for improved functionality 2025-07-28 18:17:04 +08:00
keven1024
c64c152124 fix(front): enhance error logging in error.vue and improve Tiptap component styling for better readability 2025-07-28 17:07:35 +08:00
keven1024
ecc4aefd33 chore: update dependencies in package.json and pnpm-lock.yaml to latest versions for improved stability and performance 2025-07-20 00:00:26 +08:00
keven1024
590a071dfb chore: update devDependencies in package.json for husky, lint-staged, and prettier to latest versions 2025-07-19 23:59:38 +08:00
keven
cf2d81bf9a refactor(front): 优化状态管理和组件逻辑,简化GlobalDrawer和Tiptap组件的实现 2025-07-19 22:29:48 +08:00
keven
e62f329d53 fix(front): 更新MarkdownRender组件的样式类以增强可读性 2025-07-19 19:19:33 +08:00
keven1024
421955a844 chore: update .env.example to include PASSWORD_SALT for enhanced password security 2025-07-11 10:41:50 +08:00
141 changed files with 8087 additions and 6797 deletions

View File

@@ -1,8 +1,9 @@
# 你的下载secret每一次下载次数减1的时候都会根据这里的secret生成一个下载jwt token 有效期一小时使用该下载token有效期内可以多线程下载该文件而不会被多次扣除次数
DOWNLOAD_SECRET="your-secret-token"
PASSWORD_SALT="your-passwall-salt" # 设置密码时会把密码加盐
UPLOAD_PATH="/upload" # 上传路径
REDIS_URL="redis://127.0.0.1:6379/0" # redis 地址
REDIS_URL="redis://redis:6379/0" # redis 地址
NODE_ENV="production" # 指定系统环境 production 或者 dev
MAX_LOCALSTORAGE_SIZE="100GB" # 指定实例最大上传容量支持填写人类可读的值比如1TB500GB等

BIN
.github/image/0.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 716 KiB

View File

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 1.0 MiB

View File

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 1.0 MiB

BIN
.github/image/3.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

BIN
.github/image/4.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 750 KiB

BIN
.github/image/5.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 807 KiB

BIN
.github/image/6.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

5
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,5 @@
{
"i18n-ally.localesPaths": ["front/i18n/locales"],
"i18n-ally.enabledFrameworks": ["vue"],
"i18n-ally.keystyle": "nested"
}

View File

@@ -13,7 +13,7 @@ WORKDIR /app
COPY --from=front-deps /app/dist/ .
RUN corepack enable pnpm && pnpm build
FROM golang:1.23.1 AS backend-builder
FROM golang:1.24.3 AS backend-builder
WORKDIR /app
# Download Go modules
COPY backend/go.mod backend/go.sum ./

View File

@@ -1,10 +1,16 @@
<div align="center"><a name="readme-top"></a>
# 015
015 (/ˈzɪərəʊ wʌn faɪv/, "zero-one-five") 是一个支持selfhosted的临时文件分享平台。专注于提供一次性临时的文件和文本上传处理分享服务。项目名称来源于DARLING in the FRANXX的 [](https://darling-in-the-franxx.fandom.com/wiki/Ichigo)
一个基于 Vue 3 + Nuxt 3 + Go 构建的现代文件分享网站,支持文件上传、文本分享、图片压缩、并发处理、秒传功能等,具备完整的分享管理和访问控制体系。
![015 Platform Overview](./image/0.png)
![015 Platform Overview](/.github/image/0.png)
[English](README.md) | 中文
</div>
## 🌟 功能特性
@@ -35,59 +41,69 @@
## 截图
![](./image/1.webp)
选择文件上传页面
![](/.github/image/1.png)
![](./image/2.webp)
输入文本上传页面
![](/.github/image/2.png)
![](./image/3.png)
选择文件上传页面 - 支持多选文件上传
![](/.github/image/3.png)
![](./image/4.png)
文件正在上传页面 - 类似Github的展示上传进度的文件热力图
![](/.github/image/4.png)
文件正在上传页面 - 类似 QbitTorrent 的展示文件上传进度的进度条
![](/.github/image/5.png)
文件上传成功页面
![](/.github/image/6.png)
## 🏗️ 技术架构
### 前端技术栈
- **Vue 3** - 渐进式 JavaScript 框架
- **Nuxt 3** - Vue.js 全栈框架
- **TypeScript** - 完整的类型安全
- **Tailwind CSS** - 原子化 CSS 框架
- **Reka UI** - 现代化组件库
- **Pinia** - 状态管理
- **TanStack Query** - 数据获取和缓存
- **Vue Router** - 路由管理
- **i18next** - 国际化支持
- **Vue 3** - 渐进式 JavaScript 框架
- **Nuxt 3** - Vue.js 全栈框架
- **TypeScript** - 完整的类型安全
- **Tailwind CSS** - 原子化 CSS 框架
- **Reka UI** - 现代化组件库
- **Pinia** - 状态管理
- **TanStack Query** - 数据获取和缓存
- **Vue Router** - 路由管理
- **i18next** - 国际化支持
### 后端技术栈
- **Go 1.23** - 高性能服务器端语言
- **Echo** - 高性能 HTTP 框架
- **Redis** - 缓存和会话存储
- **Asynq** - 异步任务队列
- **JWT** - 身份验证
- **Zap** - 结构化日志
- **Go 1.23** - 高性能服务器端语言
- **Echo** - 高性能 HTTP 框架
- **Redis** - 缓存和会话存储
- **Asynq** - 异步任务队列
- **JWT** - 身份验证
- **Zap** - 结构化日志
### 构建系统
- **Node.js** - 服务器端运行时
- **pnpm** - 快速包管理器
- **Husky** - Git hooks 管理
- **Prettier** - 代码格式化
- **Lint-staged** - 暂存文件检查
- **Node.js** - 服务器端运行时
- **pnpm** - 快速包管理器
- **Husky** - Git hooks 管理
- **Prettier** - 代码格式化
- **Lint-staged** - 暂存文件检查
### 存储架构
- **文件存储** - 本地文件系统存储
- **Redis 缓存** - 分享信息、文件元数据缓存
- **队列系统** - 异步任务处理队列
- **文件存储** - 本地文件系统存储
- **Redis 缓存** - 分享信息、文件元数据缓存
- **队列系统** - 异步任务处理队列
## 🚀 快速开始
### 环境要求
- Node.js 18+
- Go 1.23+
- Redis 6+
- pnpm 9+
- Node.js 18+
- Go 1.23+
- Redis 6+
- pnpm 9+
### 安装依赖
@@ -113,7 +129,7 @@ cp .env.example .env
# 配置必要的环境变量
REDIS_URL=redis://localhost:6379
UPLOAD_PATH=./uploads
UPLOAD_PATH=/.github/uploads
download_secret=your_download_secret
```
@@ -159,9 +175,9 @@ pnpm run dev:worker # Worker 服务
### 代码规范
- 使用 Prettier 进行代码格式化
- 使用 Husky + lint-staged 进行提交前检查
- 遵循 TypeScript 类型安全规范
- 使用 Prettier 进行代码格式化
- 使用 Husky + lint-staged 进行提交前检查
- 遵循 TypeScript 类型安全规范
### 提交规范
@@ -188,22 +204,22 @@ cd worker && go build -o worker .
### 已完成功能 ✅
- 前端计算哈希和秒传
- 并发切片上传 (使用 Web Worker)
- 文件上传/文本上传和分享
- 上传统计页面
- 多语言支持
- 最大上传限制
- 后端队列系统和 Worker 处理文件
- 前端计算哈希和秒传
- 并发切片上传 (使用 Web Worker)
- 文件上传/文本上传和分享
- 上传统计页面
- 多语言支持
- 最大上传限制
- 后端队列系统和 Worker 处理文件
### 计划功能 🚧
- 断点续传 (后端计算已上传部分并返回)
- 图片格式转换和压缩
- 图片 OCR 复制
- 文档转 Markdown
- 文本翻译/总结
- 支持上传多文件
- 断点续传 (后端计算已上传部分并返回)
- 图片格式转换和压缩
- 图片 OCR 复制
- 文档转 Markdown
- 文本翻译/总结
- 支持上传多文件
## 🤝 贡献指南
@@ -215,7 +231,7 @@ cd worker && go build -o worker .
## 🔗 相关链接
- [Vue 3 文档](https://vuejs.org/)
- [Nuxt 3 文档](https://nuxt.com/)
- [Echo 框架文档](https://echo.labstack.com/)
- [Asynq 文档](https://github.com/hibiken/asynq)
- [Vue 3 文档](https://vuejs.org/)
- [Nuxt 3 文档](https://nuxt.com/)
- [Echo 框架文档](https://echo.labstack.com/)
- [Asynq 文档](https://github.com/hibiken/asynq)

149
README.md
View File

@@ -1,10 +1,16 @@
<div align="center"><a name="readme-top"></a>
# 015
015 (/ˈzɪərəʊ wʌn faɪv/, "zero-one-five") is a self-hosted temporary file sharing platform. Focused on providing one-time, temporary file and text upload, processing, and sharing services. The project name originates from [Ichigo](https://darling-in-the-franxx.fandom.com/wiki/Ichigo) from DARLING in the FRANXX.
A modern file sharing website built with Vue 3 + Nuxt 3 + Go, supporting file upload, text sharing, image compression, concurrent processing, instant transfer functionality, and more, featuring a complete sharing management and access control system.
![015 Platform Overview](/docs/image/0.png)
![015 Platform Overview](/.github/image/0.png)
English | [中文](README-zh.md)
</div>
## 🌟 Features
@@ -35,59 +41,69 @@ A modern file sharing website built with Vue 3 + Nuxt 3 + Go, supporting file up
## 📸 Screenshots
![](/docs/image/1.webp)
File selection upload page
![](/.github/image/1.png)
![](/docs/image/2.webp)
Text input upload page
![](/.github/image/2.png)
![](/docs/image/3.png)
File selection upload page - supports multiple file uploads
![](/.github/image/3.png)
![](/docs/image/4.png)
File uploading page - similar to GitHub's file heatmap showing upload progress
![](/.github/image/4.png)
File uploading page - similar to qBittorrent's progress bar showing file upload progress
![](/.github/image/5.png)
File upload success page
![](/.github/image/6.png)
## 🏗️ Technical Architecture
### Frontend Tech Stack
- **Vue 3** - Progressive JavaScript framework
- **Nuxt 3** - Vue.js full-stack framework
- **TypeScript** - Complete type safety
- **Tailwind CSS** - Atomic CSS framework
- **Reka UI** - Modern component library
- **Pinia** - State management
- **TanStack Query** - Data fetching and caching
- **Vue Router** - Routing management
- **i18next** - Internationalization support
- **Vue 3** - Progressive JavaScript framework
- **Nuxt 3** - Vue.js full-stack framework
- **TypeScript** - Complete type safety
- **Tailwind CSS** - Atomic CSS framework
- **Reka UI** - Modern component library
- **Pinia** - State management
- **TanStack Query** - Data fetching and caching
- **Vue Router** - Routing management
- **i18next** - Internationalization support
### Backend Tech Stack
- **Go 1.23** - High-performance server-side language
- **Echo** - High-performance HTTP framework
- **Redis** - Caching and session storage
- **Asynq** - Asynchronous task queue
- **JWT** - Authentication
- **Zap** - Structured logging
- **Go 1.23** - High-performance server-side language
- **Echo** - High-performance HTTP framework
- **Redis** - Caching and session storage
- **Asynq** - Asynchronous task queue
- **JWT** - Authentication
- **Zap** - Structured logging
### Build System
- **Node.js** - Server-side runtime
- **pnpm** - Fast package manager
- **Husky** - Git hooks management
- **Prettier** - Code formatting
- **Lint-staged** - Staged file checking
- **Node.js** - Server-side runtime
- **pnpm** - Fast package manager
- **Husky** - Git hooks management
- **Prettier** - Code formatting
- **Lint-staged** - Staged file checking
### Storage Architecture
- **File Storage** - Local file system storage
- **Redis Cache** - Share information and file metadata caching
- **Queue System** - Asynchronous task processing queue
- **File Storage** - Local file system storage
- **Redis Cache** - Share information and file metadata caching
- **Queue System** - Asynchronous task processing queue
## 🚀 Quick Start
### Requirements
- Node.js 18+
- Go 1.23+
- Redis 6+
- pnpm 9+
- Node.js 18+
- Go 1.23+
- Redis 6+
- pnpm 9+
### Install Dependencies
@@ -113,7 +129,7 @@ cp .env.example .env
# Configure necessary environment variables
REDIS_URL=redis://localhost:6379
UPLOAD_PATH=./uploads
UPLOAD_PATH=/.github/uploads
download_secret=your_download_secret
```
@@ -139,28 +155,29 @@ pnpm run dev:worker # Worker service
│ │ ├── composables/ # Composable functions
│ │ ├── i18n/ # Internationalization files
│ │ └── assets/ # Static assets
── backend/ # Backend service (Go + Echo)
│ │ ├── internal/ # Internal packages
│ │ ├── controllers/ # Controllers
│ │ │ ├── models/ # Data models
│ │ │ ├── services/ # Business logic
│ │ │ └── utils/ # Utility functions
│ │ └── middleware/ # Middleware
── worker/ # Asynchronous task processing (Go + Asynq)
│ │ ├── internal/ # Internal packages
│ │ ├── tasks/ # Task processors
│ │ │ └── utils/ # Utility functions
│ │ └── middleware/ # Middleware
│ └── tmp/ # Temporary files
── middleware/ # Middleware
├── backend/ # Backend service (Go + Echo)
├── internal/ # Internal packages
│ │ ├── controllers/ # Controllers
│ │ ├── models/ # Data models
│ │ ├── services/ # Business logic
│ │ └── utils/ # Utility functions
── middleware/ # Middleware
├── worker/ # Asynchronous task processing (Go + Asynq)
├── internal/ # Internal packages
│ │ ├── tasks/ # Task processors
│ │ └── utils/ # Utility functions
│ └── middleware/ # Middleware
└── tmp/ # Temporary files
```
## 🔧 Development Guide
### Code Standards
- Use Prettier for code formatting
- Use Husky + lint-staged for pre-commit checking
- Follow TypeScript type safety standards
- Use Prettier for code formatting
- Use Husky + lint-staged for pre-commit checking
- Follow TypeScript type safety standards
### Commit Standards
@@ -187,22 +204,22 @@ cd worker && go build -o worker .
### Completed Features ✅
- Frontend hash calculation and instant transfer
- Concurrent chunked upload (using Web Worker)
- File upload/text upload and sharing
- Upload statistics page
- Multi-language support
- Maximum upload limits
- Backend queue system and Worker file processing
- Frontend hash calculation and instant transfer
- Concurrent chunked upload (using Web Worker)
- File upload/text upload and sharing
- Upload statistics page
- Multi-language support
- Maximum upload limits
- Backend queue system and Worker file processing
### Planned Features 🚧
- Resume upload (backend calculates uploaded parts and returns)
- Image format conversion and compression
- Image OCR copy
- Document to Markdown conversion
- Text translation/summarization
- Support for multiple file uploads
- Resume upload (backend calculates uploaded parts and returns)
- Image format conversion and compression
- Image OCR copy
- Document to Markdown conversion
- Text translation/summarization
- Support for multiple file uploads
## 🤝 Contributing
@@ -214,7 +231,7 @@ This project is licensed under AGPLV3.
## 🔗 Related Links
- [Vue 3 Documentation](https://vuejs.org/)
- [Nuxt 3 Documentation](https://nuxt.com/)
- [Echo Framework Documentation](https://echo.labstack.com/)
- [Asynq Documentation](https://github.com/hibiken/asynq)
- [Vue 3 Documentation](https://vuejs.org/)
- [Nuxt 3 Documentation](https://nuxt.com/)
- [Echo Framework Documentation](https://echo.labstack.com/)
- [Asynq Documentation](https://github.com/hibiken/asynq)

View File

@@ -1,6 +1,6 @@
# syntax=docker/dockerfile:1
FROM golang:1.23.1 AS builder
FROM golang:1.24.3 AS builder
# Set destination for COPY
WORKDIR /app

View File

@@ -1,30 +1,34 @@
module backend
go 1.23.1
go 1.24.0
toolchain go1.24.3
require (
dario.cat/mergo v1.0.1
dario.cat/mergo v1.0.2
github.com/dustin/go-humanize v1.0.1
github.com/golang-jwt/jwt/v5 v5.2.2
github.com/golang-jwt/jwt/v5 v5.3.0
github.com/gorilla/sessions v1.4.0
github.com/hibiken/asynq v0.25.1
github.com/labstack/echo-contrib v0.17.3
github.com/labstack/echo/v4 v4.13.3
github.com/labstack/echo-contrib v0.17.4
github.com/labstack/echo/v4 v4.13.4
github.com/matoous/go-nanoid/v2 v2.1.0
github.com/redis/go-redis/v9 v9.7.3
github.com/samber/lo v1.50.0
github.com/spf13/cast v1.7.1
github.com/spf13/viper v1.20.1
github.com/redis/go-redis/v9 v9.14.0
github.com/samber/lo v1.51.0
github.com/spf13/cast v1.10.0
github.com/spf13/viper v1.21.0
github.com/stretchr/testify v1.11.1
go.uber.org/zap v1.27.0
golang.org/x/crypto v0.39.0
golang.org/x/time v0.11.0
golang.org/x/crypto v0.42.0
golang.org/x/time v0.13.0
)
require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/fsnotify/fsnotify v1.8.0 // indirect
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/context v1.1.2 // indirect
@@ -32,19 +36,21 @@ require (
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/sagikazarmark/locafero v0.7.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.12.0 // indirect
github.com/spf13/pflag v1.0.6 // indirect
github.com/sagikazarmark/locafero v0.12.0 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/net v0.37.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.26.0 // indirect
google.golang.org/protobuf v1.36.5 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/net v0.44.0 // indirect
golang.org/x/sys v0.36.0 // indirect
golang.org/x/text v0.29.0 // indirect
google.golang.org/protobuf v1.36.9 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

View File

@@ -1,5 +1,5 @@
dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s=
dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
@@ -14,12 +14,12 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
@@ -38,10 +38,10 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/labstack/echo-contrib v0.17.3 h1:hj+qXksKZG1scSe9ksUXMtv7fZYN+PtQT+bPcYA3/TY=
github.com/labstack/echo-contrib v0.17.3/go.mod h1:TcRBrzW8jcC4JD+5Dc/pvOyAps0rtgzj7oBqoR3nYsc=
github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaafY=
github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g=
github.com/labstack/echo-contrib v0.17.4 h1:g5mfsrJfJTKv+F5uNKCyrjLK7js+ZW6HTjg4FnDxxgk=
github.com/labstack/echo-contrib v0.17.4/go.mod h1:9O7ZPAHUeMGTOAfg80YqQduHzt0CzLak36PZRldYrZ0=
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE=
@@ -50,34 +50,30 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM=
github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA=
github.com/redis/go-redis/v9 v9.14.0 h1:u4tNCjXOyzfgeLN+vAZaW1xUooqWDqVEsZN0U01jfAE=
github.com/redis/go-redis/v9 v9.14.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo=
github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k=
github.com/samber/lo v1.50.0 h1:XrG0xOeHs+4FQ8gJR97zDz5uOFMW7OwFWiFVzqopKgY=
github.com/samber/lo v1.50.0/go.mod h1:RjZyNk6WSnUFRKK6EyOhsRJMqft3G+pg7dCWHQCWvsc=
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs=
github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4=
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4=
github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=
github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI=
github.com/samber/lo v1.51.0 h1:kysRYLbHy/MB7kQZf5DSN50JHmMsNEdeY24VzJFu7wI=
github.com/samber/lo v1.51.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
@@ -90,21 +86,23 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM=
golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U=
golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c=
golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
golang.org/x/time v0.13.0 h1:eUlYslOIt32DgYD6utsuUeHs4d7AsEYLuIAdg7FlYgI=
golang.org/x/time v0.13.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -0,0 +1,44 @@
package controllers
import (
"backend/internal/models"
"backend/internal/utils"
"encoding/json"
"github.com/labstack/echo/v4"
"github.com/samber/lo"
)
func GetAbout(c echo.Context) error {
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("upload.maximum"))
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
fileInfoMap, err := models.GetRedisFileInfoAll()
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
currentFileSize := lo.Reduce(lo.Values(fileInfoMap), func(agg int64, item string, _ int) int64 {
var fileInfo models.RedisFileInfo
err := json.Unmarshal([]byte(item), &fileInfo)
if err != nil {
return agg
}
return agg + fileInfo.FileSize
}, 0)
return utils.HTTPSuccessHandler(c, map[string]any{
"bg_url": utils.GetEnv("about.bg_url"),
"content": utils.GetEnvMapString("about.content"),
"email": utils.GetEnv("about.email"),
"name": utils.GetEnv("about.name"),
"url": utils.GetEnv("about.url"),
"avatar": utils.GetEnv("about.avatar"),
"file": map[string]any{
"maximun": maxStorageSize,
"current": currentFileSize,
},
})
}

View File

@@ -0,0 +1,21 @@
package controllers
import (
"backend/internal/utils"
"time"
"github.com/labstack/echo/v4"
"github.com/spf13/cast"
)
func GetConfig(c echo.Context) error {
return utils.HTTPSuccessHandler(c, map[string]any{
"site_title": utils.GetEnvMapString("site.title"),
"site_desc": utils.GetEnvMapString("site.desc"),
"site_url": utils.GetEnv("site.url"),
"site_icon": utils.GetEnvWithDefault("site.icon", "/logo.png"),
"site_bg_url": utils.GetEnvWithDefault("site.bg_url", "https://img.fudaoyuan.icu/api/1/random/?scale_min=1.5&webp=true&md=false&format=302"),
"version": utils.GetEnvWithDefault("VERSION", "dev"),
"build_time": cast.ToInt(utils.GetEnvWithDefault("BUILD_TIME", cast.ToString(time.Now().Unix()))),
})
}

View File

@@ -10,6 +10,7 @@ import (
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
"github.com/spf13/cast"
)
type DownloadShareClaims struct {
@@ -25,7 +26,7 @@ func DownloadShare(c echo.Context) error {
}
claims := DownloadShareClaims{}
t, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) {
return []byte(utils.GetEnv("download_secret")), nil
return []byte(utils.GetEnv("share.download_secret")), nil
})
if err != nil {
return utils.HTTPErrorHandler(c, err)
@@ -88,15 +89,16 @@ func VaildateShare(c echo.Context) error {
if shareInfo.ViewNum < 1 {
return utils.HTTPErrorHandler(c, errors.New("下载次数不足"))
}
downloadWindow := utils.GetEnvWithDefault("share.download_window", "12")
token := jwt.NewWithClaims(jwt.SigningMethodHS256, DownloadShareClaims{
ShareId: r.ShareId,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(60 * time.Minute)),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(cast.ToDuration(downloadWindow + "h"))),
},
})
// Sign and get the complete encoded token as a string using the secret
downloadToken, err := token.SignedString([]byte(utils.GetEnv("download_secret")))
downloadToken, err := token.SignedString([]byte(utils.GetEnv("share.download_secret")))
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
@@ -121,6 +123,21 @@ func VaildateShare(c echo.Context) error {
models.SetRedisShareInfo(r.ShareId, models.RedisShareInfo{
ViewNum: latestViewNum,
})
// 统计分享数
currentDate := time.Now().Format("2006-01-02")
statData, _ := models.GetRedisStat(currentDate)
if statData == nil {
statData = &models.StatData{
FileSize: 0,
FileNum: 0,
ShareNum: 0,
DownloadNum: 0,
}
}
statData.DownloadNum += 1
models.SetRedisStat(currentDate, *statData)
if shareInfo.Type == models.ShareTypeFile {
return utils.HTTPSuccessHandler(c, map[string]any{
"token": downloadToken,

View File

@@ -40,7 +40,7 @@ func CreateUploadTask(c echo.Context) error {
"chunk_size": fileInfo.ChunkSize,
})
}
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("MAX_LOCALSTORAGE_SIZE"))
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("upload.maximum"))
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
@@ -61,9 +61,10 @@ func CreateUploadTask(c echo.Context) error {
return utils.HTTPErrorHandler(c, errors.New("存储空间不足"))
}
ChunkSize := int64(1 * 1024 * 1024)
if r.FileSize > 500*1024*1024 {
ChunkSize = r.FileSize / 500
ChunkSize := int64(0.25 * 1024 * 1024)
// 根据文件大小动态调整块大小
for r.FileSize/ChunkSize > 1000 {
ChunkSize *= 2
}
uploadTaskExpire := int64(3600)
newFileInfo := models.RedisFileInfo{
@@ -221,6 +222,20 @@ func FinishUploadTask(c echo.Context) error {
models.SetRedisFileInfo(r.FileId, models.RedisFileInfo{
FileType: models.FileTypeUpload,
})
// 统计
currentDate := time.Now().Format("2006-01-02")
statData, _ := models.GetRedisStat(currentDate)
if statData == nil {
statData = &models.StatData{
FileSize: 0,
FileNum: 0,
ShareNum: 0,
DownloadNum: 0,
}
}
statData.FileSize += fileInfo.FileSize
statData.FileNum += 1
models.SetRedisStat(currentDate, *statData)
return utils.HTTPSuccessHandler(c, map[string]any{
"size": fileInfo.FileSize,

View File

@@ -12,6 +12,7 @@ import (
"github.com/hibiken/asynq"
"github.com/labstack/echo/v4"
gonanoid "github.com/matoous/go-nanoid/v2"
"github.com/spf13/cast"
)
type CreateShareProps struct {
@@ -111,12 +112,29 @@ func CreateShareInfo(c echo.Context) error {
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
_, err = client.Enqueue(asynq.NewTask("share:remove", json), asynq.ProcessIn(time.Duration(r.Config.ExpireAt)*time.Minute))
// 这里延时分享过期时间基础上加下载窗口期后1小时删除防止用户过期前几分钟才开始下载下载一半文件不见了
downloadWindow := utils.GetEnvWithDefault("share.download_window", "12")
deleteTime := time.Duration(r.Config.ExpireAt)*time.Minute + cast.ToDuration(downloadWindow+"h") + 1*time.Hour
_, err = client.Enqueue(asynq.NewTask("share:remove", json), asynq.ProcessIn(deleteTime))
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
}
// 统计分享数
currentDate := time.Now().Format("2006-01-02")
statData, _ := models.GetRedisStat(currentDate)
if statData == nil {
statData = &models.StatData{
FileSize: 0,
FileNum: 0,
ShareNum: 0,
DownloadNum: 0,
}
}
statData.ShareNum += 1
models.SetRedisStat(currentDate, *statData)
return utils.HTTPSuccessHandler(c, map[string]any{
"id": id,
"file_name": r.FileName,

View File

@@ -4,99 +4,71 @@ import (
"backend/internal/models"
"backend/internal/utils"
"encoding/json"
"time"
"github.com/hibiken/asynq"
"github.com/labstack/echo/v4"
"github.com/samber/lo"
"github.com/spf13/cast"
)
type FileChartData struct {
FileSize int64 `json:"file_size"`
FileNum int64 `json:"file_num"`
Date string `json:"date"`
const (
DateLayout = "2006-01-02"
DaysToAnalyze = 30
QueueHistoryDays = 30
)
type StatChartData struct {
FileSize int64 `json:"file_size"`
FileNum int64 `json:"file_num"`
ShareNum int64 `json:"share_num"`
DownloadNum int64 `json:"download_num"`
}
type QueueChartData struct {
Processed int `json:"processed"`
Failed int `json:"failed"`
}
func GetStat(c echo.Context) error {
fileInfoMap, err := models.GetRedisFileInfoAll()
statInfoMap, err := models.GetRedisStatAll()
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
fileChartData := make(map[string]FileChartData)
for _, value := range fileInfoMap {
var fileInfo models.RedisFileInfo
err := json.Unmarshal([]byte(value), &fileInfo)
statChartData := make(map[string]StatChartData)
for key, value := range statInfoMap {
var statData models.StatData
err := json.Unmarshal([]byte(value), &statData)
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
if fileInfo.FileType != models.FileTypeUpload {
continue
}
if time.Unix(fileInfo.CreatedAt, 0).After(time.Now().Add(-30 * 24 * time.Hour)) {
dateKey := time.Unix(fileInfo.CreatedAt, 0).Format("2006-01-02")
if data, ok := fileChartData[dateKey]; ok {
fileChartData[dateKey] = FileChartData{
FileSize: data.FileSize + fileInfo.FileSize,
FileNum: data.FileNum + 1,
}
} else {
fileChartData[dateKey] = FileChartData{
FileSize: fileInfo.FileSize,
FileNum: 1,
}
}
statChartData[key] = StatChartData{
FileSize: statData.FileSize,
FileNum: statData.FileNum,
ShareNum: statData.ShareNum,
DownloadNum: statData.DownloadNum,
}
}
storageChartData := lo.Times(30, func(i int) FileChartData {
dateKey := time.Now().AddDate(0, 0, -i).Format("2006-01-02")
if data, ok := fileChartData[dateKey]; ok {
return FileChartData{
FileSize: data.FileSize,
FileNum: data.FileNum,
Date: dateKey,
}
}
return FileChartData{
FileSize: 0,
FileNum: 0,
Date: dateKey,
}
})
queueInspector := utils.GetQueueInspector()
queues, err := queueInspector.History("default", 30)
queues, err := queueInspector.History("default", QueueHistoryDays)
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("MAX_LOCALSTORAGE_SIZE"))
if err != nil {
return utils.HTTPErrorHandler(c, err)
}
queueData := lo.Map(queues, func(item *asynq.DailyStats, _ int) map[string]any {
return map[string]any{
"date": item.Date.Format("2006-01-02"),
"processed": item.Processed,
"failed": item.Failed,
queuesChartData := make(map[string]QueueChartData)
for _, item := range queues {
dateKey := item.Date.Format(DateLayout)
if item.Processed == 0 && item.Failed == 0 {
continue
}
})
queuesChartData[dateKey] = QueueChartData{
Processed: item.Processed,
Failed: item.Failed,
}
}
return utils.HTTPSuccessHandler(c, map[string]any{
"version": utils.GetEnvWithDefault("VERSION", "dev"),
"build_time": cast.ToInt(utils.GetEnvWithDefault("BUILD_TIME", cast.ToString(time.Now().Unix()))),
"max_limit": map[string]any{
"file_size": maxStorageSize,
},
"admin": map[string]any{
"name": utils.GetEnv("ADMIN_NAME"),
"email": utils.GetEnv("ADMIN_EMAIL"),
"url": utils.GetEnv("ADMIN_URL"),
},
"chart": map[string]any{
"storage": storageChartData,
"queue": queueData,
"storage": statChartData,
"queue": queuesChartData,
},
})
}

View File

@@ -0,0 +1,52 @@
package models
import (
"backend/internal/utils"
"encoding/json"
"dario.cat/mergo"
"github.com/redis/go-redis/v9"
)
// 统计数据结构
type StatData struct {
FileSize int64 `json:"file_size"` // 文件大小
FileNum int64 `json:"file_num"` // 文件数量
ShareNum int64 `json:"share_num"` // 分享数量
DownloadNum int64 `json:"download_num"` // 下载数量
}
func GetRedisStat(key string) (*StatData, error) {
rdb, ctx := utils.GetRedisClient()
statUnmarshalData, err := rdb.HGet(ctx, "015:stat", key).Result()
if err == redis.Nil {
return nil, nil
}
if err != nil {
return nil, err
}
var stat StatData
if err := json.Unmarshal([]byte(statUnmarshalData), &stat); err != nil {
return nil, err
}
return &stat, nil
}
func SetRedisStat(key string, stat StatData) error {
rdb, ctx := utils.GetRedisClient()
old_stat, err := GetRedisStat(key)
if err != nil {
return err
}
if old_stat != nil {
mergo.Merge(&stat, old_stat)
}
jsonData, _ := json.Marshal(stat)
_, err = rdb.HSet(ctx, "015:stat", key, string(jsonData)).Result()
return err
}
func GetRedisStatAll() (map[string]string, error) {
rdb, ctx := utils.GetRedisClient()
return rdb.HGetAll(ctx, "015:stat").Result()
}

View File

@@ -3,17 +3,17 @@ package utils
import "github.com/hibiken/asynq"
func GetQueueClient() *asynq.Client {
opt := RedisURI2AsynqOpt(GetEnv("REDIS_URL"))
opt := RedisURI2AsynqOpt(GetEnv("redis.url"))
return asynq.NewClient(opt)
}
func GetQueueInspector() *asynq.Inspector {
opt := RedisURI2AsynqOpt(GetEnv("REDIS_URL"))
opt := RedisURI2AsynqOpt(GetEnv("redis.url"))
return asynq.NewInspector(opt)
}
func RedisURI2AsynqOpt(uri string) asynq.RedisConnOpt {
opt, err := asynq.ParseRedisURI(GetEnv("REDIS_URL"))
opt, err := asynq.ParseRedisURI(GetEnv("redis.url"))
if err != nil {
panic(err)
}

View File

@@ -1,6 +1,8 @@
package utils
import (
"strings"
"github.com/spf13/viper"
)
@@ -15,16 +17,20 @@ func InitEnv() {
return
}
v = viper.New()
v.SetConfigName(".env")
v.SetConfigType("env")
v.SetConfigName("config.yaml")
v.SetConfigType("yaml")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AddConfigPath(".")
v.AddConfigPath("../")
v.AutomaticEnv()
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
// 只有当错误不是"配置文件未找到"时才 panic
panic(err)
}
v.WatchConfig()
err := v.ReadInConfig()
if err != nil {
panic(err)
// if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
// // 只有当错误不是"配置文件未找到"时才 panic
// panic(err)
// }
}
}
@@ -40,3 +46,8 @@ func GetEnvWithDefault(key string, defaultValue string) string {
}
return value
}
func GetEnvMapString(key string) map[string]string {
InitEnv()
return v.GetStringMapString(key)
}

View File

@@ -41,7 +41,7 @@ func GetUploadDirPath() (string, error) {
return "", err
}
finalPath := filepath.Join(basepath, "uploads")
uploadPath := GetEnvWithDefault("UPLOAD_PATH", finalPath)
uploadPath := GetEnvWithDefault("upload.path", finalPath)
if err := os.MkdirAll(uploadPath, 0755); err != nil {
return "", err
}

View File

@@ -0,0 +1,58 @@
package utils
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
func TestHTTPSuccessHandler(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
data := map[string]interface{}{"result": "success"}
err := HTTPSuccessHandler(c, data)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, rec.Code)
var response map[string]interface{}
err = json.Unmarshal(rec.Body.Bytes(), &response)
assert.NoError(t, err)
expected := map[string]interface{}{
"code": float64(http.StatusOK),
"message": "success",
"data": data,
}
assert.Equal(t, expected, response)
}
func TestHTTPErrorHandler(t *testing.T) {
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
err := HTTPErrorHandler(c, assert.AnError)
assert.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, rec.Code)
var response map[string]interface{}
err = json.Unmarshal(rec.Body.Bytes(), &response)
assert.NoError(t, err)
expected := map[string]interface{}{
"code": float64(http.StatusBadRequest),
"message": assert.AnError.Error(),
"data": map[string]interface{}{},
}
assert.Equal(t, expected, response)
}

View File

@@ -8,7 +8,7 @@ import (
)
func GeneratePasswordHash(password string) (string, error) {
salt := GetEnv("PASSWORD_SALT")
salt := GetEnv("share.password_salt")
if salt == "" {
return "", errors.New("请配置PASSWORD_SALT")
}

View File

@@ -0,0 +1,71 @@
package utils
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGeneratePasswordHash(t *testing.T) {
// 保存原始环境变量
originalSalt := os.Getenv("share.password_salt")
defer os.Setenv("share.password_salt", originalSalt)
tests := []struct {
name string
password string
salt string
expectError bool
errorMsg string
}{
{
name: "share.password_salt未配置",
password: "testpassword",
salt: "",
expectError: true,
errorMsg: "请配置share.password_salt",
},
{
name: "正常生成哈希",
password: "testpassword123",
salt: "testsalt",
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 设置环境变量
if tt.salt != "" {
os.Setenv("share.password_salt", tt.salt)
} else {
os.Unsetenv("share.password_salt")
}
hash, err := GeneratePasswordHash(tt.password)
if tt.expectError {
if err == nil {
t.Errorf("期望错误,但得到了 nil")
return
}
if err.Error() != tt.errorMsg {
t.Errorf("期望错误信息 '%s',但得到了 '%s'", tt.errorMsg, err.Error())
}
return
}
if err != nil {
t.Errorf("不期望错误,但得到了: %v", err)
return
}
// 验证哈希格式argon2 32字节 = 64个十六进制字符
if len(hash) != 64 {
t.Errorf("期望哈希长度为64但得到了 %d", len(hash))
}
assert.Equal(t, hash, "537275f995fdd46eb2e5455b8a29adccb60c5637689d29646676a5f1bffb63f3")
})
}
}

View File

@@ -10,7 +10,7 @@ var rdb *redis.Client = InitRedis()
var ctx = context.Background()
func InitRedis() *redis.Client {
opt, err := redis.ParseURL(GetEnv("REDIS_URL"))
opt, err := redis.ParseURL(GetEnv("redis.url"))
if err != nil {
panic(err)
}

View File

@@ -4,6 +4,7 @@ import (
"backend/internal/controllers"
"backend/internal/utils"
"backend/middleware"
"fmt"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
@@ -12,7 +13,7 @@ import (
func main() {
// 日志
var logger *zap.Logger
if utils.GetEnvWithDefault("NODE_ENV", "production") == "production" {
if utils.GetEnvWithDefault("node.env", "production") == "production" {
logger, _ = zap.NewProduction()
} else {
logger, _ = zap.NewDevelopment()
@@ -40,5 +41,7 @@ func main() {
e.GET("/image/compress/:id", controllers.GetCompressImage)
e.GET("/stat", controllers.GetStat)
e.Logger.Fatal(e.Start(":1323"))
e.GET("/config", controllers.GetConfig)
e.GET("/about", controllers.GetAbout)
e.Logger.Fatal(e.Start(fmt.Sprintf(":%s", utils.GetEnvWithDefault("api.port", "5001"))))
}

55
config.example.yaml Normal file
View File

@@ -0,0 +1,55 @@
share:
# (必填)你的下载secret每一次下载次数减1的时候都会根据这里的secret生成一个下载jwt token 有效期一小时使用该下载token有效期内可以多线程下载该文件而不会被多次扣除次数
download_secret: your-secret-token
# 颁发的下载token的窗口期默认12小时文件过期后自动从服务器删除时间为此时间基础上加1小时默认为12+1=13小时
download_window: 12
# (必填)设置密码时会把密码加盐
password_salt: your-passwall-salt
upload:
# 上传文件保存路径
path: /upload
# 指定实例最大上传容量支持填写人类可读的值比如1TiB500GiB等注意填写GiB而不是GB, Gib按1024字节计算Gb按1000字节计算
maximum: 100GiB
redis:
# (必填)redis 地址
url: redis://redis:6379/0
# 站点基本信息
site:
# 必填,对应你的公网域名
url: http://localhost:5000
title:
'en': '015'
desc:
'en': '015 is an open-source temporary file sharing platform project that supports uploading, downloading, and sharing files and text.'
icon: '/logo.png'
bg_url: 'https://img.fudaoyuan.icu/api/1/random/?scale_min=1.5&webp=true&md=false&format=302'
# 关于页面的
about:
# hero图片 推荐3:1 比例
bg_url: 'https://files.mastodon.social/site_uploads/files/000/000/001/@1x/57c12f441d083cde.png'
# 关于信息markdown格式
content:
'zh': |
### markdown测试文案
这里有一个图片示例:
![示例图片](https://cdn.ani.work/site_uploads/files/000/000/005/@1x/d68677a8b7a8d296.png)
这里有一个[示例链接](https://fudaoyuan.icu)
'en': |
### Markdown Test Content
Here is an image example:
![Sample Image](https://cdn.ani.work/site_uploads/files/000/000/005/@1x/d68677a8b7a8d296.png)
Here is a [sample link](https://fudaoyuan.icu)
email: keven@fudaoyuan.icu
name: keven
url: 'https://fudaoyuan.icu'
avatar: ''

24
docker-compose.yml Normal file
View File

@@ -0,0 +1,24 @@
services:
app:
image: fudaoyuanicu/015-app:latest
container_name: 015-app
volumes:
- ./uploads:/uploads
ports:
- "8080:80"
env_file: '.env'
depends_on:
- redis
worker:
image: fudaoyuanicu/015-worker:latest
container_name: worker
env_file: '.env'
volumes:
- ./uploads:/uploads
depends_on:
- app
- redis
redis:
image: redis:7
container_name: redis

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 654 KiB

View File

@@ -1,19 +1,19 @@
<!-- app.vue -->
<script setup lang="ts">
import { defineRule } from 'vee-validate';
import { all } from '@vee-validate/rules';
import { defineRule } from 'vee-validate'
import { all } from '@vee-validate/rules'
Object.entries(all).forEach(([name, rule]) => {
defineRule(name, rule);
});
defineRule(name, rule)
})
// @ts-check
const { $serwist } = useNuxtApp();
$serwist?.addEventListener("installed", () => {
console.log("Serwist installed!");
});
void $serwist?.register({ immediate: true });
// const { $serwist } = useNuxtApp();
// $serwist?.addEventListener("installed", () => {
// console.log("Serwist installed!");
// });
// void $serwist?.register({ immediate: true });
</script>
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>

View File

@@ -41,6 +41,24 @@
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--animate-accordion-down: accordion-down 0.2s ease-out;
--animate-accordion-up: accordion-up 0.2s ease-out;
@keyframes accordion-down {
from {
height: 0;
}
to {
height: var(--reka-accordion-content-height);
}
}
@keyframes accordion-up {
from {
height: var(--reka-accordion-content-height);
}
to {
height: 0;
}
}
}
:root {

View File

@@ -0,0 +1,127 @@
<script setup lang="ts">
import { useQuery } from '@tanstack/vue-query'
import { Skeleton } from '@/components/ui/skeleton'
import getFileSize from '~/lib/getFileSize'
import SparkMD5 from 'spark-md5'
import useMyAppConfig from '@/composables/useMyAppConfig'
import Progress from '~/components/ui/progress/Progress.vue'
import renderI18n from '~/lib/renderI18n'
import { I18nT } from 'vue-i18n'
const { locale } = useI18n()
const appConfig = useMyAppConfig()
const { data, isLoading } = useQuery({
queryKey: ['about'],
queryFn: async () => {
const data = await $fetch<{
data: {
file: {
maximun: number
current: number
}
bg_url?: string
avatar?: string
name?: string
email?: string
url?: string
content?: Record<string, string>
}
}>('/api/about')
return data?.data
},
})
const { t } = useI18n()
const genUserAvatar = (email: string) => {
return `https://www.gravatar.com/avatar/${SparkMD5.hash(email)}?d=retro`
}
</script>
<template>
<template v-if="isLoading">
<div class="flex flex-col gap-2">
<Skeleton class="aspect-[3/1] w-full rounded-xl" />
<div class="flex flex-col gap-2 items-center">
<Skeleton class="h-6 w-32 rounded" />
<Skeleton class="h-4 w-52 rounded" />
</div>
</div>
</template>
<template v-else>
<NuxtImg v-if="data?.bg_url" :src="data?.bg_url" class="aspect-[3/1] w-full rounded-xl object-cover" />
<div class="flex flex-col gap-2 items-center">
<div class="text-xl">{{ renderI18n(appConfig?.site_title ?? {}, 'en', locale) }}</div>
<div class="text-sm opacity-75 text-center px-5">
<I18nT keypath="about.powerBy" tag="span">
<NuxtLink href="https://github.com/keven1024/015" target="_blank" class="text-primary hover:underline">015</NuxtLink>
</I18nT>
</div>
</div>
</template>
<div class="font-semibold">{{ t('about.systemInfo') }}</div>
<template v-if="isLoading">
<div class="flex flex-row gap-2">
<Skeleton class="w-full h-20 rounded-xl" v-for="i in 2" :key="i" />
</div>
</template>
<template v-else>
<div class="grid grid-cols-1 md:grid-cols-2 gap-2">
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3 gap-2">
<div class="opacity-75 text-xs">{{ t('about.admin') }}</div>
<div
class="flex flex-row gap-2 items-center cursor-pointer"
@click="
() => {
if (data?.url) {
navigateTo(data?.url, { external: true })
return
}
if (data?.email) {
navigateTo(`mailto:${data?.email ?? ''}`, { external: true })
return
}
return
}
"
>
<Avatar class="size-10">
<AvatarImage v-if="!!data?.avatar || !!data?.email" :src="data?.avatar || genUserAvatar(data?.email as string)" />
<AvatarFallback class="bg-black/10 font-bold">
{{ data?.name?.charAt(0)?.toUpperCase() }}
</AvatarFallback>
</Avatar>
<div class="flex flex-col">
<div class="text-md font-semibold">{{ data?.name }}</div>
<div class="text-xs opacity-75">{{ data?.email }}</div>
</div>
</div>
</div>
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3 gap-2">
<div class="opacity-75 text-xs">{{ t('about.storage') }}</div>
<div class="text-right flex flex-row items-baseline">
<span class="text-lg font-semibold">{{ getFileSize(data?.file?.current ?? 0) }}</span>
<span class="text-md opacity-75">/ {{ getFileSize(data?.file?.maximun ?? 0) }}</span>
</div>
<Progress class="h-1" :model-value="((data?.file?.current ?? 0) / (data?.file?.maximun ?? 0)) * 100" />
</div>
</div>
</template>
<template v-if="isLoading">
<Skeleton class="w-full h-16 rounded-xl" />
</template>
<template v-else>
<div v-if="data?.content" class="rounded-xl bg-white/50 flex flex-col px-3 gap-2">
<Accordion type="single" collapsible>
<AccordionItem value="about">
<AccordionTrigger>
<span class="font-semibold">{{ t('about.about') }}</span>
</AccordionTrigger>
<AccordionContent>
<MarkdownRender :markdown="renderI18n(data?.content ?? {}, 'en', locale) ?? ''" />
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
</template>
</template>

View File

@@ -0,0 +1,187 @@
<script setup lang="ts">
import { CurveType } from '@unovis/ts'
import { AreaChart } from '@/components/ui/chart-area'
import { cx } from 'class-variance-authority'
import { useQuery } from '@tanstack/vue-query'
import { Skeleton } from '@/components/ui/skeleton'
import AboutChartTooltip from '@/components/AboutChartTooltip.vue'
import dayjs from 'dayjs'
import { times } from 'lodash-es'
interface StatChartData {
file_size: number
file_num: number
share_num: number
download_num: number
date: string
}
interface QueueChartData {
processed: number
failed: number
date: string
}
type ChartDataItem = StatChartData | QueueChartData
type ChartConfig = {
data: ChartDataItem[]
index: string
categories: string[]
colors: string[]
}
const { data, isLoading } = useQuery({
queryKey: ['stat'],
queryFn: async () => {
const response = await $fetch<{
data: {
chart: {
storage: Record<string, StatChartData>
queue: Record<string, QueueChartData>
}
}
}>('/api/stat')
return response.data
},
})
const { t } = useI18n()
const chartTabs = computed(() => {
return [
{
label: t('about.file'),
value: 'storage',
total: data.value?.chart?.storage
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.file_num, 0)
: 0,
},
{
label: t('about.share'),
value: 'share',
total: data.value?.chart?.storage
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.share_num, 0)
: 0,
},
{
label: t('about.download'),
value: 'download',
total: data.value?.chart?.storage
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.download_num, 0)
: 0,
},
{
label: t('about.task'),
value: 'queue',
total: data.value?.chart?.queue
? Object.values(data.value.chart.queue).reduce((acc: number, curr: QueueChartData) => acc + curr.processed + curr.failed, 0)
: 0,
},
]
})
const currentChartTab = ref<'storage' | 'queue' | 'share' | 'download'>('storage')
const currentChartData = computed((): ChartConfig => {
const { storage, queue } = data.value?.chart || {}
if (currentChartTab.value === 'queue') {
const queueData = times(30, (i) => {
return {
date: dayjs().subtract(i, 'day').format('YYYY-MM-DD'),
processed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.processed || 0,
failed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.failed || 0,
}
})
return {
data: queueData,
index: 'date' as const,
categories: ['processed', 'failed'] as const,
colors: ['#4ade80', '#f87171'],
}
}
const storageData = times(30, (i) => {
const base = { date: dayjs().subtract(i, 'day').format('YYYY-MM-DD') }
if (currentChartTab.value === 'share') {
return {
...base,
share_num: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.share_num || 0,
}
}
if (currentChartTab.value === 'download') {
return {
...base,
download_num: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.download_num || 0,
}
}
return {
...base,
file_size: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.file_size || 0,
file_num: storage?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.file_num || 0,
}
})
let categories = ['file_size', 'file_num']
if (currentChartTab.value === 'share') {
categories = ['share_num']
}
if (currentChartTab.value === 'download') {
categories = ['download_num']
}
let colors = ['#38bdf8', '#a78bfa']
if (currentChartTab.value === 'share') {
colors = ['#ea580c']
}
if (currentChartTab.value === 'download') {
colors = ['#a3e635']
}
return {
data: storageData as ChartDataItem[],
index: 'date' as const,
categories,
colors,
}
})
</script>
<template>
<div class="font-semibold">{{ t('about.analysis') }}</div>
<template v-if="isLoading">
<div class="flex flex-row gap-2">
<Skeleton class="w-full h-96 rounded-xl" />
</div>
</template>
<template v-else>
<div class="flex flex-col gap-2 bg-white/50 w-full rounded-xl py-5">
<div class="grid grid-cols-2 md:grid-cols-4 gap-2 px-5">
<div
:class="cx('rounded-md min-w-30 flex flex-col px-3 py-1.5 cursor-pointer', currentChartTab === tab.value && 'bg-black/10')"
v-for="tab in chartTabs"
:key="tab.value"
@click="
() => {
currentChartTab = tab.value as 'storage' | 'queue'
}
"
>
<div class="opacity-75 text-xs">{{ tab.label }}</div>
<div class="text-lg font-semibold">{{ tab.total }}</div>
</div>
</div>
<AreaChart
v-if="currentChartData"
class="h-64 w-full"
:key="currentChartTab"
:index="currentChartData.index"
:data="currentChartData.data"
:categories="currentChartData.categories"
:show-grid-line="false"
:show-legend="false"
:show-y-axis="true"
:show-x-axis="true"
:colors="currentChartData.colors"
:custom-tooltip="AboutChartTooltip"
:curve-type="CurveType.CatmullRom"
/>
</div>
</template>
</template>

View File

@@ -0,0 +1,20 @@
<script setup lang="ts">
import useMyAppConfig from '@/composables/useMyAppConfig'
import dayjs from 'dayjs'
const appConfig = useMyAppConfig()
</script>
<template>
<div class="flex flex-row flex-wrap gap-4 items-center text-sm opacity-60">
<div class="flex flex-row gap-1 opacity-100">
<NuxtLink href="https://github.com/keven1024/015" target="_blank" class="text-primary hover:underline">015</NuxtLink>
{{ appConfig?.version ?? 'dev' }}
</div>
<div v-if="appConfig?.build_time">
{{ `Build at ${dayjs(appConfig?.build_time * 1000).format('YYYY-MM-DD')}` }}
</div>
<div>Designed by <NuxtLink href="https://fudaoyuan.icu" target="_blank" class="text-primary hover:underline">keven1024</NuxtLink></div>
</div>
</template>

View File

@@ -1,53 +1,43 @@
<script setup lang="ts">
import { filesize } from "filesize";
import getFileSize from '~/lib/getFileSize'
const props = defineProps<{
data: { name: string; value: string; color: string }[];
title: string;
}>();
data: { name: string; value: string; color: string }[]
title: string
}>()
const dataKeyMap = {
file_size: {
"zh-CN": "文件大小",
en: "File Size",
},
file_num: {
"zh-CN": "文件数量",
en: "File Num",
},
processed: {
"zh-CN": "处理数量",
en: "Processed",
},
failed: {
"zh-CN": "失败数量",
en: "Failed",
},
};
file_size: {
'zh-CN': '文件大小',
en: 'File Size',
},
file_num: {
'zh-CN': '文件数量',
en: 'File Num',
},
processed: {
'zh-CN': '处理数量',
en: 'Processed',
},
failed: {
'zh-CN': '失败数量',
en: 'Failed',
},
}
</script>
<template>
<div class="rounded-md bg-white p-2 flex flex-col gap-2">
<div class="text-sm font-medium">{{ title }}</div>
<div v-for="(item, index) in data" :key="index">
<div class="flex flex-row items-center gap-2">
<div
class="h-5 w-2 rounded-full"
:style="{ backgroundColor: item.color ?? '#222' }"
></div>
<div class="text-xs font-medium">
{{
dataKeyMap?.[item.name as keyof typeof dataKeyMap]?.["en"] ??
item.name
}}
<div class="rounded-md bg-white p-2 flex flex-col gap-2">
<div class="text-sm font-medium">{{ title }}</div>
<div v-for="(item, index) in data" :key="index">
<div class="flex flex-row items-center gap-2">
<div class="h-5 w-2 rounded-full" :style="{ backgroundColor: item.color ?? '#222' }"></div>
<div class="text-xs font-medium">
{{ dataKeyMap?.[item.name as keyof typeof dataKeyMap]?.['en'] ?? item.name }}
</div>
<div class="text-sm">
{{ ['file_size']?.includes(item?.name) ? getFileSize(item.value) : item.value }}
</div>
</div>
</div>
<div class="text-sm">
{{
["file_size"]?.includes(item?.name)
? filesize(item.value)
: item.value
}}
</div>
</div>
</div>
</div>
</template>

View File

@@ -1,120 +1,108 @@
<script setup lang="ts">
import {
LucideShare,
LucideImage,
LucideBot,
LucideLanguages,
LucideFileText,
LucideImageMinus,
LucideArrowRightLeft,
LucideImagePlus,
LucideAudioLines,
LucideListMusic,
} from "lucide-vue-next";
import { cx } from "class-variance-authority";
import { isObject } from "lodash-es";
import showDrawer from "@/lib/showDrawer";
import FileShareHandle from "@/components/Preprocessing/FileShareHandle.vue";
const { t } = useI18n();
LucideShare,
LucideImage,
LucideBot,
LucideLanguages,
LucideFileText,
LucideImageMinus,
LucideArrowRightLeft,
LucideImagePlus,
LucideAudioLines,
LucideListMusic,
} from 'lucide-vue-next'
import { cx } from 'class-variance-authority'
import { isObject } from 'lodash-es'
import showDrawer from '@/lib/showDrawer'
import FileShareHandle from '@/components/Preprocessing/FileShareHandle.vue'
import type { FileShareHandleProps } from '../Preprocessing/types'
const { t } = useI18n()
const props = defineProps<{
hide: () => void;
file: File;
onFileHandle: ({ type, config }: { type: string; config: any }) => void;
}>();
hide: () => void
file: File[]
onFileHandle: (props: FileShareHandleProps) => void
}>()
const isImage = computed(() => props.file.type.startsWith("image/"));
const isVideo = computed(() => props.file.type.startsWith("video/"));
const isAudio = computed(() => props.file.type.startsWith("audio/"));
const isMedia = computed(() => isImage.value || isVideo.value || isAudio.value);
const isImage = computed(() => props.file.every((r) => r?.type?.startsWith('image/')))
const isVideo = computed(() => props.file.every((r) => r?.type?.startsWith('video/')))
const isAudio = computed(() => props.file.every((r) => r?.type?.startsWith('audio/')))
const isMedia = computed(() => isImage.value || isVideo.value || isAudio.value)
const isPDF = computed(() => props.file.type.startsWith("application/pdf"));
const isDOC = computed(() => props.file.type.startsWith("application/msword"));
const isXLS = computed(() =>
props.file.type.startsWith("application/vnd.ms-excel"),
);
const isPPT = computed(() =>
props.file.type.startsWith("application/vnd.ms-powerpoint"),
);
const isDocument = computed(
() => isPDF.value || isDOC.value || isXLS.value || isPPT.value,
);
const isPDF = computed(() => props.file.every((r) => r?.type?.startsWith('application/pdf')))
const isDOC = computed(() => props.file.every((r) => r?.type?.startsWith('application/msword')))
const isXLS = computed(() => props.file.every((r) => r?.type?.startsWith('application/vnd.ms-excel')))
const isPPT = computed(() => props.file.every((r) => r?.type?.startsWith('application/vnd.ms-powerpoint')))
const isDocument = computed(() => isPDF.value || isDOC.value || isXLS.value || isPPT.value)
const actions = [
{
label: t("file.handleType.file-share"),
icon: LucideShare,
className: "bg-green-300",
onClick: () => {
showDrawer({
render: ({ hide }) => h(FileShareHandle, { ...props, hide }),
});
{
label: t('file.handleType.file-share'),
icon: LucideShare,
className: 'bg-green-300',
onClick: () => {
showDrawer({
render: ({ hide }) => h(FileShareHandle, { ...props, hide }),
})
},
},
},
isImage.value && {
label: t("file.handleType.file-image-compress"),
icon: LucideImageMinus,
className: "bg-red-300",
onClick: () => {
props.onFileHandle({ type: "file-image-compress", config: {} });
isImage.value && {
label: t('file.handleType.file-image-compress'),
icon: LucideImageMinus,
className: 'bg-red-300',
onClick: () => {
props.onFileHandle({ type: 'file-image-compress', config: {} })
},
},
},
// isImage.value && {
// label: '图片翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
// console.log('复制链接')
// }
// },
// isImage.value && {
// label: '图片超分', icon: LucideImagePlus, className: 'bg-cyan-300', onClick: () => {
// console.log('复制链接')
// }
// },
// (isAudio.value || isVideo.value) && {
// label: '转文本', icon: LucideListMusic, className: 'bg-cyan-300', onClick: () => {
// console.log('复制链接')
// }
// },
// isAudio.value && {
// label: '语音克隆', icon: LucideAudioLines, className: 'bg-cyan-300', onClick: () => {
// console.log('复制链接')
// }
// },
// (isDocument.value || isMedia.value) && {
// label: '格式转换', icon: LucideArrowRightLeft, className: 'bg-purple-300', onClick: () => {
// console.log('复制链接')
// }
// },
// isImage.value && {
// label: '图片翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
// console.log('复制链接')
// }
// },
// isImage.value && {
// label: '图片超分', icon: LucideImagePlus, className: 'bg-cyan-300', onClick: () => {
// console.log('复制链接')
// }
// },
// (isAudio.value || isVideo.value) && {
// label: '转文本', icon: LucideListMusic, className: 'bg-cyan-300', onClick: () => {
// console.log('复制链接')
// }
// },
// isAudio.value && {
// label: '语音克隆', icon: LucideAudioLines, className: 'bg-cyan-300', onClick: () => {
// console.log('复制链接')
// }
// },
// (isDocument.value || isMedia.value) && {
// label: '格式转换', icon: LucideArrowRightLeft, className: 'bg-purple-300', onClick: () => {
// console.log('复制链接')
// }
// },
]?.filter(isObject) as {
label: string;
icon: any;
className: string;
onClick: () => void;
}[];
label: string
icon: any
className: string
onClick: () => void
}[]
</script>
<template>
<div class="flex flex-col gap-5 p-5">
<div class="flex flex-row gap-2">
<div
v-for="item in actions"
:key="item.label"
class="flex flex-col items-center gap-2 max-w-20"
@click="
() => {
props?.hide();
item?.onClick();
}
"
>
<div
:class="
cx(
'size-14 flex justify-center items-center rounded-full mx-3',
item?.className,
)
"
>
<component :is="item?.icon" />
<div class="flex flex-col gap-5 p-5">
<div class="flex flex-row gap-2">
<div
v-for="item in actions"
:key="item.label"
class="flex flex-col items-center gap-2 max-w-20"
@click="
() => {
props?.hide()
item?.onClick()
}
"
>
<div :class="cx('size-14 flex justify-center items-center rounded-full mx-3', item?.className)">
<component :is="item?.icon" />
</div>
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
</div>
</div>
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
</div>
</div>
</div>
</template>

View File

@@ -1,57 +1,56 @@
<script setup lang="ts">
import VeeForm from "@/components/VeeForm.vue";
import FormButton from "@/components/Field/FormButton.vue";
import PinInputField from "@/components/Field/PinInputField.vue";
import type { FormContext, GenericObject } from "vee-validate";
import { toast } from "vue-sonner";
const router = useRouter();
import VeeForm from '@/components/VeeForm.vue'
import FormButton from '@/components/Field/FormButton.vue'
import PinInputField from '@/components/Field/PinInputField.vue'
import type { FormContext, GenericObject } from 'vee-validate'
import { toast } from 'vue-sonner'
const router = useRouter()
const { t } = useI18n()
const props = defineProps<{
hide: () => void;
}>();
const handleSubmit = async (
form: FormContext<GenericObject, GenericObject>,
) => {
try {
const code = form.values.code;
const data = await $fetch<{
data: {
share_id: string;
};
}>(`/api/share/pickup/${code}`);
if (!data.data.share_id) {
toast.error("取件码错误");
form.resetForm();
return;
hide: () => void
}>()
const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) => {
try {
const code = form.values.code
const data = await $fetch<{
data: {
share_id: string
}
}>(`/api/share/pickup/${code}`)
if (!data.data.share_id) {
toast.error(t('pickup.codeError'))
form.resetForm()
return
}
const { share_id } = data.data
props.hide()
router.push({
path: `/s/${share_id}`,
})
return
} catch (error) {
toast.error(t('pickup.codeError'))
form.resetForm()
}
const { share_id } = data.data;
props.hide();
router.push({
path: `/s/${share_id}`,
});
return;
} catch (error) {
toast.error("取件码错误");
form.resetForm();
}
};
}
</script>
<template>
<VeeForm>
<div class="flex flex-col gap-5">
<div class="text-xl font-bold">输入取件码</div>
<PinInputField
name="code"
:rules="
(value) => {
if (value?.length !== 4) {
return false;
}
return true;
}
"
/>
<FormButton @click="handleSubmit">提交</FormButton>
</div>
</VeeForm>
<VeeForm>
<div class="flex flex-col gap-5">
<div class="text-xl font-bold">{{ t('pickup.title') }}</div>
<PinInputField
name="code"
:rules="
(value) => {
if (value?.length !== 4) {
return false
}
return true
}
"
/>
<FormButton @click="handleSubmit">{{ t('btn.submit') }}</FormButton>
</div>
</VeeForm>
</template>

View File

@@ -1,42 +1,71 @@
<script setup lang="ts">
import FileUpload from "@/components/FileUpload.vue";
import { cx } from "class-variance-authority";
import type { RuleExpression } from "vee-validate";
import FileUpload from '@/components/FileUpload.vue'
import { cx } from 'class-variance-authority'
import type { RuleExpression } from 'vee-validate'
import Button from '../ui/button/Button.vue'
import { PlusIcon } from 'lucide-vue-next'
import { isEmpty } from 'lodash-es'
const props = defineProps<{
name: string;
rules?: RuleExpression<File>;
}>();
const { value, setValue } = useField<File>(props?.name, props?.rules);
const { t } = useI18n();
name: string
rules?: RuleExpression<File[]>
}>()
const { value, setValue } = useField<File[]>(props?.name, props?.rules)
const { t } = useI18n()
</script>
<template>
<FileUpload
@onChange="
(file) => {
setValue(file);
}
"
v-slot="{ isOverDropZone }"
>
<div
:class="
cx(
'bg-white/50 rounded-md p-2 w-full h-40 flex flex-col items-center justify-center border border-dashed border-black/20 cursor-pointer text-gray-500 gap-3',
isOverDropZone && '!bg-green-100/50 ',
)
"
<FileUpload
@onChange="
(file) => {
// 这里没hash我们姑且认为name和size,type都一样的为同一个文件
setValue([...(value?.filter((r) => r?.name !== file?.name || r?.type !== file?.type || r?.size !== file?.size) || []), file])
}
"
v-slot="{ isOverDropZone }"
>
<template v-if="!!value">
<FilePreviewView :value="value" />
</template>
<template v-else>
<LucideUpload class="size-10" />
<div class="text-sm">
{{ t("file.uploadFilePlaceholder") }}
<div
:class="
cx(
'bg-white/50 rounded-md p-2 w-full min-h-40 flex flex-col items-center justify-center border border-dashed border-black/20 cursor-pointer text-gray-500 gap-3 transition-all duration-300',
isOverDropZone && '!bg-green-100/50 '
)
"
>
<template v-if="!isEmpty(value)">
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-5 w-full">
<div v-for="item in value" :key="item?.name" class="flex flex-col items-center justify-center relative">
<div class="absolute top-0 right-0">
<Button
class="size-5 p-0 bg-red-500/20 hover:bg-red-500/60 text-red-500 hover:text-white"
@click="
(e: any) => {
e.stopPropagation()
setValue(
value?.filter((r) => r?.name !== item?.name || r?.type !== item?.type || r?.size !== item?.size) || []
)
}
"
>
<LucideX class="size-3" />
</Button>
</div>
<FilePreviewView :value="item" />
</div>
<div class="flex flex-col items-center justify-center opacity-50 gap-1">
<div class="size-16 flex justify-center items-center rounded-xl bg-white/80">
<PlusIcon class="size-7" />
</div>
<div class="mb-3">{{ t('file.addMore') }}</div>
</div>
</div>
</template>
<template v-else>
<LucideUpload class="size-10" />
<div class="text-sm select-none">
{{ t('file.uploadFilePlaceholder') }}
</div>
</template>
</div>
</template>
</div>
</FileUpload>
</FileUpload>
</template>

View File

@@ -7,6 +7,7 @@
</Field>
</template>
<script setup lang="ts">
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
const props = defineProps<{
name: string

View File

@@ -3,11 +3,11 @@
</template>
<script setup lang="ts">
import Tiptap from '@/components/Tiptap.vue'
import Tiptap from '@/components/Tiptap/Index.vue'
import type { RuleExpression } from 'vee-validate'
const props = defineProps<{
name: string
rules?: RuleExpression<string>
}>()
const { value, } = useField<string>(props.name, props.rules)
const { value } = useField<string>(props.name, props.rules)
</script>

View File

@@ -1,4 +1,5 @@
<script setup lang="ts">
import { cx } from 'class-variance-authority'
export type filePreview = {
type: string
name: string
@@ -8,6 +9,7 @@ export type filePreview = {
import { LucideFileAudio, LucideFileVideo, LucideFile, LucideFileCode, LucideFileArchive, LucideFileText } from 'lucide-vue-next'
const props = defineProps<{
file: File | filePreview
class?: string
}>()
const imageUrl = computed(() => {
if (props?.file?.type?.startsWith('image/') && props?.file instanceof File) {
@@ -30,15 +32,20 @@ const fileIcon = computed(() => {
if (baseType === 'audio') {
return LucideFileAudio
}
if (baseType === 'text' || ["json", "ld+json", "html"]?.includes(type)) {
if (baseType === 'text' || ['json', 'ld+json', 'html']?.includes(type)) {
return LucideFileCode
}
if (['pdf', 'msword',
'vnd.openxmlformats-officedocument.wordprocessingml.document',
'vnd.ms-excel',
'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'vnd.ms-powerpoint',
'vnd.openxmlformats-officedocument.presentationml.presentation'].includes(type)) {
if (
[
'pdf',
'msword',
'vnd.openxmlformats-officedocument.wordprocessingml.document',
'vnd.ms-excel',
'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'vnd.ms-powerpoint',
'vnd.openxmlformats-officedocument.presentationml.presentation',
].includes(type)
) {
return LucideFileText
}
if (['zip', 'vnd.rar', 'x-tar', 'gz', 'bz2', 'x-7z-compressed'].includes(type)) {
@@ -51,11 +58,10 @@ const fileIcon = computed(() => {
<template>
<div v-if="!!imageUrl" class="flex max-w-30 max-h-20">
<div class="object-contain m-auto h-full">
<img :src="imageUrl" class="w-full h-full border border-black/20 rounded" />
<img :src="imageUrl" class="w-full h-full border border-black/20 rounded" />
</div>
</div>
<div v-if="!imageUrl" class="size-16 flex justify-center items-center rounded-xl bg-white/80">
<component :is="fileIcon" class="size-10" />
<div v-if="!imageUrl" :class="cx('flex justify-center items-center rounded-xl bg-white/80 size-16', props?.class)">
<component :is="fileIcon" class="size-[62.5%]" />
</div>
</template>
</template>

View File

@@ -1,6 +1,6 @@
<script lang="ts" setup>
import { filesize } from 'filesize'
import type { filePreview } from './FileIcon.vue';
import getFileSize from '~/lib/getFileSize'
import type { filePreview } from './FileIcon.vue'
const props = defineProps<{
value: File | filePreview
}>()
@@ -17,6 +17,6 @@ const fileInfo = computed(() => {
<div class="truncate">{{ fileInfo?.name }}</div>
<div>{{ `.${fileInfo?.ext}` }}</div>
</div>
<div class="text-xs opacity-50">{{ filesize(value?.size ?? 0) }}</div>
<div class="text-xs opacity-50">{{ getFileSize(value?.size ?? 0) }}</div>
</div>
</template>
</template>

View File

@@ -0,0 +1,44 @@
<script setup lang="ts">
import type { Graphics } from 'pixi.js'
import type { PixiExpose } from '@/components/Pixi.vue'
const props = withDefaults(
defineProps<{
size?: number
data?: { chunks: Record<number, { status: 'success' | 'error' | 'processing'; createdAt: number }>; chunkLength: number }
}>(),
{
size: 16,
data: () => ({ chunks: [], chunkLength: 0 }),
}
)
const pixiRef = ref<PixiExpose>()
const width = computed(() => pixiRef.value?.width || 0)
const height = computed(() => pixiRef.value?.height || 0)
watchEffect(() => {
console.log('data', props.data)
})
const renderGraphics = (graphics: Graphics) => {
graphics.clear()
Object.entries(props?.data?.chunks || {})?.map(([index, item]) => {
const { status, createdAt } = item || {}
const size = width.value / props.data?.chunkLength
const x = Number(index) * size
graphics.rect(x, 0, size, height.value)
let color = 0x60a5fa
if (status === 'success') {
color = 0x4ade80
}
if (status === 'error') {
color = 0xf87171
}
graphics.fill(color)
})
}
</script>
<template>
<Pixi ref="pixiRef">
<graphics @render="renderGraphics" />
</Pixi>
</template>

View File

@@ -0,0 +1,62 @@
<script setup lang="ts">
import type { Graphics } from 'pixi.js'
import type { PixiExpose } from '@/components/Pixi.vue'
let props = withDefaults(
defineProps<{
size?: number
gap?: number
data?: { chunks: Record<number, { status: 'success' | 'error' | 'processing'; createdAt: number }>; chunkLength: number }
}>(),
{
size: 16,
gap: 4,
data: () => ({ chunks: [], chunkLength: 0 }),
}
)
const pixiRef = ref<PixiExpose>()
const width = computed(() => pixiRef.value?.width)
const height = computed(() => pixiRef.value?.height)
const size = ref(props.size)
const gap = ref(props.gap)
const itemsPerRow = ref(0)
const itemsPerCol = computed(() => Math.ceil(props?.data?.chunkLength / itemsPerRow.value))
watchEffect(() => {
if (!width?.value || !height?.value || !pixiRef.value) return
itemsPerRow.value = (width.value + gap.value) / (props.size + gap.value)
if (itemsPerRow.value - Math.floor(itemsPerRow.value) > 0.5) {
itemsPerRow.value = Math.floor(itemsPerRow.value)
} else {
itemsPerRow.value = Math.ceil(itemsPerRow.value)
}
size.value = (width.value - (itemsPerRow.value - 1) * gap.value) / itemsPerRow.value
pixiRef.value.contentHeight = itemsPerCol.value * (size.value + gap.value) - gap.value
})
const renderGraphics = (graphics: Graphics) => {
graphics.clear()
Object.entries(props?.data?.chunks || {})?.map(([index, item]) => {
const { status, createdAt } = item || {}
const row = Math.floor(Number(index) / itemsPerRow.value)
const col = Number(index) % itemsPerRow.value
const x = col * (size.value + gap.value)
const y = row * (size.value + gap.value)
graphics.roundRect(x, y, size.value, size.value, 4)
let color = 0x60a5fa
if (status === 'success') {
color = 0x4ade80
}
if (status === 'error') {
color = 0xf87171
}
graphics.fill(color)
})
}
</script>
<template>
<Pixi ref="pixiRef">
<graphics @render="renderGraphics" />
</Pixi>
</template>

View File

@@ -0,0 +1,14 @@
<script setup lang="ts">
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/en'
import 'dayjs/locale/zh-cn'
dayjs.extend(relativeTime)
const { locale } = useI18n()
watchEffect(() => {
dayjs.locale(locale.value.toLowerCase())
})
</script>

View File

@@ -3,31 +3,32 @@ import { Drawer, DrawerContent } from '@/components/ui/drawer'
import { createVNode } from 'vue'
import useStore from '@/composables/useStore'
const store = useStore('drawer')
const drawer = computed(() => store?._get('drawer'))
const currentDrawer = computed(() => drawer?.value?.[drawer?.value?.length - 1])
const store = useStore()
const currentDrawer = computed(() => store.drawer?.[store.drawer?.length - 1])
const render = computed<() => Component>(() => currentDrawer?.value?.render)
const hide = computed<() => void>(() => currentDrawer?.value?.onClose)
const render = computed(() => currentDrawer?.value?.render)
const hide = computed(() => currentDrawer?.value?.onClose)
const Children = () =>
createVNode(render.value, {
hide: hide?.value,
})
render.value
? createVNode(render.value, {
hide: hide?.value,
})
: null
</script>
<template>
<Drawer
:open="!!drawer?.[drawer?.length - 1]"
:open="!!store.drawer?.[store.drawer?.length - 1]"
@update:open="
(open) => {
if (!open && drawer?.length > 0) {
if (!open && store?.drawer?.length && hide) {
hide()
}
}
"
>
<DrawerContent>
<div class="mx-auto w-full max-w-sm pb-10">
<div class="mx-auto w-full max-w-lg pb-10 px-3">
<Children />
</div>
</DrawerContent>

View File

@@ -1,47 +1,218 @@
<script lang="ts" setup>
import CircularProgress from '@/components/CircularProgress.vue'
import { chunk, get, shuffle, times } from 'lodash-es'
<script setup lang="ts">
import { LucidePlay, LucideSettings, LucideSquare } from 'lucide-vue-next'
import Button from '@/components/ui/button/Button.vue'
import FileUploadBlockProgressView from '@/components/FileUploadBlockProgressView.vue'
import { motion } from 'motion-v'
import getFileSize from '~/lib/getFileSize'
import { cx } from 'class-variance-authority'
import { filesize } from 'filesize'
import asyncWorker from '@/lib/asyncWorker'
import calcFileHashWorker from '@/lib/calcFileHashWorker?worker'
import { clamp, get, groupBy, isEmpty, isNumber, isString, sample, shuffle, times } from 'lodash-es'
import { nanoid } from 'nanoid'
import { toast } from 'vue-sonner'
import asyncWorker from '~/lib/asyncWorker'
import calcFileHashWorker from '~/lib/calcFileHashWorker?worker'
const props = defineProps<{
data: { file: File; config: any; handle_type: string }
}>()
import dayjs from 'dayjs'
import showDrawer from '~/lib/showDrawer'
import FileUploadSpeedInfoView from './FileUploadSpeedInfoView.vue'
import getFileChunk from '~/lib/getFileChunk'
import type { FileHandleKey } from '~/components/Preprocessing/types'
import asyncWait from '@/lib/asyncWait'
const props = defineProps<{
data: { file: File[]; config: Record<string, any>; handle_type: FileHandleKey }
}>()
const emit = defineEmits<{
(e: 'change', key: string): void
}>()
const form = useFormContext()
const step = ref<'hash' | 'upload'>('hash')
const calcHashTime = ref(0)
const chunkSize = ref(0)
const fileSliceUploadStatusList = ref<
const selectedFile = ref()
const uploadfiles = ref<
{
status: string
index: number
fileId: string
id?: string // 后端文件id
file: File
status: 'start' | 'pause' | 'finish' | 'error'
hash?: string
procressType: 'hash' | 'create' | 'upload' | 'finish'
uploadInfo?: {
chunks: Record<number, { status: 'success' | 'error' | 'processing'; createdAt: number }>
chunkLength: number
ChunkSize: number
}
queue: {
taskId: string
taskType: 'hash' | 'create' | 'chunk' | 'upload' | 'finish'
queueType: 'sync' | 'async' // sync任务禁止并发
index?: number
retry?: number
}[]
}[]
>([])
const selectedUploadfile = computed(() => uploadfiles.value.find((item) => item.fileId === selectedFile.value))
const selectedUploadfileChunk = computed(() => Object.values(selectedUploadfile.value?.uploadInfo?.chunks || {}))
const selectedUploadfileViewMode = ref<'progress' | 'heatmap'>('progress')
const successCount = computed(() => fileSliceUploadStatusList.value.filter((item) => item.status === 'success').length)
const alreadyUploadSize = computed(() => Math.min(successCount.value * chunkSize.value, props?.data?.file?.size))
const uploadProgress = computed(() => Math.round((alreadyUploadSize.value / (props?.data?.file?.size || 0)) * 100))
const procressTaskList = ref<Map<string, any>>(new Map())
const activeTaskList = computed(() => uploadfiles.value.filter((r) => r.queue.length > 0 && r.status === 'start'))
const activeTaskAllQueue = computed(() => activeTaskList.value.flatMap((r) => r.queue))
const batchNum = ref(3)
const { error } = useAsyncState(async () => {
const { file } = props.data || {}
if (!file) return
const { size, type = 'application/octet-stream' } = file || {}
const now = Date.now()
const res = await asyncWorker(calcFileHashWorker, { data: { file } })
const { hash } = res?.data || {}
if (hash) {
step.value = 'upload'
calcHashTime.value = Date.now() - now
const totalTaskStatus = computed(() => {
if (uploadfiles.value.some((r) => r.status === 'start')) {
return 'start'
}
if (uploadfiles.value.some((r) => r.status === 'pause')) {
return 'pause'
}
return 'disabled'
})
const totalUploadProgress = computed(() => {
const successCount = uploadfiles.value.reduce((acc, curr) => {
const { status, uploadInfo } = curr || {}
if (status === 'finish') return acc
const { chunks } = uploadInfo || {}
return acc + Object.entries(chunks || {}).filter(([index, chunk]) => chunk.status === 'success').length
}, 0)
const totalCount = uploadfiles.value.reduce((acc, curr) => {
const { status, uploadInfo } = curr || {}
if (status === 'finish') return acc
const { chunkLength } = uploadInfo || {}
return acc + (chunkLength || 0)
}, 0)
return ((successCount || 0) / (totalCount || 0)) * 100
})
const counter = useInterval(1000)
const speedChartData = ref<Record<number, { createdAt: number; value: number }[]>>({})
watch(counter, () => {
const speed = uploadfiles.value?.flatMap((item) => {
const { chunks, ChunkSize } = item?.uploadInfo || {}
return Object.entries(chunks || {})
.filter(([index, chunk]) => chunk.status === 'success' && dayjs().unix() - 60 < chunk.createdAt)
?.map(([index, chunk]) => {
const { createdAt } = chunk || {}
return {
createdAt,
value: ChunkSize || 0,
}
})
})
speedChartData.value = groupBy(speed, 'createdAt')
})
onMounted(() => {
props.data.file.forEach((file) => {
uploadfiles.value.push({
fileId: `${file.name}_${file.size}`,
file,
status: 'start',
procressType: 'hash',
queue: [
{ taskType: 'hash', queueType: 'sync', taskId: nanoid() },
{ taskType: 'create', queueType: 'sync', taskId: nanoid() },
{ taskType: 'chunk', queueType: 'sync', taskId: nanoid() },
],
})
})
})
const { error, execute, isLoading } = useAsyncState(
async () => {
while (activeTaskAllQueue.value.length > 0) {
const taskList = uploadfiles?.value?.filter((r) => r.queue.length > 0 && r.status === 'start')
await asyncWait(10) // 让出主线程防止空转导致ui卡死
await Promise.all(
times(batchNum.value, async (i: number) => {
const file = sample(taskList)
const { fileId, queue } = file || {}
if (!fileId) return
const task = get(queue, '0')
if (!task) return
const { taskId, index, queueType, taskType, retry } = task || {}
if (procressTaskList.value.has(taskId)) return
procressTaskList.value.set(taskId, task)
const uploadFileIndex = uploadfiles.value.findIndex((r) => r.fileId === file?.fileId)
if (queueType === 'async') {
if (!!retry && retry >= 3) {
toast.error('上传错误', {
description: `文件 ${file?.file?.name}${index}分块经过多次尝试依然上传失败, 我们已经终止该文件上传`,
})
uploadfiles.value[uploadFileIndex].status = 'error'
return
}
uploadfiles.value[uploadFileIndex]?.queue.shift()
}
// console.log('[start]', taskType, taskId, queueType)
try {
if (taskType === 'hash') {
await handleHash(fileId)
}
if (taskType === 'create') {
await handleCreate(fileId)
}
if (taskType === 'chunk') {
await handleChunk(fileId)
}
if (taskType === 'upload' && isNumber(index)) {
await handleUpload(fileId, index)
}
if (taskType === 'finish') {
await handleFinish(fileId)
}
// console.log('[finish]', taskType, taskId)
if (queueType === 'sync') {
uploadfiles.value[uploadFileIndex]?.queue.shift()
}
} catch (error) {
console.log('error', error)
// todo 重新加入队列
if (queueType === 'async') {
uploadfiles.value[uploadFileIndex]?.queue.push({ ...task, retry: (task?.retry || 0) + 1 })
toast.warning('上传错误', {
description: `文件 ${file?.file?.name}${index}分块上传失败, 我们将在稍后再次尝试上传`,
})
}
if (queueType === 'sync') {
uploadfiles.value[uploadFileIndex].status = 'error'
toast.error('上传错误', {
description: `文件${file?.file?.name}上传失败, 请重试`,
})
}
} finally {
procressTaskList.value.delete(taskId)
}
})
)
}
},
null,
{ immediate: false }
)
watchEffect(async () => {
if (activeTaskAllQueue.value.length > 0 && !isLoading.value) {
execute()
}
})
const handleHash = async (fileId: string) => {
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
if (!uploadfile?.file) return
uploadfile.procressType = 'hash'
const res = await asyncWorker(calcFileHashWorker, { data: { file: uploadfile.file } })
const { hash } = res?.data || {}
uploadfile.hash = hash
}
const handleCreate = async (fileId: string) => {
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
if (!uploadfile?.file) return
const { hash, file } = uploadfile || {}
if (!hash) return
uploadfile.procressType = 'create'
const { size, type = 'application/octet-stream' } = file || {}
const createData = await $fetch<{
data: {
id: string
@@ -52,66 +223,82 @@ const { error } = useAsyncState(async () => {
method: 'POST',
body: {
size,
mime_type: get(type, '', 'application/octet-stream'),
mime_type: type || 'application/octet-stream',
hash,
},
})
const { id, chunk_size, type: createType } = createData?.data || {}
uploadfile.id = id
uploadfile.uploadInfo = {
chunks: {},
chunkLength: Math.ceil(size / chunk_size),
ChunkSize: chunk_size,
}
if (createType !== 'init') {
// 文件存在
form.setFieldValue('file_id', id)
emit('change', 'result')
uploadfile.status = 'finish'
uploadfile.procressType = 'finish'
uploadfile.queue = []
return
}
chunkSize.value = chunk_size
const chunks = Math.ceil(size / chunk_size)
fileSliceUploadStatusList.value = times(chunks, (i) => ({
status: 'pending',
index: i,
}))
}
const readChunk = (start: number): Promise<ArrayBuffer> => {
const fileReader = new FileReader()
return new Promise((resolve, reject) => {
const chunk = file.slice(start, start + chunk_size)
fileReader.onload = (e) => resolve(e.target?.result as ArrayBuffer)
fileReader.onerror = reject
fileReader.readAsArrayBuffer(chunk)
})
const handleChunk = async (fileId: string) => {
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
if (!uploadfile?.file) return
const { chunkLength } = uploadfile.uploadInfo || {}
if (!chunkLength) return
uploadfile.procressType = 'upload'
const tasks = shuffle(
times(chunkLength, (i: number) => ({ taskType: 'upload' as const, queueType: 'async' as const, taskId: nanoid(), index: i }))
)
uploadfile.queue.push(...tasks)
}
const handleUpload = async (fileId: string, index: number) => {
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
if (!uploadfile?.file) return
const { id, uploadInfo } = uploadfile || {}
const { chunkLength, ChunkSize } = uploadInfo || {}
if (!ChunkSize || !id) return
if (uploadfile.procressType !== 'upload') uploadfile.procressType = 'upload'
let chunkInfo = uploadfile.uploadInfo?.chunks?.[index]
if (!chunkInfo) {
uploadfile.uploadInfo!.chunks[index] = {
status: 'processing',
createdAt: dayjs().unix(),
}
}
const chunkedUploadTasks = chunk(shuffle([...fileSliceUploadStatusList.value]), 3)
for (let i = 0; i < chunkedUploadTasks?.length; i++) {
await Promise.all(
chunkedUploadTasks?.[i]?.map(async (item: any) => {
const { index } = item || {}
try {
const chunk = await readChunk(index * chunk_size)
// console.log('chunk', chunk)
const formData = new FormData()
formData.append('file', new Blob([chunk]))
formData.append('index', index + 1)
formData.append('id', id)
fileSliceUploadStatusList.value[index].status = 'uploading'
const res = await $fetch<{
code: number
}>('/api/file/slice', {
method: 'POST',
body: formData,
})
const { code } = res || {}
if (code !== 200) {
throw new Error('上传失败')
}
fileSliceUploadStatusList.value[index].status = 'success'
} catch (error) {
console.log('error', error)
// fileSliceStatusList.value[index].status = 'error'
}
})
)
const chunk = await getFileChunk(uploadfile.file, index * ChunkSize, ChunkSize)
const formData = new FormData()
formData.append('file', new Blob([chunk]))
formData.append('index', (index + 1).toString())
formData.append('id', id)
const res = await $fetch<{
code: number
}>('/api/file/slice', {
method: 'POST',
body: formData,
})
const { code } = res || {}
if (code !== 200) {
throw new Error('上传失败')
}
const r = await $fetch<{
uploadfile.uploadInfo!.chunks[index].status = 'success'
if (Object.entries(uploadfile.uploadInfo!.chunks || {}).filter(([index, chunk]) => chunk.status === 'success').length === chunkLength) {
uploadfile.queue.push({ taskType: 'finish', queueType: 'sync', taskId: nanoid() })
}
}
const handleFinish = async (fileId: string) => {
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
if (!uploadfile?.file) return
uploadfile.procressType = 'finish'
const { id } = uploadfile || {}
const res = await $fetch<{
code: number
}>('/api/file/finish', {
method: 'POST',
@@ -119,62 +306,264 @@ const { error } = useAsyncState(async () => {
id,
},
})
if (r?.code !== 200) {
if (res?.code !== 200) {
throw new Error('上传失败')
}
form.setFieldValue('file_id', id)
emit('change', 'result')
}, null)
uploadfile.status = 'finish'
}
watch(error, (newVal) => {
if (newVal) {
toast.error('上传失败')
watchEffect(() => {
if (!isEmpty(uploadfiles.value) && uploadfiles.value.every((r) => r.status === 'finish')) {
// console.log('change', uploadfiles.value)
form.setFieldValue(
'files',
uploadfiles.value.map((item) => {
const { id, file } = item || {}
return {
id,
file,
}
})
)
emit('change', 'result')
}
emit('change', 'input')
})
onUnmounted(() => {
uploadfiles.value = []
})
const handleShowSpeedInfo = () => {
showDrawer({
render: ({ hide }) => h(FileUploadSpeedInfoView, { hide }),
})
}
</script>
<template>
<div class="flex flex-col gap-3">
<div class="text-xl font-normal">正在上传</div>
<div class="flex flex-col items-center gap-4 md:flex-row md:justify-evenly">
<div :class="cx('flex flex-row items-center gap-5', step !== 'hash' && 'opacity-50')">
<div class="flex flex-col gap-0.5 items-center">
<div class="text-xs opacity-50">1.计算hash</div>
<div class="text-3xl font-light">
<LucideLoaderCircle v-if="step === 'hash'" class="size-5 my-1 animate-spin" />
<div v-else>{{ calcHashTime }}ms</div>
</div>
<div class="grid grid-cols-4 gap-5">
<div class="rounded-xl p-3 bg-white/80 flex flex-col gap-2 col-span-4 md:col-span-3 h-32 md:h-auto">
<div class="flex flex-col gap-1">
<div @click="handleShowSpeedInfo" class="flex flex-row gap-1 items-center text-xs opacity-70">
总上传进度
<LucideInfo class="size-3" />
</div>
<div class="text-2xl font-bold">
{{
`${
getFileSize(
Object.entries(speedChartData)
?.filter((r) => dayjs().unix() - 60 < parseInt(r[0]))
?.reduce((acc, curr) => acc + curr[1]?.reduce((_acc, _curr) => _acc + _curr.value, 0), 0) / 60
) ?? 0
}/s`
}}
</div>
</div>
<div :class="cx('flex flex-row items-center gap-5 min-w-32', step !== 'upload' && 'opacity-50')">
<CircularProgress :size="80" :value="step !== 'upload' ? 0 : uploadProgress" />
<div class="flex flex-col gap-0.5 items-center">
<div class="text-xs opacity-50">2.上传文件</div>
<div class="text-3xl font-light">{{ step !== 'upload' ? 0 : uploadProgress }}%</div>
<div class="text-sm opacity-50" v-if="alreadyUploadSize">
{{ filesize(alreadyUploadSize) }} / {{ filesize(data?.file?.size) }}
<div class="flex-1 relative overflow-hidden flex flex-row gap-0.5 justify-end items-end">
<motion.div
class="w-2 shrink-0 bg-primary relative"
:style="{
height: `${(i[1]?.reduce((acc, curr) => acc + curr.value, 0) / Math.max(...Object.entries(speedChartData)?.map((r) => r[1]?.reduce((acc, curr) => acc + curr.value, 0)))) * 100}%`,
}"
:layoutId="i[0]"
v-for="i in Object.entries(speedChartData)"
:key="i[0]"
:initial="{ x: 10, opacity: 0 }"
:animate="{ x: 0, opacity: 1 }"
:transition="{ duration: 1 }"
>
</motion.div>
<!-- <BarChart class="h-full" :data="data" index="time" :categories="['value']" :showTooltip="false"
:showLegend="false" :showXAxis="false" :showYAxis="false" :showGrid="false" :groupMaxWidth="10" /> -->
</div>
</div>
<div class="rounded-xl col-span-4 md:col-span-1 bg-white/80 h-32 md:h-auto md:aspect-square flex flex-col gap-2 relative overflow-hidden">
<div class="absolute top-0 left-0 w-full h-full z-[0] flex flex-col justify-end">
<div class="w-full bg-green-100 border-t border-green-500" :style="`height: ${totalUploadProgress || 0}%`"></div>
</div>
<div class="flex flex-col gap-2 justify-between p-3 h-full relative z-[1]">
<div class="flex flex-col gap-1">
<div class="text-xs opacity-70">总上传进度</div>
<div class="text-4xl font-bold">{{ (totalUploadProgress || 0).toFixed(1) }}%</div>
</div>
<div class="flex flex-row gap-2">
<Button
class="aspect-square hover:text-white p-0 bg-green-200 hover:bg-green-300 text-green-500"
:disabled="['start', 'disabled'].includes(totalTaskStatus)"
@click="
() => {
uploadfiles.forEach((r) => {
r.status = 'start'
})
}
"
>
<LucidePlay class="size-1/2" />
</Button>
<Button
class="aspect-square hover:text-white p-0 bg-orange-200 hover:bg-orange-300 text-orange-500"
:disabled="['pause', 'disabled'].includes(totalTaskStatus)"
@click="
() => {
uploadfiles.forEach((r) => {
r.status = 'pause'
})
}
"
>
<LucideSquare class="size-1/2" />
</Button>
<!-- <Button class="aspect-square bg-blue-200 hover:bg-blue-300 text-blue-500 hover:text-white p-0">
<LucideSettings class="size-1/2" />
</Button> -->
</div>
</div>
</div>
<div class="col-span-4 flex flex-col bg-white/80 rounded-xl p-3 text-md gap-5">
<div>文件列表</div>
<div class="flex flex-col -mx-3 text-sm">
<div class="grid grid-cols-[2fr_6rem_6rem] md:grid-cols-[2fr_6rem_6rem_4fr] gap-2 border-b border-black/20 pb-2 px-3">
<div>文件名</div>
<div>文件大小</div>
<div @click="handleShowSpeedInfo" class="flex flex-row gap-1 items-center">
上传速度
<LucideInfo class="size-3" />
</div>
<div class="hidden md:block">进度</div>
</div>
<div
:class="
cx(
'grid grid-cols-[2fr_6rem_6rem] md:grid-cols-[2fr_6rem_6rem_4fr] gap-2 py-2 border-b border-black/20 items-center hover:bg-primary/30 px-3 cursor-pointer',
selectedFile === item?.fileId && 'bg-primary text-white hover:!bg-primary'
)
"
v-for="(item, index) in uploadfiles"
@click="
() => {
if (selectedFile === item?.fileId) {
selectedFile = null
} else {
selectedFile = item?.fileId
}
}
"
>
<div class="flex flex-row gap-2 items-center grow md:grow-0 overflow-hidden">
<Button
class="size-8 p-0 hover:bg-white/50"
variant="ghost"
:disabled="['finish']?.includes(item?.procressType)"
@click="
(e: Event) => {
e.stopPropagation()
if (item?.status === 'start') {
uploadfiles[index].status = 'pause'
} else {
uploadfiles[index].status = 'start'
}
}
"
>
<LucideArrowUpFromLine class="size-4 text-green-500" v-if="item?.status === 'start'" />
<LucideSquare class="size-4 text-gray-500" v-if="item?.status === 'pause'" />
<LucideCircleX class="size-4 text-red-500" v-if="item?.status === 'error'" />
<LucideCheckCircle class="size-4 text-green-500" v-if="item?.status === 'finish'" />
</Button>
<div class="truncate">{{ item?.file?.name }}</div>
</div>
<div>{{ getFileSize(item?.file?.size) }}</div>
<div>
{{
`${getFileSize(
(Object.entries(item?.uploadInfo?.chunks || {})?.filter(
([, chunk]) => chunk.status === 'success' && dayjs().unix() - 60 < chunk.createdAt
)?.length /
60) *
(item?.uploadInfo?.ChunkSize || 0)
)} /s`
}}
</div>
<div
class="flex flex-row gap-2 items-center col-span-3 md:col-span-1"
v-if="['hash', 'create', 'chunk']?.includes(item?.procressType)"
>
<LucideLoaderCircle class="size-4 animate-spin" />
<div>正在{{ item?.procressType }}...</div>
</div>
<div class="flex flex-row gap-2 items-center col-span-3 md:col-span-1" v-if="item?.procressType === 'finish'">
{{ item?.status === 'finish' ? '云端已有相同hash文件, 秒传成功' : null }}
{{ item?.status === 'error' ? '上传失败请稍后重试' : null }}
</div>
<div class="flex flex-row gap-2 items-center col-span-3 md:col-span-1" v-if="item?.procressType === 'upload'">
<div class="rounded-full bg-white/50 w-full h-2 overflow-hidden border border-white">
<div
class="h-full bg-primary"
:style="`width: ${clamp(
((Object.entries(item?.uploadInfo?.chunks || {})?.filter(([index, chunk]) => chunk.status === 'success')
?.length || 0) /
(item?.uploadInfo?.chunkLength || 0)) *
100,
0,
100
)}%`"
></div>
</div>
<div>
{{
clamp(
((Object.entries(item?.uploadInfo?.chunks || {})?.filter(([index, chunk]) => chunk.status === 'success')
?.length || 0) /
(item?.uploadInfo?.chunkLength || 0)) *
100,
0,
100
)?.toFixed(2)
}}%
</div>
</div>
</div>
</div>
</div>
<div class="flex flex-row gap-2 items-baseline">
<div class="text-md font-normal">详细信息</div>
<div class="text-xs opacity-50" v-if="step === 'upload' && fileSliceUploadStatusList?.length > 0">
当前正在上传分块{{ `${successCount}/${Math.ceil(data?.file?.size / chunkSize)}` }} 并发:3
<div class="col-span-4 flex flex-col bg-white/80 rounded-xl p-3 gap-5" v-if="selectedFile">
<div>上传详情</div>
<div class="grid grid-cols-3 text-sm gap-3">
<div>
区块 {{ selectedUploadfile?.uploadInfo?.chunkLength }} x {{ getFileSize(selectedUploadfile?.uploadInfo?.ChunkSize as number) }}
</div>
<div class="truncate col-span-2">hash: {{ selectedUploadfile?.hash }}</div>
<div>已完成: {{ selectedUploadfileChunk?.filter((r) => r.status === 'success')?.length || 0 }}</div>
<div>已丢弃: {{ selectedUploadfileChunk?.filter((r) => r.status === 'error')?.length || 0 }}</div>
<div>
待完成:
{{ (selectedUploadfile?.uploadInfo?.chunkLength || 0) - (selectedUploadfileChunk?.length || 0) }}
</div>
<div class="col-span-3 flex flex-row justify-between items-center">
<div class="text-md font-bold">{{ selectedUploadfileViewMode === 'progress' ? '区块进度条' : '区块热力图' }}</div>
<Button
size="sm"
class="ml-auto text-xs"
@click="selectedUploadfileViewMode = selectedUploadfileViewMode === 'progress' ? 'heatmap' : 'progress'"
>
<LucideArrowDownUp class="size-4" />
{{ selectedUploadfileViewMode === 'progress' ? '热力图' : '进度条' }}
</Button>
</div>
<div class="h-7 col-span-3 flex flex-row gap-2 items-center" v-if="selectedUploadfileViewMode === 'progress'">
<div class="flex-1 h-full">
<FileUploadBlockProgressView :data="selectedUploadfile?.uploadInfo" />
</div>
{{
clamp(((selectedUploadfileChunk?.length || 0) / (selectedUploadfile?.uploadInfo?.chunkLength || 0)) * 100, 0, 100)?.toFixed(
2
)
}}%
</div>
<div v-if="selectedUploadfileViewMode === 'heatmap'" class="col-span-3 bg-black/5 rounded p-2">
<FileUploadHeatMapView :size="12" :data="selectedUploadfile?.uploadInfo" />
</div>
</div>
</div>
<div class="flex flex-row flex-wrap gap-1">
<div
v-for="i in fileSliceUploadStatusList"
:class="
cx(
'rounded size-4 ',
i.status === 'pending' && 'bg-white/90',
i.status === 'uploading' && 'bg-yellow-500',
i.status === 'success' && 'bg-green-500'
)
"
/>
</div>
</div>
</template>

View File

@@ -0,0 +1,8 @@
<template>
<div class="flex flex-col gap-2 pt-3">
<div class="text-xl font-bold">上传速度如何计算</div>
<div class="opacity-75">
上传速度根据当前秒上传了 <b>文件区块的数量</b> * <b>每个文件区块的大小</b> 估算而来可能与真实上传速度有一定的误差仅供参考
</div>
</div>
</template>

View File

@@ -1,74 +1,72 @@
<script lang="ts" setup>
import MarkdownInputField from "@/components/Field/MarkdownInputField.vue";
import FormButton from "@/components/Field/FormButton.vue";
import Button from "@/components/ui/button/Button.vue";
import showDrawer from "@/lib/showDrawer";
import { h } from "vue";
import TextShareDrawer from "@/components/Drawer/TextShareDrawer.vue";
import { cx } from "class-variance-authority";
import PickupShareBtn from "@/components/PickupShareBtn.vue";
const form = useFormContext();
const { t } = useI18n();
import MarkdownInputField from '@/components/Field/MarkdownInputField.vue'
import FormButton from '@/components/Field/FormButton.vue'
import Button from '@/components/ui/button/Button.vue'
import showDrawer from '@/lib/showDrawer'
import { h } from 'vue'
import TextShareDrawer from '@/components/Drawer/TextShareDrawer.vue'
import { cx } from 'class-variance-authority'
import PickupShareBtn from '@/components/PickupShareBtn.vue'
const form = useFormContext()
const { t } = useI18n()
const emit = defineEmits<{
(e: "change", key: string): void;
}>();
(e: 'change', key: string): void
}>()
const handleTextShare = ({ type, config }: { type: string; config: any }) => {
form?.setFieldValue("handle_type", type);
form?.setFieldValue("config", config);
emit("change", "result");
};
form?.setFieldValue('handle_type', type)
form?.setFieldValue('config', config)
emit('change', 'result')
}
</script>
<template>
<div class="gap-5 flex flex-col">
<div class="text-xl font-normal">{{ t("text.uploadText") }}</div>
<div class="relative">
<MarkdownInputField
name="text"
:placeholder="t('text.uploadTextPlaceholder')"
class="max-h-[50vh] min-h-40 overflow-y-auto max-w-full [&>*]:pr-10"
rules="required"
/>
<Button
variant="ghost"
size="icon"
:class="
cx(
'absolute right-2 top-2 hover:bg-black/10 transition-all duration-300',
form?.values.text?.length > 0
? 'opacity-100'
: 'opacity-0 pointer-events-none',
)
"
@click="
() => {
form?.setValues({ text: '' });
}
"
>
<LucideX />
</Button>
<div class="gap-5 flex flex-col">
<div class="text-xl font-normal">{{ t('text.uploadText') }}</div>
<div class="relative">
<MarkdownInputField
name="text"
:placeholder="t('text.uploadTextPlaceholder')"
class="max-h-[50vh] min-h-40 overflow-y-auto max-w-full [&>*]:pr-10 flex flex-col"
rules="required"
/>
<Button
variant="ghost"
size="icon"
:class="
cx(
'absolute right-2 top-2 hover:bg-black/10 transition-all duration-300',
form?.values.text?.length > 0 ? 'opacity-100' : 'opacity-0 pointer-events-none'
)
"
@click="
() => {
form?.setValues({ text: '' })
}
"
>
<LucideX />
</Button>
</div>
<div class="flex flex-row gap-3">
<FormButton
@click="
async (form) => {
const { text } = form?.values || {}
showDrawer({
render: ({ hide }) =>
h(TextShareDrawer, {
hide,
text,
onTextHandle: handleTextShare,
}),
})
}
"
>
<LucideShare class="size-4" />{{ t('btn.submit') }}
</FormButton>
<PickupShareBtn />
</div>
</div>
<div class="flex flex-row gap-3">
<FormButton
@click="
async (form) => {
const { text } = form?.values || {};
showDrawer({
render: ({ hide }) =>
h(TextShareDrawer, {
hide,
text,
onTextHandle: handleTextShare,
}),
});
}
"
>
<LucideShare class="size-4" />{{ t("btn.submit") }}
</FormButton>
<PickupShareBtn />
</div>
</div>
</template>

View File

@@ -11,5 +11,13 @@ const renderHtml = computed(() => {
})
</script>
<template>
<div :class="cx('prose', props?.class)" v-html="renderHtml" />
</template>
<div
:class="
cx(
'prose prose-sm [&>*]:outline-none prose-p:my-1 prose-headings:my-2 prose-pre:mb-0 prose-blockquote:border-black/50 selection:bg-primary/20',
props?.class
)
"
v-html="renderHtml"
/>
</template>

View File

@@ -1,14 +1,21 @@
<script setup lang="ts">
import AsyncButton from '@/components/ui/button/AsyncButton.vue';
import showDrawer from '@/lib/showDrawer';
import PickupShareDrawer from './Drawer/PickupShareDrawer.vue';
import AsyncButton from '@/components/ui/button/AsyncButton.vue'
import showDrawer from '@/lib/showDrawer'
import PickupShareDrawer from './Drawer/PickupShareDrawer.vue'
const { t } = useI18n()
</script>
<template>
<AsyncButton variant="outline" class="gap-2" @click="async()=>{
showDrawer({ render: ({ hide }) => h(PickupShareDrawer, { hide }) })
}">
<AsyncButton
variant="outline"
class="gap-2"
@click="
async () => {
showDrawer({ render: ({ hide }) => h(PickupShareDrawer, { hide }) })
}
"
>
<LucideArchive class="size-4" />
取件
{{ t('pickup.btn') }}
</AsyncButton>
</template>
</template>

47
front/components/Pixi.vue Normal file
View File

@@ -0,0 +1,47 @@
<script setup lang="ts">
import { Application } from 'vue3-pixi'
import { useElementSize, useDevicePixelRatio } from '@vueuse/core'
export interface PixiExpose {
app: Application
width: number
height: number
contentHeight: number
ref: HTMLElement
}
const containerRef = ref<HTMLElement>()
const app = ref<Application>()
const { width: windowWidth, height: windowHeight } = useWindowSize()
const { width: containerWidth, height: containerHeight } = useElementSize(containerRef)
const width = computed(() => Math.min(containerWidth.value, windowWidth.value))
const contentHeight = ref(0)
const height = computed(() => {
if (!contentHeight.value) return Math.min(containerHeight.value, windowHeight.value)
if (containerHeight.value > contentHeight.value) return contentHeight.value
return contentHeight.value
})
const { pixelRatio } = useDevicePixelRatio()
const resolution = computed(() => pixelRatio.value ?? 1)
watchEffect(() => {
if (app.value?.app?.renderer) {
app.value?.app?.renderer?.resize(width.value, height.value)
}
})
defineExpose({
app,
width,
height,
contentHeight,
ref: containerRef,
})
</script>
<template>
<div ref="containerRef" class="w-full h-full">
<Application :width="width" :height="height" :resolution="resolution" ref="app" autoDensity antialias :backgroundAlpha="0">
<slot :width="width" :height="height" />
</Application>
</div>
</template>

View File

@@ -1,66 +1,90 @@
<script setup lang="ts">
import SwitchField from '../Field/SwitchField.vue';
import InputField from '../Field/InputField.vue';
import SelectField from '../Field/SelectField.vue';
import FormButton from '../Field/FormButton.vue';
import SwitchField from '../Field/SwitchField.vue'
import InputField from '../Field/InputField.vue'
import SelectField from '../Field/SelectField.vue'
import FormButton from '../Field/FormButton.vue'
import type { FileShareHandleProps } from './types'
const { t } = useI18n()
const props = defineProps<{
hide: () => void
file: File
onFileHandle: ({ type, config }: { type: string, config: any }) => void
file: File[]
onFileHandle: (props: FileShareHandleProps) => void
}>()
</script>
<template>
<VeeForm v-slot="{ values, setFieldValue }" :initialValues="{ download_nums: 1, expire_time: 1440 }">
<div class="flex flex-col gap-3">
<h2 class="text-lg font-bold">分享选项</h2>
<h2 class="text-lg font-bold">{{ t('fileshare.title') }}</h2>
<div class="flex flex-row items-center gap-2 text-sm">
<SelectField name="download_nums" label="下载次数" :options="[
{ label: '1次下载', value: 1 },
{ label: '2次下载', value: 2 },
{ label: '3次下载', value: 3 },
{ label: '5次下载', value: 5 },
{ label: '10次下载', value: 10 },
]" />
<SelectField name="expire_time" label="过期时间" :options="[
{ label: '5分钟', value: 5 },
{ label: '1小时', value: 60 },
{ label: '1天', value: 1440 },
{ label: '3天', value: 4320 },
]" />
后过期
<SelectField
name="download_nums"
:label="t('fileshare.downloadNums')"
:options="[
{ label: t('fileshare.downloadOptions.1time'), value: 1 },
{ label: t('fileshare.downloadOptions.2times'), value: 2 },
{ label: t('fileshare.downloadOptions.3times'), value: 3 },
{ label: t('fileshare.downloadOptions.5times'), value: 5 },
{ label: t('fileshare.downloadOptions.10times'), value: 10 },
]"
/>
{{ t('fileshare.or') }}
<SelectField
name="expire_time"
:label="t('fileshare.expireTime')"
:options="[
{ label: t('fileshare.expireOptions.5min'), value: 5 },
{ label: t('fileshare.expireOptions.1hour'), value: 60 },
{ label: t('fileshare.expireOptions.1day'), value: 1440 },
{ label: t('fileshare.expireOptions.3days'), value: 4320 },
]"
/>
{{ t('fileshare.expireAfter') }}
</div>
<div class="flex flex-col gap-1">
<div class="flex flex-row gap-3 min-h-9">
<SwitchField name="has_pickup_code" label="取件码" :rules="((value: boolean) => {
if (!!value) {
setFieldValue('has_password', false)
}
return true
})" />
<SwitchField
name="has_pickup_code"
:label="t('fileshare.pickupCode')"
:rules="
(value: boolean) => {
if (!!value) {
setFieldValue('has_password', false)
}
return true
}
"
/>
</div>
<div class="flex flex-row gap-3 min-h-9">
<SwitchField name="has_password" label="密码保护" :rules="((value: boolean) => {
if (!!value) {
setFieldValue('has_pickup_code', false)
}
return true
})" />
<InputField v-if="!!values.has_password" name="password" placeholder="请输入密码" rules="required" />
<SwitchField
name="has_password"
:label="t('fileshare.passwordProtection')"
:rules="
(value: boolean) => {
if (!!value) {
setFieldValue('has_pickup_code', false)
}
return true
}
"
/>
<InputField v-if="!!values.has_password" name="password" :placeholder="t('fileshare.passwordPlaceholder')" rules="required" />
</div>
<div class="flex flex-row gap-3 min-h-9">
<SwitchField name="has_notify" label="下载通知" />
<InputField v-if="!!values.has_notify" name="notify_email" placeholder="请输入邮箱"
rules="required" />
<SwitchField name="has_notify" :label="t('fileshare.downloadNotify')" />
<InputField v-if="!!values.has_notify" name="notify_email" :placeholder="t('fileshare.emailPlaceholder')" rules="required" />
</div>
</div>
<FormButton @click="async (form) => {
onFileHandle({ type: 'file-share', config: values })
hide()
}">提交</FormButton>
<FormButton
@click="
async (form) => {
onFileHandle({ type: 'file-share', config: values })
hide()
}
"
>{{ t('btn.submit') }}</FormButton
>
</div>
</VeeForm>
</template>
</template>

View File

@@ -1,65 +1,90 @@
<script setup lang="ts">
import SwitchField from '../Field/SwitchField.vue';
import InputField from '../Field/InputField.vue';
import SelectField from '../Field/SelectField.vue';
import FormButton from '../Field/FormButton.vue';
import SwitchField from '../Field/SwitchField.vue'
import InputField from '../Field/InputField.vue'
import SelectField from '../Field/SelectField.vue'
import FormButton from '../Field/FormButton.vue'
import type { TextShareHandleProps } from './types'
const { t } = useI18n()
const props = defineProps<{
hide: () => void
text: string
onTextHandle: ({ type, config }: { type: string, config: any }) => void
onTextHandle: (props: TextShareHandleProps) => void
}>()
</script>
<template>
<VeeForm v-slot="{ values, setFieldValue }" :initialValues="{ download_nums: 1, expire_time: 1440 }">
<div class="flex flex-col gap-3">
<h2 class="text-lg font-bold">分享选项</h2>
<h2 class="text-lg font-bold">{{ t('textshare.title') }}</h2>
<div class="flex flex-row items-center gap-2 text-sm">
<SelectField name="download_nums" label="浏览次数" :options="[
{ label: '1次浏览', value: 1 },
{ label: '2次浏览', value: 2 },
{ label: '3次浏览', value: 3 },
{ label: '5次浏览', value: 5 },
{ label: '10次浏览', value: 10 },
]" />
<SelectField name="expire_time" label="过期时间" :options="[
{ label: '5分钟', value: 5 },
{ label: '1小时', value: 60 },
{ label: '1天', value: 1440 },
{ label: '3天', value: 4320 },
]" />
后过期
<SelectField
name="download_nums"
:label="t('textshare.viewNums')"
:options="[
{ label: t('textshare.viewOptions.1time'), value: 1 },
{ label: t('textshare.viewOptions.2times'), value: 2 },
{ label: t('textshare.viewOptions.3times'), value: 3 },
{ label: t('textshare.viewOptions.5times'), value: 5 },
{ label: t('textshare.viewOptions.10times'), value: 10 },
]"
/>
{{ t('textshare.or') }}
<SelectField
name="expire_time"
:label="t('textshare.expireTime')"
:options="[
{ label: t('textshare.expireOptions.5min'), value: 5 },
{ label: t('textshare.expireOptions.1hour'), value: 60 },
{ label: t('textshare.expireOptions.1day'), value: 1440 },
{ label: t('textshare.expireOptions.3days'), value: 4320 },
]"
/>
{{ t('textshare.expireAfter') }}
</div>
<div class="flex flex-col gap-1">
<div class="flex flex-row gap-3 min-h-9">
<SwitchField name="has_pickup_code" label="取件码" :rules="((value: boolean) => {
if (!!value) {
setFieldValue('has_password', false)
}
return true
})" />
<SwitchField
name="has_pickup_code"
:label="t('textshare.pickupCode')"
:rules="
(value: boolean) => {
if (!!value) {
setFieldValue('has_password', false)
}
return true
}
"
/>
</div>
<div class="flex flex-row gap-3 min-h-9">
<SwitchField name="has_password" label="密码保护" :rules="((value: boolean) => {
if (!!value) {
setFieldValue('has_pickup_code', false)
}
return true
})" />
<InputField v-if="!!values.has_password" name="password" placeholder="请输入密码" rules="required" />
<SwitchField
name="has_password"
:label="t('textshare.passwordProtection')"
:rules="
(value: boolean) => {
if (!!value) {
setFieldValue('has_pickup_code', false)
}
return true
}
"
/>
<InputField v-if="!!values.has_password" name="password" :placeholder="t('textshare.passwordPlaceholder')" rules="required" />
</div>
<div class="flex flex-row gap-3 min-h-9">
<SwitchField name="has_notify" label="已读通知" />
<InputField v-if="!!values.has_notify" name="notify_email" placeholder="请输入邮箱"
rules="required" />
<SwitchField name="has_notify" :label="t('textshare.readNotify')" />
<InputField v-if="!!values.has_notify" name="notify_email" :placeholder="t('textshare.emailPlaceholder')" rules="required" />
</div>
</div>
<FormButton @click="async (form) => {
onTextHandle({ type: 'text-share', config: values })
hide()
}">提交</FormButton>
<FormButton
@click="
async (form) => {
onTextHandle({ type: 'text-share', config: values })
hide()
}
"
>{{ t('btn.submit') }}</FormButton
>
</div>
</VeeForm>
</template>
</template>

View File

@@ -0,0 +1,5 @@
export type FileHandleKey = 'file-share' | 'file-image-compress'
export type FileShareHandleProps = { type: FileHandleKey; config: Record<string, any> }
export type TextHandleKey = 'text-share'
export type TextShareHandleProps = { type: TextHandleKey; config: Record<string, any> }

View File

@@ -1,152 +1,212 @@
<script setup lang="ts">
import { Button } from "@/components/ui/button";
import FilePreviewView from "@/components/FilePreviewView.vue";
import { Input } from "@/components/ui/input";
import { useClipboard } from "@vueuse/core";
import { toast } from "vue-sonner";
import { useQuery } from "@tanstack/vue-query";
import useMyAppShare from "@/composables/useMyAppShare";
import useMyAppConfig from "@/composables/useMyAppConfig";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn"; // 导入中文语言包
import showDrawer from "@/lib/showDrawer";
import QrCoreDrawer from "@/components/Drawer/QrCoreDrawer.vue";
dayjs.extend(relativeTime); // 扩展 relativeTime 插件
dayjs.locale("zh-cn"); // 设置语言为中文
import { Button } from '@/components/ui/button'
import FilePreviewView from '@/components/FilePreviewView.vue'
import { Input } from '@/components/ui/input'
import { useClipboard } from '@vueuse/core'
import { toast } from 'vue-sonner'
import { useQuery } from '@tanstack/vue-query'
import useMyAppShare from '@/composables/useMyAppShare'
import useMyAppConfig from '@/composables/useMyAppConfig'
import dayjs from 'dayjs'
import showDrawer from '@/lib/showDrawer'
import QrCoreDrawer from '@/components/Drawer/QrCoreDrawer.vue'
import { h } from 'vue'
import { cx } from 'class-variance-authority'
import type { FileHandleKey } from '../Preprocessing/types'
const props = defineProps<{
data: { file: File; config: any; handle_type: string; file_id: string };
}>();
data: { files: { id: string; file: File }[]; config: Record<string, any>; handle_type: FileHandleKey }
}>()
const emit = defineEmits<{
(e: "change", key: string): void;
}>();
const { createFileShare } = useMyAppShare();
(e: 'change', key: string): void
}>()
const { t } = useI18n()
const { createFileShare } = useMyAppShare()
const { data } = useQuery({
queryKey: ["create-share", props?.data?.file_id],
queryFn: async () => {
const { file_id, config, file } = props?.data || {};
const { name } = file || {};
const data = await createFileShare({
file_id,
config,
file_name: name,
});
return data?.data;
},
});
queryKey: ['create-share', ...props?.data?.files?.map((item) => item.id)],
queryFn: async () => {
const { files, config } = props?.data || {}
const data = await createFileShare({
files: files?.map((item) => {
const { id, file } = item || {}
return { id, name: file.name }
}),
config: config as any,
})
return data?.map((item) => item?.data)
},
})
const selectedFile = ref<string | undefined>()
const selectedFileShare = computed(() => {
return data?.value?.find((item) => item?.id === selectedFile.value)
})
watchEffect(() => {
if (data?.value && data?.value?.length === 1 && !!data?.value?.[0]?.id) {
selectedFile.value = data.value[0].id
}
})
const appConfig = useMyAppConfig();
const url = computed(() => {
const { id } = data?.value || {};
return `${appConfig?.value?.site_url}/s/${id}`;
});
watchEffect(() => {
console.log('data', data?.value)
})
const { copy } = useClipboard();
const appConfig = useMyAppConfig()
const getShareUrl = (id: string) => {
return `${appConfig?.value?.site_url}/s/${id}`
}
const { copy } = useClipboard()
</script>
<template>
<div class="flex flex-col gap-3">
<h2 class="text-lg">上传成功</h2>
<div class="flex flex-col gap-3 items-center">
<div class="flex flex-col h-30 items-center">
<FilePreviewView :value="props?.data?.file" />
</div>
<div
class="flex flex-col md:flex-row gap-5 rounded-md p-5 bg-white/20 backdrop-blur-xl w-full"
>
<div class="flex flex-col gap-2 flex-1">
<div class="text-sm font-semibold">信息</div>
<div class="grid grid-cols-2 gap-2">
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1">
<div class="text-xs font-semibold">下载次数</div>
<div class="text-3xl font-light">{{ data?.download_nums }}</div>
<div class="flex flex-col gap-3">
<h2 class="text-lg">{{ t('fileshareresult.title') }}</h2>
<div class="flex flex-col gap-3 items-center">
<div v-if="data?.length === 1" class="flex flex-col h-30 items-center">
<FilePreviewView :value="props?.data?.files?.[0]?.file as File" />
</div>
<div class="rounded-xl flex flex-col bg-black/5 px-3 py-2 gap-1">
<div class="text-xs font-semibold">过期时间</div>
<div class="text-md font-light">
{{
dayjs(data?.expire_at * 1000).format("YYYY-MM-DD HH:mm:ss")
}}
</div>
</div>
<div
class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1"
v-if="data?.pickup_code"
>
<div class="flex flex-row justify-between w-full items-center">
<div class="text-xs font-semibold">提取码</div>
<Button
variant="outline"
class="bg-white/70 p-0 size-6"
size="icon"
@click="
() => {
copy(data?.pickup_code);
toast.success('复制成功');
}
"
<div v-else class="flex flex-col gap-2 w-full p-5 bg-white/20 backdrop-blur-xl rounded-md">
<div class="text-sm font-semibold">{{ t('fileshareresult.fileList') }}</div>
<div
v-for="file in data"
:class="
cx(
'flex flex-row justify-between items-center gap-1 rounded-md p-2 border border-black/10 w-full cursor-pointer',
selectedFile === file?.id && 'bg-primary text-white'
)
"
@click="selectedFile = file?.id"
>
<LucideCopy class="size-3" />
</Button>
</div>
<div class="flex flex-row gap-2">
<div v-for="s in data?.pickup_code" class="text-2xl font-light">
{{ s }}
<div class="flex flex-row items-center gap-2 flex-1 min-w-0">
<FileIcon
:file="props?.data?.files?.[data?.findIndex((i) => i?.id === file?.id) as number]?.file as File"
:class="cx('!size-7 !rounded-md shrink-0', selectedFile === file?.id && '!bg-white/50')"
/>
<div class="text-sm flex-1 truncate">{{ file?.file_name }}</div>
</div>
<div class="flex flex-row items-center gap-2 shrink-0">
<Button
variant="outline"
:class="cx('bg-white/70', selectedFile === file?.id && '!bg-white/30 border-none hover:text-white/80')"
size="icon"
@click="
() => {
copy(getShareUrl(file?.id as string))
toast.success(t('fileshareresult.copySuccess'))
}
"
>
<LucideCopy />
</Button>
<Button
variant="outline"
:class="cx('bg-white/70', selectedFile === file?.id && '!bg-white/30 border-none hover:text-white/80')"
size="icon"
@click="
() => {
showDrawer({
render: ({ ...rest }) =>
h(QrCoreDrawer, {
...rest,
data: getShareUrl(file?.id as string),
}),
})
}
"
>
<LucideQrCode />
</Button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="flex flex-col gap-5 flex-1">
<div class="text-sm font-semibold">链接</div>
<div class="flex flex-row gap-2">
<Input v-model="url" class="bg-white/70" readonly />
<Button
variant="outline"
class="bg-white/70"
size="icon"
@click="
() => {
copy(url);
toast.success('复制成功');
}
"
>
<LucideCopy />
</Button>
<div v-if="!!selectedFileShare" class="flex flex-col md:flex-row gap-5 rounded-md p-5 bg-white/20 backdrop-blur-xl w-full">
<div class="flex flex-col gap-2 flex-1">
<div class="text-sm font-semibold">{{ t('fileshareresult.info') }}</div>
<div class="grid grid-cols-2 gap-2">
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1">
<div class="text-xs font-semibold">{{ t('fileshareresult.downloadNums') }}</div>
<div class="text-3xl font-light">{{ selectedFileShare?.download_nums }}</div>
</div>
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1">
<div class="text-xs font-semibold">{{ t('fileshareresult.expireTime') }}</div>
<div class="text-md font-light">
{{ dayjs((selectedFileShare?.expire_at || 0) * 1000).format('YYYY-MM-DD HH:mm:ss') }}
</div>
</div>
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1" v-if="selectedFileShare?.pickup_code">
<div class="flex flex-row justify-between w-full items-center">
<div class="text-xs font-semibold">{{ t('fileshareresult.pickupCode') }}</div>
<Button
variant="outline"
class="bg-white/70 p-0 size-6"
size="icon"
@click="
() => {
copy(selectedFileShare?.pickup_code as string)
toast.success(t('fileshareresult.copySuccess'))
}
"
>
<LucideCopy class="size-3" />
</Button>
</div>
<div class="flex flex-row gap-2">
<div v-for="s in selectedFileShare?.pickup_code" class="text-2xl font-light">
{{ s }}
</div>
</div>
</div>
</div>
</div>
<div class="flex flex-col gap-5 flex-1">
<div class="text-sm font-semibold">{{ t('fileshareresult.link') }}</div>
<div class="flex flex-row gap-2">
<Input :model-value="getShareUrl(selectedFileShare?.id as string)" class="bg-white/70" readonly />
<Button
variant="outline"
class="bg-white/70"
size="icon"
@click="
() => {
copy(getShareUrl(selectedFileShare?.id as string))
toast.success(t('fileshareresult.copySuccess'))
}
"
>
<LucideCopy />
</Button>
<Button
variant="outline"
class="bg-white/70"
size="icon"
@click="
() => {
showDrawer({
render: ({ ...rest }) =>
h(QrCoreDrawer, {
...rest,
data: getShareUrl(selectedFileShare?.id as string),
}),
})
}
"
>
<LucideQrCode />
</Button>
</div>
</div>
</div>
<Button
variant="outline"
class="bg-white/70"
size="icon"
@click="
() => {
showDrawer({
render: ({ ...rest }) =>
h(QrCoreDrawer, {
...rest,
data: url,
}),
});
}
"
class="w-40 hover:bg-primary/90"
@click="
() => {
emit('change', 'input')
}
"
>
<LucideQrCode />
{{ t('btn.backToHome') }}
</Button>
</div>
</div>
</div>
<Button
class="hover:bg-white/50 w-40"
@click="
() => {
emit('change', 'input');
}
"
>
确定
</Button>
</div>
</div>
</template>

View File

@@ -1,45 +1,37 @@
<script lang="ts" setup>
import FileShareResult from "@/components/Result/FileShareResult.vue";
import TextShareResult from "@/components/Result/TextShareResult.vue";
import ImageCompressResult from "@/components/Result/ImageCompressResult.vue";
import FileShareResult from '@/components/Result/FileShareResult.vue'
import TextShareResult from '@/components/Result/TextShareResult.vue'
import ImageCompressResult from '@/components/Result/ImageCompressResult.vue'
import type { FileHandleKey, TextHandleKey } from '../Preprocessing/types'
type basehandleData = { config: any; handle_type: string };
type basehandleData = { config: Record<string, any> }
type filehandleData = { file: File; file_id: string } & basehandleData;
type texthandleData = { text: string } & basehandleData;
type filehandleData = { files: { id: string; file: File }[]; handle_type: FileHandleKey } & basehandleData
type texthandleData = { text: string; handle_type: TextHandleKey } & basehandleData
type handleKey = 'file-share' | 'text-share' | 'file-image-compress'
const props = defineProps<{
data: filehandleData | texthandleData;
}>();
data: filehandleData | texthandleData
}>()
const emit = defineEmits<{
(e: "change", key: string): void;
}>();
(e: 'change', key: string): void
}>()
const handleList = [
{ component: FileShareResult, key: "file-share" },
{ component: TextShareResult, key: "text-share" },
{ component: ImageCompressResult, key: "file-image-compress" },
];
const handleList: { component: Component<{ data: filehandleData | texthandleData }>; key: handleKey }[] = [
{ component: FileShareResult, key: 'file-share' },
{ component: TextShareResult, key: 'text-share' },
{ component: ImageCompressResult, key: 'file-image-compress' },
]
const activeHandle = computed(() => {
return handleList.find((item) => item.key === props?.data?.handle_type);
});
return handleList.find((item) => item.key === props?.data?.handle_type)
})
// vue这个ts蠢的没边了本来想写component: FileShareResult | TextShareResult结果不行
</script>
<template>
<div>
<component
v-if="'file' in data"
:is="activeHandle?.component"
:data="data"
@change="(key: string) => emit('change', key)"
/>
<component
v-if="'text' in data"
:is="activeHandle?.component"
:data="data"
@change="(key: string) => emit('change', key)"
/>
</div>
<div>
<component v-if="'file' in data" :is="activeHandle?.component" :data="data" @change="(key: string) => emit('change', key)" />
<component v-if="'text' in data" :is="activeHandle?.component" :data="data" @change="(key: string) => emit('change', key)" />
</div>
</template>

View File

@@ -9,9 +9,11 @@ import useMyAppConfig from '@/composables/useMyAppConfig'
import showDrawer from '@/lib/showDrawer'
import QrCoreDrawer from '@/components/Drawer/QrCoreDrawer.vue'
import dayjs from 'dayjs'
import { h } from 'vue'
import type { TextHandleKey } from '../Preprocessing/types'
const props = defineProps<{
data: { text: string; config: any; handle_type: string }
data: { text: string; config: Record<string, any>; handle_type: TextHandleKey }
}>()
const emit = defineEmits<{
@@ -38,13 +40,14 @@ const url = computed(() => {
})
const { copy } = useClipboard()
const { t } = useI18n()
</script>
<template>
<div class="flex flex-col gap-3">
<div class="flex flex-row gap-2">
<div class="flex flex-row justify-between w-full">
<h2 class="text-lg">分享成功</h2>
<h2 class="text-lg">{{ t('textshareresult.title') }}</h2>
<Button
variant="outline"
class="bg-white/70"
@@ -61,21 +64,21 @@ const { copy } = useClipboard()
</div>
<div class="flex flex-col md:flex-row gap-5 rounded-md p-5 bg-white/20 backdrop-blur-xl w-full">
<div class="flex flex-col gap-2 flex-1">
<div class="text-sm font-semibold">信息</div>
<div class="text-sm font-semibold">{{ t('textshareresult.info') }}</div>
<div class="grid grid-cols-2 gap-2">
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1">
<div class="text-xs font-semibold">下载次数</div>
<div class="text-xs font-semibold">{{ t('textshareresult.viewNums') }}</div>
<div class="text-3xl font-light">{{ data?.download_nums }}</div>
</div>
<div class="rounded-xl flex flex-col bg-black/5 px-3 py-2 gap-1">
<div class="text-xs font-semibold">过期时间</div>
<div class="text-xs font-semibold">{{ t('textshareresult.expireTime') }}</div>
<div class="text-md font-light">
{{ dayjs((data?.expire_at ?? 0) * 1000).format('YYYY-MM-DD HH:mm:ss') }}
</div>
</div>
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1" v-if="data?.pickup_code">
<div class="flex flex-row justify-between w-full items-center">
<div class="text-xs font-semibold">提取码</div>
<div class="text-xs font-semibold">{{ t('textshareresult.pickupCode') }}</div>
<Button
variant="outline"
class="bg-white/70 p-0 size-6"
@@ -83,7 +86,7 @@ const { copy } = useClipboard()
@click="
() => {
copy(data?.pickup_code as string)
toast.success('复制成功')
toast.success(t('textshareresult.copySuccess'))
}
"
>
@@ -99,7 +102,7 @@ const { copy } = useClipboard()
</div>
</div>
<div class="flex flex-col gap-5 flex-1">
<div class="text-sm font-semibold">链接</div>
<div class="text-sm font-semibold">{{ t('textshareresult.link') }}</div>
<div class="flex flex-row gap-2">
<Input v-model="url" class="bg-white/70" readonly />
<Button
@@ -109,7 +112,7 @@ const { copy } = useClipboard()
@click="
() => {
copy(url)
toast.success('复制成功')
toast.success(t('textshareresult.copySuccess'))
}
"
>
@@ -137,7 +140,7 @@ const { copy } = useClipboard()
</div>
</div>
</div>
<h2 class="text-md">内容</h2>
<h2 class="text-md">{{ t('textshareresult.content') }}</h2>
<MarkdownRender class="prose rounded-md bg-white/70 p-3 w-full max-w-full min-h-[30vh]" :markdown="props?.data?.text" />
</div>
</template>

View File

@@ -1,40 +0,0 @@
<script setup lang="ts">
import { Editor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import { Markdown } from 'tiptap-markdown';
import Placeholder from '@tiptap/extension-placeholder'
const props = defineProps<{
modelValue: string
placeholder?: string
}>()
const emit = defineEmits<{
(e: 'update:modelValue', value: string): void
}>()
const editor = ref<Editor | undefined>(undefined)
onMounted(() => {
editor.value = new Editor({
content: props.modelValue,
extensions: [StarterKit, Markdown.configure({
transformPastedText: true,
transformCopiedText: true
}), Placeholder.configure({
placeholder: props.placeholder ?? ''
})],
onUpdate: () => {
// HTML
emit('update:modelValue', editor.value?.storage?.markdown?.getMarkdown() ?? '')
}
})
})
watch(() => props.modelValue, (value) => {
editor.value?.commands.setContent(value)
})
onUnmounted(() => {
editor.value?.destroy()
})
</script>
<template>
<editor-content :editor="editor" class="prose prose-sm bg-white/50 rounded-md p-2 [&>*]:outline-none prose-p:my-1" />
</template>

View File

@@ -0,0 +1,60 @@
<script setup lang="ts">
import { Editor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import { Markdown } from 'tiptap-markdown'
import Placeholder from '@tiptap/extension-placeholder'
import { cx } from 'class-variance-authority'
const props = defineProps<{
modelValue?: string
placeholder?: string
class?: string
}>()
const emit = defineEmits<{
(e: 'update:modelValue', value: string): void
}>()
const editor = ref<Editor | undefined>(undefined)
onMounted(() => {
editor.value = new Editor({
content: props.modelValue,
extensions: [
StarterKit,
Markdown.configure({
transformPastedText: true,
transformCopiedText: true,
}),
Placeholder.configure({
placeholder: props.placeholder ?? '',
}),
// CommandsPlugin,
],
onUpdate: () => {
emit('update:modelValue', (editor.value as any)?.storage?.markdown?.getMarkdown() ?? '')
},
})
})
watch(
() => props.modelValue,
(value) => {
if (value !== (editor.value as any)?.storage?.markdown?.getMarkdown()) {
editor.value?.commands.setContent(value ?? '')
}
}
)
onUnmounted(() => {
editor.value?.destroy()
})
</script>
<template>
<editor-content
:editor="editor as any"
:class="
cx(
'prose prose-sm bg-white/50 rounded-md p-2 [&>*]:outline-none prose-p:my-1 prose-headings:my-2 prose-pre:mb-0 prose-blockquote:border-black/50 selection:bg-primary/20 max-w-full',
props.class
)
"
>
</editor-content>
</template>

View File

@@ -0,0 +1,15 @@
<script setup lang="ts">
import type { AccordionRootEmits, AccordionRootProps } from 'reka-ui'
import { AccordionRoot, useForwardPropsEmits } from 'reka-ui'
const props = defineProps<AccordionRootProps>()
const emits = defineEmits<AccordionRootEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<AccordionRoot data-slot="accordion" v-bind="forwarded">
<slot />
</AccordionRoot>
</template>

View File

@@ -0,0 +1,23 @@
<script setup lang="ts">
import type { AccordionContentProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { AccordionContent } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<AccordionContentProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = reactiveOmit(props, 'class')
</script>
<template>
<AccordionContent
data-slot="accordion-content"
v-bind="delegatedProps"
class="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
>
<div :class="cn('pt-0 pb-4', props.class)">
<slot />
</div>
</AccordionContent>
</template>

View File

@@ -0,0 +1,19 @@
<script setup lang="ts">
import type { AccordionItemProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { AccordionItem, useForwardProps } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<AccordionItemProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = reactiveOmit(props, 'class')
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<AccordionItem data-slot="accordion-item" v-bind="forwardedProps" :class="cn('border-b last:border-b-0', props.class)">
<slot />
</AccordionItem>
</template>

View File

@@ -0,0 +1,32 @@
<script setup lang="ts">
import type { AccordionTriggerProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { ChevronDown } from 'lucide-vue-next'
import { AccordionHeader, AccordionTrigger } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<AccordionTriggerProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = reactiveOmit(props, 'class')
</script>
<template>
<AccordionHeader class="flex">
<AccordionTrigger
data-slot="accordion-trigger"
v-bind="delegatedProps"
:class="
cn(
'focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180',
props.class
)
"
>
<slot />
<slot name="icon">
<ChevronDown class="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
</slot>
</AccordionTrigger>
</AccordionHeader>
</template>

View File

@@ -0,0 +1,4 @@
export { default as Accordion } from './Accordion.vue'
export { default as AccordionContent } from './AccordionContent.vue'
export { default as AccordionItem } from './AccordionItem.vue'
export { default as AccordionTrigger } from './AccordionTrigger.vue'

View File

@@ -0,0 +1,15 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { AvatarRoot } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<AvatarRoot data-slot="avatar" :class="cn('relative flex size-8 shrink-0 overflow-hidden rounded-full', props.class)">
<slot />
</AvatarRoot>
</template>

View File

@@ -0,0 +1,21 @@
<script setup lang="ts">
import type { AvatarFallbackProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { AvatarFallback } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<AvatarFallbackProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = reactiveOmit(props, 'class')
</script>
<template>
<AvatarFallback
data-slot="avatar-fallback"
v-bind="delegatedProps"
:class="cn('bg-muted flex size-full items-center justify-center rounded-full', props.class)"
>
<slot />
</AvatarFallback>
</template>

View File

@@ -0,0 +1,12 @@
<script setup lang="ts">
import type { AvatarImageProps } from 'reka-ui'
import { AvatarImage } from 'reka-ui'
const props = defineProps<AvatarImageProps>()
</script>
<template>
<AvatarImage data-slot="avatar-image" v-bind="props" class="aspect-square size-full">
<slot />
</AvatarImage>
</template>

View File

@@ -0,0 +1,3 @@
export { default as Avatar } from './Avatar.vue'
export { default as AvatarFallback } from './AvatarFallback.vue'
export { default as AvatarImage } from './AvatarImage.vue'

View File

@@ -0,0 +1,15 @@
<script setup lang="ts">
import type { DropdownMenuRootEmits, DropdownMenuRootProps } from 'reka-ui'
import { DropdownMenuRoot, useForwardPropsEmits } from 'reka-ui'
const props = defineProps<DropdownMenuRootProps>()
const emits = defineEmits<DropdownMenuRootEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<DropdownMenuRoot data-slot="dropdown-menu" v-bind="forwarded">
<slot />
</DropdownMenuRoot>
</template>

View File

@@ -0,0 +1,35 @@
<script setup lang="ts">
import type { DropdownMenuCheckboxItemEmits, DropdownMenuCheckboxItemProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { Check } from 'lucide-vue-next'
import { DropdownMenuCheckboxItem, DropdownMenuItemIndicator, useForwardPropsEmits } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuCheckboxItemProps & { class?: HTMLAttributes['class'] }>()
const emits = defineEmits<DropdownMenuCheckboxItemEmits>()
const delegatedProps = reactiveOmit(props, 'class')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<DropdownMenuCheckboxItem
data-slot="dropdown-menu-checkbox-item"
v-bind="forwarded"
:class="
cn(
'focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=\'size-\'])]:size-4',
props.class
)
"
>
<span class="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuItemIndicator>
<Check class="size-4" />
</DropdownMenuItemIndicator>
</span>
<slot />
</DropdownMenuCheckboxItem>
</template>

View File

@@ -0,0 +1,33 @@
<script setup lang="ts">
import type { DropdownMenuContentEmits, DropdownMenuContentProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { DropdownMenuContent, DropdownMenuPortal, useForwardPropsEmits } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = withDefaults(defineProps<DropdownMenuContentProps & { class?: HTMLAttributes['class'] }>(), {
sideOffset: 4,
})
const emits = defineEmits<DropdownMenuContentEmits>()
const delegatedProps = reactiveOmit(props, 'class')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<DropdownMenuPortal>
<DropdownMenuContent
data-slot="dropdown-menu-content"
v-bind="forwarded"
:class="
cn(
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--reka-dropdown-menu-content-available-height) min-w-[8rem] origin-(--reka-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md',
props.class
)
"
>
<slot />
</DropdownMenuContent>
</DropdownMenuPortal>
</template>

View File

@@ -0,0 +1,12 @@
<script setup lang="ts">
import type { DropdownMenuGroupProps } from 'reka-ui'
import { DropdownMenuGroup } from 'reka-ui'
const props = defineProps<DropdownMenuGroupProps>()
</script>
<template>
<DropdownMenuGroup data-slot="dropdown-menu-group" v-bind="props">
<slot />
</DropdownMenuGroup>
</template>

View File

@@ -0,0 +1,41 @@
<script setup lang="ts">
import type { DropdownMenuItemProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { DropdownMenuItem, useForwardProps } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = withDefaults(
defineProps<
DropdownMenuItemProps & {
class?: HTMLAttributes['class']
inset?: boolean
variant?: 'default' | 'destructive'
}
>(),
{
variant: 'default',
}
)
const delegatedProps = reactiveOmit(props, 'inset', 'variant', 'class')
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<DropdownMenuItem
data-slot="dropdown-menu-item"
:data-inset="inset ? '' : undefined"
:data-variant="variant"
v-bind="forwardedProps"
:class="
cn(
'focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive-foreground data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/40 data-[variant=destructive]:focus:text-destructive-foreground data-[variant=destructive]:*:[svg]:!text-destructive-foreground [&_svg:not([class*=\'text-\'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=\'size-\'])]:size-4',
props.class
)
"
>
<slot />
</DropdownMenuItem>
</template>

View File

@@ -0,0 +1,23 @@
<script setup lang="ts">
import type { DropdownMenuLabelProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { DropdownMenuLabel, useForwardProps } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuLabelProps & { class?: HTMLAttributes['class']; inset?: boolean }>()
const delegatedProps = reactiveOmit(props, 'class', 'inset')
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<DropdownMenuLabel
data-slot="dropdown-menu-label"
:data-inset="inset ? '' : undefined"
v-bind="forwardedProps"
:class="cn('px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', props.class)"
>
<slot />
</DropdownMenuLabel>
</template>

View File

@@ -0,0 +1,15 @@
<script setup lang="ts">
import type { DropdownMenuRadioGroupEmits, DropdownMenuRadioGroupProps } from 'reka-ui'
import { DropdownMenuRadioGroup, useForwardPropsEmits } from 'reka-ui'
const props = defineProps<DropdownMenuRadioGroupProps>()
const emits = defineEmits<DropdownMenuRadioGroupEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<DropdownMenuRadioGroup data-slot="dropdown-menu-radio-group" v-bind="forwarded">
<slot />
</DropdownMenuRadioGroup>
</template>

View File

@@ -0,0 +1,36 @@
<script setup lang="ts">
import type { DropdownMenuRadioItemEmits, DropdownMenuRadioItemProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { Circle } from 'lucide-vue-next'
import { DropdownMenuItemIndicator, DropdownMenuRadioItem, useForwardPropsEmits } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuRadioItemProps & { class?: HTMLAttributes['class'] }>()
const emits = defineEmits<DropdownMenuRadioItemEmits>()
const delegatedProps = reactiveOmit(props, 'class')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<DropdownMenuRadioItem
data-slot="dropdown-menu-radio-item"
v-bind="forwarded"
:class="
cn(
'focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=\'size-\'])]:size-4',
props.class
)
"
>
<span class="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuItemIndicator>
<Circle class="size-2 fill-current" />
</DropdownMenuItemIndicator>
</span>
<slot />
</DropdownMenuRadioItem>
</template>

View File

@@ -0,0 +1,19 @@
<script setup lang="ts">
import type { DropdownMenuSeparatorProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { DropdownMenuSeparator } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<
DropdownMenuSeparatorProps & {
class?: HTMLAttributes['class']
}
>()
const delegatedProps = reactiveOmit(props, 'class')
</script>
<template>
<DropdownMenuSeparator data-slot="dropdown-menu-separator" v-bind="delegatedProps" :class="cn('bg-border -mx-1 my-1 h-px', props.class)" />
</template>

View File

@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { HTMLAttributes } from 'vue'
import { cn } from '@/lib/utils'
const props = defineProps<{
class?: HTMLAttributes['class']
}>()
</script>
<template>
<span data-slot="dropdown-menu-shortcut" :class="cn('text-muted-foreground ml-auto text-xs tracking-widest', props.class)">
<slot />
</span>
</template>

View File

@@ -0,0 +1,15 @@
<script setup lang="ts">
import type { DropdownMenuSubEmits, DropdownMenuSubProps } from 'reka-ui'
import { DropdownMenuSub, useForwardPropsEmits } from 'reka-ui'
const props = defineProps<DropdownMenuSubProps>()
const emits = defineEmits<DropdownMenuSubEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<DropdownMenuSub data-slot="dropdown-menu-sub" v-bind="forwarded">
<slot />
</DropdownMenuSub>
</template>

View File

@@ -0,0 +1,29 @@
<script setup lang="ts">
import type { DropdownMenuSubContentEmits, DropdownMenuSubContentProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { DropdownMenuSubContent, useForwardPropsEmits } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuSubContentProps & { class?: HTMLAttributes['class'] }>()
const emits = defineEmits<DropdownMenuSubContentEmits>()
const delegatedProps = reactiveOmit(props, 'class')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<DropdownMenuSubContent
data-slot="dropdown-menu-sub-content"
v-bind="forwarded"
:class="
cn(
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--reka-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg',
props.class
)
"
>
<slot />
</DropdownMenuSubContent>
</template>

View File

@@ -0,0 +1,29 @@
<script setup lang="ts">
import type { DropdownMenuSubTriggerProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { ChevronRight } from 'lucide-vue-next'
import { DropdownMenuSubTrigger, useForwardProps } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<DropdownMenuSubTriggerProps & { class?: HTMLAttributes['class']; inset?: boolean }>()
const delegatedProps = reactiveOmit(props, 'class', 'inset')
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<DropdownMenuSubTrigger
data-slot="dropdown-menu-sub-trigger"
v-bind="forwardedProps"
:class="
cn(
'focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8',
props.class
)
"
>
<slot />
<ChevronRight class="ml-auto size-4" />
</DropdownMenuSubTrigger>
</template>

View File

@@ -0,0 +1,14 @@
<script setup lang="ts">
import type { DropdownMenuTriggerProps } from 'reka-ui'
import { DropdownMenuTrigger, useForwardProps } from 'reka-ui'
const props = defineProps<DropdownMenuTriggerProps>()
const forwardedProps = useForwardProps(props)
</script>
<template>
<DropdownMenuTrigger data-slot="dropdown-menu-trigger" v-bind="forwardedProps">
<slot />
</DropdownMenuTrigger>
</template>

View File

@@ -0,0 +1,16 @@
export { default as DropdownMenu } from './DropdownMenu.vue'
export { default as DropdownMenuCheckboxItem } from './DropdownMenuCheckboxItem.vue'
export { default as DropdownMenuContent } from './DropdownMenuContent.vue'
export { default as DropdownMenuGroup } from './DropdownMenuGroup.vue'
export { default as DropdownMenuItem } from './DropdownMenuItem.vue'
export { default as DropdownMenuLabel } from './DropdownMenuLabel.vue'
export { default as DropdownMenuRadioGroup } from './DropdownMenuRadioGroup.vue'
export { default as DropdownMenuRadioItem } from './DropdownMenuRadioItem.vue'
export { default as DropdownMenuSeparator } from './DropdownMenuSeparator.vue'
export { default as DropdownMenuShortcut } from './DropdownMenuShortcut.vue'
export { default as DropdownMenuSub } from './DropdownMenuSub.vue'
export { default as DropdownMenuSubContent } from './DropdownMenuSubContent.vue'
export { default as DropdownMenuSubTrigger } from './DropdownMenuSubTrigger.vue'
export { default as DropdownMenuTrigger } from './DropdownMenuTrigger.vue'
export { DropdownMenuPortal } from 'reka-ui'

View File

@@ -0,0 +1,24 @@
<script setup lang="ts">
import type { MenubarRootEmits, MenubarRootProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { MenubarRoot, useForwardPropsEmits } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<MenubarRootProps & { class?: HTMLAttributes['class'] }>()
const emits = defineEmits<MenubarRootEmits>()
const delegatedProps = reactiveOmit(props, 'class')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<MenubarRoot
data-slot="menubar"
v-bind="forwarded"
:class="cn('bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs', props.class)"
>
<slot />
</MenubarRoot>
</template>

View File

@@ -0,0 +1,35 @@
<script setup lang="ts">
import type { MenubarCheckboxItemEmits, MenubarCheckboxItemProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { Check } from 'lucide-vue-next'
import { MenubarCheckboxItem, MenubarItemIndicator, useForwardPropsEmits } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<MenubarCheckboxItemProps & { class?: HTMLAttributes['class'] }>()
const emits = defineEmits<MenubarCheckboxItemEmits>()
const delegatedProps = reactiveOmit(props, 'class')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<MenubarCheckboxItem
data-slot="menubar-checkbox-item"
v-bind="forwarded"
:class="
cn(
'focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=\'size-\'])]:size-4',
props.class
)
"
>
<span class="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<MenubarItemIndicator>
<Check class="size-4" />
</MenubarItemIndicator>
</span>
<slot />
</MenubarCheckboxItem>
</template>

View File

@@ -0,0 +1,34 @@
<script setup lang="ts">
import type { MenubarContentProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { MenubarContent, MenubarPortal, useForwardProps } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = withDefaults(defineProps<MenubarContentProps & { class?: HTMLAttributes['class'] }>(), {
align: 'start',
alignOffset: -4,
sideOffset: 8,
})
const delegatedProps = reactiveOmit(props, 'class')
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<MenubarPortal>
<MenubarContent
data-slot="menubar-content"
v-bind="forwardedProps"
:class="
cn(
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[12rem] origin-(--reka-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md',
props.class
)
"
>
<slot />
</MenubarContent>
</MenubarPortal>
</template>

View File

@@ -0,0 +1,12 @@
<script setup lang="ts">
import type { MenubarGroupProps } from 'reka-ui'
import { MenubarGroup } from 'reka-ui'
const props = defineProps<MenubarGroupProps>()
</script>
<template>
<MenubarGroup data-slot="menubar-group" v-bind="props">
<slot />
</MenubarGroup>
</template>

View File

@@ -0,0 +1,37 @@
<script setup lang="ts">
import type { MenubarItemEmits, MenubarItemProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { MenubarItem, useForwardPropsEmits } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<
MenubarItemProps & {
class?: HTMLAttributes['class']
inset?: boolean
variant?: 'default' | 'destructive'
}
>()
const emits = defineEmits<MenubarItemEmits>()
const delegatedProps = reactiveOmit(props, 'class', 'inset', 'variant')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<MenubarItem
data-slot="menubar-item"
:data-inset="inset ? '' : undefined"
:data-variant="variant"
v-bind="forwarded"
:class="
cn(
'focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive-foreground data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/40 data-[variant=destructive]:focus:text-destructive-foreground data-[variant=destructive]:*:[svg]:!text-destructive-foreground [&_svg:not([class*=\'text-\'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=\'size-\'])]:size-4',
props.class
)
"
>
<slot />
</MenubarItem>
</template>

View File

@@ -0,0 +1,20 @@
<script setup lang="ts">
import type { MenubarLabelProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { MenubarLabel } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<MenubarLabelProps & { class?: HTMLAttributes['class']; inset?: boolean }>()
const delegatedProps = reactiveOmit(props, 'class', 'inset')
</script>
<template>
<MenubarLabel
:data-inset="inset ? '' : undefined"
v-bind="delegatedProps"
:class="cn('px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', props.class)"
>
<slot />
</MenubarLabel>
</template>

View File

@@ -0,0 +1,12 @@
<script setup lang="ts">
import type { MenubarMenuProps } from 'reka-ui'
import { MenubarMenu } from 'reka-ui'
const props = defineProps<MenubarMenuProps>()
</script>
<template>
<MenubarMenu data-slot="menubar-menu" v-bind="props">
<slot />
</MenubarMenu>
</template>

View File

@@ -0,0 +1,15 @@
<script setup lang="ts">
import type { MenubarRadioGroupEmits, MenubarRadioGroupProps } from 'reka-ui'
import { MenubarRadioGroup, useForwardPropsEmits } from 'reka-ui'
const props = defineProps<MenubarRadioGroupProps>()
const emits = defineEmits<MenubarRadioGroupEmits>()
const forwarded = useForwardPropsEmits(props, emits)
</script>
<template>
<MenubarRadioGroup data-slot="menubar-radio-group" v-bind="forwarded">
<slot />
</MenubarRadioGroup>
</template>

View File

@@ -0,0 +1,35 @@
<script setup lang="ts">
import type { MenubarRadioItemEmits, MenubarRadioItemProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { Circle } from 'lucide-vue-next'
import { MenubarItemIndicator, MenubarRadioItem, useForwardPropsEmits } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<MenubarRadioItemProps & { class?: HTMLAttributes['class'] }>()
const emits = defineEmits<MenubarRadioItemEmits>()
const delegatedProps = reactiveOmit(props, 'class')
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
<template>
<MenubarRadioItem
data-slot="menubar-radio-item"
v-bind="forwarded"
:class="
cn(
'focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=\'size-\'])]:size-4',
props.class
)
"
>
<span class="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<MenubarItemIndicator>
<Circle class="size-2 fill-current" />
</MenubarItemIndicator>
</span>
<slot />
</MenubarRadioItem>
</template>

View File

@@ -0,0 +1,17 @@
<script setup lang="ts">
import type { MenubarSeparatorProps } from 'reka-ui'
import type { HTMLAttributes } from 'vue'
import { reactiveOmit } from '@vueuse/core'
import { MenubarSeparator, useForwardProps } from 'reka-ui'
import { cn } from '@/lib/utils'
const props = defineProps<MenubarSeparatorProps & { class?: HTMLAttributes['class'] }>()
const delegatedProps = reactiveOmit(props, 'class')
const forwardedProps = useForwardProps(delegatedProps)
</script>
<template>
<MenubarSeparator data-slot="menubar-separator" :class="cn('bg-border -mx-1 my-1 h-px', props.class)" v-bind="forwardedProps" />
</template>

Some files were not shown because too many files have changed in this diff Show More