From d54af0e569b3801ee2d72a3c827c2907830dd03f Mon Sep 17 00:00:00 2001 From: prismiwi2015 Date: Wed, 19 Aug 2026 16:50:14 +0200 Subject: [PATCH] Give the Total field a formula editor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The formula was a bare text box and a hint listing function names — which assumes the person writing it already knows their fields' ids and the engine's grammar, the two things nobody knows. The editor turns both into buttons: every number-shaped question on the form is a chip that inserts its reference, every engine function is a chip that inserts itself with the caret left inside the parentheses, and the result computes live against sample answers as you type — through the same shared engine the front end runs, so a formula that computes here computes there. A formula that does not parse says so in words instead of showing nothing. The bare box stays beside the button, for somebody pasting a formula in. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_0119U4sRRWGcTQdwYreTwpAp --- assets/css/builder.css | 60 ++++ assets/js/builder.js | 452 +++++++++++++++++++++++++++- assets/js/builder.min.js | 6 +- src/builder.ts | 26 +- src/formula-editor.ts | 221 ++++++++++++++ src/merge-tags.ts | 2 +- tests/vitest/formula-editor.test.ts | 84 ++++++ 7 files changed, 843 insertions(+), 8 deletions(-) create mode 100644 src/formula-editor.ts create mode 100644 tests/vitest/formula-editor.test.ts diff --git a/assets/css/builder.css b/assets/css/builder.css index 981e27d..74067aa 100644 --- a/assets/css/builder.css +++ b/assets/css/builder.css @@ -2441,3 +2441,63 @@ os-checkbox-label.atfb-check { .os-window__body:has( > .atfa ) { overflow: hidden; } + +/* -------------------------------------------------------------------------- */ +/* Formula editor */ +/* -------------------------------------------------------------------------- */ + +.atfb-formula__row { + display: flex; + flex-direction: column; + gap: 6px; + align-items: stretch; +} + +.atfb-formula { + max-inline-size: 560px; +} + +.atfb-formula__input { + font-family: Menlo, Consolas, monospace; + font-size: 13px; + resize: vertical; + min-block-size: 64px; +} + +/* The live verdict. Polite because it changes on every keystroke. */ +.atfb-formula__result { + margin: 6px 0 2px; + font-size: 12px; + color: var( --atfb-muted ); +} + +.atfb-formula__result.is-error { + color: var( --atfb-danger, #d63638 ); +} + +.atfb-formula__chips { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.atfb-formula__chip { + padding: 4px 10px; + font: inherit; + font-size: 12px; + color: var( --atfb-fg ); + background: var( --atfb-surface ); + border: 1px solid var( --atfb-border ); + border-radius: 999px; + cursor: pointer; +} + +.atfb-formula__chip:hover { + border-color: var( --atfb-accent ); + color: var( --atfb-accent ); +} + +.atfb-formula__chip:focus-visible { + outline: 2px solid var( --atfb-accent ); + outline-offset: 1px; +} diff --git a/assets/js/builder.js b/assets/js/builder.js index f18ebb7..578c072 100644 --- a/assets/js/builder.js +++ b/assets/js/builder.js @@ -2383,6 +2383,432 @@ var allTerrainFormsBuilder = function(exports) { } return "#888888"; } + const FUNCTIONS = { + min: -1, + max: -1, + sum: -1, + avg: -1, + round: -1, + ceil: 1, + floor: 1, + abs: 1, + sqrt: 1, + pow: 2 + }; + const PRECEDENCE = { + "+": { precedence: 1, right: false }, + "-": { precedence: 1, right: false }, + "*": { precedence: 2, right: false }, + "/": { precedence: 2, right: false }, + "%": { precedence: 2, right: false }, + "^": { precedence: 4, right: true } + }; + function calculate(formula, values, fields = []) { + if (!formula || !formula.trim()) { + return null; + } + if (formula.length > 2e3) { + return null; + } + const resolved = resolveRefs(formula, values, fields); + const tokens = tokenize(resolved); + if (!tokens) { + return null; + } + const postfix = toPostfix(tokens); + if (!postfix) { + return null; + } + const result = evalPostfix(postfix); + return result === null || !Number.isFinite(result) ? null : result; + } + function resolveRefs(formula, values, fields) { + return formula.replace(/\{([a-zA-Z0-9_]+)\}/g, (_match, fieldId) => { + const value = Object.prototype.hasOwnProperty.call(values, fieldId) ? values[fieldId] : null; + const field = fields.find((candidate) => candidate.id === fieldId) ?? null; + const literal = numericValue(value, field).toFixed(10).replace(/0+$/, "").replace(/\.$/, ""); + return literal === "" || literal === "-" ? "0" : literal; + }); + } + function numericValue(value, field) { + if (typeof value === "boolean") { + return value ? 1 : 0; + } + if (Array.isArray(value)) { + return value.reduce((total, item) => total + numericValue(item, field), 0); + } + if (value === null || value === void 0 || value === "") { + return 0; + } + const choices = field?.choices ?? []; + for (const choice of choices) { + if (String(choice.value) === String(value)) { + if (typeof choice.price === "number") { + return choice.price; + } + if (typeof choice.points === "number") { + return choice.points; + } + break; + } + } + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : 0; + } + function tokenize(formula) { + const tokens = []; + let i = 0; + while (i < formula.length) { + const char = formula[i]; + if (/\s/.test(char)) { + i++; + continue; + } + if (/[0-9.]/.test(char)) { + let number = ""; + while (i < formula.length && /[0-9.]/.test(formula[i])) { + number += formula[i]; + i++; + } + const parsed = Number(number); + if (!Number.isFinite(parsed)) { + return null; + } + tokens.push({ type: "number", value: parsed }); + continue; + } + if (/[a-zA-Z_]/.test(char)) { + let name = ""; + while (i < formula.length && /[a-zA-Z0-9_]/.test(formula[i])) { + name += formula[i]; + i++; + } + name = name.toLowerCase(); + if (!Object.prototype.hasOwnProperty.call(FUNCTIONS, name)) { + return null; + } + tokens.push({ type: "function", value: name }); + continue; + } + if (char === "(" || char === ")") { + tokens.push({ type: char, value: char }); + i++; + continue; + } + if (char === ",") { + tokens.push({ type: "comma", value: "," }); + i++; + continue; + } + if ("+-*/%^".includes(char)) { + const previous = tokens[tokens.length - 1]; + const isUnary = char === "-" && (!previous || previous.type === "operator" || previous.type === "unary" || previous.type === "(" || previous.type === "comma"); + tokens.push({ type: isUnary ? "unary" : "operator", value: char }); + i++; + continue; + } + return null; + } + return tokens; + } + function precedenceOf(token) { + if (token.type === "unary") { + return { precedence: 3, right: true }; + } + return PRECEDENCE[token.value] ?? { precedence: 0, right: false }; + } + function toPostfix(tokens) { + const output = []; + const operators = []; + const arity = []; + for (const token of tokens) { + switch (token.type) { + case "number": + output.push(token); + break; + case "function": + operators.push(token); + arity.push(1); + break; + case "comma": + while (operators.length && operators[operators.length - 1].type !== "(") { + output.push(operators.pop()); + } + if (!operators.length) { + return null; + } + if (arity.length) { + arity[arity.length - 1]++; + } + break; + case "unary": + operators.push(token); + break; + case "operator": { + const info = PRECEDENCE[token.value]; + while (operators.length) { + const top = operators[operators.length - 1]; + if (top.type !== "operator" && top.type !== "unary") { + break; + } + const topInfo = precedenceOf(top); + if (topInfo.precedence > info.precedence || topInfo.precedence === info.precedence && !info.right) { + output.push(operators.pop()); + continue; + } + break; + } + operators.push(token); + break; + } + case "(": + operators.push(token); + break; + case ")": { + while (operators.length && operators[operators.length - 1].type !== "(") { + output.push(operators.pop()); + } + if (!operators.length) { + return null; + } + operators.pop(); + if (operators.length && operators[operators.length - 1].type === "function") { + const fn = operators.pop(); + fn.arity = arity.length ? arity.pop() : 1; + output.push(fn); + } + break; + } + } + } + while (operators.length) { + const top = operators.pop(); + if (top.type === "(") { + return null; + } + output.push(top); + } + return output; + } + function evalPostfix(postfix) { + const stack = []; + for (const token of postfix) { + switch (token.type) { + case "number": + stack.push(token.value); + break; + case "unary": { + if (!stack.length) { + return null; + } + stack.push(-stack.pop()); + break; + } + case "operator": { + if (stack.length < 2) { + return null; + } + const right = stack.pop(); + const left = stack.pop(); + switch (token.value) { + case "+": + stack.push(left + right); + break; + case "-": + stack.push(left - right); + break; + case "*": + stack.push(left * right); + break; + case "/": + stack.push(right === 0 ? 0 : left / right); + break; + case "%": + stack.push(right === 0 ? 0 : left % right); + break; + case "^": + stack.push(Math.pow(left, right)); + break; + default: + return null; + } + break; + } + case "function": { + const count = token.arity ?? 1; + if (stack.length < count) { + return null; + } + const args = []; + for (let i = 0; i < count; i++) { + args.unshift(stack.pop()); + } + const result = applyFunction(token.value, args); + if (result === null) { + return null; + } + stack.push(result); + break; + } + default: + return null; + } + } + return stack.length === 1 ? stack[0] : null; + } + function applyFunction(name, args) { + if (!args.length) { + return null; + } + switch (name) { + case "min": + return Math.min(...args); + case "max": + return Math.max(...args); + case "sum": + return args.reduce((total, value) => total + value, 0); + case "avg": + return args.reduce((total, value) => total + value, 0) / args.length; + case "round": { + const precision = Math.max(-10, Math.min(10, Math.trunc(args[1] ?? 0))); + const factor = Math.pow(10, precision); + return Math.round(args[0] * factor) / factor; + } + case "ceil": + return Math.ceil(args[0]); + case "floor": + return Math.floor(args[0]); + case "abs": + return Math.abs(args[0]); + case "sqrt": + return args[0] < 0 ? 0 : Math.sqrt(args[0]); + case "pow": + return Math.pow(args[0], args[1] ?? 2); + default: + return null; + } + } + const FORMULA_FUNCTIONS = ["sum", "min", "max", "avg", "round", "ceil", "floor", "abs", "sqrt", "pow"]; + const NUMERIC_FRIENDLY = [ + "number", + "range", + "scale", + "rating", + "total", + "select", + "multiselect", + "radio", + "checkboxes", + "switch", + "quiz" + ]; + function formulaTargets(fields, except) { + return fields.filter((field) => field.id !== except && NUMERIC_FRIENDLY.includes(field.type)); + } + function formulaSampleValues(fields, except) { + const values = {}; + formulaTargets(fields, except).forEach((field, index) => { + values[field.id] = index + 1; + }); + return values; + } + function openFormulaEditor(options) { + const overlay = el("div", { class: "atfb-overlay" }); + const close = () => { + overlay.remove(); + document.removeEventListener("keydown", onKeydown); + }; + const onKeydown = (event) => { + if (event.key === "Escape") { + close(); + } + }; + const input = el("textarea", { + class: "atfb-input atfb-formula__input", + attrs: { rows: "3", "aria-label": "Formula" } + }); + input.value = String(options.field.formula ?? ""); + const result = el("p", { class: "atfb-formula__result", attrs: { "aria-live": "polite" } }); + const samples = formulaSampleValues(options.fields, options.field.id); + const preview = () => { + const formula = input.value.trim(); + if ("" === formula) { + result.textContent = "Empty. Reference a question below to start."; + result.classList.remove("is-error"); + return; + } + const computed = calculate(formula, samples, options.fields); + if (null === computed) { + result.textContent = "This does not compute yet — check the braces and parentheses."; + result.classList.add("is-error"); + return; + } + const sampled = formulaTargets(options.fields, options.field.id).map((field, index) => `${field.label || field.id} = ${index + 1}`).join(", "); + result.textContent = `With sample answers (${sampled}): ${computed}`; + result.classList.remove("is-error"); + }; + input.addEventListener("input", preview); + const chip = (label, insert, caretBack = 0) => el("button", { + class: "atfb-formula__chip", + type: "button", + text: label, + on: { + click: () => { + insertAtCursor(input, insert); + if (caretBack > 0) { + const caret = (input.selectionStart ?? input.value.length) - caretBack; + input.setSelectionRange(caret, caret); + } + } + } + }); + const targets = formulaTargets(options.fields, options.field.id); + const questions = el("div", { + class: "atfb-formula__chips", + children: targets.length ? targets.map((field) => chip(field.label || field.id, `{${field.id}}`)) : [el("p", { class: "atfb-hint", text: "No number-shaped questions yet — add a number, scale or priced choice field and it appears here." })] + }); + const functions = el("div", { + class: "atfb-formula__chips", + children: FORMULA_FUNCTIONS.map((name) => chip(`${name}()`, `${name}()`, 1)) + }); + overlay.append( + el("div", { + class: "atfb-modal atfb-formula", + attrs: { role: "dialog", "aria-label": "Formula editor" }, + children: [ + el("h2", { text: "Formula" }), + input, + result, + row("Your questions", questions, "Click one to reference its answer."), + row("Functions", functions), + el("div", { + class: "atfb-modal__actions", + children: [ + button("Cancel", close), + button( + "Save formula", + () => { + options.onSave(input.value.trim()); + close(); + }, + "primary" + ) + ] + }) + ] + }) + ); + overlay.addEventListener("click", (event) => { + if (event.target === overlay) { + close(); + } + }); + document.addEventListener("keydown", onKeydown); + options.root.append(overlay); + preview(); + input.focus(); + input.setSelectionRange(input.value.length, input.value.length); + } function shell() { return window.wp?.os ?? null; } @@ -2915,8 +3341,30 @@ var allTerrainFormsBuilder = function(exports) { this.inspector.append( row( "Formula", - textInput(String(field.formula ?? ""), (value) => update("formula", value)), - "Reference fields with braces: {f1} * {f2} + 10. Functions: min, max, sum, avg, round, ceil, floor, abs, sqrt, pow." + el("div", { + class: "atfb-formula__row", + children: [ + textInput(String(field.formula ?? ""), (value) => update("formula", value)), + // The editor is where the formula is meant to be + // written: the questions and the functions are + // buttons there, and the result computes live + // against sample answers. The bare box stays for + // somebody pasting one in. + button( + "Formula editor", + () => openFormulaEditor({ + root: this.root, + fields: this.schema?.fields ?? [], + field, + onSave: (formula) => { + update("formula", formula); + this.renderInspector(); + } + }) + ) + ] + }), + "Reference answers with braces — {f1} * {f2} + 10 — or open the editor and click them in." ), row("Currency symbol", textInput(String(field.currency ?? ""), (value) => update("currency", value))) ); diff --git a/assets/js/builder.min.js b/assets/js/builder.min.js index b98fe32..301949f 100644 --- a/assets/js/builder.min.js +++ b/assets/js/builder.min.js @@ -1,3 +1,3 @@ -var allTerrainFormsBuilder=function(W){"use strict";class ft{constructor(){this.targets=[],this.active=null,this.lastEndMs=0}start(e){if(this.active||e.origin.button!==0)return null;const{payload:s,origin:t}=e,n=t.clientX,a=t.clientY;let o=!1,l=!1,d=null,c=null,h=0,k=0;const v=()=>{document.removeEventListener("pointermove",L),document.removeEventListener("pointerup",F),document.removeEventListener("pointercancel",X),document.removeEventListener("keydown",z),window.removeEventListener("blur",X),d?.remove(),d=null,s.source.classList.remove("atf-is-dragging"),c?.onLeave?.(g),c=null,this.active=null,this.lastEndMs=Date.now()},g={payload:s,isFinished:()=>l,cancel:(_="caller")=>{l||(l=!0,v(),e.onCancel?.(_))}},T=_=>{o=!0,s.source.classList.add("atf-is-dragging");const q=s.source.getBoundingClientRect();h=s.ghost?.offsetX??n-q.left,k=s.ghost?.offsetY??a-q.top,d=s.ghost?.element??s.source.cloneNode(!0),d.classList.add("atf-drag-ghost"),d.style.width=`${q.width}px`,document.body.appendChild(d),x(_)},x=_=>{d&&(d.style.transform=`translate3d(${_.clientX-h}px, ${_.clientY-k}px, 0)`)},L=_=>{if(l)return;if(!o){if(Math.hypot(_.clientX-n,_.clientY-a)<4)return;T(_)}x(_);const q=this.hitTest(_.clientX,_.clientY);q!==c&&(c?.onLeave?.(g),c=q,c?.onEnter?.(g))},F=_=>{if(l)return;if(!o){l=!0,v(),e.onClickOnly?.();return}const q=c;if(l=!0,v(),q&&q.accept(s)){e.onCommit?.(q),q.onDrop(g,{clientX:_.clientX,clientY:_.clientY});return}e.onCancel?.(q?"rejected":"no-target")},X=()=>g.cancel("pointercancel"),z=_=>{_.key==="Escape"&&g.cancel("escape")};return document.addEventListener("pointermove",L),document.addEventListener("pointerup",F),document.addEventListener("pointercancel",X),document.addEventListener("keydown",z),window.addEventListener("blur",X),this.active=g,g}registerDropTarget(e){return this.targets=this.targets.filter(s=>s.id!==e.id),this.targets.push(e),()=>{this.targets=this.targets.filter(s=>s.id!==e.id)}}isDragging(){return this.active!==null}recentlyEndedDrag(e=500){return Date.now()-this.lastEndMso.right||so.bottom)continue;const l=mt(a.element);if(l>n){t=a,n=l;continue}l===n&&t&&bt(a.element,t.element)&&(t=a)}return t}}function mt(i){let e=0,s=i;for(;s;)e++,s=s.parentElement;return e}function bt(i,e){return(e.compareDocumentPosition(i)&Node.DOCUMENT_POSITION_FOLLOWING)!==0}function he(){return window.wp?.os??null}let ue=null;function K(){const i=he();return i?.dragManager?i.dragManager:(ue||(ue=new ft),ue)}function gt(i){const e=n=>{const a=n.detail?.payload;return a&&i.includes(a.type)?a.source:null},s=n=>e(n)?.classList.add("atf-is-dragging"),t=n=>e(n)?.classList.remove("atf-is-dragging");return document.addEventListener("os.drag.start",s),document.addEventListener("os.drag.end",t),()=>{document.removeEventListener("os.drag.start",s),document.removeEventListener("os.drag.end",t)}}function Oe(i,e,s,t,n){const a=e.getBoundingClientRect();return n&&(n.style.width=`${Math.round(a.width)}px`,n.style.maxWidth=`${Math.round(a.width)}px`,n.style.boxSizing="border-box"),{type:i,source:e,data:s,ghost:{element:n,offsetX:t.clientX-a.left,offsetY:t.clientY-a.top,hint:{neutral:"",accept:"",reject:"",hidden:!0}}}}function qe(i,e,s,t){const n=Array.from(i.querySelectorAll(e)).filter(a=>a!==t&&!a.classList.contains("atf-drag-ghost"));for(let a=0;an.fetch(l,d,{source:"allterrain-forms"}):(l,d)=>fetch(l,d))(s,{credentials:"same-origin",...e,headers:t});if(!o.ok){let l=`Request failed with status ${o.status}.`,d="";try{const c=await o.json();l=c.message??l,d=c.code??""}catch{}throw new ie(l,o.status,d)}if(o.status!==204)return await o.json()}const P=i=>pe(i);async function vt(i){if(!I?.wpRestUrl)throw new ie("AllTerrain Forms is not configured on this page.",0);const e=I.nonce?{"X-WP-Nonce":I.nonce}:{},s=he(),t=Fe(I.wpRestUrl,i),n=s?.fetch?await s.fetch(t,{credentials:"same-origin",headers:e},{source:"allterrain-forms"}):await fetch(t,{credentials:"same-origin",headers:e});if(!n.ok)throw new ie(`Request failed with status ${n.status}.`,n.status);return await n.json()}function yt(i){if(!i||!i.includes("&"))return i;const e=document.createElement("textarea");return e.innerHTML=i,e.value}const G=(i,e)=>pe(i,{method:"POST",body:JSON.stringify(e)}),ne=i=>pe(i,{method:"DELETE"});function Ie(i){const e=new URLSearchParams;for(const[t,n]of Object.entries(i))n===void 0||n===""||n===!1||e.set(t,String(n));const s=e.toString();return s?`?${s}`:""}function ae(i){const e=i?.schema?.settings;return e&&(!e.themeOverrides||Array.isArray(e.themeOverrides))&&(e.themeOverrides={...e.themeOverrides}),i}const $={config:()=>P("/config"),listForms:()=>P("/forms"),getForm:i=>P(`/forms/${i}`).then(ae),createForm:i=>G("/forms",i).then(ae),updateForm:(i,e)=>G(`/forms/${i}`,e).then(ae),duplicateForm:i=>G(`/forms/${i}/duplicate`,{}).then(ae),deleteForm:i=>ne(`/forms/${i}`),preview:(i,e)=>G(`/forms/${i}/preview`,e),pages:()=>vt("wp/v2/pages?per_page=100&status=publish&orderby=title&order=asc&_fields=id,title").then(i=>i.map(e=>({id:e.id,title:yt(e.title?.rendered??"")||`#${e.id}`}))),mergeTags:i=>P(`/forms/${i}/merge-tags`).then(e=>e.groups),analytics:(i,e="")=>P(`/forms/${i}/analytics${e?`?dimension=${encodeURIComponent(e)}`:""}`),demoStatus:()=>P("/demo"),demoSeed:i=>G("/demo",i?{count:i}:{}),demoRemove:()=>ne("/demo"),listEntries:i=>P(`/entries${Ie(i)}`),getEntry:i=>P(`/entries/${i}`),updateEntry:(i,e)=>G(`/entries/${i}`,e),deleteEntry:i=>ne(`/entries/${i}`),exportEntries:i=>P(`/entries/export${Ie(i)}`),listThemes:()=>P("/themes"),saveTheme:i=>G("/themes",i),deleteTheme:i=>ne(`/themes/${i}`)};function r(i,e={}){const s=document.createElement(i);e.class&&(s.className=e.class),e.text!==void 0&&(s.textContent=e.text),e.html!==void 0&&(s.innerHTML=e.html),e.title&&(s.title=e.title),e.type&&"type"in s&&(s.type=e.type),e.value!==void 0&&"value"in s&&(s.value=e.value),e.placeholder!==void 0&&"placeholder"in s&&(s.placeholder=e.placeholder),e.href&&"href"in s&&(s.href=e.href);for(const[t,n]of Object.entries(e.attrs??{}))n===void 0||n===!1||s.setAttribute(t,n===!0?"":String(n));Object.assign(s.style,e.style??{});for(const[t,n]of Object.entries(e.on??{}))s.addEventListener(t,n);for(const t of e.children??[])t==null||t===!1||s.append(t);return s}function O(i){i.replaceChildren()}function M(i){return r("span",{class:`dashicons ${i.startsWith("dashicons-")?i:`dashicons-${i}`}`,attrs:{"aria-hidden":"true"}})}function m(i,e,s){const t=e.id||`atf-c-${Math.random().toString(36).slice(2,9)}`;return e.id=t,r("div",{class:"atfb-row",children:[r("label",{class:"atfb-row__label",text:i,attrs:{for:t}}),e,s?r("p",{class:"atfb-row__hint",text:s}):null]})}function w(i,e,s=""){return r("input",{class:"atfb-input",type:"text",value:i,placeholder:s,on:{input:t=>e(t.target.value)}})}function R(i,e){if(Q("os-number-field")){const s=document.createElement("os-number-field");return s.setAttribute("value",i),s.classList.add("atfb-field"),s.addEventListener("os-input-change",t=>{e(String(t.detail?.value??""))}),s}return r("input",{class:"atfb-input",type:"number",value:i,on:{input:s=>e(s.target.value)}})}function re(i,e,s=4){const t=r("textarea",{class:"atfb-input atfb-input--area",attrs:{rows:s},on:{input:n=>e(n.target.value)}});return t.value=i,t}function D(i,e,s){if(Q("os-select")&&Q("os-option")){const t=document.createElement("os-select");t.setAttribute("value",i),t.classList.add("atfb-field");for(const n of e){const a=document.createElement("os-option");a.setAttribute("value",n.value),a.textContent=n.label,t.append(a)}return t.addEventListener("os-pick",n=>{s(String(n.detail?.value??""))}),t}return r("select",{class:"atfb-input atfb-select",on:{change:t=>s(t.target.value)},children:e.map(t=>r("option",{value:t.value,text:t.label,attrs:{selected:t.value===i}}))})}function A(i,e,s){if(Q("os-checkbox-label")){const n=document.createElement("os-checkbox-label");return n.setAttribute("label",i),n.classList.add("atfb-check"),e&&n.setAttribute("checked",""),n.addEventListener("os-checkbox-change",a=>{s(!!a.detail?.checked)}),n}const t=r("input",{type:"checkbox",on:{change:n=>s(n.target.checked)}});return t.checked=e,r("label",{class:"atfb-check",children:[t,r("span",{text:i})]})}function E(i,e,s="secondary",t){const n=[t?M(t):null,r("span",{text:i})];if(Q("os-button")){const a=document.createElement("os-button");a.setAttribute("variant",s),a.setAttribute("type","button"),a.classList.add("atfb-button",`atfb-button--${s}`),a.addEventListener("click",e);for(const o of n)o&&a.append(o);return a}return r("button",{class:`atfb-button atfb-button--${s}`,type:"button",on:{click:e},children:n})}function Q(i){return typeof customElements<"u"&&!!customElements.get(i)}const wt=["os-button","os-checkbox-label","os-number-field","os-select","os-option","os-segmented","os-segment","os-color-field","os-empty-state"];let oe=null;function xt(){if(oe)return oe;const i=window.wp?.os;return oe=i?.loadComponents?i.loadComponents(wt).catch(()=>{}):Promise.resolve(),oe}async function fe(i,e=""){const s=window.wp?.os;return s?.confirm?s.confirm({title:e,message:i,danger:!0}):window.confirm(i)}function N(i,e="",s="info"){const t=window.wp?.os;if(t?.notify){t.notify({title:i,body:e,type:s});return}console.info(`[AllTerrain Forms] ${i}${e?`: ${e}`:""}`)}function kt(i){let e=0,s;return(...t)=>{s=t,!e&&(e=window.requestAnimationFrame(()=>{e=0,i(...s)}))}}function me(i,e){let s=0;return(...t)=>{window.clearTimeout(s),s=window.setTimeout(()=>i(...t),e)}}function _t(i){try{return window.localStorage.getItem(i)??""}catch{return""}}function St(i,e){try{window.localStorage.setItem(i,e)}catch{}}function Me(i){const e=i.closest(".os-window__body");e&&(e.addEventListener("scroll",()=>{e.scrollTop&&(e.scrollTop=0),e.scrollLeft&&(e.scrollLeft=0)},{passive:!0}),e.scrollTop=0,e.scrollLeft=0)}function Ne(){const i=[window];try{window.parent&&window.parent!==window&&i.push(window.parent)}catch{}return i}function Lt(i){const e=i.wp?.os?.windowManager?.getAll?.()??[];for(const s of e){const t=s.iframe??s.element?.querySelector?.("iframe");if(t&&t.contentWindow===window)return s}return null}const Et=4e3,Tt=100;function Ct(i,e){const s=Date.now()+Et,t=()=>{const n=Lt(i);if(n&&n.id!==e){typeof n.close=="function"?n.close():i.wp?.os?.windowManager?.remove?.(n.id);return}!n&&Date.now()0?{form:s}:void 0;s>0&&Ot(s);for(const n of Ne())if(n.wp?.os?.openWindow?.(e,{source:"handoff",params:t})){window.setTimeout(()=>Ct(n,e),0);return}}function At(){document.addEventListener("click",i=>{const e=i.target?.closest?.("[data-atf-open-window]");if(!e)return;i.preventDefault();const s=e.getAttribute("data-atf-open-window")??"";for(const t of Ne())if(t.wp?.os?.openWindow?.(s,{source:"handoff"}))return})}const Dt="allterrain-forms/requested-form";function Ot(i){try{window.sessionStorage.setItem(Dt,String(i))}catch{}}const Pe={is:"is",is_not:"is not",contains:"contains",not_contains:"does not contain",starts_with:"starts with",ends_with:"ends with",greater:"is more than",less:"is less than",greater_equal:"is at least",less_equal:"is at most",empty:"is empty",not_empty:"has any answer"},Re=["empty","not_empty"];function Be(i,e){const s=i.find(t=>t.id===e);return s?s.label||"an untitled question":null}function He(i,e,s){return i.find(a=>a.id===e)?.choices?.find(a=>a.value===s)?.label||s}function qt(i,e){const s=Pe[i.operator]??String(i.operator);if(Re.includes(i.operator))return s;const t=He(e,i.field,i.value);return`${i.operator==="is"?"":`${s} `}${t!==""?t:"(nothing)"}`}function je(i,e){const s=Be(e,i.field),t=Pe[i.operator]??String(i.operator);if(s===null)return[{kind:"field",text:"a question that no longer exists",fieldId:i.field,missing:!0}];const n=[{kind:"field",text:s,fieldId:i.field,missing:!1},{kind:"operator",text:t}];if(Re.includes(i.operator))return n;const a=He(e,i.field,i.value);return n.push({kind:"value",text:a!==""?a:"(nothing)"}),n}function Ft(i,e){const s=i.logic;if(!s?.enabled||!s.rules.length)return[];const t=[{kind:"verb",text:s.action==="hide"?"Hidden when":"Shown when"}];return s.rules.forEach((n,a)=>{a>0&&t.push({kind:"join",text:s.match==="all"?"and":"or"}),t.push(...je(n,e))}),t}function We(i){return i.map(e=>e.text).join(" ")}function It(i,e){return We(je(i,e))}function be(i){const e=[];for(const s of i){const t=s.logic;if(t?.enabled)for(const n of t.rules)!n.field||n.field===s.id||e.push({from:n.field,to:s.id,label:It(n,i),short:qt(n,i),action:t.action,broken:Be(i,n.field)===null})}return e}function Mt(i){const e=new Map,s=new Set;for(const t of be(i)){const n=`${t.from}->${t.to}`;t.broken||s.has(n)||(s.add(n),e.set(t.from,(e.get(t.from)??0)+1))}return e}const Ue=10,Ye=22,J="http://www.w3.org/2000/svg";class Nt{constructor(e){this.edges=[],this.teardowns=[],this.frame=0,this.host=e,this.svg=document.createElementNS(J,"svg"),this.svg.setAttribute("class","atfb-logicmap"),this.svg.setAttribute("aria-hidden","true"),this.svg.setAttribute("focusable","false"),e.append(this.svg);const s=()=>this.schedule();window.addEventListener("resize",s),this.teardowns.push(()=>window.removeEventListener("resize",s));const t=e.closest(".atfb__canvas")??e;if(t.addEventListener("scroll",s,{passive:!0}),this.teardowns.push(()=>t.removeEventListener("scroll",s)),typeof ResizeObserver<"u"){const n=new ResizeObserver(s);n.observe(e),this.teardowns.push(()=>n.disconnect())}}setEdges(e){this.edges=e,this.schedule()}highlight(e){this.svg.classList.toggle("is-focused",!!e),this.svg.querySelectorAll("[data-from]").forEach(s=>{const t=e&&(s.dataset.from===e||s.dataset.to===e);s.classList.toggle("is-lit",!!t)})}destroy(){this.teardowns.forEach(e=>e()),this.teardowns=[],this.svg.remove(),this.frame&&cancelAnimationFrame(this.frame)}schedule(){this.frame||(this.frame=requestAnimationFrame(()=>{this.frame=0,this.draw()}))}draw(){this.svg.replaceChildren();const e=this.host.getBoundingClientRect();this.svg.setAttribute("viewBox",`0 0 ${e.width} ${e.height}`),this.svg.setAttribute("width",String(e.width)),this.svg.setAttribute("height",String(e.height));const s=new Map;for(const t of this.edges){const n=this.cardRect(t.from),a=this.cardRect(t.to);if(!n||!a)continue;const o=s.get(t.from)??0;s.set(t.from,o+1),this.drawEdge(t,n,a,e,o)}}cardRect(e){const s=this.host.querySelector(`[data-atfb-card="${CSS.escape(e)}"]`);return s?s.getBoundingClientRect():null}drawEdge(e,s,t,n,a){const o=s.right-n.left,l=s.top+s.height/2-n.top,d=t.right-n.left,c=t.top+t.height/2-n.top,h=Math.max(0,n.width-Ue-Math.max(o,d)),k=22+a*11+Math.min(22,Math.abs(c-l)/8),v=Math.max(12,Math.min(k,h*.4)),g=document.createElementNS(J,"path");g.setAttribute("d",`M ${o} ${l} C ${o+v} ${l}, ${d+v} ${c}, ${d} ${c}`),g.setAttribute("class",`atfb-logicmap__path is-${e.action}${e.broken?" is-broken":""}`),g.dataset.from=e.from,g.dataset.to=e.to;const T=document.createElementNS(J,"title");T.textContent=e.label,g.append(T);const x=document.createElementNS(J,"circle");x.setAttribute("cx",String(d)),x.setAttribute("cy",String(c)),x.setAttribute("r","3.5"),x.setAttribute("class",`atfb-logicmap__dot is-${e.action}${e.broken?" is-broken":""}`),x.dataset.from=e.from,x.dataset.to=e.to,this.svg.append(g,x);const L=document.createElementNS(J,"text");L.setAttribute("x",String(n.width-Ue)),L.setAttribute("y",String(c+3)),L.setAttribute("text-anchor","end"),L.setAttribute("class","atfb-logicmap__label"),L.dataset.from=e.from,L.dataset.to=e.to,L.textContent=e.short.length>Ye?`${e.short.slice(0,Ye-1)}…`:e.short;const F=document.createElementNS(J,"title");F.textContent=e.label,L.append(F),this.svg.append(L)}}const Pt={text:"text",email:"text",url:"text",tel:"text",number:"text",password:"text",date:"text",time:"text",datetime:"text",date_range:"composite",textarea:"textarea",select:"select",country:"select",multiselect:"options",radio:"options",checkboxes:"options",image_choice:"options",quiz:"options",switch:"toggle",consent:"toggle",file:"file",range:"range",rating:"summary",scale:"summary",likert:"summary",signature:"summary",repeater:"summary",color:"text",name:"composite",address:"composite",total:"text",hidden:"static",heading:"static",html:"static",divider:"static",spacer:"static",page_break:"static"};function Rt(i){return Pt[i]??"text"}function ze(i,e){const s=/^choice:(\d+):(label|value)$/.exec(e);return String(s?i.choices?.[Number(s[1])]?.[s[2]]??"":i[e]??"")}function U(i){const{value:e,onInput:s,onCommit:t}=i,n=r("span",{class:`${i.class} atfb-editable`,text:e,attrs:{contenteditable:"plaintext-only",role:"textbox",spellcheck:"false","data-placeholder":i.placeholder}});return i.bind&&(n.dataset.atfbBind=i.bind),n.addEventListener("pointerdown",a=>a.stopPropagation()),n.addEventListener("input",()=>s(n.textContent??"")),n.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),n.blur()),a.key==="Escape"&&(n.textContent=e,n.blur()),a.stopPropagation()}),n.addEventListener("blur",()=>t?.()),n}function Bt(i){const e=r("input",{class:"atf-choice__input",type:i==="checkboxes"||i==="multiselect"?"checkbox":"radio"});return e.disabled=!0,e}function Ht(i,e,s){const t=Rt(i.type),n=U({value:i.label,placeholder:"Write the question…",class:"atf-label",bind:"label",onInput:o=>s.edit(l=>{l.label=o}),onCommit:()=>s.restructure(()=>{})}),a=[t==="static"||t==="toggle"?null:n,Wt(i,e,t,s),jt(i,e,s)];return r("div",{class:"atfb-preview atf-form",children:[r("div",{class:`atf-field atf-field--${i.type}`,children:a})]})}function jt(i,e,s){if(!e?.supports.includes("hint"))return null;const t=U({value:i.hint??"",placeholder:"Add a hint…",class:"atf-hint",bind:"hint",onInput:n=>s.edit(a=>{a.hint=n})});return t.setAttribute("aria-label","Hint"),r("p",{class:"atfb-preview__hint",children:[t]})}function Wt(i,e,s,t){switch(s){case"text":return ge(i,"atf-input",t);case"textarea":return ge(i,"atf-input atf-textarea",t,!0);case"select":return r("div",{class:"atfb-preview__select",children:[ge(i,"atf-input atf-select",t)]});case"options":return Yt(i,t);case"toggle":return r("div",{class:i.type==="switch"?"atf-toggle atf-toggle--switch":"atf-toggle",children:[(()=>{const n=r("input",{class:"atf-toggle__input",type:"checkbox"});return n.disabled=!0,n})(),U({value:i.label||"",placeholder:i.type==="consent"?"What are they agreeing to?…":"What does this turn on?…",class:"atf-toggle__label",bind:"label",onInput:n=>t.edit(a=>{a.label=n}),onCommit:()=>t.restructure(()=>{})})]});case"file":return r("div",{class:"atf-file",children:[r("input",{class:"atf-file__input",type:"file"})]});case"range":return r("input",{class:"atf-range__input",type:"range"});case"composite":return r("div",{class:"atf-composite__parts",children:[r("span",{class:"atf-input atfb-preview__ghost",text:""}),r("span",{class:"atf-input atfb-preview__ghost",text:""})]});case"static":return zt(i,e,t);default:return r("div",{class:"atfb-preview__stack",children:[r("p",{class:"atfb-preview__summary",text:`${e?.label??i.type} — set this up in the panel on the right.`}),i.type==="repeater"?Ut(i,t):null]})}}function ge(i,e,s,t=!1){const n=U({value:i.placeholder??"",placeholder:i.type==="select"||i.type==="country"?"Choose…":"Placeholder…",class:`${e} atfb-preview__box${t?" atfb-preview__box--tall":""}`,bind:"placeholder",onInput:a=>s.edit(o=>{o.placeholder=a})});return n.setAttribute("aria-label","Placeholder"),n}function ve(i,e,s,t,n,a){return r("span",{class:`atf-button ${s} atfb-preview__button`,children:[U({value:i,placeholder:e,class:"atfb-preview__button-text",bind:t,onInput:o=>n.edit(l=>a(l,o))})]})}function Ut(i,e){return ve(String(i.addLabel??""),"Add another","atf-button--secondary","addLabel",e,(s,t)=>{s.addLabel=t})}function Yt(i,e){const s=r("div",{class:"atf-choices__list"});return(i.choices??[]).forEach((t,n)=>{s.append(r("div",{class:"atf-choice atfb-preview__option",children:[Bt(i.type),U({value:t.label,placeholder:"Option…",class:"atf-choice__label",bind:`choice:${n}:label`,onInput:a=>{e.edit(o=>{const l=o.choices?.[n];if(!l)return;const d=!l.value||l.value===l.label;l.label=a,d&&(l.value=a)})}}),r("button",{class:"atfb-preview__remove",type:"button",title:"Remove this option",attrs:{"aria-label":`Remove ${t.label||"this option"}`},on:{pointerdown:a=>a.stopPropagation(),click:a=>{a.stopPropagation(),e.restructure(o=>{o.choices.splice(n,1)})}},children:[r("span",{text:"×"})]})]}))}),s.append(r("button",{class:"atfb-preview__add",type:"button",on:{pointerdown:t=>t.stopPropagation(),click:t=>{t.stopPropagation(),e.restructure(n=>{const a=n.choices.length+1;n.choices.push({label:`Option ${a}`,value:`Option ${a}`})})}},children:[r("span",{text:"+ Add option"})]})),r("fieldset",{class:"atf-choices",children:[s]})}function zt(i,e,s){return i.type==="heading"?U({value:i.label,placeholder:"Section heading…",class:"atf-heading",bind:"label",onInput:t=>s.edit(n=>{n.label=t}),onCommit:()=>s.restructure(()=>{})}):i.type==="divider"?r("hr",{class:"atf-divider"}):i.type==="page_break"?r("div",{class:"atfb-preview__stack",children:[r("p",{class:"atfb-progress-name",children:[U({value:i.label,placeholder:"Name this step…",class:"atf-progress__label",bind:"label",onInput:t=>s.edit(n=>{n.label=t}),onCommit:()=>s.restructure(()=>{})})]}),r("p",{class:"atfb-preview__summary",text:"Everything after this is a new page."}),r("div",{class:"atf-nav atfb-preview__nav",children:[ve(String(i.prevLabel??""),"Back","atf-button--secondary","prevLabel",s,(t,n)=>{t.prevLabel=n}),ve(String(i.nextLabel??""),"Next","","nextLabel",s,(t,n)=>{t.nextLabel=n})]})]}):r("p",{class:"atfb-preview__summary",text:`${e?.label??i.type} — nothing is shown to the visitor here.`})}const ye=new Map;function we(i){let e=ye.get(i);return e||(e=$.mergeTags(i).catch(()=>[]),ye.set(i,e)),e}function Gt(i){ye.delete(i)}function Xt(i){const e=new Map;for(const s of i)for(const t of s.items)e.set(t.tag,t);return e}function Kt(i,e){const s=Xt(e);return i.replace(/\{[a-z_]+(?::[^}]*)?\}/gi,t=>{const n=s.get(t.toLowerCase());return n?n.sample:t})}function Jt(i){return/\{[a-z_]+(?::[^}]*)?\}/i.test(i)}let Y=null;function Z(){Y?.remove(),Y=null}typeof document<"u"&&(document.addEventListener("pointerdown",i=>{const e=i.target;e?.closest(".atfb-tagpick__open")||Y&&!Y.contains(e)&&Z()}),document.addEventListener("keydown",i=>{i.key==="Escape"&&Y&&(Z(),i.stopPropagation())}));function Vt(i,e){const s=i.selectionStart??i.value.length,t=i.selectionEnd??i.value.length;i.value=i.value.slice(0,s)+e+i.value.slice(t);const n=s+e.length;i.setSelectionRange(n,n),i.focus(),i.dispatchEvent(new Event("input",{bubbles:!0}))}function Qt(i){let e=i.parentElement;for(;e&&e!==document.body;){const s=getComputedStyle(e).overflowY;if(s==="auto"||s==="scroll"||s==="hidden")return e.getBoundingClientRect().bottom;e=e.parentElement}return window.innerHeight}function Zt(i,e){const s=r("input",{class:"atfb-input atfb-tagpick__search",type:"search",placeholder:"Search values…",attrs:{"aria-label":"Search values"}}),t=r("div",{class:"atfb-tagpick__list"}),n=a=>{t.replaceChildren();const o=a.trim().toLowerCase();let l=0;for(const d of i){const c=d.items.filter(h=>!o||h.label.toLowerCase().includes(o)||h.tag.toLowerCase().includes(o));if(!c.length){d.empty&&!o&&!d.items.length&&t.append(r("p",{class:"atfb-tagpick__group",text:d.label}),r("p",{class:"atfb-tagpick__empty",text:d.empty}));continue}t.append(r("p",{class:"atfb-tagpick__group",text:d.label}));for(const h of c)l+=1,t.append(r("button",{class:"atfb-tagpick__item",type:"button",on:{click:()=>{e(h.tag),Z()}},children:[r("span",{class:"atfb-tagpick__item-main",children:[r("span",{class:"atfb-tagpick__label",text:h.label}),r("code",{class:"atfb-tagpick__tag",text:h.tag})]}),h.hint||h.sample?r("span",{class:"atfb-tagpick__meta",text:h.sample?`e.g. ${h.sample}`:h.hint}):null]}))}!l&&o&&t.append(r("p",{class:"atfb-tagpick__empty",text:`Nothing matches “${a}”.`}))};return n(""),s.addEventListener("input",()=>n(s.value)),r("div",{class:"atfb-tagpick",attrs:{role:"dialog","aria-label":"Insert a value"},children:[r("p",{class:"atfb-tagpick__intro",text:"Pick something to drop in. It is filled in when the form is submitted."}),s,t]})}function Ge(i,e){const s=r("button",{class:"atfb-button atfb-button--ghost atfb-tagpick__open",type:"button",title:"Insert a value from the submission",children:[M("shortcode"),r("span",{text:"Insert a value"})]}),t=r("div",{class:"atfb-taggable",children:[i,r("div",{class:"atfb-taggable__tools",children:[s]})]}),n=e.preview===!1?null:r("p",{class:"atfb-taggable__preview"});n&&t.append(n);const a=()=>{if(n){if(!Jt(i.value)){n.textContent="",n.hidden=!0;return}we(e.formId).then(o=>{n.hidden=!1,n.replaceChildren(r("span",{class:"atfb-taggable__preview-label",text:"Reads as"}),r("span",{text:Kt(i.value,o)}))})}};return i.addEventListener("input",a),a(),s.addEventListener("click",o=>{if(o.stopPropagation(),Y&&t.contains(Y)){Z();return}Z(),we(e.formId).then(l=>{const d=Zt(l,c=>{Vt(i,c),a()});t.append(d),Y=d,(window.innerHeight-d.getBoundingClientRect().topQt(t))&&d.classList.add("atfb-tagpick--above"),d.querySelector(".atfb-tagpick__search")?.focus()})}),t}function Xe(i,e){const s=parseFloat(String(i??""));return Number.isFinite(s)?s:e}function Ke(i,e){let s=e[0];for(const t of e)Math.abs(t.at-i)i.accent??"#2271b1",apply:i=>({accent:i,"accent-soft":`color-mix( in srgb, ${i} 12%, transparent )`,"border-focus":i,"focus-ring-color":i,"button-bg":i,"button-bg-hover":`color-mix( in srgb, ${i} 88%, #000 )`})},{id:"roundness",label:"Roundness",hint:"Corners, everywhere at once.",kind:"scale",steps:xe.map(({value:i,label:e})=>({value:i,label:e})),owns:["radius-field","radius-button","radius-card","radius-check"],read:i=>Ke(Xe(i["radius-field"],4),xe),apply:i=>{const e=xe.find(s=>s.value===i)?.at??4;return{"radius-field":`${e}px`,"radius-button":`${e}px`,"radius-card":`${Math.min(e*2,28)}px`,"radius-check":`${Math.min(e,6)}px`}}},{id:"density",label:"Density",hint:"How much air the form has.",kind:"scale",steps:ke.map(({value:i,label:e})=>({value:i,label:e})),owns:["pad-field-x","pad-field-y","gap-fields","gap-label","button-pad-x","button-pad-y"],read:i=>Ke(Xe(i["pad-field-y"],9),ke),apply:i=>{const e=ke.find(s=>s.value===i)?.at??9;return{"pad-field-y":`${e}px`,"pad-field-x":`${Math.round(e*1.4)}px`,"gap-fields":`${Math.round(e*2.2)}px`,"gap-label":`${Math.max(4,Math.round(e*.7))}px`,"button-pad-y":`${e+2}px`,"button-pad-x":`${Math.round(e*2.2)}px`}}},{id:"shadow",label:"Depth",hint:"How far the form sits off the page.",kind:"scale",steps:es,owns:["shadow-field","shadow-field-focus","shadow-button","shadow-button-hover","shadow-card"],read:i=>{const e=i["shadow-card"]??"none";return e==="none"||e.trim()===""?i["shadow-field"]&&i["shadow-field"]!=="none"?"hard":"none":e.includes("0 1px")||e.includes("2px")?"subtle":"lifted"},apply:i=>{switch(i){case"subtle":return{"shadow-field":"none","shadow-field-focus":"none","shadow-button":"0 1px 2px rgba( 0, 0, 0, 0.12 )","shadow-button-hover":"0 2px 4px rgba( 0, 0, 0, 0.16 )","shadow-card":"0 1px 3px rgba( 0, 0, 0, 0.1 )"};case"lifted":return{"shadow-field":"none","shadow-field-focus":"0 4px 12px rgba( 0, 0, 0, 0.12 )","shadow-button":"0 4px 10px rgba( 0, 0, 0, 0.16 )","shadow-button-hover":"0 8px 20px rgba( 0, 0, 0, 0.2 )","shadow-card":"0 10px 30px rgba( 0, 0, 0, 0.14 )"};case"hard":return{"shadow-field":"3px 3px 0 currentColor","shadow-field-focus":"5px 5px 0 currentColor","shadow-button":"4px 4px 0 currentColor","shadow-button-hover":"2px 2px 0 currentColor","shadow-card":"none"};default:return{"shadow-field":"none","shadow-field-focus":"none","shadow-button":"none","shadow-button-hover":"none","shadow-card":"none"}}}},{id:"field-style",label:"Fields",hint:"How an input is drawn.",kind:"choice",steps:ts,owns:["field-style"],read:i=>i["field-style"]??"outline",apply:i=>({"field-style":i})},{id:"labels",label:"Labels",hint:"Where the question sits relative to the answer.",kind:"choice",steps:ss,owns:["label-position"],read:i=>i["label-position"]??"top",apply:i=>({"label-position":i})}]}function is(i){return _e().find(e=>e.owns.includes(i))??null}function Je(i){let e=i.activeSlug,s={...i.overrides},t=i.themes;const n=u=>{s=u,i.onOverridesReplaced?.({...u})},a=r("div",{class:"atfs-preview__frame"}),o=r("div",{class:"atfs-controls__body"}),l=r("div",{class:"atfs-quick"}),d=r("div",{class:"atfs-themes"}),c=me(async()=>{try{const u=await i.previewFor(e,s),p=a.closest(".atf-studio__preview"),f=p?.scrollTop??0;a.innerHTML=u,p&&(p.scrollTop=f),document.dispatchEvent(new CustomEvent("atf-refresh"))}catch(u){O(a),a.append(r("p",{class:"atfb-error",text:u instanceof Error?u.message:"Preview failed."}))}},180),h={"label-position":"atf-labels-","field-style":"atf-fields-"},k=(u,p,f)=>{const b=f.replace(/[^a-z0-9_-]/gi,"");for(const y of[...u.classList])y.startsWith(p)&&u.classList.remove(y);b&&u.classList.add(p+b)},v=u=>{const p=a.querySelector(".atf-form-wrap"),f=p?.querySelector(".atf-form");if(p)for(const[b,y]of Object.entries(u))y===""?p.style.removeProperty(`--atf-${b}`):p.style.setProperty(`--atf-${b}`,y),f&&h[b]&&k(f,h[b],y||(t.find(C=>C.slug===e)?.resolved[b]??""))},g=u=>{v(u.resolved);const p=a.querySelector(".atf-form");p&&(k(p,"atf-theme-",u.slug),p.classList.toggle("atf-is-dark",!!u.dark))},T=u=>s[u.token]!==void 0?s[u.token]:t.find(f=>f.slug===e)?.resolved?.[u.token]??u.default,x=()=>{O(d);for(const u of t){const p=r("button",{class:`atfs-theme${u.slug===e?" is-active":""}`,type:"button",attrs:{"aria-pressed":u.slug===e,title:u.description},children:[r("span",{class:"atfs-theme__chip",style:{background:u.resolved.surface??"#fff",borderColor:u.resolved.border??"#ccc",borderRadius:u.resolved["radius-field"]??"4px",boxShadow:u.resolved["shadow-card"]??"none"},children:[r("span",{class:"atfs-theme__accent",style:{background:u.resolved.accent??"#2271b1",borderRadius:u.resolved["radius-button"]??"4px"}})]}),r("span",{class:"atfs-theme__name",text:u.label}),u.custom?r("span",{class:"atfb-badge",text:"yours"}):null],on:{click:()=>{e=u.slug,n({}),i.onTheme(e),g(u),x(),z(),X(),ht()}}});d.append(p)}},L=()=>{const p={...t.find(f=>f.slug===e)?.resolved??{}};for(const[f,b]of Object.entries(s))p[f]=b;return p},F=u=>{const p=l.closest(".atf-studio__controls"),f=p?.scrollTop??0;u(),p&&(p.scrollTop=f)},X=me(()=>F(V),150),z=()=>{const u=L(),p=l.querySelectorAll(".atfs-dial");_e().forEach((f,b)=>{const y=p[b];if(!y)return;const C=f.read(u);if(f.kind==="colour"){const S=y.querySelector('input[type="color"]'),B=y.querySelector("input.atfb-input");S&&document.activeElement!==S&&(S.value=le(C)),B&&document.activeElement!==B&&(B.value=C);return}y.querySelectorAll(".atfs-segment").forEach((S,B)=>{const j=f.steps?.[B]?.value===C;S.classList.toggle("is-on",j),S.setAttribute("aria-pressed",String(j))})})},_=(u,p)=>{const f=u.apply(p,L());for(const[b,y]of Object.entries(f))s[b]=y,i.onOverride(b,y);v(f),z(),X()},q=()=>{O(l);const u=L();for(const p of _e()){const f=p.read(u);let b;if(p.kind==="colour"){const y=r("input",{class:"atfs-color",type:"color",value:le(f),attrs:{"aria-label":p.label},on:{input:C=>_(p,C.target.value)}});b=r("div",{class:"atfs-color-row",children:[y,w(f,C=>_(p,C))]})}else b=r("div",{class:`atfs-segmented atfs-segmented--${p.kind}`,attrs:{role:"group","aria-label":p.label},children:(p.steps??[]).map(y=>r("button",{class:`atfs-segment${y.value===f?" is-on":""}`,type:"button",text:y.label,attrs:{"aria-pressed":y.value===f},on:{click:()=>_(p,y.value)}}))});l.append(r("div",{class:"atfs-dial",children:[r("div",{class:"atfs-dial__head",children:[r("span",{class:"atfs-dial__label",text:p.label}),r("span",{class:"atfs-dial__hint",text:p.hint})]}),b]}))}},V=()=>{O(o);const u=new Map;for(const f of i.tokens){const b=u.get(f.group)??[];b.push(f),u.set(f.group,b)}const p={colour:"Colour",shape:"Corners and borders",shadow:"Shadows",fields:"Field style",space:"Spacing",type:"Type",labels:"Labels",button:"Buttons",focus:"Focus ring",motion:"Motion"};for(const[f,b]of u)o.append(r("details",{class:"atfs-group",attrs:{open:f==="colour"},children:[r("summary",{text:p[f]??f}),...b.map(y=>ms(y))]}))},ms=u=>{const p=T(u),f=S=>{S===""?delete s[u.token]:s[u.token]=S,i.onOverride(u.token,S),v({[u.token]:S})};let b;if(u.control==="color"){const S=r("input",{class:"atfs-color",type:"color",value:le(p),attrs:{"aria-label":`${u.label} colour`},on:{input:j=>{const se=j.target.value;B.value=se,f(se)}}}),B=w(p,j=>{S.value=le(j),f(j)});b=r("div",{class:"atfs-color-row",children:[S,B]})}else if(u.control==="select")b=D(p,(u.options??[]).map(S=>({value:S,label:S})),f);else if(u.control==="length"){const S=parseFloat(p)||0,B=u.unit??"px",j=u.token.includes("radius")?60:80,se=r("input",{class:"atfs-range",type:"range",value:String(S),attrs:{min:"0",max:String(j),step:"1","aria-label":u.label},on:{input:de=>{const pt=`${de.target.value}${B}`;ut.value=pt,f(pt)}}}),ut=w(p,de=>{se.value=String(parseFloat(de)||0),f(de)});b=r("div",{class:"atfs-length-row",children:[se,ut]})}else b=w(p,f);const y=m(u.label,b),C=is(u.token);return C&&(y.classList.add("is-dialled"),y.append(r("span",{class:"atfs-owned",text:C.label}))),s[u.token]!==void 0&&(y.classList.add("is-overridden"),y.append(r("button",{class:"atfs-reset",type:"button",text:"Reset",attrs:{"aria-label":`Reset ${u.label} to the theme's value`},on:{click:()=>{f(""),F(V)}}}))),y},bs=async()=>{const u=t.find(b=>b.slug===e),p=u?`${u.label} (mine)`:"My theme",f=window.prompt("Name this theme",p);if(f)try{const b={};for(const C of i.tokens){const S=T(C);S!==C.default&&(b[C.token]=S)}const y=await $.saveTheme({label:f,tokens:b});t=[...t.filter(C=>C.slug!==y.slug),y],i.onThemesChanged(t),e=y.slug,n({}),i.onTheme(e),x(),z(),F(V),N("Theme saved",y.label)}catch(b){N("Could not save the theme",b instanceof Error?b.message:"","error")}},gs=async()=>{const u=t.find(p=>p.slug===e);if(u?.custom&&await fe(`Delete “${u.label}”? Forms using it fall back to Clean.`,"Delete theme"))try{await $.deleteTheme(u.id),t=t.filter(f=>f.slug!==u.slug),i.onThemesChanged(t),e="clean",n({}),i.onTheme(e),x(),z(),F(V);const p=t.find(f=>f.slug===e);p&&g(p)}catch(p){N("Could not delete the theme",p instanceof Error?p.message:"","error")}},vs=async()=>{const u=t.find(b=>b.slug===e),p={label:u?.label??e,tokens:{...u?.tokens??{},...s}},f=JSON.stringify(p,null," ");try{await navigator.clipboard.writeText(f),N("Theme copied","Paste it into another site to import it.")}catch{window.prompt("Copy this theme",f)}},ys=()=>{const u=window.prompt("Paste a theme");if(u)try{const p=JSON.parse(u);if(!p.tokens||typeof p.tokens!="object")throw new Error("That does not look like a theme.");for(const[f,b]of Object.entries(p.tokens))s[f]=String(b),i.onOverride(f,String(b));v({...s}),z(),F(V)}catch(p){N("Could not read that theme",p instanceof Error?p.message:"","error")}},dt=E("Delete",()=>void gs(),"danger"),ht=()=>{const u=t.find(p=>p.slug===e);dt.hidden=!u?.custom};return x(),q(),V(),c(),ht(),r("div",{class:"atf-studio",children:[r("div",{class:"atf-studio__top",children:[r("div",{class:"atf-studio__topbar",children:[r("h2",{class:"atf-studio__heading",text:"Theme"}),r("div",{class:"atfs__actions",children:[E("Save as a theme",()=>void bs(),"primary"),E("Export",()=>void vs()),E("Import",ys),dt]})]}),d]}),r("div",{class:"atf-studio__panes",children:[r("aside",{class:"atf-studio__controls",children:[r("p",{class:"atfb-hint",text:"Changes apply to this form only, until you save them as a theme."}),l,r("details",{class:"atfs-advanced",children:[r("summary",{text:"Every setting"}),r("p",{class:"atfb-hint",text:"The full token list. The dials above write into it."}),o]})]}),r("main",{class:"atf-studio__preview",children:[r("h2",{class:"screen-reader-text",text:"Live preview"}),a]})]})]})}async function Se(){const i=document.querySelector("[data-atfs-root]");if(!i||i.dataset.atfsMounted)return;i.dataset.atfsMounted="1",Me(i);const e=i.querySelector("[data-atfs-bar]"),s=i.querySelector(".atfs__body")??i;try{const[t,n,a]=await Promise.all([$.config(),$.listThemes(),$.listForms()]);if(!a.length){O(s),s.append(r("div",{class:"atfb-empty",children:[r("h2",{text:"No forms to preview"}),r("p",{text:"Make a form first — a theme needs something to dress."})]}));return}let o=a[0],l={},d=o.theme;const c=()=>{O(s),s.append(Je({themes:n,tokens:t.tokens,activeSlug:d,overrides:l,standalone:!0,onTheme:h=>{d=h},onOverride:(h,k)=>{k===""?delete l[h]:l[h]=k},onOverridesReplaced:h=>{l={...h}},previewFor:async(h,k)=>{const v=await $.getForm(o.id);v.schema.settings.theme=h,v.schema.settings.themeOverrides=k;const{html:g}=await $.preview(o.id,{schema:v.schema,theme:h});return g},onThemesChanged:h=>{n.length=0,n.push(...h)}}))};e&&(O(e),e.append(r("span",{class:"atfs__label",text:"Preview against"}),D(String(o.id),a.map(h=>({value:String(h.id),label:h.title||"(untitled)"})),h=>{o=a.find(k=>String(k.id)===h)??a[0],l={},c()}))),c()}catch(t){O(s),s.append(r("p",{class:"atfb-error",text:t instanceof Error?t.message:"Could not load themes."}))}}typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>void Se()):Se(),document.addEventListener("os-window-content-loaded",()=>void Se()));function le(i){const e=i.trim();return/^#[0-9a-f]{6}$/i.test(e)?e:/^#[0-9a-f]{3}$/i.test(e)?`#${e[1]}${e[1]}${e[2]}${e[2]}${e[3]}${e[3]}`:"#888888"}function Le(){return window.wp?.os??null}const Ve="allterrain-forms/preview",Ee="allterrain-forms-preview";function ns(i){const e=Le();if(!e?.registerTitleBarButton)return()=>{};const s=()=>{try{e.registerTitleBarButton({id:Ve,label:"Preview this form",icon:"dashicons-visibility",placement:"right",order:90,match:t=>{const n=t?.id??t?.config?.id??"";return n==="allterrain-forms"||n.startsWith("allterrain-forms#")},onClick:()=>void Qe(i),owner:"allterrain-forms-builder"})}catch{}};return e.ready?e.ready(s):s(),()=>{try{e.unregisterTitleBarButton?.(Ve)}catch{}}}async function Qe(i){i.isDirty()&&await i.save();const e=i.current();e&&Ze(e.id,e.title,e.previewUrl)}function Ze(i,e,s){const t=Le();if(!t?.windowManager?.open){window.open(s,"_blank","noopener");return}t.windowManager.open({id:`${Ee}-${i}`,baseId:Ee,url:s,title:`Preview: ${e}`,icon:"dashicons-visibility"})}function as(i,e,s){if(!Le()?.windowManager?.open||!document.querySelector(`[data-window-id="${Ee}-${i}"]`))return;const a=s.includes("?")?"&":"?";Ze(i,e,`${s}${a}atf_r=${Date.now()}`)}const rs="allterrain-forms/form";function os(){return window.wp?.os?.relations??null}function ls(i){const e=i.closest("[data-window-id], .os-window");if(!e)return null;const s=e.getAttribute("data-window-id");if(s)return s;const t=e.id??"";return t?t.replace(/^wp-window-/,""):null}const cs=6e3,et=120;function tt(i,e){const s=os();if(Te.set(i,e),!s?.set)return;const t=a=>{if(ce.get(i)!==n)return;const o=ls(i);if(!o){Date.now()t(a),et);return}try{s.set(o,e)}catch(d){st||(st=!0,console.error("[AllTerrain Forms] The shell refused a window identity.",d,e)),ce.delete(i);return}if(!e||s.get?.(o)?.id===e.id||Date.now()>=a){ce.delete(i);return}window.setTimeout(()=>t(a),et)},n=Symbol("atf-identity");ce.set(i,n),t(Date.now()+cs)}let st=!1;const ce=new WeakMap,Te=new Map;function ds(){for(const[i,e]of Te){if(!i.isConnected){Te.delete(i);continue}tt(i,e)}}if(typeof document<"u")for(const i of["os-window-content-loaded","os-window-opened"])document.addEventListener(i,()=>ds());function hs(i,e){return{type:rs,id:i.id,label:i.title||"Untitled form",related:[{id:`allterrain-forms/entries-${i.id}`,label:"Entries for this form",url:`${e}admin.php?page=allterrain-forms-entries&form=${i.id}`,group:"allterrain-forms",groupLabel:"Forms",icon:"dashicons-list-view"}]}}const ee="allterrain-forms/field",us=["openstation/file","desktop-mode/file","openstation/attachment"],it="allterrain-forms/logic-map-v2";function H(i,e){return i.dataset.atfbBind=e,i}const nt={level:{key:"level",label:"Heading level",control:"select",hint:"Headings should step down one at a time.",options:[{value:"2",label:"Heading 2"},{value:"3",label:"Heading 3"},{value:"4",label:"Heading 4"},{value:"5",label:"Heading 5"},{value:"6",label:"Heading 6"}]},content:{key:"content",label:"HTML",control:"textarea",hint:"Shown as written. Scripts are stripped when the form is saved."},consenttext:{key:"consentText",label:"What they are agreeing to",control:"textarea",hint:"Shown beside the tick box. Links are allowed."},height:{key:"height",label:"Height",control:"number",hint:"In pixels."},columns:{key:"columns",label:"Columns",control:"number",hint:"How many pictures sit side by side."},multiple:{key:"multiple",label:"Let them choose more than one",control:"checkbox"},inline:{key:"inline",label:"Lay the options out in a row",control:"checkbox"},other:{key:"other",label:"Offer an “Other” box",control:"checkbox",hint:"Adds a final option with a box to type in."},filetypes:{key:"filetypes",label:"Accepted file types",control:"commas",hint:"Extensions, separated by commas. Empty accepts anything the site allows."},maxsize:{key:"maxsize",label:"Largest file",control:"number",hint:"In megabytes."},maxfiles:{key:"maxfiles",label:"How many files",control:"number"},minrows:{key:"minRows",label:"Fewest rows",control:"number",also:{key:"maxRows",label:"Most rows"}},endlabels:{key:"minLabel",label:"Label at the low end",control:"text",also:{key:"maxLabel",label:"Label at the high end"}},points:{key:"points",label:"Points if correct",control:"number"},minchoices:{key:"minChoices",label:"Fewest they may pick",control:"number",also:{key:"maxChoices",label:"Most they may pick"}}},ps={label:"the canvas edits it in place, and the inspector mirrors it",placeholder:"edited by typing into the control on the canvas",hint:"edited under the control on the canvas",nextlabel:"edited on the page break’s own Next button",prevlabel:"edited on the page break’s own Back button",addlabel:"edited on the repeater’s own Add button",choices:"the choices editor, and the option list on the canvas",required:"the toggle on the card",width:"its own row",css:"its own row",prefill:"its own section",logic:"the conditional logic section",formula:"its own row, with the currency that goes with it",currency:"rendered with the formula",correct:"the choices editor marks the right answer",default:"its own row, typed to match what the field stores",rows:"a row count on a textarea; the statement list on a Likert matrix",parts:"a tick box per part, listed by the server",min:"the validation section, paired with max",max:"the validation section, paired with min",step:"the validation section",minlength:"the validation section, paired with maxlength",maxlength:"the validation section, paired with minlength",mindate:"the validation section, paired with maxdate",maxdate:"the validation section, paired with mindate",mintime:"the validation section, paired with maxtime",maxtime:"the validation section, paired with mintime",pattern:"the validation section",unique:"the validation section",maxchoices:"rendered with minchoices",maxrows:"rendered with minrows"};function at(i,e,s){const t=i[e.key],n=a=>s(e.key,a);if(e.control==="checkbox")return A(e.label,!!t,n);if(e.control==="commas"){const a=Array.isArray(t)?t:[];return m(e.label,w(a.join(", "),o=>{n(o.split(",").map(l=>l.trim().replace(/^\./,"").toLowerCase()).filter(Boolean))}),e.hint)}return e.control==="select"?m(e.label,D(String(t??""),e.options??[],n),e.hint):e.control==="textarea"?m(e.label,re(String(t??""),n),e.hint):e.control==="number"?m(e.label,R(String(t??""),n),e.hint):m(e.label,H(w(String(t??""),n),e.key),e.hint)}function rt(i,e){const s=new Set(i.map(n=>n.key).filter(Boolean));let t=i.length+1;return e.split(` -`).map(n=>n.trim()).filter(Boolean).map((n,a)=>{const o=i[a]?.key;if(o)return{key:o,label:n};for(;s.has(`r${t}`);)t+=1;return s.add(`r${t}`),{key:`r${t}`,label:n}})}function ot(i,e,s){const t=i.findIndex(a=>a.id===e);if(t<0)return null;const n=Math.max(0,Math.min(s,i.length-1));return n===t?null:{from:t,to:n}}const Ce=[{value:"user:email",label:"Their email address",group:"About the person filling it in",tag:"{user:email}"},{value:"user:display_name",label:"Their name",group:"About the person filling it in",tag:"{user:display_name}"},{value:"user:first_name",label:"Their first name",group:"About the person filling it in"},{value:"user:last_name",label:"Their last name",group:"About the person filling it in"},{value:"user:login",label:"Their username",group:"About the person filling it in"},{value:"date:today",label:"Today’s date",group:"The date and time",tag:"{date}"},{value:"date:now",label:"The time right now",group:"The date and time",tag:"{time}"},{value:"site",label:"This site’s name",group:"About this site",tag:"{site}"},{value:"site:url",label:"This site’s address",group:"About this site",tag:"{site:url}"},{value:"site:admin_email",label:"The site administrator’s email",group:"About this site",tag:"{admin_email}"}],fs=["About the person filling it in","The date and time","About this site"],$e=(i,e)=>I?.i18n?.[i]??e;class lt{constructor(e){this.config=null,this.themes=[],this.forms=[],this.form=null,this.schema=null,this.selected=null,this.tab="build",this.logicMap=null,this.canvasTheme=r("style"),this.canvasThemeSignature="",this.openSections=new Map,this.logicMapOn=_t(it)!=="off",this.dirty=!1,this.editGeneration=0,this.saveInFlight=!1,this.queuedSave=null,this.teardowns=[],this.canvasTarget=null,this.history=[],this.historyAt=-1,this.autosave=me(()=>{this.save(!0)},2500),this.renderInspector=kt(()=>{if(O(this.inspector),!this.schema||(this.root.classList.toggle("atfb--build-only-panes",this.tab!=="build"),this.tab!=="build"))return;const s=this.schema.fields.find(o=>o.id===this.selected);if(!s){this.inspector.append(r("div",{class:"atfb-placeholder",children:[r("p",{text:"Select a field to change it."}),r("p",{class:"atfb-hint",text:"Drag a field from the palette, or press one to add it to the end."})]}));return}const t=this.config?.fieldTypes.find(o=>o.type===s.type),n=t?.supports??[],a=(o,l)=>{const d=this.liveField(s.id);d&&(d[o]=l,this.markDirty(),this.renderCanvas())};this.inspector.append(r("h3",{class:"atfb-inspector__title",text:t?.label??s.type}),r("p",{class:"atfb-hint",text:`Reference this field as {field:${s.id}}`})),n.includes("label")&&this.inspector.append(m("Label",H(w(s.label,o=>a("label",o)),"label"))),n.includes("placeholder")&&this.inspector.append(m("Placeholder",H(w(s.placeholder,o=>a("placeholder",o)),"placeholder"))),n.includes("hint")&&this.inspector.append(m("Hint",H(w(s.hint,o=>a("hint",o)),"hint"),"Shown under the field, and read out with it.")),n.includes("nextlabel")&&this.inspector.append(m("Next button",H(w(String(s.nextLabel??""),o=>a("nextLabel",o)),"nextLabel"),"Leave empty for “Next”.")),n.includes("prevlabel")&&this.inspector.append(m("Back button",H(w(String(s.prevLabel??""),o=>a("prevLabel",o)),"prevLabel"),"Leave empty for “Back”.")),n.includes("addlabel")&&this.inspector.append(m("Add button",H(w(String(s.addLabel??""),o=>a("addLabel",o)),"addLabel"),"Leave empty for “Add another”.")),n.includes("required")&&this.inspector.append(A("Required",s.required,o=>a("required",o))),n.includes("width")&&this.inspector.append(m("Width",D(s.width,[{value:"full",label:"Full width"},{value:"two-thirds",label:"Two thirds"},{value:"half",label:"Half"},{value:"third",label:"One third"},{value:"quarter",label:"One quarter"}],o=>a("width",o)))),t?.choices&&this.inspector.append(this.renderChoicesEditor(s,a)),this.renderTypeSettings(s,t,n,a),(s.type==="total"||n.includes("formula"))&&this.inspector.append(m("Formula",w(String(s.formula??""),o=>a("formula",o)),"Reference fields with braces: {f1} * {f2} + 10. Functions: min, max, sum, avg, round, ceil, floor, abs, sqrt, pow."),m("Currency symbol",w(String(s.currency??""),o=>a("currency",o)))),this.inspector.append(this.renderValidationSection(s,n,a)),this.inspector.append(this.renderLogicSection(s,a)),n.includes("prefill")&&this.inspector.append(this.prefillControl(s,a)),n.includes("css")&&this.inspector.append(m("CSS class",w(s.cssClass,o=>a("cssClass",o))))}),this.root=e,this.bar=e.querySelector("[data-atfb-bar]")??r("div"),this.palette=e.querySelector("[data-atfb-palette]")??r("div"),this.canvas=e.querySelector("[data-atfb-canvas]")??r("div"),this.inspector=e.querySelector("[data-atfb-inspector]")??r("div")}async start(){try{const[t,n,a]=await Promise.all([$.config(),$.listThemes(),$.listForms()]);this.config=t,this.themes=n,this.forms=a}catch(t){this.fail(t);return}this.teardowns.push(gt([ee])),this.teardowns.push(ns({current:()=>this.form?{id:this.form.id,title:this.form.title,previewUrl:this.form.previewUrl}:null,isDirty:()=>this.dirty,save:()=>this.save(!0)}));const e=t=>{this.dirty&&(t.preventDefault(),t.returnValue="")};window.addEventListener("beforeunload",e),this.teardowns.push(()=>window.removeEventListener("beforeunload",e));const s=t=>{!(t.metaKey||t.ctrlKey)||t.key.toLowerCase()!=="z"||t.target?.closest("input, textarea, [contenteditable]")||(t.preventDefault(),this.travel(t.shiftKey?1:-1))};this.root.addEventListener("keydown",s),this.teardowns.push(()=>this.root.removeEventListener("keydown",s)),this.renderBar(),this.renderPalette(),this.forms.length?await this.open(this.forms[0].id):this.renderFormsList()}destroy(){this.canvasTarget?.(),this.canvasTarget=null,this.teardowns.forEach(e=>e()),this.teardowns=[]}fail(e){O(this.bar),this.bar.append(r("p",{class:"atfb-error",text:e instanceof Error?e.message:"Something went wrong loading your forms."}))}renderBar(){O(this.bar);const e=D(String(this.form?.id??""),[...this.forms.map(n=>({value:String(n.id),label:n.title||"(untitled)"}))],n=>void this.open(Number(n)));e.setAttribute("aria-label","Choose a form");const s=r("input",{class:"atfb-title",type:"text",value:this.form?.title??"",placeholder:"Untitled form",attrs:{"aria-label":"Form title"},on:{input:n=>{this.form&&(this.form.title=n.target.value,this.markDirty())}}}),t=r("div",{class:"atfb-tabs",attrs:{role:"tablist"},children:[["build","Build"],["theme","Theme"],["settings","Settings"],["notify","Notifications"],["confirm","Confirmations"]].map(([n,a])=>r("button",{class:`atfb-tab${this.tab===n?" is-active":""}`,type:"button",text:a,attrs:{role:"tab","aria-selected":this.tab===n},on:{click:()=>{this.tab=n,this.renderBar(),this.renderInspector(),this.renderCanvas()}}}))});this.bar.append(r("div",{class:"atfb-bar__left",children:[this.forms.length>1?e:null,s]}),t,r("div",{class:"atfb-bar__right",children:[this.historyButton("undo","Undo",-1),this.historyButton("redo","Redo",1),E("New",()=>void this.showTemplates(),"secondary","plus-alt2"),E("Export",()=>void this.exportForm(),"secondary","download"),E("Import",()=>void this.importForm(),"secondary","upload"),E("Preview",()=>void this.preview(),"secondary","visibility"),E("Entries",()=>this.openEntries(),"secondary","list-view"),this.logicMapButton(),this.saveButton()]}))}liveField(e){return this.schema?.fields.find(s=>s.id===e)}syncCanvas(e){const s=this.canvas.querySelector(`[data-atfb-card="${CSS.escape(e.id)}"]`);if(s)for(const t of s.querySelectorAll(".atfb-editable[data-atfb-bind]")){const n=ze(e,t.dataset.atfbBind??"");t.textContent!==n&&(t.textContent=n)}}syncInspector(e){if(this.selected===e.id)for(const s of this.inspector.querySelectorAll("[data-atfb-bind]")){const t=ze(e,s.dataset.atfbBind??"");s.value!==t&&("value"in s?s.value=t:s.setAttribute("value",t))}}rebindCanvas(){if(this.tab!=="build")return;const e=document.activeElement;if(e instanceof HTMLElement&&this.canvas.contains(e)){e.addEventListener("blur",()=>this.rebindCanvas(),{once:!0});return}this.renderCanvas()}snapshot(){if(!this.schema)return;const e=JSON.stringify(this.schema);this.history[this.historyAt]!==e&&(this.history=this.history.slice(0,this.historyAt+1),this.history.push(e),this.history.length>60&&this.history.shift(),this.historyAt=this.history.length-1,this.syncHistoryButtons())}travel(e){const s=this.historyAt+e;!this.schema||s<0||s>=this.history.length||(this.historyAt=s,this.schema=JSON.parse(this.history[s]),this.schema.fields.some(t=>t.id===this.selected)||(this.selected=null),this.markDirty(),this.renderBar(),this.renderCanvas(),this.renderInspector())}historyButton(e,s,t){const n=E(s,()=>this.travel(t),"secondary",e);return n.setAttribute("data-atfb-history",String(t)),n.disabled=!this.canTravel(t),n}canTravel(e){const s=this.historyAt+e;return s>=0&&sURL.revokeObjectURL(t),1e3)}async importForm(){const e=r("input",{type:"file",attrs:{accept:"application/json,.json"}});e.addEventListener("change",async()=>{const s=e.files?.[0];if(s)try{const t=JSON.parse(await s.text());if(!t.schema)throw new Error("That file does not contain a form.");const n=await $.createForm({title:t.title??s.name.replace(/\.json$/i,""),schema:t.schema});this.forms.unshift({id:n.id,title:n.title,status:n.status,modified:n.modified,fields:n.schema.fields.length,theme:n.schema.settings.theme,entries:0,unread:0,views:0,submissions:0,shortcode:n.shortcode}),this.form=n,this.schema=n.schema,this.selected=null,this.dirty=!1,this.history=[],this.historyAt=-1,this.snapshot(),this.renderBar(),this.renderCanvas(),this.renderInspector(),N("Form imported",n.title)}catch(t){N("Could not import that file",t instanceof Error?t.message:"","error")}}),e.click()}saveButton(){const e=E("Save",()=>void this.save(),"primary");return e.disabled=!this.dirty,e.setAttribute("data-atfb-save",""),e}markDirty(){this.dirty=!0,this.editGeneration+=1;const e=this.bar.querySelector("[data-atfb-save]");e&&(e.disabled=!1),this.autosave()}async save(e=!1){if(!this.form||!this.schema)return;if(this.saveInFlight){this.queuedSave={silent:e&&(this.queuedSave?.silent??!0)};return}this.saveInFlight=!0;const s=this.editGeneration;try{const t=await $.updateForm(this.form.id,{title:this.form.title,schema:this.schema});if(s===this.editGeneration){this.form=t,this.schema=t.schema,this.dirty=!1,this.rebindCanvas();const a=this.bar.querySelector("[data-atfb-save]");a&&(a.disabled=!0)}Gt(t.id);const n=this.forms.find(a=>a.id===t.id);n&&(n.title=t.title),as(t.id,t.title,t.previewUrl),e||N("Form saved",t.title)}catch(t){N($e("saveFailed","Could not save"),t instanceof Error?t.message:"","error")}finally{this.saveInFlight=!1;const t=this.queuedSave;this.queuedSave=null,t&&this.save(t.silent)}}async open(e){if(!(this.dirty&&!await fe("You have unsaved changes. Discard them?"))){try{this.form=await $.getForm(e),this.schema=this.form.schema,this.selected=null,this.dirty=!1,this.history=[],this.historyAt=-1,this.snapshot()}catch(s){this.fail(s);return}this.renderBar(),this.renderCanvas(),this.renderInspector(),this.announceIdentity()}}announceIdentity(){this.form&&tt(this.root,hs(this.form,I?.adminUrl??""))}async showTemplates(){if(!this.config)return;const e=r("div",{class:"atfb-overlay"}),s=a=>{a.key==="Escape"&&t()},t=()=>{e.remove(),document.removeEventListener("keydown",s)},n=r("div",{class:"atfb-templates",children:this.config.templates.map(a=>r("button",{class:"atfb-template",type:"button",on:{click:async()=>{t();try{const o=await $.createForm({template:a.slug});this.forms.unshift({id:o.id,title:o.title,status:o.status,modified:o.modified,fields:o.schema.fields.length,theme:o.schema.settings.theme,entries:0,unread:0,views:0,submissions:0,shortcode:o.shortcode}),this.form=o,this.schema=o.schema,this.selected=null,this.dirty=!1,this.history=[],this.historyAt=-1,this.snapshot(),this.renderBar(),this.renderCanvas(),this.renderInspector(),this.announceIdentity()}catch(o){N("Could not create the form",o instanceof Error?o.message:"","error")}}},children:[M(a.icon),r("strong",{text:a.label}),r("span",{text:a.description})]}))});e.append(r("div",{class:"atfb-modal",attrs:{role:"dialog","aria-label":"Start a new form"},children:[r("h2",{text:"Start a new form"}),n,r("div",{class:"atfb-modal__actions",children:[E("Cancel",t)]})]})),e.addEventListener("click",a=>{a.target===e&&t()}),document.addEventListener("keydown",s),this.root.append(e),n.querySelector("button")?.focus()}renderFormsList(){O(this.canvas),this.canvas.append(r("div",{class:"atfb-empty",children:[r("h2",{text:"No forms yet"}),r("p",{text:"Start from a template, or build one from nothing."}),E("New form",()=>void this.showTemplates(),"primary","plus-alt2")]}))}openEntries(){const e=window.wp?.os;if(e?.openWindow){e.openWindow("allterrain-forms-entries");return}window.location.assign(`${I?.adminUrl??""}admin.php?page=allterrain-forms-entries`)}renderPalette(){if(!this.config)return;O(this.palette);const e=new Map;for(const t of this.config.fieldTypes){const n=e.get(t.group)??[];n.push(t),e.set(t.group,n)}const s=r("input",{class:"atfb-input atfb-palette__search",type:"search",placeholder:"Search fields",attrs:{"aria-label":"Search field types"},on:{input:t=>{const n=t.target.value.toLowerCase().trim();this.palette.querySelectorAll(".atfb-chip").forEach(a=>{const o=(a.textContent??"").toLowerCase();a.hidden=n!==""&&!o.includes(n)}),this.palette.querySelectorAll(".atfb-group").forEach(a=>{const o=Array.from(a.querySelectorAll(".atfb-chip")).some(l=>!l.hidden);a.hidden=!o})}}});this.palette.append(s);for(const[t,n]of Object.entries(this.config.groups)){const a=e.get(t);a?.length&&this.palette.append(r("div",{class:"atfb-group",children:[r("h3",{class:"atfb-group__title",text:n}),r("div",{class:"atfb-group__items",children:a.map(o=>this.paletteChip(o))})]}))}}paletteChip(e){const s=r("button",{class:"atfb-chip",type:"button",title:e.description,attrs:{"data-atf-type":e.type},children:[M(e.icon),r("span",{text:e.label})]});return s.addEventListener("pointerdown",t=>{const n=r("div",{class:"atfb-chip atfb-chip--ghost",children:[M(e.icon),r("span",{text:e.label})]});K().start({payload:Oe(ee,s,{fieldType:e.type,isNew:!0},t,n),origin:t,onClickOnly:()=>this.addField(e.type)})}),s.addEventListener("click",t=>{K().recentlyEndedDrag()&&t.preventDefault()}),s}renderCanvas(){if(O(this.canvas),!this.schema||!this.form){this.renderFormsList();return}if(this.tab!=="build"){this.canvas.append(this.renderTabCanvas());return}const e=r("div",{class:"atfb-canvas__list",attrs:{"data-atfb-list":""}});this.schema.fields.length||e.append(r("div",{class:"atfb-placeholder",text:$e("emptyCanvas","Drag a field from the left to begin.")})),this.schema.fields.forEach((t,n)=>{e.append(this.renderFieldCard(t,n))});const s=r("div",{class:"atfb-canvas__inner",children:[r("p",{class:"atfb-shortcode",text:this.form.shortcode,title:"Paste this anywhere to place the form"}),e]});this.canvas.append(s),this.registerCanvasTarget(e),this.paintLogicMap(s),this.paintCanvasTheme()}prefillControl(e,s){const t=e.prefill.startsWith("query:"),n=Ce.some(v=>v.value===e.prefill),a=t?"query":n&&e.prefill||(e.prefill?"custom":""),o=r("div",{class:"atfb-prefill__detail"}),l=r("p",{class:"atfb-row__hint atfb-prefill__preview"}),d=v=>{if(o.replaceChildren(),l.replaceChildren(),v==="query"){const g=e.prefill.startsWith("query:")?e.prefill.slice(6):"";o.append(w(g,T=>{const x=T.trim();s("prefill",x?`query:${x}`:""),c(`query:${x}`)},"utm_source"),r("p",{class:"atfb-row__hint",text:"The name of the parameter in the link people arrive on."}))}v==="custom"&&o.append(w(e.prefill,g=>{s("prefill",g),c(g)},"myplugin:something"),r("p",{class:"atfb-row__hint",text:"For a source another plugin has added through atf_resolve_prefill."})),c(e.prefill)},c=v=>{if(l.replaceChildren(),!v)return;if(v.startsWith("query:")){const T=v.slice(6);T&&(l.textContent=`A visit to …/your-page/?${T}=abc opens the form with “abc” in it.`);return}const g=Ce.find(T=>T.value===v)?.tag;g&&we(this.form?.id??0).then(T=>{for(const x of T)for(const L of x.items)if(L.tag===g){const F=v.startsWith("user:");if(!L.sample){l.textContent="Empty unless the visitor is signed in.";return}l.textContent=F?`Opens with “${L.sample}” for you — empty for a visitor who is not signed in.`:`Opens with “${L.sample}”.`;return}})};d(a);const h=r("select",{class:"atfb-input atfb-select",on:{change:v=>{const g=v.target.value;s("prefill",g==="query"||g==="custom"?"":g),d(g)}}});h.append(r("option",{value:"",text:"Nothing — leave it empty",attrs:{selected:a===""}}));for(const v of fs){const g=document.createElement("optgroup");g.label=v;for(const T of Ce.filter(x=>x.group===v))g.append(r("option",{value:T.value,text:T.label,attrs:{selected:T.value===a}}));h.append(g)}const k=document.createElement("optgroup");return k.label="From the link they arrived on",k.append(r("option",{value:"query",text:"A parameter in the web address",attrs:{selected:a==="query"}})),h.append(k,r("option",{value:"custom",text:"Something else (advanced)",attrs:{selected:a==="custom"}})),m("Pre-fill this with",r("div",{class:"atfb-prefill",children:[h,o,l]}),"What the box already contains when the form opens. They can still change it.")}renderCondition(e){const s=e.some(t=>t.kind==="field"&&t.missing);return r("span",{class:`atfb-cond${s?" is-broken":""}`,attrs:{"aria-label":We(e)},children:[M("randomize"),...e.map(t=>this.renderConditionToken(t))]})}renderConditionToken(e){return e.kind==="field"&&!e.missing?r("button",{class:"atfb-cond__chip atfb-cond__chip--field",type:"button",text:e.text,title:"Go to this question",on:{click:n=>{n.stopPropagation(),this.selectField(e.fieldId),this.canvas.querySelector(`[data-atfb-card="${CSS.escape(e.fieldId)}"]`)?.scrollIntoView({block:"nearest",behavior:"smooth"})}}}):r("span",{class:{verb:"atfb-cond__verb",field:"atfb-cond__chip atfb-cond__chip--missing",operator:"atfb-cond__op",value:"atfb-cond__chip atfb-cond__chip--value",join:"atfb-cond__join"}[e.kind],text:e.text})}section(e,s,t,n=!1){const a=r("details",{class:"atfb-section",attrs:{open:this.openSections.get(e)??n},children:[r("summary",{text:s}),...t]});return a.addEventListener("toggle",()=>this.openSections.set(e,a.open)),a}logicMapButton(){const e=be(this.schema?.fields??[]).length>0,s=E(this.logicMapOn?"Hide logic":"Show logic",()=>{this.logicMapOn=!this.logicMapOn,St(it,this.logicMapOn?"on":"off"),this.renderBar(),this.renderCanvas()},this.logicMapOn?"primary":"secondary","randomize");return s.title="Draw a line from each question to the ones it decides.",s.hidden=!e,s}paintLogicMap(e){this.logicMap?.destroy(),this.logicMap=null;const s=this.schema?.fields??[],t=be(s);if(!t.length||!this.logicMapOn)return;e.classList.add("has-logicmap");const n=new Nt(e);n.setEdges(t),n.highlight(this.selected??""),this.logicMap=n,e.addEventListener("pointerover",a=>{const o=a.target.closest("[data-atfb-card]");n.highlight(o?.dataset.atfbCard??this.selected??"")}),e.addEventListener("pointerleave",()=>n.highlight(this.selected??""))}renderFieldCard(e,s){const t=this.config?.fieldTypes.find(c=>c.type===e.type),n=this.selected===e.id,a=this.schema?.fields??[],o=Ft(e,a),l=Mt(a).get(e.id)??0,d=r("div",{class:`atfb-card${n?" is-selected":""}`,attrs:{"data-atfb-card":e.id,"data-index":s,tabindex:"0",role:"button","aria-pressed":n,"aria-label":`${e.label||t?.label||e.type}, ${s+1} of ${this.schema?.fields.length??0}`},children:[r("div",{class:"atfb-card__grip",attrs:{"aria-hidden":"true"},children:[M("menu")]}),r("div",{class:"atfb-card__body",children:[r("div",{class:"atfb-card__head",children:[M(t?.icon??"dashicons-forms"),r("span",{class:"atfb-card__type",text:t?.label??e.type}),this.requiredToggle(e),l?r("span",{class:"atfb-badge atfb-badge--controls",text:l===1?"controls 1 field":`controls ${l} fields`,title:"Other questions appear or disappear based on this answer."}):null]}),Ht(e,t,{edit:c=>{const h=this.liveField(e.id);h&&(c(h),this.markDirty(),this.syncInspector(h))},restructure:c=>{const h=this.liveField(e.id);h&&(this.snapshot(),c(h),this.markDirty(),this.renderCanvas(),this.renderInspector())}}),o.length?this.renderCondition(o):null]}),r("div",{class:"atfb-card__actions",children:[this.cardAction("admin-page","Duplicate",()=>this.duplicateField(e.id)),this.cardAction("trash","Delete",()=>void this.deleteField(e.id))]})]});return d.addEventListener("click",c=>{c.target.closest(".atfb-card__actions")||K().recentlyEndedDrag()||this.selectField(e.id)}),d.addEventListener("keydown",c=>{if(c.key==="Enter"||c.key===" "){c.preventDefault(),this.selectField(e.id);return}c.altKey&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&(c.preventDefault(),this.moveField(e.id,c.key==="ArrowUp"?s-1:s+1),window.requestAnimationFrame(()=>{this.canvas.querySelector(`[data-atfb-card="${CSS.escape(e.id)}"]`)?.focus()})),(c.key==="Delete"||c.key==="Backspace")&&(c.preventDefault(),this.deleteField(e.id))}),d.addEventListener("pointerdown",c=>{c.target.closest(".atfb-card__actions")||K().start({payload:Oe(ee,d,{fieldId:e.id,field:e,isNew:!1},c),origin:c})}),d}requiredToggle(e){return r("button",{class:`atfb-req${e.required?" is-on":""}`,type:"button",text:e.required?"Required":"Optional",title:e.required?"This must be answered. Click to make it optional.":"Click to make this required.",attrs:{"aria-pressed":e.required?"true":"false"},on:{pointerdown:t=>t.stopPropagation(),click:t=>{t.stopPropagation(),e.required=!e.required,this.markDirty(),this.renderCanvas(),this.renderInspector()}}})}cardAction(e,s,t){return r("button",{class:"atfb-card__action",type:"button",title:s,attrs:{"aria-label":s},on:{click:n=>{n.stopPropagation(),t()}},children:[M(e)]})}registerCanvasTarget(e){this.canvasTarget?.(),this.canvasTarget=null;const s=r("div",{class:"atfb-marker",attrs:{"aria-hidden":"true"}}),t=K().registerDropTarget({id:`atfb-canvas-${this.form?.id??0}`,element:e,accept:a=>a.type===ee,onEnter:()=>e.classList.add("is-dropping"),onLeave:()=>{e.classList.remove("is-dropping"),s.remove()},onDrop:(a,o)=>{e.classList.remove("is-dropping"),s.remove();const l=a.payload.data,d=l.fieldId?this.canvas.querySelector(`[data-atfb-card="${CSS.escape(l.fieldId)}"]`):null,c=qe(e,".atfb-card",o.clientY,d??void 0);if(l.isNew&&l.fieldType){this.addField(l.fieldType,c);return}if(l.fieldId&&this.schema?.fields.some(h=>h.id===l.fieldId)){this.moveField(l.fieldId,c);return}l.field&&this.insertField({...l.field,id:""},c)}}),n=a=>{const o=a.detail;if(o?.payload?.type!==ee||!e.classList.contains("is-dropping"))return;const l=o.payload.data?.fieldId?this.canvas.querySelector(`[data-atfb-card="${CSS.escape(o.payload.data.fieldId)}"]`):null,d=o.clientY??0,c=qe(e,".atfb-card",d,l??void 0),h=Array.from(e.querySelectorAll(".atfb-card")).filter(k=>k!==l);c>=h.length?e.append(s):h[c].before(s)};document.addEventListener("os.drag.move",n),this.canvasTarget=()=>{t(),document.removeEventListener("os.drag.move",n)}}addField(e,s){const t=this.config?.fieldTypes.find(a=>a.type===e);if(!t||!this.schema)return;const n={id:this.nextFieldId(),type:e,label:t.input?t.label:"",placeholder:"",hint:"",required:!1,width:"full",cssClass:"",default:"",choices:t.choices?[{label:"First choice",value:"first"},{label:"Second choice",value:"second"}]:[],logic:{enabled:!1,action:"show",match:"all",rules:[]},messages:{},prefill:"",...t.settings};this.insertField(n,s)}insertField(e,s){if(!this.schema)return;e.id||(e.id=this.nextFieldId()),this.snapshot();const t=s===void 0?this.schema.fields.length:Math.max(0,Math.min(s,this.schema.fields.length));this.schema.fields.splice(t,0,e),this.selected=e.id,this.markDirty(),this.renderCanvas(),this.renderInspector(),window.requestAnimationFrame(()=>{this.canvas.querySelector(`[data-atfb-card="${CSS.escape(e.id)}"]`)?.focus()})}moveField(e,s){if(!this.schema)return;const t=ot(this.schema.fields,e,s);if(!t)return;this.snapshot();const[n]=this.schema.fields.splice(t.from,1);this.schema.fields.splice(t.to,0,n),this.markDirty(),this.renderCanvas()}duplicateField(e){if(!this.schema)return;const s=this.schema.fields.findIndex(n=>n.id===e);if(s<0)return;const t=JSON.parse(JSON.stringify(this.schema.fields[s]));t.id=this.nextFieldId(),this.insertField(t,s+1)}async deleteField(e){if(!this.schema)return;const s=this.schema.fields.filter(n=>n.logic?.rules?.some(a=>a.field===e)),t=s.length?`Delete this field? ${s.length} other field${s.length===1?"":"s"} use it in a condition, and those conditions will stop working.`:$e("confirmDelete","Delete this? It cannot be undone.");await fe(t,"Delete field")&&(this.snapshot(),this.schema.fields=this.schema.fields.filter(n=>n.id!==e),this.selected===e&&(this.selected=null),this.markDirty(),this.renderCanvas(),this.renderInspector())}selectField(e){this.selected=e;for(const s of this.canvas.querySelectorAll("[data-atfb-card]")){const t=s.dataset.atfbCard===e;s.classList.toggle("is-selected",t),s.setAttribute("aria-pressed",t?"true":"false")}this.logicMap?.highlight(e),this.renderInspector()}nextFieldId(){const e=new Set((this.schema?.fields??[]).map(t=>t.id));let s=e.size+1;for(;e.has(`f${s}`);)s++;return`f${s}`}nextEntryId(e,s){const t=new Set(s.map(a=>a.id));let n=s.length+1;for(;t.has(`${e}${n}`);)n++;return`${e}${n}`}renderTypeSettings(e,s,t,n){for(const a of t){const o=nt[a];o&&(this.inspector.append(at(e,o,n)),o.also&&this.inspector.append(at(e,{...o,key:o.also.key,label:o.also.label,hint:o.also.hint},n)))}t.includes("rows")&&e.type!=="likert"&&this.inspector.append(m("Lines tall",R(String(e.rows??""),a=>n("rows",a)))),t.includes("rows")&&e.type==="likert"&&this.inspector.append(this.renderStatementList(e,n)),t.includes("parts")&&this.inspector.append(this.renderPartsEditor(e,s,n)),t.includes("default")&&!["files","object"].includes(s?.value??"")&&this.inspector.append(this.renderDefaultControl(e,s,n))}renderStatementList(e,s){const t=Array.isArray(e.rows)?e.rows:[];return m("Statements",re(t.map(n=>n.label??"").join(` -`),n=>s("rows",rt(t,n)),5),"One per line. Each becomes a row of the matrix.")}renderPartsEditor(e,s,t){const n=s?.parts??[],a=Array.isArray(e.parts)?e.parts:n.map(l=>l.key),o=n.map(l=>A(l.label,a.includes(l.key),d=>{const c=n.map(h=>h.key).filter(h=>h===l.key?d:a.includes(h));t("parts",c.length?c:[l.key])}));return r("div",{class:"atfb-section",children:[r("h4",{class:"atfb-section__title",text:"Parts to ask for"}),...o]})}renderDefaultControl(e,s,t){const n="Filled in before they start. They can change it.";return e.type==="switch"||e.type==="consent"?A("On by default",!!e.default,a=>t("default",a)):s?.choices&&(e.choices??[]).length?m("Default answer",D(String(e.default??""),[{value:"",label:"Nothing chosen"},...(e.choices??[]).map(a=>({value:String(a.value),label:a.label||String(a.value)}))],a=>t("default",a)),n):m("Default answer",w(String(e.default??""),a=>t("default",a)),n)}renderChoicesEditor(e,s){const t=e.choices??[],n=o=>this.liveField(e.id)?.choices?.[o],a=r("div",{class:"atfb-choices"});return t.forEach((o,l)=>{const d=r("div",{class:"atfb-choice-row",children:[e.type==="image_choice"?this.choiceImageWell(o,l,e):null,H(w(o.label,c=>{const h=n(l);if(!h)return;const k=!h.value||h.value===h.label;h.label=c,k&&(h.value=c),this.markDirty();const v=this.liveField(e.id);v&&this.syncCanvas(v)}),`choice:${l}:label`),H(w(o.value,c=>{const h=n(l);h&&(h.value=c,this.markDirty())},"value"),`choice:${l}:value`),e.type==="quiz"||o.points!==void 0?R(String(o.points??""),c=>{const h=n(l);h&&(h.points=c===""?void 0:Number(c),this.markDirty())}):R(String(o.price??""),c=>{const h=n(l);h&&(h.price=c===""?void 0:Number(c),this.markDirty())}),r("button",{class:"atfb-card__action",type:"button",attrs:{"aria-label":`Remove ${o.label}`},on:{click:()=>{const c=this.liveField(e.id);c&&((c.choices??[]).splice(l,1),s("choices",c.choices),this.renderInspector())}},children:[M("trash")]})]});a.append(d)}),r("div",{class:"atfb-section",children:[r("h4",{text:"Choices"}),r("p",{class:"atfb-hint",text:e.type==="quiz"?"Label, value, points.":"Label, value, and a price for calculations."}),a,E("Add choice",()=>{const o=this.liveField(e.id);if(!o)return;const l=o.choices??[];l.push({label:"",value:""}),s("choices",l),this.renderInspector()},"ghost","plus-alt2"),e.type==="quiz"?m("Correct answer",D(String(e.correct??""),[{value:"",label:"—"},...t.map(o=>({value:o.value,label:o.label}))],o=>s("correct",o))):null]})}choiceImageWell(e,s,t){const n=r("div",{class:`atfb-well${e.image?" has-image":""}`,attrs:{"data-choice":s,"aria-label":`Image for ${e.label||`choice ${s+1}`}`},children:[e.image?r("span",{class:"atfb-well__id",text:`#${e.image}`}):M("format-image")]}),a=K().registerDropTarget({id:`atfb-well-${t.id}-${s}`,element:n,accept:o=>us.includes(o.type),onEnter:()=>n.classList.add("is-dropping"),onLeave:()=>n.classList.remove("is-dropping"),onDrop:o=>{n.classList.remove("is-dropping");const l=o.payload.data,d=Number(l.attachmentId??l.id??l.file?.id??0);if(!d){N("That is not an image this field can use","","error");return}const c=this.liveField(t.id)?.choices?.[s];c&&(c.image=d,this.markDirty(),this.renderInspector())}});return this.teardowns.push(a),n.addEventListener("click",()=>{const o=this.liveField(t.id)?.choices?.[s];o?.image&&(o.image=void 0,this.markDirty(),this.renderInspector())}),n}renderValidationSection(e,s,t){const n=[],a=[];s.includes("minlength")&&a.push(["minlength","Minimum characters"],["maxlength","Maximum characters"]),s.includes("min")?a.push(["min","Minimum"],["max","Maximum"]):s.includes("max")&&a.push(["max","Highest"]),s.includes("step")&&a.push(["step","Steps of"]),s.includes("mindate")&&a.push(["minDate","Earliest date"],["maxDate","Latest date"]),s.includes("mintime")&&a.push(["minTime","Earliest time"],["maxTime","Latest time"]);for(const[l,d]of a)n.push(m(d,w(String(e[l]??""),c=>t(l,c))));s.includes("pattern")&&n.push(m("Pattern",w(String(e.pattern??""),l=>t("pattern",l)),"A regular expression, without slashes.")),s.includes("unique")&&n.push(A("No two people may submit the same value",!!e.unique,l=>t("unique",l)));const o=e.messages??{};return s.includes("required")&&n.push(m("Message when required",w(o.required??"",l=>{o.required=l,t("messages",o)}),"Leave empty for the default wording.")),n.length?this.section(`validation:${e.id}`,"Validation",n):r("div",{class:"atfb-section is-empty"})}renderLogicSection(e,s){const t=e.logic,n=()=>this.liveField(e.id)?.logic,a=(this.schema?.fields??[]).filter(l=>l.id!==e.id&&l.type!=="page_break"),o=r("div",{class:"atfb-rules"});return t.rules.forEach((l,d)=>{o.append(r("div",{class:"atfb-rule",children:[D(l.field,a.map(c=>({value:c.id,label:c.label||c.id})),c=>{const h=n()?.rules[d];h&&(h.field=c,this.markDirty())}),D(l.operator,Object.entries(this.config?.operators??{}).map(([c,h])=>({value:c,label:h})),c=>{const h=n()?.rules[d];h&&(h.operator=c,this.markDirty())}),w(l.value,c=>{const h=n()?.rules[d];h&&(h.value=c,this.markDirty())}),r("button",{class:"atfb-card__action",type:"button",attrs:{"aria-label":"Remove this rule"},on:{click:()=>{const c=n();c&&(c.rules.splice(d,1),s("logic",c),this.renderInspector())}},children:[M("trash")]})]}))}),this.section(`logic:${e.id}`,"Conditional logic",[A("Only show this field sometimes",t.enabled,l=>{const d=n();d&&(d.enabled=l,s("logic",d),this.renderInspector())}),t.enabled?r("div",{children:[r("div",{class:"atfb-rule-head",children:[D(t.action,[{value:"show",label:"Show"},{value:"hide",label:"Hide"}],l=>{const d=n();d&&(d.action=l,s("logic",d))}),r("span",{text:"this field when"}),D(t.match,[{value:"all",label:"all"},{value:"any",label:"any"}],l=>{const d=n();d&&(d.match=l,s("logic",d))}),r("span",{text:"of these match:"})]}),o,E("Add rule",()=>{const l=n();l&&(l.rules.push({field:a[0]?.id??"",operator:"is",value:""}),s("logic",l),this.renderInspector())},"ghost","plus-alt2")]}):null],t.enabled)}renderTabCanvas(){return this.schema?this.tab==="theme"?Je({themes:this.themes,tokens:this.config?.tokens??[],activeSlug:this.schema.settings.theme,overrides:this.schema.settings.themeOverrides,onTheme:e=>{this.schema.settings.theme=e,this.markDirty()},onOverride:(e,s)=>{s===""?delete this.schema.settings.themeOverrides[e]:this.schema.settings.themeOverrides[e]=s,this.markDirty()},onOverridesReplaced:e=>{this.schema.settings.themeOverrides={...e},this.markDirty()},previewFor:(e,s)=>this.previewHtml(e,s),onThemesChanged:e=>{this.themes=e}}):this.tab==="settings"?this.renderSettingsPane():this.tab==="notify"?this.renderNotificationsPane():this.renderConfirmationsPane():r("div")}async paintCanvasTheme(){if(!this.form||!this.schema)return;const e=this.schema.settings.theme,s=JSON.stringify([e,this.schema.settings.themeOverrides]);if(s!==this.canvasThemeSignature){this.canvasThemeSignature=s;try{const t=await this.previewHtml(e,this.schema.settings.themeOverrides??{});this.root.classList.toggle("atfb--dark-form",/atf-is-dark/.test(t));const n=/