diff --git a/assets/css/builder.css b/assets/css/builder.css index 885cb81..da24f1e 100644 --- a/assets/css/builder.css +++ b/assets/css/builder.css @@ -2696,32 +2696,39 @@ os-checkbox-label.atfb-check { button somewhere nobody could reach. Absolute against the body's `position: relative` is exact at every window size. - No bottom padding: the sticky action bar below owns the bottom edge, - and padding under it would be 14px the bar could never cover. */ + A flex column of exactly two things — the scroll region and the action + bar — rather than one scroller with a sticky bar inside it. Sticky kept + the bar in the scroll math, which produced both of its failure modes: a + window a few pixels shorter than the content scrolled by those few + pixels with nothing meaningful hidden, and a window taller than the + content left the bar floating at the end of the text instead of on the + window's edge. As a flex footer the bar is chrome: always on the bottom + edge, never part of what scrolls. */ position: absolute; inset: 0; + display: flex; + flex-direction: column; inline-size: auto; max-block-size: none; block-size: auto; - padding: 14px 16px 0; - overflow-y: auto; - display: block; + padding: 0; + overflow: hidden; } -/* Save and Cancel ride the bottom of the scrollport rather than the bottom of - the content: in a window the person sizes themselves, "scroll to find Save" - is a chore the chrome can simply remove. Stretched across the host's padding - and given a top border + opaque background so content sliding under it reads - as under it. +/* The scrollable half. `min-block-size: 0` is what lets a flex child actually + shrink below its content and scroll, instead of stretching its parent. */ +.atfb-valwin__scroll { + flex: 1 1 auto; + min-block-size: 0; + overflow-y: auto; + padding: 14px 16px; +} - `inset-block-end: 0`, exactly — a negative offset here parks part of the bar - past the scrollport edge, where the window body's `overflow: hidden` cuts - it in half. */ +/* The fixed half: Save and Cancel on the window's bottom edge, top border and + opaque background so content scrolling beneath reads as beneath. */ .atfb-valwin--window .atfb-modal__actions { - position: sticky; - inset-block-end: 0; - margin-inline: -16px; - margin-block-start: 12px; + flex: 0 0 auto; + margin: 0; padding: 10px 16px; background: var( --atfb-bg ); border-block-start: 1px solid var( --atfb-border ); diff --git a/assets/js/builder.js b/assets/js/builder.js index 6151729..6af8cf3 100644 --- a/assets/js/builder.js +++ b/assets/js/builder.js @@ -3102,7 +3102,13 @@ var allTerrainFormsBuilder = function(exports) { autofocus: ".atfb-valwin__pane:not([hidden]) input, .atfb-valwin__pane:not([hidden]) textarea", render: (body) => { const host = el("div", { class: "atfa atfb-valwin atfb-valwin--window" }); - buildEditor(host, options, state, close, "window"); + const scroll = el("div", { class: "atfb-valwin__scroll" }); + host.append(scroll); + buildEditor(scroll, options, state, close, "window"); + const actions = scroll.querySelector(".atfb-modal__actions"); + if (actions) { + host.append(actions); + } body.append(host); }, // Fires however the window closes — Save, Cancel, the title-bar X, diff --git a/assets/js/builder.min.js b/assets/js/builder.min.js index a2ec17d..71be553 100644 --- a/assets/js/builder.min.js +++ b/assets/js/builder.min.js @@ -1,3 +1,3 @@ -var allTerrainFormsBuilder=function(Z){"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:t,origin:s}=e,a=s.clientX,i=s.clientY;let o=!1,l=!1,c=null,d=null,h=0,y=0;const b=()=>{document.removeEventListener("pointermove",E),document.removeEventListener("pointerup",q),document.removeEventListener("pointercancel",j),document.removeEventListener("keydown",z),window.removeEventListener("blur",j),c?.remove(),c=null,t.source.classList.remove("atf-is-dragging"),d?.onLeave?.(g),d=null,this.active=null,this.lastEndMs=Date.now()},g={payload:t,isFinished:()=>l,cancel:($="caller")=>{l||(l=!0,b(),e.onCancel?.($))}},C=$=>{o=!0,t.source.classList.add("atf-is-dragging");const A=t.source.getBoundingClientRect();h=t.ghost?.offsetX??a-A.left,y=t.ghost?.offsetY??i-A.top,c=t.ghost?.element??t.source.cloneNode(!0),c.classList.add("atf-drag-ghost"),c.style.width=`${A.width}px`,document.body.appendChild(c),_($)},_=$=>{c&&(c.style.transform=`translate3d(${$.clientX-h}px, ${$.clientY-y}px, 0)`)},E=$=>{if(l)return;if(!o){if(Math.hypot($.clientX-a,$.clientY-i)<4)return;C($)}_($);const A=this.hitTest($.clientX,$.clientY);A!==d&&(d?.onLeave?.(g),d=A,d?.onEnter?.(g))},q=$=>{if(l)return;if(!o){l=!0,b(),e.onClickOnly?.();return}const A=d;if(l=!0,b(),A&&A.accept(t)){e.onCommit?.(A),A.onDrop(g,{clientX:$.clientX,clientY:$.clientY});return}e.onCancel?.(A?"rejected":"no-target")},j=()=>g.cancel("pointercancel"),z=$=>{$.key==="Escape"&&g.cancel("escape")};return document.addEventListener("pointermove",E),document.addEventListener("pointerup",q),document.addEventListener("pointercancel",j),document.addEventListener("keydown",z),window.addEventListener("blur",j),this.active=g,g}registerDropTarget(e){return this.targets=this.targets.filter(t=>t.id!==e.id),this.targets.push(e),()=>{this.targets=this.targets.filter(t=>t.id!==e.id)}}isDragging(){return this.active!==null}recentlyEndedDrag(e=500){return Date.now()-this.lastEndMso.right||to.bottom)continue;const l=Ft(i.element);if(l>a){s=i,a=l;continue}l===a&&s&&qt(i.element,s.element)&&(s=i)}return s}}function Ft(n){let e=0,t=n;for(;t;)e++,t=t.parentElement;return e}function qt(n,e){return(e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0}function we(){return window.wp?.os??null}let xe=null;function te(){const n=we();return n?.dragManager?n.dragManager:(xe||(xe=new Dt),xe)}function Mt(n){const e=a=>{const i=a.detail?.payload;return i&&n.includes(i.type)?i.source:null},t=a=>e(a)?.classList.add("atf-is-dragging"),s=a=>e(a)?.classList.remove("atf-is-dragging");return document.addEventListener("os.drag.start",t),document.addEventListener("os.drag.end",s),()=>{document.removeEventListener("os.drag.start",t),document.removeEventListener("os.drag.end",s)}}function je(n,e,t,s,a){const i=e.getBoundingClientRect();return a&&(a.style.width=`${Math.round(i.width)}px`,a.style.maxWidth=`${Math.round(i.width)}px`,a.style.boxSizing="border-box"),{type:n,source:e,data:t,ghost:{element:a,offsetX:s.clientX-i.left,offsetY:s.clientY-i.top,hint:{neutral:"",accept:"",reject:"",hidden:!0}}}}function He(n,e,t,s){const a=Array.from(n.querySelectorAll(e)).filter(i=>i!==s&&!i.classList.contains("atf-drag-ghost"));for(let i=0;ia.fetch(l,c,{source:"allterrain-forms"}):(l,c)=>fetch(l,c))(t,{credentials:"same-origin",...e,headers:s});if(!o.ok){let l=`Request failed with status ${o.status}.`,c="";try{const d=await o.json();l=d.message??l,c=d.code??""}catch{}throw new le(l,o.status,c)}if(o.status!==204)return await o.json()}const Y=n=>_e(n);async function Nt(n){if(!B?.wpRestUrl)throw new le("AllTerrain Forms is not configured on this page.",0);const e=B.nonce?{"X-WP-Nonce":B.nonce}:{},t=we(),s=Ue(B.wpRestUrl,n),a=t?.fetch?await t.fetch(s,{credentials:"same-origin",headers:e},{source:"allterrain-forms"}):await fetch(s,{credentials:"same-origin",headers:e});if(!a.ok)throw new le(`Request failed with status ${a.status}.`,a.status);return await a.json()}function Rt(n){if(!n||!n.includes("&"))return n;const e=document.createElement("textarea");return e.innerHTML=n,e.value}const ee=(n,e)=>_e(n,{method:"POST",body:JSON.stringify(e)}),ce=n=>_e(n,{method:"DELETE"});function ze(n){const e=new URLSearchParams;for(const[s,a]of Object.entries(n))a===void 0||a===""||a===!1||e.set(s,String(a));const t=e.toString();return t?`?${t}`:""}function de(n){const e=n?.schema?.settings;return e&&(!e.themeOverrides||Array.isArray(e.themeOverrides))&&(e.themeOverrides={...e.themeOverrides}),n}const O={config:()=>Y("/config"),listForms:()=>Y("/forms"),getForm:n=>Y(`/forms/${n}`).then(de),createForm:n=>ee("/forms",n).then(de),updateForm:(n,e)=>ee(`/forms/${n}`,e).then(de),duplicateForm:n=>ee(`/forms/${n}/duplicate`,{}).then(de),deleteForm:n=>ce(`/forms/${n}`),preview:(n,e)=>ee(`/forms/${n}/preview`,e),pages:()=>Nt("wp/v2/pages?per_page=100&status=publish&orderby=title&order=asc&_fields=id,title").then(n=>n.map(e=>({id:e.id,title:Rt(e.title?.rendered??"")||`#${e.id}`}))),mergeTags:n=>Y(`/forms/${n}/merge-tags`).then(e=>e.groups),analytics:(n,e="")=>Y(`/forms/${n}/analytics${e?`?dimension=${encodeURIComponent(e)}`:""}`),demoStatus:()=>Y("/demo"),demoSeed:n=>ee("/demo",n?{count:n}:{}),demoRemove:()=>ce("/demo"),listEntries:n=>Y(`/entries${ze(n)}`),getEntry:n=>Y(`/entries/${n}`),updateEntry:(n,e)=>ee(`/entries/${n}`,e),deleteEntry:n=>ce(`/entries/${n}`),exportEntries:n=>Y(`/entries/export${ze(n)}`),listThemes:()=>Y("/themes"),saveTheme:n=>ee("/themes",n),deleteTheme:n=>ce(`/themes/${n}`)};function r(n,e={}){const t=document.createElement(n);e.class&&(t.className=e.class),e.text!==void 0&&(t.textContent=e.text),e.html!==void 0&&(t.innerHTML=e.html),e.title&&(t.title=e.title),e.type&&"type"in t&&(t.type=e.type),e.value!==void 0&&"value"in t&&(t.value=e.value),e.placeholder!==void 0&&"placeholder"in t&&(t.placeholder=e.placeholder),e.href&&"href"in t&&(t.href=e.href);for(const[s,a]of Object.entries(e.attrs??{}))a===void 0||a===!1||t.setAttribute(s,a===!0?"":String(a));Object.assign(t.style,e.style??{});for(const[s,a]of Object.entries(e.on??{}))t.addEventListener(s,a);for(const s of e.children??[])s==null||s===!1||t.append(s);return t}function R(n){n.replaceChildren()}function W(n){return r("span",{class:`dashicons ${n.startsWith("dashicons-")?n:`dashicons-${n}`}`,attrs:{"aria-hidden":"true"}})}function f(n,e,t){const s=e.matches("input, select, textarea, button")?e:e.querySelector("input, select, textarea");if(s){const a=s.id||`atf-c-${Math.random().toString(36).slice(2,9)}`;return s.id=a,r("div",{class:"atfb-row",children:[r("label",{class:"atfb-row__label",text:n,attrs:{for:a}}),e,t?r("p",{class:"atfb-row__hint",text:t}):null]})}return r("div",{class:"atfb-row",children:[r("span",{class:"atfb-row__label",text:n}),e,t?r("p",{class:"atfb-row__hint",text:t}):null]})}function k(n,e,t=""){return r("input",{class:"atfb-input",type:"text",value:n,placeholder:t,on:{input:s=>e(s.target.value)}})}function G(n,e){if(H("os-number-field")){const t=document.createElement("os-number-field");return t.setAttribute("value",n),t.classList.add("atfb-field"),t.addEventListener("os-input-change",s=>{e(String(s.detail?.value??""))}),t}return r("input",{class:"atfb-input",type:"number",value:n,on:{input:t=>e(t.target.value)}})}function he(n,e,t=4){const s=r("textarea",{class:"atfb-input atfb-input--area",attrs:{rows:t},on:{input:a=>e(a.target.value)}});return s.value=n,s}function N(n,e,t){if(H("os-select")&&H("os-option")){const s=document.createElement("os-select");s.setAttribute("value",n),s.classList.add("atfb-field");for(const a of e){const i=document.createElement("os-option");i.setAttribute("value",a.value),i.textContent=a.label,s.append(i)}return s.addEventListener("os-pick",a=>{t(String(a.detail?.value??""))}),s}return r("select",{class:"atfb-input atfb-select",on:{change:s=>t(s.target.value)},children:e.map(s=>r("option",{value:s.value,text:s.label,attrs:{selected:s.value===n}}))})}function D(n,e,t){if(H("os-checkbox-label")){const a=document.createElement("os-checkbox-label");return a.setAttribute("label",n),a.classList.add("atfb-check"),e&&a.setAttribute("checked",""),a.addEventListener("os-checkbox-change",i=>{t(!!i.detail?.checked)}),a}const s=r("input",{type:"checkbox",on:{change:a=>t(a.target.checked)}});return s.checked=e,r("label",{class:"atfb-check",children:[s,r("span",{text:n})]})}function L(n,e,t="secondary",s){const a=[s?W(s):null,r("span",{text:n})];if(H("os-button")){const i=document.createElement("os-button");i.setAttribute("variant",t),i.setAttribute("type","button"),i.classList.add("atfb-button",`atfb-button--${t}`),i.addEventListener("click",e);for(const o of a)o&&i.append(o);return i}return r("button",{class:`atfb-button atfb-button--${t}`,type:"button",on:{click:e},children:a})}function H(n){return typeof customElements<"u"&&!!customElements.get(n)}const Pt=["os-button","os-checkbox-label","os-number-field","os-select","os-option","os-segmented","os-segment","os-color-field","os-empty-state"];let ue=null;function Bt(){if(ue)return ue;const n=window.wp?.os;return ue=n?.loadComponents?n.loadComponents(Pt).catch(()=>{}):Promise.resolve(),ue}async function ke(n,e=""){const t=window.wp?.os;return t?.confirm?t.confirm({title:e,message:n,danger:!0}):window.confirm(n)}function U(n,e="",t="info"){const s=window.wp?.os;if(s?.notify){s.notify({title:n,body:e,type:t});return}console.info(`[AllTerrain Forms] ${n}${e?`: ${e}`:""}`)}function Wt(n){let e=0,t;return(...s)=>{t=s,!e&&(e=window.requestAnimationFrame(()=>{e=0,n(...t)}))}}function Se(n,e){let t=0;return(...s)=>{window.clearTimeout(t),t=window.setTimeout(()=>n(...s),e)}}function jt(n){try{return window.localStorage.getItem(n)??""}catch{return""}}function Ht(n,e){try{window.localStorage.setItem(n,e)}catch{}}function Ye(n){const e=n.closest(".os-window__body");e&&(e.addEventListener("scroll",()=>{e.scrollTop&&(e.scrollTop=0),e.scrollLeft&&(e.scrollLeft=0)},{passive:!0}),e.scrollTop=0,e.scrollLeft=0)}function Ge(){const n=[window];try{window.parent&&window.parent!==window&&n.push(window.parent)}catch{}return n}function Ut(n){const e=n.wp?.os?.windowManager?.getAll?.()??[];for(const t of e){const s=t.iframe??t.element?.querySelector?.("iframe");if(s&&s.contentWindow===window)return t}return null}const zt=4e3,Yt=100;function Gt(n,e){const t=Date.now()+zt,s=()=>{const a=Ut(n);if(a&&a.id!==e){typeof a.close=="function"?a.close():n.wp?.os?.windowManager?.remove?.(a.id);return}!a&&Date.now()0?{form:t}:void 0;t>0&&Zt(t);for(const a of Ge())if(a.wp?.os?.openWindow?.(e,{source:"handoff",params:s})){window.setTimeout(()=>Gt(a,e),0);return}}function Kt(){document.addEventListener("click",n=>{const e=n.target?.closest?.("[data-atf-open-window]");if(!e)return;n.preventDefault();const t=e.getAttribute("data-atf-open-window")??"";for(const s of Ge())if(s.wp?.os?.openWindow?.(t,{source:"handoff"}))return})}const Vt="allterrain-forms/requested-form";function Zt(n){try{window.sessionStorage.setItem(Vt,String(n))}catch{}}function Xe(n){return`allterrain-forms/requested-form-${n}`}function Jt(n){try{const e=window.sessionStorage.getItem(Xe(n));return window.sessionStorage.removeItem(Xe(n)),Number(e)||0}catch{return 0}}const Le={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"},Ke=["empty","not_empty"];function Ve(n,e){const t=n.find(s=>s.id===e);return t?t.label||"an untitled question":null}function Ze(n,e,t){return n.find(i=>i.id===e)?.choices?.find(i=>i.value===t)?.label||t}function Qt(n,e){const t=Le[n.operator]??String(n.operator);if(Ke.includes(n.operator))return t;const s=Ze(e,n.field,n.value);return`${n.operator==="is"?"":`${t} `}${s!==""?s:"(nothing)"}`}function Je(n,e,t=0){const s=Ve(e,n.field),a=Le[n.operator]??String(n.operator);if(s===null)return[{kind:"field",text:"a question that no longer exists",fieldId:n.field,missing:!0}];const i=[{kind:"field",text:s,fieldId:n.field,missing:!1},{kind:"operator",text:a,operator:n.operator,ruleIndex:t}];if(Ke.includes(n.operator))return i;const o=Ze(e,n.field,n.value);return i.push({kind:"value",text:o!==""?o:"(nothing)",raw:n.value,sourceId:n.field,ruleIndex:t}),i}function es(n,e){const t=n.logic;if(!t?.enabled||!t.rules.length)return[];const s=[{kind:"verb",text:t.action==="hide"?"Hidden when":"Shown when"}];return t.rules.forEach((a,i)=>{i>0&&s.push({kind:"join",text:t.match==="all"?"and":"or"}),s.push(...Je(a,e,i))}),s}function Qe(n){return n.map(e=>e.text).join(" ")}function ts(n,e){return Qe(Je(n,e))}function pe(n){const e=[];for(const t of n){const s=t.logic;if(s?.enabled)for(const a of s.rules)!a.field||a.field===t.id||e.push({from:a.field,to:t.id,label:ts(a,n),short:Qt(a,n),action:s.action,broken:Ve(n,a.field)===null})}return e}function ss(n){const e=new Map,t=new Set;for(const s of pe(n)){const a=`${s.from}->${s.to}`;s.broken||t.has(a)||(t.add(a),e.set(s.from,(e.get(s.from)??0)+1))}return e}const et=10,tt=22,se="http://www.w3.org/2000/svg";class ns{constructor(e){this.edges=[],this.teardowns=[],this.frame=0,this.host=e,this.svg=document.createElementNS(se,"svg"),this.svg.setAttribute("class","atfb-logicmap"),this.svg.setAttribute("aria-hidden","true"),this.svg.setAttribute("focusable","false"),e.append(this.svg);const t=()=>this.schedule();window.addEventListener("resize",t),this.teardowns.push(()=>window.removeEventListener("resize",t));const s=e.closest(".atfb__canvas")??e;if(s.addEventListener("scroll",t,{passive:!0}),this.teardowns.push(()=>s.removeEventListener("scroll",t)),typeof ResizeObserver<"u"){const a=new ResizeObserver(t);a.observe(e),this.teardowns.push(()=>a.disconnect())}}setEdges(e){this.edges=e,this.schedule()}highlight(e){this.svg.classList.toggle("is-focused",!!e),this.svg.querySelectorAll("[data-from]").forEach(t=>{const s=e&&(t.dataset.from===e||t.dataset.to===e);t.classList.toggle("is-lit",!!s)})}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 t=new Map;for(const s of this.edges){const a=this.cardRect(s.from),i=this.cardRect(s.to);if(!a||!i)continue;const o=t.get(s.from)??0;t.set(s.from,o+1),this.drawEdge(s,a,i,e,o)}}cardRect(e){const t=this.host.querySelector(`[data-atfb-card="${CSS.escape(e)}"]`);return t?t.getBoundingClientRect():null}drawEdge(e,t,s,a,i){const o=t.right-a.left,l=t.top+t.height/2-a.top,c=s.right-a.left,d=s.top+s.height/2-a.top,h=Math.max(0,a.width-et-Math.max(o,c)),y=22+i*11+Math.min(22,Math.abs(d-l)/8),b=Math.max(12,Math.min(y,h*.4)),g=document.createElementNS(se,"path");g.setAttribute("d",`M ${o} ${l} C ${o+b} ${l}, ${c+b} ${d}, ${c} ${d}`),g.setAttribute("class",`atfb-logicmap__path is-${e.action}${e.broken?" is-broken":""}`),g.dataset.from=e.from,g.dataset.to=e.to;const C=document.createElementNS(se,"title");C.textContent=e.label,g.append(C);const _=document.createElementNS(se,"circle");_.setAttribute("cx",String(c)),_.setAttribute("cy",String(d)),_.setAttribute("r","3.5"),_.setAttribute("class",`atfb-logicmap__dot is-${e.action}${e.broken?" is-broken":""}`),_.dataset.from=e.from,_.dataset.to=e.to,this.svg.append(g,_);const E=document.createElementNS(se,"text");E.setAttribute("x",String(a.width-et)),E.setAttribute("y",String(d+3)),E.setAttribute("text-anchor","end"),E.setAttribute("class","atfb-logicmap__label"),E.dataset.from=e.from,E.dataset.to=e.to,E.textContent=e.short.length>tt?`${e.short.slice(0,tt-1)}…`:e.short;const q=document.createElementNS(se,"title");q.textContent=e.label,E.append(q),this.svg.append(E)}}const as={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 is(n){return as[n]??"text"}function st(n,e){const t=/^choice:(\d+):(label|value)$/.exec(e);return String(t?n.choices?.[Number(t[1])]?.[t[2]]??"":n[e]??"")}function J(n){const{value:e,onInput:t,onCommit:s}=n,a=r("span",{class:`${n.class} atfb-editable`,text:e,attrs:{contenteditable:"plaintext-only",role:"textbox",spellcheck:"false","data-placeholder":n.placeholder}});return n.bind&&(a.dataset.atfbBind=n.bind),a.addEventListener("pointerdown",i=>i.stopPropagation()),a.addEventListener("input",()=>t(a.textContent??"")),a.addEventListener("keydown",i=>{i.key==="Enter"&&(i.preventDefault(),a.blur()),i.key==="Escape"&&(a.textContent=e,a.blur()),i.stopPropagation()}),a.addEventListener("blur",()=>s?.()),a}function rs(n){const e=r("input",{class:"atf-choice__input",type:n==="checkboxes"||n==="multiselect"?"checkbox":"radio"});return e.disabled=!0,e}function os(n,e,t){const s=is(n.type),a=J({value:n.label,placeholder:"Write the question…",class:"atf-label",bind:"label",onInput:o=>t.edit(l=>{l.label=o}),onCommit:()=>t.restructure(()=>{})}),i=[s==="static"||s==="toggle"?null:a,cs(n,e,s,t),ls(n,e,t)];return r("div",{class:"atfb-preview atf-form",children:[r("div",{class:`atf-field atf-field--${n.type}`,children:i})]})}function ls(n,e,t){if(!e?.supports.includes("hint"))return null;const s=J({value:n.hint??"",placeholder:"Add a hint…",class:"atf-hint",bind:"hint",onInput:a=>t.edit(i=>{i.hint=a})});return s.setAttribute("aria-label","Hint"),r("p",{class:"atfb-preview__hint",children:[s]})}function cs(n,e,t,s){switch(t){case"text":return Ee(n,"atf-input",s);case"textarea":return Ee(n,"atf-input atf-textarea",s,!0);case"select":return r("div",{class:"atfb-preview__select",children:[Ee(n,"atf-input atf-select",s)]});case"options":return hs(n,s);case"toggle":return r("div",{class:n.type==="switch"?"atf-toggle atf-toggle--switch":"atf-toggle",children:[(()=>{const a=r("input",{class:"atf-toggle__input",type:"checkbox"});return a.disabled=!0,a})(),J({value:n.label||"",placeholder:n.type==="consent"?"What are they agreeing to?…":"What does this turn on?…",class:"atf-toggle__label",bind:"label",onInput:a=>s.edit(i=>{i.label=a}),onCommit:()=>s.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 us(n,e,s);default:return r("div",{class:"atfb-preview__stack",children:[r("p",{class:"atfb-preview__summary",text:`${e?.label??n.type} — set this up in the panel on the right.`}),n.type==="repeater"?ds(n,s):null]})}}function Ee(n,e,t,s=!1){const a=J({value:n.placeholder??"",placeholder:n.type==="select"||n.type==="country"?"Choose…":"Placeholder…",class:`${e} atfb-preview__box${s?" atfb-preview__box--tall":""}`,bind:"placeholder",onInput:i=>t.edit(o=>{o.placeholder=i})});return a.setAttribute("aria-label","Placeholder"),a}function Ce(n,e,t,s,a,i){return r("span",{class:`atf-button ${t} atfb-preview__button`,children:[J({value:n,placeholder:e,class:"atfb-preview__button-text",bind:s,onInput:o=>a.edit(l=>i(l,o))})]})}function ds(n,e){return Ce(String(n.addLabel??""),"Add another","atf-button--secondary","addLabel",e,(t,s)=>{t.addLabel=s})}function hs(n,e){const t=r("div",{class:"atf-choices__list"});return(n.choices??[]).forEach((s,a)=>{t.append(r("div",{class:"atf-choice atfb-preview__option",children:[rs(n.type),J({value:s.label,placeholder:"Option…",class:"atf-choice__label",bind:`choice:${a}:label`,onInput:i=>{e.edit(o=>{const l=o.choices?.[a];if(!l)return;const c=!l.value||l.value===l.label;l.label=i,c&&(l.value=i)})}}),r("button",{class:"atfb-preview__remove",type:"button",title:"Remove this option",attrs:{"aria-label":`Remove ${s.label||"this option"}`},on:{pointerdown:i=>i.stopPropagation(),click:i=>{i.stopPropagation(),e.restructure(o=>{o.choices.splice(a,1)})}},children:[r("span",{text:"×"})]})]}))}),t.append(r("button",{class:"atfb-preview__add",type:"button",on:{pointerdown:s=>s.stopPropagation(),click:s=>{s.stopPropagation(),e.restructure(a=>{const i=a.choices.length+1;a.choices.push({label:`Option ${i}`,value:`Option ${i}`})})}},children:[r("span",{text:"+ Add option"})]})),r("fieldset",{class:"atf-choices",children:[t]})}function us(n,e,t){return n.type==="heading"?J({value:n.label,placeholder:"Section heading…",class:"atf-heading",bind:"label",onInput:s=>t.edit(a=>{a.label=s}),onCommit:()=>t.restructure(()=>{})}):n.type==="divider"?r("hr",{class:"atf-divider"}):n.type==="page_break"?r("div",{class:"atfb-preview__stack",children:[r("p",{class:"atfb-progress-name",children:[J({value:n.label,placeholder:"Name this step…",class:"atf-progress__label",bind:"label",onInput:s=>t.edit(a=>{a.label=s}),onCommit:()=>t.restructure(()=>{})})]}),r("p",{class:"atfb-preview__summary",text:"Everything after this is a new page."}),r("div",{class:"atf-nav atfb-preview__nav",children:[Ce(String(n.prevLabel??""),"Back","atf-button--secondary","prevLabel",t,(s,a)=>{s.prevLabel=a}),Ce(String(n.nextLabel??""),"Next","","nextLabel",t,(s,a)=>{s.nextLabel=a})]})]}):r("p",{class:"atfb-preview__summary",text:`${e?.label??n.type} — nothing is shown to the visitor here.`})}const $e=new Map;function Ae(n){let e=$e.get(n);return e||(e=O.mergeTags(n).catch(()=>[]),$e.set(n,e)),e}function ps(n){$e.delete(n)}function fs(n){const e=new Map;for(const t of n)for(const s of t.items)e.set(s.tag,s);return e}function ms(n,e){const t=fs(e);return n.replace(/\{[a-z_]+(?::[^}]*)?\}/gi,s=>{const a=t.get(s.toLowerCase());return a?a.sample:s})}function bs(n){return/\{[a-z_]+(?::[^}]*)?\}/i.test(n)}let Q=null;function ae(){Q?.remove(),Q=null}typeof document<"u"&&(document.addEventListener("pointerdown",n=>{const e=n.target;e?.closest(".atfb-tagpick__open")||Q&&!Q.contains(e)&&ae()}),document.addEventListener("keydown",n=>{n.key==="Escape"&&Q&&(ae(),n.stopPropagation())}));function nt(n,e){const t=n.selectionStart??n.value.length,s=n.selectionEnd??n.value.length;n.value=n.value.slice(0,t)+e+n.value.slice(s);const a=t+e.length;n.setSelectionRange(a,a),n.focus(),n.dispatchEvent(new Event("input",{bubbles:!0}))}function gs(n){let e=n.parentElement;for(;e&&e!==document.body;){const t=getComputedStyle(e).overflowY;if(t==="auto"||t==="scroll"||t==="hidden")return e.getBoundingClientRect().bottom;e=e.parentElement}return window.innerHeight}function vs(n,e){const t=r("input",{class:"atfb-input atfb-tagpick__search",type:"search",placeholder:"Search values…",attrs:{"aria-label":"Search values"}}),s=r("div",{class:"atfb-tagpick__list"}),a=i=>{s.replaceChildren();const o=i.trim().toLowerCase();let l=0;for(const c of n){const d=c.items.filter(h=>!o||h.label.toLowerCase().includes(o)||h.tag.toLowerCase().includes(o));if(!d.length){c.empty&&!o&&!c.items.length&&s.append(r("p",{class:"atfb-tagpick__group",text:c.label}),r("p",{class:"atfb-tagpick__empty",text:c.empty}));continue}s.append(r("p",{class:"atfb-tagpick__group",text:c.label}));for(const h of d)l+=1,s.append(r("button",{class:"atfb-tagpick__item",type:"button",on:{click:()=>{e(h.tag),ae()}},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&&s.append(r("p",{class:"atfb-tagpick__empty",text:`Nothing matches “${i}”.`}))};return a(""),t.addEventListener("input",()=>a(t.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."}),t,s]})}function at(n,e){const t=r("button",{class:"atfb-button atfb-button--ghost atfb-tagpick__open",type:"button",title:"Insert a value from the submission",children:[W("shortcode"),r("span",{text:"Insert a value"})]}),s=r("div",{class:"atfb-taggable",children:[n,r("div",{class:"atfb-taggable__tools",children:[t]})]}),a=e.preview===!1?null:r("p",{class:"atfb-taggable__preview"});a&&s.append(a);const i=()=>{if(a){if(!bs(n.value)){a.textContent="",a.hidden=!0;return}Ae(e.formId).then(o=>{a.hidden=!1,a.replaceChildren(r("span",{class:"atfb-taggable__preview-label",text:"Reads as"}),r("span",{text:ms(n.value,o)}))})}};return n.addEventListener("input",i),i(),t.addEventListener("click",o=>{if(o.stopPropagation(),Q&&s.contains(Q)){ae();return}ae(),Ae(e.formId).then(l=>{const c=vs(l,d=>{nt(n,d),i()});s.append(c),Q=c,(window.innerHeight-c.getBoundingClientRect().topgs(s))&&c.classList.add("atfb-tagpick--above"),c.querySelector(".atfb-tagpick__search")?.focus()})}),s}function it(n,e){const t=parseFloat(String(n??""));return Number.isFinite(t)?t:e}function rt(n,e){let t=e[0];for(const s of e)Math.abs(s.at-n)n.accent??"#2271b1",apply:n=>({accent:n,"accent-soft":`color-mix( in srgb, ${n} 12%, transparent )`,"border-focus":n,"focus-ring-color":n,"button-bg":n,"button-bg-hover":`color-mix( in srgb, ${n} 88%, #000 )`})},{id:"roundness",label:"Roundness",hint:"Corners, everywhere at once.",kind:"scale",steps:Te.map(({value:n,label:e})=>({value:n,label:e})),owns:["radius-field","radius-button","radius-card","radius-check"],read:n=>rt(it(n["radius-field"],4),Te),apply:n=>{const e=Te.find(t=>t.value===n)?.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:Ie.map(({value:n,label:e})=>({value:n,label:e})),owns:["pad-field-x","pad-field-y","gap-fields","gap-label","button-pad-x","button-pad-y"],read:n=>rt(it(n["pad-field-y"],9),Ie),apply:n=>{const e=Ie.find(t=>t.value===n)?.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:ys,owns:["shadow-field","shadow-field-focus","shadow-button","shadow-button-hover","shadow-card"],read:n=>{const e=n["shadow-card"]??"none";return e==="none"||e.trim()===""?n["shadow-field"]&&n["shadow-field"]!=="none"?"hard":"none":e.includes("0 1px")||e.includes("2px")?"subtle":"lifted"},apply:n=>{switch(n){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:ws,owns:["field-style"],read:n=>n["field-style"]??"outline",apply:n=>({"field-style":n})},{id:"labels",label:"Labels",hint:"Where the question sits relative to the answer.",kind:"choice",steps:xs,owns:["label-position"],read:n=>n["label-position"]??"top",apply:n=>({"label-position":n})}]}function _s(n){return Oe().find(e=>e.owns.includes(n))??null}function ot(n){let e=n.activeSlug,t={...n.overrides},s=n.themes;const a=u=>{t=u,n.onOverridesReplaced?.({...u})},i=r("div",{class:"atfs-preview__frame"}),o=r("div",{class:"atfs-controls__body"}),l=r("div",{class:"atfs-quick"}),c=r("div",{class:"atfs-themes"}),d=Se(async()=>{try{const u=await n.previewFor(e,t),p=i.closest(".atf-studio__preview"),m=p?.scrollTop??0;i.innerHTML=u,p&&(p.scrollTop=m),document.dispatchEvent(new CustomEvent("atf-refresh"))}catch(u){R(i),i.append(r("p",{class:"atfb-error",text:u instanceof Error?u.message:"Preview failed."}))}},180),h={"label-position":"atf-labels-","field-style":"atf-fields-"},y=(u,p,m)=>{const v=m.replace(/[^a-z0-9_-]/gi,"");for(const w of[...u.classList])w.startsWith(p)&&u.classList.remove(w);v&&u.classList.add(p+v)},b=u=>{const p=i.querySelector(".atf-form-wrap"),m=p?.querySelector(".atf-form");if(p)for(const[v,w]of Object.entries(u))w===""?p.style.removeProperty(`--atf-${v}`):p.style.setProperty(`--atf-${v}`,w),m&&h[v]&&y(m,h[v],w||(s.find(I=>I.slug===e)?.resolved[v]??""))},g=u=>{b(u.resolved);const p=i.querySelector(".atf-form");p&&(y(p,"atf-theme-",u.slug),p.classList.toggle("atf-is-dark",!!u.dark))},C=u=>t[u.token]!==void 0?t[u.token]:s.find(m=>m.slug===e)?.resolved?.[u.token]??u.default,_=()=>{R(c);for(const u of s){const p=r("button",{class:`atfs-theme${u.slug===e?" is-active":""}`,type:"button",attrs:{"aria-pressed":u.slug===e,title:u.description},children:[r("span",{class:"atfs-theme__chip",style:{background:u.resolved.surface??"#fff",borderColor:u.resolved.border??"#ccc",borderRadius:u.resolved["radius-field"]??"4px",boxShadow:u.resolved["shadow-card"]??"none"},children:[r("span",{class:"atfs-theme__accent",style:{background:u.resolved.accent??"#2271b1",borderRadius:u.resolved["radius-button"]??"4px"}})]}),r("span",{class:"atfs-theme__name",text:u.label}),u.custom?r("span",{class:"atfb-badge",text:"yours"}):null],on:{click:()=>{e=u.slug,a({}),n.onTheme(e),g(u),_(),z(),j(),Tt()}}});c.append(p)}},E=()=>{const p={...s.find(m=>m.slug===e)?.resolved??{}};for(const[m,v]of Object.entries(t))p[m]=v;return p},q=u=>{const p=l.closest(".atf-studio__controls"),m=p?.scrollTop??0;u(),p&&(p.scrollTop=m)},j=Se(()=>q(x),150),z=()=>{const u=E(),p=l.querySelectorAll(".atfs-dial");Oe().forEach((m,v)=>{const w=p[v];if(!w)return;const I=m.read(u);if(m.kind==="colour"){const T=w.querySelector('input[type="color"]'),X=w.querySelector("input.atfb-input");T&&document.activeElement!==T&&(T.value=fe(I)),X&&document.activeElement!==X&&(X.value=I);return}w.querySelectorAll(".atfs-segment").forEach((T,X)=>{const V=m.steps?.[X]?.value===I;T.classList.toggle("is-on",V),T.setAttribute("aria-pressed",String(V))})})},$=(u,p)=>{const m=u.apply(p,E());for(const[v,w]of Object.entries(m))t[v]=w,n.onOverride(v,w);b(m),z(),j()},A=()=>{R(l);const u=E();for(const p of Oe()){const m=p.read(u);let v;if(p.kind==="colour"){const w=r("input",{class:"atfs-color",type:"color",value:fe(m),attrs:{"aria-label":p.label},on:{input:I=>$(p,I.target.value)}});v=r("div",{class:"atfs-color-row",children:[w,k(m,I=>$(p,I))]})}else v=r("div",{class:`atfs-segmented atfs-segmented--${p.kind}`,attrs:{role:"group","aria-label":p.label},children:(p.steps??[]).map(w=>r("button",{class:`atfs-segment${w.value===m?" is-on":""}`,type:"button",text:w.label,attrs:{"aria-pressed":w.value===m},on:{click:()=>$(p,w.value)}}))});l.append(r("div",{class:"atfs-dial",children:[r("div",{class:"atfs-dial__head",children:[r("span",{class:"atfs-dial__label",text:p.label}),r("span",{class:"atfs-dial__hint",text:p.hint})]}),v]}))}},x=()=>{R(o);const u=new Map;for(const m of n.tokens){const v=u.get(m.group)??[];v.push(m),u.set(m.group,v)}const p={colour:"Colour",shape:"Corners and borders",shadow:"Shadows",fields:"Field style",space:"Spacing",type:"Type",labels:"Labels",button:"Buttons",focus:"Focus ring",motion:"Motion"};for(const[m,v]of u)o.append(r("details",{class:"atfs-group",attrs:{open:m==="colour"},children:[r("summary",{text:p[m]??m}),...v.map(w=>F(w))]}))},F=u=>{const p=C(u),m=T=>{T===""?delete t[u.token]:t[u.token]=T,n.onOverride(u.token,T),b({[u.token]:T})};let v;if(u.control==="color"){const T=r("input",{class:"atfs-color",type:"color",value:fe(p),attrs:{"aria-label":`${u.label} colour`},on:{input:V=>{const oe=V.target.value;X.value=oe,m(oe)}}}),X=k(p,V=>{T.value=fe(V),m(V)});v=r("div",{class:"atfs-color-row",children:[T,X]})}else if(u.control==="select")v=N(p,(u.options??[]).map(T=>({value:T,label:T})),m);else if(u.control==="length"){const T=parseFloat(p)||0,X=u.unit??"px",V=u.token.includes("radius")?60:80,oe=r("input",{class:"atfs-range",type:"range",value:String(T),attrs:{min:"0",max:String(V),step:"1","aria-label":u.label},on:{input:ye=>{const Ot=`${ye.target.value}${X}`;It.value=Ot,m(Ot)}}}),It=k(p,ye=>{oe.value=String(parseFloat(ye)||0),m(ye)});v=r("div",{class:"atfs-length-row",children:[oe,It]})}else v=k(p,m);const w=f(u.label,v),I=_s(u.token);return I&&(w.classList.add("is-dialled"),w.append(r("span",{class:"atfs-owned",text:I.label}))),t[u.token]!==void 0&&(w.classList.add("is-overridden"),w.append(r("button",{class:"atfs-reset",type:"button",text:"Reset",attrs:{"aria-label":`Reset ${u.label} to the theme's value`},on:{click:()=>{m(""),q(x)}}}))),w},S=async()=>{const u=s.find(v=>v.slug===e),p=u?`${u.label} (mine)`:"My theme",m=window.prompt("Name this theme",p);if(m)try{const v={};for(const I of n.tokens){const T=C(I);T!==I.default&&(v[I.token]=T)}const w=await O.saveTheme({label:m,tokens:v});s=[...s.filter(I=>I.slug!==w.slug),w],n.onThemesChanged(s),e=w.slug,a({}),n.onTheme(e),_(),z(),q(x),U("Theme saved",w.label)}catch(v){U("Could not save the theme",v instanceof Error?v.message:"","error")}},P=async()=>{const u=s.find(p=>p.slug===e);if(u?.custom&&await ke(`Delete “${u.label}”? Forms using it fall back to Clean.`,"Delete theme"))try{await O.deleteTheme(u.id),s=s.filter(m=>m.slug!==u.slug),n.onThemesChanged(s),e="clean",a({}),n.onTheme(e),_(),z(),q(x);const p=s.find(m=>m.slug===e);p&&g(p)}catch(p){U("Could not delete the theme",p instanceof Error?p.message:"","error")}},M=async()=>{const u=s.find(v=>v.slug===e),p={label:u?.label??e,tokens:{...u?.tokens??{},...t}},m=JSON.stringify(p,null," ");try{await navigator.clipboard.writeText(m),U("Theme copied","Paste it into another site to import it.")}catch{window.prompt("Copy this theme",m)}},re=()=>{const u=window.prompt("Paste a theme");if(u)try{const p=JSON.parse(u);if(!p.tokens||typeof p.tokens!="object")throw new Error("That does not look like a theme.");for(const[m,v]of Object.entries(p.tokens))t[m]=String(v),n.onOverride(m,String(v));b({...t}),z(),q(x)}catch(p){U("Could not read that theme",p instanceof Error?p.message:"","error")}},At=L("Delete",()=>void P(),"danger"),Tt=()=>{const u=s.find(p=>p.slug===e);At.hidden=!u?.custom};return _(),A(),x(),d(),Tt(),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:[L("Save as a theme",()=>void S(),"primary"),L("Export",()=>void M()),L("Import",re),At]})]}),c]}),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"}),i]})]})]})}async function De(){const n=document.querySelector("[data-atfs-root]");if(!n||n.dataset.atfsMounted)return;n.dataset.atfsMounted="1",Ye(n);const e=n.querySelector("[data-atfs-bar]"),t=n.querySelector(".atfs__body")??n;try{const[s,a,i]=await Promise.all([O.config(),O.listThemes(),O.listForms()]);if(!i.length){R(t),t.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=i[0],l={},c=o.theme;const d=()=>{R(t),t.append(ot({themes:a,tokens:s.tokens,activeSlug:c,overrides:l,standalone:!0,onTheme:h=>{c=h},onOverride:(h,y)=>{y===""?delete l[h]:l[h]=y},onOverridesReplaced:h=>{l={...h}},previewFor:async(h,y)=>{const b=await O.getForm(o.id);b.schema.settings.theme=h,b.schema.settings.themeOverrides=y;const{html:g}=await O.preview(o.id,{schema:b.schema,theme:h});return g},onThemesChanged:h=>{a.length=0,a.push(...h)}}))};e&&(R(e),e.append(r("span",{class:"atfs__label",text:"Preview against"}),N(String(o.id),i.map(h=>({value:String(h.id),label:h.title||"(untitled)"})),h=>{o=i.find(y=>String(y.id)===h)??i[0],l={},d()}))),d()}catch(s){R(t),t.append(r("p",{class:"atfb-error",text:s instanceof Error?s.message:"Could not load themes."}))}}typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>void De()):De(),document.addEventListener("os-window-content-loaded",()=>void De()));function fe(n){const e=n.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"}const ks={min:-1,max:-1,sum:-1,avg:-1,round:-1,ceil:1,floor:1,abs:1,sqrt:1,pow:2},lt={"+":{precedence:1,right:!1},"-":{precedence:1,right:!1},"*":{precedence:2,right:!1},"/":{precedence:2,right:!1},"%":{precedence:2,right:!1},"^":{precedence:4,right:!0}};function Ss(n,e,t=[]){if(!n||!n.trim()||n.length>2e3)return null;const s=Ls(n,e,t),a=Es(s);if(!a)return null;const i=$s(a);if(!i)return null;const o=As(i);return o===null||!Number.isFinite(o)?null:o}function Ls(n,e,t){return n.replace(/\{([a-zA-Z0-9_]+)\}/g,(s,a)=>{const i=Object.prototype.hasOwnProperty.call(e,a)?e[a]:null,o=t.find(c=>c.id===a)??null,l=ct(i,o).toFixed(10).replace(/0+$/,"").replace(/\.$/,"");return l===""||l==="-"?"0":l})}function ct(n,e){if(typeof n=="boolean")return n?1:0;if(Array.isArray(n))return n.reduce((a,i)=>a+ct(i,e),0);if(n==null||n==="")return 0;const t=e?.choices??[];for(const a of t)if(String(a.value)===String(n)){if(typeof a.price=="number")return a.price;if(typeof a.points=="number")return a.points;break}const s=Number(n);return Number.isFinite(s)?s:0}function Es(n){const e=[];let t=0;for(;ti.precedence||l.precedence===i.precedence&&!i.right){e.push(t.pop());continue}break}t.push(a);break}case"(":t.push(a);break;case")":{for(;t.length&&t[t.length-1].type!=="(";)e.push(t.pop());if(!t.length)return null;if(t.pop(),t.length&&t[t.length-1].type==="function"){const i=t.pop();i.arity=s.length?s.pop():1,e.push(i)}break}}for(;t.length;){const a=t.pop();if(a.type==="(")return null;e.push(a)}return e}function As(n){const e=[];for(const t of n)switch(t.type){case"number":e.push(t.value);break;case"unary":{if(!e.length)return null;e.push(-e.pop());break}case"operator":{if(e.length<2)return null;const s=e.pop(),a=e.pop();switch(t.value){case"+":e.push(a+s);break;case"-":e.push(a-s);break;case"*":e.push(a*s);break;case"/":e.push(s===0?0:a/s);break;case"%":e.push(s===0?0:a%s);break;case"^":e.push(Math.pow(a,s));break;default:return null}break}case"function":{const s=t.arity??1;if(e.lengtht+s,0);case"avg":return e.reduce((t,s)=>t+s,0)/e.length;case"round":{const t=Math.max(-10,Math.min(10,Math.trunc(e[1]??0))),s=Math.pow(10,t);return Math.round(e[0]*s)/s}case"ceil":return Math.ceil(e[0]);case"floor":return Math.floor(e[0]);case"abs":return Math.abs(e[0]);case"sqrt":return e[0]<0?0:Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]??2);default:return null}}const Is=["sum","min","max","avg","round","ceil","floor","abs","sqrt","pow"],Os=["number","range","scale","rating","total","select","multiselect","radio","checkboxes","switch","quiz"];function Fe(n,e){return n.filter(t=>t.id!==e&&Os.includes(t.type))}function Ds(n,e){const t={};return Fe(n,e).forEach((s,a)=>{t[s.id]=a+1}),t}function Fs(n){const e=r("div",{class:"atfb-overlay"}),t=()=>{e.remove(),document.removeEventListener("keydown",s)},s=b=>{b.key==="Escape"&&t()},a=r("textarea",{class:"atfb-input atfb-formula__input",attrs:{rows:"3","aria-label":"Formula"}});a.value=String(n.field.formula??"");const i=r("p",{class:"atfb-formula__result",attrs:{"aria-live":"polite"}}),o=Ds(n.fields,n.field.id),l=()=>{const b=a.value.trim();if(b===""){i.textContent="Empty. Reference a question below to start.",i.classList.remove("is-error");return}const g=Ss(b,o,n.fields);if(g===null){i.textContent="This does not compute yet — check the braces and parentheses.",i.classList.add("is-error");return}const C=Fe(n.fields,n.field.id).map((_,E)=>`${_.label||_.id} = ${E+1}`).join(", ");i.textContent=`With sample answers (${C}): ${g}`,i.classList.remove("is-error")};a.addEventListener("input",l);const c=(b,g,C=0)=>r("button",{class:"atfb-formula__chip",type:"button",text:b,on:{click:()=>{if(nt(a,g),C>0){const _=(a.selectionStart??a.value.length)-C;a.setSelectionRange(_,_)}}}}),d=Fe(n.fields,n.field.id),h=r("div",{class:"atfb-formula__chips",children:d.length?d.map(b=>c(b.label||b.id,`{${b.id}}`)):[r("p",{class:"atfb-hint",text:"No number-shaped questions yet — add a number, scale or priced choice field and it appears here."})]}),y=r("div",{class:"atfb-formula__chips",children:Is.map(b=>c(`${b}()`,`${b}()`,1))});e.append(r("div",{class:"atfb-modal atfb-formula",attrs:{role:"dialog","aria-label":"Formula editor"},children:[r("h2",{text:"Formula"}),a,i,f("Your questions",h,"Click one to reference its answer."),f("Functions",y),r("div",{class:"atfb-modal__actions",children:[L("Cancel",t),L("Save formula",()=>{n.onSave(a.value.trim()),t()},"primary")]})]})),e.addEventListener("click",b=>{b.target===e&&t()}),document.addEventListener("keydown",s),n.root.append(e),l(),a.focus(),a.setSelectionRange(a.value.length,a.value.length)}const qs="allterrain-forms/form";function Ms(){return window.wp?.os?.relations??null}function dt(n){const e=n.closest("[data-window-id], .os-window");if(!e)return null;const t=e.getAttribute("data-window-id");if(t)return t;const s=e.id??"";return s?s.replace(/^wp-window-/,""):null}const Ns=6e3,ht=120;function ut(n,e){const t=Ms();if(qe.set(n,e),!t?.set)return;const s=i=>{if(me.get(n)!==a)return;const o=dt(n);if(!o){Date.now()s(i),ht);return}try{t.set(o,e)}catch(c){pt||(pt=!0,console.error("[AllTerrain Forms] The shell refused a window identity.",c,e)),me.delete(n);return}if(!e||t.get?.(o)?.id===e.id||Date.now()>=i){me.delete(n);return}window.setTimeout(()=>s(i),ht)},a=Symbol("atf-identity");me.set(n,a),s(Date.now()+Ns)}let pt=!1;const me=new WeakMap,qe=new Map;function Rs(){for(const[n,e]of qe){if(!n.isConnected){qe.delete(n);continue}ut(n,e)}}if(typeof document<"u")for(const n of["os-window-content-loaded","os-window-opened"])document.addEventListener(n,()=>Rs());function Ps(n,e){return{type:qs,id:n.id,label:n.title||"Untitled form",related:[{id:`allterrain-forms/entries-${n.id}`,label:"Entries for this form",url:`${e}admin.php?page=allterrain-forms-entries&form=${n.id}`,group:"allterrain-forms",groupLabel:"Forms",icon:"dashicons-list-view"}]}}const be={letters:{label:"Letters",chars:"A-Za-zÀ-ÖØ-öø-ÿ"},numbers:{label:"Numbers",chars:"0-9"},spaces:{label:"Spaces",chars:" "},punctuation:{label:`Punctuation ( . , ! ? ' " - )`,chars:`.,!?'"()\\-:;`},symbols:{label:"Symbols ( @ # & _ / + )",chars:"@#&_/+*%="}};function Bs(){return{mode:"blocks",starts:"",ends:"",contains:"",notContains:"",chars:[],minLen:"",maxLen:"",regex:"",message:"",tests:[]}}function ft(n){const e=Bs();let t;try{t=JSON.parse(n)}catch{return e}if(!t||typeof t!="object")return e;const s=t;e.mode=s.mode==="regex"?"regex":"blocks";for(const a of["starts","ends","contains","notContains","minLen","maxLen","regex","message"])typeof s[a]=="string"&&(e[a]=s[a]);return Array.isArray(s.chars)&&(e.chars=s.chars.filter(a=>typeof a=="string"&&a in be)),Array.isArray(s.tests)&&(e.tests=s.tests.filter(a=>typeof a=="string").slice(0,10)),e}function ge(n){return n.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}function ve(n){if(n.mode==="regex")return n.regex.trim();const e=[],t=n.minLen.trim(),s=n.maxLen.trim();(t!==""||s!=="")&&e.push(`(?=.{${t===""?"0":parseInt(t,10)||0},${s===""?"":parseInt(s,10)||""}}$)`),n.contains!==""&&e.push(`(?=.*${ge(n.contains)})`),n.notContains!==""&&e.push(`(?!.*${ge(n.notContains)})`),n.starts!==""&&e.push(`(?=${ge(n.starts)})`),n.ends!==""&&e.push(`(?=.*${ge(n.ends)}$)`);const a=n.chars.map(o=>be[o]?.chars??"").join(""),i=a?`[${a}]*$`:".*$";return!e.length&&!a?"":`^${e.join("")}${i}`}function mt(n){if(n.mode==="regex")return n.regex.trim()?`Matches the expression ${n.regex.trim()}`:"";const e=[];if(n.starts&&e.push(`starts with “${n.starts}”`),n.ends&&e.push(`ends with “${n.ends}”`),n.contains&&e.push(`contains “${n.contains}”`),n.notContains&&e.push(`never contains “${n.notContains}”`),n.chars.length){const i=n.chars.map(o=>(be[o]?.label??o).split(" (")[0].toLowerCase());e.push(`uses only ${i.join(" and ")}`)}const t=n.minLen.trim(),s=n.maxLen.trim();return t&&s?e.push(`is ${t}–${s} characters long`):t?e.push(`is at least ${t} characters long`):s&&e.push(`is at most ${s} characters long`),e.length?`The answer ${e.length>1?`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`:e[0]}.`:""}function Ws(n,e){const t=ve(n);if(t==="")return null;try{return new RegExp(t).test(e)}catch{return null}}function js(){return window.wp?.os?.windowManager??null}const bt="allterrain-forms-validation";function Hs(n){const e=js(),t=dt(n.root);if(e?.openChild&&t){Us(e,t,n);return}zs(n)}function Us(n,e,t){const s=`${bt}-${t.field.id}`;n.getById?.(s)&&n.remove?.(s);const a={saved:!1},i=()=>{const o=n.getById?.(s);o?.close?o.close():n.remove?.(s)};n.openChild?.(e,{id:s,baseId:bt,url:`#${s}`,title:`Custom rule — ${t.field.label||"this question"}`,icon:"dashicons-yes-alt",native:!0,width:560,height:700,minWidth:440,minHeight:480,ephemeral:!0,autofocus:".atfb-valwin__pane:not([hidden]) input, .atfb-valwin__pane:not([hidden]) textarea",render:o=>{const l=r("div",{class:"atfa atfb-valwin atfb-valwin--window"});gt(l,t,a,i,"window"),o.append(l)},onClose:()=>{a.saved||t.onCancel?.()}})}function zs(n){const e=r("div",{class:"atfb-overlay"}),t={saved:!1},s=()=>{e.remove(),document.removeEventListener("keydown",a),t.saved||n.onCancel?.()},a=o=>{o.key==="Escape"&&s()},i=r("div",{class:"atfb-modal atfb-valwin",attrs:{role:"dialog","aria-label":"Custom validation rule"},children:[r("h2",{text:"Custom rule"})]});gt(i,n,t,s,"overlay"),e.append(i),e.addEventListener("click",o=>{o.target===e&&s()}),document.addEventListener("keydown",a),n.root.append(e),e.querySelector(".atfb-valwin__pane:not([hidden]) input, .atfb-valwin__pane:not([hidden]) textarea")?.focus()}function gt(n,e,t,s,a){const i=ft(String(e.field.validationRecipe??""));i.mode==="blocks"&&ve(i)===""&&e.field.pattern&&(i.mode="regex",i.regex=String(e.field.pattern)),i.message||(i.message=String(e.field.messages?.invalid??""));const o=(x,F)=>{const S=r("input",{class:"atfb-input",value:i[x],placeholder:F,attrs:{type:"text"}});return S.addEventListener("input",()=>{i[x]=S.value,A()}),S},l=(x,F)=>{const S=r("input",{class:"atfb-input atfb-valwin__len",value:i[x],attrs:{type:"number",min:"0","aria-label":F}});return S.addEventListener("input",()=>{i[x]=S.value,A()}),S},c=r("div",{class:"atfb-valwin__chars",children:Object.entries(be).map(([x,F])=>D(F.label,i.chars.includes(x),S=>{i.chars=S?[...i.chars,x]:i.chars.filter(P=>P!==x),A()}))}),d=r("div",{class:"atfb-valwin__pane",children:[f("Starts with",o("starts","e.g. AT-")),f("Ends with",o("ends","e.g. -2026")),f("Must contain",o("contains","e.g. @")),f("Must not contain",o("notContains","e.g. spaces? type one")),f("Only these characters",c,"Leave every box unticked to allow anything."),f("Length",r("div",{class:"atfb-valwin__lengths",children:[r("span",{text:"between"}),l("minLen","Minimum length"),r("span",{text:"and"}),l("maxLen","Maximum length"),r("span",{text:"characters"})]}),"Leave a box empty for no limit.")]}),h=r("textarea",{class:"atfb-input atfb-valwin__regex",attrs:{rows:"2","aria-label":"Regular expression",placeholder:"^AT-[0-9]{4}$"}});h.value=i.regex,h.addEventListener("input",()=>{i.regex=h.value,A()});const y=r("div",{class:"atfb-valwin__pane",children:[f("Expression",h,"A regular expression, without slashes. Checked against the whole answer only if you anchor it with ^ and $.")]}),b=[["blocks","Easy blocks"],["regex","Expression (advanced)"]],g=x=>{i.mode=x,d.hidden=x!=="blocks",y.hidden=x!=="regex",A()},_=(()=>{if(H("os-segmented")&&H("os-segment")){const S=document.createElement("os-segmented");S.setAttribute("value",i.mode),S.setAttribute("label","How to write the rule"),S.classList.add("atfb-valwin__tabs");for(const[P,M]of b){const re=document.createElement("os-segment");re.setAttribute("value",P),re.textContent=M,S.append(re)}return S.addEventListener("os-pick",P=>{const M=P.detail?.value;(M==="blocks"||M==="regex")&&(S.setAttribute("value",M),g(M))}),S}const x=r("div",{class:"atfb-valwin__tabs",attrs:{role:"tablist"}}),F=()=>{x.replaceChildren(...b.map(([S,P])=>{const M=i.mode===S;return r("button",{class:`atfb-valwin__tab${M?" is-active":""}`,type:"button",text:P,attrs:{role:"tab","aria-selected":M?"true":"false"},on:{click:()=>{g(S),F()}}})}))};return F(),x})();d.hidden=i.mode!=="blocks",y.hidden=i.mode!=="regex";const E=r("input",{class:"atfb-input",value:i.message,placeholder:"That is not in the expected format.",attrs:{type:"text"}});E.addEventListener("input",()=>{i.message=E.value});const q=r("p",{class:"atfb-valwin__summary",attrs:{"aria-live":"polite"}}),j=r("div",{class:"atfb-valwin__samples"}),z=x=>{const F=r("span",{class:"atfb-valwin__verdict",attrs:{"aria-live":"polite"}}),S=r("input",{class:"atfb-input",value:x,placeholder:"Type a sample answer…",attrs:{type:"text"}});S.addEventListener("input",()=>A()),j.append(r("div",{class:"atfb-valwin__sample",children:[S,F]}))};for(const x of i.tests.length?i.tests:["","",""])z(x);const $=()=>Array.from(j.querySelectorAll("input")).map(x=>x.value),A=()=>{const x=mt(i);q.textContent=x||"Nothing yet — fill in a block above and the rule appears here in plain words.";for(const F of Array.from(j.querySelectorAll(".atfb-valwin__sample"))){const S=F.querySelector("input"),P=F.querySelector(".atfb-valwin__verdict");if(!S||!P)continue;const M=S.value===""?null:Ws(i,S.value);P.textContent=M===null?"·":M?"✓ passes":"✗ fails",P.classList.toggle("is-pass",M===!0),P.classList.toggle("is-fail",M===!1)}};n.append(r("p",{class:"atfb-hint",text:`Describe what a good answer to “${e.field.label||"this question"}” looks like — no code needed.`}),_,d,y,r("div",{class:"atfb-valwin__try",children:[r("h3",{text:"Try it out"}),q,j,L("Add another sample",()=>{z(""),A()},"ghost","plus-alt2")]}),f("When it fails, say",E,"Shown to the visitor when their answer breaks the rule. Leave empty for the default wording."),r("div",{class:"atfb-modal__actions",children:[L(a==="window"?"Close without saving":"Cancel",s),L("Save rule",()=>{const x=ve(i);i.tests=$().filter(F=>F!=="").slice(0,10),t.saved=!0,e.onSave({pattern:x,recipe:i,message:i.message.trim()}),s()},"primary")]})),A()}const Ys=["Contact","Numbers & codes","Text shape","Web"],vt=[{slug:"email",label:"An email address",group:"Contact",example:"jane@example.com",pattern:"^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$",message:"That does not look like an email address."},{slug:"phone",label:"A phone number",group:"Contact",example:"+34 612 345 678",pattern:"^(?=(?:[^0-9]*[0-9]){5,})\\+?[0-9 ().-]{5,24}$",message:"That does not look like a phone number."},{slug:"handle",label:"A username or @handle",group:"Contact",example:"@yourname",pattern:"^@?[A-Za-z0-9_]{2,30}$",message:"That does not look like a username."},{slug:"digits",label:"Numbers only",group:"Numbers & codes",example:"12345",pattern:"^[0-9]+$",message:"Numbers only, please."},{slug:"decimal",label:"A number, decimals allowed",group:"Numbers & codes",example:"3.14",pattern:"^-?[0-9]+([.,][0-9]+)?$",message:"That does not look like a number."},{slug:"price",label:"A price",group:"Numbers & codes",example:"19.99",pattern:"^[0-9]+([.,][0-9]{1,2})?$",message:"That does not look like a price."},{slug:"zip_us",label:"A ZIP code (US)",group:"Numbers & codes",example:"90210",pattern:"^[0-9]{5}(-[0-9]{4})?$",message:"That does not look like a ZIP code."},{slug:"postcode_uk",label:"A postcode (UK)",group:"Numbers & codes",example:"SW1A 1AA",pattern:"^[A-Za-z]{1,2}[0-9][A-Za-z0-9]? ?[0-9][A-Za-z]{2}$",message:"That does not look like a postcode."},{slug:"iban",label:"An IBAN",group:"Numbers & codes",example:"DE89 3704 0044 0532 0130 00",pattern:"^[A-Za-z]{2}[0-9]{2}(?: ?[A-Za-z0-9]){10,32}$",message:"That does not look like an IBAN."},{slug:"credit_card",label:"A card number",group:"Numbers & codes",example:"4242 4242 4242 4242",pattern:"^[0-9](?:[0-9 -]{9,21})?[0-9]$",message:"That does not look like a card number.",luhn:!0},{slug:"letters",label:"Letters only",group:"Text shape",example:"María López",pattern:"^[\\p{L}\\p{M} .'’-]+$",message:"Letters only, please."},{slug:"alphanumeric",label:"Letters and numbers only",group:"Text shape",example:"abc123",pattern:"^[A-Za-z0-9]+$",message:"Letters and numbers only, please."},{slug:"no_spaces",label:"One word, no spaces",group:"Text shape",example:"one-word",pattern:"^\\S+$",message:"No spaces allowed."},{slug:"url",label:"A web address",group:"Web",example:"https://example.com",pattern:"^(https?://)?([A-Za-z0-9-]+\\.)+[A-Za-z]{2,}([/?#]\\S*)?$",message:"That does not look like a web address."},{slug:"ip",label:"An IP address",group:"Web",example:"192.168.0.1",pattern:"^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$",message:"That does not look like an IP address."},{slug:"slug",label:"A URL slug",group:"Web",example:"my-page-title",pattern:"^[a-z0-9]+(-[a-z0-9]+)*$",message:"Lowercase letters, numbers and dashes only."},{slug:"hex_color",label:"A hex colour",group:"Web",example:"#3366ff",pattern:"^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$",message:"That does not look like a colour code."}];function Gs(n){return vt.find(e=>e.slug===n)??null}function Me(){return window.wp?.os??null}const yt="allterrain-forms/preview",Ne="allterrain-forms-preview";function Xs(n){const e=Me();if(!e?.registerTitleBarButton)return()=>{};const t=()=>{try{e.registerTitleBarButton({id:yt,label:"Preview this form",icon:"dashicons-visibility",placement:"right",order:90,match:s=>{const a=s?.id??s?.config?.id??"";return a==="allterrain-forms"||a.startsWith("allterrain-forms#")},onClick:()=>void wt(n),owner:"allterrain-forms-builder"})}catch{}};return e.ready?e.ready(t):t(),()=>{try{e.unregisterTitleBarButton?.(yt)}catch{}}}async function wt(n){n.isDirty()&&await n.save();const e=n.current();e&&xt(e.id,e.title,e.previewUrl)}function xt(n,e,t){const s=Me();if(!s?.windowManager?.open){window.open(t,"_blank","noopener");return}s.windowManager.open({id:`${Ne}-${n}`,baseId:Ne,url:t,title:`Preview: ${e}`,icon:"dashicons-visibility"})}function Ks(n,e,t){if(!Me()?.windowManager?.open||!document.querySelector(`[data-window-id="${Ne}-${n}"]`))return;const i=t.includes("?")?"&":"?";xt(n,e,`${t}${i}atf_r=${Date.now()}`)}const ie="allterrain-forms/field",Vs=["openstation/file","desktop-mode/file","openstation/attachment"],_t="allterrain-forms/logic-map-v2";function K(n,e){return n.dataset.atfbBind=e,n}const kt={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"}}},Zs={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(n,e,t){const s=n[e.key],a=i=>t(e.key,i);if(e.control==="checkbox")return D(e.label,!!s,a);if(e.control==="commas"){const i=Array.isArray(s)?s:[];return f(e.label,k(i.join(", "),o=>{a(o.split(",").map(l=>l.trim().replace(/^\./,"").toLowerCase()).filter(Boolean))}),e.hint)}return e.control==="select"?f(e.label,N(String(s??""),e.options??[],a),e.hint):e.control==="textarea"?f(e.label,he(String(s??""),a),e.hint):e.control==="number"?f(e.label,G(String(s??""),a),e.hint):f(e.label,K(k(String(s??""),a),e.key),e.hint)}function Lt(n,e){const t=new Set(n.map(a=>a.key).filter(Boolean));let s=n.length+1;return e.split(` +var allTerrainFormsBuilder=function(Z){"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:t,origin:s}=e,a=s.clientX,i=s.clientY;let o=!1,l=!1,c=null,d=null,h=0,y=0;const b=()=>{document.removeEventListener("pointermove",E),document.removeEventListener("pointerup",q),document.removeEventListener("pointercancel",j),document.removeEventListener("keydown",z),window.removeEventListener("blur",j),c?.remove(),c=null,t.source.classList.remove("atf-is-dragging"),d?.onLeave?.(g),d=null,this.active=null,this.lastEndMs=Date.now()},g={payload:t,isFinished:()=>l,cancel:($="caller")=>{l||(l=!0,b(),e.onCancel?.($))}},C=$=>{o=!0,t.source.classList.add("atf-is-dragging");const A=t.source.getBoundingClientRect();h=t.ghost?.offsetX??a-A.left,y=t.ghost?.offsetY??i-A.top,c=t.ghost?.element??t.source.cloneNode(!0),c.classList.add("atf-drag-ghost"),c.style.width=`${A.width}px`,document.body.appendChild(c),_($)},_=$=>{c&&(c.style.transform=`translate3d(${$.clientX-h}px, ${$.clientY-y}px, 0)`)},E=$=>{if(l)return;if(!o){if(Math.hypot($.clientX-a,$.clientY-i)<4)return;C($)}_($);const A=this.hitTest($.clientX,$.clientY);A!==d&&(d?.onLeave?.(g),d=A,d?.onEnter?.(g))},q=$=>{if(l)return;if(!o){l=!0,b(),e.onClickOnly?.();return}const A=d;if(l=!0,b(),A&&A.accept(t)){e.onCommit?.(A),A.onDrop(g,{clientX:$.clientX,clientY:$.clientY});return}e.onCancel?.(A?"rejected":"no-target")},j=()=>g.cancel("pointercancel"),z=$=>{$.key==="Escape"&&g.cancel("escape")};return document.addEventListener("pointermove",E),document.addEventListener("pointerup",q),document.addEventListener("pointercancel",j),document.addEventListener("keydown",z),window.addEventListener("blur",j),this.active=g,g}registerDropTarget(e){return this.targets=this.targets.filter(t=>t.id!==e.id),this.targets.push(e),()=>{this.targets=this.targets.filter(t=>t.id!==e.id)}}isDragging(){return this.active!==null}recentlyEndedDrag(e=500){return Date.now()-this.lastEndMso.right||to.bottom)continue;const l=Ft(i.element);if(l>a){s=i,a=l;continue}l===a&&s&&qt(i.element,s.element)&&(s=i)}return s}}function Ft(n){let e=0,t=n;for(;t;)e++,t=t.parentElement;return e}function qt(n,e){return(e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING)!==0}function we(){return window.wp?.os??null}let xe=null;function te(){const n=we();return n?.dragManager?n.dragManager:(xe||(xe=new Dt),xe)}function Mt(n){const e=a=>{const i=a.detail?.payload;return i&&n.includes(i.type)?i.source:null},t=a=>e(a)?.classList.add("atf-is-dragging"),s=a=>e(a)?.classList.remove("atf-is-dragging");return document.addEventListener("os.drag.start",t),document.addEventListener("os.drag.end",s),()=>{document.removeEventListener("os.drag.start",t),document.removeEventListener("os.drag.end",s)}}function je(n,e,t,s,a){const i=e.getBoundingClientRect();return a&&(a.style.width=`${Math.round(i.width)}px`,a.style.maxWidth=`${Math.round(i.width)}px`,a.style.boxSizing="border-box"),{type:n,source:e,data:t,ghost:{element:a,offsetX:s.clientX-i.left,offsetY:s.clientY-i.top,hint:{neutral:"",accept:"",reject:"",hidden:!0}}}}function He(n,e,t,s){const a=Array.from(n.querySelectorAll(e)).filter(i=>i!==s&&!i.classList.contains("atf-drag-ghost"));for(let i=0;ia.fetch(l,c,{source:"allterrain-forms"}):(l,c)=>fetch(l,c))(t,{credentials:"same-origin",...e,headers:s});if(!o.ok){let l=`Request failed with status ${o.status}.`,c="";try{const d=await o.json();l=d.message??l,c=d.code??""}catch{}throw new le(l,o.status,c)}if(o.status!==204)return await o.json()}const Y=n=>_e(n);async function Nt(n){if(!B?.wpRestUrl)throw new le("AllTerrain Forms is not configured on this page.",0);const e=B.nonce?{"X-WP-Nonce":B.nonce}:{},t=we(),s=Ue(B.wpRestUrl,n),a=t?.fetch?await t.fetch(s,{credentials:"same-origin",headers:e},{source:"allterrain-forms"}):await fetch(s,{credentials:"same-origin",headers:e});if(!a.ok)throw new le(`Request failed with status ${a.status}.`,a.status);return await a.json()}function Rt(n){if(!n||!n.includes("&"))return n;const e=document.createElement("textarea");return e.innerHTML=n,e.value}const ee=(n,e)=>_e(n,{method:"POST",body:JSON.stringify(e)}),ce=n=>_e(n,{method:"DELETE"});function ze(n){const e=new URLSearchParams;for(const[s,a]of Object.entries(n))a===void 0||a===""||a===!1||e.set(s,String(a));const t=e.toString();return t?`?${t}`:""}function de(n){const e=n?.schema?.settings;return e&&(!e.themeOverrides||Array.isArray(e.themeOverrides))&&(e.themeOverrides={...e.themeOverrides}),n}const O={config:()=>Y("/config"),listForms:()=>Y("/forms"),getForm:n=>Y(`/forms/${n}`).then(de),createForm:n=>ee("/forms",n).then(de),updateForm:(n,e)=>ee(`/forms/${n}`,e).then(de),duplicateForm:n=>ee(`/forms/${n}/duplicate`,{}).then(de),deleteForm:n=>ce(`/forms/${n}`),preview:(n,e)=>ee(`/forms/${n}/preview`,e),pages:()=>Nt("wp/v2/pages?per_page=100&status=publish&orderby=title&order=asc&_fields=id,title").then(n=>n.map(e=>({id:e.id,title:Rt(e.title?.rendered??"")||`#${e.id}`}))),mergeTags:n=>Y(`/forms/${n}/merge-tags`).then(e=>e.groups),analytics:(n,e="")=>Y(`/forms/${n}/analytics${e?`?dimension=${encodeURIComponent(e)}`:""}`),demoStatus:()=>Y("/demo"),demoSeed:n=>ee("/demo",n?{count:n}:{}),demoRemove:()=>ce("/demo"),listEntries:n=>Y(`/entries${ze(n)}`),getEntry:n=>Y(`/entries/${n}`),updateEntry:(n,e)=>ee(`/entries/${n}`,e),deleteEntry:n=>ce(`/entries/${n}`),exportEntries:n=>Y(`/entries/export${ze(n)}`),listThemes:()=>Y("/themes"),saveTheme:n=>ee("/themes",n),deleteTheme:n=>ce(`/themes/${n}`)};function r(n,e={}){const t=document.createElement(n);e.class&&(t.className=e.class),e.text!==void 0&&(t.textContent=e.text),e.html!==void 0&&(t.innerHTML=e.html),e.title&&(t.title=e.title),e.type&&"type"in t&&(t.type=e.type),e.value!==void 0&&"value"in t&&(t.value=e.value),e.placeholder!==void 0&&"placeholder"in t&&(t.placeholder=e.placeholder),e.href&&"href"in t&&(t.href=e.href);for(const[s,a]of Object.entries(e.attrs??{}))a===void 0||a===!1||t.setAttribute(s,a===!0?"":String(a));Object.assign(t.style,e.style??{});for(const[s,a]of Object.entries(e.on??{}))t.addEventListener(s,a);for(const s of e.children??[])s==null||s===!1||t.append(s);return t}function R(n){n.replaceChildren()}function W(n){return r("span",{class:`dashicons ${n.startsWith("dashicons-")?n:`dashicons-${n}`}`,attrs:{"aria-hidden":"true"}})}function f(n,e,t){const s=e.matches("input, select, textarea, button")?e:e.querySelector("input, select, textarea");if(s){const a=s.id||`atf-c-${Math.random().toString(36).slice(2,9)}`;return s.id=a,r("div",{class:"atfb-row",children:[r("label",{class:"atfb-row__label",text:n,attrs:{for:a}}),e,t?r("p",{class:"atfb-row__hint",text:t}):null]})}return r("div",{class:"atfb-row",children:[r("span",{class:"atfb-row__label",text:n}),e,t?r("p",{class:"atfb-row__hint",text:t}):null]})}function k(n,e,t=""){return r("input",{class:"atfb-input",type:"text",value:n,placeholder:t,on:{input:s=>e(s.target.value)}})}function G(n,e){if(H("os-number-field")){const t=document.createElement("os-number-field");return t.setAttribute("value",n),t.classList.add("atfb-field"),t.addEventListener("os-input-change",s=>{e(String(s.detail?.value??""))}),t}return r("input",{class:"atfb-input",type:"number",value:n,on:{input:t=>e(t.target.value)}})}function he(n,e,t=4){const s=r("textarea",{class:"atfb-input atfb-input--area",attrs:{rows:t},on:{input:a=>e(a.target.value)}});return s.value=n,s}function N(n,e,t){if(H("os-select")&&H("os-option")){const s=document.createElement("os-select");s.setAttribute("value",n),s.classList.add("atfb-field");for(const a of e){const i=document.createElement("os-option");i.setAttribute("value",a.value),i.textContent=a.label,s.append(i)}return s.addEventListener("os-pick",a=>{t(String(a.detail?.value??""))}),s}return r("select",{class:"atfb-input atfb-select",on:{change:s=>t(s.target.value)},children:e.map(s=>r("option",{value:s.value,text:s.label,attrs:{selected:s.value===n}}))})}function D(n,e,t){if(H("os-checkbox-label")){const a=document.createElement("os-checkbox-label");return a.setAttribute("label",n),a.classList.add("atfb-check"),e&&a.setAttribute("checked",""),a.addEventListener("os-checkbox-change",i=>{t(!!i.detail?.checked)}),a}const s=r("input",{type:"checkbox",on:{change:a=>t(a.target.checked)}});return s.checked=e,r("label",{class:"atfb-check",children:[s,r("span",{text:n})]})}function L(n,e,t="secondary",s){const a=[s?W(s):null,r("span",{text:n})];if(H("os-button")){const i=document.createElement("os-button");i.setAttribute("variant",t),i.setAttribute("type","button"),i.classList.add("atfb-button",`atfb-button--${t}`),i.addEventListener("click",e);for(const o of a)o&&i.append(o);return i}return r("button",{class:`atfb-button atfb-button--${t}`,type:"button",on:{click:e},children:a})}function H(n){return typeof customElements<"u"&&!!customElements.get(n)}const Pt=["os-button","os-checkbox-label","os-number-field","os-select","os-option","os-segmented","os-segment","os-color-field","os-empty-state"];let ue=null;function Bt(){if(ue)return ue;const n=window.wp?.os;return ue=n?.loadComponents?n.loadComponents(Pt).catch(()=>{}):Promise.resolve(),ue}async function ke(n,e=""){const t=window.wp?.os;return t?.confirm?t.confirm({title:e,message:n,danger:!0}):window.confirm(n)}function U(n,e="",t="info"){const s=window.wp?.os;if(s?.notify){s.notify({title:n,body:e,type:t});return}console.info(`[AllTerrain Forms] ${n}${e?`: ${e}`:""}`)}function Wt(n){let e=0,t;return(...s)=>{t=s,!e&&(e=window.requestAnimationFrame(()=>{e=0,n(...t)}))}}function Se(n,e){let t=0;return(...s)=>{window.clearTimeout(t),t=window.setTimeout(()=>n(...s),e)}}function jt(n){try{return window.localStorage.getItem(n)??""}catch{return""}}function Ht(n,e){try{window.localStorage.setItem(n,e)}catch{}}function Ye(n){const e=n.closest(".os-window__body");e&&(e.addEventListener("scroll",()=>{e.scrollTop&&(e.scrollTop=0),e.scrollLeft&&(e.scrollLeft=0)},{passive:!0}),e.scrollTop=0,e.scrollLeft=0)}function Ge(){const n=[window];try{window.parent&&window.parent!==window&&n.push(window.parent)}catch{}return n}function Ut(n){const e=n.wp?.os?.windowManager?.getAll?.()??[];for(const t of e){const s=t.iframe??t.element?.querySelector?.("iframe");if(s&&s.contentWindow===window)return t}return null}const zt=4e3,Yt=100;function Gt(n,e){const t=Date.now()+zt,s=()=>{const a=Ut(n);if(a&&a.id!==e){typeof a.close=="function"?a.close():n.wp?.os?.windowManager?.remove?.(a.id);return}!a&&Date.now()0?{form:t}:void 0;t>0&&Zt(t);for(const a of Ge())if(a.wp?.os?.openWindow?.(e,{source:"handoff",params:s})){window.setTimeout(()=>Gt(a,e),0);return}}function Kt(){document.addEventListener("click",n=>{const e=n.target?.closest?.("[data-atf-open-window]");if(!e)return;n.preventDefault();const t=e.getAttribute("data-atf-open-window")??"";for(const s of Ge())if(s.wp?.os?.openWindow?.(t,{source:"handoff"}))return})}const Vt="allterrain-forms/requested-form";function Zt(n){try{window.sessionStorage.setItem(Vt,String(n))}catch{}}function Xe(n){return`allterrain-forms/requested-form-${n}`}function Jt(n){try{const e=window.sessionStorage.getItem(Xe(n));return window.sessionStorage.removeItem(Xe(n)),Number(e)||0}catch{return 0}}const Le={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"},Ke=["empty","not_empty"];function Ve(n,e){const t=n.find(s=>s.id===e);return t?t.label||"an untitled question":null}function Ze(n,e,t){return n.find(i=>i.id===e)?.choices?.find(i=>i.value===t)?.label||t}function Qt(n,e){const t=Le[n.operator]??String(n.operator);if(Ke.includes(n.operator))return t;const s=Ze(e,n.field,n.value);return`${n.operator==="is"?"":`${t} `}${s!==""?s:"(nothing)"}`}function Je(n,e,t=0){const s=Ve(e,n.field),a=Le[n.operator]??String(n.operator);if(s===null)return[{kind:"field",text:"a question that no longer exists",fieldId:n.field,missing:!0}];const i=[{kind:"field",text:s,fieldId:n.field,missing:!1},{kind:"operator",text:a,operator:n.operator,ruleIndex:t}];if(Ke.includes(n.operator))return i;const o=Ze(e,n.field,n.value);return i.push({kind:"value",text:o!==""?o:"(nothing)",raw:n.value,sourceId:n.field,ruleIndex:t}),i}function es(n,e){const t=n.logic;if(!t?.enabled||!t.rules.length)return[];const s=[{kind:"verb",text:t.action==="hide"?"Hidden when":"Shown when"}];return t.rules.forEach((a,i)=>{i>0&&s.push({kind:"join",text:t.match==="all"?"and":"or"}),s.push(...Je(a,e,i))}),s}function Qe(n){return n.map(e=>e.text).join(" ")}function ts(n,e){return Qe(Je(n,e))}function pe(n){const e=[];for(const t of n){const s=t.logic;if(s?.enabled)for(const a of s.rules)!a.field||a.field===t.id||e.push({from:a.field,to:t.id,label:ts(a,n),short:Qt(a,n),action:s.action,broken:Ve(n,a.field)===null})}return e}function ss(n){const e=new Map,t=new Set;for(const s of pe(n)){const a=`${s.from}->${s.to}`;s.broken||t.has(a)||(t.add(a),e.set(s.from,(e.get(s.from)??0)+1))}return e}const et=10,tt=22,se="http://www.w3.org/2000/svg";class ns{constructor(e){this.edges=[],this.teardowns=[],this.frame=0,this.host=e,this.svg=document.createElementNS(se,"svg"),this.svg.setAttribute("class","atfb-logicmap"),this.svg.setAttribute("aria-hidden","true"),this.svg.setAttribute("focusable","false"),e.append(this.svg);const t=()=>this.schedule();window.addEventListener("resize",t),this.teardowns.push(()=>window.removeEventListener("resize",t));const s=e.closest(".atfb__canvas")??e;if(s.addEventListener("scroll",t,{passive:!0}),this.teardowns.push(()=>s.removeEventListener("scroll",t)),typeof ResizeObserver<"u"){const a=new ResizeObserver(t);a.observe(e),this.teardowns.push(()=>a.disconnect())}}setEdges(e){this.edges=e,this.schedule()}highlight(e){this.svg.classList.toggle("is-focused",!!e),this.svg.querySelectorAll("[data-from]").forEach(t=>{const s=e&&(t.dataset.from===e||t.dataset.to===e);t.classList.toggle("is-lit",!!s)})}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 t=new Map;for(const s of this.edges){const a=this.cardRect(s.from),i=this.cardRect(s.to);if(!a||!i)continue;const o=t.get(s.from)??0;t.set(s.from,o+1),this.drawEdge(s,a,i,e,o)}}cardRect(e){const t=this.host.querySelector(`[data-atfb-card="${CSS.escape(e)}"]`);return t?t.getBoundingClientRect():null}drawEdge(e,t,s,a,i){const o=t.right-a.left,l=t.top+t.height/2-a.top,c=s.right-a.left,d=s.top+s.height/2-a.top,h=Math.max(0,a.width-et-Math.max(o,c)),y=22+i*11+Math.min(22,Math.abs(d-l)/8),b=Math.max(12,Math.min(y,h*.4)),g=document.createElementNS(se,"path");g.setAttribute("d",`M ${o} ${l} C ${o+b} ${l}, ${c+b} ${d}, ${c} ${d}`),g.setAttribute("class",`atfb-logicmap__path is-${e.action}${e.broken?" is-broken":""}`),g.dataset.from=e.from,g.dataset.to=e.to;const C=document.createElementNS(se,"title");C.textContent=e.label,g.append(C);const _=document.createElementNS(se,"circle");_.setAttribute("cx",String(c)),_.setAttribute("cy",String(d)),_.setAttribute("r","3.5"),_.setAttribute("class",`atfb-logicmap__dot is-${e.action}${e.broken?" is-broken":""}`),_.dataset.from=e.from,_.dataset.to=e.to,this.svg.append(g,_);const E=document.createElementNS(se,"text");E.setAttribute("x",String(a.width-et)),E.setAttribute("y",String(d+3)),E.setAttribute("text-anchor","end"),E.setAttribute("class","atfb-logicmap__label"),E.dataset.from=e.from,E.dataset.to=e.to,E.textContent=e.short.length>tt?`${e.short.slice(0,tt-1)}…`:e.short;const q=document.createElementNS(se,"title");q.textContent=e.label,E.append(q),this.svg.append(E)}}const as={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 is(n){return as[n]??"text"}function st(n,e){const t=/^choice:(\d+):(label|value)$/.exec(e);return String(t?n.choices?.[Number(t[1])]?.[t[2]]??"":n[e]??"")}function J(n){const{value:e,onInput:t,onCommit:s}=n,a=r("span",{class:`${n.class} atfb-editable`,text:e,attrs:{contenteditable:"plaintext-only",role:"textbox",spellcheck:"false","data-placeholder":n.placeholder}});return n.bind&&(a.dataset.atfbBind=n.bind),a.addEventListener("pointerdown",i=>i.stopPropagation()),a.addEventListener("input",()=>t(a.textContent??"")),a.addEventListener("keydown",i=>{i.key==="Enter"&&(i.preventDefault(),a.blur()),i.key==="Escape"&&(a.textContent=e,a.blur()),i.stopPropagation()}),a.addEventListener("blur",()=>s?.()),a}function rs(n){const e=r("input",{class:"atf-choice__input",type:n==="checkboxes"||n==="multiselect"?"checkbox":"radio"});return e.disabled=!0,e}function os(n,e,t){const s=is(n.type),a=J({value:n.label,placeholder:"Write the question…",class:"atf-label",bind:"label",onInput:o=>t.edit(l=>{l.label=o}),onCommit:()=>t.restructure(()=>{})}),i=[s==="static"||s==="toggle"?null:a,cs(n,e,s,t),ls(n,e,t)];return r("div",{class:"atfb-preview atf-form",children:[r("div",{class:`atf-field atf-field--${n.type}`,children:i})]})}function ls(n,e,t){if(!e?.supports.includes("hint"))return null;const s=J({value:n.hint??"",placeholder:"Add a hint…",class:"atf-hint",bind:"hint",onInput:a=>t.edit(i=>{i.hint=a})});return s.setAttribute("aria-label","Hint"),r("p",{class:"atfb-preview__hint",children:[s]})}function cs(n,e,t,s){switch(t){case"text":return Ee(n,"atf-input",s);case"textarea":return Ee(n,"atf-input atf-textarea",s,!0);case"select":return r("div",{class:"atfb-preview__select",children:[Ee(n,"atf-input atf-select",s)]});case"options":return hs(n,s);case"toggle":return r("div",{class:n.type==="switch"?"atf-toggle atf-toggle--switch":"atf-toggle",children:[(()=>{const a=r("input",{class:"atf-toggle__input",type:"checkbox"});return a.disabled=!0,a})(),J({value:n.label||"",placeholder:n.type==="consent"?"What are they agreeing to?…":"What does this turn on?…",class:"atf-toggle__label",bind:"label",onInput:a=>s.edit(i=>{i.label=a}),onCommit:()=>s.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 us(n,e,s);default:return r("div",{class:"atfb-preview__stack",children:[r("p",{class:"atfb-preview__summary",text:`${e?.label??n.type} — set this up in the panel on the right.`}),n.type==="repeater"?ds(n,s):null]})}}function Ee(n,e,t,s=!1){const a=J({value:n.placeholder??"",placeholder:n.type==="select"||n.type==="country"?"Choose…":"Placeholder…",class:`${e} atfb-preview__box${s?" atfb-preview__box--tall":""}`,bind:"placeholder",onInput:i=>t.edit(o=>{o.placeholder=i})});return a.setAttribute("aria-label","Placeholder"),a}function Ce(n,e,t,s,a,i){return r("span",{class:`atf-button ${t} atfb-preview__button`,children:[J({value:n,placeholder:e,class:"atfb-preview__button-text",bind:s,onInput:o=>a.edit(l=>i(l,o))})]})}function ds(n,e){return Ce(String(n.addLabel??""),"Add another","atf-button--secondary","addLabel",e,(t,s)=>{t.addLabel=s})}function hs(n,e){const t=r("div",{class:"atf-choices__list"});return(n.choices??[]).forEach((s,a)=>{t.append(r("div",{class:"atf-choice atfb-preview__option",children:[rs(n.type),J({value:s.label,placeholder:"Option…",class:"atf-choice__label",bind:`choice:${a}:label`,onInput:i=>{e.edit(o=>{const l=o.choices?.[a];if(!l)return;const c=!l.value||l.value===l.label;l.label=i,c&&(l.value=i)})}}),r("button",{class:"atfb-preview__remove",type:"button",title:"Remove this option",attrs:{"aria-label":`Remove ${s.label||"this option"}`},on:{pointerdown:i=>i.stopPropagation(),click:i=>{i.stopPropagation(),e.restructure(o=>{o.choices.splice(a,1)})}},children:[r("span",{text:"×"})]})]}))}),t.append(r("button",{class:"atfb-preview__add",type:"button",on:{pointerdown:s=>s.stopPropagation(),click:s=>{s.stopPropagation(),e.restructure(a=>{const i=a.choices.length+1;a.choices.push({label:`Option ${i}`,value:`Option ${i}`})})}},children:[r("span",{text:"+ Add option"})]})),r("fieldset",{class:"atf-choices",children:[t]})}function us(n,e,t){return n.type==="heading"?J({value:n.label,placeholder:"Section heading…",class:"atf-heading",bind:"label",onInput:s=>t.edit(a=>{a.label=s}),onCommit:()=>t.restructure(()=>{})}):n.type==="divider"?r("hr",{class:"atf-divider"}):n.type==="page_break"?r("div",{class:"atfb-preview__stack",children:[r("p",{class:"atfb-progress-name",children:[J({value:n.label,placeholder:"Name this step…",class:"atf-progress__label",bind:"label",onInput:s=>t.edit(a=>{a.label=s}),onCommit:()=>t.restructure(()=>{})})]}),r("p",{class:"atfb-preview__summary",text:"Everything after this is a new page."}),r("div",{class:"atf-nav atfb-preview__nav",children:[Ce(String(n.prevLabel??""),"Back","atf-button--secondary","prevLabel",t,(s,a)=>{s.prevLabel=a}),Ce(String(n.nextLabel??""),"Next","","nextLabel",t,(s,a)=>{s.nextLabel=a})]})]}):r("p",{class:"atfb-preview__summary",text:`${e?.label??n.type} — nothing is shown to the visitor here.`})}const $e=new Map;function Ae(n){let e=$e.get(n);return e||(e=O.mergeTags(n).catch(()=>[]),$e.set(n,e)),e}function ps(n){$e.delete(n)}function fs(n){const e=new Map;for(const t of n)for(const s of t.items)e.set(s.tag,s);return e}function ms(n,e){const t=fs(e);return n.replace(/\{[a-z_]+(?::[^}]*)?\}/gi,s=>{const a=t.get(s.toLowerCase());return a?a.sample:s})}function bs(n){return/\{[a-z_]+(?::[^}]*)?\}/i.test(n)}let Q=null;function ae(){Q?.remove(),Q=null}typeof document<"u"&&(document.addEventListener("pointerdown",n=>{const e=n.target;e?.closest(".atfb-tagpick__open")||Q&&!Q.contains(e)&&ae()}),document.addEventListener("keydown",n=>{n.key==="Escape"&&Q&&(ae(),n.stopPropagation())}));function nt(n,e){const t=n.selectionStart??n.value.length,s=n.selectionEnd??n.value.length;n.value=n.value.slice(0,t)+e+n.value.slice(s);const a=t+e.length;n.setSelectionRange(a,a),n.focus(),n.dispatchEvent(new Event("input",{bubbles:!0}))}function gs(n){let e=n.parentElement;for(;e&&e!==document.body;){const t=getComputedStyle(e).overflowY;if(t==="auto"||t==="scroll"||t==="hidden")return e.getBoundingClientRect().bottom;e=e.parentElement}return window.innerHeight}function vs(n,e){const t=r("input",{class:"atfb-input atfb-tagpick__search",type:"search",placeholder:"Search values…",attrs:{"aria-label":"Search values"}}),s=r("div",{class:"atfb-tagpick__list"}),a=i=>{s.replaceChildren();const o=i.trim().toLowerCase();let l=0;for(const c of n){const d=c.items.filter(h=>!o||h.label.toLowerCase().includes(o)||h.tag.toLowerCase().includes(o));if(!d.length){c.empty&&!o&&!c.items.length&&s.append(r("p",{class:"atfb-tagpick__group",text:c.label}),r("p",{class:"atfb-tagpick__empty",text:c.empty}));continue}s.append(r("p",{class:"atfb-tagpick__group",text:c.label}));for(const h of d)l+=1,s.append(r("button",{class:"atfb-tagpick__item",type:"button",on:{click:()=>{e(h.tag),ae()}},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&&s.append(r("p",{class:"atfb-tagpick__empty",text:`Nothing matches “${i}”.`}))};return a(""),t.addEventListener("input",()=>a(t.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."}),t,s]})}function at(n,e){const t=r("button",{class:"atfb-button atfb-button--ghost atfb-tagpick__open",type:"button",title:"Insert a value from the submission",children:[W("shortcode"),r("span",{text:"Insert a value"})]}),s=r("div",{class:"atfb-taggable",children:[n,r("div",{class:"atfb-taggable__tools",children:[t]})]}),a=e.preview===!1?null:r("p",{class:"atfb-taggable__preview"});a&&s.append(a);const i=()=>{if(a){if(!bs(n.value)){a.textContent="",a.hidden=!0;return}Ae(e.formId).then(o=>{a.hidden=!1,a.replaceChildren(r("span",{class:"atfb-taggable__preview-label",text:"Reads as"}),r("span",{text:ms(n.value,o)}))})}};return n.addEventListener("input",i),i(),t.addEventListener("click",o=>{if(o.stopPropagation(),Q&&s.contains(Q)){ae();return}ae(),Ae(e.formId).then(l=>{const c=vs(l,d=>{nt(n,d),i()});s.append(c),Q=c,(window.innerHeight-c.getBoundingClientRect().topgs(s))&&c.classList.add("atfb-tagpick--above"),c.querySelector(".atfb-tagpick__search")?.focus()})}),s}function it(n,e){const t=parseFloat(String(n??""));return Number.isFinite(t)?t:e}function rt(n,e){let t=e[0];for(const s of e)Math.abs(s.at-n)n.accent??"#2271b1",apply:n=>({accent:n,"accent-soft":`color-mix( in srgb, ${n} 12%, transparent )`,"border-focus":n,"focus-ring-color":n,"button-bg":n,"button-bg-hover":`color-mix( in srgb, ${n} 88%, #000 )`})},{id:"roundness",label:"Roundness",hint:"Corners, everywhere at once.",kind:"scale",steps:Te.map(({value:n,label:e})=>({value:n,label:e})),owns:["radius-field","radius-button","radius-card","radius-check"],read:n=>rt(it(n["radius-field"],4),Te),apply:n=>{const e=Te.find(t=>t.value===n)?.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:Ie.map(({value:n,label:e})=>({value:n,label:e})),owns:["pad-field-x","pad-field-y","gap-fields","gap-label","button-pad-x","button-pad-y"],read:n=>rt(it(n["pad-field-y"],9),Ie),apply:n=>{const e=Ie.find(t=>t.value===n)?.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:ys,owns:["shadow-field","shadow-field-focus","shadow-button","shadow-button-hover","shadow-card"],read:n=>{const e=n["shadow-card"]??"none";return e==="none"||e.trim()===""?n["shadow-field"]&&n["shadow-field"]!=="none"?"hard":"none":e.includes("0 1px")||e.includes("2px")?"subtle":"lifted"},apply:n=>{switch(n){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:ws,owns:["field-style"],read:n=>n["field-style"]??"outline",apply:n=>({"field-style":n})},{id:"labels",label:"Labels",hint:"Where the question sits relative to the answer.",kind:"choice",steps:xs,owns:["label-position"],read:n=>n["label-position"]??"top",apply:n=>({"label-position":n})}]}function _s(n){return Oe().find(e=>e.owns.includes(n))??null}function ot(n){let e=n.activeSlug,t={...n.overrides},s=n.themes;const a=u=>{t=u,n.onOverridesReplaced?.({...u})},i=r("div",{class:"atfs-preview__frame"}),o=r("div",{class:"atfs-controls__body"}),l=r("div",{class:"atfs-quick"}),c=r("div",{class:"atfs-themes"}),d=Se(async()=>{try{const u=await n.previewFor(e,t),p=i.closest(".atf-studio__preview"),m=p?.scrollTop??0;i.innerHTML=u,p&&(p.scrollTop=m),document.dispatchEvent(new CustomEvent("atf-refresh"))}catch(u){R(i),i.append(r("p",{class:"atfb-error",text:u instanceof Error?u.message:"Preview failed."}))}},180),h={"label-position":"atf-labels-","field-style":"atf-fields-"},y=(u,p,m)=>{const v=m.replace(/[^a-z0-9_-]/gi,"");for(const w of[...u.classList])w.startsWith(p)&&u.classList.remove(w);v&&u.classList.add(p+v)},b=u=>{const p=i.querySelector(".atf-form-wrap"),m=p?.querySelector(".atf-form");if(p)for(const[v,w]of Object.entries(u))w===""?p.style.removeProperty(`--atf-${v}`):p.style.setProperty(`--atf-${v}`,w),m&&h[v]&&y(m,h[v],w||(s.find(I=>I.slug===e)?.resolved[v]??""))},g=u=>{b(u.resolved);const p=i.querySelector(".atf-form");p&&(y(p,"atf-theme-",u.slug),p.classList.toggle("atf-is-dark",!!u.dark))},C=u=>t[u.token]!==void 0?t[u.token]:s.find(m=>m.slug===e)?.resolved?.[u.token]??u.default,_=()=>{R(c);for(const u of s){const p=r("button",{class:`atfs-theme${u.slug===e?" is-active":""}`,type:"button",attrs:{"aria-pressed":u.slug===e,title:u.description},children:[r("span",{class:"atfs-theme__chip",style:{background:u.resolved.surface??"#fff",borderColor:u.resolved.border??"#ccc",borderRadius:u.resolved["radius-field"]??"4px",boxShadow:u.resolved["shadow-card"]??"none"},children:[r("span",{class:"atfs-theme__accent",style:{background:u.resolved.accent??"#2271b1",borderRadius:u.resolved["radius-button"]??"4px"}})]}),r("span",{class:"atfs-theme__name",text:u.label}),u.custom?r("span",{class:"atfb-badge",text:"yours"}):null],on:{click:()=>{e=u.slug,a({}),n.onTheme(e),g(u),_(),z(),j(),Tt()}}});c.append(p)}},E=()=>{const p={...s.find(m=>m.slug===e)?.resolved??{}};for(const[m,v]of Object.entries(t))p[m]=v;return p},q=u=>{const p=l.closest(".atf-studio__controls"),m=p?.scrollTop??0;u(),p&&(p.scrollTop=m)},j=Se(()=>q(x),150),z=()=>{const u=E(),p=l.querySelectorAll(".atfs-dial");Oe().forEach((m,v)=>{const w=p[v];if(!w)return;const I=m.read(u);if(m.kind==="colour"){const T=w.querySelector('input[type="color"]'),X=w.querySelector("input.atfb-input");T&&document.activeElement!==T&&(T.value=fe(I)),X&&document.activeElement!==X&&(X.value=I);return}w.querySelectorAll(".atfs-segment").forEach((T,X)=>{const V=m.steps?.[X]?.value===I;T.classList.toggle("is-on",V),T.setAttribute("aria-pressed",String(V))})})},$=(u,p)=>{const m=u.apply(p,E());for(const[v,w]of Object.entries(m))t[v]=w,n.onOverride(v,w);b(m),z(),j()},A=()=>{R(l);const u=E();for(const p of Oe()){const m=p.read(u);let v;if(p.kind==="colour"){const w=r("input",{class:"atfs-color",type:"color",value:fe(m),attrs:{"aria-label":p.label},on:{input:I=>$(p,I.target.value)}});v=r("div",{class:"atfs-color-row",children:[w,k(m,I=>$(p,I))]})}else v=r("div",{class:`atfs-segmented atfs-segmented--${p.kind}`,attrs:{role:"group","aria-label":p.label},children:(p.steps??[]).map(w=>r("button",{class:`atfs-segment${w.value===m?" is-on":""}`,type:"button",text:w.label,attrs:{"aria-pressed":w.value===m},on:{click:()=>$(p,w.value)}}))});l.append(r("div",{class:"atfs-dial",children:[r("div",{class:"atfs-dial__head",children:[r("span",{class:"atfs-dial__label",text:p.label}),r("span",{class:"atfs-dial__hint",text:p.hint})]}),v]}))}},x=()=>{R(o);const u=new Map;for(const m of n.tokens){const v=u.get(m.group)??[];v.push(m),u.set(m.group,v)}const p={colour:"Colour",shape:"Corners and borders",shadow:"Shadows",fields:"Field style",space:"Spacing",type:"Type",labels:"Labels",button:"Buttons",focus:"Focus ring",motion:"Motion"};for(const[m,v]of u)o.append(r("details",{class:"atfs-group",attrs:{open:m==="colour"},children:[r("summary",{text:p[m]??m}),...v.map(w=>F(w))]}))},F=u=>{const p=C(u),m=T=>{T===""?delete t[u.token]:t[u.token]=T,n.onOverride(u.token,T),b({[u.token]:T})};let v;if(u.control==="color"){const T=r("input",{class:"atfs-color",type:"color",value:fe(p),attrs:{"aria-label":`${u.label} colour`},on:{input:V=>{const oe=V.target.value;X.value=oe,m(oe)}}}),X=k(p,V=>{T.value=fe(V),m(V)});v=r("div",{class:"atfs-color-row",children:[T,X]})}else if(u.control==="select")v=N(p,(u.options??[]).map(T=>({value:T,label:T})),m);else if(u.control==="length"){const T=parseFloat(p)||0,X=u.unit??"px",V=u.token.includes("radius")?60:80,oe=r("input",{class:"atfs-range",type:"range",value:String(T),attrs:{min:"0",max:String(V),step:"1","aria-label":u.label},on:{input:ye=>{const Ot=`${ye.target.value}${X}`;It.value=Ot,m(Ot)}}}),It=k(p,ye=>{oe.value=String(parseFloat(ye)||0),m(ye)});v=r("div",{class:"atfs-length-row",children:[oe,It]})}else v=k(p,m);const w=f(u.label,v),I=_s(u.token);return I&&(w.classList.add("is-dialled"),w.append(r("span",{class:"atfs-owned",text:I.label}))),t[u.token]!==void 0&&(w.classList.add("is-overridden"),w.append(r("button",{class:"atfs-reset",type:"button",text:"Reset",attrs:{"aria-label":`Reset ${u.label} to the theme's value`},on:{click:()=>{m(""),q(x)}}}))),w},S=async()=>{const u=s.find(v=>v.slug===e),p=u?`${u.label} (mine)`:"My theme",m=window.prompt("Name this theme",p);if(m)try{const v={};for(const I of n.tokens){const T=C(I);T!==I.default&&(v[I.token]=T)}const w=await O.saveTheme({label:m,tokens:v});s=[...s.filter(I=>I.slug!==w.slug),w],n.onThemesChanged(s),e=w.slug,a({}),n.onTheme(e),_(),z(),q(x),U("Theme saved",w.label)}catch(v){U("Could not save the theme",v instanceof Error?v.message:"","error")}},P=async()=>{const u=s.find(p=>p.slug===e);if(u?.custom&&await ke(`Delete “${u.label}”? Forms using it fall back to Clean.`,"Delete theme"))try{await O.deleteTheme(u.id),s=s.filter(m=>m.slug!==u.slug),n.onThemesChanged(s),e="clean",a({}),n.onTheme(e),_(),z(),q(x);const p=s.find(m=>m.slug===e);p&&g(p)}catch(p){U("Could not delete the theme",p instanceof Error?p.message:"","error")}},M=async()=>{const u=s.find(v=>v.slug===e),p={label:u?.label??e,tokens:{...u?.tokens??{},...t}},m=JSON.stringify(p,null," ");try{await navigator.clipboard.writeText(m),U("Theme copied","Paste it into another site to import it.")}catch{window.prompt("Copy this theme",m)}},re=()=>{const u=window.prompt("Paste a theme");if(u)try{const p=JSON.parse(u);if(!p.tokens||typeof p.tokens!="object")throw new Error("That does not look like a theme.");for(const[m,v]of Object.entries(p.tokens))t[m]=String(v),n.onOverride(m,String(v));b({...t}),z(),q(x)}catch(p){U("Could not read that theme",p instanceof Error?p.message:"","error")}},At=L("Delete",()=>void P(),"danger"),Tt=()=>{const u=s.find(p=>p.slug===e);At.hidden=!u?.custom};return _(),A(),x(),d(),Tt(),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:[L("Save as a theme",()=>void S(),"primary"),L("Export",()=>void M()),L("Import",re),At]})]}),c]}),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"}),i]})]})]})}async function De(){const n=document.querySelector("[data-atfs-root]");if(!n||n.dataset.atfsMounted)return;n.dataset.atfsMounted="1",Ye(n);const e=n.querySelector("[data-atfs-bar]"),t=n.querySelector(".atfs__body")??n;try{const[s,a,i]=await Promise.all([O.config(),O.listThemes(),O.listForms()]);if(!i.length){R(t),t.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=i[0],l={},c=o.theme;const d=()=>{R(t),t.append(ot({themes:a,tokens:s.tokens,activeSlug:c,overrides:l,standalone:!0,onTheme:h=>{c=h},onOverride:(h,y)=>{y===""?delete l[h]:l[h]=y},onOverridesReplaced:h=>{l={...h}},previewFor:async(h,y)=>{const b=await O.getForm(o.id);b.schema.settings.theme=h,b.schema.settings.themeOverrides=y;const{html:g}=await O.preview(o.id,{schema:b.schema,theme:h});return g},onThemesChanged:h=>{a.length=0,a.push(...h)}}))};e&&(R(e),e.append(r("span",{class:"atfs__label",text:"Preview against"}),N(String(o.id),i.map(h=>({value:String(h.id),label:h.title||"(untitled)"})),h=>{o=i.find(y=>String(y.id)===h)??i[0],l={},d()}))),d()}catch(s){R(t),t.append(r("p",{class:"atfb-error",text:s instanceof Error?s.message:"Could not load themes."}))}}typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>void De()):De(),document.addEventListener("os-window-content-loaded",()=>void De()));function fe(n){const e=n.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"}const ks={min:-1,max:-1,sum:-1,avg:-1,round:-1,ceil:1,floor:1,abs:1,sqrt:1,pow:2},lt={"+":{precedence:1,right:!1},"-":{precedence:1,right:!1},"*":{precedence:2,right:!1},"/":{precedence:2,right:!1},"%":{precedence:2,right:!1},"^":{precedence:4,right:!0}};function Ss(n,e,t=[]){if(!n||!n.trim()||n.length>2e3)return null;const s=Ls(n,e,t),a=Es(s);if(!a)return null;const i=$s(a);if(!i)return null;const o=As(i);return o===null||!Number.isFinite(o)?null:o}function Ls(n,e,t){return n.replace(/\{([a-zA-Z0-9_]+)\}/g,(s,a)=>{const i=Object.prototype.hasOwnProperty.call(e,a)?e[a]:null,o=t.find(c=>c.id===a)??null,l=ct(i,o).toFixed(10).replace(/0+$/,"").replace(/\.$/,"");return l===""||l==="-"?"0":l})}function ct(n,e){if(typeof n=="boolean")return n?1:0;if(Array.isArray(n))return n.reduce((a,i)=>a+ct(i,e),0);if(n==null||n==="")return 0;const t=e?.choices??[];for(const a of t)if(String(a.value)===String(n)){if(typeof a.price=="number")return a.price;if(typeof a.points=="number")return a.points;break}const s=Number(n);return Number.isFinite(s)?s:0}function Es(n){const e=[];let t=0;for(;ti.precedence||l.precedence===i.precedence&&!i.right){e.push(t.pop());continue}break}t.push(a);break}case"(":t.push(a);break;case")":{for(;t.length&&t[t.length-1].type!=="(";)e.push(t.pop());if(!t.length)return null;if(t.pop(),t.length&&t[t.length-1].type==="function"){const i=t.pop();i.arity=s.length?s.pop():1,e.push(i)}break}}for(;t.length;){const a=t.pop();if(a.type==="(")return null;e.push(a)}return e}function As(n){const e=[];for(const t of n)switch(t.type){case"number":e.push(t.value);break;case"unary":{if(!e.length)return null;e.push(-e.pop());break}case"operator":{if(e.length<2)return null;const s=e.pop(),a=e.pop();switch(t.value){case"+":e.push(a+s);break;case"-":e.push(a-s);break;case"*":e.push(a*s);break;case"/":e.push(s===0?0:a/s);break;case"%":e.push(s===0?0:a%s);break;case"^":e.push(Math.pow(a,s));break;default:return null}break}case"function":{const s=t.arity??1;if(e.lengtht+s,0);case"avg":return e.reduce((t,s)=>t+s,0)/e.length;case"round":{const t=Math.max(-10,Math.min(10,Math.trunc(e[1]??0))),s=Math.pow(10,t);return Math.round(e[0]*s)/s}case"ceil":return Math.ceil(e[0]);case"floor":return Math.floor(e[0]);case"abs":return Math.abs(e[0]);case"sqrt":return e[0]<0?0:Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]??2);default:return null}}const Is=["sum","min","max","avg","round","ceil","floor","abs","sqrt","pow"],Os=["number","range","scale","rating","total","select","multiselect","radio","checkboxes","switch","quiz"];function Fe(n,e){return n.filter(t=>t.id!==e&&Os.includes(t.type))}function Ds(n,e){const t={};return Fe(n,e).forEach((s,a)=>{t[s.id]=a+1}),t}function Fs(n){const e=r("div",{class:"atfb-overlay"}),t=()=>{e.remove(),document.removeEventListener("keydown",s)},s=b=>{b.key==="Escape"&&t()},a=r("textarea",{class:"atfb-input atfb-formula__input",attrs:{rows:"3","aria-label":"Formula"}});a.value=String(n.field.formula??"");const i=r("p",{class:"atfb-formula__result",attrs:{"aria-live":"polite"}}),o=Ds(n.fields,n.field.id),l=()=>{const b=a.value.trim();if(b===""){i.textContent="Empty. Reference a question below to start.",i.classList.remove("is-error");return}const g=Ss(b,o,n.fields);if(g===null){i.textContent="This does not compute yet — check the braces and parentheses.",i.classList.add("is-error");return}const C=Fe(n.fields,n.field.id).map((_,E)=>`${_.label||_.id} = ${E+1}`).join(", ");i.textContent=`With sample answers (${C}): ${g}`,i.classList.remove("is-error")};a.addEventListener("input",l);const c=(b,g,C=0)=>r("button",{class:"atfb-formula__chip",type:"button",text:b,on:{click:()=>{if(nt(a,g),C>0){const _=(a.selectionStart??a.value.length)-C;a.setSelectionRange(_,_)}}}}),d=Fe(n.fields,n.field.id),h=r("div",{class:"atfb-formula__chips",children:d.length?d.map(b=>c(b.label||b.id,`{${b.id}}`)):[r("p",{class:"atfb-hint",text:"No number-shaped questions yet — add a number, scale or priced choice field and it appears here."})]}),y=r("div",{class:"atfb-formula__chips",children:Is.map(b=>c(`${b}()`,`${b}()`,1))});e.append(r("div",{class:"atfb-modal atfb-formula",attrs:{role:"dialog","aria-label":"Formula editor"},children:[r("h2",{text:"Formula"}),a,i,f("Your questions",h,"Click one to reference its answer."),f("Functions",y),r("div",{class:"atfb-modal__actions",children:[L("Cancel",t),L("Save formula",()=>{n.onSave(a.value.trim()),t()},"primary")]})]})),e.addEventListener("click",b=>{b.target===e&&t()}),document.addEventListener("keydown",s),n.root.append(e),l(),a.focus(),a.setSelectionRange(a.value.length,a.value.length)}const qs="allterrain-forms/form";function Ms(){return window.wp?.os?.relations??null}function dt(n){const e=n.closest("[data-window-id], .os-window");if(!e)return null;const t=e.getAttribute("data-window-id");if(t)return t;const s=e.id??"";return s?s.replace(/^wp-window-/,""):null}const Ns=6e3,ht=120;function ut(n,e){const t=Ms();if(qe.set(n,e),!t?.set)return;const s=i=>{if(me.get(n)!==a)return;const o=dt(n);if(!o){Date.now()s(i),ht);return}try{t.set(o,e)}catch(c){pt||(pt=!0,console.error("[AllTerrain Forms] The shell refused a window identity.",c,e)),me.delete(n);return}if(!e||t.get?.(o)?.id===e.id||Date.now()>=i){me.delete(n);return}window.setTimeout(()=>s(i),ht)},a=Symbol("atf-identity");me.set(n,a),s(Date.now()+Ns)}let pt=!1;const me=new WeakMap,qe=new Map;function Rs(){for(const[n,e]of qe){if(!n.isConnected){qe.delete(n);continue}ut(n,e)}}if(typeof document<"u")for(const n of["os-window-content-loaded","os-window-opened"])document.addEventListener(n,()=>Rs());function Ps(n,e){return{type:qs,id:n.id,label:n.title||"Untitled form",related:[{id:`allterrain-forms/entries-${n.id}`,label:"Entries for this form",url:`${e}admin.php?page=allterrain-forms-entries&form=${n.id}`,group:"allterrain-forms",groupLabel:"Forms",icon:"dashicons-list-view"}]}}const be={letters:{label:"Letters",chars:"A-Za-zÀ-ÖØ-öø-ÿ"},numbers:{label:"Numbers",chars:"0-9"},spaces:{label:"Spaces",chars:" "},punctuation:{label:`Punctuation ( . , ! ? ' " - )`,chars:`.,!?'"()\\-:;`},symbols:{label:"Symbols ( @ # & _ / + )",chars:"@#&_/+*%="}};function Bs(){return{mode:"blocks",starts:"",ends:"",contains:"",notContains:"",chars:[],minLen:"",maxLen:"",regex:"",message:"",tests:[]}}function ft(n){const e=Bs();let t;try{t=JSON.parse(n)}catch{return e}if(!t||typeof t!="object")return e;const s=t;e.mode=s.mode==="regex"?"regex":"blocks";for(const a of["starts","ends","contains","notContains","minLen","maxLen","regex","message"])typeof s[a]=="string"&&(e[a]=s[a]);return Array.isArray(s.chars)&&(e.chars=s.chars.filter(a=>typeof a=="string"&&a in be)),Array.isArray(s.tests)&&(e.tests=s.tests.filter(a=>typeof a=="string").slice(0,10)),e}function ge(n){return n.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&")}function ve(n){if(n.mode==="regex")return n.regex.trim();const e=[],t=n.minLen.trim(),s=n.maxLen.trim();(t!==""||s!=="")&&e.push(`(?=.{${t===""?"0":parseInt(t,10)||0},${s===""?"":parseInt(s,10)||""}}$)`),n.contains!==""&&e.push(`(?=.*${ge(n.contains)})`),n.notContains!==""&&e.push(`(?!.*${ge(n.notContains)})`),n.starts!==""&&e.push(`(?=${ge(n.starts)})`),n.ends!==""&&e.push(`(?=.*${ge(n.ends)}$)`);const a=n.chars.map(o=>be[o]?.chars??"").join(""),i=a?`[${a}]*$`:".*$";return!e.length&&!a?"":`^${e.join("")}${i}`}function mt(n){if(n.mode==="regex")return n.regex.trim()?`Matches the expression ${n.regex.trim()}`:"";const e=[];if(n.starts&&e.push(`starts with “${n.starts}”`),n.ends&&e.push(`ends with “${n.ends}”`),n.contains&&e.push(`contains “${n.contains}”`),n.notContains&&e.push(`never contains “${n.notContains}”`),n.chars.length){const i=n.chars.map(o=>(be[o]?.label??o).split(" (")[0].toLowerCase());e.push(`uses only ${i.join(" and ")}`)}const t=n.minLen.trim(),s=n.maxLen.trim();return t&&s?e.push(`is ${t}–${s} characters long`):t?e.push(`is at least ${t} characters long`):s&&e.push(`is at most ${s} characters long`),e.length?`The answer ${e.length>1?`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`:e[0]}.`:""}function Ws(n,e){const t=ve(n);if(t==="")return null;try{return new RegExp(t).test(e)}catch{return null}}function js(){return window.wp?.os?.windowManager??null}const bt="allterrain-forms-validation";function Hs(n){const e=js(),t=dt(n.root);if(e?.openChild&&t){Us(e,t,n);return}zs(n)}function Us(n,e,t){const s=`${bt}-${t.field.id}`;n.getById?.(s)&&n.remove?.(s);const a={saved:!1},i=()=>{const o=n.getById?.(s);o?.close?o.close():n.remove?.(s)};n.openChild?.(e,{id:s,baseId:bt,url:`#${s}`,title:`Custom rule — ${t.field.label||"this question"}`,icon:"dashicons-yes-alt",native:!0,width:560,height:700,minWidth:440,minHeight:480,ephemeral:!0,autofocus:".atfb-valwin__pane:not([hidden]) input, .atfb-valwin__pane:not([hidden]) textarea",render:o=>{const l=r("div",{class:"atfa atfb-valwin atfb-valwin--window"}),c=r("div",{class:"atfb-valwin__scroll"});l.append(c),gt(c,t,a,i,"window");const d=c.querySelector(".atfb-modal__actions");d&&l.append(d),o.append(l)},onClose:()=>{a.saved||t.onCancel?.()}})}function zs(n){const e=r("div",{class:"atfb-overlay"}),t={saved:!1},s=()=>{e.remove(),document.removeEventListener("keydown",a),t.saved||n.onCancel?.()},a=o=>{o.key==="Escape"&&s()},i=r("div",{class:"atfb-modal atfb-valwin",attrs:{role:"dialog","aria-label":"Custom validation rule"},children:[r("h2",{text:"Custom rule"})]});gt(i,n,t,s,"overlay"),e.append(i),e.addEventListener("click",o=>{o.target===e&&s()}),document.addEventListener("keydown",a),n.root.append(e),e.querySelector(".atfb-valwin__pane:not([hidden]) input, .atfb-valwin__pane:not([hidden]) textarea")?.focus()}function gt(n,e,t,s,a){const i=ft(String(e.field.validationRecipe??""));i.mode==="blocks"&&ve(i)===""&&e.field.pattern&&(i.mode="regex",i.regex=String(e.field.pattern)),i.message||(i.message=String(e.field.messages?.invalid??""));const o=(x,F)=>{const S=r("input",{class:"atfb-input",value:i[x],placeholder:F,attrs:{type:"text"}});return S.addEventListener("input",()=>{i[x]=S.value,A()}),S},l=(x,F)=>{const S=r("input",{class:"atfb-input atfb-valwin__len",value:i[x],attrs:{type:"number",min:"0","aria-label":F}});return S.addEventListener("input",()=>{i[x]=S.value,A()}),S},c=r("div",{class:"atfb-valwin__chars",children:Object.entries(be).map(([x,F])=>D(F.label,i.chars.includes(x),S=>{i.chars=S?[...i.chars,x]:i.chars.filter(P=>P!==x),A()}))}),d=r("div",{class:"atfb-valwin__pane",children:[f("Starts with",o("starts","e.g. AT-")),f("Ends with",o("ends","e.g. -2026")),f("Must contain",o("contains","e.g. @")),f("Must not contain",o("notContains","e.g. spaces? type one")),f("Only these characters",c,"Leave every box unticked to allow anything."),f("Length",r("div",{class:"atfb-valwin__lengths",children:[r("span",{text:"between"}),l("minLen","Minimum length"),r("span",{text:"and"}),l("maxLen","Maximum length"),r("span",{text:"characters"})]}),"Leave a box empty for no limit.")]}),h=r("textarea",{class:"atfb-input atfb-valwin__regex",attrs:{rows:"2","aria-label":"Regular expression",placeholder:"^AT-[0-9]{4}$"}});h.value=i.regex,h.addEventListener("input",()=>{i.regex=h.value,A()});const y=r("div",{class:"atfb-valwin__pane",children:[f("Expression",h,"A regular expression, without slashes. Checked against the whole answer only if you anchor it with ^ and $.")]}),b=[["blocks","Easy blocks"],["regex","Expression (advanced)"]],g=x=>{i.mode=x,d.hidden=x!=="blocks",y.hidden=x!=="regex",A()},_=(()=>{if(H("os-segmented")&&H("os-segment")){const S=document.createElement("os-segmented");S.setAttribute("value",i.mode),S.setAttribute("label","How to write the rule"),S.classList.add("atfb-valwin__tabs");for(const[P,M]of b){const re=document.createElement("os-segment");re.setAttribute("value",P),re.textContent=M,S.append(re)}return S.addEventListener("os-pick",P=>{const M=P.detail?.value;(M==="blocks"||M==="regex")&&(S.setAttribute("value",M),g(M))}),S}const x=r("div",{class:"atfb-valwin__tabs",attrs:{role:"tablist"}}),F=()=>{x.replaceChildren(...b.map(([S,P])=>{const M=i.mode===S;return r("button",{class:`atfb-valwin__tab${M?" is-active":""}`,type:"button",text:P,attrs:{role:"tab","aria-selected":M?"true":"false"},on:{click:()=>{g(S),F()}}})}))};return F(),x})();d.hidden=i.mode!=="blocks",y.hidden=i.mode!=="regex";const E=r("input",{class:"atfb-input",value:i.message,placeholder:"That is not in the expected format.",attrs:{type:"text"}});E.addEventListener("input",()=>{i.message=E.value});const q=r("p",{class:"atfb-valwin__summary",attrs:{"aria-live":"polite"}}),j=r("div",{class:"atfb-valwin__samples"}),z=x=>{const F=r("span",{class:"atfb-valwin__verdict",attrs:{"aria-live":"polite"}}),S=r("input",{class:"atfb-input",value:x,placeholder:"Type a sample answer…",attrs:{type:"text"}});S.addEventListener("input",()=>A()),j.append(r("div",{class:"atfb-valwin__sample",children:[S,F]}))};for(const x of i.tests.length?i.tests:["","",""])z(x);const $=()=>Array.from(j.querySelectorAll("input")).map(x=>x.value),A=()=>{const x=mt(i);q.textContent=x||"Nothing yet — fill in a block above and the rule appears here in plain words.";for(const F of Array.from(j.querySelectorAll(".atfb-valwin__sample"))){const S=F.querySelector("input"),P=F.querySelector(".atfb-valwin__verdict");if(!S||!P)continue;const M=S.value===""?null:Ws(i,S.value);P.textContent=M===null?"·":M?"✓ passes":"✗ fails",P.classList.toggle("is-pass",M===!0),P.classList.toggle("is-fail",M===!1)}};n.append(r("p",{class:"atfb-hint",text:`Describe what a good answer to “${e.field.label||"this question"}” looks like — no code needed.`}),_,d,y,r("div",{class:"atfb-valwin__try",children:[r("h3",{text:"Try it out"}),q,j,L("Add another sample",()=>{z(""),A()},"ghost","plus-alt2")]}),f("When it fails, say",E,"Shown to the visitor when their answer breaks the rule. Leave empty for the default wording."),r("div",{class:"atfb-modal__actions",children:[L(a==="window"?"Close without saving":"Cancel",s),L("Save rule",()=>{const x=ve(i);i.tests=$().filter(F=>F!=="").slice(0,10),t.saved=!0,e.onSave({pattern:x,recipe:i,message:i.message.trim()}),s()},"primary")]})),A()}const Ys=["Contact","Numbers & codes","Text shape","Web"],vt=[{slug:"email",label:"An email address",group:"Contact",example:"jane@example.com",pattern:"^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$",message:"That does not look like an email address."},{slug:"phone",label:"A phone number",group:"Contact",example:"+34 612 345 678",pattern:"^(?=(?:[^0-9]*[0-9]){5,})\\+?[0-9 ().-]{5,24}$",message:"That does not look like a phone number."},{slug:"handle",label:"A username or @handle",group:"Contact",example:"@yourname",pattern:"^@?[A-Za-z0-9_]{2,30}$",message:"That does not look like a username."},{slug:"digits",label:"Numbers only",group:"Numbers & codes",example:"12345",pattern:"^[0-9]+$",message:"Numbers only, please."},{slug:"decimal",label:"A number, decimals allowed",group:"Numbers & codes",example:"3.14",pattern:"^-?[0-9]+([.,][0-9]+)?$",message:"That does not look like a number."},{slug:"price",label:"A price",group:"Numbers & codes",example:"19.99",pattern:"^[0-9]+([.,][0-9]{1,2})?$",message:"That does not look like a price."},{slug:"zip_us",label:"A ZIP code (US)",group:"Numbers & codes",example:"90210",pattern:"^[0-9]{5}(-[0-9]{4})?$",message:"That does not look like a ZIP code."},{slug:"postcode_uk",label:"A postcode (UK)",group:"Numbers & codes",example:"SW1A 1AA",pattern:"^[A-Za-z]{1,2}[0-9][A-Za-z0-9]? ?[0-9][A-Za-z]{2}$",message:"That does not look like a postcode."},{slug:"iban",label:"An IBAN",group:"Numbers & codes",example:"DE89 3704 0044 0532 0130 00",pattern:"^[A-Za-z]{2}[0-9]{2}(?: ?[A-Za-z0-9]){10,32}$",message:"That does not look like an IBAN."},{slug:"credit_card",label:"A card number",group:"Numbers & codes",example:"4242 4242 4242 4242",pattern:"^[0-9](?:[0-9 -]{9,21})?[0-9]$",message:"That does not look like a card number.",luhn:!0},{slug:"letters",label:"Letters only",group:"Text shape",example:"María López",pattern:"^[\\p{L}\\p{M} .'’-]+$",message:"Letters only, please."},{slug:"alphanumeric",label:"Letters and numbers only",group:"Text shape",example:"abc123",pattern:"^[A-Za-z0-9]+$",message:"Letters and numbers only, please."},{slug:"no_spaces",label:"One word, no spaces",group:"Text shape",example:"one-word",pattern:"^\\S+$",message:"No spaces allowed."},{slug:"url",label:"A web address",group:"Web",example:"https://example.com",pattern:"^(https?://)?([A-Za-z0-9-]+\\.)+[A-Za-z]{2,}([/?#]\\S*)?$",message:"That does not look like a web address."},{slug:"ip",label:"An IP address",group:"Web",example:"192.168.0.1",pattern:"^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$",message:"That does not look like an IP address."},{slug:"slug",label:"A URL slug",group:"Web",example:"my-page-title",pattern:"^[a-z0-9]+(-[a-z0-9]+)*$",message:"Lowercase letters, numbers and dashes only."},{slug:"hex_color",label:"A hex colour",group:"Web",example:"#3366ff",pattern:"^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$",message:"That does not look like a colour code."}];function Gs(n){return vt.find(e=>e.slug===n)??null}function Me(){return window.wp?.os??null}const yt="allterrain-forms/preview",Ne="allterrain-forms-preview";function Xs(n){const e=Me();if(!e?.registerTitleBarButton)return()=>{};const t=()=>{try{e.registerTitleBarButton({id:yt,label:"Preview this form",icon:"dashicons-visibility",placement:"right",order:90,match:s=>{const a=s?.id??s?.config?.id??"";return a==="allterrain-forms"||a.startsWith("allterrain-forms#")},onClick:()=>void wt(n),owner:"allterrain-forms-builder"})}catch{}};return e.ready?e.ready(t):t(),()=>{try{e.unregisterTitleBarButton?.(yt)}catch{}}}async function wt(n){n.isDirty()&&await n.save();const e=n.current();e&&xt(e.id,e.title,e.previewUrl)}function xt(n,e,t){const s=Me();if(!s?.windowManager?.open){window.open(t,"_blank","noopener");return}s.windowManager.open({id:`${Ne}-${n}`,baseId:Ne,url:t,title:`Preview: ${e}`,icon:"dashicons-visibility"})}function Ks(n,e,t){if(!Me()?.windowManager?.open||!document.querySelector(`[data-window-id="${Ne}-${n}"]`))return;const i=t.includes("?")?"&":"?";xt(n,e,`${t}${i}atf_r=${Date.now()}`)}const ie="allterrain-forms/field",Vs=["openstation/file","desktop-mode/file","openstation/attachment"],_t="allterrain-forms/logic-map-v2";function K(n,e){return n.dataset.atfbBind=e,n}const kt={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"}}},Zs={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(n,e,t){const s=n[e.key],a=i=>t(e.key,i);if(e.control==="checkbox")return D(e.label,!!s,a);if(e.control==="commas"){const i=Array.isArray(s)?s:[];return f(e.label,k(i.join(", "),o=>{a(o.split(",").map(l=>l.trim().replace(/^\./,"").toLowerCase()).filter(Boolean))}),e.hint)}return e.control==="select"?f(e.label,N(String(s??""),e.options??[],a),e.hint):e.control==="textarea"?f(e.label,he(String(s??""),a),e.hint):e.control==="number"?f(e.label,G(String(s??""),a),e.hint):f(e.label,K(k(String(s??""),a),e.key),e.hint)}function Lt(n,e){const t=new Set(n.map(a=>a.key).filter(Boolean));let s=n.length+1;return e.split(` `).map(a=>a.trim()).filter(Boolean).map((a,i)=>{const o=n[i]?.key;if(o)return{key:o,label:a};for(;t.has(`r${s}`);)s+=1;return t.add(`r${s}`),{key:`r${s}`,label:a}})}function Et(n,e,t){const s=n.findIndex(i=>i.id===e);if(s<0)return null;const a=Math.max(0,Math.min(t,n.length-1));return a===s?null:{from:s,to:a}}const Re=[{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}"}],Js=["About the person filling it in","The date and time","About this site"],Pe=(n,e)=>B?.i18n?.[n]??e;class Ct{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=jt(_t)!=="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=Se(()=>{this.save(!0)},2500),this.renderInspector=Wt(()=>{if(R(this.inspector),!this.schema||(this.root.classList.toggle("atfb--build-only-panes",this.tab!=="build"),this.tab!=="build"))return;const t=this.schema.fields.find(o=>o.id===this.selected);if(this.root.classList.toggle("atfb--has-selection",!!t),!t){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 s=this.config?.fieldTypes.find(o=>o.type===t.type),a=s?.supports??[],i=(o,l)=>{const c=this.liveField(t.id);c&&(c[o]=l,this.markDirty(),this.renderCanvas())};this.inspector.append(r("h3",{class:"atfb-inspector__title",text:s?.label??t.type}),r("p",{class:"atfb-hint",text:`Reference this field as {field:${t.id}}`})),a.includes("label")&&this.inspector.append(f("Label",K(k(t.label,o=>i("label",o)),"label"))),a.includes("placeholder")&&this.inspector.append(f("Placeholder",K(k(t.placeholder,o=>i("placeholder",o)),"placeholder"))),a.includes("hint")&&this.inspector.append(f("Hint",K(k(t.hint,o=>i("hint",o)),"hint"),"Shown under the field, and read out with it.")),a.includes("nextlabel")&&this.inspector.append(f("Next button",K(k(String(t.nextLabel??""),o=>i("nextLabel",o)),"nextLabel"),"Leave empty for “Next”.")),a.includes("prevlabel")&&this.inspector.append(f("Back button",K(k(String(t.prevLabel??""),o=>i("prevLabel",o)),"prevLabel"),"Leave empty for “Back”.")),a.includes("addlabel")&&this.inspector.append(f("Add button",K(k(String(t.addLabel??""),o=>i("addLabel",o)),"addLabel"),"Leave empty for “Add another”.")),a.includes("required")&&this.inspector.append(D("Required",t.required,o=>i("required",o))),a.includes("width")&&this.inspector.append(f("Width",N(t.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=>i("width",o)))),s?.choices&&this.inspector.append(this.renderChoicesEditor(t,i)),this.renderTypeSettings(t,s,a,i),(t.type==="total"||a.includes("formula"))&&this.inspector.append(f("Formula",r("div",{class:"atfb-formula__row",children:[k(String(t.formula??""),o=>i("formula",o)),L("Formula editor",()=>Fs({root:this.root,fields:this.schema?.fields??[],field:t,onSave:o=>{i("formula",o),this.renderInspector()}}))]}),"Reference answers with braces — {f1} * {f2} + 10 — or open the editor and click them in."),f("Currency symbol",k(String(t.currency??""),o=>i("currency",o)))),this.inspector.append(this.renderValidationSection(t,a,i)),this.inspector.append(this.renderLogicSection(t,i)),a.includes("prefill")&&this.inspector.append(this.prefillControl(t,i)),a.includes("css")&&this.inspector.append(f("CSS class",k(t.cssClass,o=>i("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"),this.canvas.addEventListener("click",t=>{const s=t.target;if(!(this.tab!=="build"||!this.selected||s.closest("[data-atfb-card], button, os-button, a, input, textarea, select, os-select, label, [contenteditable]"))){this.selected=null;for(const a of this.canvas.querySelectorAll(".atfb-card.is-selected"))a.classList.remove("is-selected");this.renderInspector()}})}async start(){try{const[s,a,i]=await Promise.all([O.config(),O.listThemes(),O.listForms()]);this.config=s,this.themes=a,this.forms=i}catch(s){this.fail(s);return}this.teardowns.push(Mt([ie])),this.teardowns.push(Xs({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=s=>{this.dirty&&(s.preventDefault(),s.returnValue="")};window.addEventListener("beforeunload",e),this.teardowns.push(()=>window.removeEventListener("beforeunload",e));const t=s=>{!(s.metaKey||s.ctrlKey)||s.key.toLowerCase()!=="z"||s.target?.closest("input, textarea, [contenteditable]")||(s.preventDefault(),this.travel(s.shiftKey?1:-1))};if(this.root.addEventListener("keydown",t),this.teardowns.push(()=>this.root.removeEventListener("keydown",t)),this.renderBar(),this.renderPalette(),this.forms.length){const s=Jt("builder");await this.open(s&&this.forms.some(a=>a.id===s)?s:this.forms[0].id)}else this.renderFormsList()}destroy(){this.canvasTarget?.(),this.canvasTarget=null,this.teardowns.forEach(e=>e()),this.teardowns=[]}fail(e){R(this.bar),this.bar.append(r("p",{class:"atfb-error",text:e instanceof Error?e.message:"Something went wrong loading your forms."}))}renderBar(){R(this.bar);const e=N(String(this.form?.id??""),[...this.forms.map(a=>({value:String(a.id),label:a.title||"(untitled)"}))],a=>void this.open(Number(a)));e.setAttribute("aria-label","Choose a form");const t=r("input",{class:"atfb-title",type:"text",value:this.form?.title??"",placeholder:"Untitled form",attrs:{"aria-label":"Form title"},on:{input:a=>{this.form&&(this.form.title=a.target.value,this.markDirty())}}}),s=r("div",{class:"atfb-tabs",attrs:{role:"tablist"},children:[["build","Build"],["theme","Theme"],["settings","Settings"],["notify","Notifications"],["confirm","Confirmations"]].map(([a,i])=>r("button",{class:`atfb-tab${this.tab===a?" is-active":""}`,type:"button",text:i,attrs:{role:"tab","aria-selected":this.tab===a},on:{click:()=>{this.tab=a,this.renderBar(),this.renderInspector(),this.renderCanvas()}}}))});this.bar.append(r("div",{class:"atfb-bar__left",children:[this.forms.length>1?e:null,t]}),s,r("div",{class:"atfb-bar__right",children:[this.historyButton("undo","Undo",-1),this.historyButton("redo","Redo",1),L("New",()=>void this.showTemplates(),"secondary","plus-alt2"),L("Export",()=>void this.exportForm(),"secondary","download"),L("Import",()=>void this.importForm(),"secondary","upload"),L("Preview",()=>void this.preview(),"secondary","visibility"),L("Entries",()=>this.openEntries(),"secondary","list-view"),this.logicMapButton(),this.saveButton()]}))}liveField(e){return this.schema?.fields.find(t=>t.id===e)}syncCanvas(e){const t=this.canvas.querySelector(`[data-atfb-card="${CSS.escape(e.id)}"]`);if(t)for(const s of t.querySelectorAll(".atfb-editable[data-atfb-bind]")){const a=st(e,s.dataset.atfbBind??"");s.textContent!==a&&(s.textContent=a)}}syncInspector(e){if(this.selected===e.id)for(const t of this.inspector.querySelectorAll("[data-atfb-bind]")){const s=st(e,t.dataset.atfbBind??"");t.value!==s&&("value"in t?t.value=s:t.setAttribute("value",s))}}rebindCanvas(){if(this.tab!=="build")return;const e=document.activeElement;if(e instanceof HTMLElement&&this.canvas.contains(e)){e.addEventListener("blur",()=>this.rebindCanvas(),{once:!0});return}this.renderCanvas()}snapshot(){if(!this.schema)return;const e=JSON.stringify(this.schema);this.history[this.historyAt]!==e&&(this.history=this.history.slice(0,this.historyAt+1),this.history.push(e),this.history.length>60&&this.history.shift(),this.historyAt=this.history.length-1,this.syncHistoryButtons())}travel(e){const t=this.historyAt+e;!this.schema||t<0||t>=this.history.length||(this.historyAt=t,this.schema=JSON.parse(this.history[t]),this.schema.fields.some(s=>s.id===this.selected)||(this.selected=null),this.markDirty(),this.renderBar(),this.renderCanvas(),this.renderInspector())}historyButton(e,t,s){const a=L(t,()=>this.travel(s),"secondary",e);return a.setAttribute("data-atfb-history",String(s)),a.disabled=!this.canTravel(s),a}canTravel(e){const t=this.historyAt+e;return t>=0&&tURL.revokeObjectURL(s),1e3)}async importForm(){const e=r("input",{type:"file",attrs:{accept:"application/json,.json"}});e.addEventListener("change",async()=>{const t=e.files?.[0];if(t)try{const s=JSON.parse(await t.text());if(!s.schema)throw new Error("That file does not contain a form.");const a=await O.createForm({title:s.title??t.name.replace(/\.json$/i,""),schema:s.schema});this.forms.unshift({id:a.id,title:a.title,status:a.status,modified:a.modified,fields:a.schema.fields.length,theme:a.schema.settings.theme,entries:0,unread:0,views:0,submissions:0,shortcode:a.shortcode}),this.form=a,this.schema=a.schema,this.selected=null,this.dirty=!1,this.history=[],this.historyAt=-1,this.snapshot(),this.renderBar(),this.renderCanvas(),this.renderInspector(),U("Form imported",a.title)}catch(s){U("Could not import that file",s instanceof Error?s.message:"","error")}}),e.click()}saveButton(){const e=L("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 t=this.editGeneration;try{const s=await O.updateForm(this.form.id,{title:this.form.title,schema:this.schema});if(t===this.editGeneration){this.form=s,this.schema=s.schema,this.dirty=!1,this.rebindCanvas();const i=this.bar.querySelector("[data-atfb-save]");i&&(i.disabled=!0)}ps(s.id);const a=this.forms.find(i=>i.id===s.id);a&&(a.title=s.title),Ks(s.id,s.title,s.previewUrl),e||U("Form saved",s.title)}catch(s){U(Pe("saveFailed","Could not save"),s instanceof Error?s.message:"","error")}finally{this.saveInFlight=!1;const s=this.queuedSave;this.queuedSave=null,s&&this.save(s.silent)}}async openFormById(e){await this.open(e)}async open(e){if(!(this.dirty&&!await ke("You have unsaved changes. Discard them?"))){try{this.form=await O.getForm(e),this.schema=this.form.schema,this.selected=null,this.dirty=!1,this.history=[],this.historyAt=-1,this.snapshot()}catch(t){this.fail(t);return}this.renderBar(),this.renderCanvas(),this.renderInspector(),this.announceIdentity()}}announceIdentity(){this.form&&ut(this.root,Ps(this.form,B?.adminUrl??""))}async showTemplates(){if(!this.config)return;const e=r("div",{class:"atfb-overlay"}),t=i=>{i.key==="Escape"&&s()},s=()=>{e.remove(),document.removeEventListener("keydown",t)},a=r("div",{class:"atfb-templates",children:this.config.templates.map(i=>r("button",{class:"atfb-template",type:"button",on:{click:async()=>{s();try{const o=await O.createForm({template:i.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){U("Could not create the form",o instanceof Error?o.message:"","error")}}},children:[W(i.icon),r("strong",{text:i.label}),r("span",{text:i.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"}),a,r("div",{class:"atfb-modal__actions",children:[L("Cancel",s)]})]})),e.addEventListener("click",i=>{i.target===e&&s()}),document.addEventListener("keydown",t),this.root.append(e),a.querySelector("button")?.focus()}renderFormsList(){R(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."}),L("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(`${B?.adminUrl??""}admin.php?page=allterrain-forms-entries`)}renderPalette(){if(!this.config)return;R(this.palette);const e=new Map;for(const s of this.config.fieldTypes){const a=e.get(s.group)??[];a.push(s),e.set(s.group,a)}const t=r("input",{class:"atfb-input atfb-palette__search",type:"search",placeholder:"Search fields",attrs:{"aria-label":"Search field types"},on:{input:s=>{const a=s.target.value.toLowerCase().trim();this.palette.querySelectorAll(".atfb-chip").forEach(i=>{const o=(i.textContent??"").toLowerCase();i.hidden=a!==""&&!o.includes(a)}),this.palette.querySelectorAll(".atfb-group").forEach(i=>{const o=Array.from(i.querySelectorAll(".atfb-chip")).some(l=>!l.hidden);i.hidden=!o})}}});this.palette.append(t);for(const[s,a]of Object.entries(this.config.groups)){const i=e.get(s);i?.length&&this.palette.append(r("div",{class:"atfb-group",children:[r("h3",{class:"atfb-group__title",text:a}),r("div",{class:"atfb-group__items",children:i.map(o=>this.paletteChip(o))})]}))}}paletteChip(e){const t=r("button",{class:"atfb-chip",type:"button",title:e.description,attrs:{"data-atf-type":e.type},children:[W(e.icon),r("span",{text:e.label})]});return t.addEventListener("pointerdown",s=>{const a=r("div",{class:"atfb-chip atfb-chip--ghost",children:[W(e.icon),r("span",{text:e.label})]});te().start({payload:je(ie,t,{fieldType:e.type,isNew:!0},s,a),origin:s,onClickOnly:()=>this.addField(e.type)})}),t.addEventListener("click",s=>{te().recentlyEndedDrag()&&s.preventDefault()}),t}renderCanvas(){if(R(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:Pe("emptyCanvas","Drag a field from the left to begin.")})),this.schema.fields.forEach((s,a)=>{e.append(this.renderFieldCard(s,a))});const t=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(t),this.registerCanvasTarget(e),this.paintLogicMap(t),this.paintCanvasTheme()}prefillControl(e,t){const s=e.prefill.startsWith("query:"),a=Re.some(b=>b.value===e.prefill),i=s?"query":a&&e.prefill||(e.prefill?"custom":""),o=r("div",{class:"atfb-prefill__detail"}),l=r("p",{class:"atfb-row__hint atfb-prefill__preview"}),c=b=>{if(o.replaceChildren(),l.replaceChildren(),b==="query"){const g=e.prefill.startsWith("query:")?e.prefill.slice(6):"";o.append(k(g,C=>{const _=C.trim();t("prefill",_?`query:${_}`:""),d(`query:${_}`)},"utm_source"),r("p",{class:"atfb-row__hint",text:"The name of the parameter in the link people arrive on."}))}b==="custom"&&o.append(k(e.prefill,g=>{t("prefill",g),d(g)},"myplugin:something"),r("p",{class:"atfb-row__hint",text:"For a source another plugin has added through atf_resolve_prefill."})),d(e.prefill)},d=b=>{if(l.replaceChildren(),!b)return;if(b.startsWith("query:")){const C=b.slice(6);C&&(l.textContent=`A visit to …/your-page/?${C}=abc opens the form with “abc” in it.`);return}const g=Re.find(C=>C.value===b)?.tag;g&&Ae(this.form?.id??0).then(C=>{for(const _ of C)for(const E of _.items)if(E.tag===g){const q=b.startsWith("user:");if(!E.sample){l.textContent="Empty unless the visitor is signed in.";return}l.textContent=q?`Opens with “${E.sample}” for you — empty for a visitor who is not signed in.`:`Opens with “${E.sample}”.`;return}})};c(i);const h=r("select",{class:"atfb-input atfb-select",on:{change:b=>{const g=b.target.value;t("prefill",g==="query"||g==="custom"?"":g),c(g)}}});h.append(r("option",{value:"",text:"Nothing — leave it empty",attrs:{selected:i===""}}));for(const b of Js){const g=document.createElement("optgroup");g.label=b;for(const C of Re.filter(_=>_.group===b))g.append(r("option",{value:C.value,text:C.label,attrs:{selected:C.value===i}}));h.append(g)}const y=document.createElement("optgroup");return y.label="From the link they arrived on",y.append(r("option",{value:"query",text:"A parameter in the web address",attrs:{selected:i==="query"}})),h.append(y,r("option",{value:"custom",text:"Something else (advanced)",attrs:{selected:i==="custom"}})),f("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,t){const s=t.some(i=>i.kind==="field"&&i.missing),a=r("span",{class:`atfb-cond${s?" is-broken":""}`,attrs:{"aria-label":Qe(t)},children:[W("randomize"),...t.map(i=>this.renderConditionToken(e,i))]});return a.addEventListener("pointerdown",i=>i.stopPropagation()),a.addEventListener("click",i=>i.stopPropagation()),a.addEventListener("keydown",i=>i.stopPropagation()),a}editCondition(e,t,s=!0,a=""){const i=this.liveField(e)?.logic;if(i){if(t(i),this.markDirty(),!s){this.logicMap?.setEdges(pe(this.schema?.fields??[]));return}this.renderCanvas(),this.renderInspector(),a&&window.requestAnimationFrame(()=>{this.canvas.querySelector(`[data-cond="${CSS.escape(a)}"]`)?.focus()})}}condSelect(e,t,s,a,i){if(H("os-select")&&H("os-option")){const o=document.createElement("os-select");o.setAttribute("value",e),o.setAttribute("aria-label",a),o.setAttribute("data-cond",s),o.className="atfb-cond__control",o.title=a;for(const l of t){const c=document.createElement("os-option");c.setAttribute("value",l.value),c.textContent=l.label,o.append(c)}return o.addEventListener("os-pick",l=>{i(String(l.detail?.value??""))}),o}return r("select",{class:"atfb-cond__control atfb-cond__control--native",title:a,attrs:{"aria-label":a,"data-cond":s},on:{change:o=>i(o.target.value)},children:t.map(o=>r("option",{value:o.value,text:o.label,attrs:{selected:o.value===e}}))})}renderConditionToken(e,t){if(t.kind==="field"&&!t.missing)return r("button",{class:"atfb-cond__chip atfb-cond__chip--field",type:"button",text:t.text,title:"Go to this question",on:{click:a=>{a.stopPropagation(),this.selectField(t.fieldId),this.canvas.querySelector(`[data-atfb-card="${CSS.escape(t.fieldId)}"]`)?.scrollIntoView({block:"nearest",behavior:"smooth"})}}});if(t.kind==="verb")return r("button",{class:"atfb-cond__verb",type:"button",text:t.text,title:"Switch between showing and hiding this field when the condition matches.",attrs:{"data-cond":`${e.id}:verb`},on:{click:()=>this.editCondition(e.id,s=>{s.action=s.action==="hide"?"show":"hide"},!0,`${e.id}:verb`)}});if(t.kind==="join")return r("button",{class:"atfb-cond__join",type:"button",text:t.text,title:"Switch between needing every rule (and) or any one of them (or).",attrs:{"data-cond":`${e.id}:join`},on:{click:()=>this.editCondition(e.id,s=>{s.match=s.match==="all"?"any":"all"},!0,`${e.id}:join`)}});if(t.kind==="operator"){const s=`${e.id}:op:${t.ruleIndex}`;return this.condSelect(t.operator,Object.entries(Le).map(([a,i])=>({value:a,label:i})),s,"How the answer is compared",a=>this.editCondition(e.id,i=>{const o=i.rules[t.ruleIndex];o&&(o.operator=a)},!0,s))}return t.kind==="value"?this.renderConditionValue(e,t):r("span",{class:"atfb-cond__chip atfb-cond__chip--missing",text:t.text})}renderConditionValue(e,t){const s=`${e.id}:value:${t.ruleIndex}`,a=this.schema?.fields.find(c=>c.id===t.sourceId),i=(c,d)=>this.editCondition(e.id,h=>{const y=h.rules[t.ruleIndex];y&&(y.value=c)},d,s);if(a?.choices?.length){const c=a.choices.map(d=>({value:d.value,label:d.label||d.value}));return t.raw!==""&&!a.choices.some(d=>d.value===t.raw)&&c.unshift({value:t.raw,label:t.text}),this.condSelect(t.raw,c,s,"The answer that triggers this",d=>i(d,!0))}const o=["number","range","scale","rating","total"].includes(a?.type??""),l=r("input",{class:"atfb-cond__chip atfb-cond__chip--value atfb-cond__value",value:t.raw,title:"The answer that triggers this. Edit it here.",attrs:{type:"text","aria-label":"The answer that triggers this","data-cond":s,inputmode:o?"decimal":void 0,size:String(Math.max(2,Math.min(24,t.raw.length||2)))}});return l.addEventListener("input",()=>{l.size=Math.max(2,Math.min(24,l.value.length||2)),i(l.value,!1)}),l.addEventListener("change",()=>i(l.value,!0)),l.addEventListener("keydown",c=>{c.key==="Enter"&&(c.preventDefault(),i(l.value,!0))}),l}section(e,t,s,a=!1){const i=r("details",{class:"atfb-section",attrs:{open:this.openSections.get(e)??a},children:[r("summary",{text:t}),...s]});return i.addEventListener("toggle",()=>this.openSections.set(e,i.open)),i}logicMapButton(){const e=pe(this.schema?.fields??[]).length>0,t=L(this.logicMapOn?"Hide logic":"Show logic",()=>{this.logicMapOn=!this.logicMapOn,Ht(_t,this.logicMapOn?"on":"off"),this.renderBar(),this.renderCanvas()},this.logicMapOn?"primary":"secondary","randomize");return t.title="Draw a line from each question to the ones it decides.",t.hidden=!e,t}paintLogicMap(e){this.logicMap?.destroy(),this.logicMap=null;const t=this.schema?.fields??[],s=pe(t);if(!s.length||!this.logicMapOn)return;e.classList.add("has-logicmap");const a=new ns(e);a.setEdges(s),a.highlight(this.selected??""),this.logicMap=a,e.addEventListener("pointerover",i=>{const o=i.target.closest("[data-atfb-card]");a.highlight(o?.dataset.atfbCard??this.selected??"")}),e.addEventListener("pointerleave",()=>a.highlight(this.selected??""))}renderFieldCard(e,t){const s=this.config?.fieldTypes.find(d=>d.type===e.type),a=this.selected===e.id,i=this.schema?.fields??[],o=es(e,i),l=ss(i).get(e.id)??0,c=r("div",{class:`atfb-card${a?" is-selected":""}`,attrs:{"data-atfb-card":e.id,"data-index":t,tabindex:"0",role:"button","aria-pressed":a,"aria-label":`${e.label||s?.label||e.type}, ${t+1} of ${this.schema?.fields.length??0}`},children:[r("div",{class:"atfb-card__grip",attrs:{"aria-hidden":"true"},children:[W("menu")]}),r("div",{class:"atfb-card__body",children:[r("div",{class:"atfb-card__head",children:[W(s?.icon??"dashicons-forms"),r("span",{class:"atfb-card__type",text:s?.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]}),os(e,s,{edit:d=>{const h=this.liveField(e.id);h&&(d(h),this.markDirty(),this.syncInspector(h))},restructure:d=>{const h=this.liveField(e.id);h&&(this.snapshot(),d(h),this.markDirty(),this.renderCanvas(),this.renderInspector())}}),o.length?this.renderCondition(e,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 c.addEventListener("click",d=>{d.target.closest(".atfb-card__actions")||te().recentlyEndedDrag()||this.selectField(e.id)}),c.addEventListener("keydown",d=>{if(d.key==="Enter"||d.key===" "){d.preventDefault(),this.selectField(e.id);return}d.altKey&&(d.key==="ArrowUp"||d.key==="ArrowDown")&&(d.preventDefault(),this.moveField(e.id,d.key==="ArrowUp"?t-1:t+1),window.requestAnimationFrame(()=>{this.canvas.querySelector(`[data-atfb-card="${CSS.escape(e.id)}"]`)?.focus()})),(d.key==="Delete"||d.key==="Backspace")&&(d.preventDefault(),this.deleteField(e.id))}),c.addEventListener("pointerdown",d=>{d.target.closest(".atfb-card__actions")||te().start({payload:je(ie,c,{fieldId:e.id,field:e,isNew:!1},d),origin:d})}),c}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:s=>s.stopPropagation(),click:s=>{s.stopPropagation(),e.required=!e.required,this.markDirty(),this.renderCanvas(),this.renderInspector()}}})}cardAction(e,t,s){return r("button",{class:"atfb-card__action",type:"button",title:t,attrs:{"aria-label":t},on:{click:a=>{a.stopPropagation(),s()}},children:[W(e)]})}registerCanvasTarget(e){this.canvasTarget?.(),this.canvasTarget=null;const t=r("div",{class:"atfb-marker",attrs:{"aria-hidden":"true"}}),s=te().registerDropTarget({id:`atfb-canvas-${this.form?.id??0}`,element:e,accept:i=>i.type===ie,onEnter:()=>e.classList.add("is-dropping"),onLeave:()=>{e.classList.remove("is-dropping"),t.remove()},onDrop:(i,o)=>{e.classList.remove("is-dropping"),t.remove();const l=i.payload.data,c=l.fieldId?this.canvas.querySelector(`[data-atfb-card="${CSS.escape(l.fieldId)}"]`):null,d=He(e,".atfb-card",o.clientY,c??void 0);if(l.isNew&&l.fieldType){this.addField(l.fieldType,d);return}if(l.fieldId&&this.schema?.fields.some(h=>h.id===l.fieldId)){this.moveField(l.fieldId,d);return}l.field&&this.insertField({...l.field,id:""},d)}}),a=i=>{const o=i.detail;if(o?.payload?.type!==ie||!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,c=o.clientY??0,d=He(e,".atfb-card",c,l??void 0),h=Array.from(e.querySelectorAll(".atfb-card")).filter(y=>y!==l);d>=h.length?e.append(t):h[d].before(t)};document.addEventListener("os.drag.move",a),this.canvasTarget=()=>{s(),document.removeEventListener("os.drag.move",a)}}addField(e,t){const s=this.config?.fieldTypes.find(i=>i.type===e);if(!s||!this.schema)return;const a={id:this.nextFieldId(),type:e,label:s.input?s.label:"",placeholder:"",hint:"",required:!1,width:"full",cssClass:"",default:"",choices:s.choices?[{label:"First choice",value:"first"},{label:"Second choice",value:"second"}]:[],logic:{enabled:!1,action:"show",match:"all",rules:[]},messages:{},prefill:"",...s.settings};this.insertField(a,t)}insertField(e,t){if(!this.schema)return;e.id||(e.id=this.nextFieldId()),this.snapshot();const s=t===void 0?this.schema.fields.length:Math.max(0,Math.min(t,this.schema.fields.length));this.schema.fields.splice(s,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,t){if(!this.schema)return;const s=Et(this.schema.fields,e,t);if(!s)return;this.snapshot();const[a]=this.schema.fields.splice(s.from,1);this.schema.fields.splice(s.to,0,a),this.markDirty(),this.renderCanvas()}duplicateField(e){if(!this.schema)return;const t=this.schema.fields.findIndex(a=>a.id===e);if(t<0)return;const s=JSON.parse(JSON.stringify(this.schema.fields[t]));s.id=this.nextFieldId(),this.insertField(s,t+1)}async deleteField(e){if(!this.schema)return;const t=this.schema.fields.filter(a=>a.logic?.rules?.some(i=>i.field===e)),s=t.length?`Delete this field? ${t.length} other field${t.length===1?"":"s"} use it in a condition, and those conditions will stop working.`:Pe("confirmDelete","Delete this? It cannot be undone.");await ke(s,"Delete field")&&(this.snapshot(),this.schema.fields=this.schema.fields.filter(a=>a.id!==e),this.selected===e&&(this.selected=null),this.markDirty(),this.renderCanvas(),this.renderInspector())}selectField(e){this.selected=e;for(const t of this.canvas.querySelectorAll("[data-atfb-card]")){const s=t.dataset.atfbCard===e;t.classList.toggle("is-selected",s),t.setAttribute("aria-pressed",s?"true":"false")}this.logicMap?.highlight(e),this.renderInspector()}nextFieldId(){const e=new Set((this.schema?.fields??[]).map(s=>s.id));let t=e.size+1;for(;e.has(`f${t}`);)t++;return`f${t}`}nextEntryId(e,t){const s=new Set(t.map(i=>i.id));let a=t.length+1;for(;s.has(`${e}${a}`);)a++;return`${e}${a}`}renderTypeSettings(e,t,s,a){for(const i of s){const o=kt[i];o&&(this.inspector.append(St(e,o,a)),o.also&&this.inspector.append(St(e,{...o,key:o.also.key,label:o.also.label,hint:o.also.hint},a)))}s.includes("rows")&&e.type!=="likert"&&this.inspector.append(f("Lines tall",G(String(e.rows??""),i=>a("rows",i)))),s.includes("rows")&&e.type==="likert"&&this.inspector.append(this.renderStatementList(e,a)),s.includes("parts")&&this.inspector.append(this.renderPartsEditor(e,t,a)),s.includes("default")&&!["files","object"].includes(t?.value??"")&&this.inspector.append(this.renderDefaultControl(e,t,a))}renderStatementList(e,t){const s=Array.isArray(e.rows)?e.rows:[];return f("Statements",he(s.map(a=>a.label??"").join(` `),a=>t("rows",Lt(s,a)),5),"One per line. Each becomes a row of the matrix.")}renderPartsEditor(e,t,s){const a=t?.parts??[],i=Array.isArray(e.parts)?e.parts:a.map(l=>l.key),o=a.map(l=>D(l.label,i.includes(l.key),c=>{const d=a.map(h=>h.key).filter(h=>h===l.key?c:i.includes(h));s("parts",d.length?d:[l.key])}));return r("div",{class:"atfb-section",children:[r("h4",{class:"atfb-section__title",text:"Parts to ask for"}),...o]})}renderDefaultControl(e,t,s){const a="Filled in before they start. They can change it.";return e.type==="switch"||e.type==="consent"?D("On by default",!!e.default,i=>s("default",i)):t?.choices&&(e.choices??[]).length?f("Default answer",N(String(e.default??""),[{value:"",label:"Nothing chosen"},...(e.choices??[]).map(i=>({value:String(i.value),label:i.label||String(i.value)}))],i=>s("default",i)),a):f("Default answer",k(String(e.default??""),i=>s("default",i)),a)}renderChoicesEditor(e,t){const s=e.choices??[],a=o=>this.liveField(e.id)?.choices?.[o],i=r("div",{class:"atfb-choices"});return s.forEach((o,l)=>{const c=r("div",{class:"atfb-choice-row",children:[e.type==="image_choice"?this.choiceImageWell(o,l,e):null,K(k(o.label,d=>{const h=a(l);if(!h)return;const y=!h.value||h.value===h.label;h.label=d,y&&(h.value=d),this.markDirty();const b=this.liveField(e.id);b&&this.syncCanvas(b)}),`choice:${l}:label`),K(k(o.value,d=>{const h=a(l);h&&(h.value=d,this.markDirty())},"value"),`choice:${l}:value`),e.type==="quiz"||o.points!==void 0?G(String(o.points??""),d=>{const h=a(l);h&&(h.points=d===""?void 0:Number(d),this.markDirty())}):G(String(o.price??""),d=>{const h=a(l);h&&(h.price=d===""?void 0:Number(d),this.markDirty())}),r("button",{class:"atfb-card__action",type:"button",attrs:{"aria-label":`Remove ${o.label}`},on:{click:()=>{const d=this.liveField(e.id);d&&((d.choices??[]).splice(l,1),t("choices",d.choices),this.renderInspector())}},children:[W("trash")]})]});i.append(c)}),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."}),i,L("Add choice",()=>{const o=this.liveField(e.id);if(!o)return;const l=o.choices??[];l.push({label:"",value:""}),t("choices",l),this.renderInspector()},"ghost","plus-alt2"),e.type==="quiz"?f("Correct answer",N(String(e.correct??""),[{value:"",label:"—"},...s.map(o=>({value:o.value,label:o.label}))],o=>t("correct",o))):null]})}choiceImageWell(e,t,s){const a=r("div",{class:`atfb-well${e.image?" has-image":""}`,attrs:{"data-choice":t,"aria-label":`Image for ${e.label||`choice ${t+1}`}`},children:[e.image?r("span",{class:"atfb-well__id",text:`#${e.image}`}):W("format-image")]}),i=te().registerDropTarget({id:`atfb-well-${s.id}-${t}`,element:a,accept:o=>Vs.includes(o.type),onEnter:()=>a.classList.add("is-dropping"),onLeave:()=>a.classList.remove("is-dropping"),onDrop:o=>{a.classList.remove("is-dropping");const l=o.payload.data,c=Number(l.attachmentId??l.id??l.file?.id??0);if(!c){U("That is not an image this field can use","","error");return}const d=this.liveField(s.id)?.choices?.[t];d&&(d.image=c,this.markDirty(),this.renderInspector())}});return this.teardowns.push(i),a.addEventListener("click",()=>{const o=this.liveField(s.id)?.choices?.[t];o?.image&&(o.image=void 0,this.markDirty(),this.renderInspector())}),a}renderValidationSection(e,t,s){const a=[],i=[];t.includes("minlength")&&i.push(["minlength","Minimum characters"],["maxlength","Maximum characters"]),t.includes("min")?i.push(["min","Minimum"],["max","Maximum"]):t.includes("max")&&i.push(["max","Highest"]),t.includes("step")&&i.push(["step","Steps of"]),t.includes("mindate")&&i.push(["minDate","Earliest date"],["maxDate","Latest date"]),t.includes("mintime")&&i.push(["minTime","Earliest time"],["maxTime","Latest time"]);for(const[l,c]of i)a.push(f(c,k(String(e[l]??""),d=>s(l,d))));t.includes("pattern")&&a.push(...this.renderAnswerShapeRows(e,s)),t.includes("unique")&&a.push(D("No two people may submit the same value",!!e.unique,l=>s("unique",l)));const o=e.messages??{};return t.includes("required")&&a.push(f("Message when required",k(o.required??"",l=>{o.required=l,s("messages",o)}),"Leave empty for the default wording.")),a.length?this.section(`validation:${e.id}`,"Validation",a):r("div",{class:"atfb-section is-empty"})}buildShapePicker(e,t){const s=[{heading:null,options:[{value:"",label:"Anything at all"}]},...Ys.map(i=>({heading:i,options:vt.filter(o=>o.group===i).map(o=>({value:o.slug,label:o.label}))})),{heading:"Your own",options:[{value:"custom",label:"A custom rule…"}]}];if(H("os-select")&&H("os-option")){const i=document.createElement("os-select");i.setAttribute("value",e),i.setAttribute("aria-label","What the answer should look like"),i.classList.add("atfb-field");for(const o of s){if(o.heading){const l=document.createElement("os-option");l.setAttribute("value",`__heading:${o.heading}`),l.setAttribute("disabled",""),l.textContent=o.heading,i.append(l)}for(const l of o.options){const c=document.createElement("os-option");c.setAttribute("value",l.value),c.textContent=l.label,i.append(c)}}return i.addEventListener("os-pick",o=>{t(String(o.detail?.value??""))}),i}const a=r("select",{class:"atfb-input atfb-select",attrs:{"aria-label":"What the answer should look like"},on:{change:i=>t(i.target.value)}});for(const i of s){const o=i.heading?(()=>{const l=document.createElement("optgroup");return l.label=i.heading,a.append(l),l})():a;for(const l of i.options)o.append(r("option",{value:l.value,text:l.label,attrs:{selected:l.value===e}}))}return a}renderAnswerShapeRows(e,t){const a=(typeof e.validation=="string"?e.validation:"")||(e.pattern?"custom":""),i=()=>Hs({root:this.root,field:this.liveField(e.id)??e,onSave:h=>{t("validation","custom"),t("pattern",h.pattern),t("validationRecipe",JSON.stringify(h.recipe));const y={...this.liveField(e.id)?.messages??{}};y.invalid=h.message,t("messages",y),this.renderInspector()},onCancel:()=>this.renderInspector()}),o=h=>{if(h==="custom"){i();return}t("validation",h),t("pattern",""),t("validationRecipe",""),this.renderInspector()},l=this.buildShapePicker(a,o),c=Gs(a),d=[f("The answer should be",l,c?`e.g. ${c.example}`:"Checked as they type, and again on the server.")];if(a==="custom"){const h=ft(String(e.validationRecipe??"")),y=mt(h)||(e.pattern?`Matches the expression ${String(e.pattern)}`:"No rule yet — open the builder.");d.push(f("Your rule",r("div",{class:"atfb-valrule",children:[r("p",{class:"atfb-valrule__words",text:y}),L("Edit the rule…",i,"secondary","edit")]}),ve(h)||e.pattern?"Built in the rule builder, with a playground to test it.":void 0))}return d}renderLogicSection(e,t){const s=e.logic,a=()=>this.liveField(e.id)?.logic,i=(this.schema?.fields??[]).filter(l=>l.id!==e.id&&l.type!=="page_break"),o=r("div",{class:"atfb-rules"});return s.rules.forEach((l,c)=>{o.append(r("div",{class:"atfb-rule",children:[N(l.field,i.map(d=>({value:d.id,label:d.label||d.id})),d=>{const h=a()?.rules[c];h&&(h.field=d,this.markDirty())}),N(l.operator,Object.entries(this.config?.operators??{}).map(([d,h])=>({value:d,label:h})),d=>{const h=a()?.rules[c];h&&(h.operator=d,this.markDirty())}),k(l.value,d=>{const h=a()?.rules[c];h&&(h.value=d,this.markDirty())}),r("button",{class:"atfb-card__action",type:"button",attrs:{"aria-label":"Remove this rule"},on:{click:()=>{const d=a();d&&(d.rules.splice(c,1),t("logic",d),this.renderInspector())}},children:[W("trash")]})]}))}),this.section(`logic:${e.id}`,"Conditional logic",[D("Only show this field sometimes",s.enabled,l=>{const c=a();c&&(c.enabled=l,t("logic",c),this.renderInspector())}),s.enabled?r("div",{children:[r("div",{class:"atfb-rule-head",children:[N(s.action,[{value:"show",label:"Show"},{value:"hide",label:"Hide"}],l=>{const c=a();c&&(c.action=l,t("logic",c))}),r("span",{text:"this field when"}),N(s.match,[{value:"all",label:"all"},{value:"any",label:"any"}],l=>{const c=a();c&&(c.match=l,t("logic",c))}),r("span",{text:"of these match:"})]}),o,L("Add rule",()=>{const l=a();l&&(l.rules.push({field:i[0]?.id??"",operator:"is",value:""}),t("logic",l),this.renderInspector())},"ghost","plus-alt2")]}):null],s.enabled)}renderTabCanvas(){return this.schema?this.tab==="theme"?ot({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,t)=>{t===""?delete this.schema.settings.themeOverrides[e]:this.schema.settings.themeOverrides[e]=t,this.markDirty()},onOverridesReplaced:e=>{this.schema.settings.themeOverrides={...e},this.markDirty()},previewFor:(e,t)=>this.previewHtml(e,t),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,t=JSON.stringify([e,this.schema.settings.themeOverrides]);if(t!==this.canvasThemeSignature){this.canvasThemeSignature=t;try{const s=await this.previewHtml(e,this.schema.settings.themeOverrides??{});this.root.classList.toggle("atfb--dark-form",/atf-is-dark/.test(s));const a=/