diff --git a/assets/css/builder.css b/assets/css/builder.css index 923ab2f..062c45f 100644 --- a/assets/css/builder.css +++ b/assets/css/builder.css @@ -1359,23 +1359,31 @@ overflow: hidden; } +/* Two stacked rows, not two side-by-side columns: the heading and the actions + share the first, and the picker strip gets the whole width of the second. + Sitting beside the strip, the actions took ~280px off the row the chips + scroll in — enough that the last chip was always cut down the middle, which + reads as a broken card rather than as an invitation to scroll. */ .atf-studio__top { - display: flex; - align-items: flex-end; - gap: var( --atfb-gap ); + display: grid; + gap: 8px; padding: 12px 14px; border-block-end: 1px solid var( --atfb-border ); background: var( --atfb-surface ); min-inline-size: 0; } -.atf-studio__picker { +.atf-studio__topbar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px var( --atfb-gap ); min-inline-size: 0; - flex: 1 1 auto; } .atf-studio__heading { - margin: 0 0 8px; + margin: 0; font-size: 12px; font-weight: 700; text-transform: uppercase; @@ -1423,17 +1431,22 @@ /* --- The picker strip ----------------------------------------------------- */ /* A single scrolling row. Ten chips do not fit on a narrow window and wrapping - them would put the strip back to the height the column layout had. */ + them would put the strip back to the height the column layout had. + Snapping to chip boundaries is what keeps a scroll from *stopping* on half a + card — the strip is allowed to run out of room, but never to look cut. */ .atfs-themes { display: flex; gap: 8px; overflow-x: auto; padding-block-end: 4px; scrollbar-width: thin; + scroll-snap-type: x proximity; + scroll-padding-inline: 2px; } .atfs-theme { flex: 0 0 auto; + scroll-snap-align: start; inline-size: 92px; display: grid; gap: 5px; @@ -1451,12 +1464,14 @@ block-size: 30px; } +/* On the heading's line now, so nothing has to be nudged up off the strip's + scrollbar gutter. */ .atfs__actions { display: flex; flex-wrap: wrap; gap: 6px; flex: 0 0 auto; - margin-block-end: 4px; + margin-block-end: 0; } .atfs-controls__body { diff --git a/assets/js/builder.js b/assets/js/builder.js index a9a62fb..c81f9a6 100644 --- a/assets/js/builder.js +++ b/assets/js/builder.js @@ -2106,22 +2106,26 @@ var allTerrainFormsBuilder = function(exports) { el("div", { class: "atf-studio__top", children: [ + // The actions share the heading's line, not the strip's. + // Beside the strip they took the width the last chip needed + // and cut it down the middle, which reads as a broken card + // rather than as "there is more, scroll". el("div", { - class: "atf-studio__picker", + class: "atf-studio__topbar", children: [ el("h2", { class: "atf-studio__heading", text: "Theme" }), - swatches + el("div", { + class: "atfs__actions", + children: [ + button("Save as a theme", () => void saveAsTheme(), "primary"), + button("Export", () => void exportTheme()), + button("Import", importTheme), + deleteButton + ] + }) ] }), - el("div", { - class: "atfs__actions", - children: [ - button("Save as a theme", () => void saveAsTheme(), "primary"), - button("Export", () => void exportTheme()), - button("Import", importTheme), - deleteButton - ] - }) + swatches ] }), el("div", { diff --git a/assets/js/builder.min.js b/assets/js/builder.min.js index 4a27c31..033bfed 100644 --- a/assets/js/builder.min.js +++ b/assets/js/builder.min.js @@ -1,3 +1,3 @@ -var allTerrainFormsBuilder=function(H){"use strict";class dt{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,x=0;const g=()=>{document.removeEventListener("pointermove",L),document.removeEventListener("pointerup",B),document.removeEventListener("pointercancel",z),document.removeEventListener("keydown",ae),window.removeEventListener("blur",z),d?.remove(),d=null,s.source.classList.remove("atf-is-dragging"),c?.onLeave?.(m),c=null,this.active=null,this.lastEndMs=Date.now()},m={payload:s,isFinished:()=>l,cancel:(E="caller")=>{l||(l=!0,g(),e.onCancel?.(E))}},_=E=>{o=!0,s.source.classList.add("atf-is-dragging");const A=s.source.getBoundingClientRect();h=s.ghost?.offsetX??n-A.left,x=s.ghost?.offsetY??a-A.top,d=s.ghost?.element??s.source.cloneNode(!0),d.classList.add("atf-drag-ghost"),d.style.width=`${A.width}px`,document.body.appendChild(d),w(E)},w=E=>{d&&(d.style.transform=`translate3d(${E.clientX-h}px, ${E.clientY-x}px, 0)`)},L=E=>{if(l)return;if(!o){if(Math.hypot(E.clientX-n,E.clientY-a)<4)return;_(E)}w(E);const A=this.hitTest(E.clientX,E.clientY);A!==c&&(c?.onLeave?.(m),c=A,c?.onEnter?.(m))},B=E=>{if(l)return;if(!o){l=!0,g(),e.onClickOnly?.();return}const A=c;if(l=!0,g(),A&&A.accept(s)){e.onCommit?.(A),A.onDrop(m,{clientX:E.clientX,clientY:E.clientY});return}e.onCancel?.(A?"rejected":"no-target")},z=()=>m.cancel("pointercancel"),ae=E=>{E.key==="Escape"&&m.cancel("escape")};return document.addEventListener("pointermove",L),document.addEventListener("pointerup",B),document.addEventListener("pointercancel",z),document.addEventListener("keydown",ae),window.addEventListener("blur",z),this.active=m,m}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=ht(a.element);if(l>n){t=a,n=l;continue}l===n&&t&&ut(a.element,t.element)&&(t=a)}return t}}function ht(i){let e=0,s=i;for(;s;)e++,s=s.parentElement;return e}function ut(i,e){return(e.compareDocumentPosition(i)&Node.DOCUMENT_POSITION_FOLLOWING)!==0}function le(){return window.wp?.os??null}let ce=null;function Y(){const i=le();return i?.dragManager?i.dragManager:(ce||(ce=new dt),ce)}function pt(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 Te(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 $e(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 ee(l,o.status,d)}if(o.status!==204)return await o.json()}const N=i=>de(i);async function ft(i){if(!I?.wpRestUrl)throw new ee("AllTerrain Forms is not configured on this page.",0);const e=I.nonce?{"X-WP-Nonce":I.nonce}:{},s=le(),t=Ae(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 ee(`Request failed with status ${n.status}.`,n.status);return await n.json()}function mt(i){if(!i||!i.includes("&"))return i;const e=document.createElement("textarea");return e.innerHTML=i,e.value}const W=(i,e)=>de(i,{method:"POST",body:JSON.stringify(e)}),te=i=>de(i,{method:"DELETE"});function De(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}`:""}const C={config:()=>N("/config"),listForms:()=>N("/forms"),getForm:i=>N(`/forms/${i}`),createForm:i=>W("/forms",i),updateForm:(i,e)=>W(`/forms/${i}`,e),duplicateForm:i=>W(`/forms/${i}/duplicate`,{}),deleteForm:i=>te(`/forms/${i}`),preview:(i,e)=>W(`/forms/${i}/preview`,e),pages:()=>ft("wp/v2/pages?per_page=100&status=publish&orderby=title&order=asc&_fields=id,title").then(i=>i.map(e=>({id:e.id,title:mt(e.title?.rendered??"")||`#${e.id}`}))),mergeTags:i=>N(`/forms/${i}/merge-tags`).then(e=>e.groups),analytics:(i,e="")=>N(`/forms/${i}/analytics${e?`?dimension=${encodeURIComponent(e)}`:""}`),demoStatus:()=>N("/demo"),demoSeed:i=>W("/demo",i?{count:i}:{}),demoRemove:()=>te("/demo"),listEntries:i=>N(`/entries${De(i)}`),getEntry:i=>N(`/entries/${i}`),updateEntry:(i,e)=>W(`/entries/${i}`,e),deleteEntry:i=>te(`/entries/${i}`),exportEntries:i=>N(`/entries/export${De(i)}`),listThemes:()=>N("/themes"),saveTheme:i=>W("/themes",i),deleteTheme:i=>te(`/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 D(i){i.replaceChildren()}function q(i){return r("span",{class:`dashicons ${i.startsWith("dashicons-")?i:`dashicons-${i}`}`,attrs:{"aria-hidden":"true"}})}function p(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 y(i,e,s=""){return r("input",{class:"atfb-input",type:"text",value:i,placeholder:s,on:{input:t=>e(t.target.value)}})}function P(i,e){if(J("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 se(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 $(i,e,s){if(J("os-select")&&J("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 T(i,e,s){if(J("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 S(i,e,s="secondary",t){const n=[t?q(t):null,r("span",{text:i})];if(J("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 J(i){return typeof customElements<"u"&&!!customElements.get(i)}const bt=["os-button","os-checkbox-label","os-number-field","os-select","os-option","os-segmented","os-segment","os-color-field","os-empty-state"];let ie=null;function gt(){if(ie)return ie;const i=window.wp?.os;return ie=i?.loadComponents?i.loadComponents(bt).catch(()=>{}):Promise.resolve(),ie}async function he(i,e=""){const s=window.wp?.os;return s?.confirm?s.confirm({title:e,message:i,danger:!0}):window.confirm(i)}function M(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 vt(i){let e=0,s;return(...t)=>{s=t,!e&&(e=window.requestAnimationFrame(()=>{e=0,i(...s)}))}}function Fe(i,e){let s=0;return(...t)=>{window.clearTimeout(s),s=window.setTimeout(()=>i(...t),e)}}function yt(i){try{return window.localStorage.getItem(i)??""}catch{return""}}function wt(i,e){try{window.localStorage.setItem(i,e)}catch{}}function Ie(){const i=[window];try{window.parent&&window.parent!==window&&i.push(window.parent)}catch{}return i}function xt(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 kt=4e3,_t=100;function St(i,e){const s=Date.now()+kt,t=()=>{const n=xt(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&&Tt(s);for(const n of Ie())if(n.wp?.os?.openWindow?.(e,{source:"handoff",params:t})){window.setTimeout(()=>St(n,e),0);return}}function Lt(){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 Ie())if(t.wp?.os?.openWindow?.(s,{source:"handoff"}))return})}const Ct="allterrain-forms/requested-form";function Tt(i){try{window.sessionStorage.setItem(Ct,String(i))}catch{}}const qe={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"},Oe=["empty","not_empty"];function Me(i,e){const s=i.find(t=>t.id===e);return s?s.label||"an untitled question":null}function Ne(i,e,s){return i.find(a=>a.id===e)?.choices?.find(a=>a.value===s)?.label||s}function $t(i,e){const s=qe[i.operator]??String(i.operator);if(Oe.includes(i.operator))return s;const t=Ne(e,i.field,i.value);return`${i.operator==="is"?"":`${s} `}${t!==""?t:"(nothing)"}`}function Pe(i,e){const s=Me(e,i.field),t=qe[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(Oe.includes(i.operator))return n;const a=Ne(e,i.field,i.value);return n.push({kind:"value",text:a!==""?a:"(nothing)"}),n}function At(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(...Pe(n,e))}),t}function Re(i){return i.map(e=>e.text).join(" ")}function Dt(i,e){return Re(Pe(i,e))}function ue(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:Dt(n,i),short:$t(n,i),action:t.action,broken:Me(i,n.field)===null})}return e}function Ft(i){const e=new Map,s=new Set;for(const t of ue(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 Be=10,He=22,G="http://www.w3.org/2000/svg";class It{constructor(e){this.edges=[],this.teardowns=[],this.frame=0,this.host=e,this.svg=document.createElementNS(G,"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-Be-Math.max(o,d)),x=22+a*11+Math.min(22,Math.abs(c-l)/8),g=Math.max(12,Math.min(x,h*.4)),m=document.createElementNS(G,"path");m.setAttribute("d",`M ${o} ${l} C ${o+g} ${l}, ${d+g} ${c}, ${d} ${c}`),m.setAttribute("class",`atfb-logicmap__path is-${e.action}${e.broken?" is-broken":""}`),m.dataset.from=e.from,m.dataset.to=e.to;const _=document.createElementNS(G,"title");_.textContent=e.label,m.append(_);const w=document.createElementNS(G,"circle");w.setAttribute("cx",String(d)),w.setAttribute("cy",String(c)),w.setAttribute("r","3.5"),w.setAttribute("class",`atfb-logicmap__dot is-${e.action}${e.broken?" is-broken":""}`),w.dataset.from=e.from,w.dataset.to=e.to,this.svg.append(m,w);const L=document.createElementNS(G,"text");L.setAttribute("x",String(n.width-Be)),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>He?`${e.short.slice(0,He-1)}…`:e.short;const B=document.createElementNS(G,"title");B.textContent=e.label,L.append(B),this.svg.append(L)}}const qt={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 Ot(i){return qt[i]??"text"}function je(i,e){const s=/^choice:(\d+):(label|value)$/.exec(e);return String(s?i.choices?.[Number(s[1])]?.[s[2]]??"":i[e]??"")}function j(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 Mt(i){const e=r("input",{class:"atf-choice__input",type:i==="checkboxes"||i==="multiselect"?"checkbox":"radio"});return e.disabled=!0,e}function Nt(i,e,s){const t=Ot(i.type),n=j({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,Rt(i,e,t,s),Pt(i,e,s)];return r("div",{class:"atfb-preview atf-form",children:[r("div",{class:`atf-field atf-field--${i.type}`,children:a})]})}function Pt(i,e,s){if(!e?.supports.includes("hint"))return null;const t=j({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 Rt(i,e,s,t){switch(s){case"text":return pe(i,"atf-input",t);case"textarea":return pe(i,"atf-input atf-textarea",t,!0);case"select":return r("div",{class:"atfb-preview__select",children:[pe(i,"atf-input atf-select",t)]});case"options":return Ht(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})(),j({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 jt(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"?Bt(i,t):null]})}}function pe(i,e,s,t=!1){const n=j({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 fe(i,e,s,t,n,a){return r("span",{class:`atf-button ${s} atfb-preview__button`,children:[j({value:i,placeholder:e,class:"atfb-preview__button-text",bind:t,onInput:o=>n.edit(l=>a(l,o))})]})}function Bt(i,e){return fe(String(i.addLabel??""),"Add another","atf-button--secondary","addLabel",e,(s,t)=>{s.addLabel=t})}function Ht(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:[Mt(i.type),j({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 jt(i,e,s){return i.type==="heading"?j({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:[j({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:[fe(String(i.prevLabel??""),"Back","atf-button--secondary","prevLabel",s,(t,n)=>{t.prevLabel=n}),fe(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 me=new Map;function be(i){let e=me.get(i);return e||(e=C.mergeTags(i).catch(()=>[]),me.set(i,e)),e}function Ut(i){me.delete(i)}function Wt(i){const e=new Map;for(const s of i)for(const t of s.items)e.set(t.tag,t);return e}function Yt(i,e){const s=Wt(e);return i.replace(/\{[a-z_]+(?::[^}]*)?\}/gi,t=>{const n=s.get(t.toLowerCase());return n?n.sample:t})}function Gt(i){return/\{[a-z_]+(?::[^}]*)?\}/i.test(i)}let U=null;function K(){U?.remove(),U=null}typeof document<"u"&&(document.addEventListener("pointerdown",i=>{const e=i.target;e?.closest(".atfb-tagpick__open")||U&&!U.contains(e)&&K()}),document.addEventListener("keydown",i=>{i.key==="Escape"&&U&&(K(),i.stopPropagation())}));function zt(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 Xt(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 Jt(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),K()}},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 Ue(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:[q("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(!Gt(i.value)){n.textContent="",n.hidden=!0;return}be(e.formId).then(o=>{n.hidden=!1,n.replaceChildren(r("span",{class:"atfb-taggable__preview-label",text:"Reads as"}),r("span",{text:Yt(i.value,o)}))})}};return i.addEventListener("input",a),a(),s.addEventListener("click",o=>{if(o.stopPropagation(),U&&t.contains(U)){K();return}K(),be(e.formId).then(l=>{const d=Jt(l,c=>{zt(i,c),a()});t.append(d),U=d,(window.innerHeight-d.getBoundingClientRect().topXt(t))&&d.classList.add("atfb-tagpick--above"),d.querySelector(".atfb-tagpick__search")?.focus()})}),t}function We(i,e){const s=parseFloat(String(i??""));return Number.isFinite(s)?s:e}function Ye(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:ge.map(({value:i,label:e})=>({value:i,label:e})),owns:["radius-field","radius-button","radius-card","radius-check"],read:i=>Ye(We(i["radius-field"],4),ge),apply:i=>{const e=ge.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:ve.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=>Ye(We(i["pad-field-y"],9),ve),apply:i=>{const e=ve.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:Kt,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:Vt,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:Qt,owns:["label-position"],read:i=>i["label-position"]??"top",apply:i=>({"label-position":i})}]}function Zt(i){return Ge().find(e=>e.owns.includes(i))??null}function ze(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=Fe(async()=>{try{const u=await i.previewFor(e,s);a.innerHTML=u,document.dispatchEvent(new CustomEvent("atf-refresh"))}catch(u){D(a),a.append(r("p",{class:"atfb-error",text:u instanceof Error?u.message:"Preview failed."}))}},180),h=u=>s[u.token]!==void 0?s[u.token]:t.find(b=>b.slug===e)?.resolved?.[u.token]??u.default,x=()=>{D(d);for(const u of t){const f=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),x(),_(),w(),c(),ot()}}});d.append(f)}},g=()=>{const f={...t.find(b=>b.slug===e)?.resolved??{}};for(const[b,v]of Object.entries(s))f[b]=v;return f},m=(u,f)=>{const b=u.apply(f,g());for(const[v,k]of Object.entries(b))s[v]=k,i.onOverride(v,k);_(),w(),c()},_=()=>{D(l);const u=g();for(const f of Ge()){const b=f.read(u);let v;if(f.kind==="colour"){const k=r("input",{class:"atfs-color",type:"color",value:we(b),attrs:{"aria-label":f.label},on:{input:O=>m(f,O.target.value)}});v=r("div",{class:"atfs-color-row",children:[k,y(b,O=>m(f,O))]})}else v=r("div",{class:`atfs-segmented atfs-segmented--${f.kind}`,attrs:{role:"group","aria-label":f.label},children:(f.steps??[]).map(k=>r("button",{class:`atfs-segment${k.value===b?" is-on":""}`,type:"button",text:k.label,attrs:{"aria-pressed":k.value===b},on:{click:()=>m(f,k.value)}}))});l.append(r("div",{class:"atfs-dial",children:[r("div",{class:"atfs-dial__head",children:[r("span",{class:"atfs-dial__label",text:f.label}),r("span",{class:"atfs-dial__hint",text:f.hint})]}),v]}))}},w=()=>{D(o);const u=new Map;for(const b of i.tokens){const v=u.get(b.group)??[];v.push(b),u.set(b.group,v)}const f={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[b,v]of u)o.append(r("details",{class:"atfs-group",attrs:{open:b==="colour"},children:[r("summary",{text:f[b]??b}),...v.map(k=>L(k))]}))},L=u=>{const f=h(u),b=F=>{F===""?delete s[u.token]:s[u.token]=F,i.onOverride(u.token,F),c()};let v;if(u.control==="color"){const F=r("input",{class:"atfs-color",type:"color",value:we(f),attrs:{"aria-label":`${u.label} colour`},on:{input:X=>{const Z=X.target.value;re.value=Z,b(Z)}}}),re=y(f,X=>{F.value=we(X),b(X)});v=r("div",{class:"atfs-color-row",children:[F,re]})}else if(u.control==="select")v=$(f,(u.options??[]).map(F=>({value:F,label:F})),b);else if(u.control==="length"){const F=parseFloat(f)||0,re=u.unit??"px",X=u.token.includes("radius")?60:80,Z=r("input",{class:"atfs-range",type:"range",value:String(F),attrs:{min:"0",max:String(X),step:"1","aria-label":u.label},on:{input:oe=>{const ct=`${oe.target.value}${re}`;lt.value=ct,b(ct)}}}),lt=y(f,oe=>{Z.value=String(parseFloat(oe)||0),b(oe)});v=r("div",{class:"atfs-length-row",children:[Z,lt]})}else v=y(f,b);const k=p(u.label,v),O=Zt(u.token);return O&&(k.classList.add("is-dialled"),k.append(r("span",{class:"atfs-owned",text:O.label}))),s[u.token]!==void 0&&(k.classList.add("is-overridden"),k.append(r("button",{class:"atfs-reset",type:"button",text:"Reset",attrs:{"aria-label":`Reset ${u.label} to the theme's value`},on:{click:()=>{b(""),w()}}}))),k},B=async()=>{const u=t.find(v=>v.slug===e),f=u?`${u.label} (mine)`:"My theme",b=window.prompt("Name this theme",f);if(b)try{const v={};for(const O of i.tokens){const F=h(O);F!==O.default&&(v[O.token]=F)}const k=await C.saveTheme({label:b,tokens:v});t=[...t.filter(O=>O.slug!==k.slug),k],i.onThemesChanged(t),e=k.slug,n({}),i.onTheme(e),x(),w(),c(),M("Theme saved",k.label)}catch(v){M("Could not save the theme",v instanceof Error?v.message:"","error")}},z=async()=>{const u=t.find(f=>f.slug===e);if(u?.custom&&await he(`Delete “${u.label}”? Forms using it fall back to Clean.`,"Delete theme"))try{await C.deleteTheme(u.id),t=t.filter(f=>f.slug!==u.slug),i.onThemesChanged(t),e="clean",n({}),i.onTheme(e),x(),w(),c()}catch(f){M("Could not delete the theme",f instanceof Error?f.message:"","error")}},ae=async()=>{const u=t.find(v=>v.slug===e),f={label:u?.label??e,tokens:{...u?.tokens??{},...s}},b=JSON.stringify(f,null," ");try{await navigator.clipboard.writeText(b),M("Theme copied","Paste it into another site to import it.")}catch{window.prompt("Copy this theme",b)}},E=()=>{const u=window.prompt("Paste a theme");if(u)try{const f=JSON.parse(u);if(!f.tokens||typeof f.tokens!="object")throw new Error("That does not look like a theme.");for(const[b,v]of Object.entries(f.tokens))s[b]=String(v),i.onOverride(b,String(v));w(),c()}catch(f){M("Could not read that theme",f instanceof Error?f.message:"","error")}},A=S("Delete",()=>void z(),"danger"),ot=()=>{const u=t.find(f=>f.slug===e);A.hidden=!u?.custom};return x(),_(),w(),c(),ot(),r("div",{class:"atf-studio",children:[r("div",{class:"atf-studio__top",children:[r("div",{class:"atf-studio__picker",children:[r("h2",{class:"atf-studio__heading",text:"Theme"}),d]}),r("div",{class:"atfs__actions",children:[S("Save as a theme",()=>void B(),"primary"),S("Export",()=>void ae()),S("Import",E),A]})]}),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 ye(){const i=document.querySelector("[data-atfs-root]");if(!i||i.dataset.atfsMounted)return;i.dataset.atfsMounted="1";const e=i.querySelector("[data-atfs-bar]"),s=i.querySelector(".atfs__body")??i;try{const[t,n,a]=await Promise.all([C.config(),C.listThemes(),C.listForms()]);if(!a.length){D(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=()=>{D(s),s.append(ze({themes:n,tokens:t.tokens,activeSlug:d,overrides:l,standalone:!0,onTheme:h=>{d=h},onOverride:(h,x)=>{x===""?delete l[h]:l[h]=x},onOverridesReplaced:h=>{l={...h}},previewFor:async(h,x)=>{const g=await C.getForm(o.id);g.schema.settings.theme=h,g.schema.settings.themeOverrides=x;const{html:m}=await C.preview(o.id,{schema:g.schema,theme:h});return m},onThemesChanged:h=>{n.length=0,n.push(...h)}}))};e&&(D(e),e.append(r("span",{class:"atfs__label",text:"Preview against"}),$(String(o.id),a.map(h=>({value:String(h.id),label:h.title||"(untitled)"})),h=>{o=a.find(x=>String(x.id)===h)??a[0],l={},c()}))),c()}catch(t){D(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 ye()):ye(),document.addEventListener("os-window-content-loaded",()=>void ye()));function we(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 xe(){return window.wp?.os??null}const Xe="allterrain-forms/preview",ke="allterrain-forms-preview";function es(i){const e=xe();if(!e?.registerTitleBarButton)return()=>{};const s=()=>{try{e.registerTitleBarButton({id:Xe,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 Je(i),owner:"allterrain-forms-builder"})}catch{}};return e.ready?e.ready(s):s(),()=>{try{e.unregisterTitleBarButton?.(Xe)}catch{}}}async function Je(i){i.isDirty()&&await i.save();const e=i.current();e&&Ke(e.id,e.title,e.previewUrl)}function Ke(i,e,s){const t=xe();if(!t?.windowManager?.open){window.open(s,"_blank","noopener");return}t.windowManager.open({id:`${ke}-${i}`,baseId:ke,url:s,title:`Preview: ${e}`,icon:"dashicons-visibility"})}function ts(i,e,s){if(!xe()?.windowManager?.open||!document.querySelector(`[data-window-id="${ke}-${i}"]`))return;const a=s.includes("?")?"&":"?";Ke(i,e,`${s}${a}atf_r=${Date.now()}`)}const ss="allterrain-forms/form";function is(){return window.wp?.os?.relations??null}function ns(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 as=6e3,Ve=120;function Qe(i,e){const s=is();if(_e.set(i,e),!s?.set)return;const t=a=>{if(ne.get(i)!==n)return;const o=ns(i);if(!o){Date.now()t(a),Ve);return}try{s.set(o,e)}catch(d){Ze||(Ze=!0,console.error("[AllTerrain Forms] The shell refused a window identity.",d,e)),ne.delete(i);return}if(!e||s.get?.(o)?.id===e.id||Date.now()>=a){ne.delete(i);return}window.setTimeout(()=>t(a),Ve)},n=Symbol("atf-identity");ne.set(i,n),t(Date.now()+as)}let Ze=!1;const ne=new WeakMap,_e=new Map;function rs(){for(const[i,e]of _e){if(!i.isConnected){_e.delete(i);continue}Qe(i,e)}}if(typeof document<"u")for(const i of["os-window-content-loaded","os-window-opened"])document.addEventListener(i,()=>rs());function os(i,e){return{type:ss,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 V="allterrain-forms/field",ls=["openstation/file","desktop-mode/file","openstation/attachment"],et="allterrain-forms/logic-map-v2";function R(i,e){return i.dataset.atfbBind=e,i}const tt={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"}}},cs={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 st(i,e,s){const t=i[e.key],n=a=>s(e.key,a);if(e.control==="checkbox")return T(e.label,!!t,n);if(e.control==="commas"){const a=Array.isArray(t)?t:[];return p(e.label,y(a.join(", "),o=>{n(o.split(",").map(l=>l.trim().replace(/^\./,"").toLowerCase()).filter(Boolean))}),e.hint)}return e.control==="select"?p(e.label,$(String(t??""),e.options??[],n),e.hint):e.control==="textarea"?p(e.label,se(String(t??""),n),e.hint):e.control==="number"?p(e.label,P(String(t??""),n),e.hint):p(e.label,R(y(String(t??""),n),e.key),e.hint)}function it(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 nt(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 Se=[{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}"}],ds=["About the person filling it in","The date and time","About this site"],Ee=(i,e)=>I?.i18n?.[i]??e;class at{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=yt(et)!=="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=Fe(()=>{this.save(!0)},2500),this.renderInspector=vt(()=>{if(D(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(p("Label",R(y(s.label,o=>a("label",o)),"label"))),n.includes("placeholder")&&this.inspector.append(p("Placeholder",R(y(s.placeholder,o=>a("placeholder",o)),"placeholder"))),n.includes("hint")&&this.inspector.append(p("Hint",R(y(s.hint,o=>a("hint",o)),"hint"),"Shown under the field, and read out with it.")),n.includes("nextlabel")&&this.inspector.append(p("Next button",R(y(String(s.nextLabel??""),o=>a("nextLabel",o)),"nextLabel"),"Leave empty for “Next”.")),n.includes("prevlabel")&&this.inspector.append(p("Back button",R(y(String(s.prevLabel??""),o=>a("prevLabel",o)),"prevLabel"),"Leave empty for “Back”.")),n.includes("addlabel")&&this.inspector.append(p("Add button",R(y(String(s.addLabel??""),o=>a("addLabel",o)),"addLabel"),"Leave empty for “Add another”.")),n.includes("required")&&this.inspector.append(T("Required",s.required,o=>a("required",o))),n.includes("width")&&this.inspector.append(p("Width",$(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(p("Formula",y(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."),p("Currency symbol",y(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(p("CSS class",y(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([C.config(),C.listThemes(),C.listForms()]);this.config=t,this.themes=n,this.forms=a}catch(t){this.fail(t);return}this.teardowns.push(pt([V])),this.teardowns.push(es({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){D(this.bar),this.bar.append(r("p",{class:"atfb-error",text:e instanceof Error?e.message:"Something went wrong loading your forms."}))}renderBar(){D(this.bar);const e=$(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),S("New",()=>void this.showTemplates(),"secondary","plus-alt2"),S("Export",()=>void this.exportForm(),"secondary","download"),S("Import",()=>void this.importForm(),"secondary","upload"),S("Preview",()=>void this.preview(),"secondary","visibility"),S("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=je(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=je(e,s.dataset.atfbBind??"");s.value!==t&&("value"in s?s.value=t:s.setAttribute("value",t))}}rebindCanvas(){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=S(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 C.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(),M("Form imported",n.title)}catch(t){M("Could not import that file",t instanceof Error?t.message:"","error")}}),e.click()}saveButton(){const e=S("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 C.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)}Ut(t.id);const n=this.forms.find(a=>a.id===t.id);n&&(n.title=t.title),ts(t.id,t.title,t.previewUrl),e||M("Form saved",t.title)}catch(t){M(Ee("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 he("You have unsaved changes. Discard them?"))){try{this.form=await C.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&&Qe(this.root,os(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 C.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){M("Could not create the form",o instanceof Error?o.message:"","error")}}},children:[q(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:[S("Cancel",t)]})]})),e.addEventListener("click",a=>{a.target===e&&t()}),document.addEventListener("keydown",s),this.root.append(e),n.querySelector("button")?.focus()}renderFormsList(){D(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."}),S("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;D(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:[q(e.icon),r("span",{text:e.label})]});return s.addEventListener("pointerdown",t=>{const n=r("div",{class:"atfb-chip atfb-chip--ghost",children:[q(e.icon),r("span",{text:e.label})]});Y().start({payload:Te(V,s,{fieldType:e.type,isNew:!0},t,n),origin:t,onClickOnly:()=>this.addField(e.type)})}),s.addEventListener("click",t=>{Y().recentlyEndedDrag()&&t.preventDefault()}),s}renderCanvas(){if(D(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:Ee("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=Se.some(g=>g.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=g=>{if(o.replaceChildren(),l.replaceChildren(),g==="query"){const m=e.prefill.startsWith("query:")?e.prefill.slice(6):"";o.append(y(m,_=>{const w=_.trim();s("prefill",w?`query:${w}`:""),c(`query:${w}`)},"utm_source"),r("p",{class:"atfb-row__hint",text:"The name of the parameter in the link people arrive on."}))}g==="custom"&&o.append(y(e.prefill,m=>{s("prefill",m),c(m)},"myplugin:something"),r("p",{class:"atfb-row__hint",text:"For a source another plugin has added through atf_resolve_prefill."})),c(e.prefill)},c=g=>{if(l.replaceChildren(),!g)return;if(g.startsWith("query:")){const _=g.slice(6);_&&(l.textContent=`A visit to …/your-page/?${_}=abc opens the form with “abc” in it.`);return}const m=Se.find(_=>_.value===g)?.tag;m&&be(this.form?.id??0).then(_=>{for(const w of _)for(const L of w.items)if(L.tag===m){const B=g.startsWith("user:");if(!L.sample){l.textContent="Empty unless the visitor is signed in.";return}l.textContent=B?`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:g=>{const m=g.target.value;s("prefill",m==="query"||m==="custom"?"":m),d(m)}}});h.append(r("option",{value:"",text:"Nothing — leave it empty",attrs:{selected:a===""}}));for(const g of ds){const m=document.createElement("optgroup");m.label=g;for(const _ of Se.filter(w=>w.group===g))m.append(r("option",{value:_.value,text:_.label,attrs:{selected:_.value===a}}));h.append(m)}const x=document.createElement("optgroup");return x.label="From the link they arrived on",x.append(r("option",{value:"query",text:"A parameter in the web address",attrs:{selected:a==="query"}})),h.append(x,r("option",{value:"custom",text:"Something else (advanced)",attrs:{selected:a==="custom"}})),p("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":Re(e)},children:[q("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=ue(this.schema?.fields??[]).length>0,s=S(this.logicMapOn?"Hide logic":"Show logic",()=>{this.logicMapOn=!this.logicMapOn,wt(et,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=ue(s);if(!t.length||!this.logicMapOn)return;e.classList.add("has-logicmap");const n=new It(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=At(e,a),l=Ft(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:[q("menu")]}),r("div",{class:"atfb-card__body",children:[r("div",{class:"atfb-card__head",children:[q(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]}),Nt(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")||Y().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")||Y().start({payload:Te(V,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:[q(e)]})}registerCanvasTarget(e){this.canvasTarget?.(),this.canvasTarget=null;const s=r("div",{class:"atfb-marker",attrs:{"aria-hidden":"true"}}),t=Y().registerDropTarget({id:`atfb-canvas-${this.form?.id??0}`,element:e,accept:a=>a.type===V,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=$e(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!==V||!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=$e(e,".atfb-card",d,l??void 0),h=Array.from(e.querySelectorAll(".atfb-card")).filter(x=>x!==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=nt(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.`:Ee("confirmDelete","Delete this? It cannot be undone.");await he(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=tt[a];o&&(this.inspector.append(st(e,o,n)),o.also&&this.inspector.append(st(e,{...o,key:o.also.key,label:o.also.label,hint:o.also.hint},n)))}t.includes("rows")&&e.type!=="likert"&&this.inspector.append(p("Lines tall",P(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 p("Statements",se(t.map(n=>n.label??"").join(` +var allTerrainFormsBuilder=function(H){"use strict";class dt{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,x=0;const g=()=>{document.removeEventListener("pointermove",L),document.removeEventListener("pointerup",B),document.removeEventListener("pointercancel",z),document.removeEventListener("keydown",ae),window.removeEventListener("blur",z),d?.remove(),d=null,s.source.classList.remove("atf-is-dragging"),c?.onLeave?.(m),c=null,this.active=null,this.lastEndMs=Date.now()},m={payload:s,isFinished:()=>l,cancel:(E="caller")=>{l||(l=!0,g(),e.onCancel?.(E))}},k=E=>{o=!0,s.source.classList.add("atf-is-dragging");const A=s.source.getBoundingClientRect();h=s.ghost?.offsetX??n-A.left,x=s.ghost?.offsetY??a-A.top,d=s.ghost?.element??s.source.cloneNode(!0),d.classList.add("atf-drag-ghost"),d.style.width=`${A.width}px`,document.body.appendChild(d),w(E)},w=E=>{d&&(d.style.transform=`translate3d(${E.clientX-h}px, ${E.clientY-x}px, 0)`)},L=E=>{if(l)return;if(!o){if(Math.hypot(E.clientX-n,E.clientY-a)<4)return;k(E)}w(E);const A=this.hitTest(E.clientX,E.clientY);A!==c&&(c?.onLeave?.(m),c=A,c?.onEnter?.(m))},B=E=>{if(l)return;if(!o){l=!0,g(),e.onClickOnly?.();return}const A=c;if(l=!0,g(),A&&A.accept(s)){e.onCommit?.(A),A.onDrop(m,{clientX:E.clientX,clientY:E.clientY});return}e.onCancel?.(A?"rejected":"no-target")},z=()=>m.cancel("pointercancel"),ae=E=>{E.key==="Escape"&&m.cancel("escape")};return document.addEventListener("pointermove",L),document.addEventListener("pointerup",B),document.addEventListener("pointercancel",z),document.addEventListener("keydown",ae),window.addEventListener("blur",z),this.active=m,m}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=ht(a.element);if(l>n){t=a,n=l;continue}l===n&&t&&ut(a.element,t.element)&&(t=a)}return t}}function ht(i){let e=0,s=i;for(;s;)e++,s=s.parentElement;return e}function ut(i,e){return(e.compareDocumentPosition(i)&Node.DOCUMENT_POSITION_FOLLOWING)!==0}function le(){return window.wp?.os??null}let ce=null;function Y(){const i=le();return i?.dragManager?i.dragManager:(ce||(ce=new dt),ce)}function pt(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 Te(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 $e(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 ee(l,o.status,d)}if(o.status!==204)return await o.json()}const N=i=>de(i);async function ft(i){if(!I?.wpRestUrl)throw new ee("AllTerrain Forms is not configured on this page.",0);const e=I.nonce?{"X-WP-Nonce":I.nonce}:{},s=le(),t=Ae(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 ee(`Request failed with status ${n.status}.`,n.status);return await n.json()}function mt(i){if(!i||!i.includes("&"))return i;const e=document.createElement("textarea");return e.innerHTML=i,e.value}const W=(i,e)=>de(i,{method:"POST",body:JSON.stringify(e)}),te=i=>de(i,{method:"DELETE"});function De(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}`:""}const C={config:()=>N("/config"),listForms:()=>N("/forms"),getForm:i=>N(`/forms/${i}`),createForm:i=>W("/forms",i),updateForm:(i,e)=>W(`/forms/${i}`,e),duplicateForm:i=>W(`/forms/${i}/duplicate`,{}),deleteForm:i=>te(`/forms/${i}`),preview:(i,e)=>W(`/forms/${i}/preview`,e),pages:()=>ft("wp/v2/pages?per_page=100&status=publish&orderby=title&order=asc&_fields=id,title").then(i=>i.map(e=>({id:e.id,title:mt(e.title?.rendered??"")||`#${e.id}`}))),mergeTags:i=>N(`/forms/${i}/merge-tags`).then(e=>e.groups),analytics:(i,e="")=>N(`/forms/${i}/analytics${e?`?dimension=${encodeURIComponent(e)}`:""}`),demoStatus:()=>N("/demo"),demoSeed:i=>W("/demo",i?{count:i}:{}),demoRemove:()=>te("/demo"),listEntries:i=>N(`/entries${De(i)}`),getEntry:i=>N(`/entries/${i}`),updateEntry:(i,e)=>W(`/entries/${i}`,e),deleteEntry:i=>te(`/entries/${i}`),exportEntries:i=>N(`/entries/export${De(i)}`),listThemes:()=>N("/themes"),saveTheme:i=>W("/themes",i),deleteTheme:i=>te(`/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 D(i){i.replaceChildren()}function q(i){return r("span",{class:`dashicons ${i.startsWith("dashicons-")?i:`dashicons-${i}`}`,attrs:{"aria-hidden":"true"}})}function p(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 y(i,e,s=""){return r("input",{class:"atfb-input",type:"text",value:i,placeholder:s,on:{input:t=>e(t.target.value)}})}function P(i,e){if(J("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 se(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 $(i,e,s){if(J("os-select")&&J("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 T(i,e,s){if(J("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 S(i,e,s="secondary",t){const n=[t?q(t):null,r("span",{text:i})];if(J("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 J(i){return typeof customElements<"u"&&!!customElements.get(i)}const bt=["os-button","os-checkbox-label","os-number-field","os-select","os-option","os-segmented","os-segment","os-color-field","os-empty-state"];let ie=null;function gt(){if(ie)return ie;const i=window.wp?.os;return ie=i?.loadComponents?i.loadComponents(bt).catch(()=>{}):Promise.resolve(),ie}async function he(i,e=""){const s=window.wp?.os;return s?.confirm?s.confirm({title:e,message:i,danger:!0}):window.confirm(i)}function M(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 vt(i){let e=0,s;return(...t)=>{s=t,!e&&(e=window.requestAnimationFrame(()=>{e=0,i(...s)}))}}function Fe(i,e){let s=0;return(...t)=>{window.clearTimeout(s),s=window.setTimeout(()=>i(...t),e)}}function yt(i){try{return window.localStorage.getItem(i)??""}catch{return""}}function wt(i,e){try{window.localStorage.setItem(i,e)}catch{}}function Ie(){const i=[window];try{window.parent&&window.parent!==window&&i.push(window.parent)}catch{}return i}function xt(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 _t=4e3,kt=100;function St(i,e){const s=Date.now()+_t,t=()=>{const n=xt(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&&Tt(s);for(const n of Ie())if(n.wp?.os?.openWindow?.(e,{source:"handoff",params:t})){window.setTimeout(()=>St(n,e),0);return}}function Lt(){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 Ie())if(t.wp?.os?.openWindow?.(s,{source:"handoff"}))return})}const Ct="allterrain-forms/requested-form";function Tt(i){try{window.sessionStorage.setItem(Ct,String(i))}catch{}}const qe={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"},Oe=["empty","not_empty"];function Me(i,e){const s=i.find(t=>t.id===e);return s?s.label||"an untitled question":null}function Ne(i,e,s){return i.find(a=>a.id===e)?.choices?.find(a=>a.value===s)?.label||s}function $t(i,e){const s=qe[i.operator]??String(i.operator);if(Oe.includes(i.operator))return s;const t=Ne(e,i.field,i.value);return`${i.operator==="is"?"":`${s} `}${t!==""?t:"(nothing)"}`}function Pe(i,e){const s=Me(e,i.field),t=qe[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(Oe.includes(i.operator))return n;const a=Ne(e,i.field,i.value);return n.push({kind:"value",text:a!==""?a:"(nothing)"}),n}function At(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(...Pe(n,e))}),t}function Re(i){return i.map(e=>e.text).join(" ")}function Dt(i,e){return Re(Pe(i,e))}function ue(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:Dt(n,i),short:$t(n,i),action:t.action,broken:Me(i,n.field)===null})}return e}function Ft(i){const e=new Map,s=new Set;for(const t of ue(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 Be=10,He=22,G="http://www.w3.org/2000/svg";class It{constructor(e){this.edges=[],this.teardowns=[],this.frame=0,this.host=e,this.svg=document.createElementNS(G,"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-Be-Math.max(o,d)),x=22+a*11+Math.min(22,Math.abs(c-l)/8),g=Math.max(12,Math.min(x,h*.4)),m=document.createElementNS(G,"path");m.setAttribute("d",`M ${o} ${l} C ${o+g} ${l}, ${d+g} ${c}, ${d} ${c}`),m.setAttribute("class",`atfb-logicmap__path is-${e.action}${e.broken?" is-broken":""}`),m.dataset.from=e.from,m.dataset.to=e.to;const k=document.createElementNS(G,"title");k.textContent=e.label,m.append(k);const w=document.createElementNS(G,"circle");w.setAttribute("cx",String(d)),w.setAttribute("cy",String(c)),w.setAttribute("r","3.5"),w.setAttribute("class",`atfb-logicmap__dot is-${e.action}${e.broken?" is-broken":""}`),w.dataset.from=e.from,w.dataset.to=e.to,this.svg.append(m,w);const L=document.createElementNS(G,"text");L.setAttribute("x",String(n.width-Be)),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>He?`${e.short.slice(0,He-1)}…`:e.short;const B=document.createElementNS(G,"title");B.textContent=e.label,L.append(B),this.svg.append(L)}}const qt={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 Ot(i){return qt[i]??"text"}function je(i,e){const s=/^choice:(\d+):(label|value)$/.exec(e);return String(s?i.choices?.[Number(s[1])]?.[s[2]]??"":i[e]??"")}function j(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 Mt(i){const e=r("input",{class:"atf-choice__input",type:i==="checkboxes"||i==="multiselect"?"checkbox":"radio"});return e.disabled=!0,e}function Nt(i,e,s){const t=Ot(i.type),n=j({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,Rt(i,e,t,s),Pt(i,e,s)];return r("div",{class:"atfb-preview atf-form",children:[r("div",{class:`atf-field atf-field--${i.type}`,children:a})]})}function Pt(i,e,s){if(!e?.supports.includes("hint"))return null;const t=j({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 Rt(i,e,s,t){switch(s){case"text":return pe(i,"atf-input",t);case"textarea":return pe(i,"atf-input atf-textarea",t,!0);case"select":return r("div",{class:"atfb-preview__select",children:[pe(i,"atf-input atf-select",t)]});case"options":return Ht(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})(),j({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 jt(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"?Bt(i,t):null]})}}function pe(i,e,s,t=!1){const n=j({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 fe(i,e,s,t,n,a){return r("span",{class:`atf-button ${s} atfb-preview__button`,children:[j({value:i,placeholder:e,class:"atfb-preview__button-text",bind:t,onInput:o=>n.edit(l=>a(l,o))})]})}function Bt(i,e){return fe(String(i.addLabel??""),"Add another","atf-button--secondary","addLabel",e,(s,t)=>{s.addLabel=t})}function Ht(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:[Mt(i.type),j({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 jt(i,e,s){return i.type==="heading"?j({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:[j({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:[fe(String(i.prevLabel??""),"Back","atf-button--secondary","prevLabel",s,(t,n)=>{t.prevLabel=n}),fe(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 me=new Map;function be(i){let e=me.get(i);return e||(e=C.mergeTags(i).catch(()=>[]),me.set(i,e)),e}function Ut(i){me.delete(i)}function Wt(i){const e=new Map;for(const s of i)for(const t of s.items)e.set(t.tag,t);return e}function Yt(i,e){const s=Wt(e);return i.replace(/\{[a-z_]+(?::[^}]*)?\}/gi,t=>{const n=s.get(t.toLowerCase());return n?n.sample:t})}function Gt(i){return/\{[a-z_]+(?::[^}]*)?\}/i.test(i)}let U=null;function K(){U?.remove(),U=null}typeof document<"u"&&(document.addEventListener("pointerdown",i=>{const e=i.target;e?.closest(".atfb-tagpick__open")||U&&!U.contains(e)&&K()}),document.addEventListener("keydown",i=>{i.key==="Escape"&&U&&(K(),i.stopPropagation())}));function zt(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 Xt(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 Jt(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),K()}},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 Ue(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:[q("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(!Gt(i.value)){n.textContent="",n.hidden=!0;return}be(e.formId).then(o=>{n.hidden=!1,n.replaceChildren(r("span",{class:"atfb-taggable__preview-label",text:"Reads as"}),r("span",{text:Yt(i.value,o)}))})}};return i.addEventListener("input",a),a(),s.addEventListener("click",o=>{if(o.stopPropagation(),U&&t.contains(U)){K();return}K(),be(e.formId).then(l=>{const d=Jt(l,c=>{zt(i,c),a()});t.append(d),U=d,(window.innerHeight-d.getBoundingClientRect().topXt(t))&&d.classList.add("atfb-tagpick--above"),d.querySelector(".atfb-tagpick__search")?.focus()})}),t}function We(i,e){const s=parseFloat(String(i??""));return Number.isFinite(s)?s:e}function Ye(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:ge.map(({value:i,label:e})=>({value:i,label:e})),owns:["radius-field","radius-button","radius-card","radius-check"],read:i=>Ye(We(i["radius-field"],4),ge),apply:i=>{const e=ge.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:ve.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=>Ye(We(i["pad-field-y"],9),ve),apply:i=>{const e=ve.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:Kt,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:Vt,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:Qt,owns:["label-position"],read:i=>i["label-position"]??"top",apply:i=>({"label-position":i})}]}function Zt(i){return Ge().find(e=>e.owns.includes(i))??null}function ze(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=Fe(async()=>{try{const u=await i.previewFor(e,s);a.innerHTML=u,document.dispatchEvent(new CustomEvent("atf-refresh"))}catch(u){D(a),a.append(r("p",{class:"atfb-error",text:u instanceof Error?u.message:"Preview failed."}))}},180),h=u=>s[u.token]!==void 0?s[u.token]:t.find(b=>b.slug===e)?.resolved?.[u.token]??u.default,x=()=>{D(d);for(const u of t){const f=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),x(),k(),w(),c(),ot()}}});d.append(f)}},g=()=>{const f={...t.find(b=>b.slug===e)?.resolved??{}};for(const[b,v]of Object.entries(s))f[b]=v;return f},m=(u,f)=>{const b=u.apply(f,g());for(const[v,_]of Object.entries(b))s[v]=_,i.onOverride(v,_);k(),w(),c()},k=()=>{D(l);const u=g();for(const f of Ge()){const b=f.read(u);let v;if(f.kind==="colour"){const _=r("input",{class:"atfs-color",type:"color",value:we(b),attrs:{"aria-label":f.label},on:{input:O=>m(f,O.target.value)}});v=r("div",{class:"atfs-color-row",children:[_,y(b,O=>m(f,O))]})}else v=r("div",{class:`atfs-segmented atfs-segmented--${f.kind}`,attrs:{role:"group","aria-label":f.label},children:(f.steps??[]).map(_=>r("button",{class:`atfs-segment${_.value===b?" is-on":""}`,type:"button",text:_.label,attrs:{"aria-pressed":_.value===b},on:{click:()=>m(f,_.value)}}))});l.append(r("div",{class:"atfs-dial",children:[r("div",{class:"atfs-dial__head",children:[r("span",{class:"atfs-dial__label",text:f.label}),r("span",{class:"atfs-dial__hint",text:f.hint})]}),v]}))}},w=()=>{D(o);const u=new Map;for(const b of i.tokens){const v=u.get(b.group)??[];v.push(b),u.set(b.group,v)}const f={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[b,v]of u)o.append(r("details",{class:"atfs-group",attrs:{open:b==="colour"},children:[r("summary",{text:f[b]??b}),...v.map(_=>L(_))]}))},L=u=>{const f=h(u),b=F=>{F===""?delete s[u.token]:s[u.token]=F,i.onOverride(u.token,F),c()};let v;if(u.control==="color"){const F=r("input",{class:"atfs-color",type:"color",value:we(f),attrs:{"aria-label":`${u.label} colour`},on:{input:X=>{const Z=X.target.value;re.value=Z,b(Z)}}}),re=y(f,X=>{F.value=we(X),b(X)});v=r("div",{class:"atfs-color-row",children:[F,re]})}else if(u.control==="select")v=$(f,(u.options??[]).map(F=>({value:F,label:F})),b);else if(u.control==="length"){const F=parseFloat(f)||0,re=u.unit??"px",X=u.token.includes("radius")?60:80,Z=r("input",{class:"atfs-range",type:"range",value:String(F),attrs:{min:"0",max:String(X),step:"1","aria-label":u.label},on:{input:oe=>{const ct=`${oe.target.value}${re}`;lt.value=ct,b(ct)}}}),lt=y(f,oe=>{Z.value=String(parseFloat(oe)||0),b(oe)});v=r("div",{class:"atfs-length-row",children:[Z,lt]})}else v=y(f,b);const _=p(u.label,v),O=Zt(u.token);return O&&(_.classList.add("is-dialled"),_.append(r("span",{class:"atfs-owned",text:O.label}))),s[u.token]!==void 0&&(_.classList.add("is-overridden"),_.append(r("button",{class:"atfs-reset",type:"button",text:"Reset",attrs:{"aria-label":`Reset ${u.label} to the theme's value`},on:{click:()=>{b(""),w()}}}))),_},B=async()=>{const u=t.find(v=>v.slug===e),f=u?`${u.label} (mine)`:"My theme",b=window.prompt("Name this theme",f);if(b)try{const v={};for(const O of i.tokens){const F=h(O);F!==O.default&&(v[O.token]=F)}const _=await C.saveTheme({label:b,tokens:v});t=[...t.filter(O=>O.slug!==_.slug),_],i.onThemesChanged(t),e=_.slug,n({}),i.onTheme(e),x(),w(),c(),M("Theme saved",_.label)}catch(v){M("Could not save the theme",v instanceof Error?v.message:"","error")}},z=async()=>{const u=t.find(f=>f.slug===e);if(u?.custom&&await he(`Delete “${u.label}”? Forms using it fall back to Clean.`,"Delete theme"))try{await C.deleteTheme(u.id),t=t.filter(f=>f.slug!==u.slug),i.onThemesChanged(t),e="clean",n({}),i.onTheme(e),x(),w(),c()}catch(f){M("Could not delete the theme",f instanceof Error?f.message:"","error")}},ae=async()=>{const u=t.find(v=>v.slug===e),f={label:u?.label??e,tokens:{...u?.tokens??{},...s}},b=JSON.stringify(f,null," ");try{await navigator.clipboard.writeText(b),M("Theme copied","Paste it into another site to import it.")}catch{window.prompt("Copy this theme",b)}},E=()=>{const u=window.prompt("Paste a theme");if(u)try{const f=JSON.parse(u);if(!f.tokens||typeof f.tokens!="object")throw new Error("That does not look like a theme.");for(const[b,v]of Object.entries(f.tokens))s[b]=String(v),i.onOverride(b,String(v));w(),c()}catch(f){M("Could not read that theme",f instanceof Error?f.message:"","error")}},A=S("Delete",()=>void z(),"danger"),ot=()=>{const u=t.find(f=>f.slug===e);A.hidden=!u?.custom};return x(),k(),w(),c(),ot(),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:[S("Save as a theme",()=>void B(),"primary"),S("Export",()=>void ae()),S("Import",E),A]})]}),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 ye(){const i=document.querySelector("[data-atfs-root]");if(!i||i.dataset.atfsMounted)return;i.dataset.atfsMounted="1";const e=i.querySelector("[data-atfs-bar]"),s=i.querySelector(".atfs__body")??i;try{const[t,n,a]=await Promise.all([C.config(),C.listThemes(),C.listForms()]);if(!a.length){D(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=()=>{D(s),s.append(ze({themes:n,tokens:t.tokens,activeSlug:d,overrides:l,standalone:!0,onTheme:h=>{d=h},onOverride:(h,x)=>{x===""?delete l[h]:l[h]=x},onOverridesReplaced:h=>{l={...h}},previewFor:async(h,x)=>{const g=await C.getForm(o.id);g.schema.settings.theme=h,g.schema.settings.themeOverrides=x;const{html:m}=await C.preview(o.id,{schema:g.schema,theme:h});return m},onThemesChanged:h=>{n.length=0,n.push(...h)}}))};e&&(D(e),e.append(r("span",{class:"atfs__label",text:"Preview against"}),$(String(o.id),a.map(h=>({value:String(h.id),label:h.title||"(untitled)"})),h=>{o=a.find(x=>String(x.id)===h)??a[0],l={},c()}))),c()}catch(t){D(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 ye()):ye(),document.addEventListener("os-window-content-loaded",()=>void ye()));function we(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 xe(){return window.wp?.os??null}const Xe="allterrain-forms/preview",_e="allterrain-forms-preview";function es(i){const e=xe();if(!e?.registerTitleBarButton)return()=>{};const s=()=>{try{e.registerTitleBarButton({id:Xe,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 Je(i),owner:"allterrain-forms-builder"})}catch{}};return e.ready?e.ready(s):s(),()=>{try{e.unregisterTitleBarButton?.(Xe)}catch{}}}async function Je(i){i.isDirty()&&await i.save();const e=i.current();e&&Ke(e.id,e.title,e.previewUrl)}function Ke(i,e,s){const t=xe();if(!t?.windowManager?.open){window.open(s,"_blank","noopener");return}t.windowManager.open({id:`${_e}-${i}`,baseId:_e,url:s,title:`Preview: ${e}`,icon:"dashicons-visibility"})}function ts(i,e,s){if(!xe()?.windowManager?.open||!document.querySelector(`[data-window-id="${_e}-${i}"]`))return;const a=s.includes("?")?"&":"?";Ke(i,e,`${s}${a}atf_r=${Date.now()}`)}const ss="allterrain-forms/form";function is(){return window.wp?.os?.relations??null}function ns(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 as=6e3,Ve=120;function Qe(i,e){const s=is();if(ke.set(i,e),!s?.set)return;const t=a=>{if(ne.get(i)!==n)return;const o=ns(i);if(!o){Date.now()t(a),Ve);return}try{s.set(o,e)}catch(d){Ze||(Ze=!0,console.error("[AllTerrain Forms] The shell refused a window identity.",d,e)),ne.delete(i);return}if(!e||s.get?.(o)?.id===e.id||Date.now()>=a){ne.delete(i);return}window.setTimeout(()=>t(a),Ve)},n=Symbol("atf-identity");ne.set(i,n),t(Date.now()+as)}let Ze=!1;const ne=new WeakMap,ke=new Map;function rs(){for(const[i,e]of ke){if(!i.isConnected){ke.delete(i);continue}Qe(i,e)}}if(typeof document<"u")for(const i of["os-window-content-loaded","os-window-opened"])document.addEventListener(i,()=>rs());function os(i,e){return{type:ss,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 V="allterrain-forms/field",ls=["openstation/file","desktop-mode/file","openstation/attachment"],et="allterrain-forms/logic-map-v2";function R(i,e){return i.dataset.atfbBind=e,i}const tt={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"}}},cs={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 st(i,e,s){const t=i[e.key],n=a=>s(e.key,a);if(e.control==="checkbox")return T(e.label,!!t,n);if(e.control==="commas"){const a=Array.isArray(t)?t:[];return p(e.label,y(a.join(", "),o=>{n(o.split(",").map(l=>l.trim().replace(/^\./,"").toLowerCase()).filter(Boolean))}),e.hint)}return e.control==="select"?p(e.label,$(String(t??""),e.options??[],n),e.hint):e.control==="textarea"?p(e.label,se(String(t??""),n),e.hint):e.control==="number"?p(e.label,P(String(t??""),n),e.hint):p(e.label,R(y(String(t??""),n),e.key),e.hint)}function it(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 nt(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 Se=[{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}"}],ds=["About the person filling it in","The date and time","About this site"],Ee=(i,e)=>I?.i18n?.[i]??e;class at{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=yt(et)!=="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=Fe(()=>{this.save(!0)},2500),this.renderInspector=vt(()=>{if(D(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(p("Label",R(y(s.label,o=>a("label",o)),"label"))),n.includes("placeholder")&&this.inspector.append(p("Placeholder",R(y(s.placeholder,o=>a("placeholder",o)),"placeholder"))),n.includes("hint")&&this.inspector.append(p("Hint",R(y(s.hint,o=>a("hint",o)),"hint"),"Shown under the field, and read out with it.")),n.includes("nextlabel")&&this.inspector.append(p("Next button",R(y(String(s.nextLabel??""),o=>a("nextLabel",o)),"nextLabel"),"Leave empty for “Next”.")),n.includes("prevlabel")&&this.inspector.append(p("Back button",R(y(String(s.prevLabel??""),o=>a("prevLabel",o)),"prevLabel"),"Leave empty for “Back”.")),n.includes("addlabel")&&this.inspector.append(p("Add button",R(y(String(s.addLabel??""),o=>a("addLabel",o)),"addLabel"),"Leave empty for “Add another”.")),n.includes("required")&&this.inspector.append(T("Required",s.required,o=>a("required",o))),n.includes("width")&&this.inspector.append(p("Width",$(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(p("Formula",y(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."),p("Currency symbol",y(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(p("CSS class",y(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([C.config(),C.listThemes(),C.listForms()]);this.config=t,this.themes=n,this.forms=a}catch(t){this.fail(t);return}this.teardowns.push(pt([V])),this.teardowns.push(es({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){D(this.bar),this.bar.append(r("p",{class:"atfb-error",text:e instanceof Error?e.message:"Something went wrong loading your forms."}))}renderBar(){D(this.bar);const e=$(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),S("New",()=>void this.showTemplates(),"secondary","plus-alt2"),S("Export",()=>void this.exportForm(),"secondary","download"),S("Import",()=>void this.importForm(),"secondary","upload"),S("Preview",()=>void this.preview(),"secondary","visibility"),S("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=je(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=je(e,s.dataset.atfbBind??"");s.value!==t&&("value"in s?s.value=t:s.setAttribute("value",t))}}rebindCanvas(){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=S(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 C.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(),M("Form imported",n.title)}catch(t){M("Could not import that file",t instanceof Error?t.message:"","error")}}),e.click()}saveButton(){const e=S("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 C.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)}Ut(t.id);const n=this.forms.find(a=>a.id===t.id);n&&(n.title=t.title),ts(t.id,t.title,t.previewUrl),e||M("Form saved",t.title)}catch(t){M(Ee("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 he("You have unsaved changes. Discard them?"))){try{this.form=await C.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&&Qe(this.root,os(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 C.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){M("Could not create the form",o instanceof Error?o.message:"","error")}}},children:[q(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:[S("Cancel",t)]})]})),e.addEventListener("click",a=>{a.target===e&&t()}),document.addEventListener("keydown",s),this.root.append(e),n.querySelector("button")?.focus()}renderFormsList(){D(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."}),S("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;D(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:[q(e.icon),r("span",{text:e.label})]});return s.addEventListener("pointerdown",t=>{const n=r("div",{class:"atfb-chip atfb-chip--ghost",children:[q(e.icon),r("span",{text:e.label})]});Y().start({payload:Te(V,s,{fieldType:e.type,isNew:!0},t,n),origin:t,onClickOnly:()=>this.addField(e.type)})}),s.addEventListener("click",t=>{Y().recentlyEndedDrag()&&t.preventDefault()}),s}renderCanvas(){if(D(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:Ee("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=Se.some(g=>g.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=g=>{if(o.replaceChildren(),l.replaceChildren(),g==="query"){const m=e.prefill.startsWith("query:")?e.prefill.slice(6):"";o.append(y(m,k=>{const w=k.trim();s("prefill",w?`query:${w}`:""),c(`query:${w}`)},"utm_source"),r("p",{class:"atfb-row__hint",text:"The name of the parameter in the link people arrive on."}))}g==="custom"&&o.append(y(e.prefill,m=>{s("prefill",m),c(m)},"myplugin:something"),r("p",{class:"atfb-row__hint",text:"For a source another plugin has added through atf_resolve_prefill."})),c(e.prefill)},c=g=>{if(l.replaceChildren(),!g)return;if(g.startsWith("query:")){const k=g.slice(6);k&&(l.textContent=`A visit to …/your-page/?${k}=abc opens the form with “abc” in it.`);return}const m=Se.find(k=>k.value===g)?.tag;m&&be(this.form?.id??0).then(k=>{for(const w of k)for(const L of w.items)if(L.tag===m){const B=g.startsWith("user:");if(!L.sample){l.textContent="Empty unless the visitor is signed in.";return}l.textContent=B?`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:g=>{const m=g.target.value;s("prefill",m==="query"||m==="custom"?"":m),d(m)}}});h.append(r("option",{value:"",text:"Nothing — leave it empty",attrs:{selected:a===""}}));for(const g of ds){const m=document.createElement("optgroup");m.label=g;for(const k of Se.filter(w=>w.group===g))m.append(r("option",{value:k.value,text:k.label,attrs:{selected:k.value===a}}));h.append(m)}const x=document.createElement("optgroup");return x.label="From the link they arrived on",x.append(r("option",{value:"query",text:"A parameter in the web address",attrs:{selected:a==="query"}})),h.append(x,r("option",{value:"custom",text:"Something else (advanced)",attrs:{selected:a==="custom"}})),p("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":Re(e)},children:[q("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=ue(this.schema?.fields??[]).length>0,s=S(this.logicMapOn?"Hide logic":"Show logic",()=>{this.logicMapOn=!this.logicMapOn,wt(et,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=ue(s);if(!t.length||!this.logicMapOn)return;e.classList.add("has-logicmap");const n=new It(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=At(e,a),l=Ft(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:[q("menu")]}),r("div",{class:"atfb-card__body",children:[r("div",{class:"atfb-card__head",children:[q(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]}),Nt(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")||Y().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")||Y().start({payload:Te(V,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:[q(e)]})}registerCanvasTarget(e){this.canvasTarget?.(),this.canvasTarget=null;const s=r("div",{class:"atfb-marker",attrs:{"aria-hidden":"true"}}),t=Y().registerDropTarget({id:`atfb-canvas-${this.form?.id??0}`,element:e,accept:a=>a.type===V,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=$e(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!==V||!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=$e(e,".atfb-card",d,l??void 0),h=Array.from(e.querySelectorAll(".atfb-card")).filter(x=>x!==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=nt(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.`:Ee("confirmDelete","Delete this? It cannot be undone.");await he(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=tt[a];o&&(this.inspector.append(st(e,o,n)),o.also&&this.inspector.append(st(e,{...o,key:o.also.key,label:o.also.label,hint:o.also.hint},n)))}t.includes("rows")&&e.type!=="likert"&&this.inspector.append(p("Lines tall",P(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 p("Statements",se(t.map(n=>n.label??"").join(` `),n=>s("rows",it(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=>T(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"?T("On by default",!!e.default,a=>t("default",a)):s?.choices&&(e.choices??[]).length?p("Default answer",$(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):p("Default answer",y(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,R(y(o.label,c=>{const h=n(l);if(!h)return;const x=!h.value||h.value===h.label;h.label=c,x&&(h.value=c),this.markDirty();const g=this.liveField(e.id);g&&this.syncCanvas(g)}),`choice:${l}:label`),R(y(o.value,c=>{const h=n(l);h&&(h.value=c,this.markDirty())},"value"),`choice:${l}:value`),e.type==="quiz"||o.points!==void 0?P(String(o.points??""),c=>{const h=n(l);h&&(h.points=c===""?void 0:Number(c),this.markDirty())}):P(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:[q("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,S("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"?p("Correct answer",$(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}`}):q("format-image")]}),a=Y().registerDropTarget({id:`atfb-well-${t.id}-${s}`,element:n,accept:o=>ls.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){M("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(p(d,y(String(e[l]??""),c=>t(l,c))));s.includes("pattern")&&n.push(p("Pattern",y(String(e.pattern??""),l=>t("pattern",l)),"A regular expression, without slashes.")),s.includes("unique")&&n.push(T("No two people may submit the same value",!!e.unique,l=>t("unique",l)));const o=e.messages??{};return s.includes("required")&&n.push(p("Message when required",y(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:[$(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())}),$(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())}),y(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:[q("trash")]})]}))}),this.section(`logic:${e.id}`,"Conditional logic",[T("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:[$(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"}),$(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,S("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"?ze({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??{}),n=/