初版:上传接口(从线上实例导出,适配容器端口)

This commit is contained in:
deploy
2026-10-29 14:37:21 +08:00
commit d727e44572
70 changed files with 34893 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
__pycache__/
*.pyc
data/
*.zip
*.log
.temp/
+716
View File
@@ -0,0 +1,716 @@
# 服务端 API 文档
整理日期:2026-09-30。仅整理 `app.py` 新入口注册的 API,依据当前工作区源码(含未提交修改),重点覆盖**统计、新建表单和填写内容**。示例中的 ID、姓名和时间均为虚构。
## 1. 适用入口与通用约定
服务入口为 `app.py`,业务接口通过 `routes/*.py` Blueprint 注册;监控和数据库管理接口由各自的注册函数挂载。
源码位置:`routes/forms.py`(表单)、`routes/submissions.py`(填写与统计)、`routes/export.py`(导出)、`routes/files.py`(附件)、`routes/auth_routes.py` 和 `routes/auth.py`(认证)、`database.py`(数据结构与统计口径)。监控和数据库管理分别在 `monitor_api.py`、`db_manage_api.py`。
- **Base URL:`https://upload.bansonic.top`**。
- 本文所有接口路径均相对于该 Base URL,例如新建表单的完整地址为 `https://upload.bansonic.top/api/save_form`,填写页面地址为 `https://upload.bansonic.top/<formId>`。
- JSON 请求使用 `Content-Type: application/json`;填写与文件上传使用 `multipart/form-data`。
- 登录认证依赖 Cookie `session_id`,当前没有 Bearer Token 认证实现。
- 设备 Cookie `fs_device_token` 用于找回上次填写,和管理端登录会话相互独立。
- 时间通常是服务端本地时间的 ISO 字符串,不含时区。当前部分时间处理会混用带时区与不带时区对象;直接调用时建议使用与服务端一致、无时区的 ISO 格式,如 `2026-10-01T18:00:00`。
- 大小限制单位为**字节**;`10485760` = 10 MiB。扩展名使用小写且不带点,例如 `["pdf", "docx"]`。
- 响应没有统一包裹格式:有的直接返回对象/数组,有的返回 `success/message`,有的返回 `error`。
### 1.1 权限标记
| 标记 | 含义 | 未登录时的实际响应 |
| --- | --- | --- |
| 公开 | 不要求管理端登录 | 按接口自身逻辑处理 |
| 登录 | `require_login` | **302** 跳转 `/login?redirect=<请求路径>` |
| 表单管理 | 登录后,还需 admin 或在 `managed_forms` 中 | 未登录先 302;无表单权限通常 403 |
| 管理员 | `require_admin`,要求角色为 admin | JSON 401;已登录非管理员 JSON 403 |
注意:前端 `fetch` 默认跟随 302,最终可能得到登录页 HTML,调用 `response.json()` 会失败。路径含 `/admin/` 不等于一定要求管理员,须以本表的实际校验为准。
### 1.2 认证接口
| 方法 | 路径 | 请求 | 返回 |
| --- | --- | --- | --- |
| POST | `/api/login` | JSON:`username`、`password`,可选 `redirect` | `{success:true, role, redirect}`,并写入 `session_id` Cookie |
| POST | `/api/logout` | 无业务参数 | `{success:true}`,删除会话和 Cookie |
| GET | `/api/current_user` | 无参数 | 未登录 `{logged_in:false}`;登录后见下方 |
登录 Cookie 有效期 7 天,设置 `HttpOnly`、`SameSite=Strict`,当前 `Secure=false`。登录失败:空账号/密码 400、用户不存在 404、密码错误 401。
```json
{
"logged_in": true,
"username": "operator",
"role": "user",
"managed_forms": ["Ab12Cd34"],
"managed_presets": ["preset_example1"],
"session_created_at": "2026-09-30T09:00:00",
"session_expires_at": "2026-10-07T09:00:00"
}
```
## 2. 核心接口速查
| 用途 | 方法 | 路径 | 权限 |
| --- | --- | --- | --- |
| 新建表单 | POST | `/api/save_form` | 登录 |
| 获取表单配置/题目 | GET | `/api/get_form/<form_id>` | 公开 |
| 编辑表单 | POST | `/api/edit_form/<form_id>` | 表单管理 |
| 表单列表及汇总数量 | GET | `/api/admin/forms` | 登录,普通用户仅列出被授权表单 |
| 开关收集状态 | POST | `/api/admin/toggle_collect/<form_id>` | 表单管理 |
| 删除表单 | POST | `/api/admin/delete_form/<form_id>` | 表单管理 |
| 名单尾号映射 | GET | `/get_students?formId=<form_id>` | 公开 |
| 检查某尾号是否提交 | GET | `/check_submission?formId=<form_id>&studentId=<tail>` | 公开 |
| 覆盖验证预检查 | POST | `/get_verify_value` | 公开 |
| 提交填写内容/附件 | POST | `/api/submit` | 公开 |
| 检查本设备上次填写 | GET | `/api/last_submission/check?formId=<form_id>` | 设备 Cookie |
| 加载本设备上次填写 | POST | `/api/last_submission/load` | 设备 Cookie + 尾号匹配 |
| 提交状态和填写内容明细 | GET | `/api/status_data?formId=<form_id>` | 公开 |
| 公开完成进度 | GET | `/api/progress/<form_id>` | 公开,需开启 `showProgress` |
| 提交时间趋势 | GET | `/api/submission_times/<form_id>` | 登录 |
| 某身份历史填写版本 | GET | `/api/admin/submission_history?formId=<form_id>&studentId=<full_id>` | 表单管理 |
| 导出填写数据 | GET | `/api/export/<form_id>?format=json` | 登录 |
`form_id` 是表单 ID;`tail` 是学号尾号字符串(保留前导零)。**填写接口中的 `studentId` 是尾号,历史版本查询中的 `studentId` 是完整身份 ID。**
## 3. 新建及维护表单
### 3.1 新建表单:`POST /api/save_form`
权限:登录。请求为非空 JSON 对象。成功为 HTTP 200:
```json
{"success": true, "formId": "Ab12Cd34"}
```
表单 ID 由服务端生成,为 8 位大小写字母/数字。填写页面地址为 `/<formId>`。普通用户创建后会自动获得该表单的管理权限。
| 参数 | 类型 | 缺省值 | 说明 |
| --- | --- | --- | --- |
| `title` | string | `未命名表单` | 表单标题 |
| `presetId` | string / null | null | 有值为名单模式;未传、null 或空字符串为匿名模式 |
| `fields` | array | `[]` | 自定义题目,结构见 3.2;名单模式不要重复传基础字段 |
| `collectType` | string | `info` | 当前创建页固定传 `info`;服务端保存该值,不据此强制限定题型 |
| `maxSize` | number | `10485760` | 每个上传文件大小上限,字节 |
| `allowedExts` | string[] | `[]` | 全局文件扩展名;空数组表示不限制 |
| `verifyDigits` | number | `2` | 名单模式用学号后几位识别 |
| `showProgress` | boolean | `true` | 公开进度接口的显示开关 |
| `expiresAt` | string / null | null | 过期时间;空值为永不过期 |
| `overwriteVerify` | object | 最终保存为 null | 名单模式重复覆盖时的验证配置,见 3.3 |
| `duplicatePolicy` | string | `overwrite` | `once` 禁止同身份重复提交;其他值均归一化为 `overwrite` |
| `collecting` | boolean | `true` | 是否正在收集;false 时提交返回 423 |
| `announcement` | object / null | null | `{subtitle, text}`,填写页面公告,正文支持 Markdown 展示 |
| `validation` | object / null | null | `{enabled, failToast, script}`,浏览器提交前校验,见 3.4 |
名单模式服务端在 `fields` 前自动加入:
```json
[
{"name":"tail","type":"number","placeholder":"学号后2位","required":true,"options":""},
{"name":"name","type":"text","placeholder":"姓名","required":true,"options":""}
]
```
匿名模式只保存自定义题目,并忽略 `overwriteVerify`。服务端创建时未严格验证 `presetId` 存在性及题目结构;调用方应传有效预设、正确类型及唯一题目名。
名单模式示例(`presetId` 须替换为实际预设 ID):
```json
{
"title": "活动报名",
"presetId": "preset_example1",
"verifyDigits": 2,
"collectType": "info",
"maxSize": 10485760,
"allowedExts": ["pdf", "docx"],
"showProgress": true,
"collecting": true,
"duplicatePolicy": "overwrite",
"expiresAt": null,
"overwriteVerify": {"enabled":true,"field":"phone","digits":4,"label":"手机号"},
"announcement": {"subtitle":"请填写报名信息","text":"请在截止日期前完成填写。"},
"validation": {"enabled":false,"failToast":"","script":""},
"fields": [
{"name":"联系方式","type":"text","required":true,"placeholder":"请输入手机号","validationPreset":"phone"},
{"name":"参加场次","type":"radio","required":true,"options":"上午,下午","optionLayout":"wrap"},
{"name":"兴趣","type":"checkbox","required":false,"options":"音乐,运动,阅读"},
{"type":"page_break","title":"附件与备注","required":false},
{"name":"证明材料","type":"file","required":false,"allowedExts":["pdf"]},
{"name":"备注","type":"textarea","required":false}
]
}
```
匿名模式最小示例:
```json
{
"title":"意见反馈",
"presetId":null,
"duplicatePolicy":"once",
"fields":[{"name":"建议","type":"textarea","required":true}]
}
```
### 3.2 题目 `fields[]` 的结构
| 字段 | 类型 | 用途 |
| --- | --- | --- |
| `name` | string | 普通题目的显示名称,同时是提交参数名和填写数据的键;必须唯一 |
| `type` | string | 题型,见下表 |
| `placeholder` | string | 输入提示 |
| `required` | boolean | 前端必填标记 |
| `options` | string | 下拉/单选/多选选项,**英文逗号分隔的字符串** |
| `optionLayout` | string | 单选/多选布局:`wrap` 或 `column` |
| `allowedExts` | string[] | 文件题目的扩展名限制,非空时优先于全局限制 |
| `allowDecimal` | boolean | 数字题允许小数;创建页缺省为 false |
| `validationPreset` | string | 文本校验:`none/phone/qq/idCard/name/email/custom` |
| `validationPattern` | string | `custom` 时的正则表达式 |
| `ratingMax` | string / number | 评分上限,页面支持 5 或 10 |
| `sliderMin/sliderMax/sliderStep` | string / number | 滑块最小值/最大值/步长;页面缺省 `0/100/1` |
| `showWhen` | object | 浏览器条件显示配置:`{field, values, action, matchMode}` |
| `title` | string | `page_break` 的下一页标题;分页控件无需 `name` |
| `type` | 题型 | 提交形式 |
| --- | --- | --- |
| `text` / `textarea` | 短文本 / 多行文本 | 字符串 |
| `number` | 数字 | 字符串,例如 `"3.5"` |
| `select` / `radio` | 下拉 / 单选 | 单个选项字符串 |
| `checkbox` | 多选 | 英文逗号拼接,例如 `"音乐,阅读"` |
| `date` / `time` | 日期 / 时间 | 浏览器输入值,例如 `"2026-10-01"`、`"09:30"` |
| `rating` / `slider` | 评分 / 滑块 | 数值字符串 |
| `file` | 文件上传 | 同名 multipart 文件 part;每题取一个文件 |
| `page_break` | 分页 | 不提交、不写入填写数据 |
`showWhen.values` 为字符串数组;`action` 为 `show/hide`;`matchMode` 支持 `exact/contains/loose/not_equals/greater/greater_equal/less/less_equal/not_empty/empty`。这些配置由页面解释,服务端不会据此拒绝填写内容。
名单模式避免自定义题目使用 `tail`、`name`;所有模式均避免使用传输参数名 `formId`、`studentId`、`device_token`、`verifyTail`、`idCardTail`、`keep_files` 作为题目名。
### 3.3 覆盖验证 `overwriteVerify`
```json
{"enabled":true,"field":"custom","customFieldName":"验证码","digits":4,"label":"验证码"}
```
- `field`:`idCard` 身份证、`phone` 手机号、`custom` 预设自定义列。
- `digits`:比对预设值末尾多少位,缺省 4。
- `customFieldName`:自定义列名称;从预设学生的 `extra` 或同名属性读取。
- `label`:错误提示中使用的名称,缺省为身份证。
- 仅名单模式**覆盖已有提交**时执行;首次提交不要求该验证。
- 比对时转为大写。名单预设与表单的 `verifyDigits` 应保持一致,因为不同接口分别读取这两处配置。
### 3.4 自定义提交前校验 `validation`
`script` 为 JavaScript 函数表达式字符串,页面调用签名为 `(values, fields, ctx)`,支持异步返回。`values` 中普通值为字符串,文件为 File 或 null;`ctx` 包含名单姓名及尾号 `studentId`。
```json
{
"enabled": true,
"failToast": "请检查填写内容",
"script": "(values, fields, ctx) => values['备注'] ? true : {ok:false, msg:'请填写备注'}"
}
```
返回 `false` 或 `{ok:false,msg:"提示"}` 会阻止页面提交。**这是前端校验,`/api/submit` 不执行该脚本。**
### 3.5 获取配置:`GET /api/get_form/<form_id>`
权限:公开。直接返回完整表单对象,不包裹在 `data` 或 `form` 中。
除创建参数外,还包含:`id`、`createdAt`、`creator`、`creatorIP`、`presetName`、`fileFieldCount`、`announcementFiles`。`fields` 在名单模式包含自动加入的 `tail/name`,`overwriteVerify` 未启用时为 null。表单不存在 404,异常 500。
此接口返回配置,不会因过期、停止收集或关闭进度而拒绝访问。
### 3.6 编辑与收集状态
`POST /api/edit_form/<form_id>`:表单管理权限,JSON 结构基本同创建。成功 `{success:true,formId,message:"表单已更新"}`;表单不存在 404、无权限 403、空数据 400。
编辑保留 `id/createdAt/creator/creatorIP/presetId/presetName`,不支持切换名单与匿名模式。此接口**不是所有字段都可省略的局部更新**:
- 省略 `fields` 会把自定义题目清空。
- 省略 `expiresAt` 会清空过期时间。
- 省略 `verifyDigits` 会设回 2。
- 省略 `overwriteVerify` 会清空覆盖验证。
- `title/collectType/maxSize/allowedExts/showProgress/announcement/validation/collecting/duplicatePolicy` 省略时沿用原值。
编辑请求中的 `fields` 只传自定义题目,名单模式须先过滤获取配置返回的 `tail/name`。
`POST /api/admin/toggle_collect/<form_id>`:表单管理权限。
```json
{"collecting": false}
```
返回 `{success:true,collecting:false,message:"已停止收集"}`;传 `{}` 会切换当前状态。应传 JSON 布尔值,字符串 `"false"` 会被 Python `bool()` 视为 true。
`POST /api/admin/delete_form/<form_id>`:表单管理权限;成功 `{success:true,message:"表单已删除"}`。当前路由不检查删除返回值,不存在的 ID 也可能返回成功。
### 3.7 公告附件
| 方法 | 路径 | 参数 | 权限/响应 |
| --- | --- | --- | --- |
| POST | `/api/form/<form_id>/announcement_upload` | multipart:`file` | 表单管理;`{success:true,files:[...]}` |
| POST | `/api/form/<form_id>/announcement_delete/<file_id>` | 无业务参数 | 表单管理;返回剩余 `files` |
| GET | `/api/announcement_download/<file_id>` | 路径 ID | 公开;二进制附件 |
每个表单最多 3 个公告附件;单文件受 `maxSize` 限制。公告上传未校验 `allowedExts`。创建表单后再逐个上传,不把公告文件塞进创建 JSON。附件清单字段为 `id/form_id/filename/original_name/file_size/mime_type/uploaded_at/download_url`,获取表单时放在 `announcementFiles` 中。
## 4. 填写表单与提交内容
### 4.1 填写前读取
1. `GET /api/get_form/<form_id>` 获取题目、收集开关、重复策略等。
2. 名单模式 `GET /get_students?formId=<form_id>` 获取尾号与身份映射:
```json
{"01":{"id":"20260001","name":"张同学"},"02":{"id":"20260002","name":"李同学"}}
```
无表单、无预设或预设无效时返回 `{}`(HTTP 200)。映射不含身份证,但包含完整学号和姓名;尾号冲突时同一个键会被后续学生覆盖。
3. 名单模式 `GET /check_submission?formId=<form_id>&studentId=01` 返回 `{exists:true}`。`formId` 缺省 `default`,`studentId` 为尾号。
4. 如需覆盖验证预检查,`POST /get_verify_value`:
```json
{"formId":"Ab12Cd34","studentId":"01","value":"1234"}
```
返回 `{success:true}` 或 `{success:false}`,不会返回验证答案。只有表单启用覆盖验证且该尾号已提交时才可能成功。正式提交仍须传 `verifyTail`,不会复用预检查结果。
### 4.2 填写链接的 URL 预填与隐藏
填写页面支持在链接查询参数中直接指定答案,无需另建数据库预设或增加接口。例如:
```text
https://upload.bansonic.top/test?1=XXX
https://upload.bansonic.top/test?1=XXX&hidden=1,2,3
```
`test` 应替换为实际表单 ID。数字参数从 **1** 开始,对应页面显示的题目序号;分页控件不计数,文件题目计数但不支持 URL 上传。名单模式自动生成的学号尾号和姓名分别占第 1、2 项。
| 参数 | 效果 |
| --- | --- |
| `1=XXX` | 第一题预填 XXX;有效预填后禁用控件,显示“已预填,无法修改” |
| `2=第一行%0A第二行` | 第二题为 textarea 时预填两行文本 |
| `3=上午` | 下拉或单选按实际选项文字匹配,不使用选项序号 |
| `4=音乐,阅读` | 多选同时选中音乐、阅读 |
| `4=音乐&4=阅读` | 多选也支持重复参数,合并并去重 |
| `hidden=1,2,3` | 隐藏第 1、2、3 题,可与预填同时使用 |
预填支持 `text/textarea/number/select/radio/checkbox/date/time/rating/slider`。日期格式为 `YYYY-MM-DD`、时间为 `HH:mm`;数字、评分、滑块须满足控件格式、范围和步长。选项须与表单配置一致,无效选项/格式不锁定字段,页面提示手动检查;未知或越界题目序号忽略。单值题目重复参数取最后一个值。
- URL 预填优先于本地草稿和“加载上次填写”,提交后页面重置也会恢复预填和禁用状态。
- 隐藏不等于删除:已预填的隐藏答案仍随 `/api/submit` 提交,普通隐藏题目不再要求页面必填。整页隐藏时跳过该页导航。
- 名单模式预填学号尾号后自动匹配姓名,姓名以名单为准,不接受 URL 中指定另一姓名。若隐藏学号输入,需同时提供有效尾号,否则服务端身份校验仍会拒绝提交。
- 锁定发生在填写页面;URL 参数本身可由访问者修改,服务端沿用原有提交校验。
- 中文、换行及 `&/+/#` 等内容建议通过 `URLSearchParams` 编码,避免改变查询参数含义。
生成链接示例:
```javascript
const url = new URL('https://upload.bansonic.top/test');
url.search = new URLSearchParams({
1: 'XXX',
2: '第一行\n第二行',
3: '上午',
4: '音乐,阅读',
hidden: '1,2,3'
}).toString();
console.log(url.href);
```
### 4.3 提交:`POST /api/submit`
权限:公开。使用 `multipart/form-data`,浏览器发送 FormData 时让浏览器自动设置 Content-Type 和 boundary。
| 参数 | 类型 | 要求 | 含义 |
| --- | --- | --- | --- |
| `formId` | string | 应显式传 | 表单 ID;未传会使用 `default` |
| `studentId` | string | 名单模式传 | 学号尾号,例如 `"01"`,不是完整学号 |
| `device_token` | string | 建议传 | 稳定设备令牌;服务端去空白并截断为 128 字符 |
| `verifyTail` | string | 需要覆盖验证时传 | 身份证/手机号/自定义值后几位 |
| `idCardTail` | string | 可选 | 旧验证参数,`verifyTail` 为空时回退读取 |
| `<题目 name>` | string / file | 按配置传 | 所有填写内容和附件以各自题目 `name` 作为参数名 |
| `keep_files` | JSON 字符串 | 覆盖且沿用旧附件时传 | 例如 `{"证明材料":12}`,值为原文件 ID 数字 |
身份与重复规则:
- 名单模式用 `studentId` 尾号查找预设学生,真实姓名和完整学号由预设确定。传 `name` 只影响普通填写数据,不改变服务端身份。
- 匿名模式忽略 `studentId`,身份为 `anon_<device_token>`;没有令牌时回退 `anon_ip_<IP摘要>`。同一设备或相同回退 IP 可能被视为同一身份。
- `overwrite`:同一身份更新当前记录,同时保留历史快照。覆盖会替换普通填写内容,未再传的普通题目不会自动沿用。
- `once`:同一身份已有记录时返回 409。
- 沿用附件需显式传 `keep_files`;其他旧附件会被归档到历史版本。新附件以题目名上传。
普通内容的保存格式:服务端遍历配置中的非 `file/page_break` 题目,用 `request.form.get(name)` 取值;**只保存非空字符串**。未配置的额外键不会写入填写 `data`,数字/日期/评分不会转换类型,多选必须自己拼接成逗号字符串。同名多 part 只读取第一个值。
前端页面会校验必填、正则、选项及数字等,但当前提交接口没有完整的题目级校验。服务端实际校验包括:表单存在、过期/停止状态、名单身份、重复策略、覆盖验证、文件扩展名和单文件大小。
成功示例:
```json
{"success":true,"message":"提交成功","overwrite":false}
```
覆盖成功为 `message:"覆盖成功"`、`overwrite:true`。响应不返回 submission ID 或文件 ID;可从状态/加载接口获取明细。
| HTTP 状态 | 情况 |
| --- | --- |
| 400 | 表单不存在;尾号长度错误/无效学号;缺少覆盖验证;不支持的文件格式;文件超限 |
| 403 | 覆盖验证失败 |
| 409 | `once` 策略禁止重复提交 |
| 410 | 表单已过期 |
| 423 | 停止收集 |
| 500 | 服务端异常 |
错误主体通常为 `{success:false,message:"具体原因"}`。
当前实现先写版本快照和提交记录,再校验/保存上传文件,整个提交不在单一事务中。因此文件错误响应不保证此前数据完全未写入;失败后应查询状态确认,尤其 `once` 模式下直接重试可能得到 409。
### 4.4 浏览器提交示例
```javascript
// formId、deviceToken、selectedFile 由调用方提供。
const body = new FormData();
body.append('formId', formId);
body.append('studentId', '01');
body.append('device_token', deviceToken);
body.append('tail', '01'); // 名单基础题目的填写快照
body.append('name', '张同学');
body.append('联系方式', '13800001234');
body.append('参加场次', '上午');
body.append('兴趣', ['音乐', '阅读'].join(','));
body.append('备注', '无');
if (selectedFile) body.append('证明材料', selectedFile);
// 覆盖时按需:body.append('verifyTail', '1234');
// 沿用旧附件时:body.append('keep_files', JSON.stringify({'证明材料': 12}));
const response = await fetch('/api/submit', {method: 'POST', body});
const result = await response.json();
if (!response.ok || !result.success) throw new Error(result.message || '提交失败');
```
### 4.5 加载上次填写
填写页面由客户端生成 32 位十六进制随机设备令牌,写入 `fs_device_token` Cookie(30 天,`path=/`,`SameSite=Lax`),并在提交时以 `device_token` 参数上送**同一个值**。提交接口只读取 multipart 参数,不会读取设备 Cookie 代替参数,也不负责生成该 Cookie。
`GET /api/last_submission/check?formId=<form_id>`:读取设备 Cookie,只返回存在性和时间。
```json
{"exists":true,"submittedAt":"2026-09-30T10:20:00"}
```
无参数、无令牌、无记录或发生异常时均返回 `{exists:false}`(200)。它不判断 `once` 是否允许再次提交。
`POST /api/last_submission/load`:读取设备 Cookie,JSON 请求:
```json
{"formId":"Ab12Cd34","tail":"01"}
```
匿名模式传 `tail:""`。服务端查找该设备在该表单的最近一条**当前提交**,核对尾号后返回:
```json
{
"success":true,
"values":{"tail":"01","name":"张同学","参加场次":"上午","兴趣":"音乐,阅读"},
"files":[{"id":12,"fieldName":"证明材料","originalName":"报名证明.pdf","fileSize":1024}],
"submittedAt":"2026-09-30T10:20:00"
}
```
缺参数/令牌或无记录 404、尾号不匹配 403、异常 500。返回的是附件清单,不是文件字节;沿用时将文件 ID 放入 `keep_files`。设备令牌只能召回当前记录,不是历史版本查询凭据。
## 5. 统计接口与填写内容查询
### 5.1 表单列表汇总:`GET /api/admin/forms`
权限:登录。直接返回数组,按 `createdAt` 倒序。admin 获取全部,普通 user 仅获取 `managed_forms` 中的表单,无分页参数。
```json
[
{
"id":"Ab12Cd34",
"title":"活动报名",
"createdAt":"2026-09-30T09:00:00",
"expiryInfo":{"created_at":"2026-09-30T09:00:00","expires_at":null,"remaining_days":null,"remaining_hours":null,"remaining_minutes":null,"is_expired":false,"never_expires":true},
"submittedCount":1,
"totalStudents":2,
"fileCount":1,
"collectType":"info",
"maxSize":10485760,
"can_manage":true,
"presetId":"preset_example1",
"presetName":"示例名单",
"collecting":true
}
]
```
`submittedCount` 为 `submissions` 当前行数,同身份覆盖不增加;`fileCount` 为当前 `files` 行数,不含归档版本附件和公告附件;`totalStudents` 为预设名单长度,匿名模式为 0。
### 5.2 状态与完整填写内容:`GET /api/status_data`
Query:`formId`,缺省 `default`。权限:**公开**。表单不存在 404,异常 500。
```json
{
"formTitle":"活动报名",
"formId":"Ab12Cd34",
"total":2,
"submitted":1,
"showProgress":true,
"expiryInfo":{"created_at":"2026-09-30T09:00:00","expires_at":null,"remaining_days":null,"remaining_hours":null,"remaining_minutes":null,"is_expired":false,"never_expires":true},
"students":[
{
"tail":"01","id":"20260001","name":"张同学","submitted":true,
"data":{"tail":"01","name":"张同学","参加场次":"上午","兴趣":"音乐,阅读"},
"files":[{"id":12,"form_id":"Ab12Cd34","submission_id":1,"filename":"张同学20260001.pdf","original_name":"报名证明.pdf","file_size":1024,"mime_type":"application/pdf","uploaded_at":"2026-09-30T10:20:00","field_name":"证明材料","download_url":"/api/download_file/12"}]
},
{"tail":"02","id":"20260002","name":"李同学","submitted":false,"data":{},"files":[]}
]
}
```
- 名单模式:按预设名单逐人列出,包含未提交者;`students[].data` 为当前填写内容,键与题目 `name` 相同。
- 匿名模式:每条当前提交对应一个身份,附 `anonymous:true`、`shortId`;`id` 为匿名伪 ID,`name` 如 `匿名设备 a1b2`,展示 `tail` 为短码。这里的展示短码不能作为加载接口的尾号,匿名加载应传空字符串。
- `total` 为实际返回的身份条目数;名单中学号长度不足预设 `verifyDigits` 的学生会被跳过。
- `submitted`:名单模式按当前记录尾号去重;匿名模式为当前提交行数。
- `expiryInfo` 计算失败可能为 null;未设置截止时间时 `never_expires:true`,剩余时间和截止时间为 null。
- 当前 `showProgress:false` **不会阻止此接口返回填写明细**,它只是响应里的标记;只有 5.3 的公开进度接口执行该开关校验。
### 5.3 公开完成进度:`GET /api/progress/<form_id>`
权限:公开,表单 `showProgress` 必须为 true。关闭时 403 `{error:"该表单未开启进度显示"}`;不存在 404。
```json
{
"formTitle":"活动报名",
"total":2,
"submitted":1,
"progress":50.0,
"students":[{"tail":"01","name":"张同学","submitted":true},{"tail":"02","name":"李同学","submitted":false}]
}
```
`progress` 为当前提交行数 / 预设名单长度 × 100,保留 1 位小数;不返回填写 `data` 或附件。匿名模式没有预设总人数,返回 `total:0`、`progress:0`、`students:[]`,`submitted` 仍为当前提交行数。
### 5.4 提交趋势:`GET /api/submission_times/<form_id>`
权限:登录;当前没有额外的 `managed_forms` 校验。表单不存在 404、缺创建时间 400、异常 500。
```json
{
"formId":"Ab12Cd34",
"createdAt":"2026-09-30T09:00:00",
"timeLabels":["09:00","09:20","09:40"],
"slotCounts":[0,1,0],
"cumulativeCounts":[0,1,1],
"totalSubmissions":1,
"rawTimes":["2026-09-30T09:25:00"],
"overwriteTimes":["2026-09-30T09:45:00"]
}
```
示例仅展示 3 个桶,实际从创建时间到当前时间按 **20 分钟**连续分桶,不支持自定义查询时间范围。桶为左闭右开;`timeLabels` 只有 `HH:mm`,跨天可能重复。
| 返回字段 | 统计口径 |
| --- | --- |
| `slotCounts` | 每个身份首次提交落在各桶的数量,覆盖不计入 |
| `cumulativeCounts` | 首次提交数量的累计和 |
| `totalSubmissions` | `submission_history` 中出现过的不同身份数量,不是事件总数 |
| `rawTimes` | 每个身份的首次提交时间 |
| `overwriteTimes` | 所有覆盖事件时间 |
该接口读取事件历史,和当前提交/可删除的内容版本快照不是同一数据源,删除当前版本后其数量可能与当前提交人数不一致。
### 5.5 统计口径对照
| 指标 | 数据来源 | 覆盖提交是否增加 |
| --- | --- | --- |
| 列表 `submittedCount`、进度 `submitted` | 当前 `submissions` 行数 | 否 |
| 状态 `submitted` | 名单尾号去重;匿名当前行数 | 通常否;尾号冲突会影响名单统计 |
| 导出 `submissions.submitted` | 导出身份列表中 `submitted:true` 的数量 | 否 |
| 趋势 `totalSubmissions` | 事件历史中不同身份数 | 否 |
| 趋势 `overwriteTimes.length` | 事件历史中的覆盖事件 | 是 |
| 历史版本 `versions.length` | 某身份的内容快照数 | 是;删除版本会减少 |
| 监控 `business.form_submissions` | 时间桶内成功执行到计数位置的提交事件 | 是 |
## 6. 历史填写、导出与附件下载
### 6.1 查看历史内容
`GET /api/admin/submission_history?formId=<form_id>&studentId=<full_id>`,权限:表单管理。
这里 `studentId` 是**完整学号**,匿名模式是 `anon_<device_token>` 或 IP 回退伪 ID,可从状态接口 `students[].id` 获取。
```json
{
"success":true,
"versions":[
{
"id":8,"data":{"备注":"更新后的内容"},"isOverwrite":true,
"ip":"192.0.2.10","submittedAt":"2026-09-30T11:00:00","isLatest":true,
"files":[{"name":"报名证明.pdf","size":1024,"fieldName":"证明材料","archived":false,"fileId":12,"downloadUrl":"/api/download_file/12"}]
}
]
}
```
版本按 ID 倒序排列,最大 ID 标为 `isLatest`。归档文件条目使用 `archived:true`、`vfileId`、`downloadUrl:"/api/admin/download_version_file/<id>"`;尚在当前文件表的附件使用 `fileId`。缺参数 400、表单不存在 404、无权限 403;无版本为成功空数组。
`POST /api/admin/delete_submission_version/<version_id>`,权限:对应表单管理。返回:
```json
{"success":true,"deletedCurrent":false,"deletedCurrentFiles":0}
```
删除非最新版本清除该快照及其归档附件;删除最新版本同时清除该身份的当前提交和当前附件,不自动恢复上一版为当前提交。不存在 404、无权限 403。
### 6.2 导出数据
`GET /api/export/<form_id>?format=<format>&asOf=<time>`,权限:登录,当前没有额外表单授权校验。
| 参数 | 默认 | 说明 |
| --- | --- | --- |
| `format` | `json` | `json/xlsx/csv`;其他值 400 |
| `asOf` | 空 | 可选 ISO 时间点,每个身份选取该时间点之前(含)的最新版本 |
JSON 返回:
```json
{
"form":{"id":"Ab12Cd34","title":"活动报名"},
"submissions":{"formTitle":"活动报名","formId":"Ab12Cd34","total":2,"submitted":1,"students":[]}
}
```
上例省略 `form` 其他配置和 `students` 明细;真实结构与 5.2 的身份条目类似。`xlsx/csv` 直接返回下载内容,xlsx 依赖 openpyxl。表单不存在 404。
`asOf` 使用历史填写快照,但名单与题目配置仍取**当前表单/预设**,不是完整表单结构的历史回滚。时间点模式的身份附件只返回名称/大小清单,不含下载 URL;需要历史附件时使用版本接口或时间点 ZIP。
### 6.3 文件和 ZIP
| 方法 | 路径 | 权限 | 行为 |
| --- | --- | --- | --- |
| GET | `/api/download_file/<file_id>` | 公开 | 按当前文件 ID 下载,响应为二进制 |
| GET | `/api/download/<form_id>/<filename>` | 公开 | 旧版按文件名下载入口 |
| GET | `/api/admin/download_version_file/<vfile_id>` | 表单管理 | 下载归档附件 |
| POST | `/api/create_zip/<form_id>` | 登录,无额外表单授权校验 | 创建 ZIP,返回下载 URL |
| GET | `/api/download_temp_zip/<temp_file_id>` | 公开 | 下载临时 ZIP,响应关闭后清理 |
ZIP 请求 JSON:`{}` 使用默认文件名;可传 `template` 文件命名模板,及 `asOf` 时间点。返回 `{success:true,download_url,filename,file_count,total_size}`。无文件或无表单 404;同表单正在打包时 429。临时 ZIP 可被每小时清理任务删除,下载地址应及时使用。
## 7. 系统统计接口
以下接口全部要求管理员。
### 7.1 实时监控:`GET /api/monitor/realtime`
```json
{
"cpu_percent":1.2,
"memory":{"used":52428800},
"disk":{"read_speed":1024,"write_speed":2048},
"network":{"sent_speed":512,"recv_speed":1024},
"active_requests":1,
"online_users":2,
"timestamp":"2026-09-30T10:00:00"
}
```
CPU、RSS 内存、磁盘读写针对当前 Python 进程;网络针对整个系统。内存单位字节,磁盘/网络速率为字节每秒;首次差分采样或采集不可用时可能返回 0。活跃请求可能包含当前监控请求本身。
### 7.2 历史监控:`GET /api/monitor/history?granularity=1h`
`granularity` 可选 `1h/6h/24h/7d/30d`,默认和无效值均为 `1h`。返回平行数组:
```json
{
"timestamps":[],"cpu":[],"memory":[],
"net_sent":[],"net_recv":[],"disk_read":[],"disk_write":[],
"business":{
"forms_created":[],"files_uploaded_mb":[],"user_logins":[],"api_calls":[],
"form_submissions":[],"file_downloads":[],"data_exports":[]
}
}
```
`memory` 为 MiB,网络/磁盘历史速率为 KiB/s,`files_uploaded_mb` 为 MiB 上传量,其余业务数组为各桶事件数量。系统快照每分钟采集;`app.py` 记录 `/api/` 调用统计时排除 `/api/monitor/`,并将 HTTP 状态 >=400 标为错误。
其他监控接口:
| 方法 | 路径 | 参数/返回 |
| --- | --- | --- |
| GET | `/api/monitor/count_before` | Query `before_date`;返回 `{count}`,统计指定日期前的系统/API/业务监控行数 |
| POST | `/api/monitor/cleanup` | JSON `{before_date:"2026-09-01"}`;支持日期或 ISO 时间;返回 `{success:true,deleted_count}` |
### 7.3 数据库存储统计:`GET /api/db/stats`
返回 `db_size`、`total_records`、`file_storage`、`data_storage`、`tables`、`forms`:
- `tables[]`:`name/record_count/columns`,列包含 `name/type`。
- `forms[]`:`id/title/submission_count/file_count/data_size/file_size/total_size`。
- `file_storage/file_size` 从当前 `files.file_size` 求和,不含历史附件/公告文件。
- `data_storage/data_size` 从 `LENGTH(submissions.data)` 求和,是数据库相关的长度估算,不代表整体数据库或磁盘实际占用。
- 附件当前支持磁盘存储,`db_size` 不等于附件目录与数据库文件的总占用。
`GET /api/db/temp-zip-stats` 返回临时 ZIP 数量、大小和过期信息。这是存储统计,不是填写人数统计。
## 8. 其他服务端 API 清单
### 8.1 名单预设
| 方法 | 路径 | 权限 | 内容 |
| --- | --- | --- | --- |
| GET | `/api/presets` | 登录 | 可见预设数组,含 `id/name/totalStudents/usageCount` 等;总人数来自预设 config |
| POST | `/api/presets` | 登录 | multipart 上传 `file`,可选 `name/verifyDigits/fieldMapping`;返回 `success/presetId/message` |
| GET | `/api/presets/<preset_id>` | 登录 | 元信息及 `config`,不含完整学生列表 |
| POST | `/api/presets/<preset_id>/preview` | 登录 | `previewStudents` 前 10 条、`config/totalStudents/name` |
| PUT | `/api/presets/<preset_id>` | 登录 | JSON `name` 或 `fieldMapping` 更新 |
| DELETE | `/api/presets/<preset_id>` | 管理员或创建者 | 删除预设 |
| GET | `/api/presets/<preset_id>/students` | 登录 | `{students:[{id,name,group}],config}` |
| POST | `/api/presets/<preset_id>/global` | 管理员 | 设为全局,并将 `createdBy` 改为 admin |
`fieldMapping` 上传时是 JSON **字符串**,更新时是 JSON 对象,字段为 `idField/nameField/idCardField/phoneField/groupField`,值为导入列名。上传支持 xlsx/xls/csv,学号、姓名列必须可识别;Excel 解析取决于已安装的 pandas 引擎。`verifyDigits` 默认 2,创建表单时应与此一致。
预设列表做可见性筛选;详情、预览、学生列表及 PUT 当前仅检查登录,未逐项校验该预设是否在用户授权范围。PUT 字段映射不重新解析原始学生数据。
### 8.2 用户管理
均要求管理员。
| 方法 | 路径 | 参数/用途 |
| --- | --- | --- |
| GET | `/api/user/list` | 用户数组,含角色、创建时间、表单和预设授权列表 |
| POST | `/api/user/add` | JSON `username/password/role`,role 默认 user |
| POST | `/api/user/delete/<username>` | 删除用户和会话,禁止删除默认 admin |
| GET | `/api/user/<username>/forms` | `{username,managed_forms,all_forms}` |
| POST | `/api/user/<username>/forms` | JSON `{form_ids:[...]}`,替换表单授权列表 |
### 8.3 数据库管理
均要求管理员。
| 方法 | 路径 | 参数/用途 |
| --- | --- | --- |
| GET | `/api/db/tables` | 返回 `{tables}`,数据库表信息 |
| GET | `/api/db/browse` | Query `table`、`limit`(默认 50)、`offset`(默认 0) |
| POST | `/api/db/execute` | JSON `{sql:"..."}`;执行 SQL |
| GET | `/api/db/sessions` | `{sessions,count}`,活跃会话列表和数量 |
| POST | `/api/db/sessions/cleanup` | 清理过期会话 |
| POST | `/api/db/vacuum` | 数据库优化 |
| POST | `/api/db/temp-zip-cleanup` | 清理临时 ZIP |
## 9. 联调建议与当前实现边界
常用调用顺序:管理端登录 → 读取/上传预设(名单模式)→ 新建表单 → 上传公告附件 → 分享 `/<formId>` → 读取题目并提交 FormData → 查询 `status_data` 获取填写明细 → 查询趋势或导出。
联调重点:
1. 文档对应 `app.py` 注册的接口,直接运行时使用 `python app.py`。
2. 区分配置题目 `fields`、当前答案 `students[].data/values`、历史答案 `versions[].data`。
3. 区分提交尾号、完整身份 ID、匿名展示短码;尾号始终按字符串处理,表单与预设位数一致且尾号应唯一。
4. 登录会话靠 Cookie;当前 CORS 配置针对 `/api/*`,允许任意 origin,但未开启凭据支持;`SameSite=Strict` 也影响跨站登录。涉及登录的调用优先同源,跨源不能假定可直接携带会话。`/get_students` 等不在该 CORS 范围。
5. `status_data` 和当前文件下载是公开接口,关闭进度不限制答案明细访问;导出、趋势、ZIP 当前仅检查登录。按当前实现对接,不把页面隐藏或路径名称当作服务端权限保证。
6. 题目级必填/格式/条件显示主要在浏览器执行;创建/提交失败不一定有统一响应,读取 JSON 前检查状态与 Content-Type。
7. 本文为源码核对结果,未启动服务、未写入业务数据库、未执行真实提交;部署参数及线上数据需在目标环境验证。
+25
View File
@@ -0,0 +1,25 @@
FROM python:3.11-slim
ENV TZ=Asia/Shanghai \
DEBIAN_FRONTEND=noninteractive \
PYTHONUNBUFFERED=1 \
PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple \
PIP_TRUSTED_HOST=pypi.tuna.tsinghua.edu.cn \
UPLOAD_PORT=8080
WORKDIR /app
RUN sed -i 's|deb.debian.org|mirrors.aliyun.com|g; s|security.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list 2>/dev/null || true \
&& sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null || true
RUN apt-get update && apt-get install -y --no-install-recommends \
tzdata libgomp1 \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8080
CMD ["python", "app.py"]
+377
View File
@@ -0,0 +1,377 @@
"""
表单提交系统 - 主入口
重构为 Blueprint 架构
"""
import os
import sys
# 确保项目根目录在 sys.path 中(适配 MCSManager 守护进程等非标准启动方式)
_PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
if _PROJECT_DIR not in sys.path:
sys.path.insert(0, _PROJECT_DIR)
import ssl
import hashlib
import threading
import time
import tempfile
from datetime import datetime, timedelta
from concurrent.futures import ThreadPoolExecutor
from flask import Flask, request, jsonify, redirect, g
from flask_cors import CORS
from config import (
BASE_DIR, TEMPLATES_DIR, STATIC_DIR, DATA_DIR,
CERT_FILE, KEY_FILE, HTTP_PORT,
)
from db import DB_PATH, is_sqlite, table_exists, MYSQL_CONFIG, init_mysql_session_vars
from database import (
init_database, get_all_users, get_user, save_user,
get_expired_forms, delete_form,
cleanup_expired_sessions, get_online_users_count,
init_monitor_tables, insert_business_metric, insert_api_stat,
get_db_connection,
)
# ========== Flask 应用 ==========
app = Flask(__name__, template_folder=TEMPLATES_DIR, static_folder=STATIC_DIR)
CORS(app, resources={
r"/api/*": {
"origins": "*",
"methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
"allow_headers": ["Content-Type", "Authorization"]
}
})
# ========== 全局状态 ==========
zip_creation_locks = {}
temp_zip_files = {}
_active_requests_counter = {'count': 0}
_active_requests_lock = threading.Lock()
zip_executor = ThreadPoolExecutor(max_workers=3)
# ========== 初始化数据库 ==========
print("应用启动,初始化数据库...")
if not os.path.exists(DB_PATH) and is_sqlite():
os.makedirs(DATA_DIR, exist_ok=True)
init_database()
else:
if is_sqlite():
print(f"✅ 数据库已存在: {DB_PATH}")
else:
print(f"✅ 使用 MySQL 数据库: {MYSQL_CONFIG.get('host', 'localhost')}")
init_database()
init_mysql_session_vars()
try:
with get_db_connection() as conn:
if not table_exists(conn, 'sessions'):
print("🔄 检测到 sessions 表不存在,正在创建...")
from database import init_database as _init
_init()
print("✅ sessions 表创建完成")
else:
if is_sqlite():
print("✅ sessions 表已存在")
except Exception as e:
print(f"⚠️ 检查/创建 sessions 表失败: {e}")
users = get_all_users()
if not users or 'admin' not in users:
save_user('admin', {
'username': 'admin',
'password_hash': hashlib.sha256('admin123'.encode('utf-8')).hexdigest(),
'role': 'admin',
'created_at': datetime.now().isoformat(),
'managed_forms': [],
'managed_presets': []
})
print("✅ 创建默认管理员账号: admin / admin123")
print(f"✅ 数据库初始化完成,当前用户数量: {len(get_all_users())}")
try:
init_monitor_tables()
except Exception as e:
print(f"⚠️ 监控表初始化失败: {e}")
# 迁移:为已存在的 forms 表补充 announcement 列(幂等)
try:
from database import migrate_announcement_column
migrate_announcement_column()
except Exception as e:
print(f"⚠️ announcement 列迁移失败: {e}")
# 迁移:为已存在的 forms 表补充 validation 列(幂等,供提交前校验脚本使用)
try:
from database import migrate_validation_column
migrate_validation_column()
except Exception as e:
print(f"⚠️ validation 列迁移失败: {e}")
# 迁移:每个表单的 Webhook 通知配置(已有表单默认关闭)
try:
from database import migrate_webhook_column
migrate_webhook_column()
except Exception as e:
print(f"⚠️ webhook 列迁移失败: {e}")
# 迁移:为已存在的 forms 表补充 collecting 列(幂等,收集中/停止收集开关)
try:
from database import migrate_collecting_column
migrate_collecting_column()
except Exception as e:
print(f"⚠️ collecting 列迁移失败: {e}")
# 迁移:为已存在的 submissions 表补充 device_token 列(幂等,"加载上次填写"功能)
try:
from database import migrate_device_token_column
migrate_device_token_column()
except Exception as e:
print(f"⚠️ device_token 列迁移失败: {e}")
# 迁移:为已存在的 forms 表补充 duplicate_policy 列(幂等,重复提交策略/匿名模式功能)
try:
from database import migrate_duplicate_policy_column
migrate_duplicate_policy_column()
except Exception as e:
print(f"⚠️ duplicate_policy 列迁移失败: {e}")
# 迁移:创建提交历史版本表(幂等,提交历史记录/按版本导出功能)
try:
from database import migrate_submission_versions
migrate_submission_versions()
except Exception as e:
print(f"⚠️ submission_versions 表迁移失败: {e}")
# 迁移:附件由数据库 BLOB 迁移到磁盘 data/files/(幂等)
try:
from database import migrate_files_to_disk
migrate_files_to_disk()
except Exception as e:
print(f"⚠️ 附件磁盘存储迁移失败: {e}")
# ========== 图标生成 ==========
from utils.icons import generate_favicons
generate_favicons()
# ========== 启动清理 ==========
def cleanup_orphaned_temp_files():
"""启动时清理孤立的临时ZIP文件"""
try:
temp_dir = tempfile.gettempdir()
cleaned = 0
for filename in os.listdir(temp_dir):
if filename.startswith('form_zip_') and filename.endswith('.zip'):
filepath = os.path.join(temp_dir, filename)
try:
stat = os.stat(filepath)
file_time = datetime.fromtimestamp(stat.st_ctime)
age = datetime.now() - file_time
if age > timedelta(hours=1):
os.remove(filepath)
cleaned += 1
print(f"🗑️ 启动清理: 删除遗留临时文件 {filename} (已存在 {age.total_seconds()/3600:.1f} 小时)")
except Exception as e:
print(f"⚠️ 清理 {filename} 失败: {e}")
if cleaned > 0:
print(f"✅ 启动清理完成: 删除 {cleaned} 个遗留临时文件")
else:
print("✅ 启动检查: 没有发现遗留临时文件")
except Exception as e:
print(f"❌ 启动清理失败: {e}")
cleanup_orphaned_temp_files()
# ========== 注册 Blueprint ==========
from routes.auth_routes import bp as auth_bp
from routes.pages import bp as pages_bp
from routes.forms import bp as forms_bp
from routes.submissions import bp as submissions_bp
from routes.files import bp as files_bp, init_app_state as files_init
from routes.presets import bp as presets_bp
from routes.users import bp as users_bp
from routes.export import bp as export_bp
app.register_blueprint(auth_bp)
app.register_blueprint(pages_bp)
app.register_blueprint(forms_bp)
app.register_blueprint(submissions_bp)
app.register_blueprint(presets_bp)
app.register_blueprint(users_bp)
app.register_blueprint(export_bp)
app.register_blueprint(files_bp)
# 注入全局状态到 files 蓝图
files_init(zip_creation_locks, temp_zip_files)
# ========== 注册 db_manage 和 monitor 路由 ==========
from routes.auth import require_admin
from db_manage_api import register_db_manage_routes
from monitor_api import register_monitor_routes, collect_metrics_snapshot
register_db_manage_routes(app, require_admin)
register_monitor_routes(app, require_admin, _active_requests_counter)
# ========== 错误处理 ==========
@app.errorhandler(404)
def handle_404(e):
if request.path.startswith('/api/'):
return jsonify(error='接口不存在', code=404), 404
return redirect('/error?code=404')
@app.errorhandler(500)
def handle_500(e):
if request.path.startswith('/api/'):
return jsonify(error='服务器内部错误', code=500), 500
return redirect('/error?code=500')
# ========== 定时任务 ==========
def cleanup_expired_forms_task():
"""清理过期的表单和文件(根据 expires_at 判断,未设置过期时间的永不过期)"""
try:
now_str = datetime.now().isoformat()
expired_forms = get_expired_forms(now_str)
for form_id in expired_forms:
print(f"清理过期表单: {form_id}")
delete_form(form_id)
if expired_forms:
print(f"✅ 清理完成: {len(expired_forms)}个表单")
else:
print("✅ 没有过期的表单需要清理")
except Exception as e:
print(f"❌ 自动清理任务失败: {str(e)}")
def cleanup_temp_zip_files():
"""清理超过1小时未下载的临时ZIP文件"""
try:
cleaned_count = 0
cutoff_time = datetime.now() - timedelta(hours=1)
expired_ids = []
for temp_file_id, temp_info in list(temp_zip_files.items()):
try:
created_at_str = temp_info.get('created_at', '')
temp_path = temp_info.get('path', '')
if created_at_str:
file_time = datetime.fromisoformat(created_at_str.replace('Z', '+00:00').replace('+00:00', ''))
if file_time < cutoff_time:
if os.path.exists(temp_path):
try:
os.remove(temp_path)
print(f"🗑️ 清理过期临时ZIP文件: {temp_path}")
except Exception as e:
print(f"❌ 删除文件失败 {temp_path}: {e}")
expired_ids.append(temp_file_id)
cleaned_count += 1
except Exception as e:
print(f"检查临时文件 {temp_file_id} 失败: {e}")
for temp_file_id in expired_ids:
temp_zip_files.pop(temp_file_id, None)
if cleaned_count > 0:
print(f"✅ 清理临时ZIP完成: {cleaned_count}个文件")
except Exception as e:
print(f"❌ 清理临时ZIP失败: {str(e)}")
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()
scheduler.add_job(cleanup_expired_forms_task, 'cron', hour=2, minute=0)
scheduler.add_job(cleanup_temp_zip_files, 'cron', hour='*/1')
scheduler.add_job(cleanup_expired_sessions, 'cron', hour=3, minute=0)
scheduler.add_job(
lambda: collect_metrics_snapshot(_active_requests_counter, get_online_users_count),
'interval', minutes=1
)
scheduler.start()
print("✅ 自动清理任务已启动 (每天凌晨2点执行)")
print("✅ 临时ZIP清理任务已启动 (每小时执行)")
print("✅ 会话清理任务已启动 (每天凌晨3点清理过期会话)")
print("✅ 系统指标采集任务已启动 (每分钟执行)")
# ========== 监控中间件 ==========
@app.before_request
def monitor_before_request():
"""请求开始:计数 + 记录开始时间"""
g.monitor_start_time = time.time()
g.monitor_request_size = request.content_length or 0
with _active_requests_lock:
_active_requests_counter['count'] += 1
@app.after_request
def monitor_after_request(response):
"""请求结束:减计数 + 记录API调用统计"""
try:
with _active_requests_lock:
_active_requests_counter['count'] = max(0, _active_requests_counter['count'] - 1)
if request.path.startswith('/api/') and not request.path.startswith('/api/monitor/'):
elapsed_ms = int((time.time() - g.get('monitor_start_time', time.time())) * 1000)
has_error = response.status_code >= 400
bytes_in = g.get('monitor_request_size', 0)
bytes_out = response.content_length or 0
try:
insert_api_stat(
endpoint=request.path,
method=request.method,
time_ms=elapsed_ms,
has_error=has_error,
bytes_in=bytes_in,
bytes_out=bytes_out
)
except Exception:
pass
except Exception:
pass
return response
# ========== 主程序入口 ==========
if __name__ == '__main__':
try:
print("🚀 正在启动 Flask 服务器...")
if False:
print(f"🔐 检测到SSL证书,启用HTTP/HTTPS兼容模式")
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(str(CERT_FILE), str(KEY_FILE))
app.run(host='0.0.0.0', port=HTTP_PORT, ssl_context=context, debug=True)
else:
print(f"⚠️ 未检测到SSL证书,使用HTTP模式")
print(f"监听地址: http://0.0.0.0:{HTTP_PORT}")
app.run(host='0.0.0.0', port=HTTP_PORT, debug=True)
except Exception as e:
print(f"❌ 服务器启动失败: {e}")
import traceback
traceback.print_exc()
input("按回车键退出...")
+60
View File
@@ -0,0 +1,60 @@
"""
全局配置常量
"""
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')
STATIC_DIR = os.path.join(BASE_DIR, 'static')
DATA_DIR = os.path.join(BASE_DIR, 'data')
IMG_DIR = os.path.join(STATIC_DIR, 'img')
# 数据库路径由 db.py 统一管理(读取 config.yml)
# 如需获取 DB_PATH,请:from db import DB_PATH
# 兼容旧路径
FORMS_DIR = os.path.join(BASE_DIR, 'forms')
PRESETS_DIR = os.path.join(BASE_DIR, 'presets')
# Webhook 总开关;每个表单另需显式启用,默认不通知。设为 0 禁止所有对外通知。
NOTIFY_WEBHOOK = os.environ.get('UPLOAD_NOTIFY_WEBHOOK', '1') != '0'
# HTTPS 配置
from pathlib import Path
CERT_DIR = Path("/www/server/panel/vhost/cert/47.112.187.172")
CERT_FILE = CERT_DIR / "fullchain.pem"
KEY_FILE = CERT_DIR / "privkey.pem"
HTTP_PORT = int(os.environ.get('UPLOAD_PORT', '8080'))
# 智能列名识别关键词映射
FIELD_KEYWORDS = {
'idField': ['学号', 'studentid', 'id', '编号', 'no', '学号编号', '学生编号', 'student_id', '学号id'],
'nameField': ['姓名', 'name', '学生姓名', 'studentname', '学生名称', 'student_name', '名字'],
'idCardField': ['身份证', 'idcard', '身份证号', 'id_card', '证件号', '身份证号', 'identity'],
'phoneField': ['手机', '电话', 'phone', 'tel', 'mobile', '联系方式', '联系电话', '手机号'],
'groupField': ['班级', 'group', 'class', '班级名称', 'department', '年级', '专业']
}
# 可选依赖检测
try:
import pandas as pd
from difflib import SequenceMatcher
PANDAS_AVAILABLE = True
except ImportError:
PANDAS_AVAILABLE = False
print("警告: pandas未安装,名单预设管理功能将受限")
try:
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
OPENPYXL_AVAILABLE = True
except ImportError:
OPENPYXL_AVAILABLE = False
print("警告: openpyxl未安装,Excel导出功能将受限")
try:
from PIL import Image
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
print("警告: PIL/Pillow未安装,图标自动生成功能将不可用")
+19
View File
@@ -0,0 +1,19 @@
# ========== 数据库配置 ==========
database:
# 数据库类型:sqlite 或 mysql
type: sqlite
# SQLite 配置(type=sqlite 时使用)
# path 可以是相对路径(相对于项目根目录)或绝对路径
sqlite:
path: data/app.db
# MySQL 配置(type=mysql 时使用)
mysql:
host: localhost
port: 3306
user: root
password: ''
database: form_system
charset: utf8mb4
+2115
View File
File diff suppressed because it is too large Load Diff
+394
View File
@@ -0,0 +1,394 @@
"""
统一数据库管理器
读取 config.yml,根据配置返回对应数据库的连接。
切换数据库只需修改 config.yml 中的 type 字段。
核心设计:
- get_db_connection() 返回的连接,其 cursor 自动适配 SQL 方言差异
- 调用方(database.py 等)继续写 SQLite 风格的 SQL(? 占位符、INSERT OR REPLACE 等)
- MySQL 模式下,游标包装层自动将 SQL 转换为 MySQL 兼容语法
- 因此 database.py 的 85+ 处 cursor.execute 无需任何修改
"""
import os
import re
import yaml
from contextlib import contextmanager
from config import BASE_DIR, DATA_DIR
# ========== 读取配置 ==========
_config_path = os.path.join(BASE_DIR, 'config.yml')
def _load_db_config():
"""从 config.yml 加载数据库配置,文件不存在时使用默认值"""
if not os.path.exists(_config_path):
return {
'database': {
'type': 'sqlite',
'sqlite': {'path': os.path.join(DATA_DIR, 'app.db')},
'mysql': {}
}
}
with open(_config_path, 'r', encoding='utf-8') as f:
cfg = yaml.safe_load(f) or {}
if 'database' not in cfg:
cfg['database'] = {'type': 'sqlite'}
return cfg
_db_config = _load_db_config()
_db_section = _db_config.get('database', {})
# 数据库类型:sqlite / mysql
DB_TYPE = _db_section.get('type', 'sqlite')
# SQLite 路径(相对路径自动转换为绝对路径)
_sqlite_path = _db_section.get('sqlite', {}).get('path', 'data/app.db')
if not os.path.isabs(_sqlite_path):
_sqlite_path = os.path.join(BASE_DIR, _sqlite_path)
DB_PATH = _sqlite_path
# MySQL 连接参数
_mysql_cfg = _db_section.get('mysql', {})
MYSQL_CONFIG = {
'host': _mysql_cfg.get('host', 'localhost'),
'port': int(_mysql_cfg.get('port', 3306)),
'user': _mysql_cfg.get('user', 'root'),
'password': _mysql_cfg.get('password', ''),
'database': _mysql_cfg.get('database', 'form_system'),
'charset': _mysql_cfg.get('charset', 'utf8mb4'),
'blob_type': _mysql_cfg.get('blob_type', 'LONGBLOB'),
'max_allowed_packet': int(_mysql_cfg.get('max_allowed_packet', 0)),
}
# ========== SQL 方言转换 ==========
def _translate_sql(sql):
"""
将 SQLite 风格 SQL 转换为 MySQL 兼容语法。
仅在 MySQL 模式下调用;SQLite 模式下原样返回。
转换规则:
1. ? 占位符 → %s
2. INSERT OR REPLACE INTO → REPLACE INTO
3. INTEGER PRIMARY KEY AUTOINCREMENT → INTEGER PRIMARY KEY AUTO_INCREMENT
4. CREATE TABLE IF NOT EXISTS → 保持不变(MySQL 也支持)
5. BLOB 类型 → LONGBLOB(MySQL 的 BLOB 只有 64KB,LONGBLOB 可达 4GB)
"""
# 1. 参数占位符 ? → %s
# 注意:只转换独立的 ?,不碰字符串字面量内的问号
# 简单方案:按 ? 出现的位置逐个替换(SQL 中的 ? 一定是参数占位符)
sql = sql.replace('?', '%s')
# 2. INSERT OR REPLACE INTO → REPLACE INTO
sql = re.sub(
r'INSERT\s+OR\s+REPLACE\s+INTO',
'REPLACE INTO',
sql,
flags=re.IGNORECASE
)
# 3. AUTOINCREMENT → AUTO_INCREMENT
sql = re.sub(
r'\bAUTOINCREMENT\b',
'AUTO_INCREMENT',
sql,
flags=re.IGNORECASE
)
# 4. BLOB → 配置的 blob_type(默认 LONGBLOB)
sql = re.sub(
r'\bBLOB\b',
MYSQL_CONFIG['blob_type'],
sql,
flags=re.IGNORECASE
)
return sql
# ========== 游标包装层 ==========
class _MySQLCursorWrapper:
"""
包装 MySQL 游标,自动将 SQLite 风格 SQL 转换为 MySQL 语法。
对调用方完全透明,行为与 sqlite3.Cursor 一致。
"""
def __init__(self, cursor):
self._cursor = cursor
def execute(self, sql, params=None):
translated = _translate_sql(sql)
if params is not None:
return self._cursor.execute(translated, params)
return self._cursor.execute(translated)
def executemany(self, sql, params_seq):
translated = _translate_sql(sql)
return self._cursor.executemany(translated, params_seq)
def fetchone(self):
return self._cursor.fetchone()
def fetchall(self):
return self._cursor.fetchall()
def fetchmany(self, size=None):
if size is not None:
return self._cursor.fetchmany(size)
return self._cursor.fetchmany()
@property
def rowcount(self):
return self._cursor.rowcount
@property
def lastrowid(self):
return self._cursor.lastrowid
@property
def description(self):
return self._cursor.description
def close(self):
return self._cursor.close()
def __iter__(self):
return iter(self._cursor)
def __getattr__(self, name):
"""透明代理其他属性"""
return getattr(self._cursor, name)
class _MySQLConnectionWrapper:
"""
包装 MySQL 连接,使 cursor() 返回包装后的游标。
commit / rollback / close 直接代理。
"""
def __init__(self, conn):
self._conn = conn
def cursor(self):
return _MySQLCursorWrapper(self._conn.cursor())
def commit(self):
return self._conn.commit()
def rollback(self):
return self._conn.rollback()
def close(self):
return self._conn.close()
def __getattr__(self, name):
"""透明代理其他属性"""
return getattr(self._conn, name)
# ========== 统一连接管理 ==========
@contextmanager
def get_db_connection():
"""
获取数据库连接上下文管理器。
根据 config.yml 的 type 字段自动选择 SQLite 或 MySQL。
返回的连接对象具有统一的接口:
- cursor().execute() 接受 SQLite 风格 SQL(? 占位符、INSERT OR REPLACE 等)
- MySQL 模式下自动转换为 MySQL 兼容语法
- row_factory 返回 dict-like 行(SQLite 用 Row,MySQL 用 DictCursor)
- commit / rollback / close 行为一致
"""
if DB_TYPE == 'sqlite':
import sqlite3
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
try:
yield conn
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
elif DB_TYPE == 'mysql':
try:
import pymysql
except ImportError:
raise RuntimeError("MySQL 模式需要安装 pymysql:pip install pymysql")
conn = pymysql.connect(
host=MYSQL_CONFIG['host'],
port=MYSQL_CONFIG['port'],
user=MYSQL_CONFIG['user'],
password=MYSQL_CONFIG['password'],
database=MYSQL_CONFIG['database'],
charset=MYSQL_CONFIG['charset'],
cursorclass=pymysql.cursors.DictCursor
)
try:
yield _MySQLConnectionWrapper(conn)
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
else:
raise ValueError(f"不支持的数据库类型: {DB_TYPE}(可选值: sqlite / mysql)")
def is_sqlite():
"""当前是否为 SQLite 模式"""
return DB_TYPE == 'sqlite'
def is_mysql():
"""当前是否为 MySQL 模式"""
return DB_TYPE == 'mysql'
# ========== 跨数据库辅助函数 ==========
def list_table_names(conn):
"""获取所有表名(兼容 SQLite / MySQL)"""
cursor = conn.cursor()
if is_sqlite():
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
return [row['name'] for row in cursor.fetchall()]
else:
cursor.execute("""
SELECT TABLE_NAME as name
FROM information_schema.tables
WHERE TABLE_SCHEMA = %s AND TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_NAME
""", (MYSQL_CONFIG['database'],))
return [row['name'] for row in cursor.fetchall()]
def table_exists(conn, table_name):
"""检查表是否存在(兼容 SQLite / MySQL)"""
cursor = conn.cursor()
if is_sqlite():
cursor.execute(
"SELECT name FROM sqlite_master WHERE type='table' AND name = ?",
(table_name,)
)
return cursor.fetchone() is not None
else:
cursor.execute("""
SELECT TABLE_NAME
FROM information_schema.tables
WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s
""", (MYSQL_CONFIG['database'], table_name))
return cursor.fetchone() is not None
def get_table_columns(conn, table_name):
"""
获取表的列信息(兼容 SQLite / MySQL)
返回列表,每项为 dict: {name, type, notnull, pk, dflt}
"""
cursor = conn.cursor()
if is_sqlite():
cursor.execute(f"PRAGMA table_info({table_name})")
return [
{
'name': row['name'],
'type': row['type'],
'notnull': row['notnull'],
'pk': row['pk'],
'dflt': row['dflt_value']
}
for row in cursor.fetchall()
]
else:
cursor.execute("""
SELECT COLUMN_NAME as name, DATA_TYPE as type,
(IS_NULLABLE = 'NO') as notnull,
(COLUMN_KEY = 'PRI') as pk,
COLUMN_DEFAULT as dflt
FROM information_schema.columns
WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s
ORDER BY ORDINAL_POSITION
""", (MYSQL_CONFIG['database'], table_name))
return [
{
'name': row['name'],
'type': row['type'],
'notnull': 1 if row['notnull'] else 0,
'pk': 1 if row['pk'] else 0,
'dflt': row['dflt']
}
for row in cursor.fetchall()
]
def get_db_size():
"""
获取数据库文件大小(字节)。
SQLite:返回 .db 文件大小
MySQL:返回该数据库所有表的总数据大小
"""
if is_sqlite():
if os.path.exists(DB_PATH):
return os.path.getsize(DB_PATH)
return 0
else:
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT COALESCE(SUM(data_length + index_length), 0) as size
FROM information_schema.tables
WHERE table_schema = %s
""", (MYSQL_CONFIG['database'],))
row = cursor.fetchone()
return row['size'] if row else 0
def vacuum():
"""执行数据库优化(SQLite: VACUUM, MySQL: OPTIMIZE TABLE)"""
if is_sqlite():
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute('VACUUM')
else:
with get_db_connection() as conn:
cursor = conn.cursor()
tables = list_table_names(conn)
for table_name in tables:
cursor.execute(f"OPTIMIZE TABLE `{table_name}`")
def init_mysql_session_vars():
"""
MySQL 启动时配置会话级变量。
- SET GLOBAL max_allowed_packet:提升单条 SQL 最大尺寸(需 SUPER 权限)
- SET SESSION max_allowed_packet:当前连接生效
如果用户权限不足或 max_allowed_packet=0(未配置),跳过。
"""
if not is_mysql():
return
if MYSQL_CONFIG['max_allowed_packet'] <= 0:
return
try:
with get_db_connection() as conn:
cursor = conn.cursor()
val = MYSQL_CONFIG['max_allowed_packet']
try:
cursor.execute(f"SET GLOBAL max_allowed_packet = {val}")
print(f"✅ MySQL max_allowed_packet 全局已设为 {val} ({val // 1024 // 1024}MB)")
except Exception as e:
print(f"⚠️ 设置 GLOBAL max_allowed_packet 失败(可能权限不足,仅设置 SESSION 级): {e}")
cursor.execute(f"SET SESSION max_allowed_packet = {val}")
print(f"✅ MySQL max_allowed_packet 会话级已设为 {val} ({val // 1024 // 1024}MB)")
except Exception as e:
print(f"⚠️ MySQL 会话变量配置失败: {e}")
+501
View File
@@ -0,0 +1,501 @@
"""
数据库管理API - 提供数据库状态查询、SQL执行、VACUUM优化等功能
兼容 SQLite / MySQL
"""
import os
import re
import tempfile
import glob
from flask import jsonify, request, send_from_directory
from database import get_db_connection, get_all_forms, get_form_stats
from db import DB_PATH, is_sqlite, is_mysql, list_table_names, get_table_columns, table_exists, get_db_size, vacuum as db_vacuum
from datetime import datetime, timedelta
from config import TEMPLATES_DIR
# ========== 数据库统计信息 ==========
def get_db_stats():
"""获取数据库统计信息"""
stats = {
'db_size': 0,
'tables': [],
'total_records': 0,
'file_storage': 0,
'data_storage': 0,
'forms': []
}
# 获取数据库大小
stats['db_size'] = get_db_size()
with get_db_connection() as conn:
cursor = conn.cursor()
# 获取所有表
table_names = list_table_names(conn)
for table_name in table_names:
# 获取表记录数
cursor.execute(f"SELECT COUNT(*) as count FROM `{table_name}`")
record_count = cursor.fetchone()['count']
stats['total_records'] += record_count
# 获取表结构
columns = get_table_columns(conn, table_name)
column_info = [{'name': c['name'], 'type': c['type']} for c in columns]
stats['tables'].append({
'name': table_name,
'record_count': record_count,
'columns': column_info
})
# 获取文件存储大小
cursor.execute("SELECT COALESCE(SUM(file_size), 0) as total FROM files")
file_result = cursor.fetchone()
stats['file_storage'] = file_result['total'] if file_result else 0
# 获取数据存储大小(估算)
cursor.execute("SELECT COALESCE(SUM(LENGTH(data)), 0) as total FROM submissions")
data_result = cursor.fetchone()
stats['data_storage'] = data_result['total'] if data_result else 0
# 获取每个表单的存储详情
forms = get_all_forms()
for form in forms:
form_id = form['id']
form_stats = get_form_stats(form_id)
# 计算该表单的数据大小
with get_db_connection() as conn:
cursor = conn.cursor()
# 获取提交数据大小
cursor.execute("SELECT COALESCE(SUM(LENGTH(data)), 0) as total FROM submissions WHERE form_id = ?", (form_id,))
data_size = cursor.fetchone()['total'] or 0
# 获取文件大小
cursor.execute("SELECT COALESCE(SUM(file_size), 0) as total FROM files WHERE form_id = ?", (form_id,))
file_size = cursor.fetchone()['total'] or 0
stats['forms'].append({
'id': form_id,
'title': form.get('title', '未命名表单'),
'submission_count': form_stats.get('submitted_count', 0),
'file_count': form_stats.get('file_count', 0),
'data_size': data_size,
'file_size': file_size,
'total_size': data_size + file_size
})
return stats
def get_table_list():
"""获取表列表及结构"""
tables = []
with get_db_connection() as conn:
cursor = conn.cursor()
table_names = list_table_names(conn)
for table_name in table_names:
# 获取记录数
cursor.execute(f"SELECT COUNT(*) as count FROM `{table_name}`")
record_count = cursor.fetchone()['count']
# 获取列信息
columns = get_table_columns(conn, table_name)
tables.append({
'name': table_name,
'record_count': record_count,
'columns': [{'name': c['name'], 'type': c['type'], 'notnull': c['notnull'], 'pk': c['pk']} for c in columns]
})
return tables
def execute_sql(sql):
"""执行SQL命令"""
result = {
'success': False,
'rows': [],
'affected_rows': 0,
'execution_time': 0,
'error': None
}
start_time = datetime.now()
try:
with get_db_connection() as conn:
cursor = conn.cursor()
# MySQL 模式下自动转换 SQLite 风格 SQL
if is_mysql():
from db import _translate_sql
sql = _translate_sql(sql)
# 执行SQL
cursor.execute(sql)
# 判断是否是查询
sql_upper = sql.strip().upper()
is_query = sql_upper.startswith('SELECT') or sql_upper.startswith('PRAGMA') or sql_upper.startswith('SHOW') or sql_upper.startswith('DESCRIBE')
if is_query:
rows = cursor.fetchall()
result['rows'] = [dict(row) for row in rows]
else:
result['affected_rows'] = cursor.rowcount
result['success'] = True
except Exception as e:
result['error'] = str(e)
end_time = datetime.now()
result['execution_time'] = round((end_time - start_time).total_seconds() * 1000, 2)
return result
def browse_table(table_name, limit=50, offset=0):
"""浏览表数据"""
result = {
'rows': [],
'total': 0,
'error': None
}
try:
with get_db_connection() as conn:
cursor = conn.cursor()
# 获取总数
cursor.execute(f"SELECT COUNT(*) as count FROM `{table_name}`")
result['total'] = cursor.fetchone()['count']
# 获取数据
cursor.execute(f"SELECT * FROM `{table_name}` LIMIT ? OFFSET ?", (limit, offset))
rows = cursor.fetchall()
result['rows'] = [dict(row) for row in rows]
except Exception as e:
result['error'] = str(e)
return result
def vacuum_database():
"""执行VACUUM优化"""
result = {
'success': False,
'before_size': 0,
'after_size': 0,
'freed_space': 0,
'error': None
}
try:
# 获取优化前大小
result['before_size'] = get_db_size()
# 执行优化(SQLite: VACUUM, MySQL: OPTIMIZE TABLE)
db_vacuum()
# 获取优化后大小
result['after_size'] = get_db_size()
result['freed_space'] = max(0, result['before_size'] - result['after_size'])
result['success'] = True
except Exception as e:
result['error'] = str(e)
return result
def get_temp_zip_stats():
"""获取临时ZIP文件统计信息 (从文件系统temp文件夹搜索)"""
stats = {
'count': 0,
'total_size': 0,
'files': [],
'earliest_expires_minutes': None,
'is_expired': False
}
try:
temp_dir = tempfile.gettempdir()
# 查找所有 form_zip_ 开头的临时ZIP文件
pattern = os.path.join(temp_dir, 'form_zip_*.zip')
zip_files = glob.glob(pattern)
stats['count'] = len(zip_files)
now = datetime.now()
earliest_expires = None
for filepath in zip_files:
try:
filename = os.path.basename(filepath)
file_size = os.path.getsize(filepath)
file_mtime = datetime.fromtimestamp(os.path.getmtime(filepath))
stats['total_size'] += file_size
# 从文件名解析表单ID
# 格式: form_zip_{form_id}_{YYYYMMDD}_{HHMMSS}_{uuid}.zip
parts = filename.replace('.zip', '').split('_')
form_id = parts[2] if len(parts) >= 3 else None
time_str = parts[3] + '_' + parts[4] if len(parts) >= 5 else None
# 计算过期时间(临时ZIP默认30分钟过期)
# 使用文件修改时间作为上传时间
uploaded_at = file_mtime
expires_at = uploaded_at + timedelta(minutes=30)
remaining_minutes = int((expires_at - now).total_seconds() / 60)
if remaining_minutes > 0:
if earliest_expires is None or remaining_minutes < earliest_expires:
earliest_expires = remaining_minutes
else:
# 已过期
stats['is_expired'] = True
file_info = {
'filename': filename,
'filepath': filepath,
'file_size': file_size,
'form_id': form_id,
'uploaded_at': uploaded_at.isoformat(),
'expires_at': expires_at.isoformat(),
'remaining_minutes': remaining_minutes
}
# 如果有表单ID,获取表单名称
if form_id:
try:
with get_db_connection() as conn:
cursor = conn.cursor()
cursor.execute("SELECT title FROM forms WHERE id = ?", (form_id,))
form_row = cursor.fetchone()
if form_row:
file_info['form_title'] = form_row['title']
else:
file_info['form_title'] = '未知表单'
except:
file_info['form_title'] = '未知表单'
else:
file_info['form_title'] = '未知表单'
stats['files'].append(file_info)
except Exception as e:
# 跳过处理失败的文件
continue
stats['earliest_expires_minutes'] = earliest_expires if not stats['is_expired'] else -1
except Exception as e:
stats['error'] = str(e)
return stats
def cleanup_all_temp_zips():
"""清理所有临时ZIP文件 (从文件系统temp文件夹删除)"""
result = {
'success': False,
'deleted_count': 0,
'freed_size': 0,
'error': None,
'deleted_files': []
}
try:
temp_dir = tempfile.gettempdir()
# 查找所有 form_zip_ 开头的临时ZIP文件
pattern = os.path.join(temp_dir, 'form_zip_*.zip')
zip_files = glob.glob(pattern)
total_freed = 0
deleted_count = 0
for filepath in zip_files:
try:
filename = os.path.basename(filepath)
file_size = os.path.getsize(filepath)
# 删除文件
os.remove(filepath)
deleted_count += 1
total_freed += file_size
result['deleted_files'].append({
'filename': filename,
'file_size': file_size
})
except Exception as e:
# 跳过删除失败的文件
continue
result['deleted_count'] = deleted_count
result['freed_size'] = total_freed
result['success'] = True
except Exception as e:
result['error'] = str(e)
return result
# ========== API路由注册 ==========
def register_db_manage_routes(app, require_admin):
"""注册数据库管理API路由"""
@app.route('/db_manage')
@require_admin
def db_manage_page():
"""数据库管理页面"""
return send_from_directory(TEMPLATES_DIR, 'db_manage.html')
@app.route('/api/db/stats')
@require_admin
def api_db_stats():
"""获取数据库统计信息"""
try:
stats = get_db_stats()
return jsonify(stats)
except Exception as e:
return jsonify(error=str(e)), 500
@app.route('/api/db/tables')
@require_admin
def api_db_tables():
"""获取表列表"""
try:
tables = get_table_list()
return jsonify({'tables': tables})
except Exception as e:
return jsonify(error=str(e)), 500
@app.route('/api/db/execute', methods=['POST'])
@require_admin
def api_db_execute():
"""执行SQL命令"""
try:
data = request.get_json()
sql = data.get('sql', '').strip()
if not sql:
return jsonify(success=False, error='SQL命令不能为空'), 400
# 禁止危险操作
dangerous_keywords = ['DROP DATABASE', 'ATTACH', 'DETACH']
for keyword in dangerous_keywords:
if keyword.upper() in sql.upper():
return jsonify(success=False, error=f'禁止执行包含 {keyword} 的命令'), 403
result = execute_sql(sql)
return jsonify(result)
except Exception as e:
return jsonify(success=False, error=str(e)), 500
@app.route('/api/db/browse')
@require_admin
def api_db_browse():
"""浏览表数据"""
try:
table_name = request.args.get('table', '')
limit = int(request.args.get('limit', 50))
offset = int(request.args.get('offset', 0))
if not table_name:
return jsonify(error='表名不能为空'), 400
# 验证表名存在
with get_db_connection() as conn:
if not table_exists(conn, table_name):
return jsonify(error='表不存在'), 404
result = browse_table(table_name, limit, offset)
if result['error']:
return jsonify(error=result['error']), 500
return jsonify(result)
except Exception as e:
return jsonify(error=str(e)), 500
@app.route('/api/db/sessions')
@require_admin
def api_db_sessions():
"""获取所有活跃会话(管理员)"""
from database import get_all_active_sessions
try:
sessions = get_all_active_sessions()
return jsonify({
'sessions': sessions,
'count': len(sessions)
})
except Exception as e:
return jsonify(error=str(e)), 500
@app.route('/api/db/sessions/cleanup', methods=['POST'])
@require_admin
def api_cleanup_sessions():
"""手动清理过期会话"""
from database import cleanup_expired_sessions
try:
count = cleanup_expired_sessions()
return jsonify({
'success': True,
'cleaned_count': count,
'message': f'已清理 {count} 个过期会话'
})
except Exception as e:
return jsonify(error=str(e)), 500
@app.route('/api/db/vacuum', methods=['POST'])
@require_admin
def api_db_vacuum():
"""执行VACUUM优化"""
try:
result = vacuum_database()
if result['success']:
return jsonify(result)
else:
return jsonify(result), 500
except Exception as e:
return jsonify(success=False, error=str(e)), 500
@app.route('/api/db/temp-zip-stats')
@require_admin
def api_temp_zip_stats():
"""获取临时ZIP文件统计信息"""
try:
stats = get_temp_zip_stats()
return jsonify(stats)
except Exception as e:
return jsonify(success=False, error=str(e)), 500
@app.route('/api/db/temp-zip-cleanup', methods=['POST'])
@require_admin
def api_temp_zip_cleanup():
"""清理所有临时ZIP文件"""
try:
result = cleanup_all_temp_zips()
if result['success']:
return jsonify(result)
else:
return jsonify(result), 500
except Exception as e:
return jsonify(success=False, error=str(e)), 500
+51
View File
@@ -0,0 +1,51 @@
"""把 forms 表字段 placeholder 里的字面 '\\n'(反斜杠+n) 转成真实换行。
用户编辑数据库时用字面 \\n 表示想换行, 但 textarea 的 placeholder 需要
真实换行符才能渲染成多行。本脚本只对 fields 数组中 placeholder 含字面
反斜杠+n 的字段做替换。
"""
import sqlite3
import json
import shutil
DB = r"D:\Downloads\app (4).db"
BACKSLASH_N = "\\n" # 字面: 反斜杠 + n (两个字符)
REAL_NL = "\n" # 真实换行符
def process():
shutil.copy2(DB, DB + ".bak2")
conn = sqlite3.connect(DB)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("SELECT fields FROM forms WHERE id='LcqcDtBM'")
raw = cur.fetchone()["fields"]
obj = json.loads(raw)
changed = 0
for fd in obj:
pl = fd.get("placeholder")
if isinstance(pl, str) and BACKSLASH_N in pl:
print("field", fd.get("name"), "before:", repr(pl))
fd["placeholder"] = pl.replace(BACKSLASH_N, REAL_NL)
print("field", fd.get("name"), "after :", repr(fd["placeholder"]))
changed += 1
new_raw = json.dumps(obj, ensure_ascii=False)
# 验证
o2 = json.loads(new_raw)
assert len(o2) == len(obj)
for fd in o2:
assert isinstance(fd["placeholder"], str)
cur.execute("UPDATE forms SET fields=? WHERE id='LcqcDtBM'", (new_raw,))
conn.commit()
# 回读验证
cur.execute("SELECT fields FROM forms WHERE id='LcqcDtBM'")
back = cur.fetchone()["fields"]
o3 = json.loads(back)
conn.close()
print("changed fields:", changed)
print("final placeholder repr:", repr(o3[3]["placeholder"]))
print("OK")
if __name__ == "__main__":
process()
+117
View File
@@ -0,0 +1,117 @@
"""修复 D:\\Downloads\\app (4).db 中 forms 表 fields 字段的裸控制字符。
根因: JSON 字符串内的控制字符(换行/制表符/回车等)必须以转义序列形式存在。
用户在数据库里直接敲入了真实换行符(\\n), 导致 json.loads 抛
"Invalid control character" 异常。
本脚本:
1. 备份原库为 <db>.bak
2. 仅对 forms.fields / allowed_exts / overwrite_verify 中的裸控制字符做转义
(保持已转义的 \\n \\t \\r 等不变)
3. 写回并验证每个受影响字段都能被 json.loads 正常解析
"""
import sqlite3
import shutil
import re
import sys
DB = r"D:\Downloads\app (4).db"
def escape_raw_controls(s: str) -> str:
"""把字符串里的裸控制字符(0x00-0x1F, 0x7F)替换为 \\uXXXX 转义。
规则: 只处理"裸"控制字符。若某个控制字符前一个字符是反斜杠(即它已是
转义序列的一部分, 如 \\n 表示已转义的换行), 则保持不变。
"""
out = []
i = 0
n = len(s)
while i < n:
ch = s[i]
o = ord(ch)
if o < 0x20 or o == 0x7F:
# 已是转义序列(前一个字符是反斜杠)则保留
if i > 0 and s[i - 1] == "\\":
out.append(ch)
else:
out.append("\\u%04x" % o)
i += 1
continue
out.append(ch)
i += 1
return "".join(out)
def validate(s: str) -> bool:
try:
import json
json.loads(s)
return True
except Exception:
return False
def main():
if not __import__("os").path.exists(DB):
print("DB not found:", DB)
return 1
# 1. 备份
bak = DB + ".bak"
shutil.copy2(DB, bak)
print("backup ->", bak)
conn = sqlite3.connect(DB)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
# 只修 forms 表这三个 JSON 列(与报错相关的都是 forms 相关的列)
cols = ["fields", "allowed_exts", "overwrite_verify"]
cur.execute("SELECT id FROM forms")
ids = [r["id"] for r in cur.fetchall()]
changed = 0
for fid in ids:
cur.execute("SELECT " + ", ".join(cols) + " FROM forms WHERE id=?", (fid,))
row = cur.fetchone()
updates = {}
for c in cols:
v = row[c]
if v is None:
continue
if validate(v):
print(f" [{fid}] {c}: OK (valid already)")
continue
new_v = escape_raw_controls(v)
if validate(new_v):
updates[c] = new_v
print(f" [{fid}] {c}: REPAIRED")
changed += 1
else:
print(f" [{fid}] {c}: FAILED to repair", file=sys.stderr)
if updates:
set_clause = ", ".join(f"{k}=?" for k in updates)
cur.execute(f"UPDATE forms SET {set_clause} WHERE id=?", (*updates.values(), fid))
conn.commit()
# 验证
cur.execute("SELECT id FROM forms")
all_ok = True
for r in cur.fetchall():
cur2 = conn.cursor()
cur2.execute("SELECT fields, allowed_exts FROM forms WHERE id=?", (r["id"],))
rr = cur2.fetchone()
for c in ("fields", "allowed_exts"):
v = rr[c]
if v is not None and not validate(v):
print("STILL BAD", r["id"], c)
all_ok = False
conn.close()
print("changed fields:", changed)
print("ALL VALID" if all_ok else "SOME STILL INVALID")
return 0 if all_ok else 1
if __name__ == "__main__":
sys.exit(main())
+442
View File
@@ -0,0 +1,442 @@
"""
系统监控 API - 提供实时性能数据和历史趋势数据
"""
import os
import time
from datetime import datetime, timedelta
from flask import jsonify, request, send_from_directory
from config import TEMPLATES_DIR
# 网络速率计算缓存
_last_net_io = None
_last_net_time = None
# 磁盘 IO 速率计算缓存(进程级)
_last_disk_io = None
_last_disk_time = None
# ========== 当前进程句柄(用于采集进程自身的 CPU/内存)==========
_proc = None
def _get_proc():
"""获取当前 Python 进程的 psutil.Process 对象(单例)"""
global _proc
if _proc is None:
try:
import psutil
_proc = psutil.Process(os.getpid())
# 第一次调用 cpu_percent 以初始化基准(返回值为 0.0,丢弃)
_proc.cpu_percent(interval=None)
except Exception:
_proc = None
return _proc
# ========== 实时数据采集 ==========
def get_realtime_stats(active_requests_counter, get_online_users_fn):
"""获取实时系统状态"""
global _last_net_io, _last_net_time, _last_disk_io, _last_disk_time
result = {
'cpu_percent': 0.0,
'memory': {'used': 0},
'disk': {'read_speed': 0, 'write_speed': 0},
'network': {'sent_speed': 0, 'recv_speed': 0},
'active_requests': 0,
'online_users': 0,
'timestamp': datetime.now().isoformat()
}
try:
import psutil
proc = _get_proc()
# CPU — 当前 Python 进程的 CPU 使用率
if proc:
result['cpu_percent'] = proc.cpu_percent(interval=None)
# 内存 — 当前 Python 进程的 RSS(常驻内存)
if proc:
mem_info = proc.memory_info()
rss = mem_info.rss # 进程实际占用的物理内存(字节)
result['memory'] = {
'used': rss,
}
# 磁盘 IO — 进程级读写速率(差分计算)
current_time_disk = time.time()
if proc:
try:
disk_io = proc.io_counters()
if _last_disk_io is not None and _last_disk_time is not None:
elapsed = current_time_disk - _last_disk_time
if elapsed > 0:
read_speed = max(0, (disk_io.read_bytes - _last_disk_io.read_bytes) / elapsed)
write_speed = max(0, (disk_io.write_bytes - _last_disk_io.write_bytes) / elapsed)
result['disk'] = {
'read_speed': int(read_speed),
'write_speed': int(write_speed),
}
_last_disk_io = disk_io
_last_disk_time = current_time_disk
except Exception:
pass
# 网络速率(差分计算,系统级)
current_net = psutil.net_io_counters()
current_time = time.time()
if _last_net_io is not None and _last_net_time is not None:
elapsed = current_time - _last_net_time
if elapsed > 0:
sent_speed = (current_net.bytes_sent - _last_net_io.bytes_sent) / elapsed
recv_speed = (current_net.bytes_recv - _last_net_io.bytes_recv) / elapsed
result['network'] = {
'sent_speed': max(0, int(sent_speed)),
'recv_speed': max(0, int(recv_speed))
}
_last_net_io = current_net
_last_net_time = current_time
except ImportError:
# psutil 未安装,返回模拟数据
pass
except Exception as e:
print(f"⚠️ 获取实时数据失败: {e}")
# 活跃请求数
result['active_requests'] = active_requests_counter.get('count', 0)
# 在线用户数
try:
result['online_users'] = get_online_users_fn()
except:
result['online_users'] = 0
return result
def collect_metrics_snapshot(active_requests_counter, get_online_users_fn):
"""采集指标快照并入库(每分钟执行一次)"""
try:
import psutil
from database import insert_system_metrics
proc = _get_proc()
# CPU — 进程自身(使用 interval=0.1 得到准确值)
if proc:
cpu_percent = proc.cpu_percent(interval=0.1)
else:
cpu_percent = 0.0
# 内存 — 进程自身 RSS
if proc:
mem_info = proc.memory_info()
rss = mem_info.rss
else:
rss = 0
# 磁盘 IO — 进程自身累计读写字节(存快照值,历史图表做差分)
disk_read_bytes = 0
disk_write_bytes = 0
if proc:
try:
io_counters = proc.io_counters()
disk_read_bytes = io_counters.read_bytes
disk_write_bytes = io_counters.write_bytes
except Exception:
pass
# 网络(使用当前快照,不是速率)
net = psutil.net_io_counters()
active_req = active_requests_counter.get('count', 0)
online_users = 0
try:
online_users = get_online_users_fn()
except:
pass
insert_system_metrics(
cpu_percent=cpu_percent,
memory_used=rss,
disk_read_bytes=disk_read_bytes,
disk_write_bytes=disk_write_bytes,
net_sent_bytes=net.bytes_sent,
net_recv_bytes=net.bytes_recv,
active_requests=active_req,
online_users=online_users
)
except ImportError:
print("⚠️ psutil 未安装,跳过系统指标采集")
except Exception as e:
print(f"⚠️ 采集系统指标失败: {e}")
# ========== 历史数据查询 ==========
def _get_time_range(granularity_key):
"""根据时间粒度返回开始时间和采样粒度"""
now = datetime.now()
mapping = {
'1h': (now - timedelta(hours=1), '5m'), # 1小时→5分钟一档
'6h': (now - timedelta(hours=6), '10m'), # 6小时→10分钟一档
'24h': (now - timedelta(hours=24), '30m'), # 24小时→30分钟一档
'7d': (now - timedelta(days=7), '2h'), # 7天→2小时一档
'30d': (now - timedelta(days=30), '12h'), # 30天→12小时一档
}
start_time, sample_granularity = mapping.get(granularity_key, (now - timedelta(hours=1), '5m'))
return start_time.isoformat(), now.isoformat(), sample_granularity
def get_history_data(granularity_key):
"""获取历史统计数据"""
from database import (
get_system_metrics_history,
get_api_stats_history,
get_business_metrics_history
)
start_time, end_time, sample_gran = _get_time_range(granularity_key)
# 将 sample_gran 转换为分钟数(与 database.py 的 granularity_minutes 映射一致)
gran_minutes = {
'5m': 5, '10m': 10, '15m': 15,
'30m': 30, '1h': 60, '2h': 120,
'6h': 360, '12h': 720, '1d': 1440
}.get(sample_gran, 5)
# 系统指标
metrics = get_system_metrics_history(start_time, end_time, sample_gran)
timestamps = []
cpu_data = []
memory_data = []
net_sent_data = []
net_recv_data = []
disk_read_data = []
disk_write_data = []
# 用于计算网络速率(差分)
prev_net_sent = None
prev_net_recv = None
# 用于计算磁盘 IO 速率(差分)
prev_disk_read = None
prev_disk_write = None
prev_ts = None
for i, row in enumerate(metrics):
try:
ts = datetime.fromisoformat(row['timestamp'])
except:
continue
# 格式化时间标签
if granularity_key in ('1h', '6h', '24h'):
label = ts.strftime('%H:%M')
elif granularity_key == '7d':
label = ts.strftime('%m/%d %H:%M')
else:
label = ts.strftime('%m/%d')
timestamps.append(label)
cpu_data.append(round(row.get('cpu_percent') or 0, 1))
mem_used = row.get('memory_used') or 0
memory_data.append(round(mem_used / 1024 / 1024, 1)) # MB
# 网络速率(差分/时间间隔,KB/s)
cur_sent = row.get('net_sent_bytes') or 0
cur_recv = row.get('net_recv_bytes') or 0
# 磁盘 IO 速率(差分/时间间隔,KB/s)
cur_disk_read = row.get('disk_read_bytes') or 0
cur_disk_write = row.get('disk_write_bytes') or 0
if prev_ts is not None:
elapsed = (ts - prev_ts).total_seconds()
if elapsed > 0:
sent_speed = max(0, (cur_sent - prev_net_sent) / elapsed / 1024)
recv_speed = max(0, (cur_recv - prev_net_recv) / elapsed / 1024)
read_speed = max(0, (cur_disk_read - prev_disk_read) / elapsed / 1024)
write_speed = max(0, (cur_disk_write - prev_disk_write) / elapsed / 1024)
else:
sent_speed = recv_speed = read_speed = write_speed = 0
else:
sent_speed = recv_speed = read_speed = write_speed = 0
net_sent_data.append(round(sent_speed, 2))
net_recv_data.append(round(recv_speed, 2))
disk_read_data.append(round(read_speed, 2))
disk_write_data.append(round(write_speed, 2))
prev_net_sent = cur_sent
prev_net_recv = cur_recv
prev_disk_read = cur_disk_read
prev_disk_write = cur_disk_write
prev_ts = ts
# 业务指标
biz_rows = get_business_metrics_history(start_time, end_time, sample_gran)
from collections import defaultdict
biz_by_ts = defaultdict(dict)
for row in biz_rows:
try:
ts = datetime.fromisoformat(row['timestamp'])
if granularity_key in ('1h', '6h', '24h'):
label = ts.strftime('%H:%M')
elif granularity_key == '7d':
label = ts.strftime('%m/%d %H:%M')
else:
label = ts.strftime('%m/%d')
biz_by_ts[label][row['metric_name']] = row.get('total_value') or 0
except:
pass
forms_created = []
files_uploaded_mb = []
user_logins = []
api_calls = []
form_submissions = []
file_downloads = []
data_exports = []
for label in timestamps:
biz = biz_by_ts.get(label, {})
forms_created.append(biz.get('forms_created', 0))
files_uploaded_mb.append(round(biz.get('files_uploaded', 0) / 1024 / 1024, 2))
user_logins.append(int(biz.get('user_login', 0)))
api_calls.append(int(biz.get('api_calls', 0)))
form_submissions.append(int(biz.get('form_submissions', 0)))
file_downloads.append(int(biz.get('file_downloads', 0)))
data_exports.append(int(biz.get('data_exports', 0)))
# API 调用(从 api_stats 表取总调用数填充)
api_rows = get_api_stats_history(start_time, end_time)
api_by_label = defaultdict(int)
for row in api_rows:
try:
ts = datetime.fromisoformat(row['timestamp'])
if granularity_key in ('1h', '6h', '24h'):
label = ts.strftime('%H:%M')
elif granularity_key == '7d':
label = ts.strftime('%m/%d %H:%M')
else:
label = ts.strftime('%m/%d')
api_by_label[label] += int(row.get('total_count') or 0)
except:
pass
api_calls = [int(api_by_label.get(label, 0)) for label in timestamps]
return {
'timestamps': timestamps,
'cpu': cpu_data,
'memory': memory_data,
'net_sent': net_sent_data,
'net_recv': net_recv_data,
'disk_read': disk_read_data,
'disk_write': disk_write_data,
'business': {
'forms_created': forms_created,
'files_uploaded_mb': files_uploaded_mb,
'user_logins': user_logins,
'api_calls': api_calls,
'form_submissions': form_submissions,
'file_downloads': file_downloads,
'data_exports': data_exports,
}
}
# ========== 路由注册 ==========
def register_monitor_routes(app, require_admin, active_requests_counter):
"""注册监控API路由"""
from database import cleanup_monitor_data, get_online_users_count
@app.route('/monitor')
@require_admin
def monitor_page():
"""监控仪表盘页面"""
return send_from_directory(TEMPLATES_DIR, 'monitor.html')
@app.route('/api/monitor/realtime')
@require_admin
def api_monitor_realtime():
"""获取实时系统状态(每秒调用)"""
try:
data = get_realtime_stats(active_requests_counter, get_online_users_count)
return jsonify(data)
except Exception as e:
return jsonify(error=str(e)), 500
@app.route('/api/monitor/history')
@require_admin
def api_monitor_history():
"""获取历史统计数据"""
try:
granularity = request.args.get('granularity', '1h')
valid = {'1h', '6h', '24h', '7d', '30d'}
if granularity not in valid:
granularity = '1h'
data = get_history_data(granularity)
return jsonify(data)
except Exception as e:
import traceback
traceback.print_exc()
return jsonify(error=str(e)), 500
@app.route('/api/monitor/cleanup', methods=['POST'])
@require_admin
def api_monitor_cleanup():
"""清理历史监控数据"""
try:
body = request.get_json() or {}
before_date = body.get('before_date', '')
if not before_date:
return jsonify(success=False, error='before_date 参数不能为空'), 400
# 尝试解析日期
try:
# 支持 ISO 格式和 yyyy-MM-dd 格式
if 'T' in before_date:
datetime.fromisoformat(before_date)
else:
before_date = before_date + 'T00:00:00'
datetime.fromisoformat(before_date)
except ValueError:
return jsonify(success=False, error='日期格式无效,请使用 yyyy-MM-dd 或 ISO 格式'), 400
deleted_count = cleanup_monitor_data(before_date)
return jsonify(success=True, deleted_count=deleted_count)
except Exception as e:
return jsonify(success=False, error=str(e)), 500
@app.route('/api/monitor/count_before', methods=['GET'])
@require_admin
def api_monitor_count_before():
"""查询某日期前的数据条数(用于清理确认对话框)"""
try:
from database import get_db_connection
before_date = request.args.get('before_date', '')
if not before_date:
return jsonify(count=0)
if 'T' not in before_date:
before_date = before_date + 'T00:00:00'
with get_db_connection() as conn:
cursor = conn.cursor()
total = 0
for table in ('system_metrics', 'api_stats', 'business_metrics'):
try:
cursor.execute(f'SELECT COUNT(*) as c FROM {table} WHERE timestamp < ?', (before_date,))
total += cursor.fetchone()['c']
except:
pass
return jsonify(count=total)
except Exception as e:
return jsonify(count=0, error=str(e))
+12
View File
@@ -0,0 +1,12 @@
# 注意:服务器为 Python 3.14,pandas 等含 C 扩展的包必须用较新版本才有对应 wheel,
# 旧版精确锁定(如 pandas==2.0.3)会触发源码编译并在新 setuptools 下失败。
Flask==2.3.3
flask-cors>=4.0.0
APScheduler==3.10.4
pandas>=2.2
openpyxl>=3.1.2
psutil>=5.9.0
PyYAML>=6.0
pymysql>=1.1.0
requests>=2.31.0
pillow>=10.0.0
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""routes package"""
+44
View File
@@ -0,0 +1,44 @@
"""
认证装饰器(require_login / require_admin)
"""
from functools import wraps
from flask import request, jsonify, redirect
from database import get_session
def require_login(f):
"""登录校验装饰器 - 使用数据库存储会话"""
@wraps(f)
def decorated_function(*args, **kwargs):
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return redirect(f'/login?redirect={request.path}')
request.current_session = session_data
request.current_user = session_data['username']
request.current_role = session_data['role']
return f(*args, **kwargs)
return decorated_function
def require_admin(f):
"""管理员权限校验装饰器 - 使用数据库"""
@wraps(f)
def decorated_function(*args, **kwargs):
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return jsonify(error='未登录'), 401
if session_data['role'] != 'admin':
return jsonify(error='需要管理员权限'), 403
request.current_session = session_data
request.current_user = session_data['username']
return f(*args, **kwargs)
return decorated_function
+127
View File
@@ -0,0 +1,127 @@
"""
认证路由:登录/登出/当前用户
"""
from datetime import datetime
from flask import Blueprint, request, jsonify, make_response, redirect, send_from_directory
from database import get_user, get_session, create_session, delete_session
from config import TEMPLATES_DIR
from utils.helpers import hash_password, get_client_ip
from database import insert_business_metric
bp = Blueprint('auth', __name__)
@bp.route('/login')
def login_page():
"""登录页面"""
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if session_data:
redirect_url = request.args.get('redirect', '/admin')
if redirect_url.startswith('/error') or redirect_url == '/login':
redirect_url = '/admin'
return redirect(redirect_url)
return send_from_directory(TEMPLATES_DIR, 'login.html')
@bp.route('/api/login', methods=['POST'])
def api_login():
"""登录API - 使用数据库存储会话"""
try:
data = request.get_json()
username = data.get('username', '').strip()
password = data.get('password', '')
client_redirect = data.get('redirect', '')
if not username or not password:
return jsonify(success=False, message='用户名和密码不能为空'), 400
user = get_user(username)
if not user:
return jsonify(success=False, message='用户不存在'), 404
password_hash = hash_password(password)
if password_hash != user['password_hash']:
return jsonify(success=False, message='密码错误'), 401
ip_address = get_client_ip()
user_agent = request.headers.get('User-Agent', '')[:200]
session_data = create_session(
username=username,
role=user['role'],
ip_address=ip_address,
user_agent=user_agent,
data={
'login_time': datetime.now().isoformat(),
'login_method': 'web'
}
)
try:
insert_business_metric('user_login', 1)
except Exception:
pass
safe_redirect = '/admin'
if client_redirect and not client_redirect.startswith('/error') and client_redirect != '/login':
safe_redirect = client_redirect
resp = make_response(jsonify(
success=True,
role=user['role'],
redirect=safe_redirect
))
resp.set_cookie(
'session_id',
session_data['session_id'],
max_age=7*24*60*60,
httponly=True,
samesite='Strict',
secure=False
)
return resp
except Exception as e:
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
@bp.route('/api/logout', methods=['POST'])
def api_logout():
"""登出API"""
session_id = request.cookies.get('session_id')
if session_id:
delete_session(session_id)
resp = make_response(jsonify(success=True))
resp.delete_cookie('session_id')
return resp
@bp.route('/api/current_user')
def api_current_user():
"""获取当前登录用户信息"""
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return jsonify(logged_in=False)
username = session_data['username']
user = get_user(username)
if not user:
delete_session(session_id)
return jsonify(logged_in=False)
return jsonify({
'logged_in': True,
'username': username,
'role': session_data['role'],
'managed_forms': user.get('managed_forms', []),
'managed_presets': user.get('managed_presets', []),
'session_created_at': session_data.get('created_at'),
'session_expires_at': session_data.get('expires_at')
})
+215
View File
@@ -0,0 +1,215 @@
"""
数据导出 API:JSON / XLSX / CSV
"""
import re
import csv
import io as io_module
from datetime import datetime
from urllib.parse import quote
from flask import Blueprint, request, jsonify, send_file
from database import (
get_form, get_preset, get_form_submissions, get_form_files,
insert_business_metric, get_versions_as_of, build_status_students,
)
from config import OPENPYXL_AVAILABLE
from routes.auth import require_login
bp = Blueprint('export', __name__)
@bp.route('/api/export/<form_id>')
@require_login
def api_export_data(form_id):
"""导出表单数据,支持 JSON 和 XLSX 格式"""
try:
export_format = request.args.get('format', 'json')
as_of = request.args.get('asOf', '').strip()
form = get_form(form_id)
if not form:
return jsonify(error='表单不存在'), 404
preset_id = form.get('presetId')
if as_of:
# 按时间点导出:每个身份取该时间点的最新历史版本
versions_map = get_versions_as_of(form_id, as_of)
students = build_status_students(form, versions_map=versions_map)
else:
submissions = get_form_submissions(form_id)
students = build_status_students(form, submissions)
status_data = {
"formTitle": form.get('title', '未命名表单'),
"formId": form_id,
"total": len(students),
"submitted": len([s for s in students if s['submitted']]),
"students": students
}
if export_format == 'json':
try:
insert_business_metric('data_exports', 1)
except Exception:
pass
return jsonify({
'form': form,
'submissions': status_data
})
elif export_format == 'xlsx':
if not OPENPYXL_AVAILABLE:
return jsonify(error='openpyxl未安装,无法导出Excel'), 500
try:
insert_business_metric('data_exports', 1)
except Exception:
pass
return export_to_excel(form_id, form, status_data)
elif export_format == 'csv':
csv_io = io_module.StringIO()
writer = csv.writer(csv_io)
headers = ['学号', '姓名', '提交状态', '文件列表']
writer.writerow(headers)
for student in status_data.get('students', []):
files = ', '.join([f['filename']
for f in student.get('files', [])])
writer.writerow([
student.get('id', ''),
student.get('name', ''),
'已提交' if student.get('submitted') else '未提交',
files
])
csv_io.seek(0)
form_title = '未知表单'
try:
form_info = get_form(form_id)
if form_info:
form_title = form_info.get('title', '未知表单')
form_title = re.sub(r'[<>"/\\|?*]', '', form_title)[:20]
except:
pass
csv_filename = f'{form_title}_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv'
try:
ascii_csv = csv_filename.encode('ascii', 'ignore').decode()
except:
ascii_csv = f'form_{form_id}_export.csv'
encoded_csv = quote(csv_filename, safe='')
try:
insert_business_metric('data_exports', 1)
except Exception:
pass
return csv_io.getvalue(), 200, {
'Content-Type': 'text/csv; charset=utf-8-sig',
'Content-Disposition': f"attachment; filename=\"{ascii_csv}\"; filename*=UTF-8''{encoded_csv}",
'Cache-Control': 'no-cache, no-store, must-revalidate'
}
else:
return jsonify(error='不支持的导出格式'), 400
except Exception as e:
print(f"导出数据失败: {str(e)}")
import traceback
traceback.print_exc()
return jsonify(error=str(e)), 500
def export_to_excel(form_id, form_config, status_data):
"""导出数据到 Excel 文件"""
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from io import BytesIO
wb = Workbook()
ws = wb.active
ws.title = "表单数据"
header_font = Font(bold=True, color="FFFFFF")
header_fill = PatternFill(start_color="366092",
end_color="366092", fill_type="solid")
header_alignment = Alignment(horizontal="center", vertical="center")
cell_alignment = Alignment(horizontal="left", vertical="center")
border = Border(
left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin')
)
non_file_fields = [f for f in form_config.get('fields', []) if f['type'] not in ('file', 'page_break')]
field_names = [f['name'] for f in non_file_fields]
headers = ['学号', '姓名', '提交状态'] + field_names + ['文件列表']
for col, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = header_alignment
cell.border = border
row_num = 2
for student in status_data.get('students', []):
ws.cell(row=row_num, column=1, value=student.get('id', ''))
ws.cell(row=row_num, column=2, value=student.get('name', ''))
ws.cell(row=row_num, column=3,
value='已提交' if student.get('submitted') else '未提交')
student_data = student.get('data', {})
for col, field_name in enumerate(field_names, 4):
value = student_data.get(field_name, '')
ws.cell(row=row_num, column=col, value=value)
files = ', '.join([f['filename'] for f in student.get('files', [])])
ws.cell(row=row_num, column=len(headers), value=files)
for col in range(1, len(headers) + 1):
cell = ws.cell(row=row_num, column=col)
cell.border = border
cell.alignment = cell_alignment
row_num += 1
for col in range(1, len(headers) + 1):
col_letter = chr(64 + col) if col <= 26 else chr(64 +
(col - 1) // 26) + chr(65 + (col - 1) % 26)
ws.column_dimensions[col_letter].width = 20
output = BytesIO()
wb.save(output)
output.seek(0)
form_title = form_config.get('title', '未命名表单')
safe_title = "".join(
[c for c in form_title if c.isalnum() or c in (' ', '-', '_')]).strip()
time_str = datetime.now().strftime('%Y%m%d_%H%M%S')
excel_filename = f'{safe_title}_{time_str}.xlsx'
try:
ascii_filename = excel_filename.encode('ascii', 'ignore').decode()
if not ascii_filename:
ascii_filename = f'export_{form_id}.xlsx'
except:
ascii_filename = f'export_{form_id}.xlsx'
encoded_filename = quote(excel_filename, safe='')
response = send_file(
output,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
as_attachment=True,
download_name=ascii_filename
)
disposition = f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
response.headers['Content-Disposition'] = disposition
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
return response
+503
View File
@@ -0,0 +1,503 @@
"""
文件下载 / ZIP打包下载 API
"""
import os
import io
import re
import gc
import zipfile
import tempfile
import uuid
from datetime import datetime
from urllib.parse import quote
from flask import Blueprint, request, jsonify, send_file, after_this_request
from database import (
get_form, get_preset, get_file, get_file_by_name,
get_form_submissions, get_form_files, delete_file,
stream_form_files, get_form_file_count,
get_versions_as_of, get_version_archived_file,
)
from routes.auth import require_login
bp = Blueprint('files', __name__)
# 全局状态(由 app.py 注入)
zip_creation_locks = {}
temp_zip_files = {}
def init_app_state(locks, temp_zips):
"""由 app.py 调用,注入全局状态"""
global zip_creation_locks, temp_zip_files
zip_creation_locks = locks
temp_zip_files = temp_zips
@bp.route('/api/announcement_download/<int:file_id>')
def download_announcement_file(file_id):
"""下载表单公告附件(公开,供填写页面用户下载)"""
try:
from database import get_announcement_file
file_record = get_announcement_file(file_id)
if not file_record:
return jsonify(error='附件不存在'), 404
file_data = file_record['file_data']
filename = file_record['original_name'] or file_record['filename']
mime_type = file_record['mime_type'] or 'application/octet-stream'
try:
ascii_filename = filename.encode('ascii', 'ignore').decode()
if not ascii_filename:
ascii_filename = 'download'
except:
ascii_filename = 'download'
encoded_filename = quote(filename, safe='')
response = send_file(
io.BytesIO(file_data),
mimetype=mime_type,
as_attachment=True,
download_name=ascii_filename
)
disposition = f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
response.headers['Content-Disposition'] = disposition
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
except Exception as e:
return jsonify(error=f'服务器错误: {str(e)}'), 500
@bp.route('/api/download_file/<int:file_id>')
def download_file_by_id(file_id):
"""通过文件ID下载文件,临时ZIP文件下载后自动删除"""
try:
file_record = get_file(file_id)
if not file_record:
return jsonify(error='文件不存在'), 404
file_data = file_record['file_data']
filename = file_record['original_name'] or file_record['filename']
mime_type = file_record['mime_type'] or 'application/octet-stream'
is_temp_zip = filename.endswith('.zip') and (
'_自定义打包_' in filename or filename.count('_') >= 2)
form_title = '未知表单'
try:
form_info = get_form(file_record.get('form_id', ''))
if form_info:
form_title = form_info.get('title', '未知表单')
form_title = re.sub(r'[<>"/\\|?*]', '', form_title)[:20]
except:
pass
display_filename = f"{form_title}_{filename}"
try:
ascii_filename = display_filename.encode('ascii', 'ignore').decode()
if not ascii_filename:
ascii_filename = 'download'
except:
ascii_filename = 'download'
encoded_filename = quote(display_filename, safe='')
response = send_file(
io.BytesIO(file_data),
mimetype=mime_type,
as_attachment=True,
download_name=ascii_filename
)
disposition = f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
response.headers['Content-Disposition'] = disposition
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
if is_temp_zip:
@after_this_request
def remove_temp_file(response):
try:
delete_file(file_id)
print(f"✅ 临时ZIP文件已自动删除: {filename} (ID: {file_id})")
except Exception as e:
print(f"❌ 删除临时ZIP文件失败: {e}")
return response
from database import insert_business_metric
try:
insert_business_metric('file_downloads', 1)
except Exception:
pass
return response
except Exception as e:
return jsonify(error=f'服务器错误: {str(e)}'), 500
@bp.route('/api/download/<form_id>/<filename>')
def download_file(form_id, filename):
"""兼容旧版:通过表单ID和文件名下载"""
try:
file_record = get_file_by_name(form_id, filename)
if not file_record:
return jsonify(error='文件不存在'), 404
file_data = file_record['file_data']
original_name = file_record['original_name'] or filename
mime_type = file_record['mime_type'] or 'application/octet-stream'
is_temp_zip = bool(re.search(r'_\d{8}_\d{6}\.zip$', filename))
form_title = '未知表单'
student_id = ''
student_name = ''
submit_time = ''
try:
form_info = get_form(form_id)
if form_info:
form_title = form_info.get('title', '未知表单')
form_title = re.sub(r'[<>"/\\|?*]', '', form_title)[:30]
match = re.match(r'^([^_]+?)([0-9]+)_(.+?)\.([^.]+)$', original_name)
if match:
student_name = match.group(1)
student_id = match.group(2)
else:
parts = original_name.split('_')
if len(parts) >= 2:
student_name = parts[0]
student_id = parts[1].split('.')[0] if '.' in parts[1] else parts[1]
if file_record.get('created_at'):
try:
dt = datetime.fromisoformat(file_record['created_at'].replace('Z', '+00:00'))
submit_time = dt.strftime('%Y%m%d_%H%M%S')
except:
submit_time = datetime.now().strftime('%Y%m%d_%H%M%S')
except:
pass
if is_temp_zip:
time_str = datetime.now().strftime('%Y%m%d_%H%M%S')
display_name = f"{form_title}_{time_str}.zip"
else:
time_str = submit_time if submit_time else datetime.now().strftime('%Y%m%d_%H%M%S')
student_info = f"{student_id}{student_name}" if student_id and student_name else "未知"
student_info = re.sub(r'[<>"/\\|?*]', '', student_info)[:20]
ext = original_name.rsplit('.', 1)[-1] if '.' in original_name else ''
display_name = f"{form_title}_{student_info}_{time_str}.{ext}"
try:
ascii_name = display_name.encode('ascii', 'ignore').decode()
if not ascii_name:
ascii_name = 'download'
except:
ascii_name = 'download'
encoded_name = quote(display_name, safe='')
response = send_file(
io.BytesIO(file_data),
mimetype=mime_type,
as_attachment=True,
download_name=ascii_name
)
disposition = f"attachment; filename=\"{ascii_name}\"; filename*=UTF-8''{encoded_name}"
response.headers['Content-Disposition'] = disposition
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
if is_temp_zip:
@after_this_request
def remove_temp_file(response):
try:
delete_file(file_record['id'])
print(f"✅ 临时ZIP文件已自动删除: {filename}")
except Exception as e:
print(f"❌ 删除ZIP文件失败: {e}")
return response
return response
except Exception as e:
return jsonify(error=f'服务器错误: {str(e)}'), 500
@bp.route('/api/create_zip/<form_id>', methods=['POST'])
@require_login
def create_zip(form_id):
"""
创建表单文件的ZIP压缩包 - 流式处理版本(极低内存占用)
"""
temp_zip_path = None
try:
if form_id in zip_creation_locks:
return jsonify(error='该表单正在打包中,请稍后再试'), 429
zip_creation_locks[form_id] = True
try:
data = request.get_json() or {}
filename_template = data.get('template', '')
as_of = (data.get('asOf') or '').strip()
form = get_form(form_id)
if not form:
return jsonify(error='表单不存在'), 404
# asOf 时间点:按各学生在该时间点的最新版本打包(历史导出)
versions_map = None
if as_of:
versions_map = get_versions_as_of(form_id, as_of)
total_version_files = sum(len(e['files']) for e in versions_map.values())
if total_version_files == 0:
return jsonify(error='该时间点没有文件可以打包'), 404
else:
file_count = get_form_file_count(form_id)
if file_count == 0:
return jsonify(error='没有文件可以打包'), 404
form_title = form.get('title', form_id)
preset_id = form.get('presetId')
file_fields = [f for f in form.get('fields', []) if f['type'] == 'file']
has_multiple_file_fields = len(file_fields) >= 2
students_map = {}
if preset_id:
preset = get_preset(preset_id)
if preset:
for s in preset.get('students', []):
student_id = s.get('id', '')
students_map[student_id] = {
'id': student_id,
'name': s.get('name', ''),
'tail': student_id[-form.get('verifyDigits', 2):] if len(student_id) >= form.get('verifyDigits', 2) else student_id
}
submissions = get_form_submissions(form_id)
submission_data_map = {}
for sub in submissions:
submission_data_map[sub['student_id']] = sub.get('data', {})
temp_dir = tempfile.gettempdir()
time_str = datetime.now().strftime('%Y%m%d_%H%M%S')
zip_filename = f"{form_title}_{time_str}.zip"
safe_filename = re.sub(r'[<>"/\|?*]', '', zip_filename)
temp_zip_path = os.path.join(temp_dir, f"form_zip_{form_id}_{time_str}_{uuid.uuid4().hex[:8]}.zip")
used_filenames = set()
processed_count = 0
def _iter_zip_source():
"""统一产出打包条目:当前文件走流式;asOf 走版本清单(逐个取 blob)。
每项含 filename / file_data / field_name / student_id / student_data。"""
if versions_map is not None:
for student_id, entry in versions_map.items():
for f in entry['files']:
rec = None
if f.get('fileId'):
rec = get_file(f['fileId'])
elif f.get('vfileId'):
rec = get_version_archived_file(f['vfileId'])
if not rec:
continue
yield {
'filename': rec['original_name'] or rec['filename'],
'file_data': rec['file_data'],
'field_name': rec['field_name'] or '',
'student_id': student_id,
'student_data': entry['version'].get('data') or {}
}
else:
for fi in stream_form_files(form_id, batch_size=1):
yield {
'filename': fi['filename'],
'file_data': fi['file_data'],
'field_name': fi.get('field_name', '') or '',
'student_id': None,
'student_data': None
}
with zipfile.ZipFile(temp_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for file_info in _iter_zip_source():
original_filename = file_info['filename']
file_data = file_info['file_data']
field_name = file_info.get('field_name', '') or ''
if file_info.get('student_id'):
matched_student = students_map.get(file_info['student_id'])
matched_submission_data = file_info.get('student_data') or {}
else:
matched_student = None
matched_submission_data = {}
for student_id, student_info in students_map.items():
if student_id in original_filename or student_info['name'] in original_filename:
matched_student = student_info
matched_submission_data = submission_data_map.get(student_id, {})
break
if filename_template and matched_student:
new_filename = filename_template
new_filename = new_filename.replace('{学号}', matched_student['id'])
new_filename = new_filename.replace('{姓名}', matched_student['name'])
new_filename = new_filename.replace('{尾号}', matched_student['tail'])
for field_name_key, field_value in matched_submission_data.items():
placeholder = '{' + field_name_key + '}'
if placeholder in new_filename:
new_filename = new_filename.replace(placeholder, str(field_value or ''))
ext = original_filename.rsplit('.', 1)[-1] if '.' in original_filename else ''
new_filename = re.sub(r'[<>"/\|?*]', '', new_filename)
new_filename = re.sub(r'\{[^}]*\}', '', new_filename)
if ext:
new_filename = f"{new_filename}.{ext}"
if not new_filename or new_filename == f'.{ext}':
new_filename = original_filename
else:
new_filename = original_filename
if has_multiple_file_fields and field_name:
if '.' in new_filename:
name_part, ext_part = new_filename.rsplit('.', 1)
new_filename = f"{name_part}_{field_name}.{ext_part}"
else:
new_filename = f"{new_filename}_{field_name}"
final_filename = new_filename
if final_filename in used_filenames:
if '.' in final_filename:
name_part, ext_part = final_filename.rsplit('.', 1)
suffix = field_name if field_name else 'file'
final_filename = f"{name_part}_{suffix}.{ext_part}"
else:
suffix = field_name if field_name else 'file'
final_filename = f"{final_filename}_{suffix}"
counter = 1
original_final = final_filename
while final_filename in used_filenames:
if '.' in original_final:
name_part, ext_part = original_final.rsplit('.', 1)
final_filename = f"{name_part}_{counter}.{ext_part}"
else:
final_filename = f"{original_final}_{counter}"
counter += 1
used_filenames.add(final_filename)
zipf.writestr(final_filename, file_data)
file_data = None
processed_count += 1
if processed_count % 10 == 0:
gc.collect()
total_size = os.path.getsize(temp_zip_path)
temp_file_id = f"temp_{uuid.uuid4().hex}"
temp_zip_files[temp_file_id] = {
'path': temp_zip_path,
'filename': safe_filename,
'created_at': datetime.now().isoformat()
}
return jsonify(
success=True,
download_url=f"/api/download_temp_zip/{temp_file_id}",
filename=safe_filename,
file_count=processed_count,
total_size=total_size
)
finally:
zip_creation_locks.pop(form_id, None)
except Exception as e:
if temp_zip_path and os.path.exists(temp_zip_path):
try:
os.remove(temp_zip_path)
except:
pass
zip_creation_locks.pop(form_id, None)
print(f"创建ZIP失败: {str(e)}")
import traceback
traceback.print_exc()
return jsonify(error=f'服务器错误: {str(e)}'), 500
@bp.route('/api/download_temp_zip/<temp_file_id>')
def download_temp_zip(temp_file_id):
"""
下载临时ZIP文件 - 使用call_on_close在响应关闭后删除文件
"""
try:
if temp_file_id not in temp_zip_files:
return jsonify(error='临时文件不存在或已过期'), 404
temp_info = temp_zip_files[temp_file_id]
temp_path = temp_info['path']
filename = temp_info['filename']
if not os.path.exists(temp_path):
temp_zip_files.pop(temp_file_id, None)
return jsonify(error='临时文件已被清理'), 404
try:
ascii_filename = filename.encode('ascii', 'ignore').decode()
if not ascii_filename:
ascii_filename = 'download.zip'
except:
ascii_filename = 'download.zip'
encoded_filename = quote(filename, safe='')
response = send_file(
temp_path,
mimetype='application/zip',
as_attachment=True,
download_name=ascii_filename
)
disposition = f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
response.headers['Content-Disposition'] = disposition
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
def cleanup_temp_file():
try:
if os.path.exists(temp_path):
os.remove(temp_path)
print(f"✅ 临时ZIP文件已自动删除: {temp_path}")
except Exception as e:
print(f"❌ 删除临时ZIP文件失败: {e}")
finally:
temp_zip_files.pop(temp_file_id, None)
response.call_on_close(cleanup_temp_file)
return response
except Exception as e:
print(f"下载临时ZIP失败: {str(e)}")
import traceback
traceback.print_exc()
return jsonify(error=f'服务器错误: {str(e)}'), 500
+441
View File
@@ -0,0 +1,441 @@
"""
表单管理 API:保存/获取/编辑/列表/删除
"""
from datetime import datetime
from flask import Blueprint, request, jsonify
from database import (
get_form, save_form, delete_form, get_all_forms,
get_preset, update_preset_usage, get_form_stats,
get_session, get_user, update_user_managed_forms,
insert_business_metric,
)
from utils.helpers import generate_form_id, get_client_ip
from utils.expiry import get_expiry_info
from routes.auth import require_login
from utils.webhooks import normalize_webhook
bp = Blueprint('forms', __name__)
@bp.route('/api/save_form', methods=['POST'])
@require_login
def save_form_api():
"""保存表单配置"""
try:
form_data = request.get_json()
if not form_data:
return jsonify(success=False, message='无效的数据'), 400
try:
webhook = normalize_webhook(form_data.get('webhook'))
except ValueError as e:
return jsonify(success=False, message=str(e)), 400
form_id = generate_form_id()
# 获取预设ID(如果有;空串归一化为 None,匿名模式即无预设)
preset_id = form_data.get('presetId') or None
preset_config = None
if preset_id:
preset = get_preset(preset_id)
if preset:
preset_config = {
'id': preset_id,
'name': preset.get('name'),
'verifyDigits': preset.get('config', {}).get('verifyDigits', 2),
'idCardField': preset.get('config', {}).get('idCardField') is not None
}
update_preset_usage(preset_id)
# 匿名模式:不选预设 → 不注入名单字段(tail/name),由创建者完全自定义字段
anonymous_mode = not preset_id
verify_digits = form_data.get('verifyDigits', 2)
base_fields = [] if anonymous_mode else [
{'name': 'tail', 'type': 'number', 'placeholder': f'学号后{verify_digits}位',
'required': True, 'options': ''},
{'name': 'name', 'type': 'text', 'placeholder': '姓名',
'required': True, 'options': ''}
]
custom_fields = form_data.get('fields', [])
all_fields = base_fields + custom_fields
created_at = datetime.now().isoformat()
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
creator_username = session_data['username'] if session_data else '未知'
# 匿名模式无名单可比对,覆盖验证不生效
overwrite_verify = {} if anonymous_mode else form_data.get('overwriteVerify', {})
verify_config = None
if overwrite_verify.get('enabled') and overwrite_verify.get('field'):
verify_config = {
'enabled': True,
'field': overwrite_verify.get('field'),
'customFieldName': overwrite_verify.get('customFieldName', ''),
'digits': int(overwrite_verify.get('digits', 4)),
'label': overwrite_verify.get('label', '身份证')
}
form_config = {
'id': form_id,
'title': form_data.get('title', '未命名表单'),
'collectType': form_data.get('collectType', 'info'),
'maxSize': form_data.get('maxSize', 10 * 1024 * 1024),
'allowedExts': form_data.get('allowedExts', []),
'fields': all_fields,
'createdAt': created_at,
'expiresAt': form_data.get('expiresAt') or None,
'creatorIP': get_client_ip(),
'fileFieldCount': len([f for f in custom_fields if f.get('type') == 'file']),
'creator': creator_username,
'presetId': preset_id,
'presetName': preset_config.get('name') if preset_config else None,
'showProgress': form_data.get('showProgress', True),
'verifyDigits': verify_digits,
'overwriteVerify': verify_config,
'announcement': form_data.get('announcement'),
# 提交前校验(浏览器端可插拔脚本):{enabled, failToast, script}
'validation': form_data.get('validation'),
'webhook': webhook,
# 收集状态:默认收集中
'collecting': form_data.get('collecting', True),
# 重复提交策略:overwrite=同身份覆盖(默认);once=禁止重复提交
'duplicatePolicy': 'once' if form_data.get('duplicatePolicy') == 'once' else 'overwrite'
}
save_form(form_config)
try:
insert_business_metric('forms_created', 1)
except Exception:
pass
if creator_username:
user = get_user(creator_username)
if user and user.get('role') != 'admin':
managed = user.get('managed_forms', [])
if form_id not in managed:
managed.append(form_id)
update_user_managed_forms(creator_username, managed)
return jsonify(success=True, formId=form_id)
except Exception as e:
print(f"保存表单失败: {str(e)}")
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
@bp.route('/api/get_form/<form_id>')
def get_form_api(form_id):
"""获取表单配置"""
try:
form = get_form(form_id)
if not form:
return jsonify(error='表单不存在'), 404
from database import get_form_announcement_files
form['announcementFiles'] = get_form_announcement_files(form_id)
return jsonify(form)
except Exception as e:
print(f"获取表单失败: {str(e)}")
return jsonify(error=f'服务器错误: {str(e)}'), 500
@bp.route('/api/edit_form/<form_id>', methods=['POST'])
@require_login
def edit_form_api(form_id):
"""编辑表单配置"""
try:
form = get_form(form_id)
if not form:
return jsonify(success=False, message='表单不存在'), 404
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return jsonify(success=False, message='未登录'), 401
username = session_data['username']
user = get_user(username)
managed_forms = user.get('managed_forms', []) if user else []
if user['role'] != 'admin' and form_id not in managed_forms:
return jsonify(success=False, message='无权编辑此表单'), 403
form_data = request.get_json()
if not form_data:
return jsonify(success=False, message='无效的数据'), 400
created_at = form.get('createdAt')
try:
webhook = normalize_webhook(form_data.get('webhook', form.get('webhook')))
except ValueError as e:
return jsonify(success=False, message=str(e)), 400
creator = form.get('creator')
creator_ip = form.get('creatorIP')
preset_id = form.get('presetId') or None
preset_name = form.get('presetName') or None
# 沿用表单原有模式(编辑不支持切换名单/匿名,避免字段结构错乱)
anonymous_mode = not preset_id
verify_digits = form_data.get('verifyDigits', 2)
base_fields = [] if anonymous_mode else [
{'name': 'tail', 'type': 'number', 'placeholder': f'学号后{verify_digits}位',
'required': True, 'options': ''},
{'name': 'name', 'type': 'text', 'placeholder': '姓名',
'required': True, 'options': ''}
]
custom_fields = form_data.get('fields', [])
all_fields = base_fields + custom_fields
overwrite_verify = {} if anonymous_mode else form_data.get('overwriteVerify', {})
verify_config = None
if overwrite_verify.get('enabled') and overwrite_verify.get('field'):
verify_config = {
'enabled': True,
'field': overwrite_verify.get('field'),
'customFieldName': overwrite_verify.get('customFieldName', ''),
'digits': int(overwrite_verify.get('digits', 4)),
'label': overwrite_verify.get('label', '身份证')
}
updated_config = {
'id': form_id,
'title': form_data.get('title', form.get('title', '未命名表单')),
'collectType': form_data.get('collectType', form.get('collectType', 'info')),
'maxSize': form_data.get('maxSize', form.get('maxSize', 10 * 1024 * 1024)),
'allowedExts': form_data.get('allowedExts', form.get('allowedExts', [])),
'fields': all_fields,
'createdAt': created_at,
'expiresAt': form_data.get('expiresAt') or None,
'creatorIP': creator_ip,
'fileFieldCount': len([f for f in custom_fields if f.get('type') == 'file']),
'creator': creator,
'presetId': preset_id,
'presetName': preset_name,
'showProgress': form_data.get('showProgress', form.get('showProgress', True)),
'verifyDigits': verify_digits,
'overwriteVerify': verify_config,
'announcement': form_data.get('announcement', form.get('announcement')),
# 提交前校验配置
'validation': form_data.get('validation', form.get('validation')),
'webhook': webhook,
# 收集状态:编辑时保留原状态(不在载荷里则沿用当前值)
'collecting': form_data.get('collecting', form.get('collecting', True)),
# 重复提交策略:不在载荷里则沿用当前值
'duplicatePolicy': ('once' if form_data.get('duplicatePolicy') == 'once' else 'overwrite')
if 'duplicatePolicy' in form_data
else form.get('duplicatePolicy', 'overwrite')
}
save_form(updated_config)
return jsonify(success=True, formId=form_id, message='表单已更新')
except Exception as e:
print(f"编辑表单失败: {str(e)}")
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
@bp.route('/api/admin/forms')
@require_login
def admin_forms_list():
"""获取所有表单列表(管理后台用)"""
try:
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return jsonify(error='未登录'), 401
username = session_data['username']
user = get_user(username)
user_role = session_data['role']
managed_forms = user.get('managed_forms', []) if user else []
forms = []
for form in get_all_forms():
form_id = form['id']
if user_role == 'user' and form_id not in managed_forms:
continue
stats = get_form_stats(form_id)
expiry_info = get_expiry_info(form.get('createdAt', ''), form.get('expiresAt'))
total_students = 0
preset_id = form.get('presetId')
if preset_id:
preset = get_preset(preset_id)
if preset:
total_students = len(preset.get('students', []))
forms.append({
'id': form_id,
'title': form.get('title', '未命名表单'),
'createdAt': form.get('createdAt', ''),
'expiryInfo': expiry_info,
'submittedCount': stats['submitted_count'],
'totalStudents': total_students,
'fileCount': stats['file_count'],
'collectType': form.get('collectType', 'info'),
'maxSize': form.get('maxSize', 10*1024*1024),
'can_manage': user_role == 'admin' or form_id in managed_forms,
'presetId': preset_id,
'presetName': form.get('presetName'),
'collecting': form.get('collecting', True)
})
forms.sort(key=lambda x: x['createdAt'], reverse=True)
return jsonify(forms)
except Exception as e:
return jsonify(error=str(e)), 500
@bp.route('/api/admin/delete_form/<form_id>', methods=['POST'])
@require_login
def delete_form_api(form_id):
"""删除表单及关联文件"""
try:
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return jsonify(error='未登录'), 401
username = session_data['username']
user = get_user(username)
user_role = session_data['role']
managed_forms = user.get('managed_forms', []) if user else []
if user_role != 'admin' and form_id not in managed_forms:
return jsonify(success=False, message='无权删除此表单'), 403
delete_form(form_id)
return jsonify(success=True, message='表单已删除')
except Exception as e:
return jsonify(success=False, message=f'删除失败: {str(e)}'), 500
@bp.route('/api/admin/toggle_collect/<form_id>', methods=['POST'])
@require_login
def toggle_collect_api(form_id):
"""开关表单收集状态:collecting=true 收集中 / false 停止收集"""
try:
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return jsonify(error='未登录'), 401
username = session_data['username']
user = get_user(username)
user_role = session_data['role']
managed_forms = user.get('managed_forms', []) if user else []
if user_role != 'admin' and form_id not in managed_forms:
return jsonify(success=False, message='无权操作此表单'), 403
form = get_form(form_id)
if not form:
return jsonify(success=False, message='表单不存在'), 404
data = request.get_json() or {}
collecting = bool(data.get('collecting', not form.get('collecting', True)))
from database import set_form_collecting
ok = set_form_collecting(form_id, collecting)
if not ok:
return jsonify(success=False, message='更新失败'), 404
return jsonify(success=True, collecting=collecting,
message='已恢复收集' if collecting else '已停止收集')
except Exception as e:
return jsonify(success=False, message=f'操作失败: {str(e)}'), 500
# ========== 公告附件管理 API ==========
def _check_form_permission(form_id):
"""校验当前用户是否有权管理该表单,返回 (user_role, error_json)"""
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return None, (jsonify(error='未登录'), 401)
username = session_data['username']
user = get_user(username)
user_role = session_data['role']
managed_forms = user.get('managed_forms', []) if user else []
if user_role != 'admin' and form_id not in managed_forms:
return None, (jsonify(success=False, message='无权管理此表单'), 403)
return user_role, None
@bp.route('/api/form/<form_id>/announcement_upload', methods=['POST'])
@require_login
def upload_announcement_file(form_id):
"""上传表单公告附件(最多3个)"""
try:
form = get_form(form_id)
if not form:
return jsonify(success=False, message='表单不存在'), 404
role, err = _check_form_permission(form_id)
if err:
return err
file = request.files.get('file')
if not file or not file.filename:
return jsonify(success=False, message='未选择文件'), 400
from database import save_announcement_file, get_form_announcement_files
file.seek(0, 2)
size = file.tell()
file.seek(0)
if size > form['maxSize']:
return jsonify(success=False, message='文件大小超过限制'), 400
try:
file_data = file.read()
mime_type = file.content_type or 'application/octet-stream'
save_announcement_file(
form_id,
file_data,
file.filename,
original_name=file.filename,
mime_type=mime_type
)
except ValueError as ve:
return jsonify(success=False, message=str(ve)), 400
files = get_form_announcement_files(form_id)
return jsonify(success=True, files=files)
except Exception as e:
print(f"上传公告附件失败: {str(e)}")
import traceback
traceback.print_exc()
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
@bp.route('/api/form/<form_id>/announcement_delete/<int:file_id>', methods=['POST'])
@require_login
def delete_announcement_file_api(form_id, file_id):
"""删除表单公告附件"""
try:
form = get_form(form_id)
if not form:
return jsonify(success=False, message='表单不存在'), 404
role, err = _check_form_permission(form_id)
if err:
return err
from database import get_announcement_file, delete_announcement_file, get_form_announcement_files
file_record = get_announcement_file(file_id)
if not file_record or file_record['form_id'] != form_id:
return jsonify(success=False, message='附件不存在'), 404
delete_announcement_file(file_id)
files = get_form_announcement_files(form_id)
return jsonify(success=True, files=files)
except Exception as e:
print(f"删除公告附件失败: {str(e)}")
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
+199
View File
@@ -0,0 +1,199 @@
"""
页面路由:静态页面 + 图标
"""
import os
import io
from flask import Blueprint, request, redirect, send_from_directory, send_file
from database import get_form, get_session, get_user
from config import TEMPLATES_DIR, IMG_DIR, PIL_AVAILABLE
from utils.expiry import get_expiry_info
from routes.auth import require_login
bp = Blueprint('pages', __name__)
@bp.route('/')
def index():
"""根路由重定向到管理后台"""
return redirect('/admin')
@bp.route('/admin')
@require_login
def admin_page():
return send_from_directory(TEMPLATES_DIR, 'admin.html')
@bp.route('/create')
@require_login
def create_form():
return send_from_directory(TEMPLATES_DIR, 'create.html')
@bp.route('/status')
@require_login
def status_page():
return send_from_directory(TEMPLATES_DIR, 'status.html')
@bp.route('/user_manage')
@require_login
def user_manage_page():
return send_from_directory(TEMPLATES_DIR, 'user_manage.html')
@bp.route('/preset_manage')
@require_login
def preset_manage_page():
return send_from_directory(TEMPLATES_DIR, 'preset_manage.html')
@bp.route('/edit/<form_id>')
@require_login
def edit_form_page(form_id):
"""编辑表单页面"""
form = get_form(form_id)
if not form:
return redirect('/error?code=404&message=表单不存在')
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return redirect('/login')
username = session_data['username']
user = get_user(username)
managed_forms = user.get('managed_forms', []) if user else []
if user['role'] != 'admin' and form_id not in managed_forms:
return redirect('/error?code=403&message=无权编辑此表单')
return send_from_directory(TEMPLATES_DIR, 'edit.html')
@bp.route('/motion-demo')
def motion_demo_page():
"""交互式文字动画库示例页"""
return send_from_directory(TEMPLATES_DIR, 'motion-demo.html')
@bp.route('/<form_id>')
def dynamic_form(form_id):
"""动态表单页面"""
form = get_form(form_id)
if not form:
return redirect('/error?code=404&message=表单不存在或已过期')
# 检查是否过期
expiry_info = get_expiry_info(form.get('createdAt', ''), form.get('expiresAt'))
if expiry_info and expiry_info.get('is_expired'):
return redirect('/error?code=410&message=表单已过期')
return send_from_directory(TEMPLATES_DIR, 'index.html')
@bp.route('/error')
def error_page():
return send_from_directory(TEMPLATES_DIR, 'error.html')
@bp.route('/favicon.ico')
def favicon():
"""提供网站图标"""
ico_path = os.path.join(IMG_DIR, 'favicon.ico')
if os.path.exists(ico_path):
return send_file(ico_path, mimetype='image/x-icon')
png_path = os.path.join(IMG_DIR, 'favicon-32x32.png')
if os.path.exists(png_path):
return send_file(png_path, mimetype='image/png')
source_path = os.path.join(IMG_DIR, 'favicon.png')
if os.path.exists(source_path):
return send_file(source_path, mimetype='image/png')
return '', 404
@bp.route('/favicon-<int:w>x<int:h>.png')
def favicon_size(w, h):
size = w
valid_sizes = [16, 32]
if size not in valid_sizes:
return '', 404
path = os.path.join(IMG_DIR, f'favicon-{size}x{size}.png')
if os.path.exists(path):
return send_file(path, mimetype='image/png')
source_path = os.path.join(IMG_DIR, 'favicon.png')
if os.path.exists(source_path) and PIL_AVAILABLE:
try:
from PIL import Image
img = Image.open(source_path)
img = img.resize((size, size), Image.Resampling.LANCZOS)
img_io = io.BytesIO()
img.save(img_io, 'PNG', optimize=True)
img_io.seek(0)
return send_file(img_io, mimetype='image/png')
except:
pass
return '', 404
@bp.route('/apple-touch-icon.png')
def apple_touch_icon():
icon_path = os.path.join(IMG_DIR, 'apple-touch-icon.png')
if os.path.exists(icon_path):
return send_file(icon_path, mimetype='image/png')
source_path = os.path.join(IMG_DIR, 'favicon.png')
if os.path.exists(source_path) and PIL_AVAILABLE:
try:
from PIL import Image, ImageDraw
img = Image.open(source_path)
img = img.convert('RGBA')
img = img.resize((180, 180), Image.Resampling.LANCZOS)
mask = Image.new('L', (180, 180), 0)
draw = ImageDraw.Draw(mask)
draw.rounded_rectangle([0, 0, 180, 180], radius=36, fill=255)
output = Image.new('RGBA', (180, 180), (255, 255, 255, 0))
output.paste(img, (0, 0))
output.putalpha(mask)
img_io = io.BytesIO()
output.save(img_io, 'PNG', optimize=True)
img_io.seek(0)
return send_file(img_io, mimetype='image/png')
except:
pass
return '', 404
@bp.route('/android-chrome-<int:w>x<int:h>.png')
def android_chrome(w, h):
size = w
valid_sizes = [192, 512]
if size not in valid_sizes:
return '', 404
path = os.path.join(IMG_DIR, f'android-chrome-{size}x{size}.png')
if os.path.exists(path):
return send_file(path, mimetype='image/png')
source_path = os.path.join(IMG_DIR, 'favicon.png')
if os.path.exists(source_path) and PIL_AVAILABLE:
try:
from PIL import Image
img = Image.open(source_path)
img = img.resize((size, size), Image.Resampling.LANCZOS)
img_io = io.BytesIO()
img.save(img_io, 'PNG', optimize=True)
img_io.seek(0)
return send_file(img_io, mimetype='image/png')
except:
pass
return '', 404
+335
View File
@@ -0,0 +1,335 @@
"""
预设管理 API
"""
import json
from datetime import datetime
from flask import Blueprint, request, jsonify
from database import (
get_all_presets, get_preset, save_preset, delete_preset,
update_preset_usage, get_session, get_user, save_user,
)
from utils.helpers import generate_preset_id, smart_field_detection
from config import PANDAS_AVAILABLE
from routes.auth import require_login, require_admin
bp = Blueprint('presets', __name__)
@bp.route('/api/presets', methods=['GET'])
@require_login
def api_get_presets():
"""获取所有预设列表"""
try:
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return jsonify(error='未登录'), 401
username = session_data['username']
user = get_user(username)
user_role = session_data['role']
presets = []
for preset_id, preset_info in get_all_presets().items():
created_by = preset_info.get('createdBy', '')
is_global = preset_info.get('isGlobal', False)
if user_role != 'admin':
if created_by != 'admin' and not is_global:
managed_presets = user.get(
'managed_presets', []) if user else []
if preset_id not in managed_presets:
continue
presets.append({
'id': preset_id,
'name': preset_info.get('name', '未命名预设'),
'originalFilename': preset_info.get('originalFilename', ''),
'createdAt': preset_info.get('createdAt', ''),
'createdBy': created_by,
'isGlobal': is_global,
'usageCount': preset_info.get('usageCount', 0),
'lastUsed': preset_info.get('lastUsed', ''),
'totalStudents': preset_info.get('config', {}).get('totalStudents', 0)
})
presets.sort(key=lambda x: x['createdAt'], reverse=True)
return jsonify(presets)
except Exception as e:
return jsonify(error=str(e)), 500
@bp.route('/api/presets', methods=['POST'])
@require_login
def api_create_preset():
"""上传并创建预设"""
if not PANDAS_AVAILABLE:
return jsonify(success=False, message='pandas库未安装,无法处理Excel文件'), 500
import pandas as pd
try:
if 'file' not in request.files:
return jsonify(success=False, message='未上传文件'), 400
file = request.files['file']
if file.filename == '':
return jsonify(success=False, message='文件名不能为空'), 400
field_mapping = {}
if request.form.get('fieldMapping'):
field_mapping = json.loads(request.form.get('fieldMapping'))
filename = file.filename
ext = filename.rsplit('.', 1)[-1].lower()
try:
if ext in ['xlsx', 'xls']:
df = pd.read_excel(file)
elif ext == 'csv':
file.seek(0)
content = file.read()
file.seek(0)
try:
content = content.decode('utf-8')
df = pd.read_csv(file, encoding='utf-8')
except:
file.seek(0)
df = pd.read_csv(file, encoding='gbk')
else:
return jsonify(success=False, message='不支持的文件格式,请上传.xlsx, .xls或.csv文件'), 400
except Exception as e:
return jsonify(success=False, message=f'文件解析失败: {str(e)}'), 400
columns = list(df.columns)
if not field_mapping:
field_mapping = smart_field_detection(columns)
id_field = field_mapping.get('idField')
name_field = field_mapping.get('nameField')
if not id_field or id_field not in columns:
return jsonify(success=False, message=f'未能识别学号列,请手动指定。可用列: {", ".join(columns)}'), 400
if not name_field or name_field not in columns:
return jsonify(success=False, message=f'未能识别姓名列,请手动指定。可用列: {", ".join(columns)}'), 400
preset_id = generate_preset_id()
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
created_by = session_data['username'] if session_data else '未知'
students = []
extra_fields = [col for col in columns if col not in [id_field, name_field,
field_mapping.get('idCardField'),
field_mapping.get('phoneField'),
field_mapping.get('groupField')]]
for _, row in df.iterrows():
student = {
'id': str(row.get(id_field, '')).strip(),
'name': str(row.get(name_field, '')).strip()
}
if field_mapping.get('idCardField') and field_mapping['idCardField'] in columns:
id_card = str(row.get(field_mapping['idCardField'], '')).strip()
if id_card:
student['idCard'] = id_card
if field_mapping.get('phoneField') and field_mapping['phoneField'] in columns:
phone = str(row.get(field_mapping['phoneField'], '')).strip()
if phone:
student['phone'] = phone
if field_mapping.get('groupField') and field_mapping['groupField'] in columns:
group = str(row.get(field_mapping['groupField'], '')).strip()
if group:
student['group'] = group
student['extra'] = {}
for ef in extra_fields:
val = row.get(ef)
if pd.notna(val):
student['extra'][ef] = str(val).strip()
if student['id'] and student['name']:
students.append(student)
preset_config = {
'id': preset_id,
'name': request.form.get('name', f"预设_{datetime.now().strftime('%Y%m%d_%H%M%S')}"),
'originalFilename': filename,
'createdAt': datetime.now().isoformat(),
'createdBy': created_by,
'usageCount': 0,
'lastUsed': None,
'isGlobal': (created_by == 'admin'),
'config': {
'totalStudents': len(students),
'idField': id_field,
'nameField': name_field,
'verifyDigits': int(request.form.get('verifyDigits', 2)),
'idCardField': field_mapping.get('idCardField'),
'phoneField': field_mapping.get('phoneField'),
'groupField': field_mapping.get('groupField'),
'extraFields': extra_fields
},
'students': students
}
save_preset(preset_config)
if created_by and created_by != 'admin':
user = get_user(created_by)
if user:
managed_presets = user.get('managed_presets', [])
if preset_id not in managed_presets:
managed_presets.append(preset_id)
user['managed_presets'] = managed_presets
save_user(created_by, user)
return jsonify(success=True, presetId=preset_id, message='预设创建成功')
except Exception as e:
print(f"创建预设失败: {str(e)}")
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
@bp.route('/api/presets/<preset_id>', methods=['GET'])
@require_login
def api_get_preset(preset_id):
"""获取预设详情"""
try:
preset = get_preset(preset_id)
if not preset:
return jsonify(error='预设不存在'), 404
return jsonify({
'id': preset['id'],
'name': preset['name'],
'originalFilename': preset['originalFilename'],
'createdAt': preset['createdAt'],
'createdBy': preset['createdBy'],
'usageCount': preset['usageCount'],
'lastUsed': preset['lastUsed'],
'config': preset['config']
})
except Exception as e:
return jsonify(error=str(e)), 500
@bp.route('/api/presets/<preset_id>/preview', methods=['POST'])
@require_login
def api_preview_preset(preset_id):
"""预览预设数据(前10条)"""
try:
preset = get_preset(preset_id)
if not preset:
return jsonify(error='预设不存在'), 404
students = preset.get('students', [])[:10]
return jsonify({
'name': preset['name'],
'config': preset['config'],
'previewStudents': students,
'totalStudents': len(preset.get('students', []))
})
except Exception as e:
return jsonify(error=str(e)), 500
@bp.route('/api/presets/<preset_id>', methods=['PUT'])
@require_login
def api_update_preset(preset_id):
"""重命名预设或更新字段映射"""
try:
data = request.get_json()
preset = get_preset(preset_id)
if not preset:
return jsonify(error='预设不存在'), 404
if 'name' in data:
preset['name'] = data['name']
if 'fieldMapping' in data:
field_mapping = data['fieldMapping']
preset['config']['idField'] = field_mapping.get('idField', preset['config']['idField'])
preset['config']['nameField'] = field_mapping.get('nameField', preset['config']['nameField'])
preset['config']['idCardField'] = field_mapping.get('idCardField')
preset['config']['phoneField'] = field_mapping.get('phoneField')
preset['config']['groupField'] = field_mapping.get('groupField')
save_preset(preset)
return jsonify(success=True, message='预设已更新')
except Exception as e:
return jsonify(error=str(e)), 500
@bp.route('/api/presets/<preset_id>', methods=['DELETE'])
@require_login
def api_delete_preset(preset_id):
"""删除预设"""
try:
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return jsonify(error='未登录'), 401
username = session_data['username']
user = get_user(username)
user_role = session_data['role']
preset = get_preset(preset_id)
if not preset:
return jsonify(success=False, message='预设不存在'), 404
if user_role != 'admin' and preset.get('createdBy') != username:
return jsonify(success=False, message='无权删除此预设'), 403
delete_preset(preset_id)
return jsonify(success=True, message='预设已删除')
except Exception as e:
return jsonify(error=str(e)), 500
@bp.route('/api/presets/<preset_id>/students')
@require_login
def api_get_preset_students(preset_id):
"""获取预设的学生列表"""
try:
preset = get_preset(preset_id)
if not preset:
return jsonify(error='预设不存在'), 404
students = []
for s in preset.get('students', []):
students.append({
'id': s.get('id'),
'name': s.get('name'),
'group': s.get('group', '')
})
return jsonify({
'students': students,
'config': preset.get('config', {})
})
except Exception as e:
return jsonify(error=str(e)), 500
@bp.route('/api/presets/<preset_id>/global', methods=['POST'])
@require_admin
def api_set_preset_global(preset_id):
"""管理员设置预设为全局可见"""
try:
preset = get_preset(preset_id)
if not preset:
return jsonify(success=False, message='预设不存在'), 404
preset['isGlobal'] = True
preset['createdBy'] = 'admin'
save_preset(preset)
return jsonify(success=True, message='预设已设置为全局可见')
except Exception as e:
return jsonify(success=False, message=f'设置失败: {str(e)}'), 500
+662
View File
@@ -0,0 +1,662 @@
"""
表单提交 API + 状态/进度/时间数据 API
"""
import os
from datetime import datetime, timedelta
from flask import Blueprint, request, jsonify
from database import (
get_form, get_preset, get_form_submissions, get_submitted_students,
save_submission, delete_student_files, get_form_files,
record_submission_history, get_submission_history,
insert_business_metric,
get_last_submission_by_token, archive_replaced_files,
save_submission_version, update_version_file_ids, get_prev_version_id,
get_student_versions, get_submission_version, delete_submission_version,
get_version_archived_file, find_submission_id, build_status_students,
)
from utils.expiry import get_expiry_info
from routes.auth import require_login
from utils.helpers import get_client_ip
from utils.webhooks import send_form_webhook
bp = Blueprint('submissions', __name__)
# "加载上次填写"功能:客户端提交时上送的设备令牌 cookie 名
DEVICE_TOKEN_COOKIE = 'fs_device_token'
def _check_form_manage_permission(form_id):
"""校验当前登录用户是否有权管理该表单(admin 或被授权管理者)。
返回错误消息字符串,通过则返回 None。"""
from database import get_session, get_user
session_id = request.cookies.get('session_id')
session_data = get_session(session_id)
if not session_data:
return '未登录'
user = get_user(session_data['username'])
managed_forms = user.get('managed_forms', []) if user else []
if session_data['role'] != 'admin' and form_id not in managed_forms:
return '无权管理此表单'
return None
@bp.route('/get_students', methods=['GET'])
def get_students():
"""获取学生信息(不含身份证)"""
try:
form_id = request.args.get('formId', '')
if form_id:
form = get_form(form_id)
if form:
verify_digits = form.get('verifyDigits', 2)
preset_id = form.get('presetId')
if preset_id:
preset = get_preset(preset_id)
if preset:
students = {}
for s in preset.get('students', []):
student_id = s.get('id', '')
if len(student_id) >= verify_digits:
tail = student_id[-verify_digits:]
students[tail] = {
"id": student_id,
"name": s.get('name', '')
}
return jsonify(students)
return jsonify({})
except Exception as e:
print(f"get_students 接口异常: {str(e)}")
return jsonify(error=f'服务器错误: {str(e)}'), 500
@bp.route('/get_verify_value', methods=['POST'])
def get_verify_value():
"""在服务端比对覆盖验证信息,不向客户端返回答案。"""
payload = request.get_json(silent=True) or {}
tail = str(payload.get('studentId', '')).strip()
form_id = str(payload.get('formId', '')).strip()
candidate = str(payload.get('value', '')).strip().upper()
if form_id and tail and candidate:
form = get_form(form_id)
if form:
preset_id = form.get('presetId')
verify_config = form.get('overwriteVerify') or {}
if preset_id and verify_config.get('enabled') and tail in get_submitted_students(form_id):
verify_field = verify_config.get('field', 'idCard')
custom_field_name = verify_config.get('customFieldName', '')
digits = int(verify_config.get('digits', 4))
preset = get_preset(preset_id)
if preset:
preset_verify_digits = preset.get(
'config', {}).get('verifyDigits', 2)
for s in preset.get('students', []):
student_id = s.get('id', '')
if len(student_id) >= preset_verify_digits and student_id[-preset_verify_digits:] == tail:
value = ''
if verify_field == 'idCard':
value = s.get('idCard', '')
elif verify_field == 'phone':
value = s.get('phone', '')
elif verify_field == 'custom' and custom_field_name:
value = s.get('extra', {}).get(
custom_field_name, '') or s.get(custom_field_name, '')
if value:
expected = str(value).upper()[-digits:]
return jsonify(success=candidate == expected)
return jsonify(success=False)
@bp.route('/check_submission', methods=['GET'])
def check_submission():
"""检查提交状态"""
tail = request.args.get('studentId', '').strip()
form_id = request.args.get('formId', 'default')
submitted_students = get_submitted_students(form_id)
return jsonify(exists=tail in submitted_students)
@bp.route('/api/submit', methods=['POST'])
def submit_form():
"""通用表单提交接口 - BLOB存储版本"""
try:
form_id = request.form.get('formId', 'default')
tail = request.form.get('studentId', '').strip()
form = get_form(form_id)
if not form:
return jsonify(success=False, message='表单配置不存在或已过期'), 400
# 检查表单是否已过期
expiry_info = get_expiry_info(form.get('createdAt', ''), form.get('expiresAt'))
if expiry_info and expiry_info.get('is_expired'):
return jsonify(success=False, message='表单已过期,无法提交'), 410
# 检查是否已停止收集
if form.get('collecting', True) is False:
return jsonify(success=False, message='此页面已停止收集信息,如有问题请联系管理员'), 423
# 身份判定:名单模式按预设匹配学号;匿名模式(表单未选预设)按设备令牌生成伪ID
student_name = None
full_id = None
preset_id = form.get('presetId')
form_verify_digits = form.get('verifyDigits', 2)
anonymous_mode = not preset_id
device_token = (request.form.get('device_token') or '').strip()[:128]
if anonymous_mode:
if device_token:
# 伪ID = anon_ + 设备令牌:save_submission 按 student_id upsert,
# 同设备自然覆盖;文件/版本/历史按 student_id 分组逻辑全部穿透复用
full_id = 'anon_' + device_token
else:
# 令牌缺失(cookie 被禁)退化为按客户端 IP 粗粒度识别(NAT 下可能合并多人)
import hashlib
full_id = 'anon_ip_' + hashlib.md5(
(get_client_ip() or '').encode('utf-8')).hexdigest()[:16]
student_name = '匿名用户'
tail = ''
else:
if preset_id:
preset = get_preset(preset_id)
if preset:
verify_digits = form.get('verifyDigits', 2)
for s in preset.get('students', []):
student_id = s.get('id', '')
if len(student_id) >= verify_digits and student_id[-verify_digits:] == tail:
student_name = s.get('name')
full_id = student_id
break
if not student_name:
if len(tail) != form_verify_digits:
return jsonify(success=False, message=f'学号后{form_verify_digits}位长度不正确,请输入{form_verify_digits}位数字'), 400
return jsonify(success=False, message='无效学号'), 400
# 检查是否已提交
if anonymous_mode:
is_overwrite = find_submission_id(form_id, full_id) is not None
else:
submitted_students = get_submitted_students(form_id)
is_overwrite = tail in submitted_students
# 禁止重复提交策略(名单/匿名模式均生效)
if is_overwrite and form.get('duplicatePolicy') == 'once':
if anonymous_mode:
message = '此表单不允许重复提交,该设备已提交过'
else:
message = f'学号后{form_verify_digits}位({tail})已提交过,此表单不允许重复提交'
return jsonify(success=False, message=message), 409
# 覆盖验证(匿名模式无名单可比对,不适用)
if is_overwrite and preset_id:
verify_config = form.get('overwriteVerify')
if verify_config and verify_config.get('enabled'):
verify_field = verify_config.get('field', 'idCard')
verify_digits_count = verify_config.get('digits', 4)
verify_label = verify_config.get('label', '验证信息')
user_verify_value = request.form.get('verifyTail', '').strip(
) or request.form.get('idCardTail', '').strip()
user_verify_value = user_verify_value.upper()
if not user_verify_value:
return jsonify(success=False, message=f'覆盖提交需要验证{verify_label}后{verify_digits_count}位'), 400
real_verify_value = ''
field_mapping = {
'idCard': 'idCard',
'phone': 'phone',
'custom': verify_config.get('customFieldName', '')
}
preset_field_name = field_mapping.get(
verify_field, verify_field)
if preset_id:
preset = get_preset(preset_id)
if preset:
preset_verify_digits = preset.get(
'config', {}).get('verifyDigits', 2)
for s in preset.get('students', []):
student_id = s.get('id', '')
if len(student_id) >= preset_verify_digits and student_id[-preset_verify_digits:] == tail:
if verify_field == 'idCard':
real_verify_value = s.get('idCard', '')
elif verify_field == 'phone':
real_verify_value = s.get('phone', '')
elif verify_field == 'custom' and preset_field_name:
real_verify_value = s.get('extra', {}).get(
preset_field_name, '') or s.get(preset_field_name, '')
if real_verify_value:
real_verify_value = str(
real_verify_value).upper()[-verify_digits_count:]
break
if user_verify_value != real_verify_value:
return jsonify(success=False, message=f'{verify_label}后{verify_digits_count}位验证失败'), 403
# 提交内容快照(供历史版本归档)
student_data = {}
non_file_fields = [f for f in form['fields'] if f['type'] not in ('file', 'page_break')]
for field in non_file_fields:
field_name = field['name']
field_value = request.form.get(field_name, '')
if field_value:
student_data[field_name] = field_value
# 归档历史版本:每次提交(含覆盖)都留档一份快照
version_id = save_submission_version(
form_id, full_id, student_name, tail,
student_data, is_overwrite=is_overwrite,
ip_address=get_client_ip()
)
# 覆盖提交:keep_files 指定的沿用为当前文件,其余旧文件归档到上一版本
kept_file_ids = []
if is_overwrite:
try:
import json as _json
keep_map = _json.loads(request.form.get('keep_files') or '{}')
if isinstance(keep_map, dict):
kept_file_ids = list(keep_map.values())
except (ValueError, TypeError):
kept_file_ids = []
prev_version_id = get_prev_version_id(form_id, full_id, version_id)
archive_replaced_files(form_id, full_id, kept_file_ids, prev_version_id)
uploaded_files = []
new_file_ids = []
file_fields = [f for f in form['fields'] if f['type'] == 'file']
has_multiple_files = len(file_fields) > 1
# 设备令牌已在身份判定段读取;空值存 NULL(仅作"加载上次填写"召回用)
submission_id = save_submission(
form_id, full_id, student_name, tail,
is_overwrite=is_overwrite,
ip_address=get_client_ip(),
data=student_data,
device_token=device_token or None
)
# 处理文件上传 - 存储为BLOB
from database import save_file
for field in form['fields']:
if field['type'] == 'file':
file = request.files.get(field['name'])
if file and file.filename:
ext = file.filename.rsplit('.', 1)[-1].lower()
field_allowed_exts = field.get('allowedExts', [])
if not field_allowed_exts:
field_allowed_exts = form.get('allowedExts', [])
if field_allowed_exts and ext not in field_allowed_exts:
return jsonify(success=False, message=f'不支持的格式: {ext}'), 400
file.seek(0, os.SEEK_END)
size = file.tell()
file.seek(0)
if size > form['maxSize']:
return jsonify(success=False, message='文件大小超过限制'), 400
if anonymous_mode:
# 匿名文件名:匿名_ + 设备令牌前4位(仅展示名,磁盘按 fileId 存放)
base_name = f"匿名_{full_id[5:9]}"
else:
base_name = f"{student_name}{full_id}"
if has_multiple_files:
filename = f"{base_name}_{field['name']}.{ext}"
else:
filename = f"{base_name}.{ext}"
file_data = file.read()
mime_type = file.content_type or 'application/octet-stream'
file_id = save_file(
form_id=form_id,
file_data=file_data,
filename=filename,
original_name=file.filename,
mime_type=mime_type,
field_name=field['name'],
submission_id=submission_id
)
new_file_ids.append(file_id)
uploaded_files.append(filename)
try:
insert_business_metric('files_uploaded', len(file_data))
except Exception:
pass
# 版本文件清单 = 沿用保留的旧文件 + 本次新上传的文件
update_version_file_ids(version_id, kept_file_ids + new_file_ids)
# 记录提交历史
record_submission_history(
form_id, full_id,
submission_type='overwrite' if is_overwrite else 'first',
ip_address=get_client_ip()
)
try:
insert_business_metric('form_submissions', 1)
except Exception:
pass
# 每个表单显式启用后通知;请求失败不影响已保存的提交。
who = f"{student_name}(设备:{full_id[5:9]})" if anonymous_mode else f"{student_name}(学号:{tail})"
send_form_webhook(form, who, is_overwrite=is_overwrite, uploaded_files=uploaded_files)
return jsonify(success=True, message=f'{"覆盖" if is_overwrite else "提交"}成功', overwrite=is_overwrite)
except Exception as e:
print(f"提交接口异常: {str(e)}")
import traceback
traceback.print_exc()
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
@bp.route('/api/last_submission/check')
def last_submission_check():
"""静默检查:该设备(cookie 令牌)在此表单下是否有提交记录。
只返回存在性与时间,不返回任何内容数据;无效令牌由前端静默清除 cookie。"""
try:
form_id = request.args.get('formId', '')
token = request.cookies.get(DEVICE_TOKEN_COOKIE, '').strip()
if not form_id or not token:
return jsonify(exists=False)
sub = get_last_submission_by_token(form_id, token)
if not sub:
return jsonify(exists=False)
return jsonify(exists=True, submittedAt=sub['submitted_at'])
except Exception as e:
print(f"last_submission/check 异常: {str(e)}")
return jsonify(exists=False)
@bp.route('/api/last_submission/load', methods=['POST'])
def last_submission_load():
"""加载上次提交内容:必须携带 cookie 令牌 + 尾号,两者同时匹配才返回数据。"""
try:
payload = request.get_json(silent=True) or {}
form_id = str(payload.get('formId', '')).strip()
tail = str(payload.get('tail', '')).strip()
token = request.cookies.get(DEVICE_TOKEN_COOKIE, '').strip()
if not form_id or not token:
return jsonify(success=False, message='没有可用的提交记录'), 404
sub = get_last_submission_by_token(form_id, token)
if not sub:
return jsonify(success=False, message='没有找到对应的提交记录'), 404
if sub['tail'] != tail:
return jsonify(success=False, message='尾号与上次提交不一致,无法加载'), 403
files = get_form_files(form_id, sub['student_id'], sub['student_name'])
manifest = [{
'id': f['id'],
'fieldName': f['field_name'],
'originalName': f['original_name'] or f['filename'],
'fileSize': f['file_size'],
} for f in files]
return jsonify(success=True, values=sub['data'], files=manifest,
submittedAt=sub['submitted_at'])
except Exception as e:
print(f"last_submission/load 异常: {str(e)}")
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
@bp.route('/api/admin/submission_history')
@require_login
def admin_submission_history():
"""管理端:查看某学生此表单的全部历史提交版本(含文件清单,不含二进制)。"""
try:
form_id = request.args.get('formId', '').strip()
student_id = request.args.get('studentId', '').strip()
if not form_id or not student_id:
return jsonify(success=False, message='缺少参数'), 400
if not get_form(form_id):
return jsonify(success=False, message='表单不存在'), 404
perm_error = _check_form_manage_permission(form_id)
if perm_error:
return jsonify(success=False, message=perm_error), 403
versions = get_student_versions(form_id, student_id)
return jsonify(success=True, versions=versions)
except Exception as e:
print(f"submission_history 接口异常: {str(e)}")
import traceback
traceback.print_exc()
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
@bp.route('/api/admin/delete_submission_version/<int:version_id>', methods=['POST'])
@require_login
def admin_delete_submission_version(version_id):
"""管理端:删除一条历史提交版本。
非最新条仅删快照及归档附件;最新条会同时清除该学生的当前提交与现存文件。"""
try:
version = get_submission_version(version_id)
if not version:
return jsonify(success=False, message='记录不存在'), 404
perm_error = _check_form_manage_permission(version['form_id'])
if perm_error:
return jsonify(success=False, message=perm_error), 403
result = delete_submission_version(version_id)
return jsonify(success=True,
deletedCurrent=result.get('deletedCurrent', False),
deletedCurrentFiles=result.get('deletedCurrentFiles', 0))
except Exception as e:
print(f"delete_submission_version 接口异常: {str(e)}")
import traceback
traceback.print_exc()
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
@bp.route('/api/admin/download_version_file/<int:vfile_id>')
@require_login
def admin_download_version_file(vfile_id):
"""管理端:下载历史版本中的归档附件。"""
try:
record = get_version_archived_file(vfile_id)
if not record:
return jsonify(error='文件不存在'), 404
perm_error = _check_form_manage_permission(record['form_id'])
if perm_error:
return jsonify(error=perm_error), 403
from urllib.parse import quote
import io as _io
from flask import send_file
display_filename = record['original_name'] or record['filename']
mime_type = record['mime_type'] or 'application/octet-stream'
ascii_filename = display_filename.encode('ascii', 'ignore').decode() or 'download'
encoded_filename = quote(display_filename, safe='')
response = send_file(
_io.BytesIO(record['file_data']),
mimetype=mime_type,
as_attachment=True,
download_name=ascii_filename
)
disposition = f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
response.headers['Content-Disposition'] = disposition
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
return response
except Exception as e:
print(f"download_version_file 接口异常: {str(e)}")
return jsonify(error=f'服务器错误: {str(e)}'), 500
@bp.route('/api/status_data')
def api_status_data():
"""返回学生提交状态数据"""
try:
form_id = request.args.get('formId', 'default')
form = get_form(form_id)
if not form:
return jsonify(error='表单不存在'), 404
expiry_info = get_expiry_info(form.get('createdAt', ''), form.get('expiresAt'))
submissions = get_form_submissions(form_id)
# 名单模式按名单对齐;匿名模式每条提交一个身份
students = build_status_students(form, submissions)
submitted_count = len(submissions) if not form.get('presetId') else len(
{s['tail'] for s in submissions})
return jsonify({
"formTitle": form.get('title', '未命名表单'),
"formId": form_id,
"total": len(students),
"submitted": submitted_count,
"students": students,
"expiryInfo": expiry_info,
"showProgress": form.get('showProgress', True)
})
except Exception as e:
print(f"获取状态数据失败: {str(e)}")
import traceback
traceback.print_exc()
return jsonify(error=f"服务器错误: {str(e)}"), 500
@bp.route('/api/progress/<form_id>')
def api_get_progress(form_id):
"""获取表单进度(公开接口)"""
try:
form = get_form(form_id)
if not form:
return jsonify(error='表单不存在'), 404
if not form.get('showProgress', True):
return jsonify(error='该表单未开启进度显示'), 403
submissions = get_form_submissions(form_id)
preset_id = form.get('presetId')
total = 0
if preset_id:
preset = get_preset(preset_id)
if preset:
total = len(preset.get('students', []))
students = []
if preset_id:
preset = get_preset(preset_id)
if preset:
verify_digits = preset.get('config', {}).get('verifyDigits', 2)
for s in preset.get('students', []):
student_id = s.get('id', '')
if len(student_id) >= verify_digits:
tail = student_id[-verify_digits:]
submitted = any(
sub['tail'] == tail for sub in submissions)
students.append({
'tail': tail,
'name': s.get('name', ''),
'submitted': submitted
})
return jsonify({
'formTitle': form.get('title', '未命名表单'),
'total': total,
'submitted': len(submissions),
'progress': round(len(submissions) / total * 100, 1) if total > 0 else 0,
'students': students
})
except Exception as e:
return jsonify(error=str(e)), 500
@bp.route('/api/submission_times/<form_id>')
@require_login
def api_submission_times(form_id):
"""获取表单提交时间数据,用于趋势图表"""
try:
form = get_form(form_id)
if not form:
return jsonify(error='表单不存在'), 404
created_at_str = form.get('createdAt', '')
if not created_at_str:
return jsonify(error='表单创建时间未知'), 400
if created_at_str.endswith('Z'):
created_at_str = created_at_str[:-1] + '+00:00'
created_at = datetime.fromisoformat(created_at_str)
now = datetime.now()
time_data = get_submission_history(form_id)
raw_times = []
overwrite_times = []
for student_id, data in time_data.items():
first_submit = data.get('first_submit')
if first_submit:
raw_times.append(first_submit)
for record in data.get('submissions', []):
if record.get('type') == 'overwrite':
overwrite_times.append(record['time'])
time_slots = []
current_slot = created_at
while current_slot <= now + timedelta(minutes=20):
time_slots.append(current_slot)
current_slot += timedelta(minutes=20)
if len(time_slots) == 0:
time_slots = [created_at, now]
slot_counts = []
slot_labels = []
for i in range(len(time_slots) - 1):
slot_start = time_slots[i]
slot_end = time_slots[i + 1]
count = 0
for student_id, data in time_data.items():
first_submit = data.get('first_submit')
if first_submit:
submit_time = datetime.fromisoformat(
first_submit.replace('Z', '+00:00').replace('+00:00', ''))
if slot_start <= submit_time < slot_end:
count += 1
slot_counts.append(count)
slot_labels.append(slot_start.strftime('%H:%M'))
cumulative_counts = []
total = 0
for count in slot_counts:
total += count
cumulative_counts.append(total)
return jsonify({
'formId': form_id,
'createdAt': created_at.isoformat(),
'timeLabels': slot_labels,
'slotCounts': slot_counts,
'cumulativeCounts': cumulative_counts,
'totalSubmissions': len(time_data),
'rawTimes': raw_times,
'overwriteTimes': overwrite_times
})
except Exception as e:
return jsonify(error=f"服务器错误: {str(e)}"), 500
+114
View File
@@ -0,0 +1,114 @@
"""
用户管理 API
"""
from datetime import datetime
from flask import Blueprint, request, jsonify
from database import (
get_all_users, get_user, save_user, delete_user,
update_user_managed_forms, delete_user_sessions,
get_all_forms,
)
from utils.helpers import hash_password
from routes.auth import require_admin
bp = Blueprint('users', __name__)
@bp.route('/api/user/list')
@require_admin
def api_user_list():
"""获取用户列表(仅管理员)"""
try:
users = []
for username, user_info in get_all_users().items():
users.append({
'username': username,
'role': user_info.get('role', 'user'),
'created_at': user_info.get('created_at', ''),
'managed_forms': user_info.get('managed_forms', []),
'managed_presets': user_info.get('managed_presets', [])
})
users.sort(key=lambda x: (x['role'] != 'admin', x['username']))
return jsonify(users)
except Exception as e:
return jsonify(error=str(e)), 500
@bp.route('/api/user/add', methods=['POST'])
@require_admin
def api_user_add():
"""添加用户(仅管理员)"""
try:
data = request.get_json()
username = data.get('username', '').strip()
password = data.get('password', '')
role = data.get('role', 'user')
if not username or not password:
return jsonify(success=False, message='用户名和密码不能为空'), 400
if get_user(username):
return jsonify(success=False, message='用户已存在'), 409
save_user(username, {
'username': username,
'password_hash': hash_password(password),
'role': role,
'created_at': datetime.now().isoformat(),
'managed_forms': [],
'managed_presets': []
})
return jsonify(success=True, message='用户添加成功')
except Exception as e:
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
@bp.route('/api/user/delete/<username>', methods=['POST'])
@require_admin
def api_user_delete(username):
"""删除用户(仅管理员)"""
try:
if not get_user(username):
return jsonify(success=False, message='用户不存在'), 404
if username == 'admin':
return jsonify(success=False, message='不能删除默认管理员账号'), 403
delete_user_sessions(username)
delete_user(username)
return jsonify(success=True, message='用户已删除')
except Exception as e:
return jsonify(success=False, message=f'删除失败: {str(e)}'), 500
@bp.route('/api/user/<username>/forms', methods=['GET', 'POST'])
@require_admin
def api_user_forms(username):
"""管理用户的表单权限"""
try:
user = get_user(username)
if not user:
return jsonify(success=False, message='用户不存在'), 404
if request.method == 'GET':
all_forms = get_all_forms()
form_list = [{'id': f['id'], 'title': f.get('title', '未命名表单')} for f in all_forms]
return jsonify({
'username': username,
'managed_forms': user.get('managed_forms', []),
'all_forms': form_list
})
elif request.method == 'POST':
data = request.get_json()
form_ids = data.get('form_ids', [])
update_user_managed_forms(username, form_ids)
return jsonify(success=True, message='权限已更新')
except Exception as e:
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env python3
"""
清理数据库中残留的临时ZIP文件
"""
import sqlite3
import os
from datetime import datetime, timedelta
# 项目根目录与数据库路径(根据你的实际路径修改)
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DB_PATH = os.path.join(_BASE_DIR, 'data', 'app.db')
def cleanup_temp_zip_files():
"""清理所有临时ZIP文件"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
try:
# 查找所有临时ZIP文件
# 文件名包含 '_自定义打包_' 或 '_打包_' 且以 .zip 结尾
cursor.execute("""
SELECT id, form_id, filename
FROM files
WHERE filename LIKE '%_自定义打包_%.zip'
OR filename LIKE '%_打包_%.zip'
OR (filename LIKE '%.zip' AND filename LIKE '%_%_%')
""")
temp_files = cursor.fetchall()
print(f"找到 {len(temp_files)} 个临时ZIP文件")
deleted_count = 0
for file_id, form_id, filename in temp_files:
try:
# 删除文件记录
cursor.execute("DELETE FROM files WHERE id = ?", (file_id,))
deleted_count += 1
print(f"🗑️ 已删除: {filename} (ID: {file_id}, 表单: {form_id})")
except Exception as e:
print(f"❌ 删除失败 {filename}: {e}")
conn.commit()
print(f"\n✅ 清理完成: 共删除 {deleted_count} 个临时ZIP文件")
except Exception as e:
print(f"❌ 清理过程出错: {e}")
conn.rollback()
finally:
conn.close()
def cleanup_all_zip_files():
"""清理所有ZIP文件(包括非临时的,谨慎使用)"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
try:
# 查找所有ZIP文件
cursor.execute("""
SELECT id, form_id, filename
FROM files
WHERE filename LIKE '%.xlsx' OR filename LIKE '%.exe'
""")
zip_files = cursor.fetchall()
print(f"找到 {len(zip_files)} 个ZIP文件")
print("\n文件列表:")
for file_id, form_id, filename in zip_files:
print(f" - {filename} (ID: {file_id})")
confirm = input("\n确认删除以上所有ZIP文件? (yes/no): ")
if confirm.lower() != 'yes':
print("已取消")
return
deleted_count = 0
for file_id, form_id, filename in zip_files:
try:
cursor.execute("DELETE FROM files WHERE id = ?", (file_id,))
deleted_count += 1
print(f"🗑️ 已删除: {filename}")
except Exception as e:
print(f"❌ 删除失败 {filename}: {e}")
conn.commit()
print(f"\n✅ 清理完成: 共删除 {deleted_count} 个ZIP文件")
except Exception as e:
print(f"❌ 清理过程出错: {e}")
conn.rollback()
finally:
conn.close()
def show_zip_files():
"""仅显示ZIP文件列表,不删除"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
try:
cursor.execute("""
SELECT id, form_id, filename, LENGTH(file_data) as size
FROM files
WHERE filename LIKE '%.zip'
ORDER BY id DESC
""")
zip_files = cursor.fetchall()
print(f"\n找到 {len(zip_files)} 个ZIP文件:\n")
print(f"{'ID':<8} {'表单ID':<12} {'文件名':<40} {'大小(MB)':<10}")
print("-" * 80)
total_size = 0
for file_id, form_id, filename, size in zip_files:
size_mb = size / 1024 / 1024 if size else 0
total_size += size_mb
# 截断长文件名
display_name = filename[:37] + \
'...' if len(filename) > 40 else filename
print(f"{file_id:<8} {form_id:<12} {display_name:<40} {size_mb:>8.2f}")
print("-" * 80)
print(f"总计: {len(zip_files)} 个文件, {total_size:.2f} MB")
except Exception as e:
print(f"❌ 查询出错: {e}")
finally:
conn.close()
if __name__ == '__main__':
import sys
print("=" * 60)
print("临时ZIP文件清理工具")
print("=" * 60)
print(f"数据库路径: {DB_PATH}")
print()
if not os.path.exists(DB_PATH):
print(f"❌ 数据库文件不存在: {DB_PATH}")
print("请修改脚本中的 DB_PATH 变量为正确的路径")
sys.exit(1)
# 显示菜单
print("请选择操作:")
print("1. 查看所有ZIP文件列表")
print("2. 清理临时ZIP文件(推荐)")
print("3. 清理所有ZIP文件(谨慎)")
print("4. 退出")
print()
choice = input("输入选项 (1-4): ").strip()
if choice == '1':
show_zip_files()
elif choice == '2':
confirm = input("确认删除临时ZIP文件? (yes/no): ")
if confirm.lower() == 'yes':
cleanup_temp_zip_files()
else:
print("已取消")
elif choice == '3':
cleanup_all_zip_files()
elif choice == '4':
print("退出")
else:
print("无效选项")
+210
View File
@@ -0,0 +1,210 @@
"""
数据迁移脚本 - 将旧版文件系统数据迁移到SQLite数据库
"""
import os
import json
import sqlite3
from datetime import datetime
from database import init_database, get_db_connection, save_form, save_preset, save_user, save_submission, save_file
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
FORMS_DIR = os.path.join(BASE_DIR, 'forms')
PRESETS_DIR = os.path.join(BASE_DIR, 'presets')
UPLOAD_BASE_FOLDER = os.path.join(BASE_DIR, 'uploads')
USERS_FILE = os.path.join(BASE_DIR, 'users.json')
def migrate_users():
"""迁移用户数据"""
print("迁移用户数据...")
if not os.path.exists(USERS_FILE):
print(" 用户文件不存在,跳过")
return
try:
with open(USERS_FILE, 'r', encoding='utf-8') as f:
users = json.load(f)
for username, user_data in users.items():
save_user(username, user_data)
print(f" 已迁移用户: {username}")
print(f"✅ 用户数据迁移完成,共 {len(users)} 个用户")
except Exception as e:
print(f"❌ 用户数据迁移失败: {e}")
def migrate_forms():
"""迁移表单配置"""
print("迁移表单配置...")
if not os.path.exists(FORMS_DIR):
print(" 表单目录不存在,跳过")
return
count = 0
for filename in os.listdir(FORMS_DIR):
if not filename.endswith('.json'):
continue
try:
filepath = os.path.join(FORMS_DIR, filename)
with open(filepath, 'r', encoding='utf-8') as f:
form_config = json.load(f)
save_form(form_config)
print(f" 已迁移表单: {form_config.get('id')} - {form_config.get('title', '未命名')}")
count += 1
except Exception as e:
print(f" ❌ 迁移表单失败 {filename}: {e}")
print(f"✅ 表单配置迁移完成,共 {count} 个表单")
def migrate_presets():
"""迁移预设数据"""
print("迁移预设数据...")
if not os.path.exists(PRESETS_DIR):
print(" 预设目录不存在,跳过")
return
count = 0
for filename in os.listdir(PRESETS_DIR):
if not filename.endswith('.json'):
continue
try:
filepath = os.path.join(PRESETS_DIR, filename)
with open(filepath, 'r', encoding='utf-8') as f:
preset_data = json.load(f)
save_preset(preset_data)
print(f" 已迁移预设: {preset_data.get('id')} - {preset_data.get('name', '未命名')}")
count += 1
except Exception as e:
print(f" ❌ 迁移预设失败 {filename}: {e}")
print(f"✅ 预设数据迁移完成,共 {count} 个预设")
def migrate_submissions_and_files():
"""迁移提交记录和文件"""
print("迁移提交记录和文件...")
if not os.path.exists(UPLOAD_BASE_FOLDER):
print(" 上传目录不存在,跳过")
return
total_files = 0
for form_id in os.listdir(UPLOAD_BASE_FOLDER):
form_upload_dir = os.path.join(UPLOAD_BASE_FOLDER, form_id)
if not os.path.isdir(form_upload_dir):
continue
# 处理提交记录文件 (submitted.txt)
submitted_file = os.path.join(form_upload_dir, 'submitted.txt')
if os.path.exists(submitted_file):
try:
with open(submitted_file, 'r', encoding='utf-8') as f:
submitted_tails = [line.strip() for line in f if line.strip()]
# 获取表单配置以查找学生信息
from database import get_form, get_preset
form = get_form(form_id)
if form:
preset_id = form.get('presetId')
preset = get_preset(preset_id) if preset_id else None
for tail in submitted_tails:
# 查找学生信息
student_id = None
student_name = None
if preset:
verify_digits = preset.get('config', {}).get('verifyDigits', 2)
for s in preset.get('students', []):
sid = s.get('id', '')
if len(sid) >= verify_digits and sid[-verify_digits:] == tail:
student_id = sid
student_name = s.get('name', '')
break
if student_id and student_name:
save_submission(form_id, student_id, student_name, tail)
print(f" 已迁移提交记录: {form_id} - {student_name} ({tail})")
except Exception as e:
print(f" ❌ 迁移提交记录失败 {form_id}: {e}")
# 迁移文件
for filename in os.listdir(form_upload_dir):
if filename in ['submitted.txt', 'time.json'] or filename.startswith('.'):
continue
file_path = os.path.join(form_upload_dir, filename)
if not os.path.isfile(file_path):
continue
try:
with open(file_path, 'rb') as f:
file_data = f.read()
# 从文件名解析学生信息
# 格式: 姓名学号.扩展名 或 姓名学号_字段名.扩展名
name_part = filename.rsplit('.', 1)[0] # 去掉扩展名
field_name = None
if '_' in name_part:
parts = name_part.rsplit('_', 1)
name_part = parts[0]
field_name = parts[1]
save_file(
form_id=form_id,
file_data=file_data,
filename=filename,
original_name=filename,
field_name=field_name
)
print(f" 已迁移文件: {form_id}/{filename} ({len(file_data)} bytes)")
total_files += 1
except Exception as e:
print(f" ❌ 迁移文件失败 {filename}: {e}")
print(f"✅ 文件迁移完成,共 {total_files} 个文件")
def main():
"""主迁移函数"""
print("=" * 60)
print("数据迁移工具 - 文件系统到SQLite数据库")
print("=" * 60)
print()
# 初始化数据库
print("初始化数据库...")
init_database()
print()
# 执行迁移
migrate_users()
print()
migrate_forms()
print()
migrate_presets()
print()
migrate_submissions_and_files()
print()
print("=" * 60)
print("迁移完成!")
print("=" * 60)
print()
print("注意:")
print("1. 旧数据仍然保留在原位置,不会自动删除")
print("2. 请验证新系统正常工作后再手动删除旧数据")
print("3. 数据库文件位置:", os.path.join(BASE_DIR, 'app.db'))
if __name__ == '__main__':
main()
+55
View File
@@ -0,0 +1,55 @@
"""
一次性迁移脚本:为已存在的 forms 表补充 announcement 列 + 创建公告附件表。
用法(在服务器项目根目录执行):
python scripts/migrate_announcement.py
脚本是幂等的,可重复运行。
"""
import os
import sys
# 确保能导入项目根目录的 db.py / database.py
_PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _PROJECT_DIR not in sys.path:
sys.path.insert(0, _PROJECT_DIR)
from db import get_db_connection, is_sqlite, get_table_columns, table_exists
def main():
with get_db_connection() as conn:
cursor = conn.cursor()
# 1. 检查并补充 announcement 列
cols = get_table_columns(conn, 'forms')
names = [c['name'] for c in cols]
if 'announcement' not in names:
cursor.execute('ALTER TABLE forms ADD COLUMN announcement TEXT')
print("✅ 已为 forms 表添加 announcement 列")
else:
print("ℹ️ forms 表已有 announcement 列,跳过")
# 2. 检查并创建公告附件表
if not table_exists(conn, 'form_announcement_files'):
cursor.execute('''
CREATE TABLE IF NOT EXISTS form_announcement_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
form_id TEXT NOT NULL,
filename TEXT NOT NULL,
original_name TEXT,
file_size INTEGER,
mime_type TEXT,
file_data BLOB NOT NULL,
uploaded_at TEXT NOT NULL,
FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_announcement_files_form ON form_announcement_files(form_id)')
print("✅ 已创建 form_announcement_files 表")
else:
print("ℹ️ form_announcement_files 表已存在,跳过")
print("🎉 迁移完成")
if __name__ == '__main__':
main()
+64
View File
@@ -0,0 +1,64 @@
// 提交前校验脚本:压缩包内必须同时包含(doc/docx/pdf)和(ppt/pptx)
// 用法:粘贴到"启用提交前校验"的脚本框中
async function (values, fields, ctx) {
const DOC_EXTS = ['doc', 'docx', 'pdf'];
const PPT_EXTS = ['ppt', 'pptx'];
// 从 zip 原始字节中解析出所有条目文件名(无需解压)
function listZipNames(buf) {
const view = new DataView(buf);
const bytes = new Uint8Array(buf);
const decoder = flag => flag & 0x800 ? new TextDecoder('utf-8') : new TextDecoder('gbk');
const names = [];
let i = 0;
while (i + 4 <= bytes.length) {
// 找本地文件头签名 PK\x03\x04
if (bytes[i] === 0x50 && bytes[i + 1] === 0x4B && bytes[i + 2] === 0x03 && bytes[i + 3] === 0x04) {
if (i + 30 > bytes.length) break;
const nameLen = view.getUint16(i + 26, true);
const extraLen = view.getUint16(i + 28, true);
const flag = view.getUint16(i + 6, true);
if (i + 30 + nameLen > bytes.length) break;
const raw = bytes.subarray(i + 30, i + 30 + nameLen);
let name;
try { name = decoder(flag).decode(raw); } catch (e) { name = new TextDecoder('latin1').decode(raw); }
if (!name.endsWith('/')) names.push(name);
i += 30 + nameLen + extraLen;
} else {
i++;
}
}
return names;
}
const extOf = n => { const p = n.toLowerCase().split('.'); return p.length > 1 ? p.pop() : ''; };
for (const field of fields) {
if (field.type !== 'file') continue;
const file = values[field.name];
if (!file) continue;
const ext = extOf(file.name);
if (ext !== 'zip') continue;
let names;
try {
names = listZipNames(await file.arrayBuffer());
} catch (e) {
return { ok: false, msg: '压缩包读取失败,请重新打包后再上传。' };
}
if (!names.length) {
return { ok: false, msg: '压缩包为空或已损坏,请重新打包后再上传。' };
}
const hasDoc = names.some(n => DOC_EXTS.includes(extOf(n)));
const hasPpt = names.some(n => PPT_EXTS.includes(extOf(n)));
const missing = [];
if (!hasDoc) missing.push('Word 文档(doc/docx)或 PDF');
if (!hasPpt) missing.push('演示文稿(ppt/pptx)');
if (missing.length) {
return { ok: false, msg: `「${file.name}」压缩包内缺少:${missing.join('和')},请检查后重新上传。` };
}
}
return { ok: true };
}
+111
View File
@@ -0,0 +1,111 @@
/* 基础 CSS 变量 - 所有页面共用 */
/* ========== 浅色模式 ========== */
:root {
/* 背景 */
--bg-primary: #fafafa;
--bg-secondary: #ffffff;
/* 文字 */
--text-primary: #171717;
--text-secondary: #525252;
--text-muted: #737373;
/* 边框 */
--border-color: #e5e5e5;
--border-focus: #171717;
/* 输入框 */
--input-bg: #fafafa;
--input-border: #d4d4d4;
--input-text: #171717;
/* 强调色 */
--accent-bg: #171717;
--accent-text: #ffffff;
/* 毛玻璃 */
--glass-bg: rgba(255, 255, 255, 0.7);
--glass-border: rgba(255, 255, 255, 0.5);
--glass-hover: rgba(255, 255, 255, 0.9);
/* 阴影 */
--shadow-color: rgba(0, 0, 0, 0.05);
/* 状态色 - Success */
--success-bg: #f0fdf4;
--success-border: #dcfce7;
--success-text: #16a34a;
/* 状态色 - Error */
--error-bg: #fef2f2;
--error-border: #fee2e2;
--error-text: #dc2626;
/* 状态色 - Warning */
--warning-bg: #fffbeb;
--warning-border: #fef3c7;
--warning-text: #d97706;
/* 状态色 - Info */
--info-bg: #eff6ff;
--info-border: #dbeafe;
--info-text: #2563eb;
--progress-green: #4ade80;
--progress-red: #ef4444;
}
/* ========== 深色模式 ========== */
.dark {
/* 背景 */
--bg-primary: #0a0a0a;
--bg-secondary: #171717;
/* 文字 */
--text-primary: #fafafa;
--text-secondary: #a3a3a3;
--text-muted: #737373;
/* 边框 */
--border-color: #262626;
--border-focus: #fafafa;
/* 输入框 */
--input-bg: #262626;
--input-border: #404040;
--input-text: #fafafa;
/* 强调色 */
--accent-bg: #fafafa;
--accent-text: #171717;
/* 毛玻璃 */
--glass-bg: rgba(23, 23, 23, 0.8);
--glass-border: rgba(255, 255, 255, 0.1);
--glass-hover: rgba(38, 38, 38, 0.9);
/* 阴影 */
--shadow-color: rgba(0, 0, 0, 0.5);
/* 状态色 - Success */
--success-bg: rgba(22, 163, 74, 0.1);
--success-border: rgba(22, 163, 74, 0.2);
--success-text: #4ade80;
/* 状态色 - Error */
--error-bg: rgba(220, 38, 38, 0.1);
--error-border: rgba(220, 38, 38, 0.2);
--error-text: #ef4444;
/* 状态色 - Warning */
--warning-bg: rgba(217, 119, 6, 0.1);
--warning-border: rgba(217, 119, 6, 0.2);
--warning-text: #fbbf24;
/* 状态色 - Info */
--info-bg: rgba(37, 99, 235, 0.1);
--info-border: rgba(37, 99, 235, 0.2);
--info-text: #60a5fa;
--progress-green: #4ade80;
--progress-red: #ef4444;
}
+425
View File
@@ -0,0 +1,425 @@
/* ============================================================
common.css — 全站公共样式
依赖: basic.css(CSS 变量定义)
============================================================ */
/* ── 全局重置 ────────────────────────────────────────────── */
*, *::before, *::after {
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
html {
scroll-behavior: smooth;
}
::selection {
background: rgba(128, 128, 128, 0.2);
color: var(--text-primary);
}
/* ── 字体导入 ─────────────────────────────────────────────── */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:ital,wght@0,400;0,600;1,400&display=swap');
@import url('/static/toast.css');
/* ── Body 基础 ────────────────────────────────────────────── */
body {
font-family: 'Inter', sans-serif;
background-color: var(--bg-primary);
background-image:
radial-gradient(at 0% 0%, rgba(128, 128, 128, 0.03) 0px, transparent 50%),
radial-gradient(at 100% 100%, rgba(128, 128, 128, 0.03) 0px, transparent 50%);
color: var(--text-primary);
margin: 0;
min-height: 100vh;
overflow-x: hidden;
transition: background-color 0.5s ease, color 0.5s ease;
}
.dark body {
background-image:
radial-gradient(at 0% 0%, rgba(255, 255, 255, 0.02) 0px, transparent 50%),
radial-gradient(at 100% 100%, rgba(255, 255, 255, 0.02) 0px, transparent 50%);
}
/* ── 滚动条 ───────────────────────────────────────────────── */
body::-webkit-scrollbar {
width: 6px;
}
body::-webkit-scrollbar-track {
background: transparent;
}
body::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 3px;
}
body::-webkit-scrollbar-thumb:hover {
background: var(--text-muted);
}
/* ── 字体辅助类 ───────────────────────────────────────────── */
.font-serif {
font-family: 'Playfair Display', serif;
}
/* ── 毛玻璃效果 ───────────────────────────────────────────── */
.glass {
background: var(--glass-bg);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid var(--glass-border);
transition: all 0.3s ease;
}
.glass:hover {
background: var(--glass-hover);
}
/* ── 主题过渡 ─────────────────────────────────────────────── */
.theme-transition {
transition: background-color 0.5s ease, color 0.5s ease,
border-color 0.5s ease, box-shadow 0.5s ease;
}
/* ── 按钮系统 ─────────────────────────────────────────────── */
.btn {
position: relative;
overflow: hidden;
transition: all 0.3s cubic-bezier(0.2, 0, 0, 1);
font-family: 'Inter', sans-serif;
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
}
.btn::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(128, 128, 128, 0.1), transparent);
transition: left 0.5s;
}
.btn:hover::before {
left: 100%;
}
.btn-primary {
background-color: var(--accent-bg);
color: var(--accent-text);
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 10px 20px -5px var(--shadow-color);
}
.btn-secondary {
background-color: var(--bg-primary);
color: var(--text-secondary);
border: 1px solid var(--border-color);
}
.btn-secondary:hover {
background-color: var(--bg-secondary);
transform: translateY(-2px);
}
.btn-danger {
background-color: var(--error-bg);
color: var(--error-text);
border: 1px solid var(--error-border);
}
.btn-danger:hover {
opacity: 0.8;
transform: translateY(-2px);
}
/* ── 滚动进度条 ───────────────────────────────────────────── */
#scrollProgress {
background: linear-gradient(90deg, var(--text-muted), var(--text-primary));
}
/* ── 加载动画 ─────────────────────────────────────────────── */
.loading-spinner {
width: 40px;
height: 40px;
border: 3px solid var(--border-color);
border-top-color: var(--text-primary);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
/* 小尺寸 spinner(用于按钮内联)*/
.loading-spinner-sm {
width: 16px;
height: 16px;
border: 2px solid currentColor;
border-top-color: transparent;
border-radius: 50%;
animation: spin 0.8s linear infinite;
display: inline-block;
margin-left: 8px;
vertical-align: middle;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* ── Modal 对话框 ─────────────────────────────────────────── */
.modal-overlay {
position: fixed;
inset: 0;
z-index: 1000;
display: none;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
opacity: 0;
transition: opacity 0.3s ease;
}
.modal-overlay.show {
display: flex;
opacity: 1;
}
.modal-content {
background: var(--bg-secondary);
border: 1px solid var(--glass-border);
border-radius: 24px;
padding: 40px;
width: 90%;
max-width: 480px;
transform: scale(0.95) translateY(20px);
transition: transform 0.4s cubic-bezier(0.2, 0, 0, 1);
}
.modal-overlay.show .modal-content {
transform: scale(1) translateY(0);
}
/* ── GSAP 入场动画初始状态 ────────────────────────────────── */
.stagger-item {
opacity: 0;
transform: translateY(20px);
}
/* ── 输入框样式(create/edit 共用)────────────────────────── */
.input-underline {
width: 100%;
min-height: 44px;
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 10px;
padding: 10px 12px;
font-size: 15px;
color: var(--text-primary);
outline: none;
transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;
font-family: 'Inter', sans-serif;
}
.input-underline:focus {
border-color: var(--border-focus);
box-shadow: 0 0 0 3px var(--shadow-color);
}
.input-underline::placeholder {
color: var(--text-muted);
}
select.input-underline {
cursor: pointer;
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg width='10' height='6' viewBox='0 0 10 6' fill='none'%3E%3Cpath d='M1 1L5 5L9 1' stroke='%23737373' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 12px center;
padding-right: 34px;
}
/* ── 卡片字段(create/edit 共用)──────────────────────────── */
.field-card {
background: var(--glass-bg);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid var(--glass-border);
border-radius: 16px;
padding: 16px;
margin-bottom: 10px;
position: relative;
transition: all 0.4s cubic-bezier(0.2, 0, 0, 1);
overflow: hidden;
touch-action: pan-y;
}
.field-card:hover {
transform: translateY(-2px);
box-shadow: 0 20px 40px -15px var(--shadow-color);
border-color: rgba(128, 128, 128, 0.3);
background: var(--glass-hover);
}
.field-edit-input {
width: 100%;
min-height: 40px;
padding: 9px 11px;
border: 1px solid var(--border-color);
border-radius: 10px;
background: var(--bg-primary);
color: var(--text-primary);
font-size: 14px;
outline: none;
transition: border-color .2s ease, box-shadow .2s ease, background-color .2s ease;
}
.field-edit-input::placeholder { color: var(--text-muted); }
.field-edit-input:focus {
border-color: var(--border-focus);
box-shadow: 0 0 0 3px var(--shadow-color);
}
.field-condition-button {
position: absolute;
top: 16px;
right: 52px;
width: 28px !important;
height: 28px;
padding: 0 !important;
margin-top: 0 !important;
}
.field-condition-button span {
display: none;
}
.field-card.sortable-ghost {
opacity: 0.3;
background: linear-gradient(135deg, var(--info-bg) 0%, transparent 100%);
border: 2px dashed var(--info-text);
transform: scale(0.98);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.field-card.sortable-drag {
opacity: 0.95;
transform: scale(1.03) rotate(1deg);
box-shadow:
0 25px 50px -12px var(--shadow-color),
0 0 0 1px rgba(128, 128, 128, 0.1);
cursor: grabbing;
z-index: 1000;
animation: dragPulse 2s ease-in-out infinite;
}
.field-card.sortable-drag::before {
content: '';
position: absolute;
inset: 0;
border-radius: 20px;
background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, transparent 50%);
pointer-events: none;
}
@keyframes dragPulse {
0%, 100% { box-shadow: 0 25px 50px -12px var(--shadow-color); }
50% { box-shadow: 0 30px 60px -15px var(--shadow-color), 0 0 20px rgba(128, 128, 128, 0.1); }
}
@media (hover: none) and (pointer: coarse) {
.field-card.sortable-drag {
opacity: 0.98;
transform: scale(1.02);
box-shadow: 0 20px 40px -10px var(--shadow-color);
animation: none;
}
}
/* ── 拖拽手柄 ─────────────────────────────────────────────── */
.drag-handle {
cursor: grab;
padding: 8px;
margin: -8px;
border-radius: 8px;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
touch-action: none;
user-select: none;
-webkit-user-select: none;
}
.drag-handle:hover {
background: var(--bg-primary);
transform: scale(1.1);
}
.drag-handle:active {
cursor: grabbing;
transform: scale(0.95);
}
@media (hover: none) and (pointer: coarse) {
.drag-handle {
padding: 12px;
margin: -12px;
}
.drag-handle svg {
width: 20px;
height: 20px;
}
}
/* ── 自定义 Checkbox ──────────────────────────────────────── */
.checkbox-custom {
appearance: none;
width: 18px;
height: 18px;
border: 2px solid var(--border-color);
border-radius: 6px;
cursor: pointer;
position: relative;
transition: all 0.2s ease;
flex-shrink: 0;
}
.checkbox-custom:checked {
background-color: var(--accent-bg);
border-color: var(--accent-bg);
}
.checkbox-custom:checked::after {
content: '';
position: absolute;
left: 4px;
top: 1px;
width: 6px;
height: 10px;
border: 2px solid var(--accent-text);
border-top: none;
border-left: none;
transform: rotate(45deg);
}
/* ── 导航栏链接(面包屑风格)──────────────────────────────── */
.nav-link {
color: var(--text-secondary);
font-size: 14px;
transition: color 0.2s;
text-decoration: none;
}
.nav-link:hover {
color: var(--text-primary);
}
+678
View File
@@ -0,0 +1,678 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:ital,wght@0,400;0,600;1,400&display=swap');
/* 表单工作台与填写页:冷调蓝灰、清晰层级和克制的状态动效。 */
.submission-page .field-wrapper[data-url-hidden="true"] { display: none !important; }
.submission-page .url-prefilled input:disabled,
.submission-page .url-prefilled textarea:disabled,
.submission-page .url-prefilled select:disabled { cursor: not-allowed; opacity: .8; }
.submission-page .url-prefilled label,
.submission-page .url-prefilled .rating-stars { cursor: not-allowed; }
.submission-page .url-prefilled .rating-stars[aria-disabled="true"] { pointer-events: none; }
.builder-page .stagger-item,
.submission-page .stagger-item {
opacity: 1;
transform: none;
}
.builder-page,
.submission-page {
--bg-primary: #edf2f8;
--bg-secondary: #fbfdff;
--text-primary: #17253a;
--text-secondary: #465973;
--text-muted: #5f7189;
--border-color: #cfdaea;
--border-focus: #285bd4;
--input-bg: #f5f8fc;
--input-border: #c5d3e6;
--input-text: #17253a;
--accent-bg: #285bd4;
--accent-text: #fff;
--glass-bg: rgba(251, 253, 255, .88);
--glass-border: rgba(37, 74, 128, .14);
--glass-hover: rgba(251, 253, 255, .97);
--shadow-color: rgba(24, 54, 103, .13);
--studio-side: #f4f8fd;
--studio-ink-soft: #e3ebf7;
--studio-glow: rgba(63, 115, 223, .16);
color: var(--text-primary);
background-color: var(--bg-primary);
background-image:
radial-gradient(circle at 74% 0%, rgba(75, 132, 235, .14), transparent 32%),
linear-gradient(180deg, #f5f8fd 0%, #edf2f8 48%, #e8eef6 100%);
}
.dark body.builder-page,
.dark body.submission-page {
--bg-primary: #0b1524;
--bg-secondary: #142338;
--text-primary: #f0f5ff;
--text-secondary: #b6c5da;
--text-muted: #92a7c1;
--border-color: #324763;
--border-focus: #91b2ff;
--input-bg: #102036;
--input-border: #39516f;
--input-text: #f0f5ff;
--accent-bg: #91b2ff;
--accent-text: #0d1b30;
--glass-bg: rgba(20, 35, 56, .89);
--glass-border: rgba(179, 204, 239, .17);
--glass-hover: rgba(29, 48, 74, .97);
--shadow-color: rgba(0, 5, 15, .45);
--studio-side: #102035;
--studio-ink-soft: #243b59;
--studio-glow: rgba(100, 148, 255, .15);
background-color: var(--bg-primary);
background-image:
radial-gradient(circle at 75% -8%, rgba(68, 112, 190, .22), transparent 33%),
linear-gradient(180deg, #0e1c30 0%, #0b1524 46%, #09111f 100%);
}
.builder-page::before,
.submission-page::before {
content: '';
position: fixed;
inset: 0;
z-index: -1;
pointer-events: none;
opacity: .24;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 180 180' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.72' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' opacity='.11' filter='url(%23n)'/%3E%3C/svg%3E");
}
.builder-page > header,
.submission-page > header {
background: color-mix(in srgb, var(--bg-secondary) 91%, transparent) !important;
border-color: var(--glass-border) !important;
box-shadow: 0 9px 28px -24px var(--text-primary);
backdrop-filter: blur(20px) saturate(135%);
-webkit-backdrop-filter: blur(20px) saturate(135%);
}
.builder-page #scrollProgress,
.submission-page #scrollProgress {
background: var(--accent-bg) !important;
box-shadow: 0 0 16px var(--studio-glow);
}
.builder-page main { padding-top: 126px; }
.submission-page main { padding-top: 136px; }
.studio-kicker {
display: inline-flex;
align-items: center;
gap: 9px;
margin: 0 0 16px;
color: var(--accent-bg) !important;
font: 700 11px/1.3 Inter, system-ui, sans-serif !important;
letter-spacing: .15em !important;
text-transform: uppercase;
}
.studio-kicker__dot {
width: 7px;
height: 7px;
flex: none;
border-radius: 50%;
background: var(--accent-bg);
box-shadow: 0 0 0 5px var(--studio-glow);
}
.builder-page #headerSection,
.submission-page #headerSection {
position: relative;
margin-bottom: 28px;
padding-left: 2px;
}
.builder-page #headerSection h2,
.submission-page #headerSection h1 {
margin-bottom: 10px;
color: var(--text-primary);
font-family: Inter, 'Microsoft YaHei', system-ui, sans-serif;
font-size: clamp(32px, 3vw, 46px);
font-weight: 750;
line-height: 1.12;
letter-spacing: -.045em;
text-wrap: balance;
}
.builder-page #headerSection p:not(.studio-kicker),
.submission-page #headerSection p:not(.studio-kicker) {
max-width: 650px;
color: var(--text-secondary) !important;
font-size: 14px;
font-weight: 400;
line-height: 1.65;
}
.builder-page #mobileTabbar > .glass {
padding: 5px;
background: var(--studio-side);
border: 1px solid var(--border-color) !important;
box-shadow: 0 14px 28px -24px var(--text-primary);
}
.builder-page #mobileTabbar button {
min-height: 42px;
border-radius: 999px;
color: var(--text-secondary);
}
.builder-page #mobileTabbar button.active {
background: var(--accent-bg);
color: var(--accent-text);
box-shadow: 0 8px 22px -13px var(--accent-bg);
}
.builder-page #palettePane > .glass,
.builder-page #settingsPane > .glass {
background: var(--studio-side);
border: 1px solid var(--border-color);
border-radius: 22px;
box-shadow: 0 18px 42px -34px var(--text-primary);
backdrop-filter: none;
-webkit-backdrop-filter: none;
animation: studio-enter .65s cubic-bezier(.16, 1, .3, 1) both;
}
.builder-page #settingsPane > .glass { animation-delay: .11s; }
.builder-page #palettePane h2,
.builder-page #settingsPane h2,
.builder-page #fieldsSection h3 {
color: var(--text-primary) !important;
font-family: Inter, 'Microsoft YaHei', system-ui, sans-serif;
font-weight: 700;
letter-spacing: -.03em;
}
.builder-page #palettePane .fc-tile {
min-height: 48px;
padding: 10px 11px;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 12px;
box-shadow: 0 3px 9px -8px var(--text-primary);
transition: transform .25s cubic-bezier(.16, 1, .3, 1),
border-color .25s ease, box-shadow .25s ease, background-color .25s ease;
}
.builder-page #palettePane .fc-tile:hover,
.builder-page #palettePane .fc-tile:focus-visible {
background: color-mix(in srgb, var(--accent-bg) 9%, var(--bg-secondary));
border-color: var(--accent-bg);
box-shadow: 0 10px 19px -15px var(--accent-bg);
transform: translateY(-3px);
}
.builder-page #palettePane .fc-tile:active {
transform: translateY(-1px) scale(.98);
transition-duration: .1s;
}
.builder-page #palettePane .fc-tile svg,
.builder-page #palettePane .fc-tile:hover svg {
stroke: var(--accent-bg);
}
.builder-page #palettePane .fc-label { color: var(--text-primary); font-weight: 600; }
.builder-page #editorPane > .glass,
.builder-page #editorPane > #formContainer,
.submission-page #formContainer {
position: relative;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 24px;
box-shadow: 0 24px 68px -48px var(--text-primary) !important;
backdrop-filter: none;
-webkit-backdrop-filter: none;
isolation: isolate;
}
.builder-page #editorPane > .glass,
.builder-page #editorPane > #formContainer:not(.hidden) {
animation: studio-enter .75s cubic-bezier(.16, 1, .3, 1) .08s both;
}
.builder-page #fieldsSection {
padding-top: 30px;
border-top: 1px solid var(--border-color);
}
.builder-page #fieldsSection > div:first-child {
padding-bottom: 12px;
}
.builder-page #emptyFieldsState {
padding: 42px 24px;
background: var(--input-bg);
border-color: var(--input-border) !important;
border-style: dashed;
border-radius: 16px;
}
.builder-page .field-card {
background: var(--input-bg);
border-color: var(--border-color);
border-radius: 16px;
backdrop-filter: none;
-webkit-backdrop-filter: none;
transition: border-color .24s ease, box-shadow .24s ease, transform .24s cubic-bezier(.16, 1, .3, 1);
}
.builder-page .field-card:hover,
.builder-page .field-card:focus-within {
background: var(--input-bg);
border-color: var(--accent-bg);
box-shadow: 0 14px 30px -25px var(--accent-bg);
transform: translateY(-2px);
}
.builder-page .page-break-card {
background: color-mix(in srgb, var(--accent-bg) 6%, var(--bg-secondary));
border-style: dashed;
border-color: color-mix(in srgb, var(--accent-bg) 36%, var(--border-color));
}
.builder-page .page-break-card:focus-within {
border-style: solid;
}
.builder-page .page-break-card .page-break-label {
color: var(--accent-bg);
font-size: 12px;
font-weight: 700;
letter-spacing: .08em;
}
.builder-page .preset-option {
background: var(--bg-secondary);
border-color: var(--border-color);
border-radius: 12px;
}
.builder-page .preset-option:hover { border-color: var(--accent-bg); }
.builder-page .preset-option.selected {
background: color-mix(in srgb, var(--accent-bg) 9%, var(--bg-secondary));
border-color: var(--accent-bg);
box-shadow: inset 3px 0 0 var(--accent-bg);
}
.builder-page .input-underline,
.builder-page .field-edit-input,
.submission-page .form-entry-box,
.submission-page #upForm :is(input, select, textarea):not([type='checkbox']):not([type='radio']):not([type='file']):not([type='range']) {
background-color: var(--input-bg);
border-color: var(--input-border);
border-radius: 12px;
color: var(--input-text);
}
.builder-page :is(.input-underline, .field-edit-input):focus,
.submission-page #upForm :is(input, select, textarea):focus {
border-color: var(--border-focus) !important;
box-shadow: 0 0 0 4px var(--studio-glow) !important;
}
.submission-page #upForm .field-wrapper :is(input, select, textarea):focus {
box-shadow: none !important;
}
.submission-page #upForm .field-wrapper :is(input, select, textarea):focus-visible {
outline: none;
}
.builder-page :is(button, a, input, select, textarea, summary):focus-visible,
.submission-page :is(button, a, input, select, textarea):focus-visible {
outline: 2px solid var(--border-focus);
outline-offset: 3px;
}
.builder-page .btn-primary,
.submission-page #submitBtn {
background: var(--accent-bg) !important;
color: var(--accent-text) !important;
box-shadow: 0 14px 28px -18px var(--accent-bg) !important;
transition: transform .25s cubic-bezier(.16, 1, .3, 1), box-shadow .25s ease;
}
.builder-page .btn-primary { border-radius: 12px; }
.submission-page #submitBtn { border-radius: 999px; }
.builder-page .btn-primary:hover,
.submission-page #submitBtn:hover {
transform: translateY(-2px);
box-shadow: 0 19px 32px -17px var(--accent-bg) !important;
}
.builder-page .btn-primary:active,
.submission-page #submitBtn:active {
transform: translateY(0) scale(.985);
transition-duration: .1s;
}
.submission-page main > div { max-width: 700px; }
.submission-page #headerSection { margin-bottom: 32px; scroll-margin-top: 102px; }
.submission-page #headerSection h1 { font-size: clamp(38px, 4vw, 54px); }
.submission-page #formContainer { padding-top: 42px; }
.submission-page #formContainer { scroll-margin-top: 96px; }
.submission-page #announcementSection,
.submission-page #progressSection {
background: var(--studio-side);
border: 1px solid var(--border-color);
border-radius: 16px;
box-shadow: 0 12px 26px -25px var(--text-primary);
}
.submission-page #progressBar {
background: var(--accent-bg) !important;
}
.submission-page #progressPercent { color: var(--accent-bg) !important; }
.submission-page #upForm .field-wrapper {
padding: 0 0 28px;
border-bottom: 1px solid var(--border-color);
}
.submission-page #upForm .field-wrapper:hover,
.submission-page #upForm .field-wrapper:focus-within {
background: transparent;
box-shadow: none;
outline: none;
}
.submission-page #upForm input[type='range']:focus-visible,
.submission-page #upForm .rating-stars:focus-visible {
outline: none;
box-shadow: none;
}
.submission-page #upForm input[type='range']:focus-visible::-webkit-slider-thumb {
box-shadow: 0 0 0 5px var(--studio-glow);
}
.submission-page #upForm .rating-stars:focus-visible .rating-star-item:first-child {
filter: drop-shadow(0 0 6px rgba(251, 191, 36, .45));
}
.submission-page #upForm .field-wrapper > label {
display: flex;
align-items: center;
gap: 11px;
color: var(--text-primary) !important;
font-size: 15px;
font-weight: 650;
letter-spacing: 0;
text-transform: none;
}
.submission-page .field-label-content { min-width: 0; }
.submission-page .field-optional-mark {
margin-left: 4px;
color: var(--text-muted);
font-size: .88em;
font-weight: 400;
}
.submission-page .field-required-mark {
margin-left: 3px;
color: #cf3d4c;
font-size: 1.12em;
font-weight: 800;
line-height: 1;
}
.dark .submission-page .field-required-mark { color: #ff7780; }
.submission-page .field-index {
display: inline-flex;
align-items: center;
justify-content: center;
width: 29px;
height: 29px;
flex: none;
border-radius: 9px;
background: color-mix(in srgb, var(--accent-bg) 12%, var(--bg-secondary));
color: var(--accent-bg);
font: 700 11px/1 Inter, system-ui, sans-serif;
letter-spacing: 0;
}
.submission-page .slider-shell {
--slider-progress: 0%;
position: relative;
flex: 1;
min-width: 0;
height: 30px;
}
.submission-page .slider-rail {
position: absolute;
top: 50%;
right: 10px;
left: 10px;
height: 6px;
border-radius: 999px;
background: var(--border-color);
transform: translateY(-50%);
pointer-events: none;
}
.submission-page .slider-rail-fill {
display: block;
width: var(--slider-progress);
height: 100%;
border-radius: inherit;
background: var(--accent-bg);
box-shadow: 0 0 12px var(--studio-glow);
transition: width .28s cubic-bezier(.16, 1, .3, 1);
}
.submission-page .slider-thumb {
position: absolute;
top: 50%;
left: var(--slider-progress);
width: 22px;
height: 22px;
border: 3px solid var(--accent-bg);
border-radius: 50%;
background: var(--bg-secondary);
box-shadow: 0 3px 10px -5px var(--text-primary);
transform: translate(-50%, -50%);
transition: left .28s cubic-bezier(.16, 1, .3, 1),
transform .2s ease, box-shadow .2s ease;
}
.submission-page .slider-shell.is-dragging .slider-rail-fill,
.submission-page .slider-shell.is-dragging .slider-thumb {
transition-duration: 0ms;
}
.submission-page .slider-shell:focus-within .slider-thumb {
box-shadow: 0 0 0 5px var(--studio-glow), 0 3px 10px -5px var(--text-primary);
}
.submission-page #upForm .slider-shell .slider-native {
position: absolute;
inset: 0;
z-index: 1;
display: block;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
cursor: pointer;
}
.submission-page #submitBtn { min-height: 54px; }
.submission-page .form-page[hidden],
.submission-page .form-page-status[hidden],
.submission-page #pagePrevBtn[hidden],
.submission-page #nextPageBtn[hidden],
.submission-page #submitBtn[hidden] { display: none !important; }
.submission-page .form-page-status {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding-bottom: 18px;
border-bottom: 1px solid var(--border-color);
color: var(--text-muted);
font-size: 12px;
font-weight: 650;
letter-spacing: .06em;
}
.submission-page .form-page-steps { display: flex; gap: 6px; position: relative; }
.submission-page .form-page-step {
position: relative;
overflow: hidden;
width: 24px;
height: 4px;
border-radius: 999px;
background: var(--border-color);
}
.submission-page .form-page-step::after {
content: '';
position: absolute;
inset: 0;
border-radius: inherit;
background: var(--accent-bg);
transform: scaleX(0);
transform-origin: left center;
transition: transform .38s cubic-bezier(.16, 1, .3, 1);
}
.submission-page .form-page-step.complete::after { transform: scaleX(1); }
.submission-page .form-page-active {
position: absolute;
top: 0;
left: 0;
width: 24px;
height: 4px;
border-radius: 999px;
background: var(--accent-bg);
box-shadow: 0 0 12px color-mix(in srgb, var(--accent-bg) 55%, transparent);
transform: translateX(var(--step-offset, 0px));
transition: transform .46s cubic-bezier(.16, 1, .3, 1);
pointer-events: none;
}
.submission-page .numeric-display {
display: inline-block;
font-variant-numeric: tabular-nums;
white-space: nowrap;
transition: transform .22s cubic-bezier(.16, 1, .3, 1), filter .22s ease;
}
.submission-page .number-spoken {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.submission-page .number-visual {
display: inline-flex;
align-items: baseline;
white-space: pre;
}
.submission-page .number-static-digit,
.submission-page .number-reel {
display: inline-block;
width: .62em;
flex: none;
text-align: center;
}
.submission-page .number-reel {
position: relative;
height: 1.12em;
overflow: hidden;
vertical-align: -.08em;
-webkit-mask-image: linear-gradient(to bottom, transparent 0%, #000 14%, #000 86%, transparent 100%);
mask-image: linear-gradient(to bottom, transparent 0%, #000 14%, #000 86%, transparent 100%);
}
.submission-page .number-reel-track {
display: flex;
flex-direction: column;
line-height: 1.12em;
will-change: transform;
}
.submission-page .number-reel-face {
display: block;
height: 1.12em;
flex: none;
}
.submission-page .numeric-display.number-changing {
transform: translateY(-1px);
filter: brightness(1.18) drop-shadow(0 0 7px var(--numeric-glow, var(--accent-bg)));
}
.submission-page .rating-value-display { --numeric-glow: #fbbf24; }
.submission-page .form-nav {
display: flex;
gap: 12px;
}
.submission-page #pagePrevBtn {
min-width: 120px;
border: 1px solid var(--border-color);
border-radius: 999px;
color: var(--text-primary);
background: var(--input-bg);
font-weight: 600;
transition: border-color .2s ease, background-color .2s ease, transform .2s ease;
}
.submission-page #pagePrevBtn:hover {
border-color: var(--accent-bg);
transform: translateY(-2px);
}
.submission-page .form-nav #submitBtn,
.submission-page .form-nav #nextPageBtn { flex: 1; width: auto; }
.submission-page input[type="file"].has-file + div,
.submission-page input[type="file"][data-has-file="true"] + div,
.dark .submission-page input[type="file"].has-file + div,
.dark .submission-page input[type="file"][data-has-file="true"] + div {
animation: fileSelected .35s cubic-bezier(.16, 1, .3, 1) both;
}
.submission-page #particleCanvas,
.builder-page #particleCanvas { opacity: .22 !important; }
@keyframes studio-enter {
from { opacity: 0; transform: translateY(18px) scale(.99); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@media (max-width: 1279px) {
.builder-page #mobileTabbar { top: 83px; }
}
@media (max-width: 640px) {
.builder-page main,
.submission-page main { padding: 104px 16px 64px; }
.builder-page #mobileTabbar { top: 73px; }
.builder-page #editorPane > .glass,
.builder-page #editorPane > #formContainer,
.submission-page #formContainer { padding: 28px 20px; }
.submission-page #pagePrevBtn { min-width: 98px; }
.builder-page #headerSection h2 { font-size: 34px; }
.submission-page #headerSection h1 { font-size: 38px; }
.studio-kicker { margin-bottom: 12px; font-size: 10px !important; }
}
@media (prefers-reduced-motion: reduce) {
.builder-page #headerSection,
.submission-page #headerSection,
.submission-page #mainHeader,
.builder-page .stagger-item,
.submission-page .stagger-item {
opacity: 1 !important;
transform: none !important;
}
.builder-page #palettePane > .glass,
.builder-page #settingsPane > .glass,
.builder-page #editorPane > .glass,
.builder-page #editorPane > #formContainer:not(.hidden) {
animation: none;
}
.builder-page #particleCanvas,
.submission-page #particleCanvas { display: none; }
.submission-page input[type="file"].has-file + div,
.submission-page input[type="file"][data-has-file="true"] + div {
animation: none !important;
}
.builder-page .fc-tile,
.builder-page .field-card,
.builder-page .btn-primary,
.submission-page #submitBtn,
.submission-page #pagePrevBtn { transition-duration: .01ms; }
.submission-page .form-page-step::after,
.submission-page .form-page-active,
.submission-page .numeric-display { transition-duration: .01ms !important; }
.submission-page .slider-rail-fill,
.submission-page .slider-thumb { transition-duration: .01ms !important; }
.submission-page .numeric-display.number-changing { transform: none; filter: none; }
}
+333
View File
@@ -0,0 +1,333 @@
/* Toast 容器 */
#toast-stage {
position: fixed;
top: 80px;
right: 24px;
width: 320px;
z-index: 9999;
pointer-events: none;
}
#toast-container {
position: relative;
width: 100%;
height: 400px;
perspective: 1200px;
transform-style: preserve-3d;
}
/* Toast 基础 */
.toast {
position: absolute;
top: 0;
left: 0;
right: 0;
padding: 18px 24px;
border-radius: 16px;
font-size: 14px;
font-weight: 500;
backdrop-filter: blur(20px) saturate(180%);
border: 1px solid rgba(255, 255, 255, 0.15);
display: flex;
align-items: center;
gap: 12px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
pointer-events: auto;
transform-origin: center top;
will-change: transform, opacity;
}
/* ========== 进入动画状态 ========== */
.toast.entering {
opacity: 0;
transform: translateX(-120px) translateZ(50px) rotateY(25deg);
transition: none;
}
.toast.entering.show {
opacity: 1;
transform: translateX(0) translateZ(0) rotateY(0);
transition:
transform 0.6s cubic-bezier(0.23, 1, 0.32, 1),
opacity 0.5s cubic-bezier(0.23, 1, 0.32, 1),
filter 0.4s ease;
}
/* ========== 堆叠层级系统 ========== */
.toast:nth-child(1) {
z-index: 5;
transform: translateZ(0) translateY(0) scale(1);
opacity: 1;
filter: brightness(1);
}
.toast:nth-child(2) {
z-index: 4;
transform: translateZ(-50px) translateY(24px) scale(0.94);
opacity: 0.9;
filter: brightness(0.97);
}
.toast:nth-child(3) {
z-index: 3;
transform: translateZ(-100px) translateY(48px) scale(0.88);
opacity: 0.75;
filter: brightness(0.94);
}
.toast:nth-child(4) {
z-index: 2;
transform: translateZ(-150px) translateY(72px) scale(0.82);
opacity: 0.6;
filter: brightness(0.91);
}
.toast:nth-child(5) {
z-index: 1;
transform: translateZ(-200px) translateY(96px) scale(0.76);
opacity: 0.45;
filter: brightness(0.88);
}
.toast:nth-child(n+6) {
display: none;
}
/* ========== 层级过渡 ========== */
.toast.shift-down {
transition:
transform 0.5s cubic-bezier(0.23, 1, 0.32, 1),
opacity 0.4s ease,
filter 0.4s ease;
}
/* ========== 悬停展开 ========== */
#toast-stage:hover .toast {
transition:
transform 0.5s cubic-bezier(0.23, 1, 0.32, 1),
opacity 0.4s ease,
filter 0.4s ease;
}
#toast-stage:hover .toast:nth-child(1) {
transform: translateZ(0) translateY(0) scale(1) !important;
opacity: 1 !important;
filter: brightness(1) !important;
}
#toast-stage:hover .toast:nth-child(2) {
transform: translateZ(0) translateY(80px) scale(1) !important;
opacity: 1 !important;
filter: brightness(1) !important;
}
#toast-stage:hover .toast:nth-child(3) {
transform: translateZ(0) translateY(160px) scale(1) !important;
opacity: 1 !important;
filter: brightness(1) !important;
}
#toast-stage:hover .toast:nth-child(4) {
transform: translateZ(0) translateY(240px) scale(1) !important;
opacity: 1 !important;
filter: brightness(1) !important;
}
#toast-stage:hover .toast:nth-child(5) {
transform: translateZ(0) translateY(320px) scale(1) !important;
opacity: 1 !important;
filter: brightness(1) !important;
}
/* ========== 退出动画 ========== */
.toast.exiting {
opacity: 0 !important;
transform: translateX(100px) translateZ(-100px) scale(0.8) rotateY(-15deg) !important;
transition:
transform 0.35s cubic-bezier(0.4, 0, 0.2, 1),
opacity 0.3s ease !important;
pointer-events: none;
}
#toast-stage:hover .toast.exiting {
opacity: 0 !important;
transform: translateX(80px) scale(0.9) !important;
transition:
transform 0.3s cubic-bezier(0.4, 0, 0.2, 1),
opacity 0.25s ease !important;
}
#toast-stage:hover .toast.exiting:nth-child(1) {
transform: translateX(80px) translateY(0) scale(0.9) !important;
}
#toast-stage:hover .toast.exiting:nth-child(2) {
transform: translateX(80px) translateY(80px) scale(0.9) !important;
}
#toast-stage:hover .toast.exiting:nth-child(3) {
transform: translateX(80px) translateY(160px) scale(0.9) !important;
}
#toast-stage:hover .toast.exiting:nth-child(4) {
transform: translateX(80px) translateY(240px) scale(0.9) !important;
}
#toast-stage:hover .toast.exiting:nth-child(5) {
transform: translateX(80px) translateY(320px) scale(0.9) !important;
}
/* ========== 补位动画 ========== */
.toast.reordering {
transition:
transform 0.5s cubic-bezier(0.23, 1, 0.32, 1),
opacity 0.4s ease,
filter 0.4s ease;
}
/* ========== 类型样式 ========== */
.toast.success {
background: rgba(240, 253, 244, 0.85);
color: #166534;
border-color: rgba(22, 163, 74, 0.2);
}
.toast.error {
background: rgba(254, 242, 242, 0.85);
color: #991b1b;
border-color: rgba(220, 38, 38, 0.2);
}
.toast.info {
background: rgba(239, 246, 255, 0.85);
color: #1e40af;
border-color: rgba(37, 99, 235, 0.2);
}
.toast.warning {
background: rgba(255, 251, 235, 0.85);
color: #92400e;
border-color: rgba(217, 119, 6, 0.2);
}
/* ========== 深色模式 ========== */
.dark .toast.success {
background: rgba(22, 163, 74, 0.15);
color: #86efac;
border-color: rgba(22, 163, 74, 0.25);
}
.dark .toast.error {
background: rgba(220, 38, 38, 0.15);
color: #fca5a5;
border-color: rgba(220, 38, 38, 0.25);
}
.dark .toast.info {
background: rgba(37, 99, 235, 0.15);
color: #93c5fd;
border-color: rgba(37, 99, 235, 0.25);
}
.dark .toast.warning {
background: rgba(217, 119, 6, 0.15);
color: #fcd34d;
border-color: rgba(217, 119, 6, 0.25);
}
/* ========== 手机端适配 ========== */
@media (max-width: 640px) {
#toast-stage {
top: auto;
bottom: 80px;
left: 50%;
right: auto;
transform: translateX(-50%);
width: calc(100% - 32px);
max-width: 400px;
padding-bottom: env(safe-area-inset-bottom, 0px);
}
#toast-container {
height: auto;
min-height: 80px;
perspective: none;
transform-style: flat;
display: flex;
flex-direction: column-reverse;
align-items: center;
gap: 8px;
}
.toast {
position: relative;
width: 100%;
max-width: 100%;
padding: 16px 20px;
border-radius: 16px;
font-size: 15px;
box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.15), 0 4px 12px rgba(0, 0, 0, 0.1);
min-height: 56px;
/* 默认最终状态 */
transform: translateY(0) scale(1);
opacity: 1;
}
/* 入场:从下方滑入(与出场方向相反,对称) */
.toast.entering {
transform: translateY(20px) scale(0.95);
opacity: 0;
transition: none;
}
.toast.entering.show {
transform: translateY(0) scale(1);
opacity: 1;
/* 与出场动画时间一致 */
transition:
transform 0.3s ease,
opacity 0.25s ease;
}
/* 只显示最新 */
.toast:nth-child(n+2) {
display: none;
}
.toast:nth-child(1) {
transform: translateY(0) scale(1);
opacity: 1;
z-index: 10;
}
/* 出场:向下滑出 + 缩小(与入场对称) */
.toast.exiting {
transform: translateY(20px) scale(0.95) !important;
opacity: 0 !important;
transition:
transform 0.3s ease,
opacity 0.25s ease !important;
}
.toast.swiping {
transition: none !important;
opacity: 0.8;
}
.dark .toast {
box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.3), 0 4px 12px rgba(0, 0, 0, 0.2);
}
}
@media (max-width: 380px) {
#toast-stage {
width: calc(100% - 24px);
bottom: 70px;
}
.toast {
padding: 14px 16px;
font-size: 14px;
min-height: 52px;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 731 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 607 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 592 KiB

+107
View File
@@ -0,0 +1,107 @@
/* ============================================================
common.js — 全站公共脚本
包含: 主题初始化、滚动进度条、退出登录、GSAP 入场动画、
formatBytes 工具函数
============================================================ */
/* ── 1. 主题初始化 & 切换(优先读 localStorage,否则跟随系统)── */
(function initTheme() {
const root = document.documentElement;
const systemDark = window.matchMedia('(prefers-color-scheme: dark)');
function applyTheme(isDark) {
root.classList.toggle('dark', isDark);
root.classList.toggle('light', !isDark);
// 同步主题图标(如果页面有 #themeIcon)
const icon = document.getElementById('themeIcon');
if (icon) {
icon.innerHTML = isDark
? '<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>' /* 月亮 */
: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/>'; /* 太阳 */
}
}
// 首次加载:localStorage > 系统偏好
const saved = localStorage.getItem('theme');
if (saved === 'dark' || saved === 'light') {
applyTheme(saved === 'dark');
} else {
applyTheme(systemDark.matches);
}
// 系统切换时,仅在没有手动记忆时跟随
systemDark.addEventListener('change', function (e) {
if (!localStorage.getItem('theme')) {
applyTheme(e.matches);
}
});
})();
/* ── 全局主题切换(供所有页面 toggleTheme() 调用)──────────── */
function toggleTheme() {
const isDark = document.documentElement.classList.contains('dark');
const next = !isDark;
document.documentElement.classList.toggle('dark', next);
document.documentElement.classList.toggle('light', !next);
localStorage.setItem('theme', next ? 'dark' : 'light');
// 同步图标
const icon = document.getElementById('themeIcon');
if (icon) {
icon.innerHTML = next
? '<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>'
: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/>';
}
}
/* ── 2. 滚动进度条(页面需要有 id="scrollProgress" 元素)──── */
window.addEventListener('scroll', function () {
const el = document.getElementById('scrollProgress');
if (!el) return;
const winScroll = document.body.scrollTop || document.documentElement.scrollTop;
const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
const scrolled = height > 0 ? (winScroll / height) * 100 : 0;
el.style.width = scrolled + '%';
});
/* ── 3. 退出登录 ──────────────────────────────────────────── */
async function logout() {
try {
await fetch('/api/logout', { method: 'POST' });
window.location.href = '/login';
} catch (err) {
if (typeof showToast === 'function') {
showToast('退出失败', 'error');
}
}
}
/* ── 4. GSAP 入场动画(页面需要有 id="headerSection" 和
.stagger-item 元素,且 GSAP 已加载)──────────────── */
function initPageAnimation() {
if (typeof gsap === 'undefined') return;
const header = document.getElementById('headerSection');
if (header) {
gsap.to(header, { opacity: 1, y: 0, duration: 0.8, ease: 'power2.out', delay: 0.1 });
}
const items = document.querySelectorAll('.stagger-item');
if (items.length > 0) {
gsap.to(items, { opacity: 1, y: 0, duration: 0.6, stagger: 0.1, ease: 'power2.out', delay: 0.3 });
}
}
/* ── 5. formatBytes — 字节数格式化工具 ───────────────────── */
function formatBytes(bytes, decimals) {
decimals = decimals !== undefined ? decimals : 2;
if (!bytes || bytes === 0) return '0 B';
var k = 1024;
var sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
i = Math.min(i, sizes.length - 1);
return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i];
}
/* ── 6. Tailwind 统一配置(在 tailwind.config 未定义时注入)─ */
/* 注意:各页面仍需自行在 tailwind.config 中声明 darkMode: 'class'
本函数仅作为兼容性保底,不替代页面内的 tailwind.config 声明 */
File diff suppressed because one or more lines are too long
+150
View File
@@ -0,0 +1,150 @@
/**
* FormComponents — 表单字段组件库(create/edit 左栏调色板)
*
* 用法:
* <script src="/static/js/form-components.js"></script>
* <script>
* FormComponents.renderPalette(
* document.getElementById('componentPalette'),
* (type) => addField({ type }) // 点击组件时回调
* );
* </script>
*
* 组件瓦片可点击添加,也可拖拽:dragstart 写入
* dataTransfer['application/x-field-type'] = type,
* 由 create/edit 页面字段列表的 drop 事件读取(拖到指定位置插入)。
*/
(function () {
'use strict';
if (window.FormComponents) return;
const ICONS = {
text: '<path d="M4 7V5h16v2M12 5v14M9 19h6"/>',
textarea: '<path d="M4 6h16M4 10h16M4 14h10"/><rect x="3" y="3" width="18" height="18" rx="3" fill="none"/>',
select: '<path d="M3 6h18M3 12h18M3 18h10"/><path d="M16 15l2 2 4-4"/>',
radio: '<circle cx="12" cy="12" r="9" fill="none"/><circle cx="12" cy="12" r="4"/>',
checkbox: '<rect x="3" y="3" width="18" height="18" rx="4" fill="none"/><path d="M8 12l3 3 5-6"/>',
rating: '<path d="M12 3l2.7 5.5 6 .9-4.3 4.2 1 6-5.4-2.8L6.6 19.6l1-6L3.3 9.4l6-.9L12 3z"/>',
number: '<path d="M6 5v14M18 5v14M6 12h12"/>',
date: '<rect x="3" y="5" width="18" height="16" rx="2" fill="none"/><path d="M3 10h18M8 3v4M16 3v4"/>',
time: '<circle cx="12" cy="12" r="9" fill="none"/><path d="M12 7v5l3 3"/>',
file: '<path d="M12 16V4M12 4L8 8M12 4l4 4M4 17v1a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-1"/>',
slider: '<path d="M3 12h18"/><circle cx="9" cy="12" r="3" fill="none"/><circle cx="17" cy="12" r="3" fill="none"/>',
page_break: '<rect x="3" y="4" width="18" height="6" rx="1.5"/><rect x="3" y="14" width="18" height="6" rx="1.5"/><path d="M12 10v4"/>',
};
const CATALOG = [
{ type: 'text', label: '文本', hint: '短文本输入' },
{ type: 'textarea', label: '多行文本', hint: '长文本输入' },
{ type: 'number', label: '数字', hint: '数字输入' },
{ type: 'select', label: '下拉框', hint: '单选下拉' },
{ type: 'radio', label: '单选', hint: '多个选项选一个' },
{ type: 'checkbox', label: '多选', hint: '多个选项可多选' },
{ type: 'date', label: '日期', hint: '日期选择' },
{ type: 'time', label: '时间', hint: '时间选择' },
{ type: 'rating', label: '评分', hint: '星级评分' },
{ type: 'slider', label: '滑块', hint: '范围取值' },
{ type: 'file', label: '文件上传', hint: '附件收集' },
{ type: 'page_break', label: '分页', hint: '从这里开始新的一页' },
];
const CSS = `
.fc-palette { display: grid; grid-template-columns: repeat(4, minmax(0,1fr)); gap: 8px; }
@media (max-width: 480px) { .fc-palette { grid-template-columns: repeat(3, minmax(0,1fr)); } }
.fc-tile {
display: flex; flex-direction: column; align-items: center; gap: 6px;
padding: 12px 6px 10px; border-radius: 12px; cursor: grab;
border: 1px solid var(--border-color);
background: transparent;
width: 100%; color: var(--text-secondary); font: inherit; text-align: left;
transition: border-color .18s ease, background-color .18s ease, transform .18s ease;
user-select: none; -webkit-user-select: none;
}
.fc-tile:focus-visible { outline: 2px solid var(--border-focus); outline-offset: 2px; }
.fc-tile:hover {
border-color: var(--accent-bg, #6366f1);
background: color-mix(in srgb, var(--accent-bg, #6366f1) 8%, transparent);
transform: translateY(-1px);
}
.fc-tile:active { cursor: grabbing; }
.fc-tile svg { width: 20px; height: 20px; stroke: var(--text-secondary); fill: none;
stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
.fc-tile:hover svg { stroke: var(--accent-bg, #6366f1); }
.fc-tile .fc-label { font-size: 11px; color: var(--text-secondary); white-space: nowrap; }
`;
function tileHtml(item) {
return `
<button type="button" class="fc-tile" draggable="true" data-field-type="${item.type}" title="${item.hint}"
aria-label="${item.type === 'page_break' ? '插入分页控件' : `添加${item.label}字段`}">
<svg viewBox="0 0 24 24">${ICONS[item.type] || ICONS.text}</svg>
<span class="fc-label">${item.label}</span>
</button>
`;
}
window.FormComponents = {
CATALOG,
createPageBreakCard(fieldId, title, onRemove) {
const card = document.createElement('div');
card.className = 'field-card page-break-card';
card.id = fieldId;
card.innerHTML = `
<div class="flex items-center justify-between gap-3 mb-3">
<div class="flex items-center gap-2">
<button type="button" class="drag-handle" title="拖拽排序" aria-label="拖动以调整分页顺序">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="9" cy="5" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="9" cy="19" r="1"/>
<circle cx="15" cy="5" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="15" cy="19" r="1"/>
</svg>
</button>
<span class="page-break-number page-break-label">分页</span>
</div>
<div class="field-card-actions flex items-center justify-end gap-2">
<button type="button" class="page-break-remove btn-danger w-7 h-7 rounded-full flex items-center justify-center text-xs" aria-label="删除分页控件">×</button>
</div>
</div>
<label class="block text-xs mb-2" style="color:var(--text-secondary)">下一页标题(可选)</label>
<input type="text" class="field-edit-input page-title w-full" placeholder="例如:上传材料">
<p class="text-xs mt-3" style="color:var(--text-muted)">填写者完成当前页后,点击“下一页”进入这里。</p>
<input type="hidden" class="field-type" value="page_break">
`;
const input = card.querySelector('.page-title');
input.id = `${fieldId}_page_title`;
input.value = title || '';
card.querySelector('label').htmlFor = input.id;
card.querySelector('.page-break-remove').addEventListener('click', onRemove);
return card;
},
/* 渲染组件调色板。onAdd(type):点击组件回调;拖拽落位由字段列表处理。 */
renderPalette(container, onAdd) {
if (!container) return;
if (!document.getElementById('fc-palette-style')) {
const style = document.createElement('style');
style.id = 'fc-palette-style';
style.textContent = CSS;
document.head.appendChild(style);
}
container.classList.add('fc-palette');
container.innerHTML = CATALOG.map(tileHtml).join('');
container.querySelectorAll('.fc-tile').forEach(tile => {
const type = tile.dataset.fieldType;
tile.addEventListener('click', () => { if (onAdd) onAdd(type); });
tile.addEventListener('dragstart', (e) => {
e.dataTransfer.setData('application/x-field-type', type);
e.dataTransfer.setData('text/plain', 'fc:' + type);
e.dataTransfer.effectAllowed = 'copy';
tile.classList.add('fc-dragging');
});
tile.addEventListener('dragend', () => tile.classList.remove('fc-dragging'));
});
},
};
})();
+101
View File
@@ -0,0 +1,101 @@
/* URL question numbers follow the displayed order; page breaks have no number. */
(function () {
'use strict';
const supported = new Set(['text', 'textarea', 'number', 'select', 'radio', 'checkbox', 'date', 'time', 'rating', 'slider']);
function parse(fields, search) {
const questions = fields.filter(field => field.type !== 'page_break');
const params = new URLSearchParams(search);
const locked = new Map();
const hidden = new Set();
const invalid = new Set();
for (const key of new Set(params.keys())) {
if (!/^[1-9]\d*$/.test(key)) continue;
const field = questions[Number(key) - 1];
if (!field || !supported.has(field.type)) continue;
const values = params.getAll(key);
let value = values[values.length - 1];
if (['select', 'radio', 'checkbox'].includes(field.type)) {
const options = (field.options || '').split(',').map(option => option.trim()).filter(Boolean);
const selected = field.type === 'checkbox'
? [...new Set(values.flatMap(item => item.split(',')).map(item => item.trim()).filter(Boolean))]
: [value];
if ((field.required && !selected.length) || selected.some(item => !options.includes(item))) {
invalid.add(field.name);
continue;
}
value = field.type === 'checkbox' ? selected : value;
} else if (field.required && !value.trim()) {
invalid.add(field.name);
continue;
}
locked.set(field.name, { field, value });
}
for (const item of params.getAll('hidden').flatMap(value => value.split(','))) {
const number = item.trim();
if (!/^[1-9]\d*$/.test(number)) continue;
const field = questions[Number(number) - 1];
if (field) hidden.add(field.name);
}
return { locked, hidden, invalid };
}
function apply(preset, getWrapper, hooks = {}) {
const changed = [];
for (const [name, entry] of preset.locked) {
const { field } = entry;
const wrapper = getWrapper(field);
if (!wrapper) continue;
const controls = [...wrapper.querySelectorAll('input, select, textarea')];
const input = controls[0];
let value = entry.value;
if (hooks.normalize) value = hooks.normalize(field, value);
let valid = input && value !== null;
if (valid && ['radio', 'checkbox'].includes(field.type)) {
for (const control of controls) {
control.checked = field.type === 'checkbox' ? value.includes(control.value) : control.value === value;
}
} else if (valid) {
const previous = input.value;
input.value = value;
valid = String(value) === input.value && input.validity.valid;
if (field.type === 'rating') {
const max = Number(field.ratingMax) === 10 ? 10 : 5;
valid = value !== '' && Number.isInteger(Number(value)) && Number(value) >= (field.required ? 1 : 0) && Number(value) <= max;
}
if (!valid) input.value = previous;
}
if (!valid) {
preset.locked.delete(name);
preset.invalid.add(name);
continue;
}
entry.value = value;
wrapper.classList.add('url-prefilled');
for (const control of controls) control.disabled = true;
// Ratings are custom keyboard/pointer controls rather than native inputs.
const rating = wrapper.querySelector('.rating-stars');
if (rating) {
rating.setAttribute('aria-disabled', 'true');
rating.tabIndex = -1;
hooks.rating?.(rating, value);
}
changed.push(...controls);
}
for (const name of preset.hidden) {
const wrapper = getWrapper({ name });
if (!wrapper) continue;
wrapper.hidden = true;
wrapper.dataset.urlHidden = 'true';
for (const control of wrapper.querySelectorAll('input, select, textarea')) control.required = false;
}
// Apply all values before refreshing dependencies, identity and choice visuals.
for (const control of changed) {
if (control.type === 'radio' && !control.checked) continue;
control.dispatchEvent(new Event('input', { bubbles: true }));
control.dispatchEvent(new Event('change', { bubbles: true }));
}
}
window.FormLinkPreset = { parse, apply };
})();
+709
View File
@@ -0,0 +1,709 @@
/**
* FormPreview v4 — 画布即编辑器(create/edit 右栏)
*
* 预览即真实填写页,且可直接在画布上编辑:
* - 字段标题:点击直接改(同步到字段配置)
* - 占位符:直接往输入框里打字,失焦后转为占位符
* - 选项(单选/多选/下拉):就地增删改
* - 字段工具条(悬停/选中出现):必填开关、条件显示、删除;左上角手柄拖拽排序
* - 评分满分 / 滑块范围 / 文件格式:字段下方就地数值配置
*
* 数据仍存放在页面隐藏的 .field-card 编辑卡中(saveForm/populateForm 不变),
* 画布与卡片双向同步;顺序以画布为权威(orderedFieldCards)。
*
* 用法:
* FormPreview.init({
* root, getMeta,
* hooks: {
* onDelete: (fieldId) => {}, // 画布删除字段
* onCreateAt: (type, beforeId) => newId, // 调色板拖落创建,返回新卡 id
* onConditional: (fieldId) => {}, // 打开条件显示配置
* },
* });
* FormPreview.refresh(); / setSelected(id|null); / orderedFieldCards();
*/
(function () {
'use strict';
if (window.FormPreview) return;
let root = null;
let getMeta = null;
let hooks = null;
let editable = false;
let selectedId = null;
let fieldOrder = null; // 画布权威字段顺序(id 数组)
let debounceTimer = null;
let dropLine = null;
function esc(s) {
return String(s == null ? '' : s)
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
/* ---------- 数据层:隐藏 field-card ↔ 画布 ---------- */
function rawFields() {
const fields = [];
document.querySelectorAll('.field-card').forEach(card => {
const nameEl = card.querySelector('.field-name');
const typeEl = card.querySelector('.field-type');
if (!nameEl || !typeEl) return;
const type = typeEl.value;
const field = {
id: card.id,
type: type,
name: nameEl.value.trim() || '未命名字段',
placeholder: (card.querySelector('.field-placeholder') || {}).value || '',
required: !!(card.querySelector('.field-required') || { checked: true }).checked,
conditional: !!(card.querySelector('.field-show-when-field') || { value: '' }).value,
};
if (['select', 'radio', 'checkbox'].includes(type)) {
let options = (card.querySelector('.field-options-input') || {}).value || '';
if (!options) {
const optionInputs = card.querySelectorAll('.option-input');
options = Array.from(optionInputs).map(i => i.value.trim()).filter(v => v).join(',');
}
field.options = options;
}
if (type === 'file') {
let exts = (card.querySelector('.field-file-exts-combined') || {}).value || '';
if (!exts) exts = (card.querySelector('.field-file-exts-input') || {}).value || '';
field.exts = String(exts).split(/[,,\s]+/).map(s => s.replace(/^\./, '').trim())
.filter(v => v && v !== '全部');
}
if (type === 'rating') {
const rm = card.querySelector('.field-rating-max');
field.ratingMax = Number(rm && rm.value) === 10 ? 10 : 5;
}
if (type === 'slider') {
const g = cls => (card.querySelector(cls) || {}).value;
field.sliderMin = g('.field-slider-min') || '0';
field.sliderMax = g('.field-slider-max') || '100';
field.sliderStep = g('.field-slider-step') || '1';
}
fields.push(field);
});
return fields;
}
function collectFields() {
const raw = rawFields();
if (!fieldOrder) return raw;
const byId = {};
raw.forEach(f => { byId[f.id] = f; });
const ordered = fieldOrder.map(id => byId[id]).filter(Boolean);
raw.forEach(f => { if (!fieldOrder.includes(f.id)) ordered.push(f); });
return ordered;
}
function reconcileOrder() {
const ids = rawFields().map(f => f.id);
if (!fieldOrder) { fieldOrder = ids.slice(); return; }
const kept = fieldOrder.filter(id => ids.includes(id));
ids.forEach(id => { if (!kept.includes(id)) kept.push(id); });
fieldOrder = kept;
}
function insertIntoOrder(id, beforeId) {
reconcileOrder();
fieldOrder = fieldOrder.filter(x => x !== id);
const idx = beforeId ? fieldOrder.indexOf(beforeId) : -1;
if (idx >= 0) fieldOrder.splice(idx, 0, id);
else fieldOrder.push(id);
}
/* 写回隐藏编辑卡 */
function writeCard(id, fn) {
const card = document.getElementById(id);
if (card) fn(card);
}
function setName(id, v) { writeCard(id, c => { c.querySelector('.field-name').value = v; }); }
function setPlaceholder(id, v) { writeCard(id, c => { const el = c.querySelector('.field-placeholder'); if (el) el.value = v; }); }
function setRequired(id, v) { writeCard(id, c => { const el = c.querySelector('.field-required'); if (el) el.checked = v; }); }
function setOptions(id, v) { writeCard(id, c => { const el = c.querySelector('.field-options-input'); if (el) el.value = v; }); }
function setExts(id, v) { writeCard(id, c => { const el = c.querySelector('.field-file-exts-combined'); if (el) el.value = v; }); }
/* ---------- 渲染层 ---------- */
const INPUT_CLS = 'w-full bg-transparent border-b py-3 text-sm';
function renderControl(field, meta) {
switch (field.type) {
case 'select': {
const opts = (field.options || '').split(',').map(o => o.trim()).filter(Boolean);
return `
<select disabled class="${INPUT_CLS} appearance-none" style="color: var(--text-primary); border-bottom: 1px solid var(--border-color);">
<option>请选择...</option>
${opts.map(o => `<option>${esc(o)}</option>`).join('')}
</select>
${optionsEditor(field)}`;
}
case 'textarea':
return `<textarea data-fp-ph rows="3" class="w-full border rounded-xl p-4 resize-none text-sm leading-relaxed" style="background: var(--input-bg, var(--bg-primary)); color: var(--text-primary); border-color: var(--border-color);" placeholder="${esc(field.placeholder || '点击输入占位提示...')}">${esc(field.__typed || '')}</textarea>`;
case 'radio':
case 'checkbox':
return optionsAsPreview(field);
case 'file': {
const exts = field.exts && field.exts.length ? field.exts.join(', ') : '';
const sizeHint = meta.maxSizeMB ? `单个不超过 ${meta.maxSizeMB}MB` : '';
return `<div class="border-2 border-dashed rounded-xl p-6 text-center" style="border-color: var(--border-color); pointer-events: none;">
<div class="mb-2" style="color: var(--text-muted);">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="mx-auto">
<path d="M12 16V4M12 4L8 8M12 4L16 8M4 17V18C4 19.1046 4.89543 20 6 20H18C19.1046 20 20 19.1046 20 18V17"/>
</svg>
</div>
<p class="text-xs" style="color: var(--text-secondary);">点击或拖拽上传文件</p>
<p class="text-[10px] mt-1" style="color: var(--text-muted);">支持格式: ${esc(exts || '所有文件')}${sizeHint ? ' · ' + esc(sizeHint) : ''}</p>
</div>
<div class="fp-config-row">
<span class="fp-config-lb">格式</span>
<input type="text" data-fp-exts class="fp-config-input" value="${esc(exts)}" placeholder="如 jpg, png, pdf(留空不限制)">
</div>`;
}
case 'rating': {
const max = Number(field.ratingMax) === 10 ? 10 : 5;
return `<div class="flex items-center gap-4 flex-wrap">
<div class="flex gap-1.5" style="pointer-events: none;">
${Array.from({ length: 5 }, () => `<svg width="26" height="26" viewBox="0 0 24 24" fill="none" style="color: var(--text-muted); opacity:.55;"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>`).join('')}
</div>
</div>
<div class="fp-config-row">
<span class="fp-config-lb">满分</span>
<select data-fp-rmax class="fp-config-input" style="max-width:100px;">
<option value="5" ${max === 5 ? 'selected' : ''}>5 分</option>
<option value="10" ${max === 10 ? 'selected' : ''}>10 分</option>
</select>
<span class="text-xs" style="color: var(--text-muted);">分(点星评分)</span>
</div>`;
}
case 'slider': {
const min = parseFloat(field.sliderMin) || 0;
const max = parseFloat(field.sliderMax) || 100;
const mid = (min + max) / 2;
const pct = (mid - min) / (max - min || 1) * 50;
return `<div class="flex items-center gap-4" style="pointer-events: none;">
<div class="flex-1 h-1.5 rounded-full relative" style="background: var(--border-color);">
<div class="absolute h-1.5 rounded-full left-0" style="width:${pct}%; background: var(--accent-bg, #6366f1);"></div>
<div class="absolute w-4 h-4 rounded-full -top-[5px] shadow" style="left:calc(${pct}% - 8px); background: var(--accent-bg, #6366f1);"></div>
</div>
</div>
<div class="fp-config-row">
<span class="fp-config-lb">范围</span>
<input type="number" data-fp-smin class="fp-config-input" style="max-width:76px;" value="${min}">
<span class="text-xs" style="color: var(--text-muted);">至</span>
<input type="number" data-fp-smax class="fp-config-input" style="max-width:76px;" value="${max}">
<span class="text-xs" style="color: var(--text-muted);">步长</span>
<input type="number" data-fp-sstep class="fp-config-input" style="max-width:76px;" value="${esc(field.sliderStep || '1')}">
</div>`;
}
case 'date':
return `<input type="date" disabled class="${INPUT_CLS}" style="color: var(--text-primary); border-bottom: 1px solid var(--border-color);">`;
case 'time':
return `<input type="time" disabled class="${INPUT_CLS}" style="color: var(--text-primary); border-bottom: 1px solid var(--border-color);">`;
default:
// 文本/数字:直接打字编辑占位符
return `<input type="text" data-fp-ph inputmode="${field.type === 'number' ? 'numeric' : 'text'}" class="${INPUT_CLS}" style="color: var(--text-primary); border-bottom: 1px solid var(--border-color);" placeholder="${esc(field.placeholder || '点击输入占位提示...')}">`;
}
}
/* 选项就地编辑:radio/checkbox 直接以选项预览形态呈现 */
function optionsAsPreview(field) {
const opts = (field.options || '').split(',').map(o => o.trim()).filter(Boolean);
const row = (o) => {
const mark = field.type === 'checkbox'
? `<span class="fp-opt-mark" style="border-radius:6px;"></span>`
: `<span class="fp-opt-mark" style="border-radius:50%;"></span>`;
return `<label class="inline-flex items-center gap-2.5 text-sm fp-opt" style="color: var(--text-primary); position:relative; padding:8px; margin:-8px; border-radius:8px;">
${mark}<span class="fp-opt-text" contenteditable="true" data-fp-opt>${esc(o)}</span>
<button type="button" class="fp-opt-del" data-fp-opt-del title="删除选项">
<svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.4" stroke-linecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
</button>
</label>`;
};
return `<div class="flex flex-wrap gap-3 mt-1" data-fp-opts>${opts.map(row).join('') || '<span class="text-xs" style="color: var(--text-muted);">暂无选项</span>'}
<button type="button" class="fp-opt-add" data-fp-opt-add>+ 选项</button>
</div>`;
}
/* 下拉的选项编辑行 */
function optionsEditor(field) {
const opts = (field.options || '').split(',').map(o => o.trim()).filter(Boolean);
return `<div class="flex flex-wrap gap-2 mt-3" data-fp-opts>
${opts.map(o => `<span class="fp-opt-chip">
<span class="fp-opt-text" contenteditable="true" data-fp-opt>${esc(o)}</span>
<button type="button" class="fp-opt-del" data-fp-opt-del title="删除选项">
<svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.4" stroke-linecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
</button>
</span>`).join('')}
<button type="button" class="fp-opt-add" data-fp-opt-add>+ 选项</button>
</div>`;
}
function renderField(field, meta, index) {
const onCanvas = editable && !!field.id;
let chrome = '';
if (onCanvas) {
chrome = `
<span class="fp-num">${index + 1}</span>
<span class="fp-handle" title="拖拽排序" draggable="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="9" cy="5" r="1.6"/><circle cx="15" cy="5" r="1.6"/><circle cx="9" cy="12" r="1.6"/><circle cx="15" cy="12" r="1.6"/><circle cx="9" cy="19" r="1.6"/><circle cx="15" cy="19" r="1.6"/>
</svg>
</span>
<div class="fp-toolbar">
<button type="button" class="fp-chip ${field.required ? 'fp-chip-on' : ''}" data-fp-act="required" title="切换必填">✱ 必填</button>
<button type="button" class="fp-chip ${field.conditional ? 'fp-chip-on' : ''}" data-fp-act="conditional" title="条件显示">◇ 条件</button>
<button type="button" class="fp-chip fp-chip-danger" data-fp-act="delete" title="删除字段">✕</button>
</div>`;
}
const selCls = onCanvas && field.id === selectedId ? ' fp-selected' : '';
const optionalTag = (!field.required) ? ' <span class="fp-tag-optional">(选填)</span>' : '';
return `<div class="fp-field${selCls}" ${onCanvas ? `data-fp-id="${field.id}"` : ''}>
${chrome}
<div class="fp-label-line">
<label class="block text-[15px] font-semibold tracking-[0.12em] uppercase mb-2" style="color: var(--text-primary);">
<span class="fp-label-text" ${onCanvas ? 'contenteditable="true" data-fp-name' : ''}>${esc(field.name)}</span>${optionalTag}
</label>
</div>
<div class="fp-control">${renderControl(field, meta)}</div>
</div>`;
}
function renderProgress(meta) {
if (!meta.showProgress) return '';
const body = meta.anonymous
? `<p class="text-sm" style="color: var(--text-secondary);">已收集 <span style="color: var(--text-primary); font-weight:600;">0</span> 份提交</p>`
: `<p class="text-sm" style="color: var(--text-secondary);">等待大家提交…</p>`;
return `<div class="rounded-2xl p-4 mb-6" style="background: var(--bg-primary, transparent); border: 1px solid var(--border-color);">
<p class="text-[11px] font-semibold tracking-[0.2em] uppercase mb-2" style="color: var(--text-muted);">完成情况</p>
<div class="h-1.5 rounded-full overflow-hidden mb-2" style="background: var(--border-color);">
<div style="width:0%; height:100%; background: var(--accent-bg, #6366f1);"></div>
</div>
${body}
</div>`;
}
function render(meta) {
if (!root) return;
const fields = collectFields();
const rosterFields = [];
if (!meta.anonymous) {
const digits = meta.verifyDigits || '2';
rosterFields.push({ id: null, name: 'tail', type: 'number', required: true, placeholder: `学号后${digits}位` });
rosterFields.push({ id: null, name: 'name', type: 'text', required: true, placeholder: '请输入学号自动获取姓名' });
}
const onceHint = meta.once
? `<p class="text-xs text-center mb-3" style="color: var(--warning-text, #b45309);">⚠ 此表单仅允许提交一次,提交后不能再修改,请确认填写无误后再提交。</p>`
: '';
let fieldIndex = 0;
const fieldHtml = (list) => list.map(f => renderField(f, meta, f.id ? fieldIndex++ : 0)).join('');
root.innerHTML = `
<div class="fp-head px-7 pt-7 pb-5">
<h1 class="text-2xl font-bold tracking-wide" style="color: var(--text-primary);">${esc(meta.title || '未命名表单')}</h1>
<p class="text-xs mt-2" style="color: var(--text-muted);">请填写以下信息完成提交。所有字段经过加密处理。</p>
</div>
<div class="fp-body px-7 pb-8">
${(meta.subtitle || meta.announcementText) ? `
<div class="rounded-2xl p-4 mb-6" style="background: var(--bg-primary, transparent); border: 1px solid var(--border-color);">
${meta.subtitle ? `<p class="text-sm font-semibold mb-1" style="color: var(--text-primary);">${esc(meta.subtitle)}</p>` : ''}
${meta.announcementText ? `<p class="text-xs leading-relaxed whitespace-pre-wrap" style="color: var(--text-secondary);">${esc(meta.announcementText)}</p>` : ''}
</div>` : ''}
${renderProgress(meta)}
<div class="space-y-7 fp-fields">
${fieldHtml(rosterFields)}
${fieldHtml(fields)}
${fields.length === 0 && meta.anonymous ? '<p class="text-xs text-center py-6" style="color: var(--text-muted);">从左侧组件库添加字段,或直接把组件拖到这里</p>' : ''}
</div>
<div class="pt-8 fp-tail">
${onceHint}
<button type="button" disabled class="w-full py-4 px-8 rounded-full font-medium text-sm opacity-90" style="background: var(--accent-bg); color: var(--accent-text);">
提交表单
</button>
</div>
</div>
`;
if (editable) wireCanvas();
}
/* ---------- 画布交互 ---------- */
const CANVAS_CSS = `
.fp-field {
position: relative; border: 1px dashed transparent; border-radius: 14px;
padding: 14px 14px 10px; margin: -1px;
transition: border-color .15s ease, background-color .15s ease;
}
.fp-field:hover { border-color: var(--border-color); }
.fp-field.fp-selected {
border-color: var(--accent-bg, #6366f1);
background: color-mix(in srgb, var(--accent-bg, #6366f1) 6%, transparent);
}
.fp-field .fp-handle {
position: absolute; left: 8px; top: 50%; transform: translateY(-50%);
width: 32px; height: 32px; border-radius: 10px;
display: flex; align-items: center; justify-content: center;
background: var(--bg-primary, #fff); border: 1px solid var(--border-color);
color: var(--text-secondary); box-shadow: 0 2px 10px rgba(0,0,0,.14);
opacity: 0; cursor: grab; transition: opacity .15s ease, border-color .15s ease, color .15s ease;
z-index: 3;
}
.fp-handle svg { width: 18px; height: 18px; }
.fp-handle:hover { border-color: var(--accent-bg, #6366f1); color: var(--accent-bg, #6366f1); }
.fp-field:hover .fp-handle, .fp-field.fp-selected .fp-handle { opacity: 1; }
/* 手柄出现时内容右移让位,不遮标题 */
.fp-field { padding-left: 14px; }
.fp-field:hover, .fp-field.fp-selected { padding-left: 50px; }
.fp-field .fp-num {
position: absolute; right: 12px; top: 10px; font-size: 10px; font-weight: 600;
color: var(--text-muted); opacity: 0; transition: opacity .15s ease;
min-width: 18px; text-align: center;
}
.fp-field:hover .fp-num, .fp-field.fp-selected .fp-num { opacity: .7; }
.fp-field.fp-dragging { opacity: .45; }
.fp-toolbar {
position: absolute; right: 8px; top: -12px; display: flex; gap: 4px;
opacity: 0; transition: opacity .15s ease; z-index: 3;
}
.fp-field:hover .fp-toolbar, .fp-field.fp-selected .fp-toolbar { opacity: 1; }
.fp-chip {
font-size: 10px; padding: 3px 8px; border-radius: 999px; cursor: pointer;
border: 1px solid var(--border-color); background: var(--bg-primary, #fff);
color: var(--text-secondary); line-height: 1.2;
box-shadow: 0 1px 6px rgba(0,0,0,.08);
transition: all .15s ease;
}
.fp-chip:hover { border-color: var(--accent-bg, #6366f1); color: var(--accent-bg, #6366f1); }
.fp-chip-on { background: var(--accent-bg, #6366f1); border-color: var(--accent-bg, #6366f1); color: #fff; }
.fp-chip-danger:hover { border-color: #dc2626; color: #dc2626; }
.fp-label-text { outline: none; border-bottom: 1px dashed transparent; min-width: 30px; display: inline-block; }
.fp-field:hover .fp-label-text, .fp-field.fp-selected .fp-label-text { border-bottom-color: var(--border-color); }
.fp-label-text:focus { border-bottom-color: var(--accent-bg, #6366f1); }
.fp-label-text:empty::before { content: '未命名字段'; color: var(--text-muted); }
.fp-tag-optional { color: var(--text-muted); font-weight: 400; }
.fp-config-row { display: flex; align-items: center; gap: 8px; margin-top: 10px; }
.fp-config-lb { font-size: 11px; color: var(--text-muted); flex-shrink: 0; }
.fp-config-input {
font-size: 12px; padding: 4px 8px; border-radius: 8px; outline: none;
border: 1px solid var(--border-color); background: var(--input-bg, transparent);
color: var(--text-primary); width: 220px; max-width: 60%;
}
.fp-config-input:focus { border-color: var(--accent-bg, #6366f1); }
.fp-opt { position: relative; }
.fp-opt-mark { width: 22px; height: 22px; border: 2px solid var(--border-color); flex-shrink: 0;
display: inline-flex; align-items: center; justify-content: center; }
.fp-opt-text { outline: none; border-bottom: 1px dashed transparent; min-width: 16px; }
.fp-opt-text:focus { border-bottom-color: var(--accent-bg, #6366f1); }
.fp-opt .fp-opt-del {
position: absolute; right: -4px; top: -2px; width: 16px; height: 16px; border-radius: 50%;
background: rgba(220,38,38,.9); color: #fff; display: none;
align-items: center; justify-content: center; cursor: pointer;
}
.fp-opt:hover .fp-opt-del { display: flex; }
.fp-opt-chip {
display: inline-flex; align-items: center; gap: 5px; font-size: 12px;
padding: 4px 8px; border-radius: 999px; border: 1px solid var(--border-color);
color: var(--text-primary); position: relative;
}
.fp-opt-chip .fp-opt-del {
width: 14px; height: 14px; border-radius: 50%; background: rgba(220,38,38,.9);
color: #fff; display: none; align-items: center; justify-content: center; cursor: pointer;
}
.fp-opt-chip:hover .fp-opt-del { display: flex; }
.fp-opt-add {
align-self: center; font-size: 11px; padding: 4px 10px; border-radius: 999px; cursor: pointer;
border: 1px dashed var(--border-color); color: var(--text-muted); background: transparent;
transition: all .15s ease;
}
.fp-opt-add:hover { border-color: var(--accent-bg, #6366f1); color: var(--accent-bg, #6366f1); }
.fp-field.fp-drop-target { border-color: var(--accent-bg, #6366f1); }
.fp-drop-line {
height: 3px; border-radius: 3px; background: var(--accent-bg, #6366f1);
box-shadow: 0 0 10px color-mix(in srgb, var(--accent-bg, #6366f1) 60%, transparent);
margin: 6px 0; position: relative;
}
.fp-drop-line::before {
content: ''; position: absolute; left: -5px; top: -3.5px; width: 10px; height: 10px;
border-radius: 50%; background: var(--accent-bg, #6366f1);
}
`;
function wireCanvas() {
if (root.__fpWired) return;
root.__fpWired = true;
/* 点击:工具条动作 / 选中 / 空白取消 */
root.addEventListener('click', (e) => {
const act = e.target.closest('[data-fp-act]');
if (act) {
const fieldEl = act.closest('.fp-field[data-fp-id]');
const id = fieldEl && fieldEl.dataset.fpId;
const action = act.dataset.fpAct;
if (action === 'delete') {
if (selectedId === id) setSelected(null);
if (hooks.onDelete) hooks.onDelete(id);
return;
}
if (action === 'required') {
const card = document.getElementById(id);
const cb = card && card.querySelector('.field-required');
const next = cb ? !cb.checked : false;
setRequired(id, next);
act.classList.toggle('fp-chip-on', next);
const tag = fieldEl.querySelector('.fp-tag-optional');
if (tag) tag.style.display = next ? 'none' : '';
return;
}
if (action === 'conditional') {
if (hooks.onConditional) hooks.onConditional(id);
return;
}
}
if (e.target.closest('.fp-drawer, .fp-toolbar, .fp-config-row, [data-fp-opts], [contenteditable]')) return;
const fieldEl = e.target.closest('.fp-field[data-fp-id]');
if (fieldEl) {
setSelected(fieldEl.dataset.fpId);
if (hooks.onSelect) hooks.onSelect(fieldEl.dataset.fpId);
} else if (selectedId) {
setSelected(null);
if (hooks.onSelect) hooks.onSelect(null);
}
});
/* 输入:标题 / 占位符 / 选项 / 数值配置 → 写回隐藏编辑卡 */
root.addEventListener('input', (e) => {
const fieldEl = e.target.closest('.fp-field[data-fp-id]');
if (!fieldEl) return;
const id = fieldEl.dataset.fpId;
const t = e.target;
if (t.matches('[data-fp-name]')) {
setName(id, t.textContent.replace(/\n/g, ''));
} else if (t.matches('[data-fp-ph]')) {
setPlaceholder(id, t.value);
t.placeholder = t.value || '点击输入占位提示...';
} else if (t.matches('[data-fp-opt]')) {
syncOptions(fieldEl, id);
} else if (t.matches('[data-fp-exts]')) {
setExts(id, t.value);
const p = fieldEl.querySelector('.fp-control p.text-\\[10px\\]');
if (p) p.textContent = '支持格式: ' + (t.value.trim() || '所有文件');
} else if (t.matches('[data-fp-rmax]')) {
writeCard(id, c => { const el = c.querySelector('.field-rating-max'); if (el) el.value = t.value; });
} else if (t.matches('[data-fp-smin]')) {
writeCard(id, c => { const el = c.querySelector('.field-slider-min'); if (el) el.value = t.value; });
} else if (t.matches('[data-fp-smax]')) {
writeCard(id, c => { const el = c.querySelector('.field-slider-max'); if (el) el.value = t.value; });
} else if (t.matches('[data-fp-sstep]')) {
writeCard(id, c => { const el = c.querySelector('.field-slider-step'); if (el) el.value = t.value; });
}
});
/* 占位符失焦:把输入值转为占位符展示(预览即真实效果) */
root.addEventListener('focusout', (e) => {
if (e.target.matches && e.target.matches('[data-fp-ph]')) {
e.target.placeholder = e.target.value || '点击输入占位提示...';
e.target.value = '';
}
});
/* contenteditable 回车提交、粘贴纯文本 */
root.addEventListener('keydown', (e) => {
if (e.target.matches && (e.target.matches('[data-fp-name], [data-fp-opt]')) && e.key === 'Enter') {
e.preventDefault();
e.target.blur();
}
});
root.addEventListener('paste', (e) => {
const t = e.target;
if (t.matches && t.matches('[data-fp-name], [data-fp-opt]')) {
e.preventDefault();
const text = (e.clipboardData || window.clipboardData).getData('text').replace(/\n+/g, ' ');
document.execCommand('insertText', false, text);
}
});
/* 选项增删 */
root.addEventListener('click', (e) => {
const add = e.target.closest('[data-fp-opt-add]');
if (add) {
const box = add.closest('[data-fp-opts]');
const fieldEl = add.closest('.fp-field[data-fp-id]');
const chip = document.createElement('span');
chip.className = box.classList.contains('flex-wrap') && box.querySelector('.fp-opt-mark') ? 'inline-flex items-center gap-2.5 text-sm fp-opt' : 'fp-opt-chip';
if (box.querySelector('.fp-opt-mark')) {
const mark = document.createElement('span');
mark.className = 'fp-opt-mark';
mark.style.cssText = box.querySelector('.fp-opt-mark').style.cssText;
chip.appendChild(mark);
}
const txt = document.createElement('span');
txt.className = 'fp-opt-text';
txt.setAttribute('contenteditable', 'true');
txt.setAttribute('data-fp-opt', '');
chip.appendChild(txt);
chip.insertAdjacentHTML('beforeend', '<button type="button" class="fp-opt-del" data-fp-opt-del title="删除选项"><svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.4" stroke-linecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg></button>');
box.insertBefore(chip, add);
txt.focus();
syncOptions(fieldEl, fieldEl.dataset.fpId);
return;
}
const del = e.target.closest('[data-fp-opt-del]');
if (del) {
e.stopPropagation();
const fieldEl = del.closest('.fp-field[data-fp-id]');
const chip = del.closest('.fp-opt, .fp-opt-chip');
if (chip) chip.remove();
if (fieldEl) syncOptions(fieldEl, fieldEl.dataset.fpId);
}
});
/* 拖拽:手柄拖动排序 + 调色板落位 */
root.addEventListener('dragstart', (e) => {
const handle = e.target.closest('.fp-handle');
if (!handle) { e.preventDefault(); return; }
const fieldEl = handle.closest('.fp-field[data-fp-id]');
if (!fieldEl) return;
e.dataTransfer.setData('application/x-fp-field', fieldEl.dataset.fpId);
e.dataTransfer.effectAllowed = 'move';
fieldEl.classList.add('fp-dragging');
});
root.addEventListener('dragend', (e) => {
const fieldEl = e.target.closest && e.target.closest('.fp-field[data-fp-id]');
if (fieldEl) fieldEl.classList.remove('fp-dragging');
removeDropLine();
});
root.addEventListener('dragover', (e) => {
if (!isRelevantDrag(e)) return;
e.preventDefault();
e.dataTransfer.dropEffect = isMoveDrag(e) ? 'move' : 'copy';
showDropLine(computeBeforeId(e.clientY));
});
root.addEventListener('dragleave', (e) => {
if (e.target === root || !root.contains(e.relatedTarget)) removeDropLine();
});
root.addEventListener('drop', (e) => {
if (!isRelevantDrag(e)) return;
e.preventDefault();
const beforeId = computeBeforeId(e.clientY);
removeDropLine();
const newType = e.dataTransfer.getData('application/x-field-type');
if (newType) {
const newId = hooks.onCreateAt ? hooks.onCreateAt(newType, beforeId) : null;
if (newId) insertIntoOrder(newId, beforeId);
window.FormPreview.refresh();
return;
}
const movedId = e.dataTransfer.getData('application/x-fp-field');
if (movedId) {
insertIntoOrder(movedId, beforeId);
window.FormPreview.refresh();
}
});
}
function syncOptions(fieldEl, id) {
const chips = Array.from(fieldEl.querySelectorAll('[data-fp-opt]'))
.map(s => s.textContent.trim()).filter(Boolean);
setOptions(id, chips.join(','));
}
function isMoveDrag(e) { return Array.from(e.dataTransfer.types || []).includes('application/x-fp-field'); }
function isRelevantDrag(e) {
const t = Array.from(e.dataTransfer.types || []);
return t.includes('application/x-field-type') || t.includes('application/x-fp-field');
}
function computeBeforeId(clientY) {
const els = Array.from(root.querySelectorAll('.fp-field[data-fp-id]'))
.filter(el => el !== root.querySelector('.fp-field.fp-dragging'));
for (const el of els) {
const r = el.getBoundingClientRect();
if (clientY < r.top + r.height / 2) return el.dataset.fpId;
}
return null;
}
function showDropLine(beforeId) {
removeDropLine();
dropLine = document.createElement('div');
dropLine.className = 'fp-drop-line';
const anchor = beforeId ? root.querySelector(`.fp-field[data-fp-id="${beforeId}"]`) : null;
const fieldsBox = root.querySelector('.fp-fields');
const tailBox = root.querySelector('.fp-tail');
if (anchor) fieldsBox.insertBefore(dropLine, anchor);
else if (tailBox) tailBox.insertBefore(dropLine, tailBox.firstChild);
else fieldsBox.appendChild(dropLine);
}
function removeDropLine() {
if (dropLine && dropLine.parentNode) dropLine.parentNode.removeChild(dropLine);
dropLine = null;
}
/* ---------- 对外 API ---------- */
window.FormPreview = {
init(options) {
root = options.root;
getMeta = options.getMeta || (() => ({}));
hooks = options.hooks || null;
editable = !!(hooks && (hooks.onDelete || hooks.onCreateAt || hooks.onConditional));
if (editable && !document.getElementById('fp-canvas-style')) {
const style = document.createElement('style');
style.id = 'fp-canvas-style';
style.textContent = CANVAS_CSS;
document.head.appendChild(style);
}
// 左栏基础配置变化 → 整画布刷新(标题/公告/名单模式/策略等)
const debouncedFull = () => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => this.refresh(), 150);
};
document.addEventListener('input', (e) => {
if (e.target.closest('.field-card')) return; // 卡片数据由画布编辑直接写回,不触发整刷
if (e.target.closest('#formTitle, #announcementSubtitle, #announcementText, #verifyDigits, #maxSize')) debouncedFull();
});
document.addEventListener('change', (e) => {
if (e.target.closest('.field-card')) return;
if (e.target.closest('#showProgress, #verifyDigits, #maxSize')) debouncedFull();
});
this.refresh();
},
refresh() {
if (!root || !getMeta) return;
if (selectedId && !document.getElementById(selectedId)) selectedId = null; // 字段已删
reconcileOrder();
render(getMeta());
},
setSelected(id) {
selectedId = id || null;
this.refresh();
},
/* 按画布顺序返回 .field-card 元素(保存/枚举的权威顺序) */
orderedFieldCards() {
const all = Array.from(document.querySelectorAll('.field-card'));
if (!root || !editable) return all;
const ids = Array.from(root.querySelectorAll('.fp-field[data-fp-id]')).map(el => el.dataset.fpId);
const ordered = ids.map(id => document.getElementById(id)).filter(Boolean);
all.forEach(c => { if (!ids.includes(c.id)) ordered.push(c); });
return ordered;
},
};
})();
+45
View File
@@ -0,0 +1,45 @@
// CDN unavailable: keep form controls functional and show the final motion state.
(function () {
if (window.gsap) return;
function elements(target) {
if (typeof target === 'string') return document.querySelectorAll(target);
if (!target) return [];
if (target.nodeType === 1) return [target];
return typeof target.length === 'number' ? target : [];
}
function apply(target, vars = {}) {
for (const element of elements(target)) {
if (!element.style) continue;
for (const [key, value] of Object.entries(vars)) {
if (key in element.style && value !== null) element.style[key] = String(value);
}
if ('x' in vars || 'y' in vars || 'scale' in vars || 'scaleX' in vars || 'scaleY' in vars) {
const x = Number(vars.x || 0);
const y = Number(vars.y || 0);
const sx = Number(vars.scaleX ?? vars.scale ?? 1);
const sy = Number(vars.scaleY ?? vars.scale ?? 1);
element.style.transform = `translate(${x}px, ${y}px) scale(${sx}, ${sy})`;
}
}
if (typeof vars.onComplete === 'function') vars.onComplete();
return { kill() {} };
}
function timeline() {
const chain = {
to(target, vars) { apply(target, vars); return chain; },
fromTo(target, _from, vars) { apply(target, vars); return chain; }
};
return chain;
}
window.gsap = {
to: apply,
fromTo(target, _from, vars) { return apply(target, vars); },
set: apply,
killTweensOf() {},
timeline
};
})();
+247
View File
@@ -0,0 +1,247 @@
/**
* markdown.js — 原生轻量 Markdown 渲染器(零依赖、无外部 CDN)
*
* 供 index 页「公告 / 表单说明」等富文本内容使用。
* 安全策略:先对全部输入做 HTML 转义再解析 Markdown,杜绝 XSS。
*
* 支持语法:
* - 标题 # ~ ######
* - 段落、行内换行
* - 加粗 **bold** 、斜体 *italic* / _italic_ 、删除线 ~~del~~
* - 行内代码 `code` 、围栏代码块 ```lang
* - 链接 [text](url) 、裸链接自动转可点击、图片 ![alt](url)
* - 无序列表 -/+/* 、有序列表 1. 、任务列表 - [x]
* - 引用 > 、水平线 --- / *** / ___
* - 表格 | a | b |
*
* 对外接口:window.Markdown.render(markdown) -> 安全 HTML 字符串
*/
window.Markdown = (function () {
'use strict';
// 文本内容转义:仅转义 & < >(引号在文本节点中无需转义,
// 若过早转义会破坏「带提示文字链接」中引号的匹配)
function escapeHtml(s) {
return s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
// 属性值转义:在 escapeHtml 基础上再转义引号与反引号,防属性注入
function escapeAttr(s) {
return escapeHtml(s)
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
.replace(/`/g, '&#96;');
}
// 只允许安全协议;其余一律丢弃,防止 javascript: 等注入
function sanitizeUrl(url) {
var u = (url || '').trim();
if (/^(https?:|mailto:|tel:|ftp:|\/|\.\/|\.\.\/|#)/i.test(u)) return escapeAttr(u);
return '#';
}
// ===== 行内解析 =====
function inline(text) {
var t = escapeHtml(text || '');
// 行内代码
t = t.replace(/`([^`]+)`/g, '<code>$1</code>');
// 图片(必须在链接之前处理,避免 ![alt](url) 被误判为链接)
t = t.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, function (m, alt, url, title) {
var ttl = title ? ' title="' + escapeAttr(title) + '"' : '';
return '<img src="' + sanitizeUrl(url) + '" alt="' + escapeAttr(alt) + '" loading="lazy"' + ttl + '>';
});
// 链接 [text](url "title")
t = t.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g, function (m, label, url, title) {
var ttl = title ? ' title="' + escapeAttr(title) + '"' : '';
return '<a href="' + sanitizeUrl(url) + '" target="_blank" rel="noopener noreferrer"' + ttl + '>' + label + '</a>';
});
// 加粗
t = t.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
// 斜体(单星)
t = t.replace(/(^|[^*])\*([^*\s][^*]*)\*(?!\*)/g, '$1<em>$2</em>');
t = t.replace(/(^|[^_])_([^_\s][^_]*)_(?![_])/g, '$1<em>$2</em>');
// 删除线
t = t.replace(/~~([^~]+)~~/g, '<del>$1</del>');
// 裸链接自动转可点击(排除已转义的 href 属性与常见标点结尾)
t = t.replace(/(^|\s)((?:https?:\/\/)[^\s<>"'`,。;:、()【】!?]+[^\s<>"'`,。;:、()【】!?,.;:!?)\]}])/g,
function (m, pre, url) {
return pre + '<a href="' + sanitizeUrl(url) + '" target="_blank" rel="noopener noreferrer">' + url + '</a>';
});
// 单行换行保留为 <br>(段落内多个来源行 => 硬换行,尊重用户输入的换行符)
t = t.replace(/\n/g, '<br>');
return t;
}
// 拆分表格行,去除首尾多余的 | 与空白
function splitRow(row) {
return row.replace(/^\s*\|?/, '').replace(/\|?\s*$/, '').split('|').map(function (c) {
return c.trim();
});
}
function isDelimiterRow(line) {
var t = (line || '').trim().replace(/^\|/, '').replace(/\|$/, '');
return /^[\s:|-]+$/.test(t) && /-/.test(t);
}
// ===== 块级解析 =====
function render(src) {
if (!src) return '';
var lines = String(src).replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n');
var html = '';
var i = 0;
var listStack = [];
function closeLists() {
while (listStack.length) {
var l = listStack.pop();
html += l === 'ol' ? '</ol>\n' : '</ul>\n';
}
}
while (i < lines.length) {
var line = lines[i];
var trimmed = line.trim();
// 空行
if (!trimmed) { i++; continue; }
// 围栏代码块
var fence = trimmed.match(/^```([\w-]*)\s*$/);
if (fence) {
closeLists();
var code = [];
i++;
while (i < lines.length && !/^```\s*$/.test(lines[i].trim())) {
code.push(lines[i]);
i++;
}
i++; // 跳过结束围栏
html += '<pre><code' + (fence[1] ? ' class="language-' + escapeAttr(fence[1]) + '"' : '') + '>' +
escapeHtml(code.join('\n')) + '</code></pre>\n';
continue;
}
// 标题
var heading = trimmed.match(/^(#{1,6})\s+(.*)$/);
if (heading) {
closeLists();
var level = heading[1].length;
html += '<h' + level + '>' + inline(heading[2]) + '</h' + level + '>\n';
i++;
continue;
}
// 水平线
if (/^(\s*[-*_]\s*){3,}$/.test(trimmed)) {
closeLists();
html += '<hr>\n';
i++;
continue;
}
// 引用
if (trimmed.charAt(0) === '>') {
closeLists();
var quote = [];
while (i < lines.length && lines[i].trim().charAt(0) === '>') {
quote.push(lines[i].trim().replace(/^>\s?/, ''));
i++;
}
html += '<blockquote>' + inline(quote.join('\n')) + '</blockquote>\n';
continue;
}
// 任务列表
var task = trimmed.match(/^[-*+]\s+\[([ xX])\]\s+(.*)$/);
if (task) {
if (listStack.length === 0 || listStack[listStack.length - 1] !== 'ul') {
closeLists();
html += '<ul class="task-list">\n';
listStack.push('ul');
}
var checked = /[xX]/.test(task[1]);
html += '<li class="task-list-item"><input type="checkbox" disabled' + (checked ? ' checked' : '') + '> ' +
inline(task[2]) + '</li>\n';
i++;
continue;
}
// 无序列表
var ul = trimmed.match(/^[-*+]\s+(.*)$/);
if (ul) {
if (listStack.length === 0 || listStack[listStack.length - 1] !== 'ul') {
closeLists();
html += '<ul>\n';
listStack.push('ul');
}
html += '<li>' + inline(ul[1]) + '</li>\n';
i++;
continue;
}
// 有序列表
var ol = trimmed.match(/^\d+[.)]\s+(.*)$/);
if (ol) {
if (listStack.length === 0 || listStack[listStack.length - 1] !== 'ol') {
closeLists();
html += '<ol>\n';
listStack.push('ol');
}
html += '<li>' + inline(ol[1]) + '</li>\n';
i++;
continue;
}
// 表格(当前行含 | 且下一行为分隔行)
if (trimmed.indexOf('|') !== -1 && i + 1 < lines.length && isDelimiterRow(lines[i + 1])) {
closeLists();
var header = splitRow(trimmed);
var rows = [];
i += 2; // 跳过表头与分隔行
while (i < lines.length && lines[i].trim().indexOf('|') !== -1 && !isDelimiterRow(lines[i].trim())) {
rows.push(splitRow(lines[i].trim()));
i++;
}
html += '<table><thead><tr>' + header.map(function (c) {
return '<th>' + inline(c) + '</th>';
}).join('') + '</tr></thead><tbody>';
html += rows.map(function (r) {
return '<tr>' + r.map(function (c) {
return '<td>' + inline(c) + '</td>';
}).join('') + '</tr>';
}).join('');
html += '</tbody></table>\n';
continue;
}
// 普通段落(收集连续的非空、非块级起始行)
closeLists();
var para = [trimmed];
i++;
while (i < lines.length &&
lines[i].trim() &&
!/^(#{1,6}\s|```|[-*+]\s|\d+[.)]\s|>\s?|\[[ xX]\]\s)/.test(lines[i].trim()) &&
lines[i].trim().indexOf('|') === -1) {
para.push(lines[i].trim());
i++;
}
html += '<p>' + inline(para.join('\n')) + '</p>\n';
}
closeLists();
return html;
}
return { render: render, inline: inline };
})();
+970
View File
@@ -0,0 +1,970 @@
/**
* MorphCard — 胶囊按钮 → 卡片 多状态形变组件(公共库)
*
* v6:临界阻尼流体弹簧引擎。
* 容器位置/尺寸/底色/圆角不再走 CSS transition,而是由一组 ζ=1.0(临界阻尼、无过冲)
* 的二阶弹簧逐帧驱动;border-radius 每帧由当前宽高推导:
* radius = min( min(w,h)/2, lerp(min(w,h)/2 → 28, 圆角揭示进度) )
* 胶囊阶段天然等于高度一半(完整圆端),随轮廓长大连续收敛到卡片圆角,
* 与宽高/位置共享同一组弹簧,全程同步、无跳变。
* 内容面的透明度/位移/模糊/级联也由面弹簧的当前值推导,可中断、无定时器硬切。
*
* 用法(任何页面):
* <script src="/static/js/morph-card.js"></script>
* <script>
* const card = MorphCard.init({
* // 可选配置(以下为默认值)
* successTitle: '提交成功',
* successDesc: '您填写的数据已保存。',
* doneText: '确定',
* errorTitle: '无法提交',
* errorDefault: '提交失败,请稍后重试',
* backText: '返回修改',
* progressLabel: '正在上传',
* onExpand: (sourceEl) => {}, // 卡片从来源元素展开时回调
* onCollapse: (sourceEl) => {}, // 卡片收回、来源元素交还时回调
* });
*
* card.open('progress', { sourceEl: btn }); // 从某元素形变展开(verify/confirm/progress/success/error)
* card.setState('success'); // 已展开时切换内容面(宽高随弹簧平滑过渡)
* card.progress({ percent: 68, text: '2.3 MB/s · 剩余 00:04' });
* card.success(); // 成功面(对勾笔画 + 粒子)
* card.error('具体的错误信息'); // 错误面(不自动收起,用户点"返回修改"关闭)
* card.close(); // 收回来源位置
*
* // 确认卡片:无输入框的二次确认(如"仅可提交一次"提示)。
* // onConfirm 返回 true=确认(keepOpen=true 时卡片保持展开由调用方切下一面);
* // 返回字符串=错误提示显示在卡片内;取消/backdrop/Esc resolve false。
* const ok = await card.confirm({
* title: '仅可提交一次', desc: '提交后不能再修改。',
* okText: '确认提交', cancelText: '再检查一下',
* sourceEl: btn, keepOpen: true,
* onConfirm: async () => true,
* });
*
* // 验证卡片:尾号/验证码输入,resolve 输入值;取消 resolve null;
* // onSubmit 返回 true=通过;返回字符串=错误提示(卡片内显示并抖动)
* const value = await card.verify({
* title: '加载上次提交', desc: '输入学号后 2 位…',
* maxlength: 2, placeholder: '••', okText: '验证并加载',
* inputFilter: v => v.replace(/\D/g, ''),
* sourceEl: btn, keepOpen: false,
* onSubmit: async (value) => true,
* });
* </script>
*
* 依赖:页面主题变量(--accent-bg、--bg-secondary、--text-primary、--border-color 等,
* 由 basic.css 提供),缺失时使用内置深色兜底值。
*/
(function () {
'use strict';
if (window.MorphCard) return; // 单例
/* ---------- 弹簧参数 ---------- */
/* 质量=1 二阶弹簧:ω = 2π/response,k = ω²,c = 2ζω。
ζ = 1 临界阻尼(高阻尼、无过冲、平滑收敛);
response 是"到达目标的特征时间"(秒),不是固定时长。 */
const RESPONSE = 0.45;
const ZETA = 1.0;
const RESPONSE_REVEAL = RESPONSE + 0.12; // 圆角揭示略滞后于轮廓,更像液体
const RESPONSE_BG = RESPONSE + 0.08;
const RESPONSE_BG_COLLAPSE = 0.16; // 收起时先回到按钮主色,再完成轮廓收缩
const FACE_IN = 0.55, FACE_OUT = 0.22; // 内容面弹簧(入/出)
const GATE_AT = 0.45; // 展开时轮廓揭示超过该比例后内容才开始入场
const CARD_R = 28;
const SETTLE_GUARD_MS = 1000; // busy 兜底(约等于弹簧收敛时间)
const COLLAPSE_SAFETY_MS = 2000; // 收起兜底(后台标签页 rAF 暂停时也能收尾)
const FACE_WIDTH = { verify: 300, confirm: 300, progress: 250, success: 320, error: 320 };
const CARD_PAD_X = 44;
const CARD_PAD_Y = 48;
const ACCENT = [23, 23, 23]; // 兜底胶囊底色(正常被 --accent-bg 覆盖读取)
const CARD_BG = [255, 255, 255]; // 兜底卡片底色(正常被 --bg-secondary 覆盖读取)
const reduceMotion = window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches;
/* ---------- 弹簧引擎 ---------- */
const spring = v => ({ x: v, v: 0, t: v });
function stepSpring(s, dt, response, zeta) {
if (dt <= 0) return;
const w = 2 * Math.PI / response, k = w * w, c = 2 * (zeta == null ? ZETA : zeta) * w;
const n = Math.max(1, Math.ceil(dt / (1 / 240))); // 固定子步长,保证数值稳定
const h = dt / n;
for (let i = 0; i < n; i++) {
s.v += (-k * (s.x - s.t) - c * s.v) * h;
s.x += s.v * h;
}
}
const settledS = s => Math.abs(s.x - s.t) < 0.05 && Math.abs(s.v) < 0.05;
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const lerp = (a, b, t) => a + (b - a) * t;
const easeOutCubic = t => 1 - Math.pow(1 - t, 3);
/* ---------- 样式注入 ----------
说明:--um-ease-* / --um-morph-ms 变量保留为外部兼容钩子(页面级 CSS 可引用),
组件本体已不再使用 CSS 过渡做形变。 */
const CSS = `
:root {
--um-morph-ms: 560ms;
--um-ease-morph: cubic-bezier(0.32, 0.72, 0, 1);
--um-ease-out: cubic-bezier(0.23, 1, 0.32, 1);
--um-spring: cubic-bezier(0.34, 1.56, 0.64, 1);
}
body.um-locked { overflow: hidden; }
.um-backdrop {
position: fixed; inset: 0; z-index: 90;
background: rgba(8, 10, 14, 0.45);
backdrop-filter: blur(10px) saturate(1.1);
-webkit-backdrop-filter: blur(10px) saturate(1.1);
opacity: 0; pointer-events: none;
}
.um-backdrop.show { pointer-events: auto; }
.um-morpher {
position: fixed; left: 0; top: 0; z-index: 95; display: none;
border: none; border-radius: 999px;
background: var(--accent-bg, #171717);
overflow: hidden; user-select: none; -webkit-tap-highlight-color: transparent;
will-change: transform, width, height;
cursor: default;
}
/* 胶囊面的 spinner:随圆角揭示进度淡出(JS 逐帧写 opacity) */
.um-spinner {
position: absolute; left: 50%; top: 50%; width: 22px; height: 22px;
margin: -11px 0 0 -11px; border-radius: 50%;
border: 2.5px solid color-mix(in srgb, var(--accent-text, #fff) 30%, transparent);
border-top-color: var(--accent-text, #fff);
animation: um-spin 0.7s linear infinite;
pointer-events: none;
}
@keyframes um-spin { to { transform: rotate(360deg); } }
/* 多状态面:verify / confirm / progress / success / error
透明度/模糊由面弹簧逐帧写入,子元素级联亦由弹簧值推导 */
.um-face {
position: absolute; inset: 0;
display: flex; align-items: center; justify-content: center;
overflow-y: auto;
opacity: 0; pointer-events: none;
}
.um-card-inner {
display: flex; flex-direction: column; align-items: center;
width: 320px; max-width: 100%; margin: auto;
text-align: center;
color: var(--text-primary, #171717);
}
.um-badge-wrap { position: relative; width: 76px; height: 76px; }
.um-badge {
position: absolute; inset: 0; border-radius: 50%;
background: linear-gradient(135deg, #34d399, #059669);
display: flex; align-items: center; justify-content: center;
box-shadow: 0 10px 28px -8px rgba(16, 185, 129, 0.55);
transform: scale(0.4); opacity: 0;
transition: transform 0.4s var(--um-spring), opacity 0.2s ease;
}
.um-morpher.um-badge-in .um-badge { transform: scale(1); opacity: 1; }
.um-badge-error {
background: linear-gradient(135deg, #f87171, #dc2626);
box-shadow: 0 10px 28px -8px rgba(220, 38, 38, 0.5);
}
.um-badge svg { width: 34px; height: 34px; }
.um-check {
fill: none; stroke: #fff; stroke-width: 2.6;
stroke-linecap: round; stroke-linejoin: round;
stroke-dasharray: 1; stroke-dashoffset: 1;
}
.um-morpher.is-done .um-check {
stroke-dashoffset: 0;
transition: stroke-dashoffset 0.42s cubic-bezier(0.65, 0, 0.35, 1);
}
.um-ring-pulse {
position: absolute; inset: -2px; border-radius: 50%;
border: 2px solid #10b981; opacity: 0; pointer-events: none;
}
.um-morpher.is-done .um-ring-pulse { animation: um-ripple 0.65s ease-out 0.15s both; }
@keyframes um-ripple {
0% { transform: scale(1); opacity: 0.55; }
100% { transform: scale(1.75); opacity: 0; }
}
.um-title {
font-family: 'Playfair Display', Georgia, 'Times New Roman', serif;
font-size: 24px; font-weight: 500; margin-top: 22px;
color: inherit;
}
.um-desc {
font-size: 13.5px; color: var(--text-secondary, #525252);
line-height: 1.75; margin-top: 10px;
}
.um-btn {
width: 100%; height: 48px; margin-top: 26px;
border: none; border-radius: 999px; cursor: pointer;
background: var(--accent-bg, #171717); color: var(--accent-text, #ffffff);
font: 600 14px/1 inherit; letter-spacing: 0.02em;
transition: transform 0.16s ease-out, opacity 0.15s ease;
}
.um-btn:active { transform: scale(0.97); }
/* 验证面 */
.um-verify-inner { width: 300px; max-width: 100%; }
.um-verify-input {
display: block; width: 170px; margin: 22px auto 0; padding: 10px 6px;
border: none; border-bottom: 2px solid var(--border-color, #e5e5e5);
border-radius: 0; background: transparent; outline: none;
text-align: center; letter-spacing: 0.35em; text-indent: 0.35em;
font-size: 26px; font-weight: 600; line-height: 1.4;
color: var(--text-primary, #171717); font-family: inherit;
caret-color: var(--accent-bg, #171717);
transition: border-color 0.2s ease;
}
.um-verify-input:focus { border-color: var(--text-primary, #171717); }
.um-verify-input.um-input-error { border-color: var(--error-text, #ef4444); }
.um-verify-err {
min-height: 20px; margin-top: 10px;
font-size: 12px; color: var(--error-text, #ef4444);
}
.um-verify-actions { display: flex; gap: 10px; width: 100%; margin-top: 8px; }
.um-verify-actions .um-btn { flex: 1; width: auto; margin-top: 0; }
.um-btn-ghost {
background: transparent; color: var(--text-secondary, #525252);
border: 1px solid var(--border-color, #e5e5e5);
}
/* 进度面 */
.um-progress-inner { width: 250px; max-width: 100%; }
.um-progress-label {
font-size: 11px; letter-spacing: 0.4em; text-transform: uppercase;
color: var(--text-muted, #737373);
}
.um-progress-ring { position: relative; width: 132px; height: 132px; margin-top: 28px; }
.um-progress-ring svg { width: 100%; height: 100%; transform: rotate(-90deg); }
.um-ring-track { fill: none; stroke: var(--border-color, #e5e5e5); stroke-width: 5; }
.um-ring-fill {
fill: none; stroke: var(--text-primary, #171717); stroke-width: 5; stroke-linecap: round;
stroke-dasharray: 100; stroke-dashoffset: 100;
transition: stroke-dashoffset 0.25s linear;
}
.um-progress-percent {
position: absolute; inset: 0;
display: flex; align-items: center; justify-content: center;
font-size: 26px; font-weight: 600; color: var(--text-primary, #171717);
font-variant-numeric: tabular-nums;
}
.um-progress-sub {
margin-top: 24px; font-size: 12.5px; color: var(--text-muted, #737373);
font-variant-numeric: tabular-nums;
}
.um-error-inner .um-desc { color: var(--error-text, #ef4444); }
@media (prefers-reduced-motion: reduce) {
.um-spinner, .um-badge, .um-ring-pulse, .um-btn, .um-check {
transition-duration: 1ms !important;
animation-duration: 1ms !important;
}
}
`;
/* ---------- DOM ---------- */
function buildDom(opts) {
const style = document.createElement('style');
style.textContent = CSS;
document.head.appendChild(style);
const backdrop = document.createElement('div');
backdrop.className = 'um-backdrop';
backdrop.id = 'umBackdrop';
const morpher = document.createElement('div');
morpher.className = 'um-morpher';
morpher.id = 'uploadMorpher';
morpher.setAttribute('role', 'dialog');
morpher.setAttribute('aria-modal', 'true');
morpher.innerHTML = `
<span class="um-spinner" aria-hidden="true"></span>
<div class="um-face um-face-verify">
<div class="um-card-inner um-verify-inner">
<h3 class="um-title" id="umVerifyTitle">身份验证</h3>
<p class="um-desc" id="umVerifyDesc"></p>
<input type="text" class="um-verify-input" id="umVerifyInput" autocomplete="off" />
<p class="um-verify-err" id="umVerifyError"></p>
<div class="um-verify-actions">
<button type="button" class="um-btn um-btn-ghost" id="umVerifyCancel">取消</button>
<button type="button" class="um-btn" id="umVerifyOk">确认</button>
</div>
</div>
</div>
<div class="um-face um-face-confirm">
<div class="um-card-inner um-confirm-inner">
<h3 class="um-title" id="umConfirmTitle">确认提交</h3>
<p class="um-desc" id="umConfirmDesc"></p>
<p class="um-verify-err" id="umConfirmError"></p>
<div class="um-verify-actions">
<button type="button" class="um-btn um-btn-ghost" id="umConfirmCancel">取消</button>
<button type="button" class="um-btn" id="umConfirmOk">确认提交</button>
</div>
</div>
</div>
<div class="um-face um-face-progress">
<div class="um-card-inner um-progress-inner">
<p class="um-progress-label">${opts.progressLabel}</p>
<div class="um-progress-ring">
<svg viewBox="0 0 120 120">
<circle class="um-ring-track" cx="60" cy="60" r="52" pathLength="100"/>
<circle class="um-ring-fill" id="umProgressRing" cx="60" cy="60" r="52" pathLength="100"/>
</svg>
<span class="um-progress-percent" id="umProgressPercent">0%</span>
</div>
<p class="um-progress-sub" id="umProgressSub">准备中…</p>
</div>
</div>
<div class="um-face um-face-success">
<div class="um-card-inner">
<span class="um-badge-wrap">
<span class="um-ring-pulse"></span>
<span class="um-badge">
<svg viewBox="0 0 24 24"><path class="um-check" d="M5 13l4 4L19 7" pathLength="1"/></svg>
</span>
</span>
<h3 class="um-title">${opts.successTitle}</h3>
<p class="um-desc">${opts.successDesc}</p>
<button type="button" class="um-btn" id="umDoneBtn">${opts.doneText}</button>
</div>
</div>
<div class="um-face um-face-error">
<div class="um-card-inner um-error-inner">
<span class="um-badge-wrap">
<span class="um-badge um-badge-error">
<svg viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.6" stroke-linecap="round">
<path d="M12 6v7"/><path d="M12 16.5v.01"/>
</svg>
</span>
</span>
<h3 class="um-title">${opts.errorTitle}</h3>
<p class="um-desc" id="umErrorText">${opts.errorDefault}</p>
<button type="button" class="um-btn" id="umErrorBack">${opts.backText}</button>
</div>
</div>
`;
document.body.appendChild(backdrop);
document.body.appendChild(morpher);
const faces = {}, inners = {};
morpher.querySelectorAll('.um-face').forEach(f => {
const name = /um-face-(\w+)/.exec(f.className)[1];
faces[name] = f;
inners[name] = f.querySelector('.um-card-inner');
});
return { backdrop, morpher, faces, inners, spinner: morpher.querySelector('.um-spinner') };
}
/* ---------- 组件 ---------- */
const state = {
open: false, busy: false, collapsing: false,
savedRect: null, sourceEl: null, verifyActive: false,
activeFace: null, gateOpen: false, fxStage: 0
};
let dom = null;
let opts = null;
let measurer = null;
/* ---------- 弹簧组 ---------- */
const box = { x: spring(0), y: spring(0), w: spring(0), h: spring(0), reveal: spring(0), bg: spring(0), op: spring(1) };
const backdropS = spring(0);
const faceS = {};
for (const k of Object.keys(FACE_WIDTH)) faceS[k] = spring(0);
/* 底色读取:优先页面主题变量,读不到用兜底值。按次缓存,主题切换/下次展开时刷新 */
function parseColor(varName, fallback, themeEl) {
const v = getComputedStyle(themeEl).getPropertyValue(varName).trim();
if (!v) return fallback;
const m = v.match(/^#([0-9a-f]{6})$/i) || v.match(/^rgb\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)\s*\)$/i);
if (m) {
return m.length === 2
? [parseInt(m[1].slice(0, 2), 16), parseInt(m[1].slice(2, 4), 16), parseInt(m[1].slice(4, 6), 16)]
: [+m[1], +m[2], +m[3]];
}
return fallback;
}
let cachedAccent = null, cachedCard = null, cachedBorder = null;
function refreshTheme() {
// 页面可在 body 或按钮上覆盖主题变量;从形变来源读取,颜色才能与按钮一致。
const themeEl = state.sourceEl?.isConnected ? state.sourceEl : document.body;
cachedAccent = parseColor('--accent-bg', ACCENT, themeEl);
cachedCard = parseColor('--bg-secondary', CARD_BG, themeEl);
cachedBorder = parseColor('--border-color', [229, 229, 229], themeEl);
}
let rafId = null;
let lastT = 0;
let collapseSafety = null;
function ensureLoop() {
if (rafId == null) { lastT = performance.now(); rafId = requestAnimationFrame(tick); }
}
function allContainerSettled() {
return [box.x, box.y, box.w, box.h, box.reveal, box.bg, box.op, backdropS].every(settledS);
}
function allFacesSettled() {
for (const k in faceS) if (!settledS(faceS[k])) return false;
return true;
}
function visibleViewport() {
const vv = window.visualViewport;
if (vv) {
return { top: vv.offsetTop, left: vv.offsetLeft, width: vv.width, height: vv.height };
}
return { top: 0, left: 0, width: window.innerWidth, height: window.innerHeight };
}
function targetRectFallback() {
const w = Math.min(440, window.innerWidth - 32);
const h = Math.min(560, window.innerHeight - 48);
return { left: (window.innerWidth - w) / 2, top: (window.innerHeight - h) / 2, width: w, height: h };
}
/* 离屏克隆目标状态面,测量其自然内容尺寸,返回在给定视口内居中的目标矩形 */
function measureState(stateName, vp) {
const face = dom.faces[stateName];
if (!face) return targetRectFallback();
vp = vp || visibleViewport();
if (!measurer) {
measurer = document.createElement('div');
measurer.style.cssText =
'position:fixed;left:-10000px;top:0;visibility:hidden;pointer-events:none;' +
'display:flex;align-items:center;justify-content:center;';
document.body.appendChild(measurer);
}
const clone = dom.inners[stateName].cloneNode(true);
clone.removeAttribute('style');
clone.querySelectorAll('*').forEach(el => el.removeAttribute('style'));
const designWidth = FACE_WIDTH[stateName] || 320;
const maxW = Math.min(440, vp.width - 32) - CARD_PAD_X * 2;
measurer.style.width = Math.min(designWidth, maxW) + 'px';
measurer.innerHTML = '';
measurer.appendChild(clone);
const w = Math.min(measurer.offsetWidth + CARD_PAD_X * 2, vp.width - 32);
const h = Math.min(measurer.offsetHeight + CARD_PAD_Y * 2, vp.height - 32);
return {
left: vp.left + (vp.width - w) / 2,
top: vp.top + (vp.height - h) / 2,
width: w, height: h
};
}
/* 把当前面的目标矩形写入弹簧(软键盘弹起/收起、切面、展开共用) */
function retargetTo(stateName) {
const t = measureState(stateName, visibleViewport());
box.x.t = t.left; box.y.t = t.top; box.w.t = t.width; box.h.t = t.height;
}
/* 软键盘弹起/收起时,让卡片平滑避让到可视区域内(弹簧自然滑移) */
if (window.visualViewport) {
window.visualViewport.addEventListener('resize', () => {
if (!state.open || state.collapsing || !dom) return;
if (dom.morpher.style.display !== 'block') return;
retargetTo(state.activeFace || 'verify');
ensureLoop();
});
}
/* ---------- 逐帧写入 ---------- */
/* 关键:border-radius 不独立过渡,由当前宽高与揭示进度推导,见文件头注释 */
function applyBox() {
const el = dom.morpher;
const a = cachedAccent, c = cachedCard, bc = cachedBorder;
const m = clamp(box.bg.x, 0, 1);
el.style.transform = `translate3d(${box.x.x}px, ${box.y.x}px, 0)`;
el.style.width = box.w.x + 'px';
el.style.height = box.h.x + 'px';
const half = Math.min(box.w.x, box.h.x) / 2;
const radius = Math.min(half, lerp(half, CARD_R, clamp(box.reveal.x, 0, 1)));
el.style.borderRadius = radius + 'px';
el.style.backgroundColor =
`rgb(${Math.round(lerp(a[0], c[0], m))},${Math.round(lerp(a[1], c[1], m))},${Math.round(lerp(a[2], c[2], m))})`;
el.style.boxShadow = m < 0.01 ? 'none' :
`0 ${(32 * m).toFixed(1)}px ${(90 * m).toFixed(1)}px ${(-20 * m).toFixed(1)}px rgba(8,10,14,${(0.35 * m).toFixed(3)}), ` +
`0 0 0 1px rgba(${bc[0]},${bc[1]},${bc[2]},${m.toFixed(3)})`;
el.style.opacity = clamp(box.op.x, 0, 1).toFixed(3);
}
/* 内容面:透明度/模糊/子元素级联全部由面弹簧当前值推导(可中断、无定时器硬切) */
function applyFace(name) {
const s = faceS[name];
const el = dom.faces[name], inner = dom.inners[name];
if (!el) return;
const r = clamp(s.x, 0, 1);
el.style.opacity = r.toFixed(3);
el.style.pointerEvents = r > 0.6 ? 'auto' : 'none';
inner.style.filter = r < 0.999 ? `blur(${((1 - r) * 6).toFixed(2)}px)` : 'none';
const kids = inner.children;
for (let i = 0; i < kids.length; i++) {
const d = i * 0.09;
const e = easeOutCubic(clamp((r - d) / (1 - d), 0, 1));
kids[i].style.opacity = e.toFixed(3);
kids[i].style.transform = e < 0.999 ? `translateY(${((1 - e) * 14).toFixed(2)}px)` : 'none';
}
}
function burst() {
const badge = dom.morpher.querySelector('.um-badge-wrap');
if (!badge) return;
const r = badge.getBoundingClientRect();
const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
const colors = ['#10b981', '#3b82f6', '#f59e0b', '#ec4899', '#8b5cf6'];
for (let i = 0; i < 14; i++) {
const dot = document.createElement('span');
const size = 4 + Math.random() * 3;
const angle = (Math.PI * 2 * i) / 14 + (Math.random() - 0.5) * 0.6;
const dist = 46 + Math.random() * 52;
dot.style.cssText =
'position:fixed;z-index:96;pointer-events:none;border-radius:50%;' +
'left:' + (cx - size / 2) + 'px;top:' + (cy - size / 2) + 'px;' +
'width:' + size + 'px;height:' + size + 'px;background:' + colors[i % colors.length] + ';';
document.body.appendChild(dot);
const anim = dot.animate([
{ transform: 'translate(0,0) scale(1)', opacity: 1 },
{ transform: `translate(${Math.cos(angle) * dist}px, ${Math.sin(angle) * dist}px) scale(0.5)`, opacity: 0 }
], { duration: 650 + Math.random() * 300, easing: 'cubic-bezier(0.16, 1, 0.3, 1)', fill: 'forwards' });
anim.onfinish = () => dot.remove();
}
}
/* 成功/错误徽章与对勾:由面弹簧阈值触发(is-done 同时驱动描画与涟漪) */
function tickSuccessFx() {
const name = state.activeFace;
if ((name !== 'success' && name !== 'error') || state.collapsing) return;
const r = faceS[name].x;
if (state.fxStage < 1 && r > 0.55) {
state.fxStage = 1;
dom.morpher.classList.add('um-badge-in');
if (name === 'success') dom.morpher.classList.add('is-done');
}
if (state.fxStage < 2 && name === 'success' && r > 0.85) {
state.fxStage = 2;
burst();
}
}
function resetFx() {
state.fxStage = 0;
dom.morpher.classList.remove('is-done', 'um-badge-in');
}
/* ---------- 主循环 ---------- */
function tick(now) {
const dt = Math.min((now - lastT) / 1000, 0.05);
lastT = now;
/* 展开 Choreography:轮廓揭示超过阈值后内容才开始入场 */
if (state.open && !state.gateOpen && box.reveal.x > GATE_AT) {
state.gateOpen = true;
if (state.activeFace) faceS[state.activeFace].t = 1;
}
stepSpring(box.x, dt, RESPONSE);
stepSpring(box.y, dt, RESPONSE);
stepSpring(box.w, dt, RESPONSE);
stepSpring(box.h, dt, RESPONSE);
stepSpring(box.reveal, dt, RESPONSE_REVEAL);
stepSpring(box.bg, dt, state.collapsing ? RESPONSE_BG_COLLAPSE : RESPONSE_BG);
stepSpring(box.op, dt, 0.3);
stepSpring(backdropS, dt, 0.5, 1);
for (const k in faceS) stepSpring(faceS[k], dt, faceS[k].t === 1 ? FACE_IN : FACE_OUT);
applyBox();
for (const k in faceS) applyFace(k);
dom.backdrop.style.opacity = clamp(backdropS.x, 0, 1).toFixed(3);
dom.spinner.style.opacity =
(state.collapsing ? 0 : clamp(1 - box.reveal.x * 2.2, 0, 1)).toFixed(3);
tickSuccessFx();
if (state.collapsing && allContainerSettled() && allFacesSettled()) {
finishCollapse();
}
const idle = !state.open && !state.collapsing && allContainerSettled() && allFacesSettled();
if (idle) { rafId = null; return; } // 停表:完全静止时不再占用 rAF
rafId = requestAnimationFrame(tick);
}
/* ---------- 展开 / 切面 / 收起 ---------- */
/* 从来源元素锁定并展开为卡片 */
function expandFrom(sourceEl, stateName) {
// 防重入护栏:收起未完成时先强制瞬间完成收起;展开中/已展开时忽略
if (state.collapsing) finishCollapse();
if (state.open || state.busy) return;
state.sourceEl = sourceEl || null;
const rect = sourceEl ? sourceEl.getBoundingClientRect() : targetRectFallback();
state.savedRect = rect;
if (opts.onExpand) opts.onExpand(sourceEl);
if (sourceEl) sourceEl.style.visibility = 'hidden'; // 原位留白,由胶囊接管
resetFx();
dom.morpher.removeAttribute('data-um-state');
refreshTheme();
box.x.x = box.x.t = rect.left; box.y.x = box.y.t = rect.top;
box.w.x = box.w.t = rect.width; box.h.x = box.h.t = rect.height;
box.x.v = box.y.v = box.w.v = box.h.v = 0;
box.reveal.x = box.reveal.t = 0; box.reveal.v = 0;
box.bg.x = box.bg.t = 0; box.bg.v = 0;
box.op.x = box.op.t = 1; box.op.v = 0;
backdropS.x = backdropS.t = 0; backdropS.v = 0;
for (const k in faceS) { faceS[k].x = faceS[k].t = 0; faceS[k].v = 0; }
dom.morpher.style.display = 'block';
applyBox(); // 首帧即胶囊形态
dom.backdrop.classList.add('show');
document.body.classList.add('um-locked');
state.gateOpen = reduceMotion;
state.open = true;
setStateInternal(stateName);
box.reveal.t = 1; box.bg.t = 1; backdropS.t = 1;
if (reduceMotion) snapAll();
state.busy = true;
setTimeout(() => { state.busy = false; }, SETTLE_GUARD_MS);
ensureLoop();
}
/* 切换内容面:面弹簧交叉淡入,宽高随同一组弹簧滑到新内容尺寸 */
function setStateInternal(stateName) {
state.activeFace = stateName;
refreshTheme();
dom.morpher.setAttribute('data-um-state', stateName);
if (stateName !== 'success') resetFx(); else state.fxStage = 0;
for (const k in faceS) {
if (k === stateName) {
if (state.gateOpen) faceS[k].t = 1; // 展开途中由 gate 统一点火
} else {
faceS[k].t = 0;
}
}
if (state.open && dom.morpher.style.display === 'block') {
retargetTo(stateName);
ensureLoop();
}
}
/* 收起:内容快速退场 → 弹簧缩回来源位置 → 交还原位 */
function collapse(onDone) {
const tryStart = () => {
if (state.busy || state.collapsing) { setTimeout(tryStart, 100); return; }
state.collapsing = true;
state.open = false;
state.pendingCollapseDone = onDone || null;
const sourceEl = state.sourceEl;
resetFx();
dom.morpher.removeAttribute('data-um-state'); // 内容快速退场
for (const k in faceS) faceS[k].t = 0;
if (!sourceEl) {
// 无来源元素(如居中展开的错误卡):原位收缩淡出,避免变形为巨型胶囊盖住页面
const cx = box.x.x + box.w.x / 2, cy = box.y.x + box.h.x / 2;
box.w.t = box.w.x * 0.88; box.h.t = box.h.x * 0.88;
box.x.t = cx - box.w.t / 2; box.y.t = cy - box.h.t / 2;
box.op.t = 0;
backdropS.t = 0;
} else {
const r = sourceEl.getBoundingClientRect();
box.x.t = r.left; box.y.t = r.top; box.w.t = r.width; box.h.t = r.height;
box.reveal.t = 0; // 圆角沿同一组弹簧连续回到完整圆端
box.bg.t = 0;
backdropS.t = 0;
}
clearTimeout(collapseSafety);
collapseSafety = setTimeout(() => { if (state.collapsing) finishCollapse(); }, COLLAPSE_SAFETY_MS);
ensureLoop();
};
tryStart();
}
function finishCollapse() {
clearTimeout(collapseSafety);
collapseSafety = null;
const sourceEl = state.sourceEl;
dom.morpher.style.cssText = ''; // 回到 CSS 基础形态(display:none)
dom.morpher.removeAttribute('data-um-state');
resetFx();
dom.backdrop.classList.remove('show');
dom.backdrop.style.opacity = '';
// 弹簧全部归位,供下次展开使用
box.op.x = box.op.t = 1; box.op.v = 0;
for (const k in faceS) { faceS[k].x = faceS[k].t = 0; faceS[k].v = 0; }
backdropS.x = backdropS.t = 0; backdropS.v = 0;
if (sourceEl) {
if (opts.onCollapse) opts.onCollapse(sourceEl);
sourceEl.style.visibility = ''; // 交还原位
}
state.sourceEl = null;
document.body.classList.remove('um-locked');
state.collapsing = false;
state.gateOpen = false;
state.activeFace = null;
const done = state.pendingCollapseDone;
state.pendingCollapseDone = null;
if (done) done();
}
function snapAll() {
for (const s of [box.x, box.y, box.w, box.h, box.reveal, box.bg, box.op, backdropS]) { s.x = s.t; s.v = 0; }
for (const k in faceS) { faceS[k].x = faceS[k].t; faceS[k].v = 0; }
}
/* ---------- 公开 API ---------- */
const api = {
isOpen: () => state.open,
/* 从某元素形变展开为卡片;state: verify / progress / success / error */
open(stateName, options) {
if (state.open || state.busy || state.collapsing) return;
expandFrom(options && options.sourceEl, stateName);
},
/* 已展开时切换内容面(宽高随弹簧平滑过渡) */
setState: setStateInternal,
/* 收回来源位置并交还原元素 */
close() {
if (!state.open || state.collapsing) return;
collapse();
},
/* 进度面:未展开时从提交按钮展开;openProgress 由页面在提交时调用 */
openProgress(sourceEl) {
if (state.open) { setStateInternal('progress'); return; }
expandFrom(sourceEl || null, 'progress');
api.progress({ percent: 0, text: '准备中…' });
},
progress(p) {
const ring = document.getElementById('umProgressRing');
const pct = document.getElementById('umProgressPercent');
const sub = document.getElementById('umProgressSub');
if (!ring || !pct) return;
if (p.percent != null) {
const clamped = Math.max(0, Math.min(100, p.percent));
ring.style.strokeDashoffset = String(100 - clamped);
pct.textContent = Math.round(clamped) + '%';
}
if (p.text && sub) sub.textContent = p.text;
},
/* 成功面:已展开则原位切换,否则展开 */
success(sourceEl) {
if (!state.open) {
expandFrom(sourceEl || null, 'success');
} else {
setStateInternal('success');
}
},
/* 错误面:已展开则原位切换(不自动收起),否则展开 */
error(message, sourceEl) {
document.getElementById('umErrorText').textContent = message || opts.errorDefault;
if (state.open) {
setStateInternal('error');
} else {
expandFrom(sourceEl || null, 'error');
}
},
/* 验证卡片:从来源元素展开,onSubmit 返回 true 关闭(keepOpen=true 时保持展开)
并 resolve 输入值;返回字符串则作为错误显示在卡片内;取消 resolve(null)。 */
verify({ title, desc, maxlength = 2, placeholder = '••', okText = '确认',
inputFilter = null, sourceEl = null, keepOpen = false, onSubmit }) {
return new Promise((resolve) => {
const input = document.getElementById('umVerifyInput');
const errEl = document.getElementById('umVerifyError');
const okBtn = document.getElementById('umVerifyOk');
const cancelBtn = document.getElementById('umVerifyCancel');
document.getElementById('umVerifyTitle').textContent = title;
document.getElementById('umVerifyDesc').textContent = desc;
okBtn.textContent = okText;
input.setAttribute('maxlength', maxlength);
input.placeholder = placeholder;
input.value = '';
errEl.textContent = '';
input.classList.remove('um-input-error');
okBtn.disabled = false; cancelBtn.disabled = false;
state.verifyActive = true;
let settled = false;
const cleanup = () => {
okBtn.onclick = null; cancelBtn.onclick = null; input.onkeydown = null;
dom.backdrop.removeEventListener('click', onBackdrop);
document.removeEventListener('keydown', onKey);
state.verifyActive = false;
};
const finish = (value) => {
if (settled) return;
settled = true;
cleanup();
if (value !== null && keepOpen && state.open) {
resolve(value); // 卡片保持展开,由调用方切换到下一状态
} else {
collapse(() => resolve(value));
}
};
const submit = async () => {
if (settled) return;
const value = input.value.trim();
if (!value || value.length !== maxlength) {
errEl.textContent = `请输入 ${maxlength} 位`;
input.classList.add('um-input-error');
input.focus();
return;
}
okBtn.disabled = true; cancelBtn.disabled = true;
let result;
try { result = await onSubmit(value); }
catch (e) { result = (e && e.message) || '操作失败,请稍后重试'; }
if (result === true) { finish(value); }
else {
errEl.textContent = result || '验证失败';
input.classList.add('um-input-error');
okBtn.disabled = false; cancelBtn.disabled = false;
/* 抖动写在当前内容面上,避免与容器弹簧逐帧写入的 transform 冲突 */
const face = dom.faces[state.activeFace] || dom.faces.verify;
if (window.gsap) {
gsap.to(face, { x: [-5, 5, -5, 5, 0], duration: 0.4, ease: 'power2.inOut', clearProps: 'x' });
} else {
face.animate(
[{ transform: 'translateX(0)' }, { transform: 'translateX(-5px)' }, { transform: 'translateX(5px)' },
{ transform: 'translateX(-5px)' }, { transform: 'translateX(5px)' }, { transform: 'translateX(0)' }],
{ duration: 400, easing: 'ease-in-out' });
}
input.focus(); input.select();
}
};
const onBackdrop = () => finish(null);
const onKey = (e) => { if (e.key === 'Escape') finish(null); };
okBtn.onclick = submit;
cancelBtn.onclick = () => finish(null);
input.onkeydown = (e) => { if (e.key === 'Enter') submit(); };
input.oninput = inputFilter ? function () { this.value = inputFilter(this.value); } : null;
dom.backdrop.addEventListener('click', onBackdrop);
document.addEventListener('keydown', onKey);
expandFrom(sourceEl, 'verify');
setTimeout(() => input.focus(), 500);
});
},
/* 确认卡片(如"仅可提交一次"提示):从来源元素展开,无输入框。
onConfirm 返回 true 关闭(keepOpen=true 保持展开)并 resolve true;
返回字符串则在卡片内显示为错误;取消/backdrop/Esc resolve false。 */
confirm({ title = '确认提交', desc = '', okText = '确认提交', cancelText = '取消',
sourceEl = null, keepOpen = false, onConfirm }) {
return new Promise((resolve) => {
const errEl = document.getElementById('umConfirmError');
const okBtn = document.getElementById('umConfirmOk');
const cancelBtn = document.getElementById('umConfirmCancel');
document.getElementById('umConfirmTitle').textContent = title;
document.getElementById('umConfirmDesc').textContent = desc;
okBtn.textContent = okText;
cancelBtn.textContent = cancelText;
errEl.textContent = '';
okBtn.disabled = false; cancelBtn.disabled = false;
let settled = false;
const cleanup = () => {
okBtn.onclick = null; cancelBtn.onclick = null;
dom.backdrop.removeEventListener('click', onBackdrop);
document.removeEventListener('keydown', onKey);
};
const finish = (value) => {
if (settled) return;
settled = true;
cleanup();
if (value === true && keepOpen && state.open) {
resolve(true); // 卡片保持展开,由调用方切换到下一状态
} else {
collapse(() => resolve(value));
}
};
const submit = async () => {
if (settled) return;
okBtn.disabled = true; cancelBtn.disabled = true;
let result;
try { result = onConfirm ? await onConfirm() : true; }
catch (e) { result = (e && e.message) || '操作失败,请稍后重试'; }
if (result === true) { finish(true); }
else {
errEl.textContent = result || '操作失败';
okBtn.disabled = false; cancelBtn.disabled = false;
}
};
const onBackdrop = () => finish(false);
const onKey = (e) => { if (e.key === 'Escape') finish(false); };
okBtn.onclick = submit;
cancelBtn.onclick = () => finish(false);
dom.backdrop.addEventListener('click', onBackdrop);
document.addEventListener('keydown', onKey);
expandFrom(sourceEl, 'confirm');
});
}
};
window.MorphCard = {
/* 初始化:注入样式与 DOM,返回 API(单例,重复调用返回同一实例) */
init(options) {
if (dom) return api;
opts = Object.assign({
successTitle: '提交成功',
successDesc: '您填写的数据已保存。',
doneText: '确定',
errorTitle: '无法提交',
errorDefault: '提交失败,请稍后重试',
backText: '返回修改',
progressLabel: '正在上传',
onExpand: null,
onCollapse: null
}, options || {});
dom = buildDom(opts);
document.getElementById('umDoneBtn').addEventListener('click', () => api.close());
document.getElementById('umErrorBack').addEventListener('click', () => api.close());
dom.backdrop.addEventListener('click', () => {
if (state.verifyActive) return; // 验证中由 verify 的取消逻辑处理
api.close();
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !state.verifyActive) api.close();
});
return api;
}
};
})();
+297
View File
@@ -0,0 +1,297 @@
// particles.js - CSDN 风格柔和粒子网格背景
(function() {
'use strict';
class ParticleSystem {
constructor(options = {}) {
this.canvas = null;
this.ctx = null;
this.particles = [];
this.animationId = null;
// CSDN 风格配置:极其 subtle
this.config = {
particleCount: options.particleCount || null, // 默认根据屏幕计算
connectionDistance: options.connectionDistance || 100, // 连线距离短
mouseDistance: options.mouseDistance || 120, // 鼠标影响范围
attractStrength: options.attractStrength || 0.04, // 极弱的吸引力
speed: options.speed || 0.4, // 缓慢的漂移速度
size: { min: 2, max: 4 }, // 极小的粒子
opacity: { min: 0.3, max: 0.6 }, // 很淡的透明度
zIndex: options.zIndex || -1, // 放在内容后面
colorLight: '100, 100, 100', // 浅灰色(亮色模式)
colorDark: '150, 150, 150', // 中灰色(暗色模式)
lineOpacity: 0.2, // 极淡的连线
maxConnections: 5, // 限制连线数量避免杂乱
bgColor: options.bgColor || null // 背景色(可选)
};
this.mouse = { x: null, y: null, active: false };
this.isDark = false;
this.dpr = window.devicePixelRatio || 1;
this.init();
}
init() {
if (document.getElementById('particleCanvas')) return;
this.canvas = document.createElement('canvas');
this.canvas.id = 'particleCanvas';
this.canvas.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: ${this.config.zIndex};
pointer-events: none;
touch-action: none;
opacity: 0.6; /* 整体再淡一点 */
`;
document.body.insertBefore(this.canvas, document.body.firstChild);
this.ctx = this.canvas.getContext('2d', { alpha: true });
this.resize();
window.addEventListener('resize', () => this.resize(), { passive: true });
this.initEvents();
this.initThemeListener();
this.createParticles();
this.visibilityHandler = () => {
if (document.hidden) {
if (this.animationId) cancelAnimationFrame(this.animationId);
this.animationId = null;
} else if (!this.animationId) {
this.animate();
}
};
document.addEventListener('visibilitychange', this.visibilityHandler);
this.animate();
}
initEvents() {
// 鼠标移动(极其平滑的跟随)
const updateMouse = (x, y) => {
this.mouse.x = x;
this.mouse.y = y;
this.mouse.active = true;
// 延迟取消 active 状态,避免闪烁
clearTimeout(this.mouseTimer);
this.mouseTimer = setTimeout(() => {
this.mouse.active = false;
}, 100);
};
window.addEventListener('mousemove', (e) => {
updateMouse(e.clientX, e.clientY);
}, { passive: true });
// 触摸支持
window.addEventListener('touchstart', (e) => {
if (e.touches[0]) updateMouse(e.touches[0].clientX, e.touches[0].clientY);
}, { passive: true });
window.addEventListener('touchmove', (e) => {
if (e.touches[0]) updateMouse(e.touches[0].clientX, e.touches[0].clientY);
}, { passive: true });
window.addEventListener('touchend', () => {
this.mouse.active = false;
});
}
resize() {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.canvas.width = this.width * this.dpr;
this.canvas.height = this.height * this.dpr;
this.canvas.style.width = this.width + 'px';
this.canvas.style.height = this.height + 'px';
this.ctx.scale(this.dpr, this.dpr);
// 根据屏幕面积计算粒子数:每 20000 像素一个粒子,最少 40,最多 100
if (!this.config.particleCount) {
const area = this.width * this.height;
this.targetCount = Math.min(Math.max(Math.floor(area / 20000), 40), 100);
}
}
initThemeListener() {
this.checkTheme();
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
mediaQuery.addEventListener('change', () => this.checkTheme());
const observer = new MutationObserver(() => this.checkTheme());
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class', 'data-theme']
});
}
checkTheme() {
const html = document.documentElement;
this.isDark = html.classList.contains('dark') ||
html.getAttribute('data-theme') === 'dark' ||
(!html.classList.contains('light') &&
window.matchMedia('(prefers-color-scheme: dark)').matches);
}
createParticles() {
const count = this.config.particleCount || this.targetCount || 60;
this.particles = []; // 清空已有
for (let i = 0; i < count; i++) {
this.particles.push({
x: Math.random() * this.width,
y: Math.random() * this.height,
// 基础速度:极小的随机漂移
vx: (Math.random() - 0.75) * this.config.speed,
vy: (Math.random() - 0.75) * this.config.speed,
size: Math.random() * (this.config.size.max - this.config.size.min) + this.config.size.min,
opacity: Math.random() * (this.config.opacity.max - this.config.opacity.min) + this.config.opacity.min,
// 每个粒子有独立的相位,用于正弦波动,让运动更自然
phase: Math.random() * Math.PI * 2,
phaseSpeed: 0.02 + Math.random() * 0.02
});
}
}
updateParticle(p) {
// 正弦波动:让漂移更柔和自然
p.phase += p.phaseSpeed;
const waveX = Math.sin(p.phase) * 0.1;
const waveY = Math.cos(p.phase * 0.7) * 0.1;
// 基础漂移
p.x += p.vx + waveX;
p.y += p.vy + waveY;
// 鼠标吸引效果(极其柔和)
if (this.mouse.active && this.mouse.x !== null) {
const dx = this.mouse.x - p.x;
const dy = this.mouse.y - p.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < this.config.mouseDistance) {
// 距离越近吸引越弱(避免聚集太紧),越远吸引越强但总体很弱
const force = (1 - dist / this.config.mouseDistance) * this.config.attractStrength;
p.vx += dx * force * 0.01;
p.vy += dy * force * 0.01;
}
}
// 速度限制和阻尼(保持柔和感)
const maxSpeed = this.config.speed * 1.5;
p.vx = Math.max(-maxSpeed, Math.min(maxSpeed, p.vx));
p.vy = Math.max(-maxSpeed, Math.min(maxSpeed, p.vy));
// 极小的阻尼,让速度慢慢回归基础值
p.vx *= 0.995;
p.vy *= 0.995;
// 软边界:不是硬反弹,而是慢慢转向
const margin = 50;
if (p.x < -margin) p.x = this.width + margin;
if (p.x > this.width + margin) p.x = -margin;
if (p.y < -margin) p.y = this.height + margin;
if (p.y > this.height + margin) p.y = -margin;
}
draw() {
const color = this.isDark ? this.config.colorDark : this.config.colorLight;
// 绘制连线(在粒子下层)
this.drawConnections(color);
// 绘制粒子
this.particles.forEach(p => {
this.ctx.beginPath();
this.ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
this.ctx.fillStyle = `rgba(${color}, ${p.opacity})`;
this.ctx.fill();
});
}
drawConnections(color) {
// 只检查部分粒子对,优化性能
for (let i = 0; i < this.particles.length; i++) {
let connections = 0;
const p1 = this.particles[i];
// 只检查附近的粒子(简单空间分割思想:只检查索引接近的)
for (let j = i + 1; j < Math.min(i + 20, this.particles.length); j++) {
if (connections >= this.config.maxConnections) break;
const p2 = this.particles[j];
const dx = p1.x - p2.x;
const dy = p1.y - p2.y;
const distSq = dx * dx + dy * dy;
if (distSq < this.config.connectionDistance * this.config.connectionDistance) {
const dist = Math.sqrt(distSq);
const opacity = this.config.lineOpacity * (1 - dist / this.config.connectionDistance);
this.ctx.beginPath();
this.ctx.moveTo(p1.x, p1.y);
this.ctx.lineTo(p2.x, p2.y);
this.ctx.strokeStyle = `rgba(${color}, ${opacity})`;
this.ctx.lineWidth = 0.5;
this.ctx.stroke();
connections++;
}
}
}
}
animate() {
this.ctx.clearRect(0, 0, this.width, this.height);
this.particles.forEach(p => this.updateParticle(p));
this.draw();
this.animationId = requestAnimationFrame(() => this.animate());
}
destroy() {
if (this.animationId) cancelAnimationFrame(this.animationId);
if (this.visibilityHandler) document.removeEventListener('visibilitychange', this.visibilityHandler);
if (this.canvas && this.canvas.parentNode) {
this.canvas.parentNode.removeChild(this.canvas);
}
window.particleSystem = null;
}
}
// 自动初始化
function autoInit() {
if (document.body?.hasAttribute('data-no-particles')) return;
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
if (window.particleSystem) return;
if (!document.body) {
setTimeout(autoInit, 100);
return;
}
const options = {};
if (document.body.dataset.particleCount) {
options.particleCount = parseInt(document.body.dataset.particleCount);
}
window.particleSystem = new ParticleSystem(options);
}
window.ParticleSystem = ParticleSystem;
window.initParticles = (opts) => new ParticleSystem(opts);
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', autoInit);
} else {
setTimeout(autoInit, 0);
}
})();
+250
View File
@@ -0,0 +1,250 @@
/**
* Toast 3D Stack - 健壮版本
*/
(function (global) {
'use strict';
const icons = {
success: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>`,
error: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>`,
info: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>`,
warning: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>`
};
let toastId = 0;
const MAX_STACK = 5;
const DISPLAY_TIME = 4000;
let isReady = false;
const pendingQueue = [];
const isMobile = window.matchMedia('(max-width: 640px)').matches;
let touchStartY = 0;
let isDragging = false;
let currentToast = null;
function checkReady() {
return document.readyState === 'complete' || document.readyState === 'interactive';
}
function ensureReady(callback) {
if (isReady || checkReady()) {
isReady = true;
callback();
} else {
document.addEventListener('DOMContentLoaded', () => {
isReady = true;
callback();
}, { once: true });
}
}
function getContainer() {
let stage = document.getElementById('toast-stage');
if (!stage) {
stage = document.createElement('div');
stage.id = 'toast-stage';
const container = document.createElement('div');
container.id = 'toast-container';
stage.appendChild(container);
if (document.body) {
document.body.appendChild(stage);
} else {
document.addEventListener('DOMContentLoaded', () => {
document.body.appendChild(stage);
}, { once: true });
}
}
return stage.querySelector('#toast-container');
}
function createToast(message, type) {
const el = document.createElement('div');
el.className = `toast ${type} entering`;
el.dataset.id = ++toastId;
el.innerHTML = `
<div style="flex-shrink:0;width:20px;height:20px;">${icons[type] || icons.info}</div>
<div style="flex:1;min-width:0;">${escapeHtml(message)}</div>
`;
if (isMobile) {
attachTouchEvents(el);
}
return el;
}
function attachTouchEvents(el) {
el.addEventListener('touchstart', handleTouchStart, { passive: true });
el.addEventListener('touchmove', handleTouchMove, { passive: true });
el.addEventListener('touchend', handleTouchEnd, { passive: true });
el.addEventListener('click', () => removeToast(el));
}
function handleTouchStart(e) {
const touch = e.touches[0];
touchStartY = touch.clientY;
isDragging = true;
currentToast = e.currentTarget;
currentToast.classList.add('swiping');
}
function handleTouchMove(e) {
if (!isDragging || !currentToast) return;
const touch = e.touches[0];
const deltaY = touch.clientY - touchStartY;
if (deltaY > 0) {
const opacity = Math.max(0.3, 1 - deltaY / 200);
currentToast.style.transform = `translateY(${deltaY}px) scale(${Math.max(0.95, 1 - deltaY / 1000)})`;
currentToast.style.opacity = opacity;
}
}
function handleTouchEnd(e) {
if (!isDragging || !currentToast) return;
const touch = e.changedTouches[0];
const deltaY = touch.clientY - touchStartY;
currentToast.classList.remove('swiping');
if (deltaY > 80) {
removeToast(currentToast);
} else {
currentToast.style.transform = '';
currentToast.style.opacity = '';
}
isDragging = false;
currentToast = null;
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function removeToast(el, immediate = false) {
if (!el || el.classList.contains('exiting')) return;
if (immediate) {
el.remove();
return;
}
el.classList.add('exiting');
if (isMobile) {
// 移动端出场:向下滑出 + 缩小,与入场对称
el.style.transform = 'translateY(20px) scale(0.95)';
el.style.opacity = '0';
el.style.transition = 'transform 0.3s ease, opacity 0.25s ease';
} else {
el.style.transform = 'translateX(100px) translateZ(-100px) scale(0.8) rotateY(-15deg)';
el.style.opacity = '0';
el.style.transition = 'transform 0.35s ease, opacity 0.3s ease';
}
el.style.pointerEvents = 'none';
setTimeout(() => {
if (el.parentNode) el.remove();
}, isMobile ? 300 : 350);
}
function processShow(message, type) {
const container = getContainer();
if (!container) {
pendingQueue.push({ message, type });
return;
}
if (isMobile && container.children.length > 0) {
Array.from(container.children).forEach(oldToast => removeToast(oldToast, true));
}
const existingToasts = Array.from(container.children);
if (!isMobile) {
existingToasts.forEach(toast => toast.classList.add('shift-down'));
}
const el = createToast(message, type);
container.prepend(el);
// 强制同步重排
void el.offsetHeight;
// 桌面端:强制设置初始状态
if (!isMobile) {
el.style.transform = 'translateX(-120px) translateZ(50px) rotateY(25deg)';
el.style.opacity = '0';
el.style.transition = 'none';
}
requestAnimationFrame(() => {
void el.offsetHeight;
requestAnimationFrame(() => {
el.classList.add('show');
if (!isMobile) {
el.style.transform = '';
el.style.opacity = '';
el.style.transition = '';
}
});
});
setTimeout(() => {
el.classList.remove('entering', 'show');
if (!isMobile) {
el.style.cssText = '';
existingToasts.forEach(toast => {
if (toast.parentNode) toast.classList.remove('shift-down');
});
}
}, 600);
if (!isMobile && container.children.length > MAX_STACK) {
const oldest = container.lastElementChild;
if (oldest) {
oldest.style.transition = 'all 0.3s ease';
oldest.style.opacity = '0';
oldest.style.transform = 'translateZ(-250px) scale(0.7)';
setTimeout(() => oldest.remove(), 300);
}
}
setTimeout(() => removeToast(el), DISPLAY_TIME);
}
function show(message, type = 'info') {
ensureReady(() => processShow(message, type));
}
function processQueue() {
while (pendingQueue.length > 0) {
const { message, type } = pendingQueue.shift();
processShow(message, type);
}
}
if (checkReady()) {
processQueue();
} else {
window.addEventListener('load', processQueue);
}
global.Toast = {
show,
success: (msg) => show(msg, 'success'),
error: (msg) => show(msg, 'error'),
info: (msg) => show(msg, 'info'),
warning: (msg) => show(msg, 'warning'),
clear: () => {
const container = getContainer();
if (container) {
Array.from(container.children).forEach(el => removeToast(el, true));
}
}
};
global.showToast = (msg, type = 'success') => show(msg, type);
})(window);
+10
View File
@@ -0,0 +1,10 @@
(function () {
'use strict';
function load(config = {}) {
document.getElementById('enableWebhook').checked = config.enabled === true;
}
function read() {
return { enabled: document.getElementById('enableWebhook').checked };
}
window.FormWebhookSettings = { load, read };
})();
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Robert Wildling
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE WITH OR OTHER DEALINGS IN THE
SOFTWARE.
File diff suppressed because one or more lines are too long
+562
View File
@@ -0,0 +1,562 @@
<!DOCTYPE html>
<html lang="zh-CN" class="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>502 Bad Gateway</title>
<!-- Tailwind CSS (CDN) -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
serif: ['Playfair Display', 'serif'],
mono: ['SF Mono', 'monospace'],
},
colors: {
neutral: {
50: '#fafafa',
100: '#f5f5f5',
200: '#e5e5e5',
300: '#d4d4d4',
400: '#a3a3a3',
500: '#737373',
600: '#525252',
700: '#404040',
800: '#262626',
900: '#171717',
}
},
animation: {
'float': 'float 6s ease-in-out infinite',
'pulse-slow': 'pulse 4s cubic-bezier(0.4, 0, 0.6, 1) infinite',
'glitch': 'glitch 1s linear infinite',
},
keyframes: {
float: {
'0%, 100%': { transform: 'translateY(0px)' },
'50%': { transform: 'translateY(-20px)' },
},
glitch: {
'2%, 64%': { transform: 'translate(2px,0) skew(0deg)' },
'4%, 60%': { transform: 'translate(-2px,0) skew(0deg)' },
'62%': { transform: 'translate(0,0) skew(5deg)' },
}
}
}
}
}
</script>
<!-- GSAP (CDN) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<!-- 鍐呰仈 CSS锛圕SS 鍙橀噺 + 涓撳睘鏍峰紡锛?-->
<style>
/* ========== CSS 鍙橀噺锛堢户鎵胯嚜鍘熺郴缁燂級 ========== */
:root {
--bg-primary: #fafafa;
--bg-secondary: #ffffff;
--text-primary: #171717;
--text-secondary: #525252;
--text-muted: #737373;
--border-color: #e5e5e5;
--accent-bg: #171717;
--accent-text: #ffffff;
--glass-bg: rgba(255, 255, 255, 0.7);
--glass-border: rgba(255, 255, 255, 0.5);
--glass-hover: rgba(255, 255, 255, 0.9);
--shadow-color: rgba(0, 0, 0, 0.05);
--error-bg: #fef2f2;
--error-border: #fee2e2;
--error-text: #dc2626;
--warning-bg: #fffbeb;
--warning-border: #fef3c7;
--warning-text: #d97706;
}
.dark {
--bg-primary: #0a0a0a;
--bg-secondary: #171717;
--text-primary: #fafafa;
--text-secondary: #a3a3a3;
--text-muted: #737373;
--border-color: #262626;
--accent-bg: #fafafa;
--accent-text: #171717;
--glass-bg: rgba(23, 23, 23, 0.8);
--glass-border: rgba(255, 255, 255, 0.1);
--glass-hover: rgba(38, 38, 38, 0.9);
--shadow-color: rgba(0, 0, 0, 0.5);
--error-bg: rgba(220, 38, 38, 0.1);
--error-border: rgba(220, 38, 38, 0.2);
--error-text: #ef4444;
--warning-bg: rgba(217, 119, 6, 0.1);
--warning-border: rgba(217, 119, 6, 0.2);
--warning-text: #fbbf24;
}
/* ========== 鍏ㄥ眬閲嶇疆 ========== */
*, *::before, *::after { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
html { scroll-behavior: smooth; }
::selection { background: rgba(128, 128, 128, 0.2); color: var(--text-primary); }
body {
font-family: 'Inter', sans-serif;
margin: 0;
min-height: 100vh;
overflow-x: hidden;
transition: background-color 0.5s ease, color 0.5s ease;
background-image:
radial-gradient(at 0% 0%, rgba(220, 38, 38, 0.03) 0px, transparent 50%),
radial-gradient(at 100% 100%, rgba(220, 38, 38, 0.03) 0px, transparent 50%);
background-color: var(--bg-primary);
color: var(--text-primary);
}
html.dark body {
background-image:
radial-gradient(at 0% 0%, rgba(239, 68, 68, 0.05) 0px, transparent 50%),
radial-gradient(at 100% 100%, rgba(239, 68, 68, 0.05) 0px, transparent 50%);
}
.font-serif {
font-family: 'Playfair Display', serif;
}
.glass {
background: var(--glass-bg);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid var(--glass-border);
transition: all 0.3s ease;
}
.glass:hover { background: var(--glass-hover); }
.theme-transition {
transition: background-color 0.5s ease, color 0.5s ease, border-color 0.5s ease, box-shadow 0.5s ease;
}
.btn-shine {
position: relative;
overflow: hidden;
}
.btn-shine::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
transition: left 0.5s;
}
.btn-shine:hover::before { left: 100%; }
/* 鈹€鈹€ 502 澶у彿鑳屾櫙鏁板瓧 鈹€鈹€ */
.error-code {
font-family: 'Playfair Display', serif;
font-size: clamp(120px, 20vw, 200px);
font-weight: 600;
line-height: 1;
background: linear-gradient(135deg, var(--warning-text) 0%, #b45309 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
opacity: 0.15;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 0;
pointer-events: none;
user-select: none;
}
.error-content { position: relative; z-index: 1; }
.progress-ring { transform: rotate(-90deg); }
.progress-ring-circle {
transition: stroke-dashoffset 0.35s;
transform-origin: 50% 50%;
}
@media (max-width: 768px) {
.error-code { font-size: 100px; }
}
</style>
</head>
<body class="antialiased min-h-screen flex items-center justify-center relative">
<!-- 鑳屾櫙鍏夋檿 -->
<div class="fixed inset-0 overflow-hidden pointer-events-none">
<div class="absolute top-1/4 left-1/4 w-96 h-96 rounded-full blur-3xl animate-pulse-slow"
style="background: rgba(217,119,6,0.06);"></div>
<div class="absolute bottom-1/4 right-1/4 w-96 h-96 rounded-full blur-3xl animate-pulse-slow"
style="background: rgba(220,38,38,0.05); animation-delay: 2s;"></div>
</div>
<!-- Main Content -->
<main class="relative w-full max-w-2xl mx-auto px-6 py-12">
<!-- Error Code Background -->
<div class="error-code" id="errorCodeBg">502</div>
<!-- Card -->
<div class="error-content glass rounded-3xl p-8 md:p-12 shadow-2xl theme-transition" id="mainCard">
<!-- Icon 鈥?502 缃戝叧鏂紑鍥炬爣 -->
<div class="w-20 h-20 mx-auto mb-8 rounded-2xl flex items-center justify-center theme-transition"
style="background-color: var(--warning-bg); border: 1px solid var(--warning-border);" id="iconContainer">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
style="color: var(--warning-text);" id="errorIcon">
<!-- 鏂紑杩炴帴鍥炬爣锛氫袱鏈嶅姟鍣ㄤ腑闂存柇绾?-->
<rect x="2" y="6" width="6" height="12" rx="1" />
<rect x="16" y="6" width="6" height="12" rx="1" />
<line x1="8" y1="12" x2="16" y2="12" stroke-dasharray="2 3" />
<line x1="8" y1="12" x2="16" y2="12" stroke-width="2" stroke="#ef4444" opacity="0.5" />
</svg>
</div>
<!-- Title -->
<h1 class="font-serif text-3xl md:text-4xl font-medium text-center mb-4 tracking-tight theme-transition"
style="color: var(--text-primary);" id="errorTitle">
502 Bad Gateway<br>缃戝叧杩炴帴澶辫触
</h1>
<!-- Description -->
<p class="text-center mb-8 text-sm md:text-base leading-relaxed max-w-md mx-auto theme-transition"
style="color: var(--text-secondary);" id="errorDesc">
涓婃父鏈嶅姟鍣ㄦ殏鏃舵棤鍝嶅簲锛屾棤娉曞畬鎴愯姹傘€傝绋嶅悗鍒锋柊閲嶈瘯銆? </p>
<!-- Error Details (Collapsible) -->
<div class="mb-8 rounded-xl overflow-hidden theme-transition"
style="background-color: var(--bg-primary); border: 1px solid var(--border-color);">
<button onclick="toggleDetails()"
class="w-full px-4 py-3 flex items-center justify-between text-xs font-medium uppercase tracking-wider theme-transition hover:opacity-70"
style="color: var(--text-muted);">
<span>鎶€鏈鎯?/span>
<svg id="detailsArrow" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" class="transform transition-transform duration-300">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
<div id="errorDetails" class="hidden px-4 pb-4">
<div class="font-mono text-xs p-3 rounded-lg theme-transition"
style="background-color: var(--bg-secondary); color: var(--text-muted); border: 1px solid var(--border-color);">
<div class="mb-1"><span style="color: var(--warning-text);">Status:</span> <span id="detailStatus">502 Bad Gateway</span></div>
<div class="mb-1"><span style="color: var(--warning-text);">Path:</span> <span id="detailPath">/</span></div>
<div><span style="color: var(--warning-text);">Time:</span> <span id="detailTime">--</span></div>
</div>
</div>
</div>
<!-- Action Buttons -->
<div class="flex flex-col sm:flex-row gap-3 justify-center">
<button onclick="refreshPage()"
class="btn-shine px-8 py-3 rounded-full text-sm font-medium tracking-wide text-center transform hover:scale-[1.02] active:scale-[0.98] transition-all theme-transition"
style="background-color: var(--accent-bg); color: var(--accent-text); cursor: pointer; border: none;">
绔嬪嵆鍒锋柊椤甸潰
</button>
<button onclick="history.back()"
class="px-8 py-3 rounded-full text-sm font-medium tracking-wide text-center transform hover:scale-[1.02] active:scale-[0.98] transition-all theme-transition"
style="background-color: var(--bg-primary); color: var(--text-secondary); border: 1px solid var(--border-color); cursor: pointer;">
杩斿洖涓婁竴椤? </button>
</div>
</div>
<!-- Footer -->
<div class="mt-8 text-center">
<p class="text-[10px] tracking-[0.3em] uppercase font-medium theme-transition"
style="color: var(--text-muted);">
&nbsp;
</p>
</div>
</main>
<script>
// ============================================================
// 绮掑瓙绯荤粺 鈥?鍐呰仈鑷?particles.js锛堝畬鏁村唴宓岋紝鏃犲閮ㄤ緷璧栵級
// ============================================================
(function() {
'use strict';
class ParticleSystem {
constructor(options = {}) {
this.canvas = null;
this.ctx = null;
this.particles = [];
this.animationId = null;
this.config = {
particleCount: options.particleCount || null,
connectionDistance: options.connectionDistance || 100,
mouseDistance: options.mouseDistance || 120,
attractStrength: options.attractStrength || 0.04,
speed: options.speed || 0.4,
size: { min: 2, max: 4 },
opacity: { min: 0.3, max: 0.6 },
zIndex: options.zIndex || -1,
colorLight: '100, 100, 100',
colorDark: '150, 150, 150',
lineOpacity: 0.2,
maxConnections: 5,
bgColor: options.bgColor || null
};
this.mouse = { x: null, y: null, active: false };
this.isDark = false;
this.dpr = window.devicePixelRatio || 1;
this.init();
}
init() {
if (document.getElementById('particleCanvas')) return;
this.canvas = document.createElement('canvas');
this.canvas.id = 'particleCanvas';
this.canvas.style.cssText = [
'position: fixed',
'top: 0',
'left: 0',
'width: 100%',
'height: 100%',
'z-index: ' + this.config.zIndex,
'pointer-events: none',
'touch-action: none',
'opacity: 0.6'
].join(';');
document.body.insertBefore(this.canvas, document.body.firstChild);
this.ctx = this.canvas.getContext('2d', { alpha: true });
this.resize();
window.addEventListener('resize', () => this.resize(), { passive: true });
this.initEvents();
this.initThemeListener();
this.createParticles();
this.animate();
}
initEvents() {
var self = this;
var updateMouse = function(x, y) {
self.mouse.x = x; self.mouse.y = y; self.mouse.active = true;
clearTimeout(self.mouseTimer);
self.mouseTimer = setTimeout(function() { self.mouse.active = false; }, 100);
};
window.addEventListener('mousemove', function(e) {
updateMouse(e.clientX, e.clientY);
}, { passive: true });
window.addEventListener('touchstart', function(e) {
if (e.touches[0]) updateMouse(e.touches[0].clientX, e.touches[0].clientY);
}, { passive: true });
window.addEventListener('touchmove', function(e) {
if (e.touches[0]) updateMouse(e.touches[0].clientX, e.touches[0].clientY);
}, { passive: true });
window.addEventListener('touchend', function() { self.mouse.active = false; });
}
resize() {
this.width = window.innerWidth;
this.height = window.innerHeight;
this.canvas.width = this.width * this.dpr;
this.canvas.height = this.height * this.dpr;
this.canvas.style.width = this.width + 'px';
this.canvas.style.height = this.height + 'px';
this.ctx.scale(this.dpr, this.dpr);
if (!this.config.particleCount) {
var area = this.width * this.height;
this.targetCount = Math.min(Math.max(Math.floor(area / 20000), 40), 100);
}
}
initThemeListener() {
var self = this;
this.checkTheme();
var mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
mediaQuery.addEventListener('change', function() { self.checkTheme(); });
var observer = new MutationObserver(function() { self.checkTheme(); });
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme'] });
}
checkTheme() {
var html = document.documentElement;
this.isDark = html.classList.contains('dark') ||
html.getAttribute('data-theme') === 'dark' ||
(!html.classList.contains('light') && window.matchMedia('(prefers-color-scheme: dark)').matches);
}
createParticles() {
var count = this.config.particleCount || this.targetCount || 60;
this.particles = [];
for (var i = 0; i < count; i++) {
this.particles.push({
x: Math.random() * this.width,
y: Math.random() * this.height,
vx: (Math.random() - 0.75) * this.config.speed,
vy: (Math.random() - 0.75) * this.config.speed,
size: Math.random() * (this.config.size.max - this.config.size.min) + this.config.size.min,
opacity: Math.random() * (this.config.opacity.max - this.config.opacity.min) + this.config.opacity.min,
phase: Math.random() * Math.PI * 2,
phaseSpeed: 0.02 + Math.random() * 0.02
});
}
}
updateParticle(p) {
p.phase += p.phaseSpeed;
var waveX = Math.sin(p.phase) * 0.1;
var waveY = Math.cos(p.phase * 0.7) * 0.1;
p.x += p.vx + waveX;
p.y += p.vy + waveY;
if (this.mouse.active && this.mouse.x !== null) {
var dx = this.mouse.x - p.x;
var dy = this.mouse.y - p.y;
var dist = Math.sqrt(dx * dx + dy * dy);
if (dist < this.config.mouseDistance) {
var force = (1 - dist / this.config.mouseDistance) * this.config.attractStrength;
p.vx += dx * force * 0.01;
p.vy += dy * force * 0.01;
}
}
var maxSpeed = this.config.speed * 1.5;
p.vx = Math.max(-maxSpeed, Math.min(maxSpeed, p.vx));
p.vy = Math.max(-maxSpeed, Math.min(maxSpeed, p.vy));
p.vx *= 0.995;
p.vy *= 0.995;
var margin = 50;
if (p.x < -margin) p.x = this.width + margin;
if (p.x > this.width + margin) p.x = -margin;
if (p.y < -margin) p.y = this.height + margin;
if (p.y > this.height + margin) p.y = -margin;
}
draw() {
var color = this.isDark ? this.config.colorDark : this.config.colorLight;
this.drawConnections(color);
for (var i = 0; i < this.particles.length; i++) {
var p = this.particles[i];
this.ctx.beginPath();
this.ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
this.ctx.fillStyle = 'rgba(' + color + ', ' + p.opacity + ')';
this.ctx.fill();
}
}
drawConnections(color) {
for (var i = 0; i < this.particles.length; i++) {
var connections = 0;
var p1 = this.particles[i];
for (var j = i + 1; j < Math.min(i + 20, this.particles.length); j++) {
if (connections >= this.config.maxConnections) break;
var p2 = this.particles[j];
var dx = p1.x - p2.x;
var dy = p1.y - p2.y;
var distSq = dx * dx + dy * dy;
if (distSq < this.config.connectionDistance * this.config.connectionDistance) {
var dist = Math.sqrt(distSq);
var opacity = this.config.lineOpacity * (1 - dist / this.config.connectionDistance);
this.ctx.beginPath();
this.ctx.moveTo(p1.x, p1.y);
this.ctx.lineTo(p2.x, p2.y);
this.ctx.strokeStyle = 'rgba(' + color + ', ' + opacity + ')';
this.ctx.lineWidth = 0.5;
this.ctx.stroke();
connections++;
}
}
}
}
animate() {
var self = this;
this.ctx.clearRect(0, 0, this.width, this.height);
for (var i = 0; i < this.particles.length; i++) {
this.updateParticle(this.particles[i]);
}
this.draw();
this.animationId = requestAnimationFrame(function() { self.animate(); });
}
destroy() {
if (this.animationId) cancelAnimationFrame(this.animationId);
if (this.canvas && this.canvas.parentNode) {
this.canvas.parentNode.removeChild(this.canvas);
}
window.particleSystem = null;
}
}
function autoInit() {
if (document.body && document.body.hasAttribute('data-no-particles')) return;
if (window.particleSystem) return;
if (!document.body) { setTimeout(autoInit, 100); return; }
window.particleSystem = new ParticleSystem();
}
window.ParticleSystem = ParticleSystem;
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', autoInit);
} else {
setTimeout(autoInit, 0);
}
})();
// ============================================================
// 椤甸潰閫昏緫
// ============================================================
// Toggle 鎶€鏈鎯? function toggleDetails() {
var details = document.getElementById('errorDetails');
var arrow = document.getElementById('detailsArrow');
details.classList.toggle('hidden');
arrow.style.transform = details.classList.contains('hidden') ? 'rotate(0deg)' : 'rotate(180deg)';
}
// 鍒锋柊椤甸潰
function refreshPage() {
window.location.reload();
}
// ============================================================
// 涓婚鑷姩璺熼殢绯荤粺
// ============================================================
(function() {
var html = document.documentElement;
function applyTheme() {
var dark = window.matchMedia('(prefers-color-scheme: dark)').matches;
html.classList.toggle('dark', dark);
}
applyTheme();
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', applyTheme);
})();
// GSAP 鍏ュ満鍔ㄧ敾
window.addEventListener('load', function() {
// 鏇存柊鏃堕棿
document.getElementById('detailTime').textContent = new Date().toLocaleString('zh-CN');
gsap.from("#mainCard", { y: 30, opacity: 0, duration: 0.8, ease: "power2.out" });
gsap.from("#iconContainer", { scale: 0, rotation: -180, duration: 0.6, delay: 0.2, ease: "back.out(1.7)" });
gsap.from("#errorTitle", { y: 20, opacity: 0, duration: 0.6, delay: 0.3, ease: "power2.out" });
gsap.from("#errorDesc", { y: 20, opacity: 0, duration: 0.6, delay: 0.4, ease: "power2.out" });
});
// 鑳屾櫙鏁板瓧 hover 鏁堟灉
document.getElementById('errorCodeBg').addEventListener('mouseenter', function() {
gsap.to(this, { scale: 1.1, opacity: 0.2, duration: 0.3 });
});
document.getElementById('errorCodeBg').addEventListener('mouseleave', function() {
gsap.to(this, { scale: 1, opacity: 0.15, duration: 0.3 });
});
</script>
</body>
</html>
+504
View File
@@ -0,0 +1,504 @@
<!DOCTYPE html>
<html lang="zh-CN" class="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>管理后台</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
neutral: {
50: '#fafafa',
100: '#f5f5f5',
200: '#e5e5e5',
300: '#d4d4d4',
400: '#a3a3a3',
500: '#737373',
600: '#525252',
700: '#404040',
800: '#262626',
900: '#171717',
}
}
}
}
}
</script>
<!-- GSAP for animations -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="/static/js/particles.js"></script>
<link rel="stylesheet" href="/static/css/toast.css">
<script src="/static/js/toast.js"></script>
<link rel="stylesheet" href="/static/css/basic.css">
<link rel="stylesheet" href="/static/css/common.css">
<script src="/static/js/common.js"></script>
<style>
/* ── admin 页面专属样式 ── */
.form-card {
background: var(--glass-bg);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid var(--glass-border);
border-radius: 24px;
padding: 24px;
transition: all 0.4s cubic-bezier(0.2, 0, 0, 1);
opacity: 0;
transform: translateY(20px);
}
.form-card:hover {
transform: translateY(-4px);
box-shadow: 0 20px 40px -15px var(--shadow-color);
border-color: rgba(128, 128, 128, 0.3);
background: var(--glass-hover);
}
.btn-manage {
background-color: rgba(99, 102, 241, 0.1);
color: #6366f1;
border: 1px solid rgba(99, 102, 241, 0.2);
}
.btn-manage:hover {
background-color: rgba(99, 102, 241, 0.2);
transform: translateY(-2px);
}
.quick-action {
background: var(--glass-bg);
border: 1px solid var(--glass-border);
border-radius: 16px;
padding: 20px;
transition: all 0.3s ease;
cursor: pointer;
}
.quick-action:hover {
background: var(--glass-hover);
transform: translateY(-2px);
box-shadow: 0 10px 20px -10px var(--shadow-color);
}
</style>
</head>
<body class="antialiased min-h-screen relative">
<!-- Progress Bar -->
<div class="fixed top-0 left-0 w-full h-[2px] z-50 theme-transition" style="background-color: var(--border-color);">
<div id="scrollProgress" class="h-full w-0 transition-all duration-100 ease-out"></div>
</div>
<!-- Header -->
<header class="fixed top-0 w-full z-40 px-4 sm:px-6 py-4 sm:py-5 glass theme-transition border-b">
<div class="max-w-6xl mx-auto flex justify-between items-center">
<!-- 左侧:Logo / 页面标识 -->
<div class="flex items-center gap-3">
<div class="flex items-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
style="color:var(--text-primary)">
<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/>
<rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/>
</svg>
<h1 class="font-serif text-lg sm:text-xl font-semibold tracking-tight theme-transition"
style="color: var(--text-primary);">Admin</h1>
</div>
<span class="hidden sm:inline text-[10px] tracking-[0.2em] uppercase font-medium theme-transition"
style="color: var(--text-muted);">管理后台</span>
</div>
<!-- 右侧:退出登录 -->
<div class="flex items-center gap-2 sm:gap-3">
<button onclick="logout()" class="btn btn-secondary px-4 py-2.5 rounded-full text-xs sm:text-sm font-medium tracking-wide flex items-center gap-2">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
<polyline points="16 17 21 12 16 7"/>
<line x1="21" y1="12" x2="9" y2="12"/>
</svg>
<span class="hidden sm:inline">退出登录</span>
</button>
</div>
</div>
</header>
<!-- Main Content -->
<main class="relative pt-32 pb-24 px-6">
<div class="max-w-6xl mx-auto">
<!-- Header Section -->
<div class="mb-12 opacity-0" id="headerSection">
<h2 class="font-serif text-4xl sm:text-5xl leading-[1.1] font-medium tracking-tight mb-4 theme-transition"
style="color: var(--text-primary);">
管理后台
</h2>
<p class="text-sm leading-relaxed max-w-md tracking-wide font-light theme-transition"
style="color: var(--text-secondary);">
创建和管理表单,查看提交状态,管理用户权限。
</p>
</div>
<!-- Quick Actions -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-12">
<a href="/create" class="quick-action stagger-item group">
<div class="w-12 h-12 rounded-xl flex items-center justify-center mb-4 theme-transition"
style="background: var(--bg-primary);">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
class="theme-transition group-hover:scale-110 transition-transform" style="color: var(--text-primary);">
<line x1="12" y1="5" x2="12" y2="19"></line>
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
</div>
<h3 class="font-medium text-base mb-1 theme-transition" style="color: var(--text-primary);">新建表单</h3>
<p class="text-xs theme-transition" style="color: var(--text-muted);">创建数据收集表单</p>
</a>
<a href="/preset_manage" class="quick-action stagger-item group">
<div class="w-12 h-12 rounded-xl flex items-center justify-center mb-4 theme-transition"
style="background: var(--info-bg);">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
class="theme-transition group-hover:scale-110 transition-transform" style="color: var(--info-text);">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
</div>
<h3 class="font-medium text-base mb-1 theme-transition" style="color: var(--text-primary);">名单预设</h3>
<p class="text-xs theme-transition" style="color: var(--text-muted);">管理学生名单预设</p>
</a>
<a href="/user_manage" class="quick-action stagger-item group" id="userManageLink" style="display: none;">
<div class="w-12 h-12 rounded-xl flex items-center justify-center mb-4 theme-transition"
style="background: var(--success-bg);">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
class="theme-transition group-hover:scale-110 transition-transform" style="color: var(--success-text);">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
</div>
<h3 class="font-medium text-base mb-1 theme-transition" style="color: var(--text-primary);">用户管理</h3>
<p class="text-xs theme-transition" style="color: var(--text-muted);">管理用户权限</p>
</a>
<a href="/db_manage" class="quick-action stagger-item group" id="dbManageLink" style="display: none;">
<div class="w-12 h-12 rounded-xl flex items-center justify-center mb-4 theme-transition"
style="background: var(--warning-bg);">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
class="theme-transition group-hover:scale-110 transition-transform" style="color: var(--warning-text);">
<ellipse cx="12" cy="5" rx="9" ry="3"></ellipse>
<path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"></path>
<path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"></path>
</svg>
</div>
<h3 class="font-medium text-base mb-1 theme-transition" style="color: var(--text-primary);">数据库管理</h3>
<p class="text-xs theme-transition" style="color: var(--text-muted);">查看状态/执行SQL/优化</p>
</a>
<a href="/monitor" class="quick-action stagger-item group" id="monitorLink" style="display: none;">
<div class="w-12 h-12 rounded-xl flex items-center justify-center mb-4 theme-transition"
style="background: var(--info-bg);">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
class="theme-transition group-hover:scale-110 transition-transform" style="color: var(--info-text);">
<path d="M3 3v18h18"/>
<path d="m19 9-5 5-4-4-3 3"/>
</svg>
</div>
<h3 class="font-medium text-base mb-1 theme-transition" style="color: var(--text-primary);">系统监控</h3>
<p class="text-xs theme-transition" style="color: var(--text-muted);">性能指标/趋势图表</p>
</a>
<a href="http://47.112.187.172:4567/share/1n5ih0p3s0/p/-9DQeaLVvLs" class="quick-action stagger-item group">
<div class="w-12 h-12 rounded-xl flex items-center justify-center mb-4 theme-transition"
style="background: var(--warning-bg);">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
class="theme-transition group-hover:scale-110 transition-transform" style="color: var(--warning-text);">
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="16" x2="12" y2="12"></line>
<line x1="12" y1="8" x2="12.01" y2="8"></line>
</svg>
</div>
<h3 class="font-medium text-base mb-1 theme-transition" style="color: var(--text-primary);">帮助文档</h3>
<p class="text-xs theme-transition" style="color: var(--text-muted);">查看使用指南</p>
</a>
</div>
<!-- Loading State -->
<div id="loadingState" class="flex justify-center items-center h-32">
<div class="loading-spinner"></div>
</div>
<!-- Forms List -->
<div id="formsContainer" class="hidden">
<div class="flex justify-between items-center mb-6">
<h3 class="font-serif text-2xl font-medium theme-transition" style="color: var(--text-primary);">表单列表</h3>
<span class="text-sm theme-transition" style="color: var(--text-muted);" id="formCount">0 个表单</span>
</div>
<div id="formsList" class="grid grid-cols-1 lg:grid-cols-2 gap-4">
<!-- Forms will be inserted here -->
</div>
</div>
<!-- Empty State -->
<div id="emptyState" class="hidden text-center py-16">
<div class="w-16 h-16 mx-auto mb-6 rounded-full flex items-center justify-center theme-transition"
style="background: var(--bg-primary);">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
style="color: var(--text-muted);">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
<line x1="16" y1="13" x2="8" y2="13"></line>
<line x1="16" y1="17" x2="8" y2="17"></line>
<polyline points="10 9 9 9 8 9"></polyline>
</svg>
</div>
<h3 class="font-serif text-2xl font-medium mb-2 theme-transition" style="color: var(--text-primary);">暂无表单</h3>
<p class="text-sm mb-6 theme-transition" style="color: var(--text-muted);">点击上方"新建表单"创建第一个表单</p>
<a href="/create"
class="btn btn-primary inline-flex items-center gap-2 px-6 py-3 rounded-xl text-sm font-medium">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="12" y1="5" x2="12" y2="19"></line>
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
新建表单
</a>
</div>
</div>
</main>
<!-- Footer -->
<footer class="fixed bottom-6 w-full text-center pointer-events-none">
<p class="text-[10px] tracking-[0.3em] uppercase font-medium theme-transition" style="color: var(--text-muted);">
Secure Admin Panel</p>
</footer>
<script>
// Page init
let currentUser = null;
// Check auth and load data
async function init() {
try {
const response = await fetch('/api/current_user');
const data = await response.json();
if (!data.logged_in) {
window.location.href = '/login?redirect=/admin';
return;
}
currentUser = data;
// Show user management and database management links for admin
if (data.role === 'admin') {
document.getElementById('userManageLink').style.display = 'block';
document.getElementById('dbManageLink').style.display = 'block';
document.getElementById('monitorLink').style.display = 'block';
}
loadForms();
} catch (error) {
showToast('认证失败', 'error');
setTimeout(() => {
window.location.href = '/login?redirect=/admin';
}, 1500);
}
}
async function loadForms() {
try {
const response = await fetch('/api/admin/forms');
const forms = await response.json();
document.getElementById('loadingState').style.display = 'none';
if (forms.length === 0) {
document.getElementById('emptyState').classList.remove('hidden');
return;
}
document.getElementById('formsContainer').classList.remove('hidden');
document.getElementById('formCount').textContent = `${forms.length} 个表单`;
renderForms(forms);
} catch (error) {
showToast('加载表单失败', 'error');
}
}
function renderForms(forms) {
const container = document.getElementById('formsList');
container.innerHTML = forms.map((form, index) => {
const expiryInfo = form.expiryInfo || {};
const remainingDays = expiryInfo.remaining_days || 0;
const remainingHours = expiryInfo.remaining_hours || 0;
const isExpired = expiryInfo.is_expired || false;
let expiryText = '';
if (expiryInfo.never_expires) {
expiryText = '<span class="text-xs px-2 py-1 rounded-full theme-transition" style="background: var(--success-bg); color: var(--success-text);">永不过期</span>';
} else if (isExpired) {
expiryText = '<span class="text-xs px-2 py-1 rounded-full" style="background: var(--error-bg); color: var(--error-text);">已过期</span>';
} else if (remainingDays > 0) {
expiryText = `<span class="text-xs px-2 py-1 rounded-full theme-transition" style="background: var(--warning-bg); color: var(--warning-text);">${remainingDays}天${remainingHours}小时后过期</span>`;
} else {
expiryText = `<span class="text-xs px-2 py-1 rounded-full" style="background: var(--error-bg); color: var(--error-text);">${remainingHours}小时后过期</span>`;
}
return `
<div class="form-card" style="animation-delay: ${index * 0.05}s">
<div class="flex justify-between items-start mb-4">
<div>
<h4 class="font-medium text-lg mb-1 theme-transition" style="color: var(--text-primary);">${form.title}</h4>
<p class="text-xs theme-transition" style="color: var(--text-muted);">
${form.presetName ? `使用预设: ${form.presetName}` : '使用默认名单'}
</p>
</div>
<div class="flex gap-2 items-center">
<button type="button"
onclick="toggleCollect('${form.id}')"
data-toggle-collect="${form.id}"
data-collecting="${form.collecting !== false ? '1' : '0'}"
title="点击切换收集状态"
class="text-xs px-2.5 py-1 rounded-full inline-flex items-center gap-1.5 font-medium theme-transition"
style="border:1px solid ${form.collecting !== false ? 'var(--success-text)' : 'var(--error-text)'}; color:${form.collecting !== false ? 'var(--success-text)' : 'var(--error-text)'}; background:${form.collecting !== false ? 'var(--success-bg)' : 'var(--error-bg)'}; cursor:pointer;">
<span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${form.collecting !== false ? 'var(--success-text)' : 'var(--error-text)'};"></span>
${form.collecting !== false ? '收集中' : '已停止'}
</button>
${expiryText}
</div>
</div>
<div class="grid grid-cols-3 gap-4 mb-4 py-4 border-y theme-transition" style="border-color: var(--border-color);">
<div class="text-center">
<div class="text-2xl font-semibold theme-transition" style="color: var(--text-primary);">${form.submittedCount}</div>
<div class="text-xs theme-transition" style="color: var(--text-muted);">已提交</div>
</div>
<div class="text-center">
<div class="text-2xl font-semibold theme-transition" style="color: var(--text-primary);">${form.totalStudents}</div>
<div class="text-xs theme-transition" style="color: var(--text-muted);">总人数</div>
</div>
<div class="text-center">
<div class="text-2xl font-semibold theme-transition" style="color: var(--text-primary);">${form.fileCount}</div>
<div class="text-xs theme-transition" style="color: var(--text-muted);">文件数</div>
</div>
</div>
<div class="flex gap-2">
<a href="/status?formId=${form.id}" class="btn btn-manage flex-1 py-2.5 rounded-xl text-xs font-medium text-center">
查看状态
</a>
<a href="/edit/${form.id}" class="btn btn-secondary px-4 py-2.5 rounded-xl text-xs font-medium">
编辑
</a>
<button onclick="deleteForm('${form.id}')" class="btn btn-danger px-4 py-2.5 rounded-xl text-xs font-medium">
删除
</button>
</div>
</div>
`;
}).join('');
// Animate cards
gsap.to(".form-card", {
opacity: 1,
y: 0,
duration: 0.5,
stagger: 0.05,
ease: "power2.out"
});
}
async function deleteForm(formId) {
if (!confirm('确定要删除此表单吗?此操作不可恢复。')) {
return;
}
try {
const response = await fetch(`/api/admin/delete_form/${formId}`, {
method: 'POST'
});
const data = await response.json();
if (data.success) {
showToast('表单已删除', 'success');
loadForms();
} else {
showToast(data.message || '删除失败', 'error');
}
} catch (error) {
showToast('删除失败', 'error');
}
}
async function toggleCollect(formId) {
const btn = document.querySelector(`[data-toggle-collect="${formId}"]`);
const current = btn ? btn.dataset.collecting === '1' : true;
const next = !current;
try {
const response = await fetch(`/api/admin/toggle_collect/${formId}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ collecting: next })
});
const data = await response.json();
if (data.success) {
showToast(data.message || (next ? '已恢复收集' : '已停止收集'), 'success');
loadForms();
} else {
showToast(data.message || '切换失败', 'error');
}
} catch (error) {
showToast('切换失败', 'error');
}
}
// Initial Animation
window.addEventListener('load', () => {
gsap.to("#headerSection", {
opacity: 1,
y: 0,
duration: 0.8,
ease: "power2.out",
delay: 0.1
});
gsap.to(".stagger-item", {
opacity: 1,
y: 0,
duration: 0.6,
stagger: 0.1,
ease: "power2.out",
delay: 0.3
});
init();
});
</script>
</body>
</html>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+2467
View File
File diff suppressed because it is too large Load Diff
+412
View File
@@ -0,0 +1,412 @@
<!DOCTYPE html>
<html lang="zh-CN" class="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>出错了 - 表单管理系统</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
serif: ['Playfair Display', 'serif'],
mono: ['SF Mono', 'monospace'],
},
colors: {
neutral: {
50: '#fafafa',
100: '#f5f5f5',
200: '#e5e5e5',
300: '#d4d4d4',
400: '#a3a3a3',
500: '#737373',
600: '#525252',
700: '#404040',
800: '#262626',
900: '#171717',
}
},
animation: {
'float': 'float 6s ease-in-out infinite',
'pulse-slow': 'pulse 4s cubic-bezier(0.4, 0, 0.6, 1) infinite',
'glitch': 'glitch 1s linear infinite',
},
keyframes: {
float: {
'0%, 100%': { transform: 'translateY(0px)' },
'50%': { transform: 'translateY(-20px)' },
},
glitch: {
'2%, 64%': { transform: 'translate(2px,0) skew(0deg)' },
'4%, 60%': { transform: 'translate(-2px,0) skew(0deg)' },
'62%': { transform: 'translate(0,0) skew(5deg)' },
}
}
}
}
}
</script>
<!-- GSAP -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="/static/js/particles.js"></script>
<link rel="stylesheet" href="/static/css/toast.css">
<script src="/static/js/toast.js"></script>
<link rel="stylesheet" href="/static/css/basic.css">
<link rel="stylesheet" href="/static/css/common.css">
<script src="/static/js/common.js"></script>
<style>
/* ── error 页面专属样式 ── */
body {
background-image:
radial-gradient(at 0% 0%, rgba(220, 38, 38, 0.03) 0px, transparent 50%),
radial-gradient(at 100% 100%, rgba(220, 38, 38, 0.03) 0px, transparent 50%);
}
.dark body {
background-image:
radial-gradient(at 0% 0%, rgba(239, 68, 68, 0.05) 0px, transparent 50%),
radial-gradient(at 100% 100%, rgba(239, 68, 68, 0.05) 0px, transparent 50%);
}
.error-code {
font-family: 'Playfair Display', serif;
font-size: clamp(120px, 20vw, 200px);
font-weight: 600;
line-height: 1;
background: linear-gradient(135deg, var(--error-text) 0%, #991b1b 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
opacity: 0.15;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 0;
pointer-events: none;
user-select: none;
}
.error-content {
position: relative;
z-index: 1;
}
.progress-ring {
transform: rotate(-90deg);
}
.progress-ring-circle {
transition: stroke-dashoffset 0.35s;
transform-origin: 50% 50%;
}
.btn-shine {
position: relative;
overflow: hidden;
}
.btn-shine::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
transition: left 0.5s;
}
.btn-shine:hover::before {
left: 100%;
}
@media (max-width: 768px) {
.error-code {
font-size: 100px;
}
}
</style>
</head>
<body class="antialiased min-h-screen flex items-center justify-center relative">
<!-- Background Elements -->
<div class="fixed inset-0 overflow-hidden pointer-events-none">
<div class="absolute top-1/4 left-1/4 w-96 h-96 bg-red-500/5 rounded-full blur-3xl animate-pulse-slow"></div>
<div class="absolute bottom-1/4 right-1/4 w-96 h-96 bg-orange-500/5 rounded-full blur-3xl animate-pulse-slow"
style="animation-delay: 2s;"></div>
</div>
<!-- Main Content -->
<main class="relative w-full max-w-2xl mx-auto px-6 py-12">
<!-- Error Code Background -->
<div class="error-code" id="errorCodeBg">404</div>
<!-- Card -->
<div class="error-content glass rounded-3xl p-8 md:p-12 shadow-2xl theme-transition" id="mainCard">
<!-- Icon -->
<div class="w-20 h-20 mx-auto mb-8 rounded-2xl flex items-center justify-center theme-transition"
style="background-color: var(--error-bg); border: 1px solid var(--error-border);" id="iconContainer">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
style="color: var(--error-text);" id="errorIcon">
<circle cx="12" cy="12" r="10" />
<line x1="15" y1="9" x2="9" y2="15" />
<line x1="9" y1="9" x2="15" y2="15" />
</svg>
</div>
<!-- Title -->
<h1 class="font-serif text-3xl md:text-4xl font-medium text-center mb-4 tracking-tight theme-transition"
style="color: var(--text-primary);" id="errorTitle">
页面未找到
</h1>
<!-- Description -->
<p class="text-center mb-8 text-sm md:text-base leading-relaxed max-w-md mx-auto theme-transition"
style="color: var(--text-secondary);" id="errorDesc">
您访问的页面不存在或已被移除。请检查链接是否正确,或返回首页继续操作。
</p>
<!-- Error Details (Collapsible) -->
<div class="mb-8 rounded-xl overflow-hidden theme-transition"
style="background-color: var(--bg-primary); border: 1px solid var(--border-color);">
<button onclick="toggleDetails()"
class="w-full px-4 py-3 flex items-center justify-between text-xs font-medium uppercase tracking-wider theme-transition hover:opacity-70"
style="color: var(--text-muted);">
<span>技术详情</span>
<svg id="detailsArrow" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2" class="transform transition-transform duration-300">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
<div id="errorDetails" class="hidden px-4 pb-4">
<div class="font-mono text-xs p-3 rounded-lg theme-transition"
style="background-color: var(--bg-secondary); color: var(--text-muted); border: 1px solid var(--border-color);">
<div class="mb-1"><span style="color: var(--error-text);">Status:</span> <span
id="detailStatus">404 Not Found</span></div>
<div class="mb-1"><span style="color: var(--error-text);">Path:</span> <span
id="detailPath">/unknown</span></div>
<div><span style="color: var(--error-text);">Time:</span> <span id="detailTime">2024-01-01
00:00:00</span></div>
</div>
</div>
</div>
<!-- Countdown Timer -->
<div class="flex items-center justify-center gap-4 mb-8">
<div class="relative w-16 h-16">
<svg class="progress-ring w-16 h-16">
<circle class="progress-ring-circle" stroke="currentColor" stroke-width="3" fill="transparent"
r="28" cx="32" cy="32" style="color: var(--border-color); opacity: 0.3;" />
<circle class="progress-ring-circle" stroke="currentColor" stroke-width="3" fill="transparent"
r="28" cx="32" cy="32" style="color: var(--error-text);" id="progressCircle" />
</svg>
<div class="absolute inset-0 flex items-center justify-center font-mono text-lg font-semibold theme-transition"
style="color: var(--text-primary);" id="countdown">5</div>
</div>
<div class="text-sm theme-transition" style="color: var(--text-muted);">
秒后自动返回首页
</div>
</div>
<!-- Action Buttons -->
<div class="flex flex-col sm:flex-row gap-3 justify-center">
<a href="/" id="homeBtn"
class="btn-shine px-8 py-3 rounded-full text-sm font-medium tracking-wide text-center transform hover:scale-[1.02] active:scale-[0.98] transition-all theme-transition"
style="background-color: var(--accent-bg); color: var(--accent-text);">
立即返回首页
</a>
<button onclick="history.back()"
class="px-8 py-3 rounded-full text-sm font-medium tracking-wide text-center transform hover:scale-[1.02] active:scale-[0.98] transition-all theme-transition"
style="background-color: var(--bg-primary); color: var(--text-secondary); border: 1px solid var(--border-color);">
返回上一页
</button>
</div>
</div>
<!-- Footer -->
<div class="mt-8 text-center">
<p class="text-[10px] tracking-[0.3em] uppercase font-medium theme-transition"
style="color: var(--text-muted);">
Form Admin System
</p>
</div>
</main>
<script>
// Parse URL Parameters for Error Info
function parseErrorInfo() {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code') || '404';
const redirect = urlParams.get('redirect');
const message = urlParams.get('message') || '';
const path = window.location.pathname;
// Error configurations
const errorConfigs = {
'404': {
title: '页面未找到',
desc: '您访问的页面不存在或已被移除。请检查链接是否正确,或返回首页继续操作。',
icon: `<circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>`
},
'403': {
title: '访问被拒绝',
desc: '您没有权限访问此页面。如需帮助,请联系系统管理员。',
icon: `<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>`
},
'500': {
title: '服务器错误',
desc: '服务器遇到了意外情况,无法完成您的请求。请稍后再试。',
icon: `<polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/>`
},
'401': {
title: '未授权',
desc: '您需要先登录才能访问此页面。即将跳转到登录页面。',
icon: `<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/>`
}
};
const config = errorConfigs[code] || errorConfigs['404'];
// Update DOM
document.getElementById('errorCodeBg').textContent = code;
document.getElementById('errorTitle').textContent = message || config.title;
//document.getElementById('errorDesc').textContent = config.desc;
document.getElementById('errorIcon').innerHTML = config.icon;
document.getElementById('detailStatus').textContent = code + ' ' + (config.title === '页面未找到' ? 'Not Found' : config.title);
document.getElementById('detailPath').textContent = path;
document.getElementById('detailTime').textContent = new Date().toLocaleString('zh-CN');
const description = urlParams.get('description');
if (description) {
document.getElementById('errorDesc').textContent = decodeURIComponent(description);
}
// Update redirect target for 401
if (code === '401') {
document.getElementById('homeBtn').href = '/login?redirect=' + encodeURIComponent(path);
}
// 设置首页按钮行为
const homeBtn = document.getElementById('homeBtn');
if (code === '401') {
homeBtn.href = '/login'; // 401 直接回登录,不带任何参数
homeBtn.textContent = '去登录';
} else if (redirect) {
homeBtn.href = redirect; // 其他错误,有指定回跳就回指定页面
} else {
homeBtn.href = '/'; // 默认回首页
}
return code;
}
// Toggle Details
function toggleDetails() {
const details = document.getElementById('errorDetails');
const arrow = document.getElementById('detailsArrow');
details.classList.toggle('hidden');
arrow.style.transform = details.classList.contains('hidden') ? 'rotate(0deg)' : 'rotate(180deg)';
}
// Countdown Logic
let countdown = 5;
const circle = document.getElementById('progressCircle');
const radius = circle.r.baseVal.value;
const circumference = radius * 2 * Math.PI;
circle.style.strokeDasharray = `${circumference} ${circumference}`;
circle.style.strokeDashoffset = circumference;
function setProgress(percent) {
const offset = circumference - percent / 100 * circumference;
circle.style.strokeDashoffset = offset;
}
function startCountdown() {
const timer = setInterval(() => {
countdown--;
document.getElementById('countdown').textContent = countdown;
setProgress((5 - countdown) / 5 * 100);
if (countdown <= 0) {
clearInterval(timer);
const code = document.getElementById('errorCodeBg').textContent;
if (code === '401') {
window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
} else {
window.location.href = '/';
}
}
}, 1000);
}
// Animations
window.addEventListener('load', () => {
parseErrorInfo();
// Animate card entrance
gsap.from("#mainCard", {
y: 30,
opacity: 0,
duration: 0.8,
ease: "power2.out"
});
gsap.from("#iconContainer", {
scale: 0,
rotation: -180,
duration: 0.6,
delay: 0.2,
ease: "back.out(1.7)"
});
gsap.from("#errorTitle", {
y: 20,
opacity: 0,
duration: 0.6,
delay: 0.3,
ease: "power2.out"
});
gsap.from("#errorDesc", {
y: 20,
opacity: 0,
duration: 0.6,
delay: 0.4,
ease: "power2.out"
});
// Start countdown after animation
setTimeout(startCountdown, 1000);
});
// Hover effect for error code
document.getElementById('errorCodeBg').addEventListener('mouseenter', function () {
gsap.to(this, {
scale: 1.1,
opacity: 0.2,
duration: 0.3
});
});
document.getElementById('errorCodeBg').addEventListener('mouseleave', function () {
gsap.to(this, {
scale: 1,
opacity: 0.15,
duration: 0.3
});
});
</script>
</body>
</html>
+4522
View File
File diff suppressed because it is too large Load Diff
+194
View File
@@ -0,0 +1,194 @@
<!DOCTYPE html>
<html lang="zh-CN" class="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>登录 - 表单管理系统</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
serif: ['Playfair Display', 'serif'],
}
}
}
}
</script>
<!-- GSAP -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<!-- Particles -->
<script src="/static/js/particles.js"></script>
<!-- Toast -->
<script src="/static/js/toast.js"></script>
<link rel="stylesheet" href="/static/css/toast.css">
<!-- Basic & Common Styles -->
<link rel="stylesheet" href="/static/css/basic.css">
<link rel="stylesheet" href="/static/css/common.css">
<!-- Common JS (theme init, utils) -->
<script src="/static/js/common.js"></script>
<style>
/* ── login 页面专属样式 ── */
.input-wrapper {
position: relative;
background-color: var(--input-bg);
border: 2px solid var(--input-border);
border-radius: 12px;
transition: all 0.3s ease;
}
.input-wrapper:focus-within {
border-color: var(--text-primary);
box-shadow: 0 0 0 3px var(--shadow-color);
}
.input-field {
background: transparent;
border: none;
color: var(--input-text);
width: 100%;
padding: 14px 16px;
font-size: 15px;
font-weight: 500;
outline: none;
}
.input-field::placeholder {
color: var(--text-muted);
opacity: 0.8;
}
</style>
</head>
<body class="antialiased min-h-screen flex items-center justify-center relative">
<!-- Main Content -->
<main class="relative z-10 w-full max-w-md mx-auto px-6 py-12">
<div id="loginCard" class="glass rounded-3xl p-8 md:p-10 shadow-2xl opacity-0 transform translate-y-8">
<div class="text-center mb-10">
<h1 class="font-serif text-3xl font-semibold tracking-tight mb-2" style="color: var(--text-primary);">
Form Admin
</h1>
<p class="text-xs tracking-[0.2em] uppercase font-medium" style="color: var(--text-muted);">
Secure Login
</p>
<div class="w-16 h-[2px] mx-auto mt-4" style="background-color: var(--border-color);"></div>
</div>
<form id="loginForm" class="space-y-6">
<div class="space-y-2">
<label class="block text-xs font-semibold tracking-wide uppercase"
style="color: var(--text-secondary);">
用户名
</label>
<div class="input-wrapper">
<input type="text" id="username" placeholder="请输入用户名" required autofocus class="input-field"
autocomplete="username">
</div>
</div>
<div class="space-y-2">
<label class="block text-xs font-semibold tracking-wide uppercase"
style="color: var(--text-secondary);">
密码
</label>
<div class="input-wrapper">
<input type="password" id="password" placeholder="请输入密码" required class="input-field"
autocomplete="current-password">
</div>
</div>
<div class="flex items-center justify-between text-xs pt-2">
<label class="flex items-center cursor-pointer">
<input type="checkbox" id="remember" class="mr-2 accent-gray-900 dark:accent-white">
<span style="color: var(--text-secondary);">记住我</span>
</label>
<button type="button" onclick="showToast('请联系管理员重置密码', 'error')"
class="font-medium hover:opacity-70 transition-opacity text-xs"
style="color: var(--text-muted);">
忘记密码?
</button>
</div>
<button type="submit" id="loginBtn"
class="btn-primary w-full py-4 rounded-xl text-sm font-semibold tracking-wide uppercase flex items-center justify-center mt-8">
<span id="btnText">登录</span>
</button>
</form>
<div class="mt-8 pt-6 border-t text-center" style="border-color: var(--border-color);">
<div class="flex items-center justify-center gap-2 text-[10px] tracking-[0.2em] uppercase font-medium"
style="color: var(--text-muted);">
<span>Secure Admin Panel</span>
<span>•</span>
<span id="clock">00:00</span>
</div>
</div>
</div>
</main>
<script>
// Clock
setInterval(() => {
document.getElementById('clock').textContent =
new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false });
}, 1000);
// GSAP
window.addEventListener('load', () => {
gsap.to("#loginCard", { opacity: 1, y: 0, duration: 0.8, ease: "power2.out", delay: 0.2 });
});
// Form
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = document.getElementById('loginBtn');
const btnText = document.getElementById('btnText');
btn.disabled = true;
btnText.innerHTML = '登录中<span class="loading-spinner"></span>';
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: document.getElementById('username').value.trim(),
password: document.getElementById('password').value,
remember: document.getElementById('remember').checked
})
});
const data = await res.json();
if (data.success) {
showToast('登录成功', 'success');
setTimeout(() => location.href = data.redirect || '/admin', 500);
} else {
showToast(data.message, 'error');
btn.disabled = false;
btnText.textContent = '重新登录';
}
} catch {
showToast('网络错误', 'error');
btn.disabled = false;
btnText.textContent = '重新登录';
}
});
</script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+151
View File
@@ -0,0 +1,151 @@
<!doctype html>
<html lang="zh-CN" class="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<title>文字动效实验室 · Form System</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Inter:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;600;700&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
<script src="/static/vendor/charwrapper.min.js"></script>
<script src="https://unpkg.com/split-type@0.3.4/umd/index.min.js"></script>
<style>
:root{color-scheme:dark;--bg:#081321;--panel:#101f33;--panel2:#142740;--line:#263d5c;--ink:#eef4ff;--muted:#9aacc5;--soft:#7085a3;--blue:#91b2ff;--cyan:#65d8d0;--amber:#ffc66e;--mono:'DM Mono',monospace;--sans:Inter,'Noto Sans SC',sans-serif}
*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:radial-gradient(ellipse at 78% -15%,#1c3760 0,transparent 42%),radial-gradient(ellipse at 2% 70%,#122741 0,transparent 34%),var(--bg);color:var(--ink);font:15px/1.65 var(--sans);min-height:100vh}body:before{content:"";position:fixed;inset:0;pointer-events:none;opacity:.17;background-image:radial-gradient(#8298b8 1px,transparent 1px);background-size:46px 46px;mask-image:linear-gradient(to bottom,#000,transparent 78%)}
.topbar{height:66px;border-bottom:1px solid #253956;background:#0d1b2dcc;backdrop-filter:blur(18px);display:flex;align-items:center;justify-content:space-between;padding:0 max(24px,calc((100vw - 1120px)/2));position:sticky;top:0;z-index:10}.brand{font:500 12px var(--mono);letter-spacing:.28em;color:#d9e5fa}.topmeta{font:11px var(--mono);color:var(--soft);letter-spacing:.1em}.wrap{width:min(100% - 40px,1040px);margin:auto;position:relative}.hero{padding:76px 0 34px}.eyebrow{display:flex;align-items:center;gap:10px;color:var(--blue);font-size:11px;font-weight:700;letter-spacing:.18em;text-transform:uppercase}.dot{width:8px;height:8px;border-radius:50%;background:var(--blue);box-shadow:0 0 15px #91b2ff}.hero h1{font-size:clamp(36px,6vw,66px);letter-spacing:-.055em;line-height:1.08;margin:18px 0 16px;max-width:760px}.hero p{color:var(--muted);font-size:16px;max-width:680px;margin:0}.hero-note{margin-top:25px;padding:15px 18px;border:1px solid #2a4262;background:#102039a8;border-radius:14px;color:#aebed3;font-size:13px;display:flex;gap:12px;align-items:flex-start}.hero-note b{color:var(--blue);font:11px var(--mono);letter-spacing:.1em;white-space:nowrap;padding-top:3px}
.stack{display:grid;gap:18px;padding:20px 0 80px}.card{position:relative;overflow:hidden;background:linear-gradient(145deg,#13253bfa,#0e1c2ff5);border:1px solid #29415f;border-radius:22px;padding:clamp(22px,4vw,38px);box-shadow:0 22px 70px #0209145c}.card:after{content:"";position:absolute;right:-80px;top:-100px;width:250px;height:250px;border-radius:50%;background:#8bb0ff0b;filter:blur(22px);pointer-events:none}.card-head{display:flex;align-items:flex-start;justify-content:space-between;gap:20px;position:relative;z-index:1}.tag{display:inline-flex;align-items:center;gap:8px;font:11px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--blue)}.tag i{font-style:normal;color:#778daa}.card h2{font-size:23px;letter-spacing:-.03em;margin:8px 0 6px}.desc{color:var(--muted);font-size:13px;margin:0;max-width:650px}.repo{font:11px var(--mono);color:#a9bad2;text-decoration:none;border:1px solid #304968;border-radius:999px;padding:8px 12px;white-space:nowrap;transition:.2s}.repo:hover{border-color:var(--blue);color:var(--blue);transform:translateY(-1px)}
.demo{margin-top:24px;padding:22px;border:1px solid #293f5d;border-radius:16px;background:#091728a8;position:relative;z-index:1}.demo-label{font:10px var(--mono);letter-spacing:.14em;color:#7489a5;text-transform:uppercase;margin-bottom:13px}.demo-line{display:flex;align-items:center;gap:16px;flex-wrap:wrap}.sample{min-height:54px;display:flex;align-items:center;font-size:clamp(24px,4vw,36px);font-weight:600;letter-spacing:-.035em;line-height:1.35}.sample.small{font-size:20px}.sample .char{display:inline-block;white-space:pre}.sample .char-add{color:var(--cyan)}.sample .char-remove{color:#f38e9e}.sample .char-add,.sample .char-remove{overflow:hidden}.pill{font:11px var(--mono);color:#a9bad2;background:#142741;border:1px solid #2a4261;border-radius:999px;padding:6px 10px}.controls{display:flex;gap:9px;flex-wrap:wrap;margin-top:18px}.btn{appearance:none;border:1px solid #385376;background:#142943;color:#dce8fa;padding:10px 15px;border-radius:999px;font:600 12px var(--sans);cursor:pointer;transition:transform .2s,border-color .2s,background .2s}.btn:hover{transform:translateY(-2px);border-color:#91b2ff;background:#1b3555}.btn.primary{background:var(--blue);border-color:var(--blue);color:#0a1a31}.btn.primary:hover{background:#b0c7ff}.btn:focus-visible{outline:2px solid #fff;outline-offset:3px}.explain{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-top:20px}.fact{padding:12px 14px;border-left:2px solid #385575;background:#102139;border-radius:0 10px 10px 0;color:#9eafc6;font-size:12px}.fact strong{display:block;color:#dfe9f8;font-size:12px;margin-bottom:3px}.readout{font:12px var(--mono);color:#d2e2fa;min-width:78px}.split-phrase{font-size:clamp(27px,4vw,38px);font-weight:600;letter-spacing:.01em}.split-phrase .char{display:inline-block;will-change:transform,opacity}.counter{display:flex;align-items:center;gap:5px;min-height:64px;font:600 clamp(28px,5vw,54px)/1 var(--mono);font-variant-numeric:tabular-nums;color:var(--blue)}.roller-cell{display:inline-flex;align-items:center;justify-content:center;overflow:hidden;min-width:.68em;height:1.18em;padding:0 .08em;border:1px solid #385274;border-radius:9px;background:linear-gradient(180deg,#1a304c,#102239);box-shadow:inset 0 1px #ffffff0b,0 5px 15px #02091430;will-change:transform}.roller-cell.is-cjk{min-width:1.08em;font-family:var(--sans);font-size:.8em;font-weight:700}.roller-cell.is-separator{min-width:.28em;padding:0;border-color:transparent;background:transparent;box-shadow:none;color:#8095b2}.roller-cell.cell-enter{animation:cell-enter .5s cubic-bezier(.2,.85,.25,1.2) both}@keyframes cell-enter{from{opacity:0;transform:translateY(55%) scale(.82);filter:blur(5px)}to{opacity:1;transform:translateY(0) scale(1);filter:blur(0)}}.counter-wrap{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.unit{color:var(--muted);font-size:15px}.lib-status{font:10px var(--mono);color:var(--soft);margin-top:12px}.lib-status[data-state="error"]{color:#ff9eaa}.lib-status[data-state="ok"]{color:#8fddbd}.footer{color:#617792;text-align:center;font:10px var(--mono);letter-spacing:.12em;padding:0 0 36px}
@media(max-width:680px){.topbar{height:58px;padding:0 20px}.topmeta{display:none}.wrap{width:min(100% - 28px,1040px)}.hero{padding:55px 0 24px}.card-head{display:block}.repo{display:inline-flex;margin-top:14px}.demo{padding:18px 15px}.explain{grid-template-columns:1fr}.hero-note{display:block}.hero-note b{display:block;margin-bottom:4px}}
@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}}
</style>
<style>
/* Metamorphosis owns the segment layout; style each generated glyph without splitting control. */
#rollCounter{display:block;min-height:64px;font:600 clamp(28px,5vw,54px)/1.18 var(--mono);font-variant-numeric:tabular-nums;letter-spacing:normal;white-space:nowrap;color:var(--blue)}
#rollCounter .metamorphosis-item{display:inline-block;vertical-align:baseline;min-width:.66em;padding:0 .025em;margin-inline:.015em;text-align:center;border:1px solid #385274;border-radius:7px;background:linear-gradient(180deg,#1a304c,#102239);box-shadow:inset 0 1px #ffffff0b;will-change:transform,opacity}
</style>
</head>
<body>
<header class="topbar"><div class="brand">FORM SYSTEM <span style="color:#7085a3">/ MOTION LAB</span></div><div class="topmeta">TEXT TRANSITION STUDIES&nbsp;&nbsp;·&nbsp;&nbsp;001—003</div></header>
<main class="wrap">
<section class="hero">
<div class="eyebrow"><span class="dot"></span> TYPE IN MOTION / INTERACTIVE STUDY</div>
<h1>让变化的文字,<br>自己动起来。</h1>
<p>三个开源库,三种文字变化方式。点按钮试试看:智能识别增删、老虎机数字滚动,以及拆字后的自定义入场动效。</p>
<div class="hero-note"><b>HOW TO READ</b><span>这页是可操作的对比样例。每个模块都用真实库驱动;如果浏览器无法访问 CDN,会在模块下方显示加载状态。</span></div>
</section>
<section class="stack" aria-label="文字动画库示例">
<article class="card">
<div class="card-head"><div><div class="tag">01 <i>/ SMART DIFF</i></div><h2>字符增删 · 平滑让位</h2><p class="desc">适合状态文案或短句变化。尝试让“文字”变为“文1字”,保留匹配字符,只为新增字符做入场,邻字随排版自然让位。</p></div><a class="repo" href="https://github.com/rowild/charwrapper" target="_blank" rel="noreferrer">GITHUB ↗</a></div>
<div class="demo"><div class="demo-label">LIVE TRANSITION / CHARWRAPPER + GSAP</div><div class="demo-line"><div class="sample" id="smartText" aria-live="polite">文字</div><span class="pill">新增字符从下方进入</span></div><div class="controls"><button class="btn primary" id="smartInsert">插入「1」</button><button class="btn" id="smartRemove">恢复「文字」</button><button class="btn" id="smartPhrase">试试另一句</button></div><div class="lib-status" id="charStatus" role="status">正在加载 CharWrapper…</div></div>
<div class="explain"><div class="fact"><strong>智能匹配</strong>优先复用前后两版中相同的字符。</div><div class="fact"><strong>变化处才动</strong>可设置新增、删除时长与错开间隔。</div><div class="fact"><strong>调用方式</strong>文字更新时调用 transitionTo;不是全页自动监听。</div></div>
</article>
<article class="card">
<div class="card-head"><div><div class="tag">02 <i>/ CASCADE ROLL</i></div><h2>逐字滚动 · 中文也能用</h2><p class="desc">中文汉字和数字都按字素分段。库会为每个字生成独立的 DOM 节点,同时由一个控制器协调整句排版和级联动画,让相邻字符移动得更连贯。</p></div><a class="repo" href="https://github.com/olicarignan/metamorphosis" target="_blank" rel="noreferrer">GITHUB ↗</a></div>
<div class="demo"><div class="demo-label">LIVE TRANSITION / METAMORPHOSIS · ONE SEGMENT PER GLYPH</div><div class="demo-line counter-wrap"><div class="counter" id="rollCounter" aria-live="polite"></div><span class="unit" id="rollUnit">次提交</span><span class="pill" id="rollMode">数字模式 · 按位滚动</span></div><div class="controls"><button class="btn primary" id="rollNext">增加数值</button><button class="btn" id="rollRandom">随机跳转</button><button class="btn" id="rollReset">重置</button><button class="btn" id="rollChinese" aria-pressed="false">循环处理中…</button></div><div class="lib-status" id="morphStatus" role="status">正在加载 Metamorphosis…</div></div>
<div class="explain"><div class="fact"><strong>逐字素切分</strong>“提交成功”会成为四个独立的字素节点。</div><div class="fact"><strong>独立样式,统一编排</strong>每字可用 CSS 单独设样式,控制器负责同步更新与错峰。</div><div class="fact"><strong>顺序与布局</strong>一条文本用一个控制器,库自动测量新旧位置并平滑让位。</div></div>
</article>
<article class="card">
<div class="card-head"><div><div class="tag">03 <i>/ SPLIT & ANIMATE</i></div><h2>拆开文字 · 自由编排</h2><p class="desc">SplitType 把文字拆成可单独控制的字符节点,再交给 GSAP 做淡入、上移和错峰。适合标题入场、提示文案和一次性的强调动画。</p></div><a class="repo" href="https://github.com/lukePeavey/SplitType" target="_blank" rel="noreferrer">GITHUB ↗</a></div>
<div class="demo"><div class="demo-label">LIVE REVEAL / SPLITTYPE + GSAP</div><div class="demo-line"><div class="sample split-phrase" id="splitText">每个字符都能独立起舞</div><span class="pill">逐字错峰揭示</span></div><div class="controls"><button class="btn primary" id="splitReplay">重新播放</button><button class="btn" id="splitSwap">换一句</button></div><div class="lib-status" id="splitStatus" role="status">正在加载 SplitType…</div></div>
<div class="explain"><div class="fact"><strong>粒度清晰</strong>拆成字符、词或行,逐个取得元素。</div><div class="fact"><strong>动画自由</strong>配合 GSAP、CSS 或 Web Animations API。</div><div class="fact"><strong>需要手动更新</strong>文本变化后重新拆分,再启动目标动画。</div></div>
</article>
</section>
<footer class="footer">FORM SYSTEM · MOTION EXPERIMENTS · RESPECT REDUCED MOTION</footer>
</main>
<script type="module">
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
const setStatus = (id, message, state='ok') => { const el=document.getElementById(id); el.textContent=message; el.dataset.state=state; };
const safeGsap = window.gsap;
// 01 — CharWrapper keeps matched glyphs and animates only insertions/removals.
const smartEl=document.getElementById('smartText');
let charWrapper=null, smartValue='文字';
try {
if (!window.CharWrapper) throw new Error('CharWrapper 加载失败:上游仓库没有发布 npm/CDN 构建文件');
if (!safeGsap) throw new Error('GSAP 未加载,请检查 CDN 网络连接');
charWrapper=new window.CharWrapper(smartEl,{wrap:{chars:true}});
charWrapper.wrap();
setStatus('charStatus','已就绪 · 点击按钮触发 transitionTo()');
} catch(e) { setStatus('charStatus',e.message,'error'); }
function smartTo(next){
if(!charWrapper)return;
smartValue=next;
charWrapper.transitionTo(next,{strategy:'smart',addDuration:.52,removeDuration:.32,stagger:.035,ease:'power3.out'});
}
document.getElementById('smartInsert').onclick=()=>smartTo('文1字');
document.getElementById('smartRemove').onclick=()=>smartTo('文字');
document.getElementById('smartPhrase').onclick=()=>smartTo(smartValue==='报名成功!'?'表单已提交':'报名成功!');
// 02 — One controller coordinates the library's per-grapheme DOM segments.
const rollRoot=document.getElementById('rollCounter');
let morphController=null, count=8042, dotTimer=null, dotStateIndex=0;
function updateRollingText(value){
if(!morphController)return;
rollRoot.setAttribute('aria-label',value);
morphController.update(value);
}
function showNumber(value){
stopProcessingLoop();
count=value;
document.getElementById('rollUnit').textContent='次提交';
document.getElementById('rollMode').textContent='数字模式 · 按位滚动';
updateRollingText(count.toLocaleString('en-US'));
}
function showChinese(){
if(dotTimer){stopProcessingLoop();return;}
const states=['处理中.','处理中..','处理中...'];
dotStateIndex=0;
document.getElementById('rollUnit').textContent='中文文案';
document.getElementById('rollMode').textContent='循环切换 · 900 ms';
document.getElementById('rollChinese').textContent='停止循环';
document.getElementById('rollChinese').setAttribute('aria-pressed','true');
updateRollingText(states[dotStateIndex]);
dotTimer=setInterval(()=>{
dotStateIndex=(dotStateIndex+1)%states.length;
updateRollingText(states[dotStateIndex]);
},900);
}
function stopProcessingLoop(){
if(dotTimer){clearInterval(dotTimer);dotTimer=null;}
const button=document.getElementById('rollChinese');
if(button){button.textContent='循环处理中…';button.setAttribute('aria-pressed','false');}
}
try {
const {MorphController}=await import('https://esm.sh/@ocarignan/metamorphosis@latest');
morphController=new MorphController();
morphController.attach(rollRoot,{
granularity:'grapheme',locale:'zh-CN',cascade:true,enterSlide:24,stagger:30,
duration:460,ease:'cubic-bezier(.2,.8,.2,1)',respectReducedMotion:true
});
showNumber(count);
setStatus('morphStatus','已就绪 · 单控制器协调整行逐字滚动');
} catch(e) { setStatus('morphStatus','加载失败:'+e.message,'error'); }
function updateCount(value){if(!morphController)return;showNumber(value);}
document.getElementById('rollNext').onclick=()=>updateCount(count+Math.ceil(Math.random()*917));
document.getElementById('rollRandom').onclick=()=>updateCount(Math.floor(120+Math.random()*120000));
document.getElementById('rollReset').onclick=()=>updateCount(8042);
document.getElementById('rollChinese').onclick=()=>{if(morphController)showChinese()};
// 03 — SplitType only splits; GSAP provides the actual reveal choreography.
const splitEl=document.getElementById('splitText');
let splitInstance=null, splitToggle=false;
function replaySplit(){
if(!window.SplitType||!safeGsap)return;
if(splitInstance)splitInstance.revert();
splitInstance=new window.SplitType(splitEl,{types:'words, chars',tagName:'span'});
safeGsap.killTweensOf(splitInstance.chars);
safeGsap.fromTo(splitInstance.chars,{yPercent:110,opacity:0,rotateX:-45},{yPercent:0,opacity:1,rotateX:0,duration:reduced?0:.62,stagger:reduced?0:.025,ease:'power3.out',clearProps:'transform,opacity'});
}
if(window.SplitType&&safeGsap){setStatus('splitStatus','已就绪 · 拆分字符后用 GSAP 编排');requestAnimationFrame(replaySplit)}
else setStatus('splitStatus','SplitType 或 GSAP 未能从 CDN 加载','error');
document.getElementById('splitReplay').onclick=replaySplit;
document.getElementById('splitSwap').onclick=()=>{splitToggle=!splitToggle; if(splitInstance)splitInstance.revert();splitEl.textContent=splitToggle?'变化也可以很有节奏':'每个字符都能独立起舞';replaySplit()};
window.addEventListener('pagehide',()=>{stopProcessingLoop();morphController?.destroy()});
</script>
</body>
</html>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+846
View File
@@ -0,0 +1,846 @@
<!DOCTYPE html>
<html lang="zh-CN" class="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>用户管理 - 表单管理系统</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
serif: ['Playfair Display', 'serif'],
},
colors: {
neutral: {
50: '#fafafa',
100: '#f5f5f5',
200: '#e5e5e5',
300: '#d4d4d4',
400: '#a3a3a3',
500: '#737373',
600: '#525252',
700: '#404040',
800: '#262626',
900: '#171717',
}
}
}
}
}
</script>
<!-- GSAP for animations -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="/static/js/particles.js"></script>
<script src="/static/js/toast.js"></script>
<link rel="stylesheet" href="/static/css/basic.css">
<link rel="stylesheet" href="/static/css/common.css">
<script src="/static/js/common.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:ital,wght@0,400;0,600;1,400&display=swap');
@import url('/static/css/toast.css');
* {
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
body {
font-family: 'Inter', sans-serif;
background-color: var(--bg-primary);
background-image:
radial-gradient(at 0% 0%, rgba(128,128,128,0.03) 0px, transparent 50%),
radial-gradient(at 100% 100%, rgba(128,128,128,0.03) 0px, transparent 50%);
color: var(--text-primary);
margin: 0;
min-height: 100vh;
overflow-x: hidden;
transition: background-color 0.5s ease, color 0.5s ease;
}
.dark body {
background-image:
radial-gradient(at 0% 0%, rgba(255,255,255,0.02) 0px, transparent 50%),
radial-gradient(at 100% 100%, rgba(255,255,255,0.02) 0px, transparent 50%);
}
.glass {
background: var(--glass-bg);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid var(--glass-border);
transition: all 0.3s ease;
}
.glass:hover {
background: var(--glass-hover);
}
.theme-transition {
transition: background-color 0.5s ease, color 0.5s ease, border-color 0.5s ease, box-shadow 0.5s ease;
}
/* User Card */
.user-card {
background: var(--glass-bg);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid var(--glass-border);
border-radius: 24px;
padding: 24px;
transition: all 0.4s cubic-bezier(0.2, 0, 0, 1);
opacity: 0;
transform: translateY(20px);
}
.user-card:hover {
transform: translateY(-4px);
box-shadow: 0 20px 40px -15px var(--shadow-color);
border-color: rgba(128,128,128,0.3);
background: var(--glass-hover);
}
/* Role Badge */
.role-badge {
display: inline-flex;
align-items: center;
padding: 4px 12px;
border-radius: 9999px;
font-size: 10px;
font-weight: 600;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.role-admin {
background: var(--error-bg);
color: var(--error-text);
border: 1px solid var(--error-border);
}
.role-user {
background: rgba(99, 102, 241, 0.1);
color: #6366f1;
border: 1px solid rgba(99, 102, 241, 0.2);
}
.dark .role-user {
background: rgba(99, 102, 241, 0.2);
color: #818cf8;
border-color: rgba(99, 102, 241, 0.3);
}
/* Buttons */
.btn {
position: relative;
overflow: hidden;
transition: all 0.3s cubic-bezier(0.2, 0, 0, 1);
}
.btn::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(128,128,128,0.1), transparent);
transition: left 0.5s;
}
.btn:hover::before {
left: 100%;
}
.btn-primary {
background-color: var(--accent-bg);
color: var(--accent-text);
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 10px 20px -5px var(--shadow-color);
}
.btn-secondary {
background-color: var(--bg-primary);
color: var(--text-secondary);
border: 1px solid var(--border-color);
}
.btn-secondary:hover {
background-color: var(--bg-secondary);
transform: translateY(-2px);
}
.btn-manage {
background-color: rgba(99, 102, 241, 0.1);
color: #6366f1;
border: 1px solid rgba(99, 102, 241, 0.2);
}
.btn-manage:hover {
background-color: rgba(99, 102, 241, 0.2);
transform: translateY(-2px);
}
.btn-danger {
background-color: var(--danger-bg);
color: var(--danger-text);
border: 1px solid var(--error-border);
}
.btn-danger:hover {
opacity: 0.8;
transform: translateY(-2px);
}
.btn-danger:disabled {
opacity: 0.4;
cursor: not-allowed;
transform: none;
}
/* Modal */
.modal-overlay {
position: fixed;
inset: 0;
z-index: 5000;
display: none;
align-items: center;
justify-content: center;
background: rgba(0,0,0,0.4);
backdrop-filter: blur(12px);
opacity: 0;
transition: opacity 0.3s ease;
}
.modal-overlay.show {
display: flex;
opacity: 1;
}
.modal-box {
background: var(--bg-secondary);
border: 1px solid var(--glass-border);
border-radius: 24px;
padding: 32px;
width: 90%;
max-width: 480px;
max-height: 90vh;
overflow-y: auto;
transform: scale(0.95);
transition: transform 0.3s cubic-bezier(0.2, 0, 0, 1);
}
.modal-overlay.show .modal-box {
transform: scale(1);
}
@media (max-width: 640px) {
.modal-box {
width: 100%;
max-width: none;
max-height: 100vh;
border-radius: 24px 24px 0 0;
margin-top: auto;
padding: 24px;
}
.modal-overlay {
align-items: flex-end;
}
}
/* Form Elements */
.input-field {
background-color: var(--bg-primary);
border: 2px solid var(--border-color);
border-radius: 12px;
color: var(--text-primary);
width: 100%;
padding: 14px 16px;
font-size: 15px;
font-weight: 500;
outline: none;
transition: all 0.3s ease;
}
.input-field:focus {
border-color: var(--text-primary);
box-shadow: 0 0 0 4px var(--shadow-color);
}
.input-field::placeholder {
color: var(--text-muted);
}
.checkbox-group {
display: flex;
flex-direction: column;
gap: 8px;
max-height: 200px;
overflow-y: auto;
padding: 12px;
background: var(--bg-primary);
border-radius: 12px;
border: 1px solid var(--border-color);
}
.checkbox-item {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 12px;
border-radius: 10px;
cursor: pointer;
transition: all 0.2s;
font-size: 14px;
color: var(--text-secondary);
}
.checkbox-item:hover {
background: var(--bg-secondary);
}
.checkbox-item input[type="checkbox"] {
width: 18px;
height: 18px;
accent-color: var(--accent-bg);
cursor: pointer;
}
/* Loading */
.loading-spinner {
width: 40px;
height: 40px;
border: 3px solid var(--border-color);
border-top-color: var(--text-primary);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Scrollbar */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-muted);
}
</style>
</head>
<body class="antialiased min-h-screen relative">
<!-- Header -->
<header class="fixed top-0 w-full z-40 px-4 sm:px-6 py-4 sm:py-5 glass theme-transition border-b">
<div class="max-w-6xl mx-auto flex justify-between items-center">
<!-- 左侧:面包屑 -->
<div class="flex items-center gap-2">
<a href="/admin" class="nav-link flex items-center gap-1.5">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/>
<rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/>
</svg>
<span class="hidden sm:inline text-sm">管理后台</span>
</a>
<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" style="color:var(--text-muted);opacity:0.4">
<path d="m9 18 6-6-6-6"/>
</svg>
<span class="text-sm font-medium" style="color:var(--text-primary)">用户管理</span>
</div>
<div class="flex items-center gap-2 sm:gap-3">
<a href="/admin" class="btn btn-secondary px-4 py-2.5 rounded-full text-xs sm:text-sm font-medium tracking-wide flex items-center gap-2">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M19 12H5M12 19l-7-7 7-7"/>
</svg>
<span class="hidden sm:inline">返回</span>
</a>
<button onclick="showAddUserModal()" class="btn btn-primary px-4 py-2.5 rounded-full text-xs sm:text-sm font-medium tracking-wide flex items-center gap-2">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
<line x1="12" y1="5" x2="12" y2="19"></line>
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
<span class="hidden sm:inline">添加用户</span>
</button>
</div>
</div>
</header>
<!-- Main Content -->
<main class="relative pt-28 sm:pt-36 pb-24 px-4 sm:px-6">
<div class="max-w-6xl mx-auto">
<!-- Header Section -->
<div class="mb-8 sm:mb-12 opacity-0" id="headerSection">
<h2 class="font-serif text-3xl sm:text-4xl font-medium tracking-tight mb-3 theme-transition" style="color: var(--text-primary);">
用户管理
</h2>
<p class="text-sm leading-relaxed max-w-md tracking-wide font-light theme-transition" style="color: var(--text-secondary);">
管理系统用户账号,分配表单管理权限,保障系统安全。
</p>
</div>
<!-- Loading State -->
<div id="loading" class="flex justify-center items-center h-64">
<div class="loading-spinner"></div>
</div>
<!-- Users Grid -->
<div id="usersContainer" class="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6" style="display: none;"></div>
<!-- Empty State -->
<div id="emptyState" class="hidden text-center py-24">
<div class="w-16 h-16 mx-auto mb-6 rounded-full flex items-center justify-center theme-transition" style="background-color: var(--bg-primary);">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="color: var(--text-muted);">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
</div>
<h3 class="font-serif text-2xl font-medium mb-2 theme-transition" style="color: var(--text-primary);">暂无用户</h3>
<p class="text-sm theme-transition" style="color: var(--text-muted);">点击上方按钮添加第一个用户</p>
</div>
</div>
</main>
<!-- Footer -->
<footer class="fixed bottom-6 w-full text-center pointer-events-none">
<p class="text-[10px] tracking-[0.3em] uppercase font-medium theme-transition" style="color: var(--text-muted);">Secure Admin Panel</p>
</footer>
<!-- Add User Modal -->
<div class="modal-overlay" id="addUserModal">
<div class="modal-box">
<div class="flex justify-between items-center mb-6">
<h3 class="font-serif text-xl font-semibold theme-transition" style="color: var(--text-primary);">添加新用户</h3>
<button onclick="closeAddUserModal()" class="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors" style="color: var(--text-muted);">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
</div>
<div class="space-y-5">
<div>
<label class="block text-xs font-semibold tracking-wide uppercase mb-2 theme-transition" style="color: var(--text-secondary);">
用户名
</label>
<input type="text" id="newUsername" placeholder="请输入用户名" maxlength="20" class="input-field">
</div>
<div>
<label class="block text-xs font-semibold tracking-wide uppercase mb-2 theme-transition" style="color: var(--text-secondary);">
密码
</label>
<input type="password" id="newPassword" placeholder="请输入密码(至少6位)" minlength="6" class="input-field">
</div>
<div>
<label class="block text-xs font-semibold tracking-wide uppercase mb-2 theme-transition" style="color: var(--text-secondary);">
角色
</label>
<select id="userRole" class="input-field cursor-pointer">
<option value="user">普通用户</option>
<option value="admin">管理员</option>
</select>
</div>
</div>
<div class="flex gap-3 mt-8">
<button onclick="closeAddUserModal()" class="btn btn-secondary flex-1 py-3 rounded-xl text-sm font-medium">
取消
</button>
<button onclick="addUser()" class="btn btn-primary flex-1 py-3 rounded-xl text-sm font-medium">
添加
</button>
</div>
</div>
</div>
<!-- Permissions Modal -->
<div class="modal-overlay" id="permsModal">
<div class="modal-box">
<div class="flex justify-between items-center mb-6">
<h3 class="font-serif text-xl font-semibold theme-transition" style="color: var(--text-primary);">
表单权限 - <span id="permsUsername" class="text-base font-normal" style="color: var(--text-secondary);"></span>
</h3>
<button onclick="closePermsModal()" class="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors" style="color: var(--text-muted);">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
</div>
<div class="mb-4">
<label class="block text-xs font-semibold tracking-wide uppercase mb-3 theme-transition" style="color: var(--text-secondary);">
选择可管理的表单
</label>
<div class="checkbox-group" id="formsCheckboxes">
<!-- Checkboxes will be inserted here -->
</div>
</div>
<div class="flex gap-3 mt-6">
<button onclick="closePermsModal()" class="btn btn-secondary flex-1 py-3 rounded-xl text-sm font-medium">
取消
</button>
<button onclick="saveUserPerms()" class="btn btn-primary flex-1 py-3 rounded-xl text-sm font-medium">
保存权限
</button>
</div>
</div>
</div>
<script>
// Global Variables
let currentManageUsername = '';
let allForms = [];
// Check Admin Permission
async function checkAdmin() {
try {
const response = await fetch('/api/current_user');
const data = await response.json();
if (!data.logged_in || data.role !== 'admin') {
showToast('需要管理员权限', 'error');
setTimeout(() => window.location.href = '/admin', 1000);
return;
}
loadUsers();
} catch (error) {
console.error('检查权限失败:', error);
window.location.href = '/login?redirect=/user_manage';
}
}
// Load Users
async function loadUsers() {
const loading = document.getElementById('loading');
const container = document.getElementById('usersContainer');
const empty = document.getElementById('emptyState');
try {
const response = await fetch('/api/user/list');
const users = await response.json();
loading.style.display = 'none';
if (!users || users.length === 0) {
empty.classList.remove('hidden');
container.style.display = 'none';
return;
}
empty.classList.add('hidden');
container.style.display = 'grid';
container.innerHTML = users.map((user, index) => `
<div class="user-card" style="animation-delay: ${index * 0.1}s">
<div class="flex justify-between items-start mb-4">
<div class="flex items-center gap-3">
<div class="w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold"
style="background-color: var(--accent-bg); color: var(--accent-text);">
${user.username.charAt(0).toUpperCase()}
</div>
<div>
<h3 class="font-medium text-base theme-transition" style="color: var(--text-primary);">
${user.username}
</h3>
<span class="role-badge role-${user.role}">
${user.role === 'admin' ? '管理员' : '普通用户'}
</span>
</div>
</div>
<div class="flex gap-2">
${user.role !== 'admin' ? `
<button onclick="manageUserForms('${user.username}', '${user.role}')"
class="btn btn-manage py-2 px-3 rounded-xl text-xs font-medium">
权限
</button>
` : ''}
<button onclick="deleteUser('${user.username}', '${user.role}')"
class="btn btn-danger py-2 px-3 rounded-xl text-xs font-medium"
${user.username === 'admin' ? 'disabled' : ''}>
删除
</button>
</div>
</div>
<div class="pt-4 border-t theme-transition" style="border-color: var(--border-color);">
<div class="flex justify-between items-center text-sm">
<span class="theme-transition" style="color: var(--text-muted);">创建时间</span>
<span class="font-medium theme-transition" style="color: var(--text-secondary);">
${formatDate(user.created_at)}
</span>
</div>
<div class="flex justify-between items-center text-sm mt-2">
<span class="theme-transition" style="color: var(--text-muted);">管理表单数</span>
<span class="font-medium theme-transition" style="color: var(--text-secondary);">
${user.managed_forms ? user.managed_forms.length : 0} 个
</span>
</div>
</div>
</div>
`).join('');
// Animate cards
gsap.to(".user-card", {
opacity: 1,
y: 0,
duration: 0.6,
stagger: 0.1,
ease: "power2.out"
});
} catch (error) {
loading.style.display = 'none';
showToast('加载用户失败: ' + error.message, 'error');
}
}
// Modal Functions
function showAddUserModal() {
document.getElementById('newUsername').value = '';
document.getElementById('newPassword').value = '';
document.getElementById('userRole').value = 'user';
document.getElementById('addUserModal').classList.add('show');
document.getElementById('addUserModal').style.display = 'flex';
}
function closeAddUserModal() {
document.getElementById('addUserModal').classList.remove('show');
setTimeout(() => {
document.getElementById('addUserModal').style.display = 'none';
}, 300);
}
async function addUser() {
const username = document.getElementById('newUsername').value.trim();
const password = document.getElementById('newPassword').value;
const role = document.getElementById('userRole').value;
if (!username || !password) {
showToast('请填写用户名和密码', 'error');
return;
}
if (username.length < 2) {
showToast('用户名至少2个字符', 'error');
return;
}
if (password.length < 6) {
showToast('密码至少6个字符', 'error');
return;
}
try {
const response = await fetch('/api/user/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, role })
});
const data = await response.json();
if (data.success) {
showToast('用户添加成功', 'success');
closeAddUserModal();
loadUsers();
} else {
showToast(data.message || '添加失败', 'error');
}
} catch (error) {
showToast('添加失败: ' + error.message, 'error');
}
}
async function deleteUser(username, role) {
if (username === 'admin') {
showToast('不能删除默认管理员', 'error');
return;
}
if (!confirm(`确定要删除用户 "${username}" 吗?`)) {
return;
}
try {
const response = await fetch(`/api/user/delete/${username}`, {
method: 'POST'
});
const data = await response.json();
if (data.success) {
showToast('用户已删除', 'success');
loadUsers();
} else {
showToast(data.message || '删除失败', 'error');
}
} catch (error) {
showToast('删除失败: ' + error.message, 'error');
}
}
async function manageUserForms(username, role) {
if (role === 'admin') {
showToast('管理员可管理所有表单', 'info');
return;
}
currentManageUsername = username;
document.getElementById('permsUsername').textContent = username;
try {
const [formsResponse, permsResponse] = await Promise.all([
fetch('/api/admin/forms'),
fetch(`/api/user/${username}/forms`)
]);
const forms = await formsResponse.json();
const permsData = await permsResponse.json();
allForms = forms;
const userForms = permsData.managed_forms || [];
const checkboxesDiv = document.getElementById('formsCheckboxes');
if (forms.length === 0) {
checkboxesDiv.innerHTML = '<div style="color: var(--text-muted); text-align: center; padding: 20px;">暂无表单</div>';
} else {
checkboxesDiv.innerHTML = forms.map(form => `
<label class="checkbox-item">
<input type="checkbox" value="${form.id}" ${userForms.includes(form.id) ? 'checked' : ''}>
<div class="flex-1 min-w-0">
<div class="font-medium truncate" style="color: var(--text-primary);">${form.title}</div>
<div class="text-xs" style="color: var(--text-muted);">${form.id}</div>
</div>
</label>
`).join('');
}
document.getElementById('permsModal').classList.add('show');
document.getElementById('permsModal').style.display = 'flex';
} catch (error) {
showToast('加载权限失败: ' + error.message, 'error');
}
}
function closePermsModal() {
document.getElementById('permsModal').classList.remove('show');
setTimeout(() => {
document.getElementById('permsModal').style.display = 'none';
}, 300);
}
async function saveUserPerms() {
const checkboxes = document.querySelectorAll('#formsCheckboxes input[type="checkbox"]:checked');
const selectedFormIds = Array.from(checkboxes).map(cb => cb.value);
try {
const response = await fetch(`/api/user/${currentManageUsername}/forms`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ form_ids: selectedFormIds })
});
const data = await response.json();
if (data.success) {
showToast('权限已更新', 'success');
closePermsModal();
loadUsers();
} else {
showToast(data.message || '保存失败', 'error');
}
} catch (error) {
showToast('保存失败: ' + error.message, 'error');
}
}
// Utilities
function formatDate(dateString) {
if (!dateString) return '-';
const date = new Date(dateString);
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
}
// Close modals on outside click
document.querySelectorAll('.modal-overlay').forEach(modal => {
modal.addEventListener('click', function(e) {
if (e.target === this) {
if (this.id === 'addUserModal') closeAddUserModal();
if (this.id === 'permsModal') closePermsModal();
}
});
});
// Close on ESC
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
closeAddUserModal();
closePermsModal();
}
});
// Initial Animation
window.addEventListener('load', () => {
gsap.to("#headerSection", {
opacity: 1,
y: 0,
duration: 0.8,
ease: "power2.out",
delay: 0.2
});
});
// Start
window.addEventListener('DOMContentLoaded', checkAdmin);
</script>
</body>
</html>
+2793
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""utils package"""
+46
View File
@@ -0,0 +1,46 @@
"""
过期时间计算
"""
from datetime import datetime
def get_expiry_info(created_at_str, expires_at_str=None):
"""获取过期信息"""
if not created_at_str:
return None
try:
created_at = datetime.fromisoformat(
created_at_str.replace('Z', '+00:00'))
# 没有设置过期时间 -> 永不过期
if not expires_at_str:
return {
'created_at': created_at.isoformat(),
'expires_at': None,
'remaining_days': None,
'remaining_hours': None,
'remaining_minutes': None,
'is_expired': False,
'never_expires': True
}
expires_at = datetime.fromisoformat(
expires_at_str.replace('Z', '+00:00'))
remaining = expires_at - datetime.now()
days = remaining.days
hours, remainder = divmod(remaining.seconds, 3600)
minutes, _ = divmod(remainder, 60)
return {
'created_at': created_at.isoformat(),
'expires_at': expires_at.isoformat(),
'remaining_days': days,
'remaining_hours': hours,
'remaining_minutes': minutes,
'is_expired': remaining.total_seconds() <= 0,
'never_expires': False
}
except:
return None
+73
View File
@@ -0,0 +1,73 @@
"""
工具函数:密码哈希、ID 生成、智能列名识别
"""
import hashlib
import uuid
import random
import string
from difflib import SequenceMatcher
from config import FIELD_KEYWORDS
def get_client_ip():
"""获取真实客户端 IP。
nginx 反代场景下 request.remote_addr 是代理地址(如 127.0.0.1),
优先取代理注入的 X-Real-IP,其次 X-Forwarded-For 的首个地址,最后回退 remote_addr。"""
from flask import request
real_ip = (request.headers.get('X-Real-IP') or '').strip()
if real_ip:
return real_ip
forwarded = (request.headers.get('X-Forwarded-For') or '').strip()
if forwarded:
# 多级代理时为逗号分隔链,首个为客户端原始 IP
return forwarded.split(',')[0].strip()
return request.remote_addr or ''
def hash_password(password):
"""密码哈希"""
return hashlib.sha256(password.encode('utf-8')).hexdigest()
def generate_session_id():
"""生成会话ID"""
return uuid.uuid4().hex
def generate_form_id():
"""生成随机表单ID"""
return ''.join(random.choices(string.ascii_letters + string.digits, k=8))
def generate_preset_id():
"""生成预设ID"""
return 'preset_' + ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
def smart_field_detection(columns):
"""智能识别列名对应关系"""
result = {}
columns_lower = [str(col).lower().strip() for col in columns]
for field_type, keywords in FIELD_KEYWORDS.items():
best_match = None
best_ratio = 0
for i, col in enumerate(columns_lower):
for keyword in keywords:
if keyword.lower() == col:
best_match = columns[i]
best_ratio = 1.0
break
if keyword.lower() in col or col in keyword.lower():
ratio = SequenceMatcher(None, keyword.lower(), col).ratio()
if ratio > best_ratio and ratio > 0.6:
best_ratio = ratio
best_match = columns[i]
if best_ratio == 1.0:
break
if best_match:
result[field_type] = best_match
return result
+90
View File
@@ -0,0 +1,90 @@
"""
图标自动生成
"""
import os
from config import BASE_DIR, IMG_DIR, PIL_AVAILABLE
def generate_favicons():
"""根据 favicon.png 自动生成各种尺寸的图标文件"""
if not PIL_AVAILABLE:
print("⚠️ PIL未安装,跳过图标生成")
return
from PIL import Image, ImageDraw
source_path = os.path.join(IMG_DIR, 'favicon.png')
if not os.path.exists(source_path):
print("⚠️ 未找到 favicon.png,跳过图标生成")
print(" 如需自定义图标,请放置 favicon.png 到 static/img/ 目录")
return
try:
img = Image.open(source_path)
if img.mode != 'RGBA':
img = img.convert('RGBA')
icon_specs = [
('favicon-16x16.png', 16, 16),
('favicon-32x32.png', 32, 32),
('apple-touch-icon.png', 180, 180),
('android-chrome-192x192.png', 192, 192),
('android-chrome-512x512.png', 512, 512),
]
generated = []
for filename, width, height in icon_specs:
output_path = os.path.join(IMG_DIR, filename)
if os.path.exists(output_path):
continue
resized = img.resize((width, height), Image.Resampling.LANCZOS)
if 'apple-touch-icon' in filename:
mask = Image.new('L', (width, height), 0)
draw = ImageDraw.Draw(mask)
radius = width // 5
draw.rounded_rectangle([0, 0, width, height], radius=radius, fill=255)
output = Image.new('RGBA', (width, height), (255, 255, 255, 0))
output.paste(resized, (0, 0))
output.putalpha(mask)
resized = output
resized.save(output_path, 'PNG', optimize=True)
generated.append(filename)
ico_path = os.path.join(IMG_DIR, 'favicon.ico')
if not os.path.exists(ico_path):
sizes = [(16, 16), (32, 32), (48, 48), (64, 64)]
ico_images = []
for size in sizes:
resized = img.resize(size, Image.Resampling.LANCZOS)
if resized.mode == 'RGBA':
background = Image.new('RGB', size, (255, 255, 255))
background.paste(resized, mask=resized.split()[3])
resized = background
elif resized.mode != 'RGB':
resized = resized.convert('RGB')
ico_images.append(resized)
ico_images[0].save(
ico_path,
format='ICO',
sizes=sizes,
append_images=ico_images[1:]
)
generated.append('favicon.ico')
if generated:
print(f"✅ 已生成图标文件: {', '.join(generated)}")
else:
print("✅ 所有图标文件已存在,跳过生成")
except Exception as e:
print(f"❌ 图标生成失败: {str(e)}")
import traceback
traceback.print_exc()
+39
View File
@@ -0,0 +1,39 @@
"""Per-form switch for the existing hardcoded submission notification."""
import requests
def normalize_webhook(value=None):
if value is None:
return {'enabled': False}
if not isinstance(value, dict):
raise ValueError('Webhook 配置必须是对象')
enabled = value.get('enabled', False)
if not isinstance(enabled, bool):
raise ValueError('Webhook enabled 必须为布尔值')
return {'enabled': enabled}
def send_form_webhook(form, who, *, is_overwrite=False, uploaded_files=None):
from config import NOTIFY_WEBHOOK
if not NOTIFY_WEBHOOK:
return False
try:
webhook = normalize_webhook(form.get('webhook'))
except ValueError:
return False
if not webhook['enabled']:
return False
action = '覆盖' if is_overwrite else '提交'
message = (f"{who}{action}成功,表单标题:{form.get('title', '未命名表单')},"
f"表单id:{form.get('id', '')}")
try:
# Preserve the original built-in URL, GET request and per-file notifications.
for filename in uploaded_files or [None]:
content = f'{message},文件:{filename}' if filename is not None else message
response = requests.get(f"https://api.chuckfang.com/c415ce0b/ 表单提交通知/{content}", timeout=3)
response.raise_for_status()
return True
except requests.RequestException:
# Keep failures separate from the already-saved submission.
print(f"Webhook 通知失败,表单 {form.get('id', '')} 的提交已保存")
return False