Files
zzy 84f8516c37 feat(upload): 分片断点续传 + 前端静态资源去 CDN 化
1) 分片上传(routes/chunked.py)
   - POST /api/upload/init  建会话,校验表单/字段/扩展名/体积
   - POST /api/upload/chunk 单片上传,幂等可重传,http body 直写磁盘
   - GET  /api/upload/status 查询已收分片
   - POST /api/upload/complete 按序合并 + sha256 校验 + 清理分片
   - /api/submit 新增 field fileTokens 挂载已上传文件(零拷贝 os.replace)
   - 过期会话(24h)由定时任务清理

2) 弱网下的样式可靠性
   - Tailwind Play CDN / GSAP 改为本地自托管(static/js/vendor/)
   - vendor 资源 1 年 immutable 缓存,自家 css/js 1 小时
   - CSS link 失败自动带 ?r= 重试一次
   - status 页加关键内联样式兜底,极端情况下仍可读

3) 大文件落盘沿用流式写入(无 400MB 内存峰值)
2026-11-13 12:06:32 +08:00

2508 lines
135 KiB
HTML

<!DOCTYPE html>
<html lang="zh-CN" class="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>新建表单</title>
<!-- Tailwind CSS -->
<script src="/static/js/vendor/tailwind-play.js"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
serif: ['Playfair Display', 'serif'],
},
colors: {
neutral: {
50: '#fafafa',
100: '#f5f5f5',
200: '#e5e5e5',
300: '#d4d4d4',
400: '#a3a3a3',
500: '#737373',
600: '#525252',
700: '#404040',
800: '#262626',
900: '#171717',
}
}
}
}
}
</script>
<!-- GSAP for animations -->
<script src="/static/js/vendor/gsap.min.js"></script>
<script src="/static/js/gsap-fallback.js"></script>
<!-- SortableJS for drag and drop -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<script src="/static/js/particles.js"></script>
<link rel="stylesheet" href="/static/css/toast.css" onerror="this.onerror=null;this.href='/static/css/toast.css?r='+Date.now()">
<script src="/static/js/toast.js"></script>
<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/form-components.js"></script>
<script src="/static/js/webhook-settings.js"></script>
<style>
/* ── create 页面专属样式 ── */
/* Checkbox Custom */
.checkbox-custom {
appearance: none;
width: 18px;
height: 18px;
border: 2px solid var(--border-color);
border-radius: 6px;
cursor: pointer;
position: relative;
transition: all 0.2s;
flex-shrink: 0;
}
.checkbox-custom:checked {
background-color: var(--accent-bg);
border-color: var(--accent-bg);
}
.checkbox-custom:checked::after {
content: '';
position: absolute;
left: 4px;
top: 0px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
.dark .checkbox-custom:checked::after {
border-color: var(--accent-text);
}
/* Link Input */
.link-input {
width: 100%;
padding: 12px 16px;
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 12px;
font-size: 13px;
color: var(--text-secondary);
cursor: pointer;
transition: all 0.2s;
font-family: 'SF Mono', monospace;
}
.link-input:hover {
border-color: var(--text-muted);
}
.link-input.copied {
border-color: var(--success-text);
background: var(--success-bg);
color: var(--success-text);
}
/* Info Box */
.info-box {
background: var(--info-bg);
border: 1px solid var(--info-border);
color: var(--info-text);
padding: 16px 20px;
border-radius: 12px;
font-size: 14px;
line-height: 1.6;
}
/* Preset Selection */
.preset-option {
padding: 12px 16px;
border-radius: 12px;
cursor: pointer;
transition: all 0.2s;
border: 1px solid var(--border-color);
margin-bottom: 8px;
}
.preset-option:hover {
background: var(--bg-primary);
border-color: var(--text-muted);
}
.preset-option.selected {
background: var(--info-bg);
border-color: var(--info-text);
}
/* Advanced Settings */
.advanced-settings {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
}
.advanced-settings.open {
max-height: 3000px;
}
/* Rating Stars */
.rating-input {
display: flex;
gap: 4px;
}
.rating-star {
cursor: pointer;
transition: transform 0.2s;
}
.rating-star:hover {
transform: scale(1.2);
}
/* 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);
}
/* Mobile touch optimization for sortable */
@media (hover: none) and (pointer: coarse) {
.field-card {
touch-action: pan-y pinch-zoom;
}
.sortable-drag {
touch-action: none;
}
}
/* 窄屏在题型、编辑区和设置区之间切换 */
@media (max-width: 1279px) {
#builderContainer:not(.palette-mode) #palettePane { display: none !important; }
#builderContainer:not(.editor-mode) #editorPane { display: none !important; }
#builderContainer:not(.settings-mode) #settingsPane { display: none !important; }
#tabPalette.active, #tabEditor.active, #tabSettings.active {
background: var(--accent-bg); color: var(--accent-text);
}
}
.palette-pane .fc-palette { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
.palette-pane .fc-tile {
flex-direction: row; justify-content: flex-start; gap: 9px;
min-height: 42px; padding: 9px 10px;
}
.palette-pane .fc-tile svg { width: 17px; height: 17px; flex: 0 0 auto; }
.palette-pane .fc-label { font-size: 12px; }
@media (min-width: 1280px) {
.palette-pane > .glass, .settings-pane > .glass {
max-height: calc(100vh - 128px);
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: color-mix(in srgb, var(--text-muted) 42%, transparent) transparent;
}
.palette-pane > .glass::-webkit-scrollbar,
.settings-pane > .glass::-webkit-scrollbar { width: 7px; }
.palette-pane > .glass::-webkit-scrollbar-track,
.settings-pane > .glass::-webkit-scrollbar-track { background: transparent; }
.palette-pane > .glass::-webkit-scrollbar-thumb,
.settings-pane > .glass::-webkit-scrollbar-thumb {
background: color-mix(in srgb, var(--text-muted) 34%, transparent);
border: 2px solid transparent;
border-radius: 999px;
background-clip: padding-box;
}
.palette-pane > .glass::-webkit-scrollbar-thumb:hover,
.settings-pane > .glass::-webkit-scrollbar-thumb:hover {
background: color-mix(in srgb, var(--text-secondary) 58%, transparent);
background-clip: padding-box;
}
}
#fieldsList { min-height: 48px; display: grid; gap: 12px; }
#fieldsList .field-card { margin-bottom: 0; }
.field-sort-guide {
display: flex; align-items: center; gap: 12px; padding: 12px 14px; margin-bottom: 14px;
border: 1px solid var(--border-color); border-radius: 14px;
background: linear-gradient(110deg, var(--bg-primary), transparent 82%);
color: var(--text-secondary); font-size: 12px;
}
.field-sort-guide-icon {
display: grid; width: 32px; height: 32px; flex: 0 0 auto; place-items: center;
border: 1px solid var(--border-color); border-radius: 10px; color: var(--accent-bg);
}
.field-order-controls { display: flex; align-items: center; gap: 4px; }
.field-order-button {
display: inline-grid; width: 32px; height: 32px; place-items: center;
border: 1px solid var(--border-color); border-radius: 10px;
background: var(--bg-primary); color: var(--text-secondary);
transition: color .18s ease, border-color .18s ease, background .18s ease, transform .18s ease;
}
.field-order-button:hover:not(:disabled) {
color: var(--accent-bg); border-color: var(--border-focus); background: var(--glass-hover); transform: translateY(-1px);
}
.field-order-button:disabled { opacity: .35; cursor: not-allowed; }
.field-order-button:focus-visible, .drag-handle:focus-visible { outline: 2px solid var(--border-focus); outline-offset: 2px; }
.field-card .drag-handle {
display: grid; width: 32px; height: 32px; margin: 0; padding: 0; place-items: center;
border: 1px solid var(--border-color); background: var(--bg-primary); color: var(--text-muted);
}
.field-card .drag-handle:hover { color: var(--accent-bg); border-color: var(--border-focus); }
.field-card.sortable-ghost { opacity: .42; border-style: dashed; transform: scale(.99); }
.field-card.sortable-drag { transform: scale(1.015); animation: none; }
@media (max-width: 640px) {
.field-sort-guide { align-items: flex-start; }
.field-order-button, .field-card .drag-handle { width: 36px; height: 36px; }
}
#fieldsList.palette-drop-active {
outline: 2px dashed var(--border-focus);
outline-offset: 5px;
border-radius: 14px;
}
</style>
</head>
<body class="builder-page antialiased min-h-screen relative pb-24">
<!-- Progress Bar -->
<div class="fixed top-0 left-0 w-full h-[2px] z-50 theme-transition" style="background-color: var(--border-color);">
<div id="scrollProgress" class="h-full w-0 transition-all duration-100 ease-out"></div>
</div>
<!-- Header -->
<header class="fixed top-0 w-full z-40 px-4 sm:px-6 py-4 sm:py-5 glass theme-transition border-b"
style="border-color: var(--glass-border);">
<div class="max-w-7xl mx-auto flex justify-between items-center">
<!-- 左侧:面包屑 -->
<div class="flex items-center gap-2.5">
<a href="/admin" class="nav-link flex items-center gap-1.5">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/>
<rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/>
</svg>
<span class="hidden sm:inline text-sm">管理后台</span>
</a>
<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" style="color:var(--text-muted);opacity:0.4">
<path d="m9 18 6-6-6-6"/>
</svg>
<span class="text-sm font-medium" style="color:var(--text-primary)">新建表单</span>
</div>
<!-- 右侧:返回 -->
<div class="flex justify-end sm:gap-3">
<a href="/admin" class="btn btn-secondary px-4 py-2.5 rounded-full text-xs sm:text-sm font-medium tracking-wide flex justify-end">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M19 12H5M12 19l-7-7 7-7"/>
</svg>
<span class="hidden sm:inline">返回</span>
</a>
</div>
</div>
</header>
<!-- Main Content -->
<main class="relative pt-32 px-6">
<div class="max-w-[1600px] mx-auto grid grid-cols-1 xl:grid-cols-[230px_minmax(0,1fr)_280px] 2xl:grid-cols-[260px_minmax(0,1fr)_320px] gap-6 2xl:gap-8 items-start" id="builderContainer">
<!-- 移动端:题型库 / 题目编辑区切换 -->
<div class="xl:hidden w-full sticky top-[84px] z-30" id="mobileTabbar">
<div class="glass rounded-full p-1 flex theme-transition" style="border-color: var(--glass-border);">
<button type="button" id="tabPalette" onclick="showMobilePane('palette')"
class="flex-1 py-2.5 rounded-full text-sm font-medium transition-all duration-200 theme-transition">
题型
</button>
<button type="button" id="tabEditor" onclick="showMobilePane('editor')"
class="flex-1 py-2.5 rounded-full text-sm font-medium transition-all duration-200 theme-transition">
编辑表单<span id="tabEditorCount" class="hidden ml-1.5 px-1.5 py-0.5 rounded-full text-[10px]" style="background: var(--accent-bg); color: var(--accent-text);">0</span>
</button>
<button type="button" id="tabSettings" onclick="showMobilePane('settings')"
class="flex-1 py-2.5 rounded-full text-sm font-medium transition-all duration-200 theme-transition">
设置
</button>
</div>
</div>
<aside id="palettePane" class="palette-pane w-full xl:sticky xl:top-[104px] self-start">
<div class="glass rounded-3xl p-5 sm:p-6 theme-transition">
<div class="mb-5">
<p class="text-[10px] font-semibold tracking-[0.22em] uppercase mb-2" style="color: var(--text-muted);">组件库</p>
<h2 class="font-serif text-2xl font-medium tracking-tight" style="color: var(--text-primary);">添加题目</h2>
<p class="text-xs mt-2 leading-relaxed" style="color: var(--text-secondary);">点击题型添加到编辑区,也可以拖到指定位置。</p>
</div>
<div id="componentPalette"></div>
<div id="basicSettingsPanel" class="mt-6 pt-6 border-t" style="border-color: var(--border-color);">
<div class="mb-4">
<p class="text-[10px] font-semibold tracking-[0.22em] uppercase mb-1" style="color: var(--text-muted);">基础设置</p>
<h3 class="text-base font-semibold" style="color: var(--text-primary);">名单与提交</h3>
</div>
<div class="mb-5">
<label class="block text-xs mb-2" style="color: var(--text-secondary);">附件大小限制 (MB)</label>
<input type="number" id="maxSize" value="1024" min="1" max="10240"
class="input-underline theme-transition bg-transparent text-sm">
</div>
<div id="presetSelection" class="mb-4">
<button type="button" class="preset-option w-full text-left" onclick="selectPreset('__anon__')" data-preset-id="__anon__" id="anonPresetCard" aria-pressed="true">
<span class="flex justify-between items-center gap-2">
<span class="flex min-w-0 items-center gap-2">
<span class="font-medium text-sm shrink-0" style="color: var(--text-primary);">匿名收集</span>
<span class="text-xs truncate" style="color: var(--text-muted);">不使用名单,字段完全自定义</span>
</span>
</span>
</button>
<p class="text-xs mt-4 mb-2" style="color: var(--text-secondary);">名单预设</p>
<div id="presetsList" class="max-h-40 overflow-y-auto">
<div class="text-center py-4 text-sm" style="color: var(--text-muted);">加载中...</div>
</div>
<div class="mt-3 flex gap-2">
<button type="button" onclick="loadPresets()"
class="text-xs px-3 py-2 rounded-lg border transition-colors"
style="border-color: var(--border-color); color: var(--text-muted);">刷新</button>
<a href="/preset_manage" target="_blank"
class="text-xs px-3 py-2 rounded-lg border transition-colors inline-flex items-center gap-1"
style="border-color: var(--border-color); color: var(--text-muted);">管理名单</a>
</div>
</div>
<div id="duplicatePolicySection" class="mt-5">
<p class="text-xs mb-2" style="color: var(--text-secondary);">重复提交</p>
<button type="button" class="preset-option w-full text-left flex min-w-0 items-center gap-2" id="policyOverwriteCard" onclick="setDuplicatePolicy('overwrite')" aria-pressed="true">
<span class="font-medium text-sm shrink-0" style="color: var(--text-primary);">允许覆盖</span>
<span class="text-xs truncate" style="color: var(--text-muted);">再次提交时更新原记录</span>
</button>
<button type="button" class="preset-option w-full text-left flex min-w-0 items-center gap-2" id="policyOnceCard" onclick="setDuplicatePolicy('once')" aria-pressed="false">
<span class="font-medium text-sm shrink-0" style="color: var(--text-primary);">仅限一次</span>
<span class="text-xs truncate" style="color: var(--text-muted);">已提交者不能再次提交</span>
</button>
</div>
</div>
</div>
</aside>
<!-- 右侧:表单设置与题目编辑 -->
<div id="editorPane" class="w-full min-w-0 mx-auto lg:mx-0">
<!-- Header Section -->
<div class="mb-12" id="headerSection">
<p class="studio-kicker"><span class="studio-kicker__dot"></span> FORM STUDIO / CREATE</p>
<h2 class="font-serif text-4xl sm:text-5xl leading-[1.1] font-medium tracking-tight mb-4 theme-transition"
style="color: var(--text-primary);">
创建新表单
</h2>
<p class="text-sm leading-relaxed max-w-md tracking-wide font-light theme-transition"
style="color: var(--text-secondary);">
从题型开始搭建内容,再配置收集规则。完成后即可分享给填写者。
</p>
</div>
<!-- Form Container -->
<div class="glass rounded-3xl p-8 sm:p-12 relative overflow-hidden shadow-2xl theme-transition"
style="box-shadow: 0 20px 50px var(--shadow-color);">
<!-- Basic Info -->
<div class="space-y-8 mb-10">
<div class="stagger-item">
<label class="block text-[11px] font-semibold tracking-[0.2em] uppercase mb-3 theme-transition"
style="color: var(--text-muted);">
表单标题
</label>
<input type="text" id="formTitle" placeholder="例如:秋季资料收集"
class="input-underline font-medium text-lg theme-transition">
</div>
<!-- 公告 / 表单说明 -->
<details id="announcementDetails" class="stagger-item rounded-2xl border group"
style="border-color: var(--border-color); background: var(--bg-primary);">
<summary class="flex cursor-pointer list-none items-center justify-between gap-4 px-4 py-3">
<span class="text-sm font-medium" style="color: var(--text-primary);">公告 / 表单说明</span>
<span class="flex items-center gap-2 text-xs" style="color: var(--text-muted);">
可选
<svg class="transition-transform group-open:rotate-180" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"></polyline></svg>
</span>
</summary>
<div class="space-y-4 border-t px-4 pb-4 pt-4" style="border-color: var(--border-color);">
<input type="text" id="announcementSubtitle" placeholder="副标题(可选)"
class="input-underline theme-transition">
<textarea id="announcementText" rows="4" placeholder="填写公告或表单说明,支持纯文本(可选)"
class="input-underline theme-transition resize-y w-full"></textarea>
<!-- 公告附件 -->
<div>
<div class="flex items-center justify-between mb-2">
<label class="block text-[11px] font-semibold tracking-[0.2em] uppercase theme-transition"
style="color: var(--text-muted);">
附件
</label>
<span class="text-xs theme-transition" style="color: var(--text-muted);" id="announcementFileCount">0 / 3</span>
</div>
<div id="announcementFilesList" class="space-y-2"></div>
<button type="button" onclick="addAnnouncementFileInput()" id="addAnnouncementFileBtn"
class="mt-2 text-xs px-3 py-2 rounded-lg border hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors inline-flex items-center gap-1"
style="border-color: var(--border-color); color: var(--text-secondary);">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
stroke-width="2">
<line x1="12" y1="5" x2="12" y2="19"></line>
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
添加附件
</button>
</div>
</div>
</details>
</div>
<section id="fieldsSection" class="mb-10 stagger-item scroll-mt-28">
<div class="flex justify-between items-end mb-4">
<div>
<p class="text-[10px] font-semibold tracking-[0.2em] uppercase mb-1" style="color: var(--text-muted);">Form Builder</p>
<h3 class="font-serif text-2xl font-medium tracking-tight" style="color: var(--text-primary);">题目编辑</h3>
</div>
<span class="text-xs" style="color: var(--text-muted);" id="fieldCount">0 个题目</span>
</div>
<div class="field-sort-guide">
<span class="field-sort-guide-icon" aria-hidden="true">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M8 5h12M8 12h12M8 19h12"/><path d="m3 5 1.5 1.5L6 5M3 12l1.5 1.5L6 12M3 19l1.5 1.5L6 19"/></svg>
</span>
<span><strong style="color: var(--text-primary);">调整题目顺序</strong><br>拖动左侧手柄,或用卡片上的上下按钮精确移动</span>
</div>
<p id="fieldOrderStatus" class="sr-only" role="status" aria-live="polite"></p>
<div id="emptyFieldsState" class="rounded-2xl border border-dashed p-8 text-center mb-4" style="border-color: var(--border-color); color: var(--text-muted);">
<p class="text-sm font-medium" style="color: var(--text-secondary);">还没有题目</p>
<p class="text-xs mt-1">从左侧选择一种题型开始搭建表单</p>
</div>
<div id="fieldsList"></div>
</section>
<!-- Advanced Settings Toggle -->
<div id="advancedTogglePanel" class="mb-6 stagger-item">
<button type="button" onclick="toggleAdvancedSettings()" class="w-full flex items-center justify-between gap-2 text-sm font-medium"
style="color: var(--text-muted);">
<span>高级设置</span>
<svg id="advancedArrow" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" class="transition-transform">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
</div>
<!-- Advanced Settings -->
<div id="advancedSettings" class="advanced-settings mb-10">
<div class="flex flex-col gap-4 p-4 rounded-2xl" style="background: var(--bg-primary);">
<div id="verifyDigitsBlock">
<label
class="block text-[11px] font-semibold tracking-[0.2em] uppercase mb-3 theme-transition"
style="color: var(--text-muted);">
学号验证位数
</label>
<select id="verifyDigits" class="input-underline theme-transition bg-transparent">
<option value="2">后2位</option>
<option value="3">后3位</option>
<option value="4">后4位</option>
<option value="6">后6位</option>
</select>
</div>
<!-- 覆盖验证配置 -->
<div class="space-y-4" id="overwriteVerifyBlock">
<label class="flex items-center gap-3 cursor-pointer">
<input type="checkbox" id="enableOverwriteVerify" class="checkbox-custom" checked
onchange="toggleVerifyConfig()">
<span class="text-sm" style="color: var(--text-secondary);">启用覆盖验证(防止误覆盖他人提交)</span>
</label>
<div id="verifyConfigPanel" class="space-y-4 pl-7">
<div>
<label
class="block text-[11px] font-semibold tracking-[0.2em] uppercase mb-2 theme-transition"
style="color: var(--text-muted);">
验证字段
</label>
<select id="verifyField" class="input-underline theme-transition bg-transparent"
onchange="updateVerifyConfig()">
<option value="idCard">身份证号</option>
<option value="phone">手机号</option>
<option value="custom">自定义字段</option>
</select>
</div>
<div id="customFieldPanel" class="hidden">
<label
class="block text-[11px] font-semibold tracking-[0.2em] uppercase mb-2 theme-transition"
style="color: var(--text-muted);">
自定义字段名
</label>
<input type="text" id="customFieldName" placeholder="例如:家长手机号"
class="input-underline theme-transition">
</div>
<div>
<label
class="block text-[11px] font-semibold tracking-[0.2em] uppercase mb-2 theme-transition"
style="color: var(--text-muted);">
验证位数
</label>
<select id="verifyDigitsCount"
class="input-underline theme-transition bg-transparent">
<option value="2">后2位</option>
<option value="3">后3位</option>
<option value="4" selected>后4位</option>
<option value="6">后6位</option>
</select>
</div>
<div>
<label
class="block text-[11px] font-semibold tracking-[0.2em] uppercase mb-2 theme-transition"
style="color: var(--text-muted);">
显示标签
</label>
<input type="text" id="verifyLabel" value="身份证" placeholder="例如:身份证"
class="input-underline theme-transition">
</div>
</div>
</div>
<div>
<label class="flex items-center gap-3 cursor-pointer">
<input type="checkbox" id="showProgress" class="checkbox-custom" checked>
<span class="text-sm" style="color: var(--text-secondary);">显示进度给填写者</span>
</label>
</div>
<div>
<label class="flex items-center gap-3 cursor-pointer">
<input type="checkbox" id="enableExpiry" class="checkbox-custom">
<span class="text-sm" style="color: var(--text-secondary);">设置过期时间</span>
</label>
<div id="expiryConfig" class="mt-2 hidden">
<input type="datetime-local" id="expiryDate" class="input-underline theme-transition bg-transparent text-sm" style="color: var(--text-primary);">
</div>
</div>
<div class="space-y-4">
<label class="flex items-center gap-3 cursor-pointer">
<input type="checkbox" id="enableWebhook" class="checkbox-custom">
<span class="text-sm" style="color: var(--text-secondary);">启用内置 Webhook 提交通知</span>
</label>
</div>
<!-- 提交前校验(可选,浏览器端脚本) -->
<div class="space-y-4">
<label class="flex items-center gap-3 cursor-pointer">
<input type="checkbox" id="enableValidation" class="checkbox-custom"
onchange="toggleValidation()">
<span class="text-sm" style="color: var(--text-secondary);">
启用提交前校验(浏览器端运行脚本,可收到本表单全部字段值/文件,自行判定通过与否)
</span>
</label>
<div id="validationPanel" class="hidden space-y-4 pl-7">
<div>
<label
class="block text-[11px] font-semibold tracking-[0.2em] uppercase mb-2 theme-transition"
style="color: var(--text-muted);">
未通过时的提示文案
</label>
<input type="text" id="validationFailToast" class="input-underline theme-transition"
placeholder="例如:请用《综测页面》生成的 Word 上传,当前文档无法解析(缺少【加分明细】表格)">
</div>
<div>
<div class="flex items-center justify-between mb-2">
<label
class="block text-[11px] font-semibold tracking-[0.2em] uppercase theme-transition"
style="color: var(--text-muted);">
校验脚本(函数体)
</label>
<button type="button" onclick="fillDocxSampleValidation()"
class="text-xs px-3 py-1.5 rounded-lg border hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
style="border-color: var(--border-color); color: var(--text-muted);">
载入综测 .docx 校验示例
</button>
</div>
<textarea id="validationScript" rows="12" spellcheck="false"
class="input-underline theme-transition resize-y w-full font-mono text-xs"
style="color: var(--text-primary);"
placeholder="async (values, fields, ctx) => { ... }"></textarea>
<p class="text-[11px] mt-2 leading-relaxed theme-transition"
style="color: var(--text-muted);">
脚本为函数表达式,收 <code>values</code>(字段名→值,文件字段为 File 对象)、
<code>fields</code>、<code>ctx</code>(含 name/studentId)。
返回 <code>true</code> 或 <code>{ok:true}</code> 表示通过;
返回 <code>false</code> 或 <code>{ok:false, msg:'...'}</code> 表示不通过,
不通过时优先弹 <code>msg</code>,否则弹上面文案。
</p>
</div>
</div>
</div>
</div>
</div>
<!-- Actions -->
<div class="flex gap-4 pt-6 border-t stagger-item" style="border-color: var(--border-color);">
<button onclick="window.location.href='/admin'"
class="btn flex-1 py-4 rounded-xl text-sm font-semibold tracking-wide theme-transition"
style="background-color: var(--bg-primary); color: var(--text-secondary); border: 1px solid var(--border-color);">
取消
</button>
<button onclick="saveForm()" id="saveBtn"
class="btn btn-primary flex-1 py-4 rounded-xl text-sm font-semibold tracking-wide shadow-lg hover:shadow-xl transform hover:scale-[1.02] active:scale-[0.98]">
创建表单
</button>
</div>
</div>
</div><!-- /中栏:编辑 -->
<aside id="settingsPane" class="settings-pane w-full xl:sticky xl:top-[104px] self-start">
<div class="glass rounded-3xl p-5 sm:p-6 theme-transition">
<div class="mb-5">
<p class="text-[10px] font-semibold tracking-[0.22em] uppercase mb-2" style="color: var(--text-muted);">表单配置</p>
<h2 class="font-serif text-2xl font-medium tracking-tight" style="color: var(--text-primary);">设置</h2>
<p class="text-xs mt-2 leading-relaxed" style="color: var(--text-secondary);">名单、提交规则和高级选项集中在这里。</p>
</div>
<div id="settingsPaneBody"></div>
</div>
</aside>
</div>
</main>
<!-- Conditional Field Modal -->
<div class="modal-overlay" id="conditionalModal" style="display: none;">
<div class="modal-content" style="max-width: 520px;">
<div class="flex justify-between items-center mb-6">
<h3 class="font-serif text-xl font-medium" style="color: var(--text-primary);">条件显示逻辑</h3>
<button onclick="closeConditionalModal()" class="w-8 h-8 rounded-full flex items-center justify-center" style="color: var(--text-muted);">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
</button>
</div>
<div class="space-y-4">
<div>
<label class="text-sm block mb-2" style="color: var(--text-muted);">触发字段(支持所有题型)</label>
<select id="conditionalTriggerField" class="w-full bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)]" onchange="updateConditionalFieldOptions()">
<option value="">-- 选择触发字段 --</option>
</select>
</div>
<div>
<label id="conditionalValueLabel" class="text-sm block mb-2" style="color: var(--text-muted);">匹配值</label>
<select id="conditionalTriggerValue" multiple class="w-full bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)] h-32">
</select>
<input id="conditionalTriggerInput" type="text" class="hidden w-full bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)]" placeholder="输入匹配值">
<p id="conditionalValueHint" class="text-xs mt-1" style="color: var(--text-muted);">按住 Ctrl/Cmd 可以多选</p>
</div>
<div>
<label class="text-sm block mb-2" style="color: var(--text-muted);">匹配方式</label>
<select id="conditionalMatchMode" class="w-full bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)]">
<option value="exact">完全匹配 - 用户选择的所有选项必须完全一致</option>
<option value="contains">包含关系 - 用户选择必须包含设置的选项</option>
<option value="loose">宽松匹配 - 用户选择的任意一项符合即可</option>
<option value="not_equals">不等于</option>
<option value="greater">大于</option>
<option value="greater_equal">大于或等于</option>
<option value="less">小于</option>
<option value="less_equal">小于或等于</option>
<option value="not_empty">已填写 / 已选择</option>
<option value="empty">未填写 / 未选择</option>
</select>
</div>
<div>
<label class="text-sm block mb-2" style="color: var(--text-muted);">执行操作</label>
<select id="conditionalAction" class="w-full bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)]">
<option value="show">显示此字段</option>
<option value="hide">隐藏此字段</option>
</select>
</div>
</div>
<div class="flex gap-3 mt-6">
<button onclick="closeConditionalModal()" class="btn flex-1 py-3 rounded-xl text-sm font-medium" style="background-color: var(--bg-primary); color: var(--text-secondary); border: 1px solid var(--border-color);">取消</button>
<button onclick="saveConditionalConfig()" class="btn btn-primary flex-1 py-3 rounded-xl text-sm font-medium">保存</button>
</div>
</div>
</div>
<!-- Success Modal -->
<div class="modal-overlay" id="successModal">
<div class="modal-content">
<div class="text-center mb-8">
<div class="w-16 h-16 mx-auto mb-4 rounded-full flex items-center justify-center theme-transition"
style="background-color: var(--success-bg);">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
style="color: var(--success-text);">
<path d="M5 13l4 4L19 7" />
</svg>
</div>
<h3 class="font-serif text-2xl font-medium mb-2 theme-transition" style="color: var(--text-primary);">
创建成功
</h3>
<p class="text-sm theme-transition" style="color: var(--text-muted);">
表单已生成,请复制以下链接分享给填写者
</p>
</div>
<div class="space-y-4 mb-8">
<div>
<label class="block text-[10px] font-semibold tracking-[0.2em] uppercase mb-2 theme-transition"
style="color: var(--text-muted);">
填写链接
</label>
<input type="text" id="formLink" class="link-input" readonly onclick="copyLink('formLink')">
</div>
<div>
<label class="block text-[10px] font-semibold tracking-[0.2em] uppercase mb-2 theme-transition"
style="color: var(--text-muted);">
状态查看链接
</label>
<input type="text" id="statusLink" class="link-input" readonly onclick="copyLink('statusLink')">
</div>
</div>
<div class="flex gap-3">
<button onclick="closeSuccessModal()"
class="btn flex-1 py-3 rounded-xl text-sm font-medium theme-transition"
style="background-color: var(--bg-primary); color: var(--text-secondary); border: 1px solid var(--border-color);">
关闭
</button>
<button onclick="goToForm()"
class="btn btn-primary flex-1 py-3 rounded-xl text-sm font-medium shadow-lg">
查看表单
</button>
</div>
</div>
</div>
<script>
// Field Types Configuration
const fieldTypes = {
'text': { label: '文本', icon: 'T' },
'textarea': { label: '多行文本', icon: '¶' },
'number': { label: '数字', icon: '123' },
'select': { label: '下拉选择', icon: '▼' },
'radio': { label: '单选', icon: '◉' },
'checkbox': { label: '多选', icon: '☑' },
'rating': { label: '评分', icon: '★' },
'date': { label: '日期', icon: '📅' },
'time': { label: '时间', icon: '🕐' },
'slider': { label: '滑块', icon: '━' },
'file': { label: '文件上传', icon: '📎' },
'page_break': { label: '分页', icon: 'Ⅱ' }
};
let fieldCount = 0;
let currentFormId = '';
let selectedPresetId = '';
let sortableInstance = null;
let pendingAnnouncementFiles = [];
// Initialize Sortable with mobile support - 丝滑动画优化
function initSortable() {
const fieldsList = document.getElementById('fieldsList');
if (!fieldsList) return;
if (sortableInstance) {
sortableInstance.destroy();
}
if (!fieldsList.dataset.orderKeysBound) {
fieldsList.dataset.orderKeysBound = 'true';
fieldsList.addEventListener('keydown', event => {
const handle = event.target.closest('.drag-handle');
if (!handle || !['ArrowUp', 'ArrowDown'].includes(event.key)) return;
event.preventDefault();
const card = handle.closest('.field-card');
if (card) moveField(card.id, event.key === 'ArrowUp' ? -1 : 1);
});
}
if (typeof Sortable === 'undefined') return;
// Detect if touch device
const isTouchDevice = window.matchMedia('(hover: none) and (pointer: coarse)').matches;
sortableInstance = new Sortable(fieldsList, {
handle: '.drag-handle',
animation: 220,
ghostClass: 'sortable-ghost',
dragClass: 'sortable-drag',
delay: isTouchDevice ? 150 : 0, // 减少延迟,更灵敏
delayOnTouchOnly: true,
touchStartThreshold: 3, // 更灵敏的触摸阈值
forceFallback: true, // 始终使用 fallback 以获得一致的动画效果
fallbackClass: 'sortable-drag',
fallbackTolerance: 2,
easing: "cubic-bezier(0.2, 0.8, 0.2, 1)",
scroll: true, // 启用自动滚动
scrollSensitivity: 80, // 滚动灵敏度
scrollSpeed: 20, // 滚动速度
bubbleScroll: true, // 允许父容器滚动
onStart: function (evt) {
// 添加视觉反馈 - 丝滑启动
const item = evt.item;
item.style.transition = 'none';
item.setAttribute('aria-grabbed', 'true');
fieldsList.classList.add('is-reordering');
document.body.style.cursor = 'grabbing';
// 拖动时弱化其余卡片,由 Sortable 负责位置过渡。
const siblings = Array.from(fieldsList.children).filter(c => c !== item);
gsap.to(siblings, {
opacity: 0.88,
duration: 0.18,
ease: "power2.out"
});
},
onEnd: function (evt) {
const item = evt.item;
const siblings = Array.from(fieldsList.children).filter(c => c !== item);
// 恢复样式 - 丝滑结束动画
item.style.transition = '';
item.removeAttribute('aria-grabbed');
fieldsList.classList.remove('is-reordering');
document.body.style.cursor = '';
// 其余卡片恢复原状。
gsap.to(siblings, {
opacity: 1,
duration: 0.2,
ease: "power2.out"
});
if (evt.oldIndex !== evt.newIndex) {
updateFieldNumbers();
updateFieldCount();
announceFieldOrder(item, evt.newIndex, true);
}
}
});
if (!fieldsList.dataset.paletteDropBound) {
fieldsList.dataset.paletteDropBound = 'true';
fieldsList.addEventListener('dragover', (event) => {
if (!event.dataTransfer || !Array.from(event.dataTransfer.types).includes('application/x-field-type')) return;
event.preventDefault();
event.dataTransfer.dropEffect = 'copy';
fieldsList.classList.add('palette-drop-active');
});
fieldsList.addEventListener('dragleave', (event) => {
if (!fieldsList.contains(event.relatedTarget)) fieldsList.classList.remove('palette-drop-active');
});
fieldsList.addEventListener('drop', (event) => {
const type = event.dataTransfer?.getData('application/x-field-type');
if (!type) return;
event.preventDefault();
fieldsList.classList.remove('palette-drop-active');
const target = event.target.closest('.field-card');
const beforeId = target && event.clientY < target.getBoundingClientRect().top + target.offsetHeight / 2
? target.id
: target?.nextElementSibling?.id;
const id = addField({ type, beforeId });
updateFieldBadge();
if (id) document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
});
}
}
function updateFieldNumbers() {
const cards = document.querySelectorAll('#fieldsList > .field-card');
let fieldNumber = 0;
let pageNumber = 1;
cards.forEach((card, orderIndex) => {
const controls = card.querySelectorAll('.field-order-button');
if (controls.length === 2) {
controls[0].disabled = orderIndex === 0;
controls[1].disabled = orderIndex === cards.length - 1;
controls[0].setAttribute('aria-label', `将第 ${orderIndex + 1} 项上移`);
controls[1].setAttribute('aria-label', `将第 ${orderIndex + 1} 项下移`);
}
if (card.classList.contains('page-break-card')) {
pageNumber++;
card.querySelector('.page-break-number').textContent = `第 ${pageNumber} 页从这里开始`;
return;
}
fieldNumber++;
const numberEl = card.querySelector('.field-number');
if (numberEl) {
numberEl.textContent = `字段 #${fieldNumber}`;
}
});
}
function addFieldOrderControls(card) {
const actions = card.querySelector('.field-card-actions');
if (!actions || actions.querySelector('.field-order-controls')) return;
const controls = document.createElement('div');
controls.className = 'field-order-controls';
controls.innerHTML = `
<button type="button" class="field-order-button" data-order-direction="-1" title="上移" aria-label="上移">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m18 15-6-6-6 6"/></svg>
</button>
<button type="button" class="field-order-button" data-order-direction="1" title="下移" aria-label="下移">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m6 9 6 6 6-6"/></svg>
</button>`;
controls.querySelectorAll('button').forEach(button => {
button.addEventListener('click', () => moveField(card.id, Number(button.dataset.orderDirection)));
});
actions.prepend(controls);
}
function announceFieldOrder(card, index, showFeedback = false) {
const label = card.querySelector('.field-name')?.value.trim()
|| card.querySelector('.page-title')?.value.trim()
|| card.querySelector('.page-break-number')?.textContent.trim()
|| '题目';
const status = document.getElementById('fieldOrderStatus');
if (status) status.textContent = `已将“${label}”移至第 ${index + 1} 项`;
if (showFeedback) showToast('排序已更新', 'success');
}
function moveField(fieldId, direction) {
const list = document.getElementById('fieldsList');
const card = document.getElementById(fieldId);
if (!list || !card || card.parentElement !== list) return;
const cards = Array.from(list.children).filter(item => item.classList.contains('field-card'));
const from = cards.indexOf(card);
const to = from + direction;
if (from < 0 || to < 0 || to >= cards.length) return;
const positions = new Map(cards.map(item => [item, item.getBoundingClientRect().top]));
const target = cards[to];
if (direction < 0) list.insertBefore(card, target);
else list.insertBefore(card, target.nextElementSibling);
updateFieldNumbers();
announceFieldOrder(card, to);
if (!window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
Array.from(list.children).forEach(item => {
const previousTop = positions.get(item);
if (previousTop == null || typeof item.animate !== 'function') return;
const delta = previousTop - item.getBoundingClientRect().top;
if (Math.abs(delta) < 1) return;
item.animate([
{ transform: `translateY(${delta}px)` },
{ transform: 'translateY(0)' }
], { duration: 260, easing: 'cubic-bezier(.2,.8,.2,1)' });
});
}
}
function updateFieldCount() {
const questions = document.querySelectorAll('#fieldsList .field-card:not(.page-break-card)').length;
const pages = document.querySelectorAll('#fieldsList .page-break-card').length + 1;
document.getElementById('fieldCount').textContent = `${questions} 个题目${pages > 1 ? ` · ${pages} 页` : ''}`;
const emptyState = document.getElementById('emptyFieldsState');
if (emptyState) emptyState.classList.toggle('hidden', questions > 0);
}
function toggleAdvancedSettings() {
const settings = document.getElementById('advancedSettings');
const arrow = document.getElementById('advancedArrow');
settings.classList.toggle('open');
arrow.style.transform = settings.classList.contains('open') ? 'rotate(180deg)' : 'rotate(0)';
}
// Load Presets
async function loadPresets() {
const container = document.getElementById('presetsList');
container.innerHTML = '<div class="text-center py-4 text-sm" style="color: var(--text-muted);">加载中...</div>';
try {
const response = await fetch('/api/presets');
const presets = await response.json();
if (presets.length === 0) {
container.innerHTML = `
<div class="text-center py-4">
<p class="text-sm mb-2" style="color: var(--text-muted);">暂无预设</p>
<a href="/preset_manage" target="_blank" class="text-sm" style="color: var(--info-text);">去创建预设 →</a>
</div>
`;
return;
}
// Check for presetId in URL
const urlParams = new URLSearchParams(window.location.search);
const urlPresetId = urlParams.get('presetId');
container.innerHTML = presets.map(p => `
<button type="button" class="preset-option w-full text-left ${p.id === urlPresetId || p.id === selectedPresetId ? 'selected' : ''}"
onclick="selectPreset('${p.id}')" data-preset-id="${p.id}" aria-pressed="false">
<span class="flex justify-between items-center gap-2">
<span class="flex min-w-0 items-center gap-2">
<span class="font-medium text-sm shrink-0" style="color: var(--text-primary);">${p.name}</span>
<span class="text-xs truncate" style="color: var(--text-muted);">${p.totalStudents}人 · 使用${p.usageCount}次</span>
</span>
${p.id === urlPresetId || p.id === selectedPresetId ? `
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="color: var(--info-text);">
<polyline points="20 6 9 17 4 12"></polyline>
</svg>
` : ''}
</span>
</button>
`).join('');
// Auto-select if URL has presetId
if (urlPresetId) {
selectedPresetId = urlPresetId;
}
updatePresetSelectionUI();
} catch (error) {
container.innerHTML = `<div class="text-center py-4 text-sm" style="color: var(--error-text);">加载失败</div>`;
}
}
function selectPreset(presetId) {
// '__anon__' 表示匿名收集(selectedPresetId 置空);重复点击名单预设则取消选择回到匿名
selectedPresetId = presetId === '__anon__' ? '' :
(selectedPresetId === presetId ? '' : presetId);
updatePresetSelectionUI();
onPresetModeChange();
}
const PRESET_CHECK_SVG = `
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="color: var(--info-text);">
<polyline points="20 6 9 17 4 12"></polyline>
</svg>`;
// 依据 selectedPresetId 同步所有选择卡片(匿名卡 + 名单卡)的选中态
function updatePresetSelectionUI() {
document.querySelectorAll('#presetSelection .preset-option').forEach(el => {
const id = el.dataset.presetId;
const isSelected = selectedPresetId ? id === selectedPresetId : id === '__anon__';
el.classList.toggle('selected', isSelected);
el.setAttribute('aria-pressed', String(isSelected));
const icon = el.querySelector('svg');
if (icon) icon.remove();
if (isSelected) {
const flex = el.querySelector('.flex');
if (flex) flex.innerHTML += PRESET_CHECK_SVG;
}
});
}
// 匿名模式切换:隐藏名单专属设置(学号验证位数、覆盖验证)
function onPresetModeChange() {
const anonymous = !selectedPresetId;
document.getElementById('verifyDigitsBlock').classList.toggle('hidden', anonymous);
syncRosterOnlyPanels();
}
// 覆盖验证块可见性:仅「名单模式 且 允许覆盖提交」时展示
function syncRosterOnlyPanels() {
const anonymous = !selectedPresetId;
const once = getDuplicatePolicy() === 'once';
document.getElementById('overwriteVerifyBlock').classList.toggle('hidden', anonymous || once);
}
function setDuplicatePolicy(policy) {
document.getElementById('policyOverwriteCard').classList.toggle('selected', policy !== 'once');
document.getElementById('policyOnceCard').classList.toggle('selected', policy === 'once');
document.getElementById('policyOverwriteCard').setAttribute('aria-pressed', String(policy !== 'once'));
document.getElementById('policyOnceCard').setAttribute('aria-pressed', String(policy === 'once'));
syncRosterOnlyPanels();
}
function getDuplicatePolicy() {
return document.getElementById('policyOnceCard').classList.contains('selected') ? 'once' : 'overwrite';
}
function addField(options = {}) {
const fieldId = 'field_' + (++fieldCount);
const type = options.type || 'text';
if (type === 'page_break') {
const card = FormComponents.createPageBreakCard(fieldId, options.title, () => removeField(fieldId));
addFieldOrderControls(card);
const list = document.getElementById('fieldsList');
list.appendChild(card);
const anchor = options.beforeId && document.getElementById(options.beforeId);
if (anchor && anchor.parentNode === list) list.insertBefore(card, anchor);
gsap.fromTo(card, { opacity: 0, y: 12 }, { opacity: 1, y: 0, duration: 0.3, ease: 'power3.out' });
updateFieldCount();
updateFieldNumbers();
updateFieldBadge();
return fieldId;
}
const fieldDiv = document.createElement('div');
fieldDiv.className = 'field-card';
fieldDiv.id = fieldId;
// Set initial state for animation
fieldDiv.style.opacity = '0';
fieldDiv.style.transform = 'translateY(16px) scale(0.985)';
fieldDiv.style.maxHeight = '0';
fieldDiv.style.marginBottom = '0';
fieldDiv.style.paddingTop = '0';
fieldDiv.style.paddingBottom = '0';
fieldDiv.style.transition = 'none';
const typeInfo = fieldTypes[type] || fieldTypes['text'];
// Build extra fields based on type
let extraFields = '';
if (type === 'file') {
extraFields = getFileFieldHTML(options.allowedExts);
} else if (['text', 'textarea'].includes(type)) {
extraFields = getTextValidationFieldHTML(options.validationPreset, options.validationPattern);
} else if (type === 'number') {
extraFields = getNumberFieldHTML(options.allowDecimal);
} else if (['select', 'radio', 'checkbox'].includes(type)) {
extraFields = getOptionsFieldHTML(type, options.options, options.optionLayout);
} else if (type === 'rating') {
extraFields = getRatingFieldHTML(options.ratingMax);
} else if (type === 'slider') {
extraFields = getSliderFieldHTML(options);
}
// 获取所有字段列表(用于条件显示的触发字段选择)
const allFields = [];
document.querySelectorAll('.field-card').forEach(card => {
const nameInput = card.querySelector('.field-name');
const typeSelect = card.querySelector('.field-type');
if (nameInput && typeSelect) {
allFields.push({
name: nameInput.value,
type: typeSelect.value
});
}
});
// 也包含当前正在添加的字段
if (options.name && options.type) {
allFields.push({
name: options.name,
type: options.type
});
}
// 添加条件显示配置
const conditionalConfig = getConditionalConfigHTML(options.showWhen, allFields);
fieldDiv.innerHTML = `
<div class="flex items-center justify-between gap-3 mb-3">
<div class="flex items-center gap-2">
<button type="button" class="drag-handle" title="拖拽排序" aria-label="拖动以调整题目顺序">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="9" cy="12" r="1"></circle>
<circle cx="9" cy="5" r="1"></circle>
<circle cx="9" cy="19" r="1"></circle>
<circle cx="15" cy="12" r="1"></circle>
<circle cx="15" cy="5" r="1"></circle>
<circle cx="15" cy="19" r="1"></circle>
</svg>
</button>
<span class="field-number text-[10px] font-semibold tracking-[0.2em] uppercase theme-transition" style="color: var(--text-muted);">
字段 #${fieldCount}
</span>
<span class="text-xs px-2 py-1 rounded-full" style="background: var(--bg-primary); color: var(--text-secondary);">
${typeInfo.label}
</span>
</div>
<div class="field-card-actions flex items-center justify-end gap-2">
<button type="button" onclick="removeField('${fieldId}')"
class="btn-danger w-7 h-7 rounded-full flex items-center justify-center text-xs transition-transform hover:scale-110">
×
</button>
</div>
</div>
<div class="space-y-3">
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
<input type="text" placeholder="字段名称(如:上传文件)"
class="field-edit-input field-name"
value="${options.name || ''}">
${type === 'textarea' ? `
<textarea placeholder="提示文字(可选,支持多行)" rows="1"
class="field-edit-input field-placeholder resize-none">${options.placeholder || ''}</textarea>
` : `
<input type="text" placeholder="提示文字(可选)"
class="field-edit-input field-placeholder"
value="${options.placeholder || ''}">
`}
</div>
${extraFields}
<input type="hidden" class="field-show-when-field" value="${options.showWhen?.field || ''}">
<input type="hidden" class="field-show-when-values" value="${options.showWhen?.values?.join(',') || ''}">
<input type="hidden" class="field-show-when-action" value="${options.showWhen?.action || 'show'}">
<input type="hidden" class="field-show-when-match-mode" value="${options.showWhen?.matchMode || 'exact'}">
${options.showWhen?.field ? `
<button type="button" onclick="openConditionalModal('${fieldId}')"
class="field-condition-button rounded-lg flex items-center justify-center gap-2 text-xs transition-all hover:scale-[1.02]"
style="background: var(--info-bg); color: var(--info-text); border: 1px solid var(--info-text);">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="3"></circle>
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
</svg>
<span>当 ${options.showWhen.field} = ${options.showWhen.values?.join(', ') || ''} 时${options.showWhen.action === 'show' ? '显示' : '隐藏'}</span>
</button>
` : `
<button type="button" onclick="openConditionalModal('${fieldId}')"
class="field-condition-button rounded-lg flex items-center justify-center gap-2 text-xs transition-all hover:scale-[1.02]"
style="background: var(--bg-primary); color: var(--text-muted); border: 1px solid var(--border-color);">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="3"></circle>
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
</svg>
<span>条件显示</span>
</button>
`}
<label class="flex items-center gap-3 cursor-pointer group">
<input type="checkbox" class="checkbox-custom field-required" ${options.required !== false ? 'checked' : ''}>
<span class="text-sm theme-transition group-hover:text-[var(--text-primary)]" style="color: var(--text-secondary);">
必填字段
</span>
</label>
</div>
<input type="hidden" class="field-type" value="${type}">
`;
addFieldOrderControls(fieldDiv);
fieldDiv.dataset.showWhenField = options.showWhen?.field || '';
fieldDiv.dataset.showWhenValues = options.showWhen?.values?.join(',') || '';
fieldDiv.dataset.showWhenAction = options.showWhen?.action || 'show';
fieldDiv.dataset.showWhenMatchMode = options.showWhen?.matchMode || 'exact';
document.getElementById('fieldsList').appendChild(fieldDiv);
// 拖落指定位置:插到锚点字段之前
if (options.beforeId) {
const anchor = document.getElementById(options.beforeId);
const list = document.getElementById('fieldsList');
if (anchor && anchor.parentNode === list) list.insertBefore(fieldDiv, anchor);
}
// Initialize options if provided
if (['select', 'radio', 'checkbox'].includes(type) && options.options) {
const opts = options.options.split(',').map(o => o.trim()).filter(o => o);
const container = fieldDiv.querySelector('.options-list');
const firstInput = container.querySelector('.option-input');
if (opts.length > 0) {
firstInput.value = opts[0];
firstInput.nextElementSibling.classList.remove('opacity-0', 'pointer-events-none');
for (let i = 1; i < opts.length; i++) {
addOptionToContainer(container, opts[i]);
}
}
updateOptionsInput(container);
}
// Initialize file presets if provided
if (type === 'file' && options.allowedExts) {
initializeFilePresets(fieldDiv, options.allowedExts);
}
// 题目卡片展开时保持短促、稳定的位移反馈。
gsap.to(fieldDiv, {
opacity: 1,
y: 0,
scale: 1,
maxHeight: '500px',
marginBottom: '10px',
paddingTop: '16px',
paddingBottom: '16px',
duration: 0.32,
ease: "power3.out",
onComplete: () => {
fieldDiv.style.maxHeight = '';
fieldDiv.style.paddingTop = '';
fieldDiv.style.paddingBottom = '';
fieldDiv.style.transform = '';
}
});
updateFieldCount();
updateFieldNumbers();
return fieldDiv.id;
}
function removeField(fieldId) {
const el = document.getElementById(fieldId);
if (!el) return;
// 先禁用 CSS transition,避免与 GSAP 冲突
el.style.transition = 'none';
// 获取当前高度用于动画
const currentHeight = el.offsetHeight;
el.style.maxHeight = currentHeight + 'px';
// 收起卡片后再更新字段序号。
gsap.to(el, {
opacity: 0,
scale: 0.985,
maxHeight: 0,
marginBottom: 0,
paddingTop: 0,
paddingBottom: 0,
duration: 0.24,
ease: "power2.inOut",
onComplete: () => {
el.remove();
updateFieldCount();
updateFieldNumbers();
updateFieldBadge();
}
});
}
function mountSettingsPane() {
const target = document.getElementById('settingsPaneBody');
const basic = document.getElementById('basicSettingsPanel');
const toggle = document.getElementById('advancedTogglePanel');
const advanced = document.getElementById('advancedSettings');
if (!target || !basic || !toggle || !advanced) return;
basic.classList.remove('mt-6', 'pt-6', 'border-t');
basic.style.borderColor = '';
toggle.classList.remove('stagger-item');
advanced.classList.remove('mb-10');
target.append(basic, toggle, advanced);
}
/* ---- 窄屏三标签 ---- */
function showMobilePane(pane) {
const container = document.getElementById('builderContainer');
container.classList.remove('palette-mode', 'editor-mode', 'settings-mode');
container.classList.add(`${pane}-mode`);
syncMobileTabs();
}
function syncMobileTabs() {
const container = document.getElementById('builderContainer');
for (const [id, mode] of [['tabPalette', 'palette'], ['tabEditor', 'editor'], ['tabSettings', 'settings']]) {
const button = document.getElementById(id);
const active = container.classList.contains(`${mode}-mode`);
button.classList.toggle('active', active);
button.setAttribute('aria-pressed', String(active));
}
}
function updateFieldBadge() {
const badge = document.getElementById('tabEditorCount');
if (!badge) return;
const n = document.querySelectorAll('#fieldsList .field-card:not(.page-break-card)').length;
badge.textContent = n;
badge.classList.toggle('hidden', n === 0);
}
function toggleValidation() {
const panel = document.getElementById('validationPanel');
if (panel) panel.classList.toggle('hidden', !document.getElementById('enableValidation').checked);
}
function fillDocxSampleValidation() {
const ta = document.getElementById('validationScript');
ta.value = DOCX_SAMPLE_SCRIPT;
}
const DOCX_SAMPLE_SCRIPT = `async (values) => {
// 仅匹配格式:是否《综测页面》docx.html 生成的规范文档(含“加分明细”主表)
const file = Object.values(values || {}).find(v => v instanceof File && String(v.name || '').toLowerCase().endsWith('.docx'));
if (!file) return { ok: true }; // 未选 .docx,交给字段必填规则
const MSG = '请使用表单说明中的综测文档生成器进行文档生成后再填写';
// 懒加载 JSZip
const loadJSZip = () => new Promise((resolve, reject) => {
if (window.JSZip) return resolve(window.JSZip);
const urls = ['https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js', 'https://unpkg.com/jszip@3.10.1/dist/jszip.min.js', 'https://cdn.staticfile.net/jszip/3.10.1/jszip.min.js'];
let i = 0;
const next = () => { if (i >= urls.length) return reject(new Error('jszip load failed')); const s = document.createElement('script'); s.src = urls[i++]; s.onload = () => window.JSZip ? resolve(window.JSZip) : next(); s.onerror = next; document.head.appendChild(s); };
next();
});
try {
const JSZip = await loadJSZip();
const zip = await JSZip.loadAsync(file); // 非 zip 会抛错 → 格式不匹配
const entry = zip.file('word/document.xml');
const body = entry ? (await entry.async('string')).replace(/<[^>]+>/g, '') : '';
if (!body.includes('加分明细')) return { ok: false, msg: MSG };
return { ok: true };
} catch (e) {
return { ok: false, msg: MSG };
}
}`;
function saveForm() {
const webhook = FormWebhookSettings.read();
const title = document.getElementById('formTitle').value.trim();
if (!title) {
showToast('请输入表单标题', 'error');
document.getElementById('formTitle').focus();
return;
}
// 预设可选:未选 = 匿名收集模式;名单模式由服务端按 presetId 区分
// Check if at least one field exists
// 可见题目卡的 DOM 顺序就是保存顺序,Sortable 会同步更新它。
const fieldItems = document.querySelectorAll('#fieldsList .field-card');
if (![...fieldItems].some(item => !item.classList.contains('page-break-card'))) {
showToast('请至少创建一个题目', 'error');
const addFieldSection = document.getElementById('componentPalette');
if (addFieldSection) {
addFieldSection.scrollIntoView({ behavior: 'smooth', block: 'center' });
addFieldSection.style.border = '2px solid var(--error-text)';
addFieldSection.style.borderRadius = '12px';
addFieldSection.style.padding = '8px';
setTimeout(() => {
addFieldSection.style.border = '';
addFieldSection.style.padding = '';
}, 3000);
}
return;
}
const maxSizeInput = document.getElementById('maxSize');
const maxSize = Number(maxSizeInput.value);
if (!Number.isInteger(maxSize) || maxSize < 1 || maxSize > 10240) {
showToast('附件大小限制请输入 1 到 10240 MB 的整数', 'error');
maxSizeInput.focus();
return;
}
const verifyDigits = parseInt(document.getElementById('verifyDigits').value);
const showProgress = document.getElementById('showProgress').checked;
// 过期时间
const enableExpiry = document.getElementById('enableExpiry').checked;
const expiryDateVal = document.getElementById('expiryDate').value;
let expiresAt = null;
if (enableExpiry && expiryDateVal) {
expiresAt = new Date(expiryDateVal).toISOString();
}
const fields = [];
const fieldNames = new Set();
let pageHasQuestion = false;
for (let item of fieldItems) {
const type = item.querySelector('.field-type').value;
if (type === 'page_break') {
if (!pageHasQuestion) {
showToast('分页控件前需要至少一个题目,且不能连续分页', 'error');
item.scrollIntoView({ behavior: 'smooth', block: 'center' });
return;
}
fields.push({ type: 'page_break', title: item.querySelector('.page-title').value.trim(), required: false });
pageHasQuestion = false;
continue;
}
pageHasQuestion = true;
const name = item.querySelector('.field-name').value.trim();
const placeholder = item.querySelector('.field-placeholder').value.trim();
const required = item.querySelector('.field-required').checked;
const options = item.querySelector('.field-options-input')?.value.trim() || '';
const optionLayout = item.querySelector('.field-option-layout')?.value || 'wrap';
// Get file extensions from combined hidden input
const fileExtsCombined = item.querySelector('.field-file-exts-combined')?.value.trim() || '';
if (!name) {
showToast('请完善字段信息(名称为必填)', 'error');
item.querySelector('.field-name')?.focus();
item.scrollIntoView({ behavior: 'smooth', block: 'center' });
item.style.borderColor = 'var(--error-text)';
setTimeout(() => {
item.style.borderColor = '';
}, 2000);
return;
}
if (fieldNames.has(name)) {
showToast(`题目名称“${name}”重复,请使用不同名称`, 'error');
item.querySelector('.field-name')?.focus();
return;
}
fieldNames.add(name);
const fieldData = { name, type, placeholder, required, options, optionLayout };
if (['text', 'textarea'].includes(type)) {
fieldData.validationPreset = item.querySelector('.field-validation-preset')?.value || 'none';
fieldData.validationPattern = item.querySelector('.field-validation-pattern')?.value.trim() || '';
}
if (type === 'number') {
fieldData.allowDecimal = item.querySelector('.field-number-decimal')?.checked === true;
}
if (type === 'file' && fileExtsCombined) {
fieldData.allowedExts = fileExtsCombined.split(',').map(e => e.trim()).filter(e => e);
}
if (type === 'rating') {
fieldData.ratingMax = item.querySelector('.field-rating-max')?.value || '5';
}
if (type === 'slider') {
fieldData.sliderMin = item.querySelector('.field-slider-min')?.value || '0';
fieldData.sliderMax = item.querySelector('.field-slider-max')?.value || '100';
fieldData.sliderStep = item.querySelector('.field-slider-step')?.value || '1';
}
// 读取条件显示配置
const showWhenField = item.dataset.showWhenField || item.querySelector('.field-show-when-field')?.value;
const showWhenValues = item.dataset.showWhenValues || item.querySelector('.field-show-when-values')?.value;
const showWhenAction = item.dataset.showWhenAction || item.querySelector('.field-show-when-action')?.value;
const showWhenMatchMode = item.dataset.showWhenMatchMode || item.querySelector('.field-show-when-match-mode')?.value;
if (showWhenField && (showWhenValues || ['empty', 'not_empty'].includes(showWhenMatchMode))) {
fieldData.showWhen = {
field: showWhenField,
values: (showWhenValues || '').split(',').map(v => v.trim()).filter(v => v),
action: showWhenAction || 'show',
matchMode: showWhenMatchMode || 'exact'
};
}
fields.push(fieldData);
}
if (!pageHasQuestion) {
showToast('最后一页需要至少一个题目', 'error');
return;
}
// 构建覆盖验证配置(匿名模式无名单可比对,不启用)
const enableOverwriteVerify = document.getElementById('enableOverwriteVerify').checked;
let overwriteVerify = { enabled: false };
if (enableOverwriteVerify && selectedPresetId) {
const verifyField = document.getElementById('verifyField').value;
const verifyDigitsCount = document.getElementById('verifyDigitsCount').value;
const verifyLabel = document.getElementById('verifyLabel').value || '身份证';
const customFieldName = document.getElementById('customFieldName').value;
overwriteVerify = {
enabled: true,
field: verifyField,
digits: parseInt(verifyDigitsCount),
label: verifyLabel,
customFieldName: verifyField === 'custom' ? customFieldName : ''
};
}
const formData = {
title,
collectType: 'info',
maxSize: maxSize * 1024 * 1024,
fields,
presetId: selectedPresetId,
duplicatePolicy: getDuplicatePolicy(),
verifyDigits,
showProgress,
expiresAt,
overwriteVerify,
webhook,
announcement: {
subtitle: document.getElementById('announcementSubtitle').value.trim(),
text: document.getElementById('announcementText').value.trim()
},
validation: {
enabled: document.getElementById('enableValidation').checked,
failToast: document.getElementById('validationFailToast').value.trim(),
script: document.getElementById('validationScript').value
}
};
const btn = document.getElementById('saveBtn');
const originalText = btn.textContent;
btn.disabled = true;
btn.innerHTML = '<span class="flex items-center justify-center gap-2">创建中<svg class="animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg></span>';
fetch('/api/save_form', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(formData)
})
.then(r => r.json())
.then(data => {
btn.disabled = false;
btn.textContent = originalText;
if (data.success) {
currentFormId = data.formId;
uploadAnnouncementFiles().then(() => {
showSuccessModal();
showToast('表单创建成功', 'success');
}).catch(() => {
showSuccessModal();
showToast('表单已创建,但部分附件上传失败', 'error');
});
} else {
showToast(`创建失败:${data.message}`, 'error');
}
})
.catch(e => {
btn.disabled = false;
btn.textContent = originalText;
showToast(`网络错误:${e.message}`, 'error');
});
}
// ========== 公告附件 ==========
function addAnnouncementFileInput() {
if (pendingAnnouncementFiles.length >= 3) {
showToast('最多只能添加 3 个附件', 'error');
return;
}
pendingAnnouncementFiles.push(null);
renderAnnouncementFiles();
}
function onAnnouncementFileSelect(index, input) {
if (!input.files || !input.files[0]) {
pendingAnnouncementFiles[index] = null;
renderAnnouncementFiles();
return;
}
pendingAnnouncementFiles[index] = input.files[0];
renderAnnouncementFiles();
}
function removeAnnouncementFile(index) {
pendingAnnouncementFiles.splice(index, 1);
renderAnnouncementFiles();
}
function renderAnnouncementFiles() {
const list = document.getElementById('announcementFilesList');
const count = document.getElementById('announcementFileCount');
const addBtn = document.getElementById('addAnnouncementFileBtn');
list.innerHTML = '';
count.textContent = `${pendingAnnouncementFiles.length} / 3`;
pendingAnnouncementFiles.forEach((file, index) => {
const div = document.createElement('div');
div.className = 'flex items-center gap-3 p-3 rounded-xl';
div.style.cssText = 'background: var(--bg-primary); border: 1px solid var(--border-color);';
if (file) {
const sizeMB = (file.size / (1024 * 1024)).toFixed(2);
div.innerHTML = `
<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="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
</svg>
<div class="flex-1 min-w-0">
<p class="text-sm truncate" style="color: var(--text-primary);">${file.name}</p>
<p class="text-xs" style="color: var(--text-muted);">${sizeMB} MB</p>
</div>
<button type="button" onclick="removeAnnouncementFile(${index})"
class="text-xs px-2 py-1 rounded hover:bg-red-50 dark:hover:bg-red-900/30"
style="color: var(--error-text);">移除</button>
`;
} else {
div.innerHTML = `
<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="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
<polyline points="14 2 14 8 20 8"></polyline>
</svg>
<input type="file" class="flex-1 min-w-0 text-sm" style="color: var(--text-secondary);"
onchange="onAnnouncementFileSelect(${index}, this)">
`;
}
list.appendChild(div);
});
addBtn.style.display = pendingAnnouncementFiles.length >= 3 ? 'none' : '';
}
function uploadAnnouncementFiles() {
const files = pendingAnnouncementFiles.filter(f => f !== null);
if (files.length === 0 || !currentFormId) return Promise.resolve();
const tasks = files.map(file => {
const fd = new FormData();
fd.append('file', file);
return fetch(`/api/form/${currentFormId}/announcement_upload`, {
method: 'POST',
body: fd
}).then(r => r.json()).then(d => {
if (!d.success) throw new Error(d.message || '上传失败');
return d;
});
});
return Promise.all(tasks);
}
function showSuccessModal() {
const formUrl = `${window.location.origin}/${currentFormId}`;
const statusUrl = `${window.location.origin}/status?formId=${currentFormId}`;
document.getElementById('formLink').value = formUrl;
document.getElementById('statusLink').value = statusUrl;
document.getElementById('successModal').style.display = 'flex';
requestAnimationFrame(() => {
document.getElementById('successModal').classList.add('show');
});
}
function closeSuccessModal() {
document.getElementById('successModal').classList.remove('show');
setTimeout(() => {
document.getElementById('successModal').style.display = 'none';
}, 300);
}
function goToForm() {
window.location.href = `/${currentFormId}`;
}
function copyLink(inputId) {
const input = document.getElementById(inputId);
input.select();
input.setSelectionRange(0, 99999);
try {
document.execCommand('copy');
input.classList.add('copied');
showToast('链接已复制到剪贴板', 'success');
setTimeout(() => {
input.classList.remove('copied');
}, 2000);
} catch (err) {
showToast('复制失败,请手动复制', 'error');
}
}
// Initial Animation
window.addEventListener('load', () => {
mountSettingsPane();
gsap.fromTo("#headerSection", { opacity: 0, y: 16 }, {
opacity: 1,
y: 0,
duration: 0.75,
ease: "power3.out",
delay: 0.1
});
gsap.fromTo(".stagger-item", { opacity: 0, y: 12 }, {
opacity: 1,
y: 0,
duration: 0.58,
stagger: 0.07,
ease: "power3.out",
delay: 0.3
});
initSortable();
// Load presets
loadPresets();
// 左侧组件库:点击添加;拖拽时由字段列表按落点插入。
if (window.FormComponents) {
FormComponents.renderPalette(document.getElementById('componentPalette'), (type) => {
const id = addField({ type: type });
if (id) document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
updateFieldBadge();
if (window.matchMedia('(max-width: 1279px)').matches) showMobilePane('editor');
});
}
// 初始态:默认匿名收集(不选预设)+ 默认允许覆盖提交,并同步名单专属设置可见性
updatePresetSelectionUI();
onPresetModeChange();
setDuplicatePolicy('overwrite');
if (window.matchMedia('(max-width: 1279px)').matches) showMobilePane('editor');
syncMobileTabs();
});
// Toggle Expiry Config
document.getElementById('enableExpiry').addEventListener('change', function() {
const panel = document.getElementById('expiryConfig');
if (this.checked) {
panel.classList.remove('hidden');
// 默认填入 7 天后
if (!document.getElementById('expiryDate').value) {
const d = new Date();
d.setDate(d.getDate() + 7);
d.setHours(23, 59, 0, 0);
document.getElementById('expiryDate').value = d.toISOString().slice(0, 16);
}
} else {
panel.classList.add('hidden');
}
});
// Toggle Verify Config Panel
function toggleVerifyConfig() {
const enabled = document.getElementById('enableOverwriteVerify').checked;
const panel = document.getElementById('verifyConfigPanel');
if (enabled) {
panel.classList.remove('hidden');
updateVerifyConfig();
} else {
panel.classList.add('hidden');
}
}
// Update Verify Config based on field selection
function updateVerifyConfig() {
const field = document.getElementById('verifyField').value;
const customPanel = document.getElementById('customFieldPanel');
const labelInput = document.getElementById('verifyLabel');
// 显示/隐藏自定义字段输入
if (field === 'custom') {
customPanel.classList.remove('hidden');
} else {
customPanel.classList.add('hidden');
}
// 自动更新标签
const labels = {
'idCard': '身份证',
'phone': '手机号',
'custom': '验证信息'
};
if (labelInput.value === '' || Object.values(labels).includes(labelInput.value)) {
labelInput.value = labels[field] || '验证信息';
}
}
// Helper functions for field types
function getTextValidationFieldHTML(preset = 'none', pattern = '') {
const safePattern = String(pattern).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return `
<div class="field-text-validation space-y-2">
<label class="text-xs block" style="color: var(--text-muted);">文本校验</label>
<select class="field-validation-preset w-full bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)] focus:outline-none focus:border-[var(--border-focus)] theme-transition" onchange="toggleTextValidation(this)">
<option value="none" ${preset === 'none' ? 'selected' : ''}>不校验</option>
<option value="phone" ${preset === 'phone' ? 'selected' : ''}>手机号</option>
<option value="qq" ${preset === 'qq' ? 'selected' : ''}>QQ 号</option>
<option value="idCard" ${preset === 'idCard' ? 'selected' : ''}>身份证号</option>
<option value="name" ${preset === 'name' ? 'selected' : ''}>姓名</option>
<option value="email" ${preset === 'email' ? 'selected' : ''}>邮箱</option>
<option value="custom" ${preset === 'custom' ? 'selected' : ''}>自定义正则表达式</option>
</select>
<div class="field-validation-pattern-wrap ${preset === 'custom' ? '' : 'hidden'}">
<input type="text" class="field-validation-pattern w-full bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)] focus:outline-none focus:border-[var(--border-focus)] theme-transition" value="${safePattern}" placeholder="例如:^[A-Z]{2}\\d{6}$">
</div>
</div>
`;
}
function toggleTextValidation(select) {
select.closest('.field-text-validation')?.querySelector('.field-validation-pattern-wrap')?.classList.toggle('hidden', select.value !== 'custom');
}
function getNumberFieldHTML(allowDecimal = false) {
return `
<label class="field-number-config flex items-center gap-2 text-sm cursor-pointer" style="color: var(--text-secondary);">
<input type="checkbox" class="checkbox-custom field-number-decimal" ${allowDecimal ? 'checked' : ''}>
<span>允许输入小数</span>
</label>
`;
}
function getFileFieldHTML(allowedExts) {
return `
<div class="field-file-exts space-y-3">
<div>
<label class="text-xs block mb-2" style="color: var(--text-muted);">文件类型预设</label>
<div class="flex flex-wrap gap-2">
<button type="button" onclick="toggleFilePreset(this, 'image')" class="file-preset-btn px-3 py-1.5 rounded-lg text-xs border transition-all" data-type="image" style="border-color: var(--border-color); color: var(--text-secondary);">
📷 图片
</button>
<button type="button" onclick="toggleFilePreset(this, 'video')" class="file-preset-btn px-3 py-1.5 rounded-lg text-xs border transition-all" data-type="video" style="border-color: var(--border-color); color: var(--text-secondary);">
🎬 视频
</button>
<button type="button" onclick="toggleFilePreset(this, 'ppt')" class="file-preset-btn px-3 py-1.5 rounded-lg text-xs border transition-all" data-type="ppt" style="border-color: var(--border-color); color: var(--text-secondary);">
📊 PPT
</button>
<button type="button" onclick="toggleFilePreset(this, 'excel')" class="file-preset-btn px-3 py-1.5 rounded-lg text-xs border transition-all" data-type="excel" style="border-color: var(--border-color); color: var(--text-secondary);">
📈 Excel
</button>
<button type="button" onclick="toggleFilePreset(this, 'word')" class="file-preset-btn px-3 py-1.5 rounded-lg text-xs border transition-all" data-type="word" style="border-color: var(--border-color); color: var(--text-secondary);">
📝 Word
</button>
<button type="button" onclick="toggleFilePreset(this, 'pdf')" class="file-preset-btn px-3 py-1.5 rounded-lg text-xs border transition-all" data-type="pdf" style="border-color: var(--border-color); color: var(--text-secondary);">
📄 PDF
</button>
<button type="button" onclick="toggleFilePreset(this, 'audio')" class="file-preset-btn px-3 py-1.5 rounded-lg text-xs border transition-all" data-type="audio" style="border-color: var(--border-color); color: var(--text-secondary);">
🎵 音频
</button>
<button type="button" onclick="toggleFilePreset(this, 'code')" class="file-preset-btn px-3 py-1.5 rounded-lg text-xs border transition-all" data-type="code" style="border-color: var(--border-color); color: var(--text-secondary);">
💻 代码
</button>
<button type="button" onclick="toggleFilePreset(this, 'custom')" class="file-preset-btn px-3 py-1.5 rounded-lg text-xs border transition-all" data-type="custom" style="border-color: var(--border-color); color: var(--text-secondary);">
✏️ 自定义格式
</button>
</div>
</div>
<div class="custom-exts-panel hidden space-y-2">
<label class="text-xs block" style="color: var(--text-muted);">输入自定义格式(以英文逗号分隔)</label>
<input type="text" placeholder="例如:zip, rar, 7z, psd"
class="field-file-exts-input w-full bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)] focus:outline-none focus:border-[var(--border-focus)] theme-transition"
oninput="updateFileExtsFromInput(this)">
</div>
<input type="hidden" class="field-file-exts-combined" value="">
</div>
`;
}
function getOptionsFieldHTML(type, options, optionLayout = 'wrap') {
return `
<div class="field-options space-y-2">
<div class="flex items-center justify-between gap-3">
<label class="text-xs" style="color: var(--text-muted);">选项列表</label>
${['radio', 'checkbox'].includes(type) ? `<select class="field-option-layout bg-transparent text-xs rounded-lg border px-2 py-1" style="border-color: var(--border-color); color: var(--text-secondary);"><option value="wrap" ${optionLayout !== 'column' ? 'selected' : ''}>单行排列</option><option value="column" ${optionLayout === 'column' ? 'selected' : ''}>多行排列</option></select>` : ''}
</div>
<div class="options-list space-y-2">
<div class="option-item flex justify-end">
<input type="text" placeholder="输入选项"
class="option-input flex-1 bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)] focus:outline-none focus:border-[var(--border-focus)] theme-transition"
onkeydown="handleOptionKeydown(event, this)"
oninput="updateOptionsInput(this.closest('.options-list'))">
<button onclick="removeOption(this)" class="btn-danger w-8 h-8 rounded-lg flex items-center justify-center text-xs opacity-0 pointer-events-none">
×
</button>
</div>
</div>
<button onclick="addOption(this)" class="btn btn-secondary py-2 px-4 rounded-lg text-xs font-medium flex items-center gap-1 mt-2">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<line x1="12" y1="5" x2="12" y2="19"></line>
<line x1="5" y1="12" x2="19" y2="12"></line>
</svg>
添加选项
</button>
<input type="hidden" class="field-options-input" value="${options || ''}">
</div>
`;
}
function getRatingFieldHTML(ratingMax) {
const maxVal = Number(ratingMax) === 10 ? '10' : '5';
return `
<div class="field-rating-config flex items-center gap-4">
<label class="text-sm" style="color: var(--text-muted);">最大分值:</label>
<select class="field-rating-max bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)]">
<option value="5" ${maxVal === '5' ? 'selected' : ''}>5分</option>
<option value="10" ${maxVal === '10' ? 'selected' : ''}>10分</option>
</select>
</div>
`;
}
function getSliderFieldHTML(options) {
return `
<div class="field-slider-config">
<div class="grid grid-cols-3 gap-2">
<label class="text-xs space-y-1" style="color: var(--text-muted);">最小值
<input type="number" value="${options.sliderMin || '0'}" class="field-slider-min w-full bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)] focus:outline-none focus:border-[var(--border-focus)]">
</label>
<label class="text-xs space-y-1" style="color: var(--text-muted);">最大值
<input type="number" value="${options.sliderMax || '100'}" class="field-slider-max w-full bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)] focus:outline-none focus:border-[var(--border-focus)]">
</label>
<label class="text-xs space-y-1" style="color: var(--text-muted);">每次变化
<input type="number" min="0.01" step="any" value="${options.sliderStep || '1'}" class="field-slider-step w-full bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)] focus:outline-none focus:border-[var(--border-focus)]">
</label>
</div>
</div>
`;
}
// 获取条件显示配置的HTML(现在通过模态框设置,这里返回空)
function getConditionalConfigHTML(showWhen, allFields) {
return '';
}
// 条件显示模态框相关函数
let currentEditingFieldId = null;
function openConditionalModal(fieldId) {
currentEditingFieldId = fieldId;
const fieldCard = document.getElementById(fieldId);
if (!fieldCard) return;
// 获取当前条件配置
const currentField = fieldCard.querySelector('.field-show-when-field')?.value || '';
const currentValues = fieldCard.querySelector('.field-show-when-values')?.value || '';
const currentAction = fieldCard.querySelector('.field-show-when-action')?.value || 'show';
const currentMatchMode = fieldCard.querySelector('.field-show-when-match-mode')?.value || 'exact';
// 获取所有可作为触发字段的列表
const allFields = [];
document.querySelectorAll('.field-card').forEach(card => {
const fid = card.id;
const nameInput = card.querySelector('.field-name');
const typeSelect = card.querySelector('.field-type');
const fieldNum = card.querySelector('.field-number');
if (nameInput && typeSelect && fid !== currentEditingFieldId) {
const fieldType = typeSelect.value;
if (['radio', 'checkbox', 'select'].includes(fieldType)) {
// 从隐藏输入框获取选项,如果没有则从 options-list 获取
let optionsInput = card.querySelector('.field-options-input');
let options = optionsInput?.value || '';
// 如果隐藏输入框为空,尝试从 options-list 获取
if (!options) {
const optionInputs = card.querySelectorAll('.option-input');
options = Array.from(optionInputs).map(input => input.value.trim()).filter(v => v).join(',');
}
// 即使字段名为空,只要有选项就可以作为触发字段
const fieldName = nameInput.value || '未命名字段';
const fieldNumText = fieldNum?.textContent || '';
allFields.push({
id: fid,
name: fieldName,
type: fieldType,
number: fieldNumText.replace('字段 #', ''),
options: options
});
}
}
});
// 填充触发字段选择
const triggerSelect = document.getElementById('conditionalTriggerField');
triggerSelect.innerHTML = '<option value="">-- 选择触发字段 --</option>' +
allFields.map(f => `<option value="${f.name}" data-options="${f.options}" data-type="${f.type}" ${currentField === f.name ? 'selected' : ''}>${f.number}. ${f.name} (${f.type === 'radio' ? '单选' : f.type === 'checkbox' ? '多选' : '下拉'})</option>`).join('');
// 填充触发值选择
updateConditionalFieldOptions();
// 设置当前值
setTimeout(() => {
const valueSelect = document.getElementById('conditionalTriggerValue');
if (currentValues) {
const values = currentValues.split(',');
Array.from(valueSelect.options).forEach(opt => {
if (values.includes(opt.value)) {
opt.selected = true;
}
});
}
document.getElementById('conditionalAction').value = currentAction;
document.getElementById('conditionalMatchMode').value = currentMatchMode;
}, 100);
// 显示模态框
document.getElementById('conditionalModal').style.display = 'flex';
setTimeout(() => {
document.getElementById('conditionalModal').classList.add('show');
}, 10);
}
function updateConditionalFieldOptions() {
const triggerSelect = document.getElementById('conditionalTriggerField');
const valueSelect = document.getElementById('conditionalTriggerValue');
const selectedOption = triggerSelect.options[triggerSelect.selectedIndex];
const matchModeSelect = document.getElementById('conditionalMatchMode');
valueSelect.innerHTML = '';
if (selectedOption && selectedOption.value) {
const fieldType = selectedOption.dataset.type;
const optionsStr = selectedOption.dataset.options || '';
const options = optionsStr.split(',').map(o => o.trim()).filter(o => o);
valueSelect.innerHTML = options.map(o => `<option value="${o}">${o}</option>`).join('');
// 匹配模式始终显示,但对非多选字段隐藏选择框(用包含模式默认值)
if (fieldType !== 'checkbox') {
matchModeSelect.closest('div').style.display = 'none';
matchModeSelect.value = 'contains';
} else {
matchModeSelect.closest('div').style.display = '';
}
}
}
function closeConditionalModal() {
document.getElementById('conditionalModal').classList.remove('show');
setTimeout(() => {
document.getElementById('conditionalModal').style.display = 'none';
}, 300);
currentEditingFieldId = null;
}
function saveConditionalConfig() {
if (!currentEditingFieldId) return;
const field = document.getElementById('conditionalTriggerField').value;
const valueSelect = document.getElementById('conditionalTriggerValue');
const selectedValues = Array.from(valueSelect.selectedOptions).map(opt => opt.value);
let matchMode = document.getElementById('conditionalMatchMode').value;
const action = document.getElementById('conditionalAction').value;
// 获取触发字段类型,单选/下拉框使用包含模式
const triggerSelect = document.getElementById('conditionalTriggerField');
const selectedOption = triggerSelect.options[triggerSelect.selectedIndex];
const fieldType = selectedOption?.dataset.type;
if (fieldType !== 'checkbox') {
matchMode = 'contains';
}
const fieldCard = document.getElementById(currentEditingFieldId);
if (!fieldCard) return;
fieldCard.querySelector('.field-show-when-field').value = field;
fieldCard.querySelector('.field-show-when-values').value = selectedValues.join(',');
fieldCard.querySelector('.field-show-when-action').value = action;
fieldCard.querySelector('.field-show-when-match-mode').value = matchMode;
// 更新按钮显示状态
const btn = fieldCard.querySelector('button[onclick^="openConditionalModal"]');
if (btn) {
if (field && selectedValues.length > 0) {
btn.style.background = 'var(--info-bg)';
btn.style.color = 'var(--info-text)';
btn.style.borderColor = 'var(--info-text)';
btn.querySelector('span').textContent = `当 ${field} = ${selectedValues.join(', ')} 时${action === 'show' ? '显示' : '隐藏'}`;
} else {
btn.style.background = 'var(--bg-primary)';
btn.style.color = 'var(--text-muted)';
btn.style.borderColor = 'var(--border-color)';
btn.querySelector('span').textContent = '条件显示';
}
}
// 显示提示
showToast('条件显示设置已保存', 'success');
closeConditionalModal();
}
// 升级版条件联动:所有题型都可作为触发字段。
function openConditionalModal(fieldId) {
currentEditingFieldId = fieldId;
const fieldCard = document.getElementById(fieldId);
if (!fieldCard) return;
const currentField = fieldCard.dataset.showWhenField || fieldCard.querySelector('.field-show-when-field')?.value || '';
const currentValues = fieldCard.dataset.showWhenValues || fieldCard.querySelector('.field-show-when-values')?.value || '';
const currentAction = fieldCard.dataset.showWhenAction || fieldCard.querySelector('.field-show-when-action')?.value || 'show';
const currentMatchMode = fieldCard.dataset.showWhenMatchMode || fieldCard.querySelector('.field-show-when-match-mode')?.value || 'exact';
const typeLabels = { text:'文本', textarea:'多行文本', number:'数字', select:'下拉', radio:'单选', checkbox:'多选', date:'日期', time:'时间', rating:'评分', slider:'滑块', file:'文件' };
const fields = Array.from(document.querySelectorAll('.field-card')).filter(card => card.id !== fieldId && !card.classList.contains('page-break-card')).map(card => {
const type = card.querySelector('.field-type')?.value || 'text';
const name = card.querySelector('.field-name')?.value || '未命名字段';
const number = (card.querySelector('.field-number')?.textContent || '').replace('字段 #', '');
const options = Array.from(card.querySelectorAll('.option-input')).map(input => input.value.trim()).filter(Boolean).join(',');
return { name, type, number, options };
});
const esc = value => String(value).replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
const trigger = document.getElementById('conditionalTriggerField');
trigger.innerHTML = '<option value="">-- 选择触发字段 --</option>' + fields.map(f =>
`<option value="${esc(f.name)}" data-options="${esc(f.options)}" data-type="${f.type}" ${currentField === f.name ? 'selected' : ''}>${f.number}. ${esc(f.name)} (${typeLabels[f.type] || f.type})</option>`
).join('');
updateConditionalFieldOptions();
const choice = ['radio','checkbox','select'].includes(trigger.options[trigger.selectedIndex]?.dataset.type);
if (choice) {
const values = currentValues.split(',').filter(Boolean);
Array.from(document.getElementById('conditionalTriggerValue').options).forEach(opt => opt.selected = values.includes(opt.value));
} else {
document.getElementById('conditionalTriggerInput').value = currentValues;
}
document.getElementById('conditionalAction').value = currentAction;
document.getElementById('conditionalMatchMode').value = currentMatchMode;
document.getElementById('conditionalModal').style.display = 'flex';
requestAnimationFrame(() => document.getElementById('conditionalModal').classList.add('show'));
}
function updateConditionalFieldOptions() {
const trigger = document.getElementById('conditionalTriggerField');
const selected = trigger.options[trigger.selectedIndex];
const type = selected?.dataset.type || '';
const choice = ['radio','checkbox','select'].includes(type);
const values = document.getElementById('conditionalTriggerValue');
const input = document.getElementById('conditionalTriggerInput');
const hint = document.getElementById('conditionalValueHint');
const mode = document.getElementById('conditionalMatchMode');
values.classList.toggle('hidden', !choice);
input.classList.toggle('hidden', choice);
hint.classList.toggle('hidden', !choice);
if (choice) {
values.innerHTML = (selected?.dataset.options || '').split(',').map(v => v.trim()).filter(Boolean).map(v => `<option value="${v.replace(/"/g,'&quot;')}">${v}</option>`).join('');
mode.value = type === 'checkbox' ? 'loose' : 'contains';
} else {
input.type = ['number','rating','slider'].includes(type) ? 'number' : type === 'date' ? 'date' : type === 'time' ? 'time' : 'text';
input.placeholder = type === 'file' ? '文件类型使用“已填写 / 未填写”' : '输入匹配值';
if (!['empty','not_empty','not_equals','greater','greater_equal','less','less_equal'].includes(mode.value)) mode.value = 'exact';
}
}
function saveConditionalConfig() {
if (!currentEditingFieldId) return;
const trigger = document.getElementById('conditionalTriggerField');
const selected = trigger.options[trigger.selectedIndex];
const type = selected?.dataset.type || '';
const choice = ['radio','checkbox','select'].includes(type);
const values = choice
? Array.from(document.getElementById('conditionalTriggerValue').selectedOptions).map(opt => opt.value)
: [document.getElementById('conditionalTriggerInput').value.trim()].filter(Boolean);
const mode = document.getElementById('conditionalMatchMode').value;
const action = document.getElementById('conditionalAction').value;
const card = document.getElementById(currentEditingFieldId);
card.querySelector('.field-show-when-field').value = trigger.value;
card.querySelector('.field-show-when-values').value = values.join(',');
card.querySelector('.field-show-when-action').value = action;
card.querySelector('.field-show-when-match-mode').value = mode;
card.querySelector('.field-show-when-field').setAttribute('value', trigger.value);
card.querySelector('.field-show-when-values').setAttribute('value', values.join(','));
card.querySelector('.field-show-when-action').setAttribute('value', action);
card.querySelector('.field-show-when-match-mode').setAttribute('value', mode);
card.dataset.showWhenField = trigger.value;
card.dataset.showWhenValues = values.join(',');
card.dataset.showWhenAction = action;
card.dataset.showWhenMatchMode = mode;
const button = card.querySelector('.field-condition-button');
const active = trigger.value && (values.length || ['empty','not_empty'].includes(mode));
button.style.background = active ? 'var(--info-bg)' : 'var(--bg-primary)';
button.style.color = active ? 'var(--info-text)' : 'var(--text-muted)';
button.style.borderColor = active ? 'var(--info-text)' : 'var(--border-color)';
button.querySelector('span').textContent = active ? `当 ${trigger.value} 联动` : '条件显示';
showToast('条件显示设置已保存', 'success');
closeConditionalModal();
}
// File preset functions
const filePresets = {
'image': ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'],
'video': ['mp4', 'mov', 'avi', 'mkv', 'flv', 'wmv', 'webm'],
'ppt': ['ppt', 'pptx', 'pps', 'ppsx'],
'excel': ['xls', 'xlsx', 'csv', 'xlsm'],
'word': ['doc', 'docx', 'rtf'],
'pdf': ['pdf'],
'audio': ['mp3', 'wav', 'flac', 'aac', 'ogg', 'm4a', 'wma'],
'code': ['js', 'py', 'html', 'css', 'java', 'cpp', 'c', 'php', 'rb', 'go', 'ts', 'json', 'xml'],
'custom': []
};
function toggleFilePreset(btn, type) {
btn.classList.toggle('selected');
const isSelected = btn.classList.contains('selected');
const container = btn.closest('.field-file-exts');
if (isSelected) {
btn.style.backgroundColor = 'var(--info-bg)';
btn.style.borderColor = 'var(--info-text)';
btn.style.color = 'var(--info-text)';
} else {
btn.style.backgroundColor = '';
btn.style.borderColor = 'var(--border-color)';
btn.style.color = 'var(--text-secondary)';
}
// Handle custom type panel visibility
if (type === 'custom') {
const customPanel = container.querySelector('.custom-exts-panel');
if (isSelected) {
customPanel.classList.remove('hidden');
customPanel.querySelector('input').focus();
} else {
customPanel.classList.add('hidden');
customPanel.querySelector('input').value = '';
}
}
updateFileExtsCombined(container);
}
function updateFileExtsFromInput(input) {
updateFileExtsCombined(input.closest('.field-file-exts'));
}
function updateFileExtsCombined(container) {
const selectedTypes = container.querySelectorAll('.file-preset-btn.selected');
const customInput = container.querySelector('.field-file-exts-input');
let allExts = [];
selectedTypes.forEach(btn => {
const type = btn.dataset.type;
if (type !== 'custom' && filePresets[type]) {
allExts = allExts.concat(filePresets[type]);
}
});
// Add custom extensions if custom is selected
const customBtn = container.querySelector('[data-type="custom"]');
if (customBtn && customBtn.classList.contains('selected') && customInput && customInput.value.trim()) {
const customExts = customInput.value.split(',').map(e => e.trim()).filter(e => e);
allExts = allExts.concat(customExts);
}
// Remove duplicates
allExts = [...new Set(allExts)];
container.querySelector('.field-file-exts-combined').value = allExts.join(',');
}
function initializeFilePresets(fieldDiv, allowedExts) {
if (!allowedExts) return;
// Handle both array and string formats
let exts = [];
if (Array.isArray(allowedExts)) {
exts = allowedExts.map(e => e.trim()).filter(e => e);
} else if (typeof allowedExts === 'string') {
exts = allowedExts.split(',').map(e => e.trim()).filter(e => e);
} else {
return;
}
const container = fieldDiv.querySelector('.field-file-exts');
if (!container) return;
const customExts = [];
exts.forEach(ext => {
let found = false;
for (const [type, presetExts] of Object.entries(filePresets)) {
if (type !== 'custom' && presetExts.includes(ext.toLowerCase())) {
const btn = container.querySelector(`[data-type="${type}"]`);
if (btn && !btn.classList.contains('selected')) {
toggleFilePreset(btn, type);
}
found = true;
break;
}
}
if (!found) {
customExts.push(ext);
}
});
// If there are custom extensions, select custom type and fill input
if (customExts.length > 0) {
const customBtn = container.querySelector('[data-type="custom"]');
if (customBtn && !customBtn.classList.contains('selected')) {
toggleFilePreset(customBtn, 'custom');
}
const customInput = container.querySelector('.field-file-exts-input');
if (customInput) {
customInput.value = customExts.join(', ');
updateFileExtsCombined(container);
}
}
}
// Options functions
function handleOptionKeydown(event, input) {
if (event.key === 'Enter') {
event.preventDefault();
const container = input.closest('.options-list');
addOptionToContainer(container);
}
}
function addOption(btn) {
const container = btn.previousElementSibling;
addOptionToContainer(container);
}
function addOptionToContainer(container, value = '') {
const item = document.createElement('div');
item.className = 'option-item flex justify-end';
item.innerHTML = `
<input type="text" placeholder="输入选项" value="${value}"
class="option-input flex-1 bg-[var(--bg-primary)] rounded-lg px-3 py-2 text-sm border border-[var(--border-color)] focus:outline-none focus:border-[var(--border-focus)] theme-transition"
onkeydown="handleOptionKeydown(event, this)"
oninput="updateOptionsInput(this.closest('.options-list'))">
<button onclick="removeOption(this)" class="btn-danger w-8 h-8 rounded-lg flex items-center justify-center text-xs">
×
</button>
`;
container.appendChild(item);
// Enable delete button on first item if there are multiple items
const allItems = container.querySelectorAll('.option-item');
if (allItems.length > 1) {
allItems.forEach(item => {
const deleteBtn = item.querySelector('button');
deleteBtn.classList.remove('opacity-0', 'pointer-events-none');
});
}
item.querySelector('input').focus();
updateOptionsInput(container);
}
function removeOption(btn) {
const item = btn.closest('.option-item');
const container = item.closest('.options-list');
item.remove();
// Disable delete button on first item if only one left
const allItems = container.querySelectorAll('.option-item');
if (allItems.length === 1) {
const deleteBtn = allItems[0].querySelector('button');
deleteBtn.classList.add('opacity-0', 'pointer-events-none');
}
updateOptionsInput(container);
}
function updateOptionsInput(container) {
const inputs = container.querySelectorAll('.option-input');
const values = [];
inputs.forEach(input => {
if (input.value.trim()) {
values.push(input.value.trim());
}
});
const hiddenInput = container.closest('.field-options').querySelector('.field-options-input');
if (hiddenInput) {
hiddenInput.value = values.join(',');
}
}
</script>
</body>
</html>