710 lines
34 KiB
JavaScript
710 lines
34 KiB
JavaScript
/**
|
||
* FormPreview v4 — 画布即编辑器(create/edit 右栏)
|
||
*
|
||
* 预览即真实填写页,且可直接在画布上编辑:
|
||
* - 字段标题:点击直接改(同步到字段配置)
|
||
* - 占位符:直接往输入框里打字,失焦后转为占位符
|
||
* - 选项(单选/多选/下拉):就地增删改
|
||
* - 字段工具条(悬停/选中出现):必填开关、条件显示、删除;左上角手柄拖拽排序
|
||
* - 评分满分 / 滑块范围 / 文件格式:字段下方就地数值配置
|
||
*
|
||
* 数据仍存放在页面隐藏的 .field-card 编辑卡中(saveForm/populateForm 不变),
|
||
* 画布与卡片双向同步;顺序以画布为权威(orderedFieldCards)。
|
||
*
|
||
* 用法:
|
||
* FormPreview.init({
|
||
* root, getMeta,
|
||
* hooks: {
|
||
* onDelete: (fieldId) => {}, // 画布删除字段
|
||
* onCreateAt: (type, beforeId) => newId, // 调色板拖落创建,返回新卡 id
|
||
* onConditional: (fieldId) => {}, // 打开条件显示配置
|
||
* },
|
||
* });
|
||
* FormPreview.refresh(); / setSelected(id|null); / orderedFieldCards();
|
||
*/
|
||
(function () {
|
||
'use strict';
|
||
|
||
if (window.FormPreview) return;
|
||
|
||
let root = null;
|
||
let getMeta = null;
|
||
let hooks = null;
|
||
let editable = false;
|
||
let selectedId = null;
|
||
let fieldOrder = null; // 画布权威字段顺序(id 数组)
|
||
let debounceTimer = null;
|
||
let dropLine = null;
|
||
|
||
function esc(s) {
|
||
return String(s == null ? '' : s)
|
||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||
.replace(/"/g, '"').replace(/'/g, ''');
|
||
}
|
||
|
||
/* ---------- 数据层:隐藏 field-card ↔ 画布 ---------- */
|
||
|
||
function rawFields() {
|
||
const fields = [];
|
||
document.querySelectorAll('.field-card').forEach(card => {
|
||
const nameEl = card.querySelector('.field-name');
|
||
const typeEl = card.querySelector('.field-type');
|
||
if (!nameEl || !typeEl) return;
|
||
const type = typeEl.value;
|
||
const field = {
|
||
id: card.id,
|
||
type: type,
|
||
name: nameEl.value.trim() || '未命名字段',
|
||
placeholder: (card.querySelector('.field-placeholder') || {}).value || '',
|
||
required: !!(card.querySelector('.field-required') || { checked: true }).checked,
|
||
conditional: !!(card.querySelector('.field-show-when-field') || { value: '' }).value,
|
||
};
|
||
|
||
if (['select', 'radio', 'checkbox'].includes(type)) {
|
||
let options = (card.querySelector('.field-options-input') || {}).value || '';
|
||
if (!options) {
|
||
const optionInputs = card.querySelectorAll('.option-input');
|
||
options = Array.from(optionInputs).map(i => i.value.trim()).filter(v => v).join(',');
|
||
}
|
||
field.options = options;
|
||
}
|
||
if (type === 'file') {
|
||
let exts = (card.querySelector('.field-file-exts-combined') || {}).value || '';
|
||
if (!exts) exts = (card.querySelector('.field-file-exts-input') || {}).value || '';
|
||
field.exts = String(exts).split(/[,,\s]+/).map(s => s.replace(/^\./, '').trim())
|
||
.filter(v => v && v !== '全部');
|
||
}
|
||
if (type === 'rating') {
|
||
const rm = card.querySelector('.field-rating-max');
|
||
field.ratingMax = Number(rm && rm.value) === 10 ? 10 : 5;
|
||
}
|
||
if (type === 'slider') {
|
||
const g = cls => (card.querySelector(cls) || {}).value;
|
||
field.sliderMin = g('.field-slider-min') || '0';
|
||
field.sliderMax = g('.field-slider-max') || '100';
|
||
field.sliderStep = g('.field-slider-step') || '1';
|
||
}
|
||
fields.push(field);
|
||
});
|
||
return fields;
|
||
}
|
||
|
||
function collectFields() {
|
||
const raw = rawFields();
|
||
if (!fieldOrder) return raw;
|
||
const byId = {};
|
||
raw.forEach(f => { byId[f.id] = f; });
|
||
const ordered = fieldOrder.map(id => byId[id]).filter(Boolean);
|
||
raw.forEach(f => { if (!fieldOrder.includes(f.id)) ordered.push(f); });
|
||
return ordered;
|
||
}
|
||
|
||
function reconcileOrder() {
|
||
const ids = rawFields().map(f => f.id);
|
||
if (!fieldOrder) { fieldOrder = ids.slice(); return; }
|
||
const kept = fieldOrder.filter(id => ids.includes(id));
|
||
ids.forEach(id => { if (!kept.includes(id)) kept.push(id); });
|
||
fieldOrder = kept;
|
||
}
|
||
|
||
function insertIntoOrder(id, beforeId) {
|
||
reconcileOrder();
|
||
fieldOrder = fieldOrder.filter(x => x !== id);
|
||
const idx = beforeId ? fieldOrder.indexOf(beforeId) : -1;
|
||
if (idx >= 0) fieldOrder.splice(idx, 0, id);
|
||
else fieldOrder.push(id);
|
||
}
|
||
|
||
/* 写回隐藏编辑卡 */
|
||
function writeCard(id, fn) {
|
||
const card = document.getElementById(id);
|
||
if (card) fn(card);
|
||
}
|
||
function setName(id, v) { writeCard(id, c => { c.querySelector('.field-name').value = v; }); }
|
||
function setPlaceholder(id, v) { writeCard(id, c => { const el = c.querySelector('.field-placeholder'); if (el) el.value = v; }); }
|
||
function setRequired(id, v) { writeCard(id, c => { const el = c.querySelector('.field-required'); if (el) el.checked = v; }); }
|
||
function setOptions(id, v) { writeCard(id, c => { const el = c.querySelector('.field-options-input'); if (el) el.value = v; }); }
|
||
function setExts(id, v) { writeCard(id, c => { const el = c.querySelector('.field-file-exts-combined'); if (el) el.value = v; }); }
|
||
|
||
/* ---------- 渲染层 ---------- */
|
||
|
||
const INPUT_CLS = 'w-full bg-transparent border-b py-3 text-sm';
|
||
|
||
function renderControl(field, meta) {
|
||
switch (field.type) {
|
||
case 'select': {
|
||
const opts = (field.options || '').split(',').map(o => o.trim()).filter(Boolean);
|
||
return `
|
||
<select disabled class="${INPUT_CLS} appearance-none" style="color: var(--text-primary); border-bottom: 1px solid var(--border-color);">
|
||
<option>请选择...</option>
|
||
${opts.map(o => `<option>${esc(o)}</option>`).join('')}
|
||
</select>
|
||
${optionsEditor(field)}`;
|
||
}
|
||
case 'textarea':
|
||
return `<textarea data-fp-ph rows="3" class="w-full border rounded-xl p-4 resize-none text-sm leading-relaxed" style="background: var(--input-bg, var(--bg-primary)); color: var(--text-primary); border-color: var(--border-color);" placeholder="${esc(field.placeholder || '点击输入占位提示...')}">${esc(field.__typed || '')}</textarea>`;
|
||
case 'radio':
|
||
case 'checkbox':
|
||
return optionsAsPreview(field);
|
||
case 'file': {
|
||
const exts = field.exts && field.exts.length ? field.exts.join(', ') : '';
|
||
const sizeHint = meta.maxSizeMB ? `单个不超过 ${meta.maxSizeMB}MB` : '';
|
||
return `<div class="border-2 border-dashed rounded-xl p-6 text-center" style="border-color: var(--border-color); pointer-events: none;">
|
||
<div class="mb-2" style="color: var(--text-muted);">
|
||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="mx-auto">
|
||
<path d="M12 16V4M12 4L8 8M12 4L16 8M4 17V18C4 19.1046 4.89543 20 6 20H18C19.1046 20 20 19.1046 20 18V17"/>
|
||
</svg>
|
||
</div>
|
||
<p class="text-xs" style="color: var(--text-secondary);">点击或拖拽上传文件</p>
|
||
<p class="text-[10px] mt-1" style="color: var(--text-muted);">支持格式: ${esc(exts || '所有文件')}${sizeHint ? ' · ' + esc(sizeHint) : ''}</p>
|
||
</div>
|
||
<div class="fp-config-row">
|
||
<span class="fp-config-lb">格式</span>
|
||
<input type="text" data-fp-exts class="fp-config-input" value="${esc(exts)}" placeholder="如 jpg, png, pdf(留空不限制)">
|
||
</div>`;
|
||
}
|
||
case 'rating': {
|
||
const max = Number(field.ratingMax) === 10 ? 10 : 5;
|
||
return `<div class="flex items-center gap-4 flex-wrap">
|
||
<div class="flex gap-1.5" style="pointer-events: none;">
|
||
${Array.from({ length: 5 }, () => `<svg width="26" height="26" viewBox="0 0 24 24" fill="none" style="color: var(--text-muted); opacity:.55;"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>`).join('')}
|
||
</div>
|
||
</div>
|
||
<div class="fp-config-row">
|
||
<span class="fp-config-lb">满分</span>
|
||
<select data-fp-rmax class="fp-config-input" style="max-width:100px;">
|
||
<option value="5" ${max === 5 ? 'selected' : ''}>5 分</option>
|
||
<option value="10" ${max === 10 ? 'selected' : ''}>10 分</option>
|
||
</select>
|
||
<span class="text-xs" style="color: var(--text-muted);">分(点星评分)</span>
|
||
</div>`;
|
||
}
|
||
case 'slider': {
|
||
const min = parseFloat(field.sliderMin) || 0;
|
||
const max = parseFloat(field.sliderMax) || 100;
|
||
const mid = (min + max) / 2;
|
||
const pct = (mid - min) / (max - min || 1) * 50;
|
||
return `<div class="flex items-center gap-4" style="pointer-events: none;">
|
||
<div class="flex-1 h-1.5 rounded-full relative" style="background: var(--border-color);">
|
||
<div class="absolute h-1.5 rounded-full left-0" style="width:${pct}%; background: var(--accent-bg, #6366f1);"></div>
|
||
<div class="absolute w-4 h-4 rounded-full -top-[5px] shadow" style="left:calc(${pct}% - 8px); background: var(--accent-bg, #6366f1);"></div>
|
||
</div>
|
||
</div>
|
||
<div class="fp-config-row">
|
||
<span class="fp-config-lb">范围</span>
|
||
<input type="number" data-fp-smin class="fp-config-input" style="max-width:76px;" value="${min}">
|
||
<span class="text-xs" style="color: var(--text-muted);">至</span>
|
||
<input type="number" data-fp-smax class="fp-config-input" style="max-width:76px;" value="${max}">
|
||
<span class="text-xs" style="color: var(--text-muted);">步长</span>
|
||
<input type="number" data-fp-sstep class="fp-config-input" style="max-width:76px;" value="${esc(field.sliderStep || '1')}">
|
||
</div>`;
|
||
}
|
||
case 'date':
|
||
return `<input type="date" disabled class="${INPUT_CLS}" style="color: var(--text-primary); border-bottom: 1px solid var(--border-color);">`;
|
||
case 'time':
|
||
return `<input type="time" disabled class="${INPUT_CLS}" style="color: var(--text-primary); border-bottom: 1px solid var(--border-color);">`;
|
||
default:
|
||
// 文本/数字:直接打字编辑占位符
|
||
return `<input type="text" data-fp-ph inputmode="${field.type === 'number' ? 'numeric' : 'text'}" class="${INPUT_CLS}" style="color: var(--text-primary); border-bottom: 1px solid var(--border-color);" placeholder="${esc(field.placeholder || '点击输入占位提示...')}">`;
|
||
}
|
||
}
|
||
|
||
/* 选项就地编辑:radio/checkbox 直接以选项预览形态呈现 */
|
||
function optionsAsPreview(field) {
|
||
const opts = (field.options || '').split(',').map(o => o.trim()).filter(Boolean);
|
||
const row = (o) => {
|
||
const mark = field.type === 'checkbox'
|
||
? `<span class="fp-opt-mark" style="border-radius:6px;"></span>`
|
||
: `<span class="fp-opt-mark" style="border-radius:50%;"></span>`;
|
||
return `<label class="inline-flex items-center gap-2.5 text-sm fp-opt" style="color: var(--text-primary); position:relative; padding:8px; margin:-8px; border-radius:8px;">
|
||
${mark}<span class="fp-opt-text" contenteditable="true" data-fp-opt>${esc(o)}</span>
|
||
<button type="button" class="fp-opt-del" data-fp-opt-del title="删除选项">
|
||
<svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.4" stroke-linecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
|
||
</button>
|
||
</label>`;
|
||
};
|
||
return `<div class="flex flex-wrap gap-3 mt-1" data-fp-opts>${opts.map(row).join('') || '<span class="text-xs" style="color: var(--text-muted);">暂无选项</span>'}
|
||
<button type="button" class="fp-opt-add" data-fp-opt-add>+ 选项</button>
|
||
</div>`;
|
||
}
|
||
|
||
/* 下拉的选项编辑行 */
|
||
function optionsEditor(field) {
|
||
const opts = (field.options || '').split(',').map(o => o.trim()).filter(Boolean);
|
||
return `<div class="flex flex-wrap gap-2 mt-3" data-fp-opts>
|
||
${opts.map(o => `<span class="fp-opt-chip">
|
||
<span class="fp-opt-text" contenteditable="true" data-fp-opt>${esc(o)}</span>
|
||
<button type="button" class="fp-opt-del" data-fp-opt-del title="删除选项">
|
||
<svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.4" stroke-linecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
|
||
</button>
|
||
</span>`).join('')}
|
||
<button type="button" class="fp-opt-add" data-fp-opt-add>+ 选项</button>
|
||
</div>`;
|
||
}
|
||
|
||
function renderField(field, meta, index) {
|
||
const onCanvas = editable && !!field.id;
|
||
let chrome = '';
|
||
if (onCanvas) {
|
||
chrome = `
|
||
<span class="fp-num">${index + 1}</span>
|
||
<span class="fp-handle" title="拖拽排序" draggable="true">
|
||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||
<circle cx="9" cy="5" r="1.6"/><circle cx="15" cy="5" r="1.6"/><circle cx="9" cy="12" r="1.6"/><circle cx="15" cy="12" r="1.6"/><circle cx="9" cy="19" r="1.6"/><circle cx="15" cy="19" r="1.6"/>
|
||
</svg>
|
||
</span>
|
||
<div class="fp-toolbar">
|
||
<button type="button" class="fp-chip ${field.required ? 'fp-chip-on' : ''}" data-fp-act="required" title="切换必填">✱ 必填</button>
|
||
<button type="button" class="fp-chip ${field.conditional ? 'fp-chip-on' : ''}" data-fp-act="conditional" title="条件显示">◇ 条件</button>
|
||
<button type="button" class="fp-chip fp-chip-danger" data-fp-act="delete" title="删除字段">✕</button>
|
||
</div>`;
|
||
}
|
||
const selCls = onCanvas && field.id === selectedId ? ' fp-selected' : '';
|
||
const optionalTag = (!field.required) ? ' <span class="fp-tag-optional">(选填)</span>' : '';
|
||
return `<div class="fp-field${selCls}" ${onCanvas ? `data-fp-id="${field.id}"` : ''}>
|
||
${chrome}
|
||
<div class="fp-label-line">
|
||
<label class="block text-[15px] font-semibold tracking-[0.12em] uppercase mb-2" style="color: var(--text-primary);">
|
||
<span class="fp-label-text" ${onCanvas ? 'contenteditable="true" data-fp-name' : ''}>${esc(field.name)}</span>${optionalTag}
|
||
</label>
|
||
</div>
|
||
<div class="fp-control">${renderControl(field, meta)}</div>
|
||
</div>`;
|
||
}
|
||
|
||
function renderProgress(meta) {
|
||
if (!meta.showProgress) return '';
|
||
const body = meta.anonymous
|
||
? `<p class="text-sm" style="color: var(--text-secondary);">已收集 <span style="color: var(--text-primary); font-weight:600;">0</span> 份提交</p>`
|
||
: `<p class="text-sm" style="color: var(--text-secondary);">等待大家提交…</p>`;
|
||
return `<div class="rounded-2xl p-4 mb-6" style="background: var(--bg-primary, transparent); border: 1px solid var(--border-color);">
|
||
<p class="text-[11px] font-semibold tracking-[0.2em] uppercase mb-2" style="color: var(--text-muted);">完成情况</p>
|
||
<div class="h-1.5 rounded-full overflow-hidden mb-2" style="background: var(--border-color);">
|
||
<div style="width:0%; height:100%; background: var(--accent-bg, #6366f1);"></div>
|
||
</div>
|
||
${body}
|
||
</div>`;
|
||
}
|
||
|
||
function render(meta) {
|
||
if (!root) return;
|
||
const fields = collectFields();
|
||
|
||
const rosterFields = [];
|
||
if (!meta.anonymous) {
|
||
const digits = meta.verifyDigits || '2';
|
||
rosterFields.push({ id: null, name: 'tail', type: 'number', required: true, placeholder: `学号后${digits}位` });
|
||
rosterFields.push({ id: null, name: 'name', type: 'text', required: true, placeholder: '请输入学号自动获取姓名' });
|
||
}
|
||
|
||
const onceHint = meta.once
|
||
? `<p class="text-xs text-center mb-3" style="color: var(--warning-text, #b45309);">⚠ 此表单仅允许提交一次,提交后不能再修改,请确认填写无误后再提交。</p>`
|
||
: '';
|
||
|
||
let fieldIndex = 0;
|
||
const fieldHtml = (list) => list.map(f => renderField(f, meta, f.id ? fieldIndex++ : 0)).join('');
|
||
|
||
root.innerHTML = `
|
||
<div class="fp-head px-7 pt-7 pb-5">
|
||
<h1 class="text-2xl font-bold tracking-wide" style="color: var(--text-primary);">${esc(meta.title || '未命名表单')}</h1>
|
||
<p class="text-xs mt-2" style="color: var(--text-muted);">请填写以下信息完成提交。所有字段经过加密处理。</p>
|
||
</div>
|
||
<div class="fp-body px-7 pb-8">
|
||
${(meta.subtitle || meta.announcementText) ? `
|
||
<div class="rounded-2xl p-4 mb-6" style="background: var(--bg-primary, transparent); border: 1px solid var(--border-color);">
|
||
${meta.subtitle ? `<p class="text-sm font-semibold mb-1" style="color: var(--text-primary);">${esc(meta.subtitle)}</p>` : ''}
|
||
${meta.announcementText ? `<p class="text-xs leading-relaxed whitespace-pre-wrap" style="color: var(--text-secondary);">${esc(meta.announcementText)}</p>` : ''}
|
||
</div>` : ''}
|
||
${renderProgress(meta)}
|
||
<div class="space-y-7 fp-fields">
|
||
${fieldHtml(rosterFields)}
|
||
${fieldHtml(fields)}
|
||
${fields.length === 0 && meta.anonymous ? '<p class="text-xs text-center py-6" style="color: var(--text-muted);">从左侧组件库添加字段,或直接把组件拖到这里</p>' : ''}
|
||
</div>
|
||
<div class="pt-8 fp-tail">
|
||
${onceHint}
|
||
<button type="button" disabled class="w-full py-4 px-8 rounded-full font-medium text-sm opacity-90" style="background: var(--accent-bg); color: var(--accent-text);">
|
||
提交表单
|
||
</button>
|
||
</div>
|
||
</div>
|
||
`;
|
||
|
||
if (editable) wireCanvas();
|
||
}
|
||
|
||
/* ---------- 画布交互 ---------- */
|
||
|
||
const CANVAS_CSS = `
|
||
.fp-field {
|
||
position: relative; border: 1px dashed transparent; border-radius: 14px;
|
||
padding: 14px 14px 10px; margin: -1px;
|
||
transition: border-color .15s ease, background-color .15s ease;
|
||
}
|
||
.fp-field:hover { border-color: var(--border-color); }
|
||
.fp-field.fp-selected {
|
||
border-color: var(--accent-bg, #6366f1);
|
||
background: color-mix(in srgb, var(--accent-bg, #6366f1) 6%, transparent);
|
||
}
|
||
.fp-field .fp-handle {
|
||
position: absolute; left: 8px; top: 50%; transform: translateY(-50%);
|
||
width: 32px; height: 32px; border-radius: 10px;
|
||
display: flex; align-items: center; justify-content: center;
|
||
background: var(--bg-primary, #fff); border: 1px solid var(--border-color);
|
||
color: var(--text-secondary); box-shadow: 0 2px 10px rgba(0,0,0,.14);
|
||
opacity: 0; cursor: grab; transition: opacity .15s ease, border-color .15s ease, color .15s ease;
|
||
z-index: 3;
|
||
}
|
||
.fp-handle svg { width: 18px; height: 18px; }
|
||
.fp-handle:hover { border-color: var(--accent-bg, #6366f1); color: var(--accent-bg, #6366f1); }
|
||
.fp-field:hover .fp-handle, .fp-field.fp-selected .fp-handle { opacity: 1; }
|
||
/* 手柄出现时内容右移让位,不遮标题 */
|
||
.fp-field { padding-left: 14px; }
|
||
.fp-field:hover, .fp-field.fp-selected { padding-left: 50px; }
|
||
.fp-field .fp-num {
|
||
position: absolute; right: 12px; top: 10px; font-size: 10px; font-weight: 600;
|
||
color: var(--text-muted); opacity: 0; transition: opacity .15s ease;
|
||
min-width: 18px; text-align: center;
|
||
}
|
||
.fp-field:hover .fp-num, .fp-field.fp-selected .fp-num { opacity: .7; }
|
||
.fp-field.fp-dragging { opacity: .45; }
|
||
|
||
.fp-toolbar {
|
||
position: absolute; right: 8px; top: -12px; display: flex; gap: 4px;
|
||
opacity: 0; transition: opacity .15s ease; z-index: 3;
|
||
}
|
||
.fp-field:hover .fp-toolbar, .fp-field.fp-selected .fp-toolbar { opacity: 1; }
|
||
.fp-chip {
|
||
font-size: 10px; padding: 3px 8px; border-radius: 999px; cursor: pointer;
|
||
border: 1px solid var(--border-color); background: var(--bg-primary, #fff);
|
||
color: var(--text-secondary); line-height: 1.2;
|
||
box-shadow: 0 1px 6px rgba(0,0,0,.08);
|
||
transition: all .15s ease;
|
||
}
|
||
.fp-chip:hover { border-color: var(--accent-bg, #6366f1); color: var(--accent-bg, #6366f1); }
|
||
.fp-chip-on { background: var(--accent-bg, #6366f1); border-color: var(--accent-bg, #6366f1); color: #fff; }
|
||
.fp-chip-danger:hover { border-color: #dc2626; color: #dc2626; }
|
||
|
||
.fp-label-text { outline: none; border-bottom: 1px dashed transparent; min-width: 30px; display: inline-block; }
|
||
.fp-field:hover .fp-label-text, .fp-field.fp-selected .fp-label-text { border-bottom-color: var(--border-color); }
|
||
.fp-label-text:focus { border-bottom-color: var(--accent-bg, #6366f1); }
|
||
.fp-label-text:empty::before { content: '未命名字段'; color: var(--text-muted); }
|
||
.fp-tag-optional { color: var(--text-muted); font-weight: 400; }
|
||
|
||
.fp-config-row { display: flex; align-items: center; gap: 8px; margin-top: 10px; }
|
||
.fp-config-lb { font-size: 11px; color: var(--text-muted); flex-shrink: 0; }
|
||
.fp-config-input {
|
||
font-size: 12px; padding: 4px 8px; border-radius: 8px; outline: none;
|
||
border: 1px solid var(--border-color); background: var(--input-bg, transparent);
|
||
color: var(--text-primary); width: 220px; max-width: 60%;
|
||
}
|
||
.fp-config-input:focus { border-color: var(--accent-bg, #6366f1); }
|
||
|
||
.fp-opt { position: relative; }
|
||
.fp-opt-mark { width: 22px; height: 22px; border: 2px solid var(--border-color); flex-shrink: 0;
|
||
display: inline-flex; align-items: center; justify-content: center; }
|
||
.fp-opt-text { outline: none; border-bottom: 1px dashed transparent; min-width: 16px; }
|
||
.fp-opt-text:focus { border-bottom-color: var(--accent-bg, #6366f1); }
|
||
.fp-opt .fp-opt-del {
|
||
position: absolute; right: -4px; top: -2px; width: 16px; height: 16px; border-radius: 50%;
|
||
background: rgba(220,38,38,.9); color: #fff; display: none;
|
||
align-items: center; justify-content: center; cursor: pointer;
|
||
}
|
||
.fp-opt:hover .fp-opt-del { display: flex; }
|
||
.fp-opt-chip {
|
||
display: inline-flex; align-items: center; gap: 5px; font-size: 12px;
|
||
padding: 4px 8px; border-radius: 999px; border: 1px solid var(--border-color);
|
||
color: var(--text-primary); position: relative;
|
||
}
|
||
.fp-opt-chip .fp-opt-del {
|
||
width: 14px; height: 14px; border-radius: 50%; background: rgba(220,38,38,.9);
|
||
color: #fff; display: none; align-items: center; justify-content: center; cursor: pointer;
|
||
}
|
||
.fp-opt-chip:hover .fp-opt-del { display: flex; }
|
||
.fp-opt-add {
|
||
align-self: center; font-size: 11px; padding: 4px 10px; border-radius: 999px; cursor: pointer;
|
||
border: 1px dashed var(--border-color); color: var(--text-muted); background: transparent;
|
||
transition: all .15s ease;
|
||
}
|
||
.fp-opt-add:hover { border-color: var(--accent-bg, #6366f1); color: var(--accent-bg, #6366f1); }
|
||
|
||
.fp-field.fp-drop-target { border-color: var(--accent-bg, #6366f1); }
|
||
.fp-drop-line {
|
||
height: 3px; border-radius: 3px; background: var(--accent-bg, #6366f1);
|
||
box-shadow: 0 0 10px color-mix(in srgb, var(--accent-bg, #6366f1) 60%, transparent);
|
||
margin: 6px 0; position: relative;
|
||
}
|
||
.fp-drop-line::before {
|
||
content: ''; position: absolute; left: -5px; top: -3.5px; width: 10px; height: 10px;
|
||
border-radius: 50%; background: var(--accent-bg, #6366f1);
|
||
}
|
||
`;
|
||
|
||
function wireCanvas() {
|
||
if (root.__fpWired) return;
|
||
root.__fpWired = true;
|
||
|
||
/* 点击:工具条动作 / 选中 / 空白取消 */
|
||
root.addEventListener('click', (e) => {
|
||
const act = e.target.closest('[data-fp-act]');
|
||
if (act) {
|
||
const fieldEl = act.closest('.fp-field[data-fp-id]');
|
||
const id = fieldEl && fieldEl.dataset.fpId;
|
||
const action = act.dataset.fpAct;
|
||
if (action === 'delete') {
|
||
if (selectedId === id) setSelected(null);
|
||
if (hooks.onDelete) hooks.onDelete(id);
|
||
return;
|
||
}
|
||
if (action === 'required') {
|
||
const card = document.getElementById(id);
|
||
const cb = card && card.querySelector('.field-required');
|
||
const next = cb ? !cb.checked : false;
|
||
setRequired(id, next);
|
||
act.classList.toggle('fp-chip-on', next);
|
||
const tag = fieldEl.querySelector('.fp-tag-optional');
|
||
if (tag) tag.style.display = next ? 'none' : '';
|
||
return;
|
||
}
|
||
if (action === 'conditional') {
|
||
if (hooks.onConditional) hooks.onConditional(id);
|
||
return;
|
||
}
|
||
}
|
||
if (e.target.closest('.fp-drawer, .fp-toolbar, .fp-config-row, [data-fp-opts], [contenteditable]')) return;
|
||
const fieldEl = e.target.closest('.fp-field[data-fp-id]');
|
||
if (fieldEl) {
|
||
setSelected(fieldEl.dataset.fpId);
|
||
if (hooks.onSelect) hooks.onSelect(fieldEl.dataset.fpId);
|
||
} else if (selectedId) {
|
||
setSelected(null);
|
||
if (hooks.onSelect) hooks.onSelect(null);
|
||
}
|
||
});
|
||
|
||
/* 输入:标题 / 占位符 / 选项 / 数值配置 → 写回隐藏编辑卡 */
|
||
root.addEventListener('input', (e) => {
|
||
const fieldEl = e.target.closest('.fp-field[data-fp-id]');
|
||
if (!fieldEl) return;
|
||
const id = fieldEl.dataset.fpId;
|
||
const t = e.target;
|
||
|
||
if (t.matches('[data-fp-name]')) {
|
||
setName(id, t.textContent.replace(/\n/g, ''));
|
||
} else if (t.matches('[data-fp-ph]')) {
|
||
setPlaceholder(id, t.value);
|
||
t.placeholder = t.value || '点击输入占位提示...';
|
||
} else if (t.matches('[data-fp-opt]')) {
|
||
syncOptions(fieldEl, id);
|
||
} else if (t.matches('[data-fp-exts]')) {
|
||
setExts(id, t.value);
|
||
const p = fieldEl.querySelector('.fp-control p.text-\\[10px\\]');
|
||
if (p) p.textContent = '支持格式: ' + (t.value.trim() || '所有文件');
|
||
} else if (t.matches('[data-fp-rmax]')) {
|
||
writeCard(id, c => { const el = c.querySelector('.field-rating-max'); if (el) el.value = t.value; });
|
||
} else if (t.matches('[data-fp-smin]')) {
|
||
writeCard(id, c => { const el = c.querySelector('.field-slider-min'); if (el) el.value = t.value; });
|
||
} else if (t.matches('[data-fp-smax]')) {
|
||
writeCard(id, c => { const el = c.querySelector('.field-slider-max'); if (el) el.value = t.value; });
|
||
} else if (t.matches('[data-fp-sstep]')) {
|
||
writeCard(id, c => { const el = c.querySelector('.field-slider-step'); if (el) el.value = t.value; });
|
||
}
|
||
});
|
||
|
||
/* 占位符失焦:把输入值转为占位符展示(预览即真实效果) */
|
||
root.addEventListener('focusout', (e) => {
|
||
if (e.target.matches && e.target.matches('[data-fp-ph]')) {
|
||
e.target.placeholder = e.target.value || '点击输入占位提示...';
|
||
e.target.value = '';
|
||
}
|
||
});
|
||
|
||
/* contenteditable 回车提交、粘贴纯文本 */
|
||
root.addEventListener('keydown', (e) => {
|
||
if (e.target.matches && (e.target.matches('[data-fp-name], [data-fp-opt]')) && e.key === 'Enter') {
|
||
e.preventDefault();
|
||
e.target.blur();
|
||
}
|
||
});
|
||
root.addEventListener('paste', (e) => {
|
||
const t = e.target;
|
||
if (t.matches && t.matches('[data-fp-name], [data-fp-opt]')) {
|
||
e.preventDefault();
|
||
const text = (e.clipboardData || window.clipboardData).getData('text').replace(/\n+/g, ' ');
|
||
document.execCommand('insertText', false, text);
|
||
}
|
||
});
|
||
|
||
/* 选项增删 */
|
||
root.addEventListener('click', (e) => {
|
||
const add = e.target.closest('[data-fp-opt-add]');
|
||
if (add) {
|
||
const box = add.closest('[data-fp-opts]');
|
||
const fieldEl = add.closest('.fp-field[data-fp-id]');
|
||
const chip = document.createElement('span');
|
||
chip.className = box.classList.contains('flex-wrap') && box.querySelector('.fp-opt-mark') ? 'inline-flex items-center gap-2.5 text-sm fp-opt' : 'fp-opt-chip';
|
||
if (box.querySelector('.fp-opt-mark')) {
|
||
const mark = document.createElement('span');
|
||
mark.className = 'fp-opt-mark';
|
||
mark.style.cssText = box.querySelector('.fp-opt-mark').style.cssText;
|
||
chip.appendChild(mark);
|
||
}
|
||
const txt = document.createElement('span');
|
||
txt.className = 'fp-opt-text';
|
||
txt.setAttribute('contenteditable', 'true');
|
||
txt.setAttribute('data-fp-opt', '');
|
||
chip.appendChild(txt);
|
||
chip.insertAdjacentHTML('beforeend', '<button type="button" class="fp-opt-del" data-fp-opt-del title="删除选项"><svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3.4" stroke-linecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg></button>');
|
||
box.insertBefore(chip, add);
|
||
txt.focus();
|
||
syncOptions(fieldEl, fieldEl.dataset.fpId);
|
||
return;
|
||
}
|
||
const del = e.target.closest('[data-fp-opt-del]');
|
||
if (del) {
|
||
e.stopPropagation();
|
||
const fieldEl = del.closest('.fp-field[data-fp-id]');
|
||
const chip = del.closest('.fp-opt, .fp-opt-chip');
|
||
if (chip) chip.remove();
|
||
if (fieldEl) syncOptions(fieldEl, fieldEl.dataset.fpId);
|
||
}
|
||
});
|
||
|
||
/* 拖拽:手柄拖动排序 + 调色板落位 */
|
||
root.addEventListener('dragstart', (e) => {
|
||
const handle = e.target.closest('.fp-handle');
|
||
if (!handle) { e.preventDefault(); return; }
|
||
const fieldEl = handle.closest('.fp-field[data-fp-id]');
|
||
if (!fieldEl) return;
|
||
e.dataTransfer.setData('application/x-fp-field', fieldEl.dataset.fpId);
|
||
e.dataTransfer.effectAllowed = 'move';
|
||
fieldEl.classList.add('fp-dragging');
|
||
});
|
||
root.addEventListener('dragend', (e) => {
|
||
const fieldEl = e.target.closest && e.target.closest('.fp-field[data-fp-id]');
|
||
if (fieldEl) fieldEl.classList.remove('fp-dragging');
|
||
removeDropLine();
|
||
});
|
||
|
||
root.addEventListener('dragover', (e) => {
|
||
if (!isRelevantDrag(e)) return;
|
||
e.preventDefault();
|
||
e.dataTransfer.dropEffect = isMoveDrag(e) ? 'move' : 'copy';
|
||
showDropLine(computeBeforeId(e.clientY));
|
||
});
|
||
root.addEventListener('dragleave', (e) => {
|
||
if (e.target === root || !root.contains(e.relatedTarget)) removeDropLine();
|
||
});
|
||
root.addEventListener('drop', (e) => {
|
||
if (!isRelevantDrag(e)) return;
|
||
e.preventDefault();
|
||
const beforeId = computeBeforeId(e.clientY);
|
||
removeDropLine();
|
||
|
||
const newType = e.dataTransfer.getData('application/x-field-type');
|
||
if (newType) {
|
||
const newId = hooks.onCreateAt ? hooks.onCreateAt(newType, beforeId) : null;
|
||
if (newId) insertIntoOrder(newId, beforeId);
|
||
window.FormPreview.refresh();
|
||
return;
|
||
}
|
||
const movedId = e.dataTransfer.getData('application/x-fp-field');
|
||
if (movedId) {
|
||
insertIntoOrder(movedId, beforeId);
|
||
window.FormPreview.refresh();
|
||
}
|
||
});
|
||
}
|
||
|
||
function syncOptions(fieldEl, id) {
|
||
const chips = Array.from(fieldEl.querySelectorAll('[data-fp-opt]'))
|
||
.map(s => s.textContent.trim()).filter(Boolean);
|
||
setOptions(id, chips.join(','));
|
||
}
|
||
|
||
function isMoveDrag(e) { return Array.from(e.dataTransfer.types || []).includes('application/x-fp-field'); }
|
||
function isRelevantDrag(e) {
|
||
const t = Array.from(e.dataTransfer.types || []);
|
||
return t.includes('application/x-field-type') || t.includes('application/x-fp-field');
|
||
}
|
||
|
||
function computeBeforeId(clientY) {
|
||
const els = Array.from(root.querySelectorAll('.fp-field[data-fp-id]'))
|
||
.filter(el => el !== root.querySelector('.fp-field.fp-dragging'));
|
||
for (const el of els) {
|
||
const r = el.getBoundingClientRect();
|
||
if (clientY < r.top + r.height / 2) return el.dataset.fpId;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function showDropLine(beforeId) {
|
||
removeDropLine();
|
||
dropLine = document.createElement('div');
|
||
dropLine.className = 'fp-drop-line';
|
||
const anchor = beforeId ? root.querySelector(`.fp-field[data-fp-id="${beforeId}"]`) : null;
|
||
const fieldsBox = root.querySelector('.fp-fields');
|
||
const tailBox = root.querySelector('.fp-tail');
|
||
if (anchor) fieldsBox.insertBefore(dropLine, anchor);
|
||
else if (tailBox) tailBox.insertBefore(dropLine, tailBox.firstChild);
|
||
else fieldsBox.appendChild(dropLine);
|
||
}
|
||
function removeDropLine() {
|
||
if (dropLine && dropLine.parentNode) dropLine.parentNode.removeChild(dropLine);
|
||
dropLine = null;
|
||
}
|
||
|
||
/* ---------- 对外 API ---------- */
|
||
|
||
window.FormPreview = {
|
||
init(options) {
|
||
root = options.root;
|
||
getMeta = options.getMeta || (() => ({}));
|
||
hooks = options.hooks || null;
|
||
editable = !!(hooks && (hooks.onDelete || hooks.onCreateAt || hooks.onConditional));
|
||
if (editable && !document.getElementById('fp-canvas-style')) {
|
||
const style = document.createElement('style');
|
||
style.id = 'fp-canvas-style';
|
||
style.textContent = CANVAS_CSS;
|
||
document.head.appendChild(style);
|
||
}
|
||
// 左栏基础配置变化 → 整画布刷新(标题/公告/名单模式/策略等)
|
||
const debouncedFull = () => {
|
||
clearTimeout(debounceTimer);
|
||
debounceTimer = setTimeout(() => this.refresh(), 150);
|
||
};
|
||
document.addEventListener('input', (e) => {
|
||
if (e.target.closest('.field-card')) return; // 卡片数据由画布编辑直接写回,不触发整刷
|
||
if (e.target.closest('#formTitle, #announcementSubtitle, #announcementText, #verifyDigits, #maxSize')) debouncedFull();
|
||
});
|
||
document.addEventListener('change', (e) => {
|
||
if (e.target.closest('.field-card')) return;
|
||
if (e.target.closest('#showProgress, #verifyDigits, #maxSize')) debouncedFull();
|
||
});
|
||
this.refresh();
|
||
},
|
||
|
||
refresh() {
|
||
if (!root || !getMeta) return;
|
||
if (selectedId && !document.getElementById(selectedId)) selectedId = null; // 字段已删
|
||
reconcileOrder();
|
||
render(getMeta());
|
||
},
|
||
|
||
setSelected(id) {
|
||
selectedId = id || null;
|
||
this.refresh();
|
||
},
|
||
|
||
/* 按画布顺序返回 .field-card 元素(保存/枚举的权威顺序) */
|
||
orderedFieldCards() {
|
||
const all = Array.from(document.querySelectorAll('.field-card'));
|
||
if (!root || !editable) return all;
|
||
const ids = Array.from(root.querySelectorAll('.fp-field[data-fp-id]')).map(el => el.dataset.fpId);
|
||
const ordered = ids.map(id => document.getElementById(id)).filter(Boolean);
|
||
all.forEach(c => { if (!ids.includes(c.id)) ordered.push(c); });
|
||
return ordered;
|
||
},
|
||
};
|
||
})();
|