Files
zzy f6bda29e96 feat(frontend): 提交页大文件改走分片上传
- >4MB 的文件:init -> 8MB 分片逐片上传(单片失败退避重试 5 次)-> complete
- 成功后把 upload_id 以 fileTokens 一起提交,服务端零拷贝挂载
- <=4MB 仍走原单包 multipart,行为不变
- 进度条聚合显示总进度/速度/剩余时间,并标注"可断点续传"
- 顺带修掉原 IndexedDB 恢复文件的竞态(现在提交前统一 await 收集)

本地验证:node 直接调用页面里的真实函数跑 30MB 文件(4 片)提交成功;
模拟 2 次分片失败后自动重试成功。
2026-11-13 12:25:27 +08:00

4643 lines
184 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!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 id="pageTitle">表单提交</title>
<!-- Tailwind CSS -->
<script src="/static/js/vendor/tailwind-play.js"></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 premium animations -->
<script src="/static/js/vendor/gsap.min.js"></script>
<script src="/static/js/gsap-fallback.js"></script>
<script src="/static/js/particles.js"></script>
<script src="/static/js/toast.js"></script>
<script src="/static/js/morph-card.js?v=8"></script>
<link rel="stylesheet" href="/static/css/toast.css" onerror="this.onerror=null;this.href='/static/css/toast.css?r='+Date.now()">
<link rel="stylesheet" href="/static/css/basic.css" onerror="this.onerror=null;this.href='/static/css/basic.css?r='+Date.now()">
<link rel="stylesheet" href="/static/css/common.css" onerror="this.onerror=null;this.href='/static/css/common.css?r='+Date.now()">
<link rel="stylesheet" href="/static/css/form-experience.css" onerror="this.onerror=null;this.href='/static/css/form-experience.css?r='+Date.now()">
<script src="/static/js/common.js"></script>
<script src="/static/js/markdown.js"></script>
<script src="/static/js/form-link-preset.js"></script>
<style>
/* ── index 页面专属样式 ── */
/* Input autofill */
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus {
-webkit-box-shadow: 0 0 0px 1000px var(--bg-secondary) inset;
-webkit-text-fill-color: var(--text-primary);
transition: background-color 5000s ease-in-out 0s;
}
.input-underline {
background-image: linear-gradient(var(--border-focus), var(--border-focus));
background-position: 0% 100%;
background-repeat: no-repeat;
background-size: 0% 2px;
transition: background-size 0.3s ease, border-color 0.3s ease, color 0.3s ease;
}
.input-underline:focus {
background-size: 100% 2px;
}
.form-entry-box {
width: 100%;
min-height: 46px;
padding: 11px 14px;
border: 1px solid var(--border-color);
border-radius: 12px;
background: var(--input-bg);
color: var(--text-primary);
outline: none;
transition: border-color .2s ease, box-shadow .2s ease, background-color .2s ease;
}
.form-entry-box:focus {
border-color: var(--border-focus);
box-shadow: 0 0 0 3px var(--shadow-color);
}
.btn-slide {
position: relative;
overflow: hidden;
}
.btn-slide::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-slide:hover::before {
left: 100%;
}
/* 深色模式下的输入框优化 */
.dark input[type="text"],
.dark input[type="number"],
.dark input[type="date"],
.dark input[type="time"],
.dark textarea,
.dark select {
color: #fafafa !important;
}
.dark input::placeholder,
.dark textarea::placeholder {
color: var(--text-muted) !important;
}
/* 深色模式下的下拉选项 */
.dark select option {
background-color: #171717;
color: #fafafa;
}
/* 深色模式下的滑块 */
.dark input[type="range"] {
background: #404040;
}
.dark input[type="range"]::-webkit-slider-thumb {
background: #fafafa;
}
/* 深色模式下的文件上传区域 */
.dark .upload-dropzone {
border-color: #404040;
color: #a3a3a3;
}
.dark .upload-dropzone:hover {
border-color: #737373;
background: #262626;
}
/* Progress Grid Styles */
.progress-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(48px, 1fr));
gap: 8px;
max-height: 0;
overflow: hidden;
transition: max-height 0.4s ease, opacity 0.3s ease, border-color 0.3s ease, margin-top 0.3s ease, padding-top 0.3s ease;
opacity: 0;
border-top: 1px solid transparent;
padding-top: 0;
margin-top: 0;
}
.progress-grid.expanded {
max-height: 500px;
opacity: 1;
margin-top: 16px;
padding-top: 16px;
border-color: var(--border-color);
}
.progress-cell {
aspect-ratio: 1;
display: flex;
align-items: center;
justify-content: center;
border-radius: 8px;
font-size: 11px;
font-weight: 600;
transition: all 0.3s ease;
}
.progress-cell.completed {
background: var(--progress-green);
color: white;
}
.progress-cell.pending {
background: var(--progress-red);
color: white;
}
.progress-toggle {
cursor: pointer;
transition: background-color 0.2s ease;
}
.progress-toggle:hover { background: var(--studio-glow); }
.progress-toggle svg { transition: transform 0.3s ease; }
.progress-toggle.expanded svg {
transform: rotate(180deg);
}
/* Rating Stars */
.rating-stars {
display: flex;
gap: 4px;
}
.rating-star {
cursor: pointer;
transition: transform 0.2s, color 0.2s;
color: var(--border-color);
}
.rating-star:hover,
.rating-star.active {
color: #fbbf24;
transform: scale(1.1);
}
/* Slider */
input[type="range"] {
-webkit-appearance: none;
width: 100%;
height: 6px;
border-radius: 3px;
background: var(--border-color);
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border-radius: 50%;
background: var(--accent-bg);
cursor: pointer;
transition: transform 0.2s;
}
input[type="range"]::-webkit-slider-thumb:hover {
transform: scale(1.1);
}
.slider-value {
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
min-width: 40px;
text-align: right;
}
/* 评分字段样式 */
.rating-stars {
display: flex;
gap: 8px;
align-items: center;
}
.rating-star-item {
cursor: pointer;
transition: transform 0.2s ease, color 0.2s ease;
border-radius: 4px;
position: relative;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.rating-star-item:hover {
transform: scale(1.1);
}
.rating-star-item:active {
transform: scale(0.95);
}
.rating-stars:focus-visible {
outline: 2px solid var(--border-focus);
outline-offset: 4px;
border-radius: 8px;
}
/* 星星图标容器 */
.rating-star-item .star-icon {
width: 32px;
height: 32px;
transition: all 0.2s ease;
pointer-events: none;
}
/* 浅色模式 - 未选中星星 */
.light .rating-star-item {
color: #d4d4d4;
}
/* 深色模式 - 未选中星星 */
.dark .rating-star-item {
color: #525252;
}
/* 选中状态的星星 - 全满 */
.rating-star-item[data-value="full"],
.rating-star-item[data-value="half"] { color: #f59e0b !important; }
.rating-value-display[data-rated="true"] { color: #fbbf24; }
/* 移动端优化 */
@media (max-width: 640px) {
.rating-star-item {
width: 44px;
height: 44px;
}
.rating-star-item .star-icon {
width: 36px;
height: 36px;
}
.rating-stars {
gap: 6px;
}
}
/* 单选/多选框样式 */
.custom-check-box {
position: relative;
background: transparent;
}
/* 浅色模式 */
.light .custom-check-box {
border-color: #d4d4d4 !important;
}
/* 深色模式 */
.dark .custom-check-box {
border-color: #404040 !important;
}
/* 选中状态 */
.custom-check-box.checked {
background-color: var(--accent-bg) !important;
border-color: var(--accent-bg) !important;
}
.custom-check-box.radio-check.checked {
background-color: transparent !important;
border-color: var(--accent-bg) !important;
}
.custom-check-box svg {
display: block;
}
/* 深色模式下的对勾 */
.dark .custom-check-box svg polyline {
stroke: #171717 !important;
}
/* 浅色模式下的对勾 */
.light .custom-check-box svg polyline {
stroke: #ffffff !important;
}
/* 移动端优化 */
@media (max-width: 640px) {
.rating-star {
width: 36px !important;
height: 36px !important;
}
.custom-check-box {
width: 24px !important;
height: 24px !important;
}
label.inline-flex {
padding: 12px !important;
min-height: 44px;
}
/* 移动端进度网格优化 */
.progress-grid {
grid-template-columns: repeat(auto-fill, minmax(36px, 1fr));
gap: 4px;
border-top: 1px solid transparent;
margin-top: 0;
padding-top: 0;
}
.progress-cell {
font-size: 9px;
border-radius: 4px;
}
}
/* 深色模式下的卡片和容器 */
.dark .glass {
background: rgba(23, 23, 23, 0.9);
border-color: rgba(255, 255, 255, 0.1);
}
/* 深色模式下的进度条 */
.dark #progressBar {
background: linear-gradient(90deg, #4ade80, #22c55e);
}
/* 深色模式下的消息提示 */
.dark #message.success {
background: rgba(22, 163, 74, 0.2);
border-color: rgba(22, 163, 74, 0.3);
color: #4ade80;
}
.dark #message.error {
background: rgba(220, 38, 38, 0.2);
border-color: rgba(220, 38, 38, 0.3);
color: #f87171;
}
.dark #message.info {
background: rgba(37, 99, 235, 0.2);
border-color: rgba(37, 99, 235, 0.3);
color: #60a5fa;
}
/* 深色模式下的按钮 */
.dark .btn-primary {
background-color: #fafafa;
color: #171717;
}
.dark .btn-secondary {
background-color: #262626;
color: #a3a3a3;
border-color: #404040;
}
/* 深色模式下的标签 */
.dark label.block {
color: #a3a3a3;
}
/* 文件上传区域样式 */
.upload-dropzone {
border: 2px dashed var(--border-color);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.upload-dropzone:hover {
border-color: var(--text-muted);
background: var(--bg-primary);
}
/* 文件已选定状态 - 浅色模式 */
input[type="file"].has-file+div,
input[type="file"][data-has-file="true"]+div {
border-color: #22c55e !important;
border-style: solid !important;
background: rgba(34, 197, 94, 0.08) !important;
box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.15), 0 4px 20px rgba(34, 197, 94, 0.1) !important;
color: #16a34a !important;
transform: translateY(-1px);
}
input[type="file"].has-file+div svg,
input[type="file"][data-has-file="true"]+div svg {
color: #22c55e !important;
transform: scale(1.1);
transition: all 0.3s ease;
}
/* 文件名显示样式增强 */
input[type="file"].has-file+div p[id^="fileName_"],
input[type="file"][data-has-file="true"]+div p[id^="fileName_"] {
color: #16a34a !important;
font-weight: 500;
}
.dark input[type="file"].has-file+div p[id^="fileName_"],
.dark input[type="file"][data-has-file="true"]+div p[id^="fileName_"] {
color: #4ade80 !important;
font-weight: 500;
}
/* 深色模式下的文件上传 */
.dark input[type="file"]+div {
border-color: #404040;
color: #737373;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.dark input[type="file"]:hover+div {
border-color: #737373;
background: #262626;
}
/* 文件已选定状态 - 深色模式 */
.dark input[type="file"].has-file+div,
.dark input[type="file"][data-has-file="true"]+div {
border-color: #4ade80 !important;
background: rgba(74, 222, 128, 0.1) !important;
box-shadow: 0 0 0 3px rgba(74, 222, 128, 0.2), 0 4px 20px rgba(74, 222, 128, 0.15) !important;
color: #4ade80 !important;
}
.dark input[type="file"].has-file+div svg,
.dark input[type="file"][data-has-file="true"]+div svg {
color: #4ade80 !important;
transform: scale(1.1);
transition: all 0.3s ease;
}
/* 深色模式下的评分值显示 */
.dark .rating-value-display {
color: #525252;
}
.dark .rating-value-display[data-rated="true"] {
color: #fbbf24;
}
/* 文件选择成功动画 */
@keyframes fileSelected {
0% {
transform: scale(1) translateY(0);
}
25% {
transform: scale(0.98) translateY(2px);
}
50% {
transform: scale(1.02) translateY(-2px);
}
100% {
transform: scale(1) translateY(-1px);
}
}
/* 文件上传区域过渡效果增强 */
input[type="file"]+div {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
}
input[type="file"]+div svg {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
/* 脉冲光环效果 - 文件已选定时 */
@keyframes filePulse {
0%, 100% {
box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.15), 0 4px 20px rgba(34, 197, 94, 0.1);
}
50% {
box-shadow: 0 0 0 5px rgba(34, 197, 94, 0.1), 0 4px 25px rgba(34, 197, 94, 0.15);
}
}
input[type="file"].has-file+div,
input[type="file"][data-has-file="true"]+div {
animation: fileSelected 0.5s cubic-bezier(0.4, 0, 0.2, 1), filePulse 2s ease-in-out infinite 0.5s;
}
.dark input[type="file"].has-file+div,
.dark input[type="file"][data-has-file="true"]+div {
animation: fileSelected 0.5s cubic-bezier(0.4, 0, 0.2, 1), filePulseDark 2s ease-in-out infinite 0.5s;
}
@keyframes filePulseDark {
0%, 100% {
box-shadow: 0 0 0 3px rgba(74, 222, 128, 0.2), 0 4px 20px rgba(74, 222, 128, 0.15);
}
50% {
box-shadow: 0 0 0 5px rgba(74, 222, 128, 0.15), 0 4px 25px rgba(74, 222, 128, 0.2);
}
}
/* ===== IndexedDB 存储悬浮球样式 ===== */
.storage-fab {
position: fixed;
bottom: 24px;
left: 24px;
width: 56px;
height: 56px;
border-radius: 50%;
background: var(--accent-bg);
color: var(--accent-text);
border: none;
cursor: pointer;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15), 0 0 0 1px rgba(255, 255, 255, 0.1);
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 1000;
backdrop-filter: blur(10px);
}
.storage-fab:hover {
transform: scale(1.1);
box-shadow: 0 6px 30px rgba(0, 0, 0, 0.2), 0 0 0 1px rgba(255, 255, 255, 0.15);
}
.storage-fab:active {
transform: scale(0.95);
}
.storage-fab.pulse {
animation: fabPulse 2s ease-in-out infinite;
}
@keyframes fabPulse {
0%, 100% { box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15), 0 0 0 0 rgba(128, 128, 128, 0.4); }
50% { box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15), 0 0 0 10px rgba(128, 128, 128, 0); }
}
.storage-panel {
position: fixed;
bottom: 88px;
left: 24px;
width: 360px;
max-width: calc(100vw - 48px);
max-height: 500px;
background: var(--bg-secondary);
border: 1px solid var(--glass-border);
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(20px);
z-index: 999;
opacity: 0;
transform: scale(0.9) translateY(20px);
pointer-events: none;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
overflow: hidden;
}
.storage-panel.open {
opacity: 1;
transform: scale(1) translateY(0);
pointer-events: auto;
}
.storage-panel-header {
padding: 20px;
border-bottom: 1px solid var(--border-color);
display: flex;
justify-content: space-between;
align-items: center;
}
.storage-panel-body {
padding: 20px;
max-height: 350px;
overflow-y: auto;
}
.storage-ring {
position: relative;
width: 120px;
height: 120px;
margin: 0 auto 20px;
}
.storage-ring svg {
transform: rotate(-90deg);
}
.storage-ring-bg {
fill: none;
stroke: var(--border-color);
stroke-width: 8;
}
.storage-ring-progress {
fill: none;
stroke: var(--accent-bg);
stroke-width: 8;
stroke-linecap: round;
transition: stroke-dashoffset 0.5s ease;
}
.storage-ring-text {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
.storage-file-item {
display: flex;
align-items: center;
padding: 12px;
border-radius: 12px;
background: var(--bg-primary);
margin-bottom: 8px;
transition: all 0.2s;
}
.storage-file-item:hover {
background: var(--glass-bg);
}
.storage-file-icon {
width: 40px;
height: 40px;
border-radius: 10px;
background: var(--accent-bg);
color: var(--accent-text);
display: flex;
align-items: center;
justify-content: center;
margin-right: 12px;
flex-shrink: 0;
}
.storage-file-info {
flex: 1;
min-width: 0;
}
.storage-file-name {
font-size: 13px;
font-weight: 500;
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.storage-file-size {
font-size: 11px;
color: var(--text-muted);
margin-top: 2px;
}
.storage-file-delete {
width: 32px;
height: 32px;
border-radius: 8px;
border: none;
background: transparent;
color: var(--text-muted);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
}
.storage-file-delete:hover {
background: rgba(220, 38, 38, 0.1);
color: #ef4444;
}
.storage-empty-state {
text-align: center;
padding: 40px 20px;
color: var(--text-muted);
}
.storage-empty-state svg {
margin-bottom: 12px;
opacity: 0.5;
}
@media (max-width: 480px) {
.storage-fab {
bottom: 20px;
left: 20px;
width: 48px;
height: 48px;
}
.storage-panel {
bottom: 76px;
left: 20px;
width: calc(100vw - 40px);
}
}
/* ===== Markdown 渲染样式(公告 / 表单说明)===== */
.markdown-body {
font-size: 14px;
line-height: 1.7;
word-break: break-word;
color: var(--text-primary);
}
.markdown-body > :first-child { margin-top: 0; }
.markdown-body > :last-child { margin-bottom: 0; }
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
font-weight: 600;
line-height: 1.4;
margin: 1.25em 0 0.5em;
color: var(--text-primary);
}
.markdown-body h1 { font-size: 1.5em; }
.markdown-body h2 { font-size: 1.3em; }
.markdown-body h3 { font-size: 1.15em; }
.markdown-body h4 { font-size: 1.05em; }
.markdown-body h5,
.markdown-body h6 { font-size: 1em; }
.markdown-body p { margin: 0.6em 0; }
.markdown-body a { color: #2563eb; text-decoration: underline; text-underline-offset: 2px; word-break: break-all; }
.dark .markdown-body a { color: #60a5fa; }
.markdown-body strong { font-weight: 600; color: var(--text-primary); }
.markdown-body em { font-style: italic; }
.markdown-body del { color: var(--text-muted); }
.markdown-body code {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.9em;
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 4px;
padding: 1px 5px;
color: var(--accent-color, #2563eb);
word-break: break-all;
}
.dark .markdown-body code { color: #93c5fd; }
.markdown-body pre {
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 12px 14px;
overflow-x: auto;
margin: 0.8em 0;
}
.markdown-body pre code {
background: transparent;
border: none;
padding: 0;
color: var(--text-primary);
}
.markdown-body ul,
.markdown-body ol {
margin: 0.6em 0;
padding-left: 1.4em;
}
.markdown-body ul { list-style: disc; }
.markdown-body ol { list-style: decimal; }
.markdown-body li { margin: 0.25em 0; }
.markdown-body ul.task-list { list-style: none; padding-left: 0.2em; }
.markdown-body li.task-list-item input[type="checkbox"] {
margin-right: 6px;
vertical-align: middle;
accent-color: var(--accent-bg, #2563eb);
}
.markdown-body blockquote {
margin: 0.8em 0;
padding: 6px 14px;
border-left: 3px solid var(--border-focus);
background: var(--bg-primary);
border-radius: 0 8px 8px 0;
color: var(--text-secondary);
}
.markdown-body hr {
border: none;
border-top: 1px solid var(--border-color);
margin: 1.2em 0;
}
.markdown-body img {
max-width: 100%;
border-radius: 8px;
margin: 0.6em 0;
}
.markdown-body table {
width: 100%;
border-collapse: collapse;
margin: 0.8em 0;
font-size: 0.95em;
display: block;
overflow-x: auto;
}
.markdown-body th,
.markdown-body td {
border: 1px solid var(--border-color);
padding: 6px 10px;
text-align: left;
}
.markdown-body th {
background: var(--bg-primary);
font-weight: 600;
}
.markdown-body tr:nth-child(even) td { background: var(--bg-primary); }
/* ===== 公告超长折叠 / 羽化 / 箭头展开(当前禁用,取消注释可启用)===== */
/*
#announcementTextDisplay {
max-height: none;
transition: max-height 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}
#announcementTextDisplay.collapsed {
overflow: hidden;
}
.announcement-fade {
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 3em;
background: linear-gradient(to bottom, transparent, var(--bg-secondary));
pointer-events: none;
opacity: 0;
transition: opacity 0.3s ease;
border-radius: 0 0 16px 16px;
}
.announcement-fade.visible { opacity: 1; }
.announcement-toggle {
display: flex;
align-items: center;
justify-content: center;
margin: 10px auto 0;
width: 30px;
height: 30px;
border-radius: 50%;
border: 1px solid var(--border-color);
background: var(--bg-secondary);
color: var(--text-muted);
cursor: pointer;
transition: transform 0.3s ease, background 0.3s ease, border-color 0.3s ease;
}
.announcement-toggle:hover {
background: var(--bg-primary);
color: var(--text-primary);
}
.announcement-toggle:active { transform: scale(0.92); }
.announcement-chevron {
transition: transform 0.6s cubic-bezier(0.34, 1.4, 0.64, 1);
transform: rotate(0deg);
}
.announcement-toggle.expanded .announcement-chevron {
transform: rotate(180deg);
}
*/
</style>
</head>
<body class="submission-page antialiased min-h-screen relative overflow-x-hidden">
<!-- Storage FAB (Floating Action Button) -->
<button class="storage-fab" id="storageFab" onclick="toggleStoragePanel()" title="存储管理">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
<polyline points="17 8 12 3 7 8"/>
<line x1="12" y1="3" x2="12" y2="15"/>
</svg>
</button>
<!-- Storage Panel -->
<div class="storage-panel" id="storagePanel">
<div class="storage-panel-header">
<div>
<h3 class="font-serif text-lg font-medium" style="color: var(--text-primary);">本地存储</h3>
<p class="text-xs mt-0.5" style="color: var(--text-muted);">IndexedDB 文件管理</p>
</div>
<button onclick="toggleStoragePanel()" class="w-8 h-8 rounded-lg flex items-center justify-center transition-colors" style="color: var(--text-muted);" onmouseover="this.style.backgroundColor='var(--bg-primary)'" onmouseout="this.style.backgroundColor='transparent'">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="18" y1="6" x2="6" y2="18"/>
<line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</button>
</div>
<div class="storage-panel-body">
<!-- Storage Ring Chart -->
<div class="storage-ring">
<svg width="120" height="120" viewBox="0 0 120 120">
<circle class="storage-ring-bg" cx="60" cy="60" r="52"/>
<circle class="storage-ring-progress" id="storageRingProgress" cx="60" cy="60" r="52"
stroke-dasharray="326.73" stroke-dashoffset="326.73"/>
</svg>
<div class="storage-ring-text">
<div class="text-2xl font-bold numeric-display" style="color: var(--text-primary);" id="storagePercent">0%</div>
<div class="text-xs numeric-display" style="color: var(--text-muted);" id="storageRatio">0/0 MB</div>
</div>
</div>
<!-- Storage Stats -->
<div class="grid grid-cols-2 gap-3 mb-4">
<div class="p-3 rounded-xl" style="background: var(--bg-primary);">
<div class="text-xs mb-1" style="color: var(--text-muted);">已用空间</div>
<div class="text-sm font-semibold numeric-display" style="color: var(--text-primary);" id="usedSpace">0 MB</div>
</div>
<div class="p-3 rounded-xl" style="background: var(--bg-primary);">
<div class="text-xs mb-1" style="color: var(--text-muted);">可用空间</div>
<div class="text-sm font-semibold numeric-display" style="color: var(--text-primary);" id="availableSpace">0 MB</div>
</div>
</div>
<!-- File List -->
<div class="mb-3">
<div class="flex justify-between items-center mb-2">
<span class="text-xs font-medium" style="color: var(--text-muted);">已存储文件</span>
<span class="text-xs numeric-display" style="color: var(--accent-bg);" id="fileCount">0 个</span>
</div>
<div id="fileList">
<!-- Files will be listed here -->
</div>
</div>
<!-- Actions -->
<div class="flex gap-2 mt-4">
<button onclick="storageManager.clearAllFiles()" class="flex-1 py-2.5 px-4 rounded-xl text-xs font-medium transition-all duration-200" style="background: rgba(220, 38, 38, 0.1); color: #ef4444; border: 1px solid rgba(220, 38, 38, 0.2);">
清空存储
</button>
<button onclick="storageManager.persistStorage()" class="flex-1 py-2.5 px-4 rounded-xl text-xs font-medium transition-all duration-200" style="background: var(--bg-primary); color: var(--text-secondary); border: 1px solid var(--border-color);">
持久化
</button>
</div>
</div>
</div>
<!-- 提交反馈形变卡片:公共库 static/js/morph-card.js(本页仅保留页面级横幅样式) -->
<style>
/* 「检测到上次提交」横幅(页面级 UI,形变卡片本体在 static/js/morph-card.js) */
.last-sub-banner {
display: flex; align-items: center; flex-wrap: wrap; gap: 12px;
padding: 12px 18px;
border: 1px solid var(--border-color); border-radius: 14px;
background: var(--bg-secondary);
font-size: 12.5px; color: var(--text-secondary);
opacity: 0; transform: translateY(-6px);
transition: opacity 0.35s var(--um-ease-out), transform 0.35s var(--um-ease-out);
}
.last-sub-banner.show { opacity: 1; transform: translateY(0); }
.lsb-text { display: inline-flex; align-items: center; gap: 7px; }
.lsb-load {
margin-left: auto; border: none; cursor: pointer;
padding: 7px 14px; border-radius: 999px;
background: var(--accent-bg); color: var(--accent-text);
font: 600 12px/1 inherit; letter-spacing: 0.02em;
transition: transform 0.16s ease-out;
}
.lsb-load:active { transform: scale(0.96); }
.lsb-dismiss {
border: none; background: transparent; cursor: pointer;
color: var(--text-muted); font-size: 12px; padding: 4px 2px;
transition: color 0.2s ease;
}
.lsb-dismiss:hover { color: var(--text-secondary); }
</style>
<!-- Fixed Top 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 shadow-[0_0_10px_rgba(128,128,128,0.5)] theme-transition"
style="background-color: var(--text-primary);"></div>
</div>
<!-- Fixed Header -->
<header class="fixed top-0 w-full z-40 px-6 py-5 glass theme-transition border-b" id="mainHeader">
<div class="max-w-3xl mx-auto flex justify-between items-center">
<div class="text-[11px] tracking-[0.4em] uppercase font-medium theme-transition"
style="color: var(--text-primary);">
Form System
</div>
<div class="text-[11px] tracking-widest font-mono theme-transition" style="color: var(--text-muted);" id="clock">
00:00
</div>
</div>
</header>
<!-- Main Content -->
<main class="relative pt-32 pb-24 px-6">
<div class="max-w-xl mx-auto">
<!-- Header Section -->
<div class="mb-16 space-y-4" id="headerSection">
<p class="studio-kicker"><span class="studio-kicker__dot"></span> FORM / SUBMISSION</p>
<div class="overflow-hidden">
<h1 class="font-serif text-4xl sm:text-5xl leading-[1.1] font-medium tracking-tight theme-transition"
style="color: var(--text-primary);" id="formTitleDisplay">
表单提交
</h1>
</div>
<p class="text-sm leading-relaxed max-w-sm tracking-wide font-light theme-transition"
style="color: var(--text-secondary);" id="formSubtitleDisplay">
请填写以下信息,核对无误后提交。
</p>
<!-- 公告 / 表单说明 -->
<div id="announcementSection" class="hidden glass rounded-2xl p-5 mt-4">
<div class="space-y-3">
<div id="announcementTextDisplay" class="markdown-body text-sm leading-relaxed theme-transition relative"
style="color: var(--text-primary);"></div>
<!-- 折叠展开箭头按钮(当前禁用,取消注释可启用) -->
<!--
<button type="button" id="announcementToggle" class="announcement-toggle hidden"
aria-label="展开/收起公告" title="展开">
<svg class="announcement-chevron" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
-->
<div id="announcementFilesDisplay" class="space-y-2">
<!-- 附件下载列表 -->
</div>
</div>
</div>
</div>
<!-- Progress Section (if enabled) -->
<div id="progressSection" class="glass rounded-2xl p-6 mb-8 hidden">
<div class="flex justify-between items-center">
<div class="flex items-center gap-3">
<span class="text-sm font-medium" style="color: var(--text-primary);">完成情况</span>
<span id="progressText" class="text-sm numeric-display" style="color: var(--text-muted);">0/0</span>
</div>
<div class="flex items-center gap-3">
<span id="progressPercent" class="text-sm font-semibold numeric-display" style="color: var(--progress-green);">0%</span>
<button type="button" id="progressToggle" class="progress-toggle inline-flex items-center justify-center w-9 h-9 rounded-lg"
style="color: var(--text-muted);" aria-label="展开完成明细" aria-expanded="false" aria-controls="progressGrid">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
</div>
</div>
<div class="mt-3 h-2 rounded-full overflow-hidden" style="background: var(--border-color);">
<div id="progressBar" class="h-full rounded-full transition-all duration-500"
style="background: linear-gradient(90deg, var(--progress-green), #4ade80); width: 0%;"></div>
</div>
<div id="progressGrid" class="progress-grid">
<!-- Grid cells will be inserted here -->
</div>
<div class="mt-3 flex items-center gap-4 text-xs" style="color: var(--text-muted);">
<div class="flex items-center gap-1">
<div class="w-3 h-3 rounded" style="background: var(--progress-green);"></div>
<span>已完成</span>
</div>
<div class="flex items-center gap-1">
<div class="w-3 h-3 rounded" style="background: var(--progress-red);"></div>
<span>未完成</span>
</div>
</div>
</div>
<!-- Form Container -->
<div class="glass rounded-3xl p-8 sm:p-12 relative overflow-hidden shadow-2xl theme-transition" id="formContainer"
style="box-shadow: 0 20px 50px var(--shadow-color);">
<!-- Decorative corner accent -->
<div
class="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-neutral-200/20 to-transparent opacity-50 pointer-events-none dark:from-white/5">
</div>
<form id="upForm" enctype="multipart/form-data" novalidate class="relative z-10 space-y-10">
<!-- Dynamic form content -->
</form>
<!-- Message Container -->
<div id="message"
class="mt-8 hidden rounded-2xl p-4 text-sm font-medium tracking-wide transform transition-all duration-500 border theme-transition">
</div>
</div>
</div>
</main>
<!-- ID Card Verification Modal -->
<div id="idCardModal" class="fixed inset-0 z-50 hidden items-center justify-center p-4">
<div class="absolute inset-0 backdrop-blur-md transition-opacity duration-300 opacity-0 theme-transition"
style="background-color: rgba(0,0,0,0.4);" id="modalBackdrop"></div>
<div
class="relative rounded-2xl shadow-2xl w-full max-w-md p-8 sm:p-10 transform scale-95 opacity-0 transition-all duration-300 border theme-transition"
style="background-color: var(--bg-secondary); border-color: var(--glass-border);" id="modalContent">
<!-- Modal accent line -->
<div
class="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-neutral-300 via-neutral-500 to-neutral-300 dark:from-neutral-700 dark:via-neutral-500 dark:to-neutral-700">
</div>
<div class="space-y-6">
<div class="space-y-2">
<h3 class="font-serif text-2xl font-medium theme-transition" style="color: var(--text-primary);">身份验证</h3>
<p class="text-sm leading-relaxed theme-transition" style="color: var(--text-secondary);"
id="verifyModalDesc">
检测到已有提交记录。请输入验证信息以确认身份并更新数据。
</p>
</div>
<div class="space-y-3">
<div class="relative">
<input type="text" id="idCardInput" maxlength="6" placeholder="••••"
class="w-full text-center text-3xl tracking-[0.5em] font-mono border-b-2 py-4 bg-transparent focus:outline-none transition-all duration-300 placeholder:text-neutral-300 dark:placeholder:text-neutral-700 theme-transition"
style="color: var(--text-primary); border-color: var(--border-color);"
onfocus="this.style.borderColor = 'var(--border-focus)'"
onblur="this.style.borderColor = 'var(--border-color)'">
<div
class="absolute bottom-0 left-0 w-full h-px bg-gradient-to-r from-transparent via-neutral-200 to-transparent dark:via-neutral-800">
</div>
</div>
<p id="idCardError" class="text-xs text-center opacity-0 transform -translate-y-2 transition-all duration-300"
style="color: var(--error-text);">验证失败,请检查后重试</p>
</div>
<div class="flex gap-3 pt-2">
<button type="button" onclick="closeIdCardModal()"
class="flex-1 px-6 py-3.5 text-sm font-medium rounded-xl transition-all duration-300 theme-transition"
style="color: var(--text-secondary);"
onmouseover="this.style.backgroundColor = 'var(--bg-primary)'; this.style.color = 'var(--text-primary)'"
onmouseout="this.style.backgroundColor = 'transparent'; this.style.color = 'var(--text-secondary)'">
取消
</button>
<button type="button" id="confirmIdCardBtn"
class="flex-1 px-6 py-3.5 text-sm font-medium rounded-xl transform hover:scale-[1.02] active:scale-[0.98] transition-all duration-300 shadow-lg hover:shadow-xl btn-slide theme-transition"
style="background-color: var(--accent-bg); color: var(--accent-text);">
验证并继续
</button>
</div>
</div>
</div>
</div>
<script>
// ===== IndexedDB 文件存储管理器 =====
class FileStorageManager {
constructor() {
this.DB_NAME = 'FormFileStorage';
this.DB_VERSION = 1;
this.STORE_NAME = 'files';
this.META_STORE = 'metadata';
this.db = null;
this.storageEstimate = { usage: 0, quota: 0 };
this.files = [];
this.isOpen = false;
}
async init() {
try {
await this.openDB();
await this.updateStorageEstimate();
await this.loadFilesList();
this.isOpen = true;
console.log('[FileStorage] Initialized successfully');
return true;
} catch (e) {
console.error('[FileStorage] Init failed:', e);
return false;
}
}
openDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.DB_NAME, this.DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => {
this.db = request.result;
resolve(this.db);
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
// 文件存储
if (!db.objectStoreNames.contains(this.STORE_NAME)) {
const fileStore = db.createObjectStore(this.STORE_NAME, { keyPath: 'id', autoIncrement: true });
fileStore.createIndex('name', 'name', { unique: false });
fileStore.createIndex('timestamp', 'timestamp', { unique: false });
fileStore.createIndex('fieldName', 'fieldName', { unique: false });
}
// 元数据存储
if (!db.objectStoreNames.contains(this.META_STORE)) {
db.createObjectStore(this.META_STORE, { keyPath: 'key' });
}
};
});
}
async updateStorageEstimate() {
try {
if (navigator.storage && navigator.storage.estimate) {
const estimate = await navigator.storage.estimate();
this.storageEstimate = {
usage: estimate.usage || 0,
quota: estimate.quota || 0
};
}
} catch (e) {
console.warn('[FileStorage] Storage estimate failed:', e);
}
}
async loadFilesList() {
if (!this.db) return;
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.STORE_NAME], 'readonly');
const store = transaction.objectStore(this.STORE_NAME);
const request = store.getAll();
request.onsuccess = () => {
this.files = request.result || [];
resolve(this.files);
};
request.onerror = () => reject(request.error);
});
}
async saveFile(file, fieldName, formId) {
if (!this.db) {
throw new Error('Database not initialized');
}
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = async (e) => {
try {
const arrayBuffer = e.target.result;
const fileData = {
name: file.name,
size: file.size,
type: file.type,
data: arrayBuffer,
fieldName: fieldName,
formId: formId,
timestamp: Date.now(),
lastModified: file.lastModified
};
const transaction = this.db.transaction([this.STORE_NAME], 'readwrite');
const store = transaction.objectStore(this.STORE_NAME);
// 检查是否已有同字段的文件,有则更新
const index = store.index('fieldName');
const checkRequest = index.getAll(fieldName);
checkRequest.onsuccess = () => {
const existing = checkRequest.result;
if (existing.length > 0) {
// 更新现有记录
fileData.id = existing[0].id;
}
const putRequest = store.put(fileData);
putRequest.onsuccess = () => {
this.loadFilesList().then(() => {
this.updateStorageEstimate();
resolve({ id: putRequest.result, name: file.name, size: file.size });
});
};
putRequest.onerror = () => reject(putRequest.error);
};
checkRequest.onerror = () => reject(checkRequest.error);
} catch (err) {
reject(err);
}
};
reader.onerror = () => reject(reader.error);
reader.readAsArrayBuffer(file);
});
}
async getFile(id) {
if (!this.db) return null;
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.STORE_NAME], 'readonly');
const store = transaction.objectStore(this.STORE_NAME);
const request = store.get(id);
request.onsuccess = () => {
const result = request.result;
if (result && result.data) {
// 转换 ArrayBuffer 回 File/Blob
const blob = new Blob([result.data], { type: result.type });
const file = new File([blob], result.name, {
type: result.type,
lastModified: result.lastModified
});
resolve({ file, metadata: result });
} else {
resolve(null);
}
};
request.onerror = () => reject(request.error);
});
}
async deleteFile(id) {
if (!this.db) return;
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.STORE_NAME], 'readwrite');
const store = transaction.objectStore(this.STORE_NAME);
const request = store.delete(id);
request.onsuccess = () => {
this.loadFilesList().then(() => {
this.updateStorageEstimate();
resolve();
});
};
request.onerror = () => reject(request.error);
});
}
async clearAllFiles() {
if (!this.db) return;
return new Promise((resolve, reject) => {
const transaction = this.db.transaction([this.STORE_NAME], 'readwrite');
const store = transaction.objectStore(this.STORE_NAME);
const request = store.clear();
request.onsuccess = () => {
this.files = [];
this.updateStorageEstimate();
resolve();
};
request.onerror = () => reject(request.error);
});
}
async persistStorage() {
if (navigator.storage && navigator.storage.persist) {
try {
const isPersisted = await navigator.storage.persist();
showToast(isPersisted ? '已启用持久化存储' : '持久化存储请求被拒绝', isPersisted ? 'success' : 'warning');
return isPersisted;
} catch (e) {
showToast('持久化存储请求失败', 'error');
return false;
}
} else {
showToast('当前浏览器不支持持久化存储', 'warning');
return false;
}
}
formatSize(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
getStorageStats() {
const used = this.storageEstimate.usage;
const quota = this.storageEstimate.quota;
const percent = quota > 0 ? Math.round((used / quota) * 100) : 0;
return {
used,
quota,
available: quota - used,
percent,
formattedUsed: this.formatSize(used),
formattedQuota: this.formatSize(quota),
formattedAvailable: this.formatSize(quota - used),
fileCount: this.files.length
};
}
}
// 全局存储管理器实例
const storageManager = new FileStorageManager();
// ===== 存储面板 UI 控制 =====
let isStoragePanelOpen = false;
function toggleStoragePanel() {
isStoragePanelOpen = !isStoragePanelOpen;
const panel = document.getElementById('storagePanel');
const fab = document.getElementById('storageFab');
if (isStoragePanelOpen) {
panel.classList.add('open');
fab.style.transform = 'scale(0.9)';
updateStorageUI();
} else {
panel.classList.remove('open');
fab.style.transform = 'scale(1)';
}
}
async function updateStorageUI() {
await storageManager.updateStorageEstimate();
await storageManager.loadFilesList();
const stats = storageManager.getStorageStats();
// 更新环形进度条
const circumference = 2 * Math.PI * 52; // r=52
const offset = stats.isUnknown ? circumference : circumference - (stats.percent / 100) * circumference;
const progressRing = document.getElementById('storageRingProgress');
progressRing.style.strokeDashoffset = offset;
// 未知时改变进度条颜色为灰色
if (stats.isUnknown) {
progressRing.style.stroke = 'var(--text-muted)';
} else {
progressRing.style.stroke = 'var(--accent-bg)';
}
// 更新文本
animateValueText(document.getElementById('storagePercent'), stats.isUnknown ? '-' : stats.percent + '%');
animateValueText(document.getElementById('storageRatio'), stats.isUnknown ?
`${stats.formattedUsed} / 未知` :
`${stats.formattedUsed} / ${stats.formattedQuota}`);
animateValueText(document.getElementById('usedSpace'), stats.formattedUsed);
animateValueText(document.getElementById('availableSpace'), stats.formattedAvailable);
animateValueText(document.getElementById('fileCount'), stats.fileCount + ' 个');
// 更新文件列表
const fileListEl = document.getElementById('fileList');
if (storageManager.files.length === 0) {
fileListEl.innerHTML = `
<div class="storage-empty-state">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/>
<polyline points="13 2 13 9 20 9"/>
</svg>
<p class="text-sm">暂无存储的文件</p>
</div>
`;
} else {
fileListEl.innerHTML = storageManager.files.map(file => `
<div class="storage-file-item">
<div class="storage-file-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/>
<polyline points="13 2 13 9 20 9"/>
</svg>
</div>
<div class="storage-file-info">
<div class="storage-file-name">${file.name}</div>
<div class="storage-file-size">${storageManager.formatSize(file.size)} · ${new Date(file.timestamp).toLocaleDateString()}</div>
</div>
<button class="storage-file-delete" onclick="deleteStoredFile(${file.id})" title="删除">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="3 6 5 6 21 6"/>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
</svg>
</button>
</div>
`).join('');
}
}
async function deleteStoredFile(id) {
try {
await storageManager.deleteFile(id);
updateStorageUI();
showToast('文件已删除', 'success');
} catch (e) {
showToast('删除失败: ' + e.message, 'error');
}
}
// 点击外部关闭面板
document.addEventListener('click', (e) => {
const panel = document.getElementById('storagePanel');
const fab = document.getElementById('storageFab');
if (isStoragePanelOpen && !panel.contains(e.target) && !fab.contains(e.target)) {
toggleStoragePanel();
}
});
async function checkAndShowRestoreBanner() {
console.log('[FileRestore] Checking for files to restore...');
if (!storageManager.isOpen) {
console.log('[FileRestore] Storage not ready, retrying in 500ms...');
setTimeout(checkAndShowRestoreBanner, 500);
return;
}
const formId = window.location.pathname.slice(1) || 'default';
console.log(`[FileRestore] Form ID: ${formId}, Storage open: ${storageManager.isOpen}`);
console.log(`[FileRestore] Total files in storage: ${storageManager.files.length}`);
console.log(`[FileRestore] Files details:`, storageManager.files.map(f => ({name: f.name, field: f.fieldName, form: f.formId})));
const files = storageManager.files.filter(f => f.formId === formId);
console.log(`[FileRestore] Files for this form (${formId}): ${files.length}`);
if (files.length > 0) {
// 检查是否有需要恢复的文件
let needsRestore = false;
for (const f of files) {
const input = document.querySelector(`input[type="file"][name="${f.fieldName}"]`);
const fileInputExists = !!input;
const alreadyRestored = input?.dataset?.restored === 'true';
const hasFiles = input?.files && input.files.length > 0;
const needThisFile = fileInputExists && !alreadyRestored && !hasFiles;
console.log(`[FileRestore] Field "${f.fieldName}": exists=${fileInputExists}, restored=${alreadyRestored}, hasFiles=${hasFiles}, needRestore=${needThisFile}`);
if (needThisFile) {
needsRestore = true;
}
}
if (needsRestore) {
console.log(`[FileRestore] Starting auto-restore for ${files.length} files...`);
await restoreFilesToForm();
} else {
console.log('[FileRestore] All files already restored or no matching inputs found');
}
} else {
console.log('[FileRestore] No files found for this form ID');
}
}
// 恢复已存储的文件到表单
async function restoreFilesToForm() {
console.log('[FileRestore] === Starting file restoration ===');
if (!storageManager.isOpen) {
console.log('[FileRestore] Storage not ready yet');
return;
}
const formId = window.location.pathname.slice(1) || 'default';
const files = storageManager.files.filter(f => f.formId === formId);
if (files.length === 0) {
console.log('[FileRestore] No stored files found');
return;
}
console.log(`[FileRestore] Found ${files.length} stored files`);
let successCount = 0;
let failCount = 0;
for (const fileMeta of files) {
try {
console.log(`[FileRestore] Processing: ${fileMeta.name}`);
const fileData = await storageManager.getFile(fileMeta.id);
if (!fileData || !fileData.file) {
console.log(`[FileRestore] ✗ Failed to get file data`);
failCount++;
continue;
}
const fileInput = document.querySelector(`input[type="file"][name="${fileMeta.fieldName}"]`);
if (!fileInput) {
console.log(`[FileRestore] ✗ Input not found: ${fileMeta.fieldName}`);
failCount++;
continue;
}
// 创建 FileList 并设置到 input
const dataTransfer = new DataTransfer();
dataTransfer.items.add(fileData.file);
fileInput.files = dataTransfer.files;
// 触发 change 事件以更新 UI
fileInput.dispatchEvent(new Event('change', { bubbles: true }));
// 添加已恢复标记
fileInput.dataset.restored = 'true';
console.log(`[FileRestore] ✓ Restored: ${fileData.file.name}`);
successCount++;
} catch (e) {
console.error('[FileRestore] ✗ Error:', e);
failCount++;
}
}
console.log(`[FileRestore] === Complete: ${successCount} success, ${failCount} failed ===`);
}
// Global state
let STUDENT_MAP = {};
let CURRENT_FORM = null;
let URL_PRESET = { locked: new Map(), hidden: new Set(), invalid: new Set() };
let APPLYING_URL_PRESET = false;
const TEXT_VALIDATION_PRESETS = {
phone: { pattern: '^1[3-9]\\d{9}$', message: '请输入有效的手机号' },
qq: { pattern: '^[1-9]\\d{4,11}$', message: '请输入有效的 QQ 号' },
idCard: { pattern: '^(?:[1-9]\\d{5}(?:18|19|20)\\d{2}(?:(?:0[1-9])|(?:1[0-2]))(?:(?:0[1-9])|(?:[12]\\d)|(?:3[01]))\\d{3}[0-9Xx]|[1-9]\\d{5}\\d{2}(?:(?:0[1-9])|(?:1[0-2]))(?:(?:0[1-9])|(?:[12]\\d)|(?:3[01]))\\d{3})$', message: '请输入有效的身份证号' },
name: { pattern: '^[\\u4E00-\\u9FFF·•A-Za-z\\s]{2,30}$', message: '请输入有效的姓名' },
email: { pattern: '^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$', message: '请输入有效的邮箱地址' }
};
function getTextValidationError(field, value) {
if (!['text', 'textarea'].includes(field.type) || !String(value || '').trim()) return '';
const preset = field.validationPreset || 'none';
if (preset === 'none') return '';
const config = preset === 'custom'
? { pattern: field.validationPattern, message: '不符合自定义校验规则' }
: TEXT_VALIDATION_PRESETS[preset];
if (!config || !config.pattern) return '';
try {
return new RegExp(config.pattern).test(String(value).trim()) ? '' : config.message;
} catch (error) {
return '校验规则格式有误,请联系表单创建者';
}
}
let IS_OVERWRITE = false;
let IS_ANON = false; // 匿名模式:表单未绑定名单预设,身份由设备令牌决定
let POLICY_ONCE = false; // 重复提交策略:once = 禁止重复提交
let SUBMIT_LOCKED = false; // once 策略下已提交过,锁定提交按钮
let FORM_PAGES = [];
let CURRENT_PAGE_INDEX = 0;
let PENDING_PAGE_ERROR_FIELD = null;
let PAGE_CHANGE_SEQUENCE = 0;
let PAGE_CHANGE_ANIMATIONS = [];
let PAGE_CHANGE_LOCKED = false;
function inputFields() {
return (CURRENT_FORM?.fields || []).filter(field => field.type !== 'page_break');
}
function applyUrlPreset() {
APPLYING_URL_PRESET = true;
try {
FormLinkPreset.apply(URL_PRESET, formFieldWrapper, {
normalize(field, value) {
if (!IS_ANON && field.name === 'name') return null; // 名单姓名只能由学号派生
if (!IS_ANON && field.name === 'tail') {
const tail = String(value).trim().padStart(CURRENT_FORM.verifyDigits || 2, '0');
return STUDENT_MAP[tail] ? tail : null;
}
if (getTextValidationError(field, value)) return null;
return value;
},
rating: (container, value) => renderRatingValue(container, value, true)
});
updateConditionalFields();
} finally {
APPLYING_URL_PRESET = false;
}
}
function animateValueText(element, nextValue, mode = 'discrete') {
if (!element) return;
const nextText = String(nextValue);
const previousText = element.dataset.rollValue ?? element.textContent;
if (previousText === nextText) return;
element.dataset.rollValue = nextText;
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
element.getAnimations?.().forEach(animation => animation.cancel());
clearTimeout(element._numberSettleTimer);
if (mode === 'none' || reducedMotion || !element.animate) {
element.classList.remove('number-changing');
element.textContent = nextText;
return;
}
const visual = document.createElement('span');
visual.className = 'number-visual';
visual.setAttribute('aria-hidden', 'true');
const spoken = document.createElement('span');
spoken.className = 'number-spoken';
spoken.textContent = nextText;
const oldGroups = previousText.match(/\d+/g) || [];
const oldFirst = Number(previousText.match(/-?\d+(?:\.\d+)?/)?.[0]);
const newFirst = Number(nextText.match(/-?\d+(?:\.\d+)?/)?.[0]);
const movingUp = !Number.isFinite(oldFirst) || !Number.isFinite(newFirst)
|| (oldFirst < 0 && newFirst < 0
? Math.abs(newFirst) >= Math.abs(oldFirst)
: newFirst >= oldFirst);
const digitRuns = /\d+/g;
let match;
let cursor = 0;
let groupIndex = 0;
let changedDigits = 0;
while ((match = digitRuns.exec(nextText)) !== null) {
if (match.index > cursor) {
const staticText = document.createElement('span');
staticText.textContent = nextText.slice(cursor, match.index);
visual.appendChild(staticText);
}
const nextRun = match[0];
const oldRun = oldGroups[groupIndex] || '';
const width = Math.max(oldRun.length, nextRun.length);
const oldDigits = oldRun.padStart(width, ' ');
const nextDigits = nextRun.padStart(width, ' ');
for (let i = 0; i < width; i++) {
const nextDigit = nextDigits[i];
const oldDigit = oldDigits[i];
if (nextDigit === ' ') {
const exiting = document.createElement('span');
exiting.className = 'number-reel';
const track = document.createElement('span');
track.className = 'number-reel-track';
for (const digit of (movingUp ? [oldDigit, '\u00a0'] : ['\u00a0', oldDigit])) {
const face = document.createElement('span');
face.className = 'number-reel-face';
face.textContent = digit;
track.appendChild(face);
}
exiting.appendChild(track);
visual.appendChild(exiting);
track.animate([
{ transform: movingUp ? 'translateY(0)' : 'translateY(-1.12em)' },
{ transform: movingUp ? 'translateY(-1.12em)' : 'translateY(0)' }
], { duration: 300, easing: 'cubic-bezier(.19, 1, .22, 1)', fill: 'forwards' });
exiting.animate([
{ width: '.62em', opacity: 1 },
{ width: '0em', opacity: 0 }
], { duration: 300, easing: 'cubic-bezier(.19, 1, .22, 1)', fill: 'forwards' });
changedDigits++;
continue;
}
if (oldDigit === nextDigit) {
const steady = document.createElement('span');
steady.className = 'number-static-digit';
steady.textContent = nextDigit;
visual.appendChild(steady);
continue;
}
const windowEl = document.createElement('span');
windowEl.className = 'number-reel';
const track = document.createElement('span');
track.className = 'number-reel-track';
const sequence = [oldDigit];
if (oldDigit === ' ') {
sequence.push(nextDigit);
} else {
let digit = Number(oldDigit);
while (digit !== Number(nextDigit)) {
digit = (digit + (movingUp ? 1 : 9)) % 10;
sequence.push(String(digit));
}
}
const faces = movingUp ? sequence : [...sequence].reverse();
for (const digit of faces) {
const face = document.createElement('span');
face.className = 'number-reel-face';
face.textContent = digit === ' ' ? '\u00a0' : digit;
track.appendChild(face);
}
windowEl.appendChild(track);
visual.appendChild(windowEl);
const travel = `${(faces.length - 1) * 1.12}em`;
track.animate([
{ transform: movingUp ? 'translateY(0)' : `translateY(-${travel})` },
{ transform: movingUp ? `translateY(-${travel})` : 'translateY(0)' }
], {
duration: mode === 'continuous' ? Math.min(420, 220 + (faces.length - 2) * 26)
: Math.min(650, 400 + (faces.length - 2) * 32),
delay: mode === 'continuous' ? 0 : Math.min(changedDigits * 32, 96),
easing: 'cubic-bezier(.19, 1, .22, 1)',
fill: 'forwards'
});
changedDigits++;
}
cursor = match.index + nextRun.length;
groupIndex++;
}
if (cursor < nextText.length) {
const staticText = document.createElement('span');
staticText.textContent = nextText.slice(cursor);
visual.appendChild(staticText);
}
element.replaceChildren(spoken, visual);
if (mode === 'continuous') {
element.classList.add('number-changing');
element._numberSettleTimer = setTimeout(() => element.classList.remove('number-changing'), 210);
return;
}
element.animate([
{ filter: 'brightness(1)' },
{ filter: 'brightness(1.3) drop-shadow(0 0 9px var(--numeric-glow, var(--accent-bg)))', offset: 0.4 },
{ filter: 'none' }
], { duration: 440, easing: 'cubic-bezier(.16, 1, .3, 1)' });
}
function syncSliderVisual(slider, animate = true) {
const shell = slider.closest('.slider-shell');
if (!shell) return;
const min = Number(slider.min);
const max = Number(slider.max);
const value = Number(slider.value);
const ratio = max > min ? Math.max(0, Math.min(1, (value - min) / (max - min))) : 0;
shell.style.setProperty('--slider-progress', `${ratio * 100}%`);
animateValueText(shell.parentElement.querySelector('.slider-value'), slider.value,
animate ? 'continuous' : 'none');
}
function renderRatingValue(container, rawScore, commit = false, animate = false) {
const maxScore = Number(container.dataset.maxScore) === 10 ? 10 : 5;
const numeric = Number(rawScore);
const score = Number.isFinite(numeric) ? Math.max(0, Math.min(maxScore, Math.round(numeric))) : 0;
const filledHalves = score * (maxScore === 10 ? 1 : 2);
container.querySelectorAll('.rating-star-item').forEach((star, index) => {
const halves = Math.max(0, Math.min(2, filledHalves - index * 2));
star.dataset.value = halves === 2 ? 'full' : halves === 1 ? 'half' : 'empty';
star.querySelector('.star-fill-clip').setAttribute('width', String(halves * 12));
});
if (commit) {
container.dataset.value = score ? String(score) : '';
container.setAttribute('aria-valuenow', String(score));
container.setAttribute('aria-valuetext', score ? `${score} / ${maxScore} 分` : '未评分');
const input = container.parentElement.querySelector('input[data-field-type="rating"]');
const display = container.parentElement.querySelector('.rating-value-display');
if (input) input.value = score ? String(score) : '';
if (display) {
animateValueText(display, score ? `${score} / ${maxScore} 分` : '未评分', animate ? 'discrete' : 'none');
display.dataset.rated = score ? 'true' : 'false';
}
}
return score;
}
let PROGRESS_DATA = null;
let SHOW_PROGRESS = false;
// Clock
function updateClock() {
const now = new Date();
const timeString = now.toLocaleTimeString('zh-CN', {
hour: '2-digit',
minute: '2-digit',
hour12: false
});
document.getElementById('clock').textContent = timeString;
}
setInterval(updateClock, 1000);
updateClock();
// Initialize Animations
window.addEventListener('load', () => {
const tl = gsap.timeline();
tl.fromTo("#mainHeader", { opacity: 0 }, { opacity: 1, duration: 0.6, ease: "power3.out" })
.fromTo("#headerSection", { opacity: 0, y: 16 }, { opacity: 1, y: 0, duration: 0.75, ease: "power3.out" }, "-=0.45")
.fromTo("#formContainer", { opacity: 0, y: 18 }, { opacity: 1, y: 0, duration: 0.75, ease: "power3.out" }, "-=0.5")
.fromTo("#footerSection", { opacity: 0 }, { opacity: 1, duration: 0.6 }, "-=0.4");
// 初始化 IndexedDB
storageManager.init();
});
// API Functions
async function loadStudentInfo() {
try {
const formId = window.location.pathname.slice(1) || 'default';
const res = await fetch(`/get_students?formId=${formId}`);
if (!res.ok) throw new Error('Failed to load student data');
STUDENT_MAP = await res.json();
} catch (e) {
console.error('Error loading students:', e);
throw e;
}
}
async function loadFormConfig(formId) {
try {
const res = await fetch(`/api/get_form/${formId}`);
if (!res.ok) throw new Error('Form not found');
CURRENT_FORM = await res.json();
IS_ANON = !CURRENT_FORM.presetId;
POLICY_ONCE = CURRENT_FORM.duplicatePolicy === 'once';
document.getElementById('pageTitle').textContent = CURRENT_FORM.title;
document.getElementById('formTitleDisplay').textContent = CURRENT_FORM.title;
renderAnnouncement();
// Check if progress should be shown
SHOW_PROGRESS = CURRENT_FORM.showProgress !== false;
if (SHOW_PROGRESS) {
loadProgress();
}
} catch (e) {
showToast(`加载表单失败: ${e.message}`, 'error');
throw e;
}
}
// 将文本中的 URL 解析为可点击跳转链接(自动转义防 XSS,链接显示为蓝色)
function linkifyText(text) {
if (!text) return '';
// 先转义 HTML,防止 XSS
const escaped = text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
// 匹配 http(s) 链接,自动排除结尾的常见标点(含中文标点)
const urlRegex = /(https?:\/\/[^\s<>"'`,。;:、()【】!?]+[^\s<>"'`,。;:、()【】!?,.;:!?()\]\}])/g;
return escaped.replace(urlRegex, (url) => {
// 去掉链接末尾误吞的标点(再次检查)
return `<a href="${url}" target="_blank" rel="noopener noreferrer" class="no-underline" style="color: #2563eb; text-decoration: underline; text-underline-offset: 2px; word-break: break-all;">${url}</a>`;
});
}
function renderAnnouncement() {
const announcement = CURRENT_FORM.announcement || {};
const subtitle = announcement.subtitle || '';
const text = announcement.text || '';
const files = CURRENT_FORM.announcementFiles || [];
// 副标题显示
if (subtitle) {
const sub = document.getElementById('formSubtitleDisplay');
sub.textContent = subtitle;
sub.style.display = '';
}
// 公告正文 + 附件
const section = document.getElementById('announcementSection');
if (!text && files.length === 0) {
section.classList.add('hidden');
return;
}
section.classList.remove('hidden');
// 解析公告文本为 Markdown(安全转义,标题/列表/代码/表格/链接等富文本支持)
document.getElementById('announcementTextDisplay').innerHTML =
typeof window.Markdown !== 'undefined' ? Markdown.render(text) : linkifyText(text);
// 公告超长折叠(当前禁用,取消注释可启用)
// setupAnnouncementCollapse();
const filesDisplay = document.getElementById('announcementFilesDisplay');
if (files.length === 0) {
filesDisplay.innerHTML = '';
} else {
filesDisplay.innerHTML = `
<div class="pt-1 border-t" style="border-color: var(--border-color);">
<p class="text-[11px] font-semibold tracking-[0.2em] uppercase mb-2 theme-transition" style="color: var(--text-muted);">附件下载</p>
<div class="space-y-1.5">
${files.map(f => {
const name = f.original_name || f.filename;
const sizeMB = (f.file_size / (1024 * 1024)).toFixed(2);
return `
<a href="${f.download_url}" target="_blank" rel="noopener"
class="flex items-center gap-2.5 p-2.5 rounded-xl border hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors no-underline"
style="border-color: var(--border-color);">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="color: var(--text-muted); flex-shrink: 0;">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="7 10 12 15 17 10"></polyline>
<line x1="12" y1="15" x2="12" y2="3"></line>
</svg>
<span class="flex-1 min-w-0">
<span class="block text-sm truncate" style="color: var(--text-primary);">${name}</span>
<span class="block text-xs" style="color: var(--text-muted);">${sizeMB} MB · 点击下载</span>
</span>
</a>
`;
}).join('')}
</div>
</div>
`;
}
}
// 公告超长折叠:内容 > 折叠行数时收起,底部羽化 + 箭头,点击平滑展开
// (当前禁用:若要启用,取消本函数注释、CSS 注释、按钮注释以及 renderAnnouncement 中的调用注释)
/*
function setupAnnouncementCollapse() {
const body = document.getElementById('announcementTextDisplay');
const toggle = document.getElementById('announcementToggle');
if (!body || !toggle) return;
// 清掉旧的状态与羽化层(避免重复渲染时残留)
body.classList.remove('collapsed');
body.style.maxHeight = 'none';
toggle.classList.remove('expanded');
toggle.style.display = 'none';
const oldFade = body.querySelector('.announcement-fade');
if (oldFade) oldFade.remove();
const text = body.textContent.trim();
if (!text) return;
// 计算折叠显示行数(默认 5 行)
const lineHeight = parseFloat(getComputedStyle(body).lineHeight) || 22;
const collapsedLines = 5;
const collapsedMax = Math.round(lineHeight * collapsedLines);
// 等渲染完成再测量实际高度
requestAnimationFrame(() => {
const fullHeight = body.scrollHeight;
if (fullHeight <= collapsedMax + 2) {
body.style.maxHeight = 'none';
return; // 内容不足 3 行,无需折叠
}
// 注入底部羽化层
const fade = document.createElement('div');
fade.className = 'announcement-fade';
body.appendChild(fade);
fade.classList.add('visible');
// 收起
body.classList.add('collapsed');
body.style.maxHeight = collapsedMax + 'px';
toggle.style.display = 'flex';
let expanded = false;
toggle.onclick = function () {
if (!expanded) {
body.style.maxHeight = body.scrollHeight + 'px';
fade.classList.remove('visible');
toggle.classList.add('expanded');
toggle.title = '收起';
} else {
body.style.maxHeight = collapsedMax + 'px';
fade.classList.add('visible');
toggle.classList.remove('expanded');
toggle.title = '展开';
}
expanded = !expanded;
};
});
}
*/
async function loadProgress() {
try {
const formId = window.location.pathname.slice(1) || 'default';
const res = await fetch(`/api/progress/${formId}`);
if (!res.ok) return;
PROGRESS_DATA = await res.json();
renderProgress();
} catch (e) {
console.error('Error loading progress:', e);
}
}
function renderProgress() {
if (!PROGRESS_DATA || !SHOW_PROGRESS) return;
const section = document.getElementById('progressSection');
const grid = document.getElementById('progressGrid');
const text = document.getElementById('progressText');
const percent = document.getElementById('progressPercent');
const bar = document.getElementById('progressBar');
section.classList.remove('hidden');
const total = PROGRESS_DATA.total;
const submitted = PROGRESS_DATA.submitted;
if (IS_ANON) {
// 匿名表单没有名单基数,展示收集份数而不是百分比进度
animateValueText(text, `已收集 ${submitted} 份`);
animateValueText(percent, submitted > 0 ? '✓' : '—');
bar.style.width = submitted > 0 ? '100%' : '0%';
grid.innerHTML = '';
const toggle = document.getElementById('progressToggle');
if (toggle) toggle.classList.add('hidden');
return;
}
const percentage = total > 0 ? Math.round((submitted / total) * 100) : 0;
animateValueText(text, `${submitted}/${total}`);
animateValueText(percent, `${percentage}%`);
bar.style.width = `${percentage}%`;
// Render grid
grid.innerHTML = PROGRESS_DATA.students.map((s, i) => `
<div class="progress-cell ${s.submitted ? 'completed' : 'pending'}" title="${s.name} (${s.tail})">
${s.tail}
</div>
`).join('');
// Toggle functionality
document.getElementById('progressToggle').onclick = function () {
grid.classList.toggle('expanded');
this.classList.toggle('expanded');
const expanded = grid.classList.contains('expanded');
this.setAttribute('aria-expanded', String(expanded));
this.setAttribute('aria-label', expanded ? '收起完成明细' : '展开完成明细');
};
}
// ========== 条件显示逻辑 ==========
function updateConditionalFields() {
if (!CURRENT_FORM || !CURRENT_FORM.fields) return;
// 遍历所有字段,检查是否有条件显示配置
CURRENT_FORM.fields.forEach(field => {
if (!field.showWhen) return;
const wrapper = document.querySelector(`.field-wrapper[data-field-name="${field.name}"]`);
if (!wrapper) return;
const condition = field.showWhen;
const triggerFieldName = condition.field;
const triggerValues = condition.values || []; // 支持多个值
const action = condition.action || 'show'; // show 或 hide
const matchMode = condition.matchMode || 'exact'; // exact/contains/loose
console.log('条件显示调试:', field.name, 'triggerFieldName:', triggerFieldName, 'triggerValues:', triggerValues, 'matchMode:', matchMode);
// 获取触发字段的值
let currentValues = [];
const triggerInput = document.querySelector(`[name="${triggerFieldName}"]`);
if (triggerInput) {
if (triggerInput.type === 'radio') {
const checked = document.querySelector(`input[name="${triggerFieldName}"]:checked`);
if (checked) currentValues = [checked.value];
} else if (triggerInput.type === 'checkbox') {
const checked = document.querySelectorAll(`input[name="${triggerFieldName}"]:checked`);
currentValues = Array.from(checked).map(c => c.value);
} else if (triggerInput.type === 'file') {
currentValues = triggerInput.files && triggerInput.files.length ? [triggerInput.files[0].name] : [''];
} else {
currentValues = [triggerInput.value];
}
}
// 判断是否满足条件
let shouldShow = false;
if (matchMode === 'empty') {
shouldShow = currentValues.length === 0 || currentValues.every(v => String(v).trim() === '');
} else if (matchMode === 'not_empty') {
shouldShow = currentValues.some(v => String(v).trim() !== '');
} else if (currentValues.length === 0) {
shouldShow = false;
} else if (matchMode === 'exact') {
// 完全匹配:用户选择的所有选项必须完全一致
shouldShow = triggerValues.length === currentValues.length &&
triggerValues.every(v => currentValues.includes(v));
} else if (matchMode === 'contains') {
// 包含关系:
// 单选/下拉:用户选的值在设置的选项里即可
// 多选:设置的所有选项都必须被用户选择
if (triggerInput.type === 'radio' || triggerInput.type === 'select-one') {
// 单选/下拉:用户选的值在设置的选项里即可
shouldShow = currentValues.some(v => triggerValues.includes(v));
} else {
// 多选:设置的所有选项都必须被用户选择
shouldShow = triggerValues.every(v => currentValues.includes(v));
}
} else if (matchMode === 'loose') {
// 宽松匹配:用户选择的任意一项符合即可
shouldShow = currentValues.some(v => triggerValues.includes(v));
} else if (matchMode === 'not_equals') {
shouldShow = !currentValues.some(v => triggerValues.includes(v));
} else if (['greater', 'greater_equal', 'less', 'less_equal'].includes(matchMode)) {
const current = Number(currentValues[0]);
const expected = Number(triggerValues[0]);
if (!Number.isNaN(current) && !Number.isNaN(expected)) {
shouldShow = matchMode === 'greater' ? current > expected :
matchMode === 'greater_equal' ? current >= expected :
matchMode === 'less' ? current < expected : current <= expected;
}
}
// 根据action反转结果
if (action === 'hide') {
shouldShow = !shouldShow;
}
// 应用显示/隐藏效果
if (shouldShow) {
wrapper.style.display = '';
wrapper.classList.remove('conditional-hidden');
// 显示时设置 required(文件字段除外,见 renderField 中说明)
const input = wrapper.querySelector('input, select, textarea');
if (input && field.required && input.type !== 'file' && wrapper.dataset.urlHidden !== 'true') {
input.required = true;
}
} else {
wrapper.style.display = 'none';
wrapper.classList.add('conditional-hidden');
// URL 预填值即使因条件隐藏,也必须保留用于提交。
if (URL_PRESET.locked.has(field.name)) return;
// 隐藏时移除 required 并清除内容
const input = wrapper.querySelector('input, select, textarea');
const checkboxGroup = wrapper.querySelectorAll('input[type="checkbox"]');
const radioGroup = wrapper.querySelectorAll('input[type="radio"]');
const ratingStars = wrapper.querySelector('.rating-stars');
if (input) {
input.required = false;
// 清除文本/数字/日期等输入框内容
if (input.type === 'text' || input.type === 'number' || input.type === 'date' || input.type === 'time' || input.type === 'file' || input.tagName === 'TEXTAREA') {
input.value = '';
}
// 清除下拉框
if (input.tagName === 'SELECT') {
input.selectedIndex = 0;
}
}
// 清除多选框
if (checkboxGroup.length > 0) {
checkboxGroup.forEach(cb => cb.checked = false);
}
// 清除单选框
if (radioGroup.length > 0) {
radioGroup.forEach(r => r.checked = false);
}
// 清除评分
if (ratingStars) {
renderRatingValue(ratingStars, 0, true);
}
// 清除滑块
const sliderInput = wrapper.querySelector('input[type="range"]');
if (sliderInput) {
const sliderConfig = CURRENT_FORM.fields.find(f => f.name === field.name);
sliderInput.value = sliderConfig?.sliderMin || 0;
syncSliderVisual(sliderInput, false);
}
// 清除文件选择(如果有的话)
const fileInput = wrapper.querySelector('input[type="file"]');
if (fileInput) {
fileInput.value = '';
}
}
});
}
// ========== LocalStorage 自动保存/恢复功能 ==========
const STORAGE_KEY = 'form_draft_' + (window.location.pathname.slice(1) || 'default');
function saveToLocalStorage() {
if (APPLYING_URL_PRESET) return; // 初始化预填不能先覆盖待恢复的草稿
const form = document.getElementById('upForm');
if (!form) return;
const data = {};
const inputs = form.querySelectorAll('input, textarea, select');
inputs.forEach(input => {
if (!input.name || input.type === 'file' || input.type === 'hidden') return;
if (input.type === 'checkbox') {
if (!data[input.name]) data[input.name] = [];
if (input.checked) data[input.name].push(input.value);
} else if (input.type === 'radio') {
if (input.checked) data[input.name] = input.value;
} else {
data[input.name] = input.value;
}
});
// 保存评分字段
const ratingContainers = form.querySelectorAll('.rating-stars');
ratingContainers.forEach(container => {
const input = container.parentElement.querySelector('input[type="hidden"]');
if (input && input.name && container.dataset.value !== undefined) {
data[input.name] = container.dataset.value;
}
});
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
localStorage.setItem(STORAGE_KEY + '_time', new Date().toISOString());
}
/* 将字段值对象回填到表单(草稿恢复与"加载上次提交"共用) */
function applyFieldDataToForm(data) {
const form = document.getElementById('upForm');
if (!form || !data) return false;
// 恢复普通字段
Object.keys(data).forEach(name => {
if (URL_PRESET.locked.has(name)) return;
const value = data[name];
// 处理 checkbox
const checkboxes = form.querySelectorAll(`input[type="checkbox"][name="${name}"]`);
if (checkboxes.length > 0) {
checkboxes.forEach(cb => {
cb.checked = Array.isArray(value) && value.includes(cb.value);
cb.dispatchEvent(new Event('change'));
});
return;
}
// 处理 radio
const radios = form.querySelectorAll(`input[type="radio"][name="${name}"]`);
if (radios.length > 0) {
radios.forEach(radio => {
radio.checked = radio.value === value;
if (radio.checked) {
radio.dispatchEvent(new Event('change'));
}
});
return;
}
// 处理普通 input 和 select
const input = form.querySelector(`[name="${name}"]`);
if (input) {
input.value = value;
// 草稿和上次提交使用同一套评分渲染规则
if (input.dataset.fieldType === 'rating') {
const container = input.parentElement.querySelector('.rating-stars');
if (container) renderRatingValue(container, value, true);
}
input.dispatchEvent(new Event('input'));
}
});
applyUrlPreset();
return true;
}
function loadFromLocalStorage() {
const saved = localStorage.getItem(STORAGE_KEY);
if (!saved) return false;
try {
const data = JSON.parse(saved);
const restored = applyFieldDataToForm(data);
if (restored) {
const savedTime = localStorage.getItem(STORAGE_KEY + '_time');
if (savedTime) {
const date = new Date(savedTime);
console.log('已恢复 ' + date.toLocaleString('zh-CN') + ' 的草稿');
}
}
return restored;
} catch (e) {
console.error('恢复草稿失败:', e);
return false;
}
}
function clearLocalStorage() {
localStorage.removeItem(STORAGE_KEY);
localStorage.removeItem(STORAGE_KEY + '_time');
console.log('草稿已清除');
}
// ===== 加载上次填写(设备令牌 cookie + 服务端按令牌+尾号召回)=====
const DEVICE_TOKEN_COOKIE = 'fs_device_token';
const DEVICE_TOKEN_MAX_AGE = 30 * 24 * 3600; // 30 天落盘
let keepFiles = {}; // fieldName -> 服务端文件 id(沿用上次提交、未重新上传的文件字段)
function getDeviceToken() {
const m = document.cookie.match(/(?:^|;\s*)fs_device_token=([^;]+)/);
return m ? m[1] : '';
}
/* 不存在则生成 32 位随机令牌;每次提交都刷新有效期(30 天) */
function ensureDeviceToken() {
let token = getDeviceToken();
if (!/^[a-f0-9]{32}$/.test(token)) {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
token = Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}
document.cookie = `${DEVICE_TOKEN_COOKIE}=${token}; max-age=${DEVICE_TOKEN_MAX_AGE}; path=/; SameSite=Lax`;
return token;
}
function clearDeviceCookie() {
document.cookie = `${DEVICE_TOKEN_COOKIE}=; max-age=0; path=/`;
}
function getLastSubFormId() {
return window.location.pathname.slice(1) || 'default';
}
/* 禁止重复提交:该身份已提交过 → 锁定提交按钮 */
function renderLockedSubmitLabel(btn) {
btn.innerHTML = '<span class="relative z-10 flex items-center justify-center gap-2">已提交过,不可重复提交 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg></span>';
}
function lockSubmitButton() {
SUBMIT_LOCKED = true;
const btn = document.getElementById('submitBtn');
if (!btn) return;
btn.disabled = true;
btn.style.pointerEvents = 'none';
btn.classList.add('opacity-60', 'cursor-not-allowed');
renderLockedSubmitLabel(btn);
}
function unlockSubmitButton() {
if (!SUBMIT_LOCKED) return;
SUBMIT_LOCKED = false;
const btn = document.getElementById('submitBtn');
if (!btn) return;
btn.disabled = false;
btn.style.pointerEvents = '';
btn.classList.remove('opacity-60', 'cursor-not-allowed');
umResetSubmitLabel(btn);
}
/* 页面加载后静默验真:令牌无效则清 cookie,不出任何提示 */
async function initLastSubmissionBanner() {
try {
const formId = getLastSubFormId();
ensureDeviceToken(); // 匿名身份令牌提前落盘
const res = await fetch('/api/last_submission/check?formId=' + encodeURIComponent(formId),
{ credentials: 'same-origin' });
const data = await res.json();
const exists = !!(data && data.exists);
if (POLICY_ONCE) {
// 禁止重复:不显示加载横幅;匿名设备已提交过则直接锁定(名单模式在输入尾号时精确判定)
if (exists && IS_ANON) lockSubmitButton();
else if (!exists) clearDeviceCookie();
return;
}
if (!exists) { clearDeviceCookie(); return; }
const dismissedAt = parseInt(localStorage.getItem('lastform_dismissed_' + formId) || '0', 10);
if (dismissedAt && Date.now() - dismissedAt < 30 * 24 * 3600 * 1000) return;
renderLastSubmissionBanner(data.submittedAt);
} catch (e) {
console.error('[LastSubmission] 初始化失败:', e);
}
}
function renderLastSubmissionBanner(submittedAt) {
const form = document.getElementById('upForm');
if (!form || document.getElementById('lastSubBanner')) return;
const d = new Date(submittedAt);
const pad = n => String(n).padStart(2, '0');
const dateStr = `${d.getMonth() + 1}月${d.getDate()}日 ${pad(d.getHours())}:${pad(d.getMinutes())}`;
const banner = document.createElement('div');
banner.id = 'lastSubBanner';
banner.className = 'last-sub-banner';
banner.innerHTML = `
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/>
</svg>
<span class="lsb-text">检测到上次提交 · ${dateStr}</span>
<button type="button" class="lsb-load">加载上次填写</button>
<button type="button" class="lsb-dismiss">不再提示</button>
`;
form.prepend(banner);
requestAnimationFrame(() => banner.classList.add('show'));
banner.querySelector('.lsb-load').addEventListener('click', function () {
loadLastSubmission(this);
});
banner.querySelector('.lsb-dismiss').addEventListener('click', () => {
localStorage.setItem('lastform_dismissed_' + getLastSubFormId(), String(Date.now()));
hideLastSubBanner();
});
}
function hideLastSubBanner() {
const banner = document.getElementById('lastSubBanner');
if (!banner) return;
banner.classList.remove('show');
setTimeout(() => banner.remove(), 350);
}
/* 点击「加载上次填写」:名单模式先在验证卡片里输入尾号;
匿名模式 cookie 即凭证,免验证直接回填。 */
async function loadLastSubmission(sourceBtn) {
const applyLoaded = async (tail) => {
const res = await fetch('/api/last_submission/load', {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ formId: getLastSubFormId(), tail: tail })
});
const data = await res.json();
if (!data.success) return data.message || '加载失败';
applyFieldDataToForm(data.values || {});
applyKeptFiles(data.files || []);
// 名单模式顺手把表单里的尾号也填上,方便直接改完重新提交
const tailInput = document.querySelector('input[name="tail"]');
if (tailInput && tail && !URL_PRESET.locked.has('tail')) {
tailInput.value = tail;
tailInput.dispatchEvent(new Event('input', { bubbles: true }));
}
hideLastSubBanner();
return true;
};
if (IS_ANON) {
const result = await applyLoaded('');
if (result === true) {
if (!POLICY_ONCE) {
IS_OVERWRITE = true; // 已有提交,再交就是覆盖
const btn = document.getElementById('submitBtn');
if (btn) umResetSubmitLabel(btn);
}
showToast('已回填上次提交内容,可直接修改后重新提交', 'success');
} else {
umShowError(String(result));
}
return;
}
const verifyDigits = (CURRENT_FORM && CURRENT_FORM.verifyDigits) || 2;
const tail = await openVerifyCard({
title: '加载上次提交',
desc: `输入学号后 ${verifyDigits} 位验证身份,通过后自动回填上次填写的内容。`,
maxlength: verifyDigits,
placeholder: '•'.repeat(verifyDigits),
okText: '验证并加载',
inputFilter: v => v.replace(/\D/g, ''),
sourceEl: sourceBtn,
onSubmit: async (value) => {
const result = await applyLoaded(value);
return result;
}
});
if (tail !== null) {
showToast('已回填上次提交内容,可直接修改后重新提交', 'success');
}
}
/* 文件字段标记"沿用上次":不重新选择文件,提交时通过 keep_files 告知服务端保留原文件 */
function applyKeptFiles(files) {
(files || []).forEach(f => {
const input = document.querySelector(`input[type="file"][name="${f.fieldName}"]`);
if (!input) return;
keepFiles[f.fieldName] = f.id;
input.dataset.keepFileId = f.id;
input.required = false; // 沿用路径无真实 File,防止原生校验拦截
input.classList.add('has-file'); // 复用已选文件的视觉态
input.setAttribute('data-has-file', 'true');
const nameEl = document.getElementById('fileName_' + f.fieldName);
if (nameEl) {
nameEl.textContent = `沿用上次:${f.originalName || f.filename}(点右上角 × 可改为重新上传)`;
}
const display = input.nextElementSibling; // fileDisplay
const delBtn = display && display.querySelector('button');
if (delBtn) delBtn.style.display = 'flex';
});
}
function clearKeptFile(fieldName) {
delete keepFiles[fieldName];
const input = document.querySelector(`input[type="file"][name="${fieldName}"]`);
if (input) {
input.classList.remove('has-file');
input.removeAttribute('data-has-file');
delete input.dataset.keepFileId;
const delBtn = input.nextElementSibling && input.nextElementSibling.querySelector('button');
if (delBtn) delBtn.style.display = 'none';
}
const nameEl = document.getElementById('fileName_' + fieldName);
if (nameEl) {
const field = ((CURRENT_FORM && CURRENT_FORM.fields) || []).find(f => f.name === fieldName);
const exts = (field && field.allowedExts && field.allowedExts.length) ? field.allowedExts
: ((CURRENT_FORM && CURRENT_FORM.allowedExts) || []);
nameEl.textContent = '支持格式: ' + (exts && exts.length ? exts.join(', ') : '所有文件');
}
}
// 自动保存监听
document.addEventListener('DOMContentLoaded', () => {
document.addEventListener('input', (e) => {
if (e.target.closest('#upForm')) {
saveToLocalStorage();
}
});
document.addEventListener('change', (e) => {
if (e.target.closest('#upForm')) {
saveToLocalStorage();
}
});
});
function showStoppedCollect() {
document.title = '此页面已停止收集信息';
const titleEl = document.getElementById('formTitleDisplay');
if (titleEl) titleEl.textContent = '此页面已停止收集信息';
const subEl = document.getElementById('formSubtitleDisplay');
if (subEl) subEl.textContent = '如有问题请联系管理员';
const container = document.getElementById('formContainer');
if (container) container.style.display = 'none';
const prog = document.getElementById('progressSection');
if (prog) prog.style.display = 'none';
const ann = document.getElementById('announcementSection');
if (ann) ann.style.display = 'none';
}
function formFieldWrapper(field) {
return [...document.querySelectorAll('#upForm .field-wrapper')]
.find(wrapper => wrapper.dataset.fieldName === field.name);
}
function showFormPage(index, scroll = true, animateCount = scroll) {
if (!FORM_PAGES.length) return;
const previousIndex = CURRENT_PAGE_INDEX;
CURRENT_PAGE_INDEX = Math.max(0, Math.min(index, FORM_PAGES.length - 1));
FORM_PAGES.forEach((page, pageIndex) => { page.hidden = pageIndex !== CURRENT_PAGE_INDEX; });
document.getElementById('formTitleDisplay').textContent = FORM_PAGES[CURRENT_PAGE_INDEX].dataset.title || CURRENT_FORM.title;
const multiple = FORM_PAGES.length > 1;
const status = document.getElementById('formPageStatus');
status.hidden = !multiple;
if (multiple) {
animateValueText(document.getElementById('formPageCount'),
`第 ${CURRENT_PAGE_INDEX + 1} / ${FORM_PAGES.length} 页`,
animateCount && previousIndex !== CURRENT_PAGE_INDEX ? 'discrete' : 'none');
const steps = document.getElementById('formPageSteps');
if (steps.querySelectorAll('.form-page-step').length !== FORM_PAGES.length) {
const markers = FORM_PAGES.map(() => {
const marker = document.createElement('span');
marker.className = 'form-page-step';
return marker;
});
const active = document.createElement('span');
active.className = 'form-page-active';
steps.replaceChildren(...markers, active);
}
steps.querySelectorAll('.form-page-step').forEach((marker, pageIndex) => {
marker.classList.toggle('complete', pageIndex < CURRENT_PAGE_INDEX);
});
steps.style.setProperty('--step-offset', `${CURRENT_PAGE_INDEX * 30}px`);
}
const isLastPage = CURRENT_PAGE_INDEX === FORM_PAGES.length - 1;
document.getElementById('pagePrevBtn').hidden = CURRENT_PAGE_INDEX === 0;
document.getElementById('nextPageBtn').hidden = isLastPage;
document.getElementById('submitBtn').hidden = !isLastPage;
if (scroll) {
const card = document.getElementById('formContainer');
const cardTop = card.getBoundingClientRect().top;
const targetY = Math.max(0, Math.min(
window.scrollY + cardTop - 102,
document.documentElement.scrollHeight - window.innerHeight
));
window.scrollTo({
top: targetY,
behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth'
});
}
}
function setPageNavigationBusy(busy) {
['pagePrevBtn', 'nextPageBtn'].forEach(id => {
const button = document.getElementById(id);
if (!button) return;
button.disabled = busy;
button.setAttribute('aria-disabled', String(busy));
});
const nav = document.querySelector('#upForm .form-nav');
if (nav) nav.setAttribute('aria-busy', String(busy));
}
async function navigateFormPage(index) {
if (PAGE_CHANGE_LOCKED || !FORM_PAGES.length) return;
const target = Math.max(0, Math.min(index, FORM_PAGES.length - 1));
if (target === CURRENT_PAGE_INDEX) return;
PAGE_CHANGE_LOCKED = true;
const sequence = ++PAGE_CHANGE_SEQUENCE;
setPageNavigationBusy(true);
const container = document.getElementById('formContainer');
const title = document.getElementById('formTitleDisplay');
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const canAnimate = !reducedMotion && typeof container?.animate === 'function';
try {
PAGE_CHANGE_ANIMATIONS.forEach(animation => animation.cancel());
PAGE_CHANGE_ANIMATIONS = [];
if (!canAnimate) {
showFormPage(target);
// Keep a brief click guard so a double click cannot skip another page.
await new Promise(resolve => setTimeout(resolve, 220));
return;
}
const cardTop = container.getBoundingClientRect().top;
if (Math.abs(cardTop - 102) > 8) {
const targetY = Math.max(0, Math.min(
window.scrollY + cardTop - 102,
document.documentElement.scrollHeight - window.innerHeight
));
window.scrollTo({ top: targetY, behavior: 'smooth' });
await new Promise(resolve => {
const deadline = performance.now() + 1000;
const check = () => {
if (Math.abs(window.scrollY - targetY) < 8 || performance.now() >= deadline) resolve();
else requestAnimationFrame(check);
};
requestAnimationFrame(check);
});
}
if (sequence !== PAGE_CHANGE_SEQUENCE) return;
const direction = target > CURRENT_PAGE_INDEX ? 1 : -1;
const previousPage = FORM_PAGES[CURRENT_PAGE_INDEX];
const currentTitle = title.textContent;
const nextTitle = FORM_PAGES[target].dataset.title || CURRENT_FORM.title;
const animateTitle = nextTitle !== currentTitle;
const oldHeight = container.getBoundingClientRect().height;
const outgoing = [previousPage.animate([
{ opacity: 1, transform: 'translateX(0)' },
{ opacity: 0, transform: `translateX(${-direction * 18}px)` }
], { duration: 180, easing: 'ease-in', fill: 'forwards' })];
if (animateTitle) outgoing.push(title.animate([
{ opacity: 1, transform: 'translateY(0)' },
{ opacity: 0, transform: 'translateY(9px)' }
], { duration: 180, easing: 'ease-in', fill: 'forwards' }));
PAGE_CHANGE_ANIMATIONS = outgoing;
await Promise.allSettled(outgoing.map(animation => animation.finished));
if (sequence !== PAGE_CHANGE_SEQUENCE) return;
showFormPage(target, false, true);
outgoing.forEach(animation => animation.cancel());
const newHeight = container.getBoundingClientRect().height;
const incoming = [
container.animate([
{ height: `${oldHeight}px` }, { height: `${newHeight}px` }
], { duration: 440, easing: 'cubic-bezier(.16, 1, .3, 1)', fill: 'both' }),
FORM_PAGES[target].animate([
{ opacity: 0, transform: `translateX(${direction * 22}px)` },
{ opacity: 1, transform: 'translateX(0)' }
], { duration: 440, easing: 'cubic-bezier(.16, 1, .3, 1)', fill: 'both' })
];
if (animateTitle) incoming.push(title.animate([
{ opacity: 0, transform: 'translateY(-9px)' },
{ opacity: 1, transform: 'translateY(0)' }
], { duration: 420, easing: 'cubic-bezier(.16, 1, .3, 1)', fill: 'both' }));
PAGE_CHANGE_ANIMATIONS = incoming;
await Promise.allSettled(incoming.map(animation => animation.finished));
} catch (error) {
console.error('表单分页切换失败:', error);
if (sequence === PAGE_CHANGE_SEQUENCE) showFormPage(target, false, false);
} finally {
if (sequence === PAGE_CHANGE_SEQUENCE) {
PAGE_CHANGE_ANIMATIONS.forEach(animation => animation.cancel());
PAGE_CHANGE_ANIMATIONS = [];
container?.style.removeProperty('height');
PAGE_CHANGE_LOCKED = false;
setPageNavigationBusy(false);
}
}
}
function pageValidationError(field, message) {
const wrapper = formFieldWrapper(field);
const pageIndex = FORM_PAGES.indexOf(wrapper?.closest('.form-page'));
if (pageIndex >= 0 && pageIndex !== CURRENT_PAGE_INDEX) showFormPage(pageIndex);
PENDING_PAGE_ERROR_FIELD = field;
umShowError(message, document.getElementById(CURRENT_PAGE_INDEX < FORM_PAGES.length - 1 ? 'nextPageBtn' : 'submitBtn'));
return false;
}
function validateFormPage(pageIndex) {
const page = FORM_PAGES[pageIndex];
if (!page) return true;
const fields = inputFields().filter(field => formFieldWrapper(field)?.closest('.form-page') === page);
const tailField = fields.find(field => field.name === 'tail');
if (tailField && !IS_ANON) {
const tail = formFieldWrapper(tailField)?.querySelector('[name="tail"]')?.value.trim() || '';
const digits = CURRENT_FORM.verifyDigits || 2;
if (tail.length !== digits || !STUDENT_MAP[tail]) {
return pageValidationError(tailField, `请输入有效的学号后${digits}位`);
}
}
for (const field of fields) {
const wrapper = formFieldWrapper(field);
if (!wrapper || wrapper.dataset.urlHidden === 'true' || wrapper.classList.contains('conditional-hidden')) continue;
const input = wrapper.querySelector('[name]');
if (field.required) {
if (field.type === 'file') {
const stored = storageManager.files.find(file => file.fieldName === field.name);
if (!input?.files?.length && !stored && !keepFiles[field.name])
return pageValidationError(field, `请上传 ${field.name}`);
} else if (field.type === 'checkbox' || field.type === 'radio') {
if (!wrapper.querySelector('input:checked'))
return pageValidationError(field, `${field.type === 'radio' ? '请选择' : '请至少选择一项'} ${field.name}`);
} else if (field.type === 'rating') {
const value = wrapper.querySelector('.rating-stars')?.dataset.value;
if (!value || value === '0') return pageValidationError(field, `请为 ${field.name} 评分`);
} else if (!input?.value?.trim()) {
return pageValidationError(field, `请填写 ${field.name}`);
}
}
const value = input?.value || '';
const textError = getTextValidationError(field, value);
if (textError) return pageValidationError(field, `${field.name}${textError}`);
if (field.type === 'number' && value !== '' && field.allowDecimal !== true && !Number.isInteger(Number(value)))
return pageValidationError(field, `${field.name}只能输入整数`);
if (field.type === 'file' && input?.files?.[0]) {
const file = input.files[0];
if (file.size > CURRENT_FORM.maxSize)
return pageValidationError(field, `文件大小超过限制 ${formatFileSize(CURRENT_FORM.maxSize)}`);
const ext = file.name.split('.').pop().toLowerCase();
const allowed = field.allowedExts?.length ? field.allowedExts : CURRENT_FORM.allowedExts;
if (allowed?.length && !allowed.includes(ext))
return pageValidationError(field, `不支持的文件格式: .${ext}`);
}
}
return true;
}
function nextFormPage() {
if (PAGE_CHANGE_LOCKED) return;
if (validateFormPage(CURRENT_PAGE_INDEX)) navigateFormPage(CURRENT_PAGE_INDEX + 1);
}
function renderForm() {
// 已停止收集:不渲染填写表单,仅显示停止提示
if (CURRENT_FORM && CURRENT_FORM.collecting === false) {
showStoppedCollect();
return;
}
const form = document.getElementById('upForm');
form.innerHTML = '';
FORM_PAGES = [];
CURRENT_PAGE_INDEX = 0;
URL_PRESET = FormLinkPreset.parse(CURRENT_FORM.fields, window.location.search);
const pageStatus = document.createElement('div');
pageStatus.id = 'formPageStatus';
pageStatus.className = 'form-page-status';
pageStatus.hidden = true;
pageStatus.innerHTML = '<span id="formPageCount" class="numeric-display"></span><span id="formPageSteps" class="form-page-steps" aria-hidden="true"></span>';
form.appendChild(pageStatus);
function appendPage(title = '') {
const page = document.createElement('section');
page.className = 'form-page space-y-10';
page.dataset.title = title || '';
form.appendChild(page);
FORM_PAGES.push(page);
return page;
}
let activePage = appendPage();
let questionIndex = 0;
// 先渲染所有字段
CURRENT_FORM.fields.forEach(field => {
if (field.type === 'page_break') {
activePage = appendPage(field.title);
return;
}
const index = questionIndex++;
const wrapper = document.createElement('div');
wrapper.className = 'stagger-item group space-y-2 field-wrapper';
wrapper.dataset.fieldName = field.name;
// Label
const label = document.createElement('label');
const labelId = `field-label-${index}`;
const controlId = `field-control-${index}`;
label.id = labelId;
label.className = 'block text-[15px] font-semibold tracking-[0.12em] uppercase transition-colors duration-300 mb-2 theme-transition';
label.style.color = 'var(--text-primary)';
const fieldIndex = document.createElement('span');
fieldIndex.className = 'field-index';
fieldIndex.textContent = String(index + 1).padStart(2, '0');
const labelContent = document.createElement('span');
labelContent.className = 'field-label-content';
const fieldName = document.createElement('span');
fieldName.textContent = field.name;
labelContent.appendChild(fieldName);
if (field.required) {
const requiredMark = document.createElement('span');
requiredMark.className = 'field-required-mark';
requiredMark.textContent = '*';
requiredMark.setAttribute('aria-hidden', 'true');
const requiredText = document.createElement('span');
requiredText.className = 'sr-only';
requiredText.textContent = '必填';
labelContent.append(requiredMark, requiredText);
} else {
const optionalMark = document.createElement('span');
optionalMark.className = 'field-optional-mark';
optionalMark.textContent = '(选填)';
labelContent.appendChild(optionalMark);
}
label.append(fieldIndex, labelContent);
const updateLabelColor = (focused) => {
label.style.color = focused ? 'var(--accent-color)' : 'var(--text-primary)';
};
wrapper.appendChild(label);
let input;
switch (field.type) {
case 'select':
const selectWrapper = document.createElement('div');
selectWrapper.className = 'relative';
input = document.createElement('select');
input.className = 'form-entry-box appearance-none cursor-pointer text-sm theme-transition pr-10';
input.style.color = 'var(--text-primary)';
input.style.borderColor = 'var(--border-color)';
input.dataset.fieldType = field.type;
input.onfocus = () => {
input.style.borderColor = 'var(--border-focus)';
updateLabelColor(true);
};
input.onblur = () => {
input.style.borderColor = 'var(--border-color)';
updateLabelColor(false);
};
input.addEventListener('change', () => {
saveToLocalStorage();
// 触发条件显示逻辑
updateConditionalFields();
});
// Add default option
const defaultOption = document.createElement('option');
defaultOption.value = '';
defaultOption.textContent = '请选择...';
input.appendChild(defaultOption);
if (field.options) {
field.options.split(',').forEach(opt => {
const option = document.createElement('option');
option.value = opt.trim();
option.textContent = opt.trim();
option.style.backgroundColor = 'var(--bg-secondary)';
option.style.color = 'var(--text-primary)';
input.appendChild(option);
});
}
const arrow = document.createElement('div');
arrow.innerHTML = '<svg width="10" height="6" viewBox="0 0 10 6" fill="none"><path d="M1 1L5 5L9 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
arrow.className = 'absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none theme-transition';
arrow.style.color = 'var(--text-muted)';
selectWrapper.appendChild(input);
selectWrapper.appendChild(arrow);
wrapper.appendChild(selectWrapper);
break;
case 'textarea':
input = document.createElement('textarea');
input.className = 'w-full border rounded-xl p-4 focus:outline-none focus:ring-4 transition-all duration-300 resize-none min-h-[120px] text-sm leading-relaxed theme-transition';
input.style.backgroundColor = 'var(--input-bg)';
input.style.color = 'var(--text-primary)';
input.style.borderColor = 'var(--border-color)';
input.placeholder = field.placeholder || '请输入...';
input.style.setProperty('--tw-placeholder-color', 'var(--text-muted)');
input.dataset.fieldType = field.type;
input.onfocus = () => {
input.style.borderColor = 'var(--border-focus)';
input.style.setProperty('--tw-ring-color', 'var(--shadow-color)');
updateLabelColor(true);
};
input.onblur = () => {
input.style.borderColor = 'var(--border-color)';
updateLabelColor(false);
};
input.addEventListener('input', () => {
input.setCustomValidity(getTextValidationError(field, input.value));
saveToLocalStorage();
});
wrapper.appendChild(input);
break;
case 'file':
const fileWrapper = document.createElement('div');
fileWrapper.className = 'relative group/file cursor-pointer';
input = document.createElement('input');
input.type = 'file';
input.className = 'absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10';
input.dataset.fieldType = field.type;
const fieldExts = field.allowedExts;
const formExts = CURRENT_FORM.allowedExts;
const allowedExts = fieldExts && fieldExts.length > 0 ? fieldExts : formExts;
if (allowedExts && allowedExts.length > 0) {
input.accept = allowedExts.map(ext => '.' + ext).join(',');
}
const fileDisplay = document.createElement('div');
fileDisplay.className = 'border-2 border-dashed rounded-xl p-6 text-center relative transition-all duration-300 theme-transition';
fileDisplay.style.borderColor = 'var(--border-color)';
fileDisplay.innerHTML = `
<div class="mb-2 theme-transition" 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 tracking-wide theme-transition" style="color: var(--text-secondary);">点击或拖拽上传文件</p>
<p class="text-[10px] mt-1 theme-transition" style="color: var(--text-muted);" id="fileName_${field.name}">支持格式: ${allowedExts ? allowedExts.join(', ') : '所有文件'}</p>
`;
// 删除按钮 — 独立创建,避免 field.name 含特殊字符导致选择器失败
const deleteBtn = document.createElement('button');
deleteBtn.type = 'button';
deleteBtn.className = 'absolute -top-2.5 -right-2.5 w-6 h-6 rounded-full flex items-center justify-center z-20 transition-all duration-200 hover:scale-110 active:scale-95';
deleteBtn.style.cssText = 'display:none; background:rgba(220,38,38,0.9); color:white; box-shadow:0 2px 8px rgba(220,38,38,0.3);';
deleteBtn.title = '删除文件';
deleteBtn.innerHTML = `<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.5" stroke-linecap="round">
<path d="M18 6L6 18M6 6l12 12"/>
</svg>`;
fileDisplay.appendChild(deleteBtn);
fileWrapper.onmouseenter = () => {
fileDisplay.style.borderColor = 'var(--text-muted)';
fileDisplay.style.backgroundColor = 'var(--bg-primary)';
};
fileWrapper.onmouseleave = () => {
fileDisplay.style.borderColor = 'var(--border-color)';
fileDisplay.style.backgroundColor = 'transparent';
};
// 删除按钮逻辑
deleteBtn.addEventListener('click', async (e) => {
e.stopPropagation();
// "沿用上次"状态:点击 × 仅取消沿用标记,恢复待上传样式
if (input.dataset.keepFileId) {
clearKeptFile(field.name);
return;
}
const savedId = input.dataset.savedFileId;
if (savedId) {
try {
await storageManager.deleteFile(Number(savedId));
console.log(`[FileDelete] Deleted file ID ${savedId} for field: ${field.name}`);
updateStorageUI();
showToast('文件已删除', 'success');
} catch (e) {
console.error('[FileDelete] Failed:', e);
}
}
// 重置 input
input.value = '';
input.files = new DataTransfer().files;
delete input.dataset.savedFileId;
input.classList.remove('has-file');
input.removeAttribute('data-has-file');
// 重置显示
fileDisplay.style.borderColor = 'var(--border-color)';
fileDisplay.style.backgroundColor = 'transparent';
fileDisplay.style.boxShadow = 'none';
fileDisplay.style.transform = 'translateY(0)';
fileDisplay.style.animation = '';
document.getElementById(`fileName_${field.name}`).textContent =
'支持格式: ' + (allowedExts ? allowedExts.join(', ') : '所有文件');
// 恢复上传图标
const iconDiv = fileDisplay.querySelector('div:first-child');
if (iconDiv) {
iconDiv.innerHTML = `<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>`;
}
// 隐藏删除按钮
deleteBtn.style.display = 'none';
});
input.addEventListener('change', async function () {
const fileName = this.files[0] ? this.files[0].name : '支持格式: ' + (allowedExts ? allowedExts.join(', ') : '所有文件');
document.getElementById(`fileName_${field.name}`).textContent = fileName;
// 重置所有状态
this.classList.remove('has-file');
this.removeAttribute('data-has-file');
fileDisplay.style.borderColor = 'var(--border-color)';
fileDisplay.style.backgroundColor = 'transparent';
fileDisplay.style.boxShadow = 'none';
fileDisplay.style.transform = 'translateY(0)';
if (this.files[0]) {
// 文件已选定 - 应用明显的视觉状态
this.classList.add('has-file');
this.setAttribute('data-has-file', 'true');
// 添加入场动画
fileDisplay.style.animation = 'none';
fileDisplay.offsetHeight; // 触发重排
fileDisplay.style.animation = 'fileSelected 0.5s cubic-bezier(0.4, 0, 0.2, 1)';
// 显示成功图标
const iconDiv = fileDisplay.querySelector('div:first-child');
if (iconDiv) {
iconDiv.innerHTML = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M5 13l4 4L19 7"/>
</svg>`;
}
// 立即显示删除按钮(不用等 IndexedDB 保存完)
deleteBtn.style.display = 'flex';
// 保存到 IndexedDB
try {
const formId = window.location.pathname.slice(1) || 'default';
console.log(`[FileSave] Saving file to IndexedDB: ${this.files[0].name} for field: ${field.name}`);
const result = await storageManager.saveFile(this.files[0], field.name, formId);
console.log(`[FileSave] File saved successfully with ID: ${result.id}`);
this.dataset.savedFileId = result.id;
updateStorageUI();
} catch (e) {
console.error('保存文件到 IndexedDB 失败:', e);
}
} else {
// 恢复默认图标
const iconDiv = fileDisplay.querySelector('div:first-child');
if (iconDiv) {
iconDiv.innerHTML = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M12 16V4M12 4L8 8M12 4L16 8M4 17V18C4 19.1046 4.89543 20 6 20H18C19.1046 20 20 19.1046 20 18V17"/>
</svg>`;
}
// 隐藏删除按钮
deleteBtn.style.display = 'none';
delete input.dataset.savedFileId;
}
});
// 拖拽上传支持 + GSAP 动画(主动迎合交互)
let dragCounter = 0;
let breathTween = null;
let iconReachTween = null;
fileWrapper.addEventListener('dragenter', (e) => {
e.preventDefault();
e.stopPropagation();
dragCounter++;
if (dragCounter === 1) {
// 消除可能的旧动画
if (breathTween) breathTween.kill();
if (iconReachTween) iconReachTween.kill();
// 拖入时轻微抬起,并突出边界
gsap.to(fileDisplay, {
scale: 1.025,
borderColor: 'var(--accent-bg)',
boxShadow: '0 12px 32px var(--studio-glow)',
backgroundColor: 'var(--studio-glow)',
duration: 0.28,
ease: 'power3.out',
overwrite: 'auto',
onComplete: () => {
// 停在轻微抬起的位置,等待释放
breathTween = gsap.to(fileDisplay, {
y: -2,
duration: 0.25,
ease: 'power2.out'
});
}
});
// 图标短暂上移,提示可以放下文件
const icon = fileDisplay.querySelector('div:first-child svg');
if (icon) {
iconReachTween = gsap.to(icon, {
scaleX: 1,
scaleY: 1,
y: -4,
duration: 0.28,
ease: 'power3.out',
overwrite: 'auto',
onComplete: () => {
// 图标回落到拖入状态
iconReachTween = gsap.to(icon, {
y: -3,
scaleY: 1,
scaleX: 1,
duration: 0.25,
ease: 'power2.out'
});
}
});
}
}
});
fileWrapper.addEventListener('dragover', (e) => {
e.preventDefault();
e.stopPropagation();
});
fileWrapper.addEventListener('dragleave', (e) => {
e.preventDefault();
e.stopPropagation();
dragCounter--;
if (dragCounter === 0) {
if (breathTween) breathTween.kill();
if (iconReachTween) iconReachTween.kill();
gsap.killTweensOf(fileDisplay);
gsap.to(fileDisplay, {
scale: 1,
y: 0,
borderColor: 'var(--border-color)',
boxShadow: 'none',
backgroundColor: 'transparent',
duration: 0.25,
ease: 'power3.out',
overwrite: 'auto'
});
const icon = fileDisplay.querySelector('div:first-child svg');
if (icon) {
gsap.killTweensOf(icon);
gsap.to(icon, {
scaleX: 1,
scaleY: 1,
y: 0,
duration: 0.25,
ease: 'power3.out',
overwrite: 'auto'
});
}
}
});
fileWrapper.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
dragCounter = 0;
if (breathTween) breathTween.kill();
if (iconReachTween) iconReachTween.kill();
const files = e.dataTransfer.files;
if (files.length > 0) {
// 「接住!」— 快速收缩再弹性弹回
gsap.to(fileDisplay, {
scale: 0.95,
duration: 0.1,
ease: 'power2.in',
overwrite: 'auto',
onComplete: () => {
gsap.to(fileDisplay, {
scale: 1,
y: 0,
borderColor: 'var(--border-color)',
boxShadow: 'none',
backgroundColor: 'transparent',
duration: 0.3,
ease: 'power3.out'
});
}
});
const icon = fileDisplay.querySelector('div:first-child svg');
if (icon) {
gsap.killTweensOf(icon);
gsap.set(icon, { scaleX: 1, scaleY: 1, y: 0 });
}
// 将拖拽的文件注入到 file input 并触发上传
const dt = new DataTransfer();
dt.items.add(files[0]);
input.files = dt.files;
input.dispatchEvent(new Event('change'));
} else {
gsap.killTweensOf(fileDisplay);
gsap.to(fileDisplay, {
scale: 1,
y: 0,
borderColor: 'var(--border-color)',
boxShadow: 'none',
backgroundColor: 'transparent',
duration: 0.3,
ease: 'power2.out',
overwrite: 'auto'
});
}
});
fileWrapper.appendChild(input);
fileWrapper.appendChild(fileDisplay);
wrapper.appendChild(fileWrapper);
break;
case 'radio':
case 'checkbox':
const optionsGrid = document.createElement('div');
optionsGrid.className = field.optionLayout === 'column'
? 'flex flex-col items-start gap-3 mt-3'
: 'flex flex-wrap gap-3 mt-3';
optionsGrid.setAttribute('role', 'group');
optionsGrid.setAttribute('aria-labelledby', labelId);
if (field.options) {
field.options.split(',').forEach(opt => {
const optionValue = opt.trim();
const optionId = field.name + '_' + optionValue.replace(/\s+/g, '_');
const label = document.createElement('label');
label.className = 'inline-flex items-center cursor-pointer group/check';
label.style.position = 'relative';
label.style.padding = '8px';
label.style.margin = '-8px';
label.style.borderRadius = '8px';
label.setAttribute('for', optionId);
const checkbox = document.createElement('input');
checkbox.type = field.type;
checkbox.name = field.name;
checkbox.value = optionValue;
checkbox.id = optionId;
checkbox.className = 'peer sr-only';
checkbox.dataset.fieldType = field.type;
checkbox.style.position = 'absolute';
checkbox.style.width = '1px';
checkbox.style.height = '1px';
checkbox.style.opacity = '0';
checkbox.style.pointerEvents = 'none';
checkbox.addEventListener('change', () => {
saveToLocalStorage();
updateCheckboxVisual(checkbox, customCheck, field.type);
// 触发条件显示逻辑
updateConditionalFields();
});
const customCheck = document.createElement('div');
customCheck.className = 'custom-check-box';
customCheck.style.width = '22px';
customCheck.style.height = '22px';
customCheck.style.border = '2px solid var(--border-color)';
customCheck.style.display = 'flex';
customCheck.style.alignItems = 'center';
customCheck.style.justifyContent = 'center';
customCheck.style.transition = 'all 0.2s';
customCheck.style.flexShrink = '0';
if (field.type === 'checkbox') {
customCheck.style.borderRadius = '6px';
const checkIcon = document.createElement('div');
checkIcon.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>';
checkIcon.style.opacity = '0';
checkIcon.style.transform = 'scale(0)';
checkIcon.style.transition = 'all 0.2s';
customCheck.appendChild(checkIcon);
} else {
customCheck.classList.add('radio-check');
customCheck.style.borderRadius = '50%';
const innerDot = document.createElement('div');
innerDot.className = 'radio-check-dot';
innerDot.style.width = '12px';
innerDot.style.height = '12px';
innerDot.style.borderRadius = '50%';
innerDot.style.backgroundColor = '#3b82f6';
innerDot.style.opacity = '0';
innerDot.style.transform = 'scale(0)';
innerDot.style.transition = 'all 0.2s';
customCheck.appendChild(innerDot);
}
const span = document.createElement('span');
span.className = 'ml-2.5 text-sm select-none theme-transition';
span.style.color = 'var(--text-secondary)';
span.textContent = optionValue;
label.appendChild(checkbox);
label.appendChild(customCheck);
label.appendChild(span);
optionsGrid.appendChild(label);
function updateCheckboxVisual(input, visualBox, type) {
const isDark = document.documentElement.classList.contains('dark');
if (type === 'checkbox') {
const icon = visualBox.querySelector('div');
if (input.checked) {
visualBox.style.backgroundColor = 'var(--accent-bg)';
visualBox.style.borderColor = 'var(--accent-bg)';
visualBox.classList.add('checked');
icon.style.opacity = '1';
icon.style.transform = 'scale(1)';
const svg = icon.querySelector('svg');
if (svg) {
svg.querySelector('polyline').setAttribute('stroke', isDark ? '#171717' : '#ffffff');
}
} else {
visualBox.style.backgroundColor = 'transparent';
visualBox.style.borderColor = isDark ? '#404040' : '#d4d4d4';
visualBox.classList.remove('checked');
icon.style.opacity = '0';
icon.style.transform = 'scale(0)';
}
} else {
// 按整组真实 checked 状态同步,未选项的初始化/主题回调不能清掉已选项。
const sameName = optionsGrid.querySelectorAll('input[type="radio"]');
sameName.forEach(r => {
const rLabel = r.closest('label');
if (rLabel) {
const rBox = rLabel.querySelector('.custom-check-box');
if (rBox) {
rBox.style.backgroundColor = 'transparent';
rBox.style.borderColor = r.checked ? 'var(--accent-bg)' : (isDark ? '#404040' : '#d4d4d4');
rBox.classList.toggle('checked', r.checked);
const rDot = rBox.querySelector('div');
if (rDot) {
rDot.style.opacity = r.checked ? '1' : '0';
rDot.style.transform = r.checked ? 'scale(1)' : 'scale(0)';
rDot.style.backgroundColor = 'var(--accent-bg)';
}
}
}
});
}
}
setTimeout(() => {
updateCheckboxVisual(checkbox, customCheck, field.type);
const observer = new MutationObserver(() => {
updateCheckboxVisual(checkbox, customCheck, field.type);
});
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
}, 0);
});
}
wrapper.appendChild(optionsGrid);
break;
case 'rating':
const ratingWrapper = document.createElement('div');
ratingWrapper.className = 'flex items-center gap-4 flex-wrap';
const ratingContainer = document.createElement('div');
ratingContainer.className = 'rating-stars';
const maxStars = 5;
const maxScore = Number(field.ratingMax) === 10 ? 10 : 5;
ratingContainer.dataset.maxScore = maxScore;
ratingContainer.dataset.value = '';
ratingContainer.setAttribute('role', 'slider');
ratingContainer.setAttribute('tabindex', '0');
ratingContainer.setAttribute('aria-labelledby', labelId);
ratingContainer.setAttribute('aria-valuemin', '0');
ratingContainer.setAttribute('aria-valuemax', String(maxScore));
ratingContainer.setAttribute('aria-valuenow', '0');
ratingContainer.setAttribute('aria-valuetext', '未评分');
for (let i = 1; i <= maxStars; i++) {
const star = document.createElement('div');
star.className = 'rating-star-item';
star.dataset.starIndex = i;
star.dataset.value = 'empty';
star.setAttribute('aria-hidden', 'true');
const clipId = `rating-clip-${index}-${i}`;
star.innerHTML = `
<svg class="star-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<defs><clipPath id="${clipId}" clipPathUnits="userSpaceOnUse"><rect class="star-fill-clip" x="0" y="0" width="0" height="24"/></clipPath></defs>
<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="#fbbf24" clip-path="url(#${clipId})"/>
<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" stroke-linejoin="round"/>
</svg>
`;
const pointerScore = (event) => {
if (maxScore === 5) return i;
const bounds = star.getBoundingClientRect();
return i * 2 - (event.clientX < bounds.left + bounds.width / 2 ? 1 : 0);
};
star.addEventListener('click', (event) => {
event.preventDefault();
if (ratingContainer.getAttribute('aria-disabled') === 'true') return;
const score = pointerScore(event);
const currentValue = Number(ratingContainer.dataset.value) || 0;
renderRatingValue(ratingContainer, currentValue === score ? 0 : score, true, true);
ratingContainer.focus({ preventScroll: true });
saveToLocalStorage();
});
star.addEventListener('mousemove', (event) => {
if (ratingContainer.getAttribute('aria-disabled') !== 'true') renderRatingValue(ratingContainer, pointerScore(event));
});
star.addEventListener('mouseleave', () => renderRatingValue(ratingContainer, ratingContainer.dataset.value));
ratingContainer.appendChild(star);
}
ratingContainer.addEventListener('keydown', (event) => {
if (ratingContainer.getAttribute('aria-disabled') === 'true') return;
const current = Number(ratingContainer.dataset.value) || 0;
let next;
if (event.key === 'ArrowRight' || event.key === 'ArrowUp') next = current + 1;
else if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') next = current - 1;
else if (event.key === 'Home') next = 0;
else if (event.key === 'End') next = maxScore;
else return;
event.preventDefault();
renderRatingValue(ratingContainer, next, true, true);
saveToLocalStorage();
});
const ratingValueDisplay = document.createElement('span');
ratingValueDisplay.className = 'rating-value-display numeric-display';
ratingValueDisplay.style.fontSize = '16px';
ratingValueDisplay.style.fontWeight = '700';
ratingValueDisplay.style.minWidth = '60px';
ratingValueDisplay.style.transition = 'color 0.2s';
ratingValueDisplay.textContent = '未评分';
ratingValueDisplay.dataset.rated = 'false';
const ratingInput = document.createElement('input');
ratingInput.type = 'hidden';
ratingInput.name = field.name;
ratingInput.dataset.fieldType = 'rating';
ratingWrapper.appendChild(ratingContainer);
ratingWrapper.appendChild(ratingValueDisplay);
ratingWrapper.appendChild(ratingInput);
wrapper.appendChild(ratingWrapper);
renderRatingValue(ratingContainer, 0, true);
break;
case 'slider':
const sliderContainer = document.createElement('div');
sliderContainer.className = 'slider-control flex items-center gap-4';
const sliderShell = document.createElement('div');
sliderShell.className = 'slider-shell';
const sliderRail = document.createElement('div');
sliderRail.className = 'slider-rail';
const sliderFill = document.createElement('span');
sliderFill.className = 'slider-rail-fill';
const sliderThumb = document.createElement('span');
sliderThumb.className = 'slider-thumb';
sliderRail.append(sliderFill, sliderThumb);
const slider = document.createElement('input');
slider.type = 'range';
slider.id = controlId;
label.htmlFor = controlId;
slider.name = field.name;
slider.min = field.sliderMin || '0';
slider.max = field.sliderMax || '100';
slider.step = field.sliderStep || '1';
slider.value = slider.min;
slider.className = 'slider-native';
slider.dataset.fieldType = field.type;
const sliderValue = document.createElement('span');
sliderValue.className = 'slider-value numeric-display';
sliderValue.textContent = slider.value;
slider.addEventListener('input', (event) => {
syncSliderVisual(slider, event.isTrusted);
saveToLocalStorage();
});
let pointerDown = false;
slider.addEventListener('pointerdown', () => { pointerDown = true; });
slider.addEventListener('pointermove', () => {
if (pointerDown) sliderShell.classList.add('is-dragging');
});
for (const eventName of ['pointerup', 'pointercancel', 'blur']) {
slider.addEventListener(eventName, () => {
pointerDown = false;
sliderShell.classList.remove('is-dragging');
});
}
sliderShell.append(sliderRail, slider);
sliderContainer.appendChild(sliderShell);
sliderContainer.appendChild(sliderValue);
wrapper.appendChild(sliderContainer);
syncSliderVisual(slider, false);
break;
case 'date':
input = document.createElement('input');
input.type = 'date';
input.className = 'form-entry-box text-sm theme-transition';
input.style.color = 'var(--text-primary)';
input.style.borderColor = 'var(--border-color)';
input.dataset.fieldType = field.type;
input.onfocus = () => {
input.style.borderColor = 'var(--border-focus)';
updateLabelColor(true);
};
input.onblur = () => {
input.style.borderColor = 'var(--border-color)';
updateLabelColor(false);
};
input.addEventListener('change', () => saveToLocalStorage());
wrapper.appendChild(input);
break;
case 'time':
input = document.createElement('input');
input.type = 'time';
input.className = 'form-entry-box text-sm theme-transition';
input.style.color = 'var(--text-primary)';
input.style.borderColor = 'var(--border-color)';
input.dataset.fieldType = field.type;
input.onfocus = () => {
input.style.borderColor = 'var(--border-focus)';
updateLabelColor(true);
};
input.onblur = () => {
input.style.borderColor = 'var(--border-color)';
updateLabelColor(false);
};
input.addEventListener('change', () => saveToLocalStorage());
wrapper.appendChild(input);
break;
default:
input = document.createElement('input');
input.type = field.type;
if (field.type === 'number') {
input.step = field.allowDecimal ? 'any' : '1';
input.inputMode = field.allowDecimal ? 'decimal' : 'numeric';
}
input.className = 'form-entry-box text-sm theme-transition';
input.style.color = 'var(--text-primary)';
input.style.borderColor = 'var(--border-color)';
input.placeholder = field.placeholder || '';
input.style.setProperty('--tw-placeholder-color', 'var(--text-muted)');
input.dataset.fieldType = field.type;
input.onfocus = () => {
input.style.borderColor = 'var(--border-focus)';
updateLabelColor(true);
};
input.onblur = () => {
input.style.borderColor = 'var(--border-color)';
updateLabelColor(false);
};
input.addEventListener('input', () => {
input.setCustomValidity(getTextValidationError(field, input.value));
saveToLocalStorage();
});
wrapper.appendChild(input);
}
if (input && !['radio', 'checkbox', 'rating', 'slider'].includes(field.type)) {
input.id = controlId;
label.htmlFor = controlId;
}
if (input && field.type !== 'radio' && field.type !== 'checkbox' && field.type !== 'file' && field.type !== 'rating' && field.type !== 'slider') {
input.name = field.name;
// 如果字段有条件显示配置,不在 HTML 元素上设置 required,提交时手动验证
input.required = Boolean(field.required && !field.showWhen);
} else if (field.type === 'file') {
input.name = field.name;
// 文件字段不能用原生 required:"沿用上次/恢复"时 input 无真实 File,
// 浏览器气泡会在 JS 校验之前拦截提交;必填校验由 handleSubmit 统一处理
input.required = false;
}
// Special tail number handling(匿名模式无名单联动,name/tail 为普通自定义字段)
if (field.name === 'name' && !IS_ANON) {
input.disabled = true;
input.style.opacity = '0.7';
input.style.cursor = 'not-allowed';
input.placeholder = '请输入学号自动获取姓名';
}
if (field.name === 'tail' && field.type === 'number') {
input.inputMode = 'numeric';
input.pattern = '\d*';
input.addEventListener('input', (e) => {
let displayValue = e.target.value.trim();
const verifyDigits = CURRENT_FORM.verifyDigits || 2;
let tail = displayValue;
let info = STUDENT_MAP[tail];
if (!info && tail.length > 0 && tail.length < verifyDigits) {
const paddedTail = tail.padStart(verifyDigits, '0');
info = STUDENT_MAP[paddedTail];
if (info) tail = paddedTail;
}
if (!info && tail.length > verifyDigits) {
const trimmedTail = tail.slice(-verifyDigits);
info = STUDENT_MAP[trimmedTail];
if (info) tail = trimmedTail;
}
const nameField = CURRENT_FORM.fields.find(f => f.name === 'name');
if (nameField) {
const nameInput = document.querySelector('input[name="name"]');
if (nameInput) {
if (info) {
nameInput.value = info.name;
gsap.fromTo(nameInput,
{ backgroundColor: "rgba(128, 128, 128, 0.1)" },
{ backgroundColor: "transparent", duration: 0.5 }
);
} else {
nameInput.value = '';
}
nameInput.disabled = true;
nameInput.style.opacity = '0.7';
nameInput.style.cursor = 'not-allowed';
}
}
if (info) checkSubmissionStatus(tail);
});
input.addEventListener('blur', (e) => {
let value = e.target.value.trim();
const verifyDigits = CURRENT_FORM.verifyDigits || 2;
if (value.length > 0 && value.length < verifyDigits) {
e.target.value = value.padStart(verifyDigits, '0');
e.target.dispatchEvent(new Event('input'));
}
});
}
activePage.appendChild(wrapper);
});
applyUrlPreset();
if (URL_PRESET.invalid.size) showToast('链接中部分预填内容无效,请检查并手动填写', 'info');
FORM_PAGES = FORM_PAGES.filter(page => {
const wrappers = [...page.querySelectorAll('.field-wrapper')];
if (wrappers.length) {
if (wrappers.some(wrapper => wrapper.dataset.urlHidden !== 'true')) return true;
// 保留隐藏题目的 DOM 供提交,只从分页导航移除整页隐藏的页面。
page.hidden = true;
return false;
}
page.remove();
return false;
});
if (!FORM_PAGES.length) appendPage();
// Submit button
const submitWrapper = document.createElement('div');
submitWrapper.className = 'stagger-item pt-6';
const submitBtn = document.createElement('button');
submitBtn.type = 'submit';
submitBtn.id = 'submitBtn';
submitBtn.className = 'w-full py-4 px-8 rounded-full font-medium tracking-wide text-sm transform hover:scale-[1.02] active:scale-[0.98] transition-all duration-300 btn-slide relative overflow-hidden theme-transition';
submitBtn.style.backgroundColor = 'var(--accent-bg)';
submitBtn.style.color = 'var(--accent-text)';
submitBtn.style.boxShadow = '0 4px 20px var(--shadow-color)';
submitBtn.innerHTML = '<span class="relative z-10 flex items-center justify-center gap-2">提交表单 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="opacity-70"><path d="M5 12h14M12 5l7 7-7 7"/></svg></span>';
const nextBtn = submitBtn.cloneNode(true);
nextBtn.type = 'button';
nextBtn.id = 'nextPageBtn';
nextBtn.innerHTML = '<span class="relative z-10 flex items-center justify-center gap-2">下一页 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="M5 12h14M12 5l7 7-7 7"/></svg></span>';
nextBtn.addEventListener('click', nextFormPage);
const nav = document.createElement('div');
nav.className = 'form-nav';
const prevBtn = document.createElement('button');
prevBtn.type = 'button';
prevBtn.id = 'pagePrevBtn';
prevBtn.className = 'px-5 py-4 text-sm';
prevBtn.textContent = '上一页';
prevBtn.hidden = true;
prevBtn.addEventListener('click', () => navigateFormPage(CURRENT_PAGE_INDEX - 1));
nav.append(prevBtn, nextBtn, submitBtn);
// 禁止重复提交:按钮上方常驻提示
if (POLICY_ONCE) {
const onceHint = document.createElement('p');
onceHint.className = 'text-xs text-center mb-3 theme-transition';
onceHint.style.color = 'var(--warning-text, #b45309)';
onceHint.textContent = '⚠ 此表单仅允许提交一次,提交后不能再修改,请确认填写无误后再提交。';
submitWrapper.appendChild(onceHint);
}
submitWrapper.appendChild(nav);
form.appendChild(submitWrapper);
form.removeEventListener('submit', handleSubmit);
form.addEventListener('submit', handleSubmit);
showFormPage(0, false);
gsap.fromTo(".stagger-item", { opacity: 0, y: 12 }, {
opacity: 1,
y: 0,
duration: 0.58,
stagger: 0.07,
ease: "power3.out",
delay: 0.2
});
// 初始化条件显示
setTimeout(() => {
updateConditionalFields();
}, 100);
// 恢复草稿数据
setTimeout(() => {
const restored = loadFromLocalStorage();
if (restored) {
showToast('已自动恢复上次未提交的草稿', 'info');
}
}, 500);
}
async function checkSubmissionStatus(tail = null) {
if (IS_ANON) return; // 匿名模式无名单,状态由设备令牌检查驱动
if (!tail) {
const tailInput = document.querySelector('input[name="tail"]');
if (!tailInput) return;
tail = tailInput.value.trim();
}
const verifyDigits = CURRENT_FORM.verifyDigits || 2;
if (tail.length === 1 && tail >= '1' && tail <= '9' && verifyDigits === 2) {
tail = '0' + tail;
}
if (!tail || !STUDENT_MAP[tail]) return;
try {
const res = await fetch(`/check_submission?studentId=${tail}&formId=${window.location.pathname.slice(1) || 'default'}`);
const data = await res.json();
const submitBtn = document.getElementById('submitBtn');
if (data.exists) {
if (POLICY_ONCE) { lockSubmitButton(); return; } // 禁止重复:该学号已提交过
const needVerify = (CURRENT_FORM.overwriteVerify && CURRENT_FORM.overwriteVerify.enabled) || CURRENT_FORM.requireIdCard;
const verifyLabel = CURRENT_FORM.overwriteVerify && CURRENT_FORM.overwriteVerify.label ? CURRENT_FORM.overwriteVerify.label : '身份证';
if (needVerify) {
submitBtn.innerHTML = '<span class="relative z-10 flex items-center justify-center gap-2">更新已有记录(需' + verifyLabel + '验证) <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg></span>';
} else {
submitBtn.innerHTML = '<span class="relative z-10 flex items-center justify-center gap-2">更新已有记录 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg></span>';
}
submitBtn.classList.add('ring-2', 'ring-offset-2');
submitBtn.style.setProperty('--tw-ring-color', 'var(--text-muted)');
IS_OVERWRITE = true;
} else {
unlockSubmitButton();
submitBtn.innerHTML = '<span class="relative z-10 flex items-center justify-center gap-2">提交表单 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="opacity-70"><path d="M5 12h14M12 5l7 7-7 7"/></svg></span>';
submitBtn.classList.remove('ring-2', 'ring-offset-2');
IS_OVERWRITE = false;
}
} catch (e) {
console.error('Status check error:', e);
}
}
function openIdCardModal() {
const modal = document.getElementById('idCardModal');
const backdrop = document.getElementById('modalBackdrop');
const content = document.getElementById('modalContent');
const input = document.getElementById('idCardInput');
const error = document.getElementById('idCardError');
const desc = document.getElementById('verifyModalDesc');
const verifyConfig = CURRENT_FORM && CURRENT_FORM.overwriteVerify;
const verifyLabel = verifyConfig && verifyConfig.label ? verifyConfig.label : '验证信息';
const verifyDigits = verifyConfig && verifyConfig.digits ? verifyConfig.digits : 4;
desc.textContent = `检测到已有提交记录。请输入该学生${verifyLabel}后${verifyDigits}位以验证身份并更新数据。`;
input.setAttribute('maxlength', verifyDigits);
input.placeholder = '•'.repeat(verifyDigits);
modal.style.display = 'flex';
requestAnimationFrame(() => {
backdrop.classList.remove('opacity-0');
content.classList.remove('opacity-0', 'scale-95');
content.classList.add('scale-100');
});
input.value = '';
input.style.borderColor = 'var(--border-color)';
error.classList.remove('opacity-100', 'translate-y-0');
error.classList.add('opacity-0', '-translate-y-2');
input.oninput = function () {
this.value = this.value.toUpperCase().replace(/[^0-9X]/g, '');
};
input.focus();
return new Promise((resolve, reject) => {
const confirmHandler = async () => {
const tail = document.querySelector('input[name="tail"]').value.trim();
const userInput = input.value.trim();
if (!userInput || userInput.length !== verifyDigits) {
input.style.borderColor = 'var(--error-text)';
error.classList.remove('opacity-0', '-translate-y-2');
error.classList.add('opacity-100', 'translate-y-0');
return;
}
try {
const formId = window.location.pathname.slice(1) || 'default';
const resp = await fetch('/get_verify_value', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ studentId: tail, formId, value: userInput })
});
const data = await resp.json();
if (data.success) {
closeIdCardModal();
resolve(userInput);
} else {
input.style.borderColor = 'var(--error-text)';
error.classList.remove('opacity-0', '-translate-y-2');
error.classList.add('opacity-100', 'translate-y-0');
input.select();
gsap.to(content, {
x: [-5, 5, -5, 5, 0],
duration: 0.4,
ease: "power2.inOut"
});
}
} catch (e) {
closeIdCardModal();
reject(e);
}
};
const cancelHandler = () => {
closeIdCardModal();
reject(new Error('User cancelled'));
};
document.getElementById('confirmIdCardBtn').onclick = confirmHandler;
document.querySelector('#idCardModal button[onclick="closeIdCardModal()"]').onclick = cancelHandler;
input.onkeydown = (e) => {
if (e.key === 'Enter') confirmHandler();
};
});
}
function closeIdCardModal() {
const modal = document.getElementById('idCardModal');
const backdrop = document.getElementById('modalBackdrop');
const content = document.getElementById('modalContent');
backdrop.classList.add('opacity-0');
content.classList.remove('scale-100');
content.classList.add('opacity-0', 'scale-95');
setTimeout(() => {
modal.style.display = 'none';
}, 300);
}
/* ===== 提交反馈形变卡片:公共库封装(static/js/morph-card.js) ===== */
/* 恢复提交按钮默认文案(防止形变收回时按钮残留上传进度内容) */
function umResetSubmitLabel(btn) {
if (!btn) return;
if (SUBMIT_LOCKED) { renderLockedSubmitLabel(btn); return; }
if (IS_OVERWRITE) {
btn.innerHTML = '<span class="relative z-10 flex items-center justify-center gap-2">更新已有记录 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg></span>';
btn.classList.add('ring-2', 'ring-offset-2');
} else {
btn.innerHTML = '<span class="relative z-10 flex items-center justify-center gap-2">提交表单 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="opacity-70"><path d="M5 12h14M12 5l7 7-7 7"/></svg></span>';
btn.classList.remove('ring-2', 'ring-offset-2');
}
}
const UMC = MorphCard.init({
successDesc: '您填写的数据已保存,<br>可以继续修改或关闭页面。',
onExpand: (el) => { if (el && el.id === 'submitBtn') umResetSubmitLabel(el); },
onCollapse: (el) => {
if (el && el.id === 'submitBtn') umResetSubmitLabel(el);
if (PENDING_PAGE_ERROR_FIELD) {
formFieldWrapper(PENDING_PAGE_ERROR_FIELD)?.querySelector('input:not([type="hidden"]), select, textarea')?.focus();
PENDING_PAGE_ERROR_FIELD = null;
}
}
});
function openVerifyCard(opts) { return UMC.verify(opts); }
function umOpenProgress() { UMC.openProgress(document.getElementById('submitBtn')); }
function umUpdateProgress(p) { UMC.progress(p); }
function umShowSuccess() { UMC.success(); }
function umShowError(msg, sourceEl = document.getElementById('submitBtn')) { UMC.error(msg, sourceEl); }
function closeUploadModal() { UMC.close(); }
/* ===== 大文件分片上传(弱网断点续传) =====
小文件(<=4MB)仍走原来的单包 multipart,行为不变;
大文件切成 8MB 分片,每片失败自动退避重试,最后把 upload_id 挂到提交里。 */
const CHUNK_THRESHOLD = 4 * 1024 * 1024;
const CHUNK_SIZE = 8 * 1024 * 1024;
const CHUNK_RETRIES = 5;
function postJSON(url, body) {
return fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
}).then(async (r) => ({ status: r.status, data: await r.json().catch(() => ({})) }));
}
function putChunk(uploadId, index, blob, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', `/api/upload/chunk?upload_id=${encodeURIComponent(uploadId)}&index=${index}`);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.upload.onprogress = (e) => { if (e.lengthComputable && onProgress) onProgress(e.loaded); };
xhr.onload = () => {
if (xhr.status === 200) {
try { resolve(JSON.parse(xhr.responseText || '{}')); } catch (e) { resolve({}); }
} else {
reject(new Error(`分片 ${index + 1} 上传失败(HTTP ${xhr.status})`));
}
};
xhr.onerror = () => reject(new Error(`分片 ${index + 1} 网络错误`));
xhr.ontimeout = () => reject(new Error(`分片 ${index + 1} 超时`));
xhr.send(blob);
});
}
async function uploadFileChunked(file, formId, fieldName, onProgress) {
const init = await postJSON('/api/upload/init', {
formId, field: fieldName, filename: file.name, size: file.size, chunkSize: CHUNK_SIZE
});
if (!init.data || !init.data.ok) throw new Error((init.data && init.data.message) || '上传初始化失败');
const uploadId = init.data.upload_id;
const chunkSize = init.data.chunk_size || CHUNK_SIZE;
const total = init.data.total_chunks || Math.ceil(file.size / chunkSize);
let done = 0;
for (let i = 0; i < total; i++) {
const blob = file.slice(i * chunkSize, Math.min((i + 1) * chunkSize, file.size));
let attempt = 0;
for (;;) {
try {
await putChunk(uploadId, i, blob, (loaded) => {
if (onProgress) onProgress(done + Math.min(loaded, blob.size));
});
break;
} catch (err) {
attempt += 1;
if (attempt > CHUNK_RETRIES) {
throw new Error(`${file.name} 第 ${i + 1}/${total} 片重试 ${CHUNK_RETRIES} 次仍失败,请检查网络后重试`);
}
await new Promise((r) => setTimeout(r, Math.min(1000 * attempt, 8000)));
}
}
done += blob.size;
if (onProgress) onProgress(done);
}
const comp = await postJSON('/api/upload/complete', { upload_id: uploadId });
if (!comp.data || !comp.data.ok) throw new Error((comp.data && comp.data.message) || '分片合并失败');
return uploadId;
}
async function collectPickedFiles() {
const map = {};
for (const field of inputFields()) {
if (field.type !== 'file') continue;
const input = document.querySelector(`[name="${field.name}"]`);
if (input && input.files && input.files[0]) { map[field.name] = input.files[0]; continue; }
const stored = storageManager.files.find((f) => f.fieldName === field.name);
if (stored) {
try {
const got = await storageManager.getFile(stored.id);
if (got && got.file) map[field.name] = got.file;
} catch (e) { /* 读不出来当作没选 */ }
}
}
return map;
}
function formatFileSize(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
function formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
async function handleSubmit(e) {
e.preventDefault();
if (CURRENT_PAGE_INDEX < FORM_PAGES.length - 1) {
nextFormPage();
return;
}
if (SUBMIT_LOCKED) return;
applyUrlPreset();
const submitBtn = document.getElementById('submitBtn');
const tailInput = document.querySelector('input[name="tail"]');
const tail = IS_ANON ? '' : (tailInput ? tailInput.value.trim() : '');
for (let pageIndex = 0; pageIndex < FORM_PAGES.length; pageIndex++) {
if (!validateFormPage(pageIndex)) return;
}
// ===== 可插拔提交前校验(validation)=====
// 脚本在浏览器端运行,收到本表单全部字段内容(文件字段为 File 对象),自行判定通过与否。
const vcfg = CURRENT_FORM.validation;
if (vcfg && vcfg.enabled && vcfg.script && String(vcfg.script).trim()) {
// 收集全部字段内容
const values = {};
for (const field of inputFields()) {
const input = document.querySelector(`[name="${field.name}"]`);
if (field.type === 'file') {
let file = null;
if (input && input.files && input.files[0]) file = input.files[0];
else {
const sf = storageManager.files.find(f => f.fieldName === field.name);
if (sf) { const g = await storageManager.getFile(sf.id); file = g ? g.file : null; }
}
values[field.name] = file;
} else if (field.type === 'rating') {
const ri = document.querySelector(`input[name="${field.name}"][data-field-type="rating"]`);
const rc = ri ? ri.parentElement.querySelector('.rating-stars') : null;
values[field.name] = (rc && rc.dataset.value) ? rc.dataset.value : '';
} else if (field.type === 'checkbox') {
const chk = document.querySelectorAll(`[name="${field.name}"]:checked`);
values[field.name] = Array.from(chk).map(c => c.value).join(',');
} else if (field.type === 'radio') {
const chk = document.querySelector(`[name="${field.name}"]:checked`);
values[field.name] = chk ? chk.value : '';
} else {
values[field.name] = input ? input.value : '';
}
}
let vfn = null;
try {
vfn = new Function('values', 'fields', 'ctx',
`"use strict"; return (${String(vcfg.script)})(values, fields, ctx);`);
} catch (err) {
console.error('[validation] 脚本解析失败:', err);
}
if (vfn) {
const ctx = { name: (STUDENT_MAP[tail] || {}).name || '', studentId: tail };
let result;
try {
result = await vfn(values, inputFields(), ctx);
} catch (err) {
umShowError(`校验脚本出错:${err && err.message ? err.message : err}`);
return;
}
const fallbackMsg = (vcfg.failToast || '').trim() || '提交内容未通过校验,请检查后重试。';
let blocked = false, msg = fallbackMsg;
if (result === false) blocked = true;
else if (result && typeof result === 'object' && result.ok === false) {
blocked = true;
if (typeof result.msg === 'string' && result.msg.trim()) msg = result.msg.trim();
}
if (blocked) { umShowError(msg); return; }
}
}
let verifyTail = '';
const needVerify = IS_OVERWRITE && !IS_ANON && (
(CURRENT_FORM.overwriteVerify && CURRENT_FORM.overwriteVerify.enabled) ||
CURRENT_FORM.requireIdCard
);
if (needVerify) {
const verifyConfig = CURRENT_FORM.overwriteVerify;
const verifyLabel = verifyConfig && verifyConfig.label ? verifyConfig.label : '验证信息';
const verifyDigits = verifyConfig && verifyConfig.digits ? verifyConfig.digits : 4;
verifyTail = await openVerifyCard({
title: '身份验证',
desc: `检测到已有提交记录。请输入该学生${verifyLabel}后${verifyDigits}位以验证身份并更新数据。`,
maxlength: verifyDigits,
placeholder: '•'.repeat(verifyDigits),
okText: '确认并继续',
inputFilter: v => v.toUpperCase().replace(/[^0-9X]/g, ''),
sourceEl: submitBtn,
keepOpen: true, // 验证通过后卡片保持展开,原位切换到上传进度
onSubmit: async (value) => {
const formId = window.location.pathname.slice(1) || 'default';
const resp = await fetch('/get_verify_value', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ studentId: tail, formId, value })
});
const data = await resp.json();
if (data.success) return true;
return `${verifyLabel}后${verifyDigits}位不匹配`;
}
});
if (verifyTail === null) return; // 用户取消
}
const submitFormId = window.location.pathname.slice(1) || 'default';
const pickedFiles = await collectPickedFiles();
const formData = new FormData();
formData.append('studentId', tail);
formData.append('formId', window.location.pathname.slice(1) || 'default');
// 设备令牌:30 天落盘 cookie,服务端据此支持"加载上次填写"
formData.append('device_token', ensureDeviceToken());
if (verifyTail) {
formData.append('verifyTail', verifyTail);
formData.append('idCardTail', verifyTail);
}
inputFields().forEach(field => {
if (field.type === 'rating') {
const ratingInput = document.querySelector(`input[name="${field.name}"][data-field-type="rating"]`);
if (ratingInput) {
const ratingContainer = ratingInput.parentElement.querySelector('.rating-stars');
if (ratingContainer && ratingContainer.dataset.value) {
formData.append(field.name, ratingContainer.dataset.value);
}
}
} else if (field.type === 'file') {
const picked = pickedFiles[field.name];
if (!picked) return;
// 大文件不进 FormData:稍后分片上传,用 fileTokens 挂载
if (picked.size > CHUNK_THRESHOLD) return;
formData.append(field.name, picked);
} else {
const input = document.querySelector(`[name="${field.name}"]`);
if (!input) return;
if (field.type === 'checkbox') {
const checked = document.querySelectorAll(`[name="${field.name}"]:checked`);
formData.append(field.name, Array.from(checked).map(c => c.value).join(','));
} else if (field.type === 'radio') {
const checked = document.querySelector(`[name="${field.name}"]:checked`);
if (checked) formData.append(field.name, checked.value);
} else {
formData.append(field.name, input.value);
}
}
});
// 标记"沿用上次提交"的文件:服务端保留原文件,不要求重新上传
if (Object.keys(keepFiles).length > 0) {
formData.append('keep_files', JSON.stringify(keepFiles));
}
// 禁止重复提交:提交前形变卡片二次确认
if (POLICY_ONCE) {
const ok = await UMC.confirm({
title: '仅可提交一次',
desc: '此表单只允许提交一次,提交后不能再修改。请确认填写无误。',
okText: '确认提交',
cancelText: '再检查一下',
sourceEl: submitBtn,
keepOpen: true, // 确认后卡片保持展开,原位切换到上传进度
});
if (!ok) return; // 用户取消,卡片收回
}
submitBtn.disabled = true;
submitBtn.classList.add('opacity-90', 'cursor-not-allowed');
// 展开上传进度卡片(接管原按钮位置)
umOpenProgress();
// ===== 大文件先分片上传,成功后把 upload_id 作为 fileTokens 一起提交 =====
const bigFiles = Object.entries(pickedFiles).filter(([, f]) => f && f.size > CHUNK_THRESHOLD);
if (bigFiles.length) {
const totalBytes = bigFiles.reduce((sum, [, f]) => sum + f.size, 0);
const fileTokens = {};
let uploadedBefore = 0;
let lastTick = Date.now();
let lastBytes = 0;
try {
for (const [fieldName, file] of bigFiles) {
const uploadId = await uploadFileChunked(file, submitFormId, fieldName, (loadedInFile) => {
const overall = uploadedBefore + loadedInFile;
const now = Date.now();
const dt = (now - lastTick) / 1000;
if (dt < 0.25 && overall < totalBytes) return;
const speed = dt > 0 ? (overall - lastBytes) / dt / 1024 / 1024 : 0;
lastTick = now;
lastBytes = overall;
const remain = speed > 0 ? (totalBytes - overall) / (speed * 1024 * 1024) : 0;
umUpdateProgress({
percent: Math.round((overall / totalBytes) * 100),
text: `${speed.toFixed(2)} MB/s · ${formatFileSize(overall)} / ${formatFileSize(totalBytes)} · 剩余 ${formatTime(remain)}(分片上传,可断点续传)`
});
});
fileTokens[fieldName] = uploadId;
uploadedBefore += file.size;
}
formData.append('fileTokens', JSON.stringify(fileTokens));
} catch (err) {
console.error('分片上传失败:', err);
submitBtn.disabled = false;
submitBtn.classList.remove('opacity-90', 'cursor-not-allowed');
umShowError(err.message || '文件上传失败,请重试');
return;
}
}
const xhr = new XMLHttpRequest();
let startTime = Date.now(), lastTime = startTime, lastLoaded = 0;
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
const now = Date.now();
const currentLoaded = e.loaded;
const timeDiff = (now - lastTime) / 1000;
const bytesDiff = currentLoaded - lastLoaded;
const speed = timeDiff > 0 ? bytesDiff / 1024 / 1024 : 0;
lastTime = now;
lastLoaded = currentLoaded;
const remainingBytes = e.total - currentLoaded;
const remainingTime = speed > 0 ? remainingBytes / (speed * 1024 * 1024) : 0;
const percent = Math.round((currentLoaded / e.total) * 100);
umUpdateProgress({
percent,
text: `${speed.toFixed(2)} MB/s · ${formatFileSize(currentLoaded)} / ${formatFileSize(e.total)} · 剩余 ${formatTime(remainingTime)}`
});
}
});
xhr.addEventListener('load', () => {
submitBtn.disabled = false;
submitBtn.classList.remove('opacity-90', 'cursor-not-allowed');
umUpdateProgress({ text: '服务器处理中…' });
try {
if (xhr.status < 200 || xhr.status >= 300) {
umShowError(`服务器错误:${xhr.status} ${xhr.statusText}`);
return;
}
if (!xhr.responseText || xhr.responseText.trim() === '') {
umShowError('服务器返回空响应,请稍后重试');
return;
}
const data = JSON.parse(xhr.responseText);
if (data.success) {
clearLocalStorage();
keepFiles = {}; // 提交成功,"沿用上次"状态随之失效
const toast = document.getElementById('toast');
if (toast) {
toast.classList.remove('show');
}
umShowSuccess();
if (POLICY_ONCE) lockSubmitButton(); // 禁止重复:成功后锁定,避免再交被拒的困惑
const oldMsgDiv = document.getElementById('message');
if (oldMsgDiv) {
oldMsgDiv.style.display = 'none';
}
document.getElementById('upForm').reset();
const nameField = CURRENT_FORM.fields.find(f => f.name === 'name');
if (nameField) {
const nameInput = document.querySelector('input[name="name"]');
if (nameInput) nameInput.value = '';
}
document.querySelectorAll('input[type="file"]').forEach(input => {
input.value = '';
input.classList.remove('has-file');
input.removeAttribute('data-has-file');
const fileWrapper = input.closest('[class*="group/file"]');
if (fileWrapper) {
const fileDisplay = fileWrapper.querySelector('div');
const fileNameDisplay = fileWrapper.querySelector('p[id^="fileName_"]');
const iconDiv = fileDisplay?.querySelector('div:first-child');
if (fileDisplay) {
fileDisplay.style.borderColor = 'var(--border-color)';
fileDisplay.style.backgroundColor = 'transparent';
fileDisplay.style.boxShadow = 'none';
fileDisplay.style.transform = 'translateY(0)';
fileDisplay.style.animation = 'none';
}
if (fileNameDisplay) {
const fieldName = fileNameDisplay.id.replace('fileName_', '');
const field = CURRENT_FORM.fields.find(f => f.name === fieldName);
const allowedExts = field?.allowedExts || CURRENT_FORM.allowedExts;
fileNameDisplay.textContent = '支持格式: ' + (allowedExts ? allowedExts.join(', ') : '所有文件');
fileNameDisplay.style.color = '';
fileNameDisplay.style.fontWeight = '';
}
if (iconDiv) {
iconDiv.innerHTML = `<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M12 16V4M12 4L8 8M12 4L16 8M4 17V18C4 19.1046 4.89543 20 6 20H18C19.1046 20 20 19.1046 20 18V17"/>
</svg>`;
}
}
});
document.querySelectorAll('.rating-stars').forEach(container => {
renderRatingValue(container, 0, true);
});
applyUrlPreset();
gsap.fromTo("#formContainer",
{ scale: 1 },
{ scale: 1.02, duration: 0.15, yoyo: true, repeat: 1, ease: "power2.inOut" }
);
checkSubmissionStatus();
if (SHOW_PROGRESS) {
loadProgress();
}
// 提交成功后清理 IndexedDB 中的文件
storageManager.clearAllFiles().then(() => {
updateStorageUI();
});
} else {
umShowError(`提交失败:${data.message}`);
}
} catch (e) {
console.error('响应解析错误:', e);
console.error('原始响应:', xhr.responseText);
umShowError('响应解析错误,请稍后重试');
}
setTimeout(() => {
if (IS_OVERWRITE) {
submitBtn.innerHTML = '<span class="relative z-10 flex items-center justify-center gap-2">更新已有记录 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg></span>';
submitBtn.classList.add('ring-2', 'ring-offset-2');
} else {
submitBtn.innerHTML = '<span class="relative z-10 flex items-center justify-center gap-2">提交表单 <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="opacity-70"><path d="M5 12h14M12 5l7 7-7 7"/></svg></span>';
submitBtn.classList.remove('ring-2', 'ring-offset-2');
}
}, 2000);
});
xhr.addEventListener('error', () => {
submitBtn.disabled = false;
submitBtn.classList.remove('opacity-90', 'cursor-not-allowed');
umShowError('网络错误,请检查网络后重试');
});
xhr.open('POST', '/api/submit');
xhr.send(formData);
}
// Initialize
async function init() {
try {
const formId = window.location.pathname.slice(1);
if (!formId || formId === '') {
showToast('无效的表单链接', 'error');
return;
}
await Promise.all([
loadStudentInfo(),
loadFormConfig(formId)
]);
renderForm();
// 检测是否有可恢复的文件,显示提示
setTimeout(() => {
checkAndShowRestoreBanner();
}, 1000);
// 检测设备令牌:是否显示"加载上次填写"横幅
initLastSubmissionBanner();
} catch (e) {
console.error('Initialization error:', e);
}
}
init();
</script>
</body>
</html>