grapesjs-forms 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +62 -0
- package/LICENSE +21 -0
- package/README.md +200 -2
- package/dist/build.d.ts +68 -0
- package/dist/contract.d.ts +100 -0
- package/dist/editor/FormComponents.d.ts +62 -0
- package/dist/events.d.ts +23 -0
- package/dist/grapesjs-forms.js +2754 -0
- package/dist/grapesjs-forms.js.map +1 -0
- package/dist/grapesjs-forms.umd.cjs +103 -0
- package/dist/grapesjs-forms.umd.cjs.map +1 -0
- package/dist/grapesjs-forms.umd.js +103 -0
- package/dist/i18n/index.d.ts +21 -0
- package/dist/i18n/locales/en.d.ts +3 -0
- package/dist/i18n/locales/ru.d.ts +3 -0
- package/dist/i18n/locales/uk.d.ts +3 -0
- package/dist/i18n/types.d.ts +143 -0
- package/dist/index.d.ts +25 -0
- package/dist/placeholders.d.ts +29 -0
- package/dist/plugin.d.ts +28 -0
- package/dist/runtime/index.d.ts +8 -0
- package/dist/runtime/script.d.ts +17 -0
- package/dist/runtime.iife.js +2 -0
- package/dist/runtime.iife.js.map +1 -0
- package/dist/runtime.js +205 -0
- package/dist/runtime.js.map +1 -0
- package/dist/schema.d.ts +142 -0
- package/dist/store/IndexedDbFormStore.d.ts +22 -0
- package/dist/store/MemoryFormStore.d.ts +23 -0
- package/dist/store/RestFormStore.d.ts +37 -0
- package/dist/store/types.d.ts +69 -0
- package/dist/surveyjs.d.ts +19 -0
- package/dist/types.d.ts +79 -0
- package/dist/ui/FormEditor.d.ts +86 -0
- package/dist/ui/dom.d.ts +12 -0
- package/dist/ui/styles.d.ts +10 -0
- package/dist/utils.d.ts +9 -0
- package/openapi.yaml +240 -0
- package/package.json +58 -4
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
(function(g,U){typeof exports=="object"&&typeof module<"u"?U(exports):typeof define=="function"&&define.amd?define(["exports"],U):(g=typeof globalThis<"u"?globalThis:g||self,U(g.grapesjsForms={}))})(this,function(g){"use strict";var Fs=Object.defineProperty;var Ts=(g,U,ae)=>U in g?Fs(g,U,{enumerable:!0,configurable:!0,writable:!0,value:ae}):g[U]=ae;var $=(g,U,ae)=>Ts(g,typeof U!="symbol"?U+"":U,ae);const U=/\{\{\s*([A-Za-z_][\w.\-]*)\s*\}\}/g,ae=new Set(["form","page"]);function st(i,e={}){return String(i??"").replace(U,(t,s)=>{const[a,...n]=s.split(".");if(!ae.has(a))return t;const l=a==="form"?e.form:e.page;if(a==="page"&&!l)return t;let o=l;for(const u of n)o=o&&typeof o=="object"?o[u]:void 0;return o==null||typeof o=="object"?"":String(o)})}const it=i=>!!i&&new RegExp(U.source).test(i),nt=[{token:"{{url}}",at:"run"},{token:"{{path}}",at:"run"},{token:"{{host}}",at:"run"},{token:"{{referrer}}",at:"run"},{token:"{{title}}",at:"run"},{token:"{{lang}}",at:"run"},{token:"{{query.utm_source}}",at:"run"},{token:"{{cookie.name}}",at:"run"},{token:"{{storage.key}}",at:"run"},{token:"{{date}}",at:"run"},{token:"{{time}}",at:"run"},{token:"{{datetime}}",at:"run"},{token:"{{timestamp}}",at:"run"},{token:"{{uuid}}",at:"run"},{token:"{{form.id}}",at:"build"},{token:"{{form.name}}",at:"build"},{token:"{{page.id}}",at:"build"},{token:"{{page.name}}",at:"build"},{token:"{{page.slug}}",at:"build"}],ye=["text","email","tel","url","number","password","textarea","select","radio","checkbox","checkboxes","date","time","datetime","range","color","file","hidden"],de=["heading","paragraph"],at=[...ye,...de],pe=["select","radio","checkboxes"],ve=["text","email","tel","url","password","textarea"],rt=["number","range","date","time","datetime"],N=i=>de.includes(i),_e=i=>pe.includes(i),ke=["full","1/2","1/3","2/3","1/4","3/4"],ot=/^[A-Za-z_][A-Za-z0-9_.\-[\]]{0,63}$/,Dt=/^[A-Za-z_:][A-Za-z0-9_:.-]*$/,Ut=new Set(["id","name","type","value","for","form","formaction","srcdoc","action","method"]);function G(i){const e=String(i||"").normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").slice(0,64);return e?/^[a-z_]/.test(e)?e:`f_${e}`.slice(0,64):""}function Q(i,e){if(!e.has(i))return i;let t=2;for(;e.has(`${i}_${t}`.slice(0,64));)t++;return`${i}_${t}`.slice(0,64)}function xe(i,e=Ut){if(!i||typeof i!="object"||Array.isArray(i))return;const t={};return Object.entries(i).forEach(([s,a])=>{const n=String(s).trim();if(!Dt.test(n)||/^on/i.test(n)||e.has(n.toLowerCase())||a==null||typeof a=="object")return;const l=String(a);/^\s*(javascript|vbscript|data:text\/html)/i.test(l)||(t[n]=l)}),Object.keys(t).length?t:void 0}let Ht=0;const K=()=>`f${Date.now().toString(36)}${(Ht++).toString(36)}${Math.random().toString(36).slice(2,6)}`,re=i=>i==null||i===""?void 0:typeof i=="string"?i:typeof i=="number"||typeof i=="boolean"?String(i):void 0,Jt=i=>{const e=typeof i=="number"?i:typeof i=="string"&&i.trim()?Number(i):NaN;return Number.isInteger(e)&&e>=0?e:void 0};function lt(i){const e=typeof i=="string"?i.split(/\r?\n/):Array.isArray(i)?i:[],t=[],s=new Set;return e.forEach(a=>{let n,l;if(typeof a=="string"||typeof a=="number"){const o=String(a).trim(),u=o.indexOf("|");u>0?(l=o.slice(0,u).trim(),n=o.slice(u+1).trim()):l=n=o}else a&&typeof a=="object"&&(l=re(a.value??a.label??a.text),n=re(a.label??a.text??a.value));l==null||l===""||s.has(l)||(s.add(l),t.push({label:n||l,value:l}))}),t}function ct(i){if(!i||typeof i!="object")return null;const e=at.includes(i.type)?i.type:"text",t={id:typeof i.id=="string"&&i.id?i.id:K(),type:e,name:""};N(e)||(t.name=typeof i.name=="string"&&ot.test(i.name)?i.name:G(i.name||i.label||"")||e);const s=n=>{const l=re(i[n]);l!==void 0&&(t[n]=l)};["label","placeholder","help","value","min","max","step","pattern","accept","autocomplete","text"].forEach(s),["required","multiple","readonly","disabled"].forEach(n=>{i[n]===!0&&(t[n]=!0)}),["minLength","maxLength","rows"].forEach(n=>{const l=Jt(i[n]);l!==void 0&&(t[n]=l)}),ke.includes(i.width)&&i.width!=="full"&&(t.width=i.width),_e(e)&&(t.options=lt(i.options));const a=xe(i.attrs);return a&&(t.attrs=a),e==="hidden"&&(delete t.required,delete t.placeholder,delete t.width),N(e)&&(["required","placeholder","value","help"].forEach(n=>delete t[n]),t.text===void 0&&t.label&&(t.text=t.label),delete t.label),t}function dt(i){const e=[],t=new Set,s=new Set;return(Array.isArray(i)?i:[]).forEach(a=>{const n=ct(a);n&&(s.has(n.id)&&(n.id=K()),s.add(n.id),N(n.type)||(n.name=Q(n.name,t),t.add(n.name)),e.push(n))}),e}function pt(i){const e=i&&typeof i=="object"?i:{},t={};return["endpoint","successMessage","errorMessage","redirect","submitLabel"].forEach(s=>{const a=re(e[s]);a!==void 0&&a.trim()&&(t[s]=a.trim())}),t.endpoint&&!Ce(t.endpoint)&&delete t.endpoint,t.redirect&&!Ce(t.redirect)&&delete t.redirect,e.reset===!1&&(t.reset=!1),e.honeypot===!1&&(t.honeypot=!1),t}const Ce=i=>/^(https?:\/\/|\/|\.{0,2}\/|\?|#)/i.test(i.trim())||!/^[a-z][a-z0-9+.-]*:/i.test(i.trim());function q(i){const e=i&&typeof i=="object"?i:{},t={id:re(e.id)||"",name:(re(e.name)||"").trim()||"Form",fields:dt(e.fields),settings:pt(e.settings)},s=xe(e.attrs);return s&&(t.attrs=s),e.version!==void 0&&e.version!==null&&(t.version=e.version),typeof e.updatedAt=="string"&&(t.updatedAt=e.updatedAt),t}const Ae=i=>i.fields.filter(e=>!N(e.type)),Fe=i=>i.label||i.text||i.name||i.type,je="_gjsf_hp",zt=/^[^\s@<>()[\],;:"]+@[^\s@<>()[\],;:"]+\.[^\s@<>()[\],;:"]{2,}$/,Bt=/^\d{4}-\d{2}-\d{2}$/,Vt=/^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/,qt=/^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/,Yt=/^#[0-9a-f]{6}$/i,ut=i=>i==null||i===""||Array.isArray(i)&&i.length===0||i===!1,Kt=i=>i==null||i===""?[]:Array.isArray(i)?i.map(e=>String(e)).filter(e=>e!==""):String(i).split(",").map(e=>e.trim()).filter(Boolean),Wt=i=>i===!0||i===1||typeof i=="string"&&/^(1|true|on|yes)$/i.test(i.trim());function mt(i,e={}){const t=[],s={},a=(o,u)=>void t.push({field:o,code:u}),n=!!e&&typeof e[je]=="string"&&e[je].trim()!=="";Ae(i).forEach(o=>{const u=e==null?void 0:e[o.name];if(o.type==="checkbox"){const h=Wt(u);o.required&&!h&&a(o.name,"required"),s[o.name]=h;return}if(o.type==="checkboxes"||o.type==="select"&&o.multiple){const h=Kt(u);if(!h.length){o.required&&a(o.name,"required"),s[o.name]=[];return}const v=new Set((o.options||[]).map(p=>p.value));v.size&&h.some(p=>!v.has(p))&&a(o.name,"option"),s[o.name]=h;return}if(o.type==="file"){if(ut(u)){o.required&&a(o.name,"required");return}s[o.name]=u;return}const r=ut(u)?"":Array.isArray(u)?String(u[0]??""):String(u),d=o.type==="textarea"||o.type==="password"?r:r.trim();if(!d){o.required&&a(o.name,"required"),s[o.name]=o.type==="number"||o.type==="range"?null:"";return}if(ve.includes(o.type)&&(o.minLength!=null&&d.length<o.minLength&&a(o.name,"minLength"),o.maxLength!=null&&d.length>o.maxLength&&a(o.name,"maxLength")),o.type==="email"&&!zt.test(d)&&a(o.name,"email"),o.type==="url"&&!/^https?:\/\/[^\s]+\.[^\s]+/i.test(d)&&a(o.name,"url"),o.type==="color"&&!Yt.test(d)&&a(o.name,"color"),o.pattern&&ve.includes(o.type))try{new RegExp(`^(?:${o.pattern})$`,"u").test(d)||a(o.name,"pattern")}catch{}if(_e(o.type)){const h=new Set((o.options||[]).map(v=>v.value));h.size&&!h.has(d)&&a(o.name,"option")}if(o.type==="number"||o.type==="range"){const h=Number(d.replace(",","."));if(!Number.isFinite(h)){a(o.name,"number"),s[o.name]=d;return}o.min!=null&&o.min!==""&&h<Number(o.min)&&a(o.name,"min"),o.max!=null&&o.max!==""&&h>Number(o.max)&&a(o.name,"max"),s[o.name]=h;return}const y=o.type==="date"?Bt:o.type==="time"?Vt:o.type==="datetime"?qt:null;y&&(y.test(d)?(o.min&&d<o.min&&a(o.name,"min"),o.max&&d>o.max&&a(o.name,"max")):a(o.name,o.type==="time"?"time":"date")),s[o.name]=d});const l={};return t.forEach(o=>{var u;return(l[u=o.field]||(l[u]=[])).push(o.code)}),{ok:!t.length,problems:t,errors:l,data:s,spam:n}}const T={form:"gjsf-form",field:"gjsf-field",label:"gjsf-label",req:"gjsf-req",input:"gjsf-input",options:"gjsf-options",option:"gjsf-option",check:"gjsf-check",optionLabel:"gjsf-option-label",help:"gjsf-help",error:"gjsf-error",heading:"gjsf-heading",text:"gjsf-text",actions:"gjsf-actions",submit:"gjsf-submit",message:"gjsf-message",hp:"gjsf-hp"},ft={"1/2":"gjsf-w-1-2","1/3":"gjsf-w-1-3","2/3":"gjsf-w-2-3","1/4":"gjsf-w-1-4","3/4":"gjsf-w-3-4"},Gt={datetime:"datetime-local"};function Te(i){const e={...i.attrs||{}},t=(e.class||"").split(/\s+/).filter(Boolean);return delete e.class,{attrs:e,classes:t}}function Le(i,e={}){var n,l;const t=i.settings||{},s={...xe(i.attrs)||{}};delete s.class,Object.assign(s,{"data-gjsf-form":i.id,method:"post","data-gjsf-success":t.successMessage||((n=e.texts)==null?void 0:n.success)||"","data-gjsf-error":t.errorMessage||((l=e.texts)==null?void 0:l.error)||""});const a=t.endpoint||e.action||"";return a&&(s.action=a),i.version!=null&&(s["data-gjsf-version"]=String(i.version)),t.redirect&&(s["data-gjsf-redirect"]=t.redirect),t.reset===!1&&(s["data-gjsf-reset"]="false"),Ae(i).some(o=>o.type==="file")&&(s.enctype="multipart/form-data"),e.codes&&Object.keys(e.codes).length&&(s["data-gjsf-codes"]=JSON.stringify(e.codes)),e.pageId&&(s["data-gjsf-page"]=e.pageId),s}function Oe(i,e={}){var l,o,u;const t={form:{id:i.id,name:i.name},...e.ctx||{}},s=(e.key||i.id.slice(0,8)).replace(/[^\w-]/g,""),a=(r,d)=>`gjsf-${s}-${r.name.replace(/[^\w-]/g,"_")}${d==null?"":`-${d}`}`,n=[];return i.fields.forEach(r=>{if(N(r.type)){const{attrs:_,classes:x}=Te(r);n.push(r.type==="heading"?{tag:"h3",part:"heading",classes:[T.heading,...x],attrs:_,kids:[r.text||""]}:{tag:"p",part:"text",classes:[T.text,...x],attrs:_,kids:[r.text||""]});return}let d=st(r.value||"",t);const y=it(d)?d:"";if(y&&(d=""),r.type==="hidden"){const{attrs:_}=Te(r);n.push({tag:"input",void:!0,part:"hidden",attrs:{..._,type:"hidden",name:r.name,value:d,...y?{"data-gjsf-value":y}:{}}});return}const{attrs:h,classes:v}=Te(r),p=a(r),k=[T.field,`${T.field}--${r.type}`,...r.width&&ft[r.width]?[ft[r.width]]:[],...r.required?["is-required"]:[]],O=[r.label||r.name];r.required&&O.push({tag:"span",part:"req",classes:[T.req],attrs:{"aria-hidden":"true"},kids:["*"]});const D=r.help?{tag:"div",part:"help",classes:[T.help],attrs:{id:`${p}-help`},kids:[r.help]}:null,W={tag:"div",part:"error",classes:[T.error],attrs:{"data-gjsf-error-for":r.name,"aria-live":"polite"}},H={};if(r.required&&(H.required=""),r.readonly&&(H.readonly=""),r.disabled&&(H.disabled=""),r.help&&(H["aria-describedby"]=`${p}-help`),y&&(H["data-gjsf-value"]=y),r.type==="radio"||r.type==="checkboxes"){const _=r.type==="checkboxes",x=new Set(d.split(",").map(S=>S.trim()).filter(Boolean)),j=(r.options||[]).map((S,w)=>({tag:"label",part:"option",classes:[T.option],kids:[{tag:"input",void:!0,part:"check",classes:[T.check,...v],attrs:{...h,type:_?"checkbox":"radio",name:r.name,value:S.value,id:a(r,w),...x.has(S.value)?{checked:""}:{},...r.required&&(!_&&w===0)?{required:""}:{},...r.disabled?{disabled:""}:{},...y?{"data-gjsf-value":y}:{}}},{tag:"span",part:"option-label",classes:[T.optionLabel],kids:[S.label]}]}));n.push({tag:"fieldset",part:"field",classes:k,attrs:{"data-gjsf-field":r.name,..._&&r.required?{"data-gjsf-required":""}:{},...r.help?{"aria-describedby":`${p}-help`}:{}},kids:[{tag:"legend",part:"label",classes:[T.label],kids:O},{tag:"div",part:"options",classes:[T.options],kids:j},...D?[D]:[],W]});return}if(r.type==="checkbox"){n.push({tag:"div",part:"field",classes:k,attrs:{"data-gjsf-field":r.name},kids:[{tag:"label",part:"option",classes:[T.option],kids:[{tag:"input",void:!0,part:"check",classes:[T.check,...v],attrs:{...h,...H,type:"checkbox",name:r.name,value:"1",id:p,.../^(1|true|on|yes)$/i.test(d)?{checked:""}:{}}},{tag:"span",part:"option-label",classes:[T.optionLabel],kids:O}]},...D?[D]:[],W]});return}let B;if(r.type==="textarea")B={tag:"textarea",part:"input",classes:[T.input,...v],attrs:{...h,...H,name:r.name,id:p,...r.placeholder?{placeholder:r.placeholder}:{},...r.rows?{rows:String(r.rows)}:{},...r.minLength!=null?{minlength:String(r.minLength)}:{},...r.maxLength!=null?{maxlength:String(r.maxLength)}:{},...r.autocomplete?{autocomplete:r.autocomplete}:{}},kids:d?[d]:[]};else if(r.type==="select"){const _=new Set(d.split(",").map(j=>j.trim()).filter(Boolean)),x=[];r.multiple||x.push({tag:"option",part:"choice",attrs:{value:"",..._.size?{}:{selected:""},...r.required?{disabled:""}:{}},kids:[r.placeholder||"—"]}),(r.options||[]).forEach(j=>x.push({tag:"option",part:"choice",attrs:{value:j.value,..._.has(j.value)?{selected:""}:{}},kids:[j.label]})),B={tag:"select",part:"input",classes:[T.input,...v],attrs:{...h,...H,name:r.name,id:p,...r.multiple?{multiple:""}:{},...r.autocomplete?{autocomplete:r.autocomplete}:{}},kids:x}}else{const _={...h,...H,type:Gt[r.type]||r.type,name:r.name,id:p};r.placeholder&&!["range","color","file","date","time","datetime"].includes(r.type)&&(_.placeholder=r.placeholder),d&&r.type!=="file"&&r.type!=="password"&&(_.value=d),r.min&&(_.min=r.min),r.max&&(_.max=r.max),r.step&&(_.step=r.step),r.minLength!=null&&(_.minlength=String(r.minLength)),r.maxLength!=null&&(_.maxlength=String(r.maxLength)),r.pattern&&(_.pattern=r.pattern),r.accept&&r.type==="file"&&(_.accept=r.accept),r.multiple&&r.type==="file"&&(_.multiple=""),r.autocomplete&&(_.autocomplete=r.autocomplete),B={tag:"input",void:!0,part:"input",classes:[T.input,...v],attrs:_}}n.push({tag:"div",part:"field",classes:k,attrs:{"data-gjsf-field":r.name},kids:[{tag:"label",part:"label",classes:[T.label],attrs:{for:p},kids:O},B,...D?[D]:[],W]})}),((l=i.settings)==null?void 0:l.honeypot)!==!1&&n.push({tag:"div",part:"hp",classes:[T.hp],attrs:{"aria-hidden":"true"},style:{position:"absolute",left:"-10000px",width:"1px",height:"1px",overflow:"hidden"},kids:[{tag:"input",void:!0,part:"hp-input",attrs:{type:"text",name:je,tabindex:"-1",autocomplete:"off",value:""}}]}),n.push({tag:"div",part:"actions",classes:[T.actions],kids:[{tag:"button",part:"submit",classes:[T.submit],attrs:{type:"submit"},kids:[((o=i.settings)==null?void 0:o.submitLabel)||((u=e.texts)==null?void 0:u.submit)||"Send"]}]}),n.push({tag:"div",part:"message",classes:[T.message],attrs:{role:"status","aria-live":"polite"}}),n}const Zt=i=>i.replace(/[&<>]/g,e=>({"&":"&","<":"<",">":">"})[e]),Xt=i=>i.replace(/[&<>"]/g,e=>({"&":"&","<":"<",">":">",'"':"""})[e]),ht=(i,e)=>{var s;const t={...(s=i.classes)!=null&&s.length?{class:i.classes.join(" ")}:{},...i.attrs||{}};return e&&(t["data-gjsf-part"]=e),i.style&&(t.style=Object.entries(i.style).map(([a,n])=>`${a}:${n}`).join(";")),Object.entries(t).map(([a,n])=>n===""&&!["value","action"].includes(a)?` ${a}`:` ${a}="${Xt(n)}"`).join("")};function Ne(i){if(typeof i=="string")return Zt(i);const e=`<${i.tag}${ht(i,i.part)}>`;return i.void?e:`${e}${(i.kids||[]).map(Ne).join("")}</${i.tag}>`}function $e(i,e={}){var s;const t=[T.form,...(((s=i.attrs)==null?void 0:s.class)||"").split(/\s+/).filter(Boolean),...e.classes||[]];return`<form${ht({classes:t,attrs:Le(i,e)})}>${Oe(i,e).map(Ne).join("")}</form>`}const gt=Symbol.for("grapesjs.plugin-controls"),Qt="plugin:options";function es(i,e){i.meta=e;try{const t=globalThis.grapesjs;t!=null&&t.plugins&&!t.plugins.get(e.id)&&t.plugins.add(e.id,i)}catch{}return i}function ts(i){const e=i;let t=e[gt];return t||(t=new Map,Object.defineProperty(e,gt,{value:t,configurable:!0})),t}function ss(i,e,t,s){const a=new Set((e.options||[]).filter(o=>o.live).map(o=>o.key)),n={meta:e,getOptions:()=>t(),setOptions(o){var d;const u={applied:[],reload:[]},r={};return Object.keys(o||{}).forEach(y=>{a.has(y)?(r[y]=o[y],u.applied.push(y)):u.reload.push(y)}),u.applied.length&&s(r),(d=i.trigger)==null||d.call(i,Qt,{id:e.id,patch:o,result:u}),u}},l=ts(i);return l.set(e.id,n),()=>{l.get(e.id)===n&&l.delete(e.id)}}function we(i){const e=this;if(!e||e.__gjsf||e.tagName!=="FORM")return;e.__gjsf=!0;const t=e.ownerDocument,s=t.defaultView||window,a=s.location,n=x=>Array.prototype.slice.call(e.querySelectorAll(x)),l=x=>e.getAttribute(x)||"";let o={};try{o=JSON.parse(l("data-gjsf-codes")||"{}")||{}}catch{o={}}const u=x=>(x<10?"0":"")+x,r=x=>{const j=(t.cookie||"").split(";");for(let S=0;S<j.length;S++){const w=j[S].trim(),M=w.indexOf("=");if(M>0&&decodeURIComponent(w.slice(0,M))===x)return decodeURIComponent(w.slice(M+1))}return""},d=()=>{const x=s.crypto;if(x&&typeof x.randomUUID=="function")try{return x.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,j=>{const S=Math.random()*16|0;return(j==="x"?S:S&3|8).toString(16)})},y=x=>String(x||"").replace(/\{\{\s*([A-Za-z_][\w.-]*)\s*\}\}/g,(j,S)=>{const w=S.indexOf("."),M=w<0?S:S.slice(0,w),L=w<0?"":S.slice(w+1),R=new Date;let J=null;try{J=new URLSearchParams(a.search)}catch{J=null}switch(M){case"url":return a.href;case"path":return a.pathname;case"host":return a.host;case"referrer":return t.referrer||"";case"title":return t.title||"";case"lang":return t.documentElement.lang||s.navigator&&s.navigator.language||"";case"query":return J&&J.get(L)||"";case"cookie":return r(L);case"storage":try{return s.localStorage.getItem(L)||""}catch{return""}case"date":return R.getFullYear()+"-"+u(R.getMonth()+1)+"-"+u(R.getDate());case"time":return u(R.getHours())+":"+u(R.getMinutes());case"datetime":return R.toISOString();case"timestamp":return String(R.getTime());case"uuid":return d();case"page":return L==="url"?a.href:L==="path"||L==="slug"?a.pathname:(L==="name"||L==="title")&&t.title||"";default:return""}}),h=x=>{n("[data-gjsf-value]").forEach(j=>{const S=y(j.getAttribute("data-gjsf-value")||""),w=(j.getAttribute("type")||"").toLowerCase();if(w==="hidden")j.value=S;else{if(x)return;if(w==="checkbox"||w==="radio"){const M=S.split(",").map(L=>L.trim());j.checked=j.value==="1"&&w==="checkbox"?/^(1|true|on|yes)$/i.test(S):M.indexOf(j.value)>=0}else if(j.tagName==="SELECT"){const M=S.split(",").map(L=>L.trim());Array.prototype.forEach.call(j.options,L=>L.selected=M.indexOf(L.value)>=0)}else j.value||(j.value=S)}})};h(!1);const v=e.querySelector(".gjsf-message"),p=n('[type="submit"]'),k=(x,j)=>{e.classList.remove("is-sending","is-success","is-error"),x&&e.classList.add("is-"+x),e.setAttribute("aria-busy",x==="sending"?"true":"false"),p.forEach(S=>S.disabled=x==="sending"),v&&(v.textContent=j||"",j?v.removeAttribute("hidden"):v.setAttribute("hidden",""))},O=x=>x.replace(/["\\]/g,"\\$&"),D=x=>e.querySelector('[data-gjsf-field="'+O(x)+'"]'),W=x=>{const j=D(x);j&&j.classList.remove("has-error");const S=e.querySelector('[data-gjsf-error-for="'+O(x)+'"]');S&&(S.textContent=""),n('[name="'+O(x)+'"]').forEach(w=>w.removeAttribute("aria-invalid"))},H=()=>{n("[data-gjsf-field]").forEach(x=>W(x.getAttribute("data-gjsf-field")||""))},B=x=>{let j=null,S=!1;return Object.keys(x||{}).forEach(w=>{const M=[].concat(x[w]).map(J=>o[J]||J),L=D(w),R=e.querySelector('[data-gjsf-error-for="'+O(w)+'"]');!L&&!R||(S=!0,L&&L.classList.add("has-error"),R&&(R.textContent=M.join(" ")),n('[name="'+O(w)+'"]').forEach(J=>{J.setAttribute("aria-invalid","true"),j||(j=J)}))}),j&&j.focus(),S};e.addEventListener("input",x=>{const j=x.target;j&&j.name&&W(j.name)}),e.addEventListener("change",x=>{const j=x.target;j&&j.name&&W(j.name)});const _=(x,j,S)=>{const w=new(s.CustomEvent||CustomEvent)(x,{bubbles:!0,cancelable:!!S,detail:j});return e.dispatchEvent(w),w};e.addEventListener("submit",x=>{if(x.preventDefault(),e.classList.contains("is-sending"))return;H(),h(!0);const j={};if(n("[data-gjsf-required]").forEach(E=>{const A=E.getAttribute("data-gjsf-field")||"";E.querySelector("input:checked")||(j[A]=["required"])}),typeof e.checkValidity=="function"&&!e.checkValidity()){typeof e.reportValidity=="function"&&e.reportValidity();return}if(Object.keys(j).length){B(j);return}const S=new FormData(e),w={};let M=!1;S.forEach((E,A)=>{if(typeof E!="string"){if(!E.name&&!E.size)return;M=!0}A in w?w[A]=[].concat(w[A],E):w[A]=E}),n("[data-gjsf-field]").forEach(E=>{const A=E.getAttribute("data-gjsf-field")||"",ie=E.classList;ie.contains("gjsf-field--checkboxes")||E.querySelector("select[multiple]")?w[A]=A in w?[].concat(w[A]):[]:ie.contains("gjsf-field--checkbox")&&(w[A]=A in w)});const L={url:a.href,referrer:t.referrer||"",lang:t.documentElement.lang||""};l("data-gjsf-page")&&(L.page_id=l("data-gjsf-page"));const R=l("data-gjsf-form"),J=E=>{_("gjsf:success",{formId:R,data:w,response:E});const A=E&&E.redirect||l("data-gjsf-redirect");if(A){k("success",""),a.assign(A);return}l("data-gjsf-reset")!=="false"&&(e.reset(),h(!1)),k("success",E&&E.message||l("data-gjsf-success"))},te=(E,A)=>{A&&A.errors&&B(A.errors),_("gjsf:error",{formId:R,data:w,status:E,response:A}),k("error",A&&(A.error||A.message)||l("data-gjsf-error"))},X={formId:R,data:w,meta:L,formData:S,promise:null},se=_("gjsf:submit",X,!0);k("sending");let V;if(X.promise)V=Promise.resolve(X.promise);else if(se.defaultPrevented){k("");return}else{const E=e.getAttribute("action");if(!E){te(0,{});return}let A;const ie={Accept:"application/json"};M?(S.append("_meta",JSON.stringify(L)),A=S):(ie["Content-Type"]="application/json",A=JSON.stringify({data:w,meta:L})),V=s.fetch(E,{method:"POST",headers:ie,body:A,credentials:"same-origin"}).then(ce=>ce.text().then(he=>{let ne={};try{ne=he?JSON.parse(he):{}}catch{ne={}}if(!ce.ok)throw{status:ce.status,body:ne};return ne}))}V.then(E=>J(E||{}),E=>te(E&&E.status||0,E&&(E.body||(E.errors?E:null))||{}))})}const Y="gjsf-form",Se="gjsf-part",ue="data-gjsf-form",Ie="data-gjsf-part",bt={removable:!1,draggable:!1,copyable:!1,droppable:!1,editable:!1,stylable:!0,selectable:!0,hoverable:!0,layerable:!0},is=["action","method","enctype","data-gjsf-success","data-gjsf-error","data-gjsf-redirect","data-gjsf-reset","data-gjsf-version","data-gjsf-codes","data-gjsf-page","data-gjsf-missing"];function Re(i){return typeof i=="string"?{type:"textnode",content:i}:{type:Se,tagName:i.tag,attributes:{...i.attrs||{},[Ie]:i.part},classes:i.classes||[],void:!!i.void,components:(i.kids||[]).map(Re),...bt}}const yt=()=>Math.random().toString(36).slice(2,7),ns=`.${T.hp}{position:absolute!important;left:-10000px!important;width:1px;height:1px;overflow:hidden}`,as=`
|
|
2
|
+
form.${T.form}:empty{min-height:64px;outline:1px dashed rgba(127,127,127,.6);display:flex;align-items:center;justify-content:center}
|
|
3
|
+
form.${T.form}:empty::before{content:attr(data-gjsf-placeholder);opacity:.6;font:13px/1.3 sans-serif}
|
|
4
|
+
form.${T.form}[data-gjsf-missing]{outline:1px dashed #e57373}
|
|
5
|
+
`;class vt{constructor(e,t){$(this,"offs",[]);this.editor=e,this.host=t;const s=e.DomComponents,a=this;s.addType(Se,{isComponent:r=>{var d;return(d=r==null?void 0:r.getAttribute)!=null&&d.call(r,Ie)?{type:Se}:!1},model:{defaults:{...bt}}}),s.addType(Y,{isComponent:r=>(r==null?void 0:r.tagName)==="FORM"&&r.hasAttribute(ue)?{type:Y,formId:r.getAttribute(ue)||""}:!1,model:{defaults:{tagName:"form",name:"Form",droppable:!1,classes:[T.form],formId:"",gjsfKey:"",script:we,"script-props":["formId"],traits:[]},init(){this.get("gjsfKey")||this.set("gjsfKey",yt()),this.set("traits",a.traits()),this.on("change:formId",()=>a.rebuild(this))}},view:{events:{dblclick:"onEdit",submit:"onSubmit"},onEdit(r){var d;(d=r==null?void 0:r.stopPropagation)==null||d.call(r),e.runCommand(t.editCommand,{component:this.model})},onSubmit(r){r.preventDefault()}}});const n=r=>{if(!(!r||r.__gjsfGuard)&&(r.__gjsfGuard=!0,r.addEventListener("submit",d=>{d.preventDefault(),d.stopPropagation()},!0),!r.getElementById("gjsf-canvas-style"))){const d=r.createElement("style");d.id="gjsf-canvas-style",d.textContent=as,(r.head||r.documentElement).appendChild(d)}},l=r=>{var d,y,h,v;return n(((d=r==null?void 0:r.window)==null?void 0:d.document)||((v=(h=(y=r==null?void 0:r.frame)==null?void 0:y.view)==null?void 0:h.getDoc)==null?void 0:v.call(h))||e.Canvas.getDocument())};e.on("canvas:frame:load",l),this.offs.push(()=>e.off("canvas:frame:load",l)),e.onReady(()=>{try{n(e.Canvas.getDocument())}catch{}});const o=r=>{var d;((d=r==null?void 0:r.get)==null?void 0:d.call(r,"type"))===Y&&(r.get("gjsfCreate")?(r.unset("gjsfCreate"),t.onCreate(r)):r.get("formId")&&!r.components().length&&this.rebuild(r),this.ensureCss())};e.on("component:add",o),this.offs.push(()=>e.off("component:add",o));const u=r=>{var d;((d=r==null?void 0:r.get)==null?void 0:d.call(r,"type"))===Y&&this.refreshTraits(r)};e.on("component:selected",u),this.offs.push(()=>e.off("component:selected",u))}traits(){return[{type:"select",name:"formId",label:this.host.labels.chooseForm(),changeProp:!0,options:this.selectOptions()},{type:"button",name:"gjsf-edit",label:!1,text:this.host.labels.editForm(),full:!0,command:this.host.editCommand}]}selectOptions(){return[{id:"",name:this.host.labels.noForm()},...this.host.formOptions()]}refreshTraits(e){var n,l,o,u;const t=(n=e.getTrait)==null?void 0:n.call(e,"formId");t?(t.set("options",this.selectOptions()),t.set("label",this.host.labels.chooseForm())):e.set("traits",this.traits());const s=(l=e.getTrait)==null?void 0:l.call(e,"gjsf-edit");if(s==null||s.set("text",this.host.labels.editForm()),this.editor.getSelected()===e)try{(u=(o=this.editor.TraitManager)==null?void 0:o.render)==null||u.call(o)}catch{}}all(){const e=[],t=a=>{a.get("type")===Y&&e.push(a),a.components().forEach(t)},s=this.editor.getWrapper();return s&&t(s),e}ensureCss(){const e=this.editor.Css;e.getRule(`.${T.hp}`)||e.addRules(ns)}rebuild(e){const t=String(e.get("formId")||""),s=this.host.form(t),a={"data-gjsf-placeholder":this.host.labels.noForm()},n=()=>{var h;const o={...e.getAttributes()},u=e.get("gjsfOwnAttrs")||[];if([...is,...u].forEach(v=>delete o[v]),!t){delete o[ue],e.setAttributes({...o,...a}),e.components().reset();return}if(!s){e.setAttributes({...o,[ue]:t,"data-gjsf-missing":"","data-gjsf-placeholder":this.host.labels.missingForm()});return}const r=this.host.buildOptions(s,e),d=Le(s,r);delete o["data-gjsf-placeholder"];const y=Object.keys(s.attrs||{}).filter(v=>v!=="class");e.set("gjsfOwnAttrs",y),e.setAttributes({...o,...d,...a}),(((h=s.attrs)==null?void 0:h.class)||"").split(/\s+/).filter(Boolean).forEach(v=>e.addClass(v)),e.components().reset(),e.components().add(Oe(s,{...r,key:e.get("gjsfKey")||yt()}).map(Re)),this.ensureCss()},l=this.editor.UndoManager;l!=null&&l.skip?l.skip(n):n()}rebuildAll(e,t){let s=0;return this.all().forEach(a=>{const n=String(a.get("formId")||"");if(e&&n!==e)return;const l=this.host.form(n);t&&l&&!t(a,l)||t&&!l&&!n||(this.rebuild(a),s++)}),s}destroy(){this.offs.splice(0).forEach(e=>e())}}const oe={forms:"forms:list",saved:"forms:saved",removed:"forms:removed",submitted:"forms:submitted"},me={open:"forms:open",edit:"forms:edit"},rs={submit:"gjsf:submit",success:"gjsf:success",error:"gjsf:error"},xt={forms:"Forms",newForm:"New form",defaultFormName:"Form",noForms:"No forms yet.",formName:"Form name",fields:"Fields",settings:"Settings",preview:"Preview",submissions:"Submissions",json:"JSON",addField:"Add a field",noFields:"No fields yet: add one from the list on the left.",noFieldSelected:"Select a field to edit it.",fieldType:"Type",fieldLabel:"Label",fieldName:"Name (key)",fieldNameHint:"The key of the value in a submission.",placeholder:"Placeholder",help:"Help text",required:"Required",defaultValue:"Default value",hiddenValue:"Value sent",options:"Options",optionsHint:"Label and the value sent.",addOption:"Add an option",optionLabel:"Label",optionValue:"Value",multiple:"Several values",min:"Min",max:"Max",step:"Step",minLength:"Min length",maxLength:"Max length",pattern:"Pattern (regular expression)",accept:"File types",autocomplete:"Autocomplete",rows:"Rows",readonly:"Read only",disabled:"Disabled",width:"Width",attrs:"Attributes",addAttr:"Add an attribute",attrName:"Name",attrValue:"Value",text:"Text",type_text:"Text",type_email:"E-mail",type_tel:"Phone",type_url:"URL",type_number:"Number",type_password:"Password",type_textarea:"Long text",type_select:"Dropdown",type_radio:"Radio buttons",type_checkbox:"Checkbox",type_checkboxes:"Checkboxes",type_date:"Date",type_time:"Time",type_datetime:"Date and time",type_range:"Slider",type_color:"Colour",type_file:"File",type_hidden:"Hidden",type_heading:"Heading",type_paragraph:"Paragraph",moveUp:"Move up",moveDown:"Move down",duplicate:"Duplicate",remove:"Remove",endpoint:"Submit to (URL)",endpointHint:"Empty — %s",noEndpoint:"the site handles the gjsf:submit event",successMessage:"Message after sending",errorMessage:"Message on error",redirect:"Redirect after sending (URL)",reset:"Clear the form after sending",honeypot:"Spam trap (hidden field for bots)",submitLabel:"Button text",formAttrs:"Form attributes",submit:"Send",success:"Thank you! Your message has been sent.",error:"Could not send the form. Please try again.",problem_required:"Please fill in this field.",problem_email:"Please enter a valid e-mail address.",problem_url:"Please enter a valid URL.",problem_number:"Please enter a number.",problem_min:"The value is too small.",problem_max:"The value is too large.",problem_minLength:"The text is too short.",problem_maxLength:"The text is too long.",problem_pattern:"The value does not match the format.",problem_option:"Please choose one of the options.",problem_date:"Please enter a valid date.",problem_time:"Please enter a valid time.",problem_color:"Please choose a colour.",placeholders:"Placeholders",placeholdersHint:"{{form.*}} and {{page.*}} are filled when the page is built; the rest in the visitor’s browser.",noSubmissions:"No submissions yet.",submissionsUnsupported:"This backend does not list submissions.",date:"Date",refresh:"Refresh",downloadCsv:"Download CSV",loadMore:"Load more",shownOf:"%s of %s",confirmDeleteSubmission:"Delete this submission?",importSurveyJs:"Import SurveyJS JSON",exportSurveyJs:"Export as SurveyJS JSON",applyJson:"Apply",jsonHint:"The form as JSON. Paste a form of this plugin or a SurveyJS survey and press Apply.",jsonError:"Not valid JSON: %s",skipped:"Skipped (not plain form fields): %s",removeForm:"Delete the form",confirmRemoveForm:'Delete the form "%s" and its submissions? Pages that use it keep a copy.',duplicateForm:"Duplicate",copyOf:"%s (copy)",close:"Close",saving:"Saving…",saved:"Saved",saveError:"Not saved: %s",conflict:"The form was changed elsewhere (412). It was reloaded.",chooseForm:"Form",editForm:"Edit the form",noForm:"— choose a form —",blocksCategory:"Forms",newFormBlock:"New form",missingForm:"The form was deleted: this is a copy.",previewHint:"Styled by the open page. Sending here goes to the forms store.",previewSent:"Sent to the store.",defaultName:"Name",defaultEmail:"E-mail",defaultMessage:"Message"},os={forms:"Формы",newForm:"Новая форма",defaultFormName:"Форма",noForms:"Форм пока нет.",formName:"Название формы",fields:"Поля",settings:"Настройки",preview:"Просмотр",submissions:"Заявки",json:"JSON",addField:"Добавить поле",noFields:"Полей пока нет: добавьте из списка слева.",noFieldSelected:"Выберите поле, чтобы изменить его.",fieldType:"Тип",fieldLabel:"Подпись",fieldName:"Имя (ключ)",fieldNameHint:"Ключ значения в заявке.",placeholder:"Плейсхолдер",help:"Подсказка",required:"Обязательное",defaultValue:"Значение по умолчанию",hiddenValue:"Отправляемое значение",options:"Варианты",optionsHint:"Подпись и отправляемое значение.",addOption:"Добавить вариант",optionLabel:"Подпись",optionValue:"Значение",multiple:"Несколько значений",min:"Мин.",max:"Макс.",step:"Шаг",minLength:"Мин. длина",maxLength:"Макс. длина",pattern:"Шаблон (регулярное выражение)",accept:"Типы файлов",autocomplete:"Автозаполнение",rows:"Строк",readonly:"Только чтение",disabled:"Отключено",width:"Ширина",attrs:"Атрибуты",addAttr:"Добавить атрибут",attrName:"Имя",attrValue:"Значение",text:"Текст",type_text:"Текст",type_email:"E-mail",type_tel:"Телефон",type_url:"Ссылка",type_number:"Число",type_password:"Пароль",type_textarea:"Длинный текст",type_select:"Список",type_radio:"Переключатели",type_checkbox:"Флажок",type_checkboxes:"Флажки",type_date:"Дата",type_time:"Время",type_datetime:"Дата и время",type_range:"Ползунок",type_color:"Цвет",type_file:"Файл",type_hidden:"Скрытое",type_heading:"Заголовок",type_paragraph:"Абзац",moveUp:"Выше",moveDown:"Ниже",duplicate:"Копировать",remove:"Удалить",endpoint:"Куда отправлять (URL)",endpointHint:"Пусто — %s",noEndpoint:"отправку обрабатывает сайт (событие gjsf:submit)",successMessage:"Сообщение после отправки",errorMessage:"Сообщение об ошибке",redirect:"Перейти после отправки (URL)",reset:"Очищать форму после отправки",honeypot:"Ловушка для спама (скрытое поле для ботов)",submitLabel:"Текст кнопки",formAttrs:"Атрибуты формы",submit:"Отправить",success:"Спасибо! Сообщение отправлено.",error:"Не удалось отправить форму. Попробуйте ещё раз.",problem_required:"Заполните это поле.",problem_email:"Введите правильный адрес e-mail.",problem_url:"Введите правильную ссылку.",problem_number:"Введите число.",problem_min:"Значение слишком маленькое.",problem_max:"Значение слишком большое.",problem_minLength:"Текст слишком короткий.",problem_maxLength:"Текст слишком длинный.",problem_pattern:"Значение не подходит под формат.",problem_option:"Выберите один из вариантов.",problem_date:"Введите правильную дату.",problem_time:"Введите правильное время.",problem_color:"Выберите цвет.",placeholders:"Плейсхолдеры",placeholdersHint:"{{form.*}} и {{page.*}} подставляются при сборке страницы, остальные — в браузере посетителя.",noSubmissions:"Заявок пока нет.",submissionsUnsupported:"Это хранилище не отдаёт список заявок.",date:"Дата",refresh:"Обновить",downloadCsv:"Скачать CSV",loadMore:"Ещё",shownOf:"%s из %s",confirmDeleteSubmission:"Удалить эту заявку?",importSurveyJs:"Импорт SurveyJS JSON",exportSurveyJs:"Экспорт в SurveyJS JSON",applyJson:"Применить",jsonHint:"Форма в виде JSON. Вставьте форму этого плагина или опрос SurveyJS и нажмите «Применить».",jsonError:"Неверный JSON: %s",skipped:"Пропущено (не поля обычной формы): %s",removeForm:"Удалить форму",confirmRemoveForm:"Удалить форму «%s» и её заявки? На страницах, где она стоит, останется копия.",duplicateForm:"Копировать",copyOf:"%s (копия)",close:"Закрыть",saving:"Сохранение…",saved:"Сохранено",saveError:"Не сохранено: %s",conflict:"Форму изменили в другом месте (412). Она перечитана.",chooseForm:"Форма",editForm:"Редактировать форму",noForm:"— выберите форму —",blocksCategory:"Формы",newFormBlock:"Новая форма",missingForm:"Форма удалена: это копия.",previewHint:"Со стилями открытой страницы. Отправка отсюда идёт в хранилище форм.",previewSent:"Отправлено в хранилище.",defaultName:"Имя",defaultEmail:"E-mail",defaultMessage:"Сообщение"},ls={forms:"Форми",newForm:"Нова форма",defaultFormName:"Форма",noForms:"Форм ще немає.",formName:"Назва форми",fields:"Поля",settings:"Налаштування",preview:"Перегляд",submissions:"Заявки",json:"JSON",addField:"Додати поле",noFields:"Полів ще немає: додайте зі списку ліворуч.",noFieldSelected:"Виберіть поле, щоб змінити його.",fieldType:"Тип",fieldLabel:"Підпис",fieldName:"Імʼя (ключ)",fieldNameHint:"Ключ значення в заявці.",placeholder:"Плейсхолдер",help:"Підказка",required:"Обовʼязкове",defaultValue:"Значення за замовчуванням",hiddenValue:"Значення, що надсилається",options:"Варіанти",optionsHint:"Підпис і значення, що надсилається.",addOption:"Додати варіант",optionLabel:"Підпис",optionValue:"Значення",multiple:"Кілька значень",min:"Мін.",max:"Макс.",step:"Крок",minLength:"Мін. довжина",maxLength:"Макс. довжина",pattern:"Шаблон (регулярний вираз)",accept:"Типи файлів",autocomplete:"Автозаповнення",rows:"Рядків",readonly:"Лише читання",disabled:"Вимкнено",width:"Ширина",attrs:"Атрибути",addAttr:"Додати атрибут",attrName:"Імʼя",attrValue:"Значення",text:"Текст",type_text:"Текст",type_email:"E-mail",type_tel:"Телефон",type_url:"Посилання",type_number:"Число",type_password:"Пароль",type_textarea:"Довгий текст",type_select:"Список",type_radio:"Перемикачі",type_checkbox:"Прапорець",type_checkboxes:"Прапорці",type_date:"Дата",type_time:"Час",type_datetime:"Дата й час",type_range:"Повзунок",type_color:"Колір",type_file:"Файл",type_hidden:"Приховане",type_heading:"Заголовок",type_paragraph:"Абзац",moveUp:"Вище",moveDown:"Нижче",duplicate:"Копіювати",remove:"Видалити",endpoint:"Куди надсилати (URL)",endpointHint:"Порожньо — %s",noEndpoint:"надсилання обробляє сайт (подія gjsf:submit)",successMessage:"Повідомлення після надсилання",errorMessage:"Повідомлення про помилку",redirect:"Перейти після надсилання (URL)",reset:"Очищати форму після надсилання",honeypot:"Пастка для спаму (приховане поле для ботів)",submitLabel:"Текст кнопки",formAttrs:"Атрибути форми",submit:"Надіслати",success:"Дякуємо! Повідомлення надіслано.",error:"Не вдалося надіслати форму. Спробуйте ще раз.",problem_required:"Заповніть це поле.",problem_email:"Введіть правильну адресу e-mail.",problem_url:"Введіть правильне посилання.",problem_number:"Введіть число.",problem_min:"Значення замале.",problem_max:"Значення завелике.",problem_minLength:"Текст закороткий.",problem_maxLength:"Текст задовгий.",problem_pattern:"Значення не відповідає формату.",problem_option:"Виберіть один із варіантів.",problem_date:"Введіть правильну дату.",problem_time:"Введіть правильний час.",problem_color:"Виберіть колір.",placeholders:"Плейсхолдери",placeholdersHint:"{{form.*}} і {{page.*}} підставляються під час збирання сторінки, решта — у браузері відвідувача.",noSubmissions:"Заявок ще немає.",submissionsUnsupported:"Це сховище не віддає список заявок.",date:"Дата",refresh:"Оновити",downloadCsv:"Завантажити CSV",loadMore:"Ще",shownOf:"%s з %s",confirmDeleteSubmission:"Видалити цю заявку?",importSurveyJs:"Імпорт SurveyJS JSON",exportSurveyJs:"Експорт у SurveyJS JSON",applyJson:"Застосувати",jsonHint:"Форма у вигляді JSON. Вставте форму цього плагіна або опитування SurveyJS і натисніть «Застосувати».",jsonError:"Неправильний JSON: %s",skipped:"Пропущено (не поля звичайної форми): %s",removeForm:"Видалити форму",confirmRemoveForm:"Видалити форму «%s» і її заявки? На сторінках, де вона стоїть, залишиться копія.",duplicateForm:"Копіювати",copyOf:"%s (копія)",close:"Закрити",saving:"Збереження…",saved:"Збережено",saveError:"Не збережено: %s",conflict:"Форму змінили в іншому місці (412). Її перечитано.",chooseForm:"Форма",editForm:"Редагувати форму",noForm:"— виберіть форму —",blocksCategory:"Форми",newFormBlock:"Нова форма",missingForm:"Форму видалено: це копія.",previewHint:"Зі стилями відкритої сторінки. Надсилання звідси йде до сховища форм.",previewSent:"Надіслано до сховища.",defaultName:"Імʼя",defaultEmail:"E-mail",defaultMessage:"Повідомлення"},Me="gjsForms",Pe={en:xt,ru:os,uk:ls},jt=Object.keys(Pe);function cs(i){const e=i.I18n;if(!e||typeof e.addMessages!="function")return;const t={};jt.forEach(s=>{t[s]={[Me]:{...Pe[s]}}}),e.addMessages(t)}function ds(i,e={}){return t=>{var n;const s=e[t];if(typeof s=="string"&&s)return s;let a;try{a=(n=i.I18n)==null?void 0:n.t(`${Me}.${t}`,{params:{form:"{form}",page:"{page}"}})}catch{a=void 0}return typeof a=="string"&&a?a:xt[t]}}const ee=(i,...e)=>e.reduce((t,s)=>t.replace("%s",String(s)),i),I=i=>i===void 0?i:JSON.parse(JSON.stringify(i)),De=()=>{const i=typeof globalThis<"u"?globalThis.crypto:void 0;if(i&&typeof i.randomUUID=="function")try{return i.randomUUID()}catch{}const e=new Uint8Array(16);if(i&&typeof i.getRandomValues=="function")i.getRandomValues(e);else for(let s=0;s<16;s++)e[s]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(s=>s.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`},wt=i=>{console.error("[grapesjs-forms]",i)};class Ee extends Error{constructor(t="The form was changed elsewhere (412)"){super(t);$(this,"status",412);this.name="ConflictError"}}class Z extends Error{constructor(e,t,s={}){super(e),this.status=t,this.errors=s,this.name="StoreError"}}class Ue{constructor(){$(this,"forms",new Map);$(this,"submissions",new Map)}async changed(e,t){}async listForms(){return[...this.forms.values()].map(I)}async getForm(e){const t=this.forms.get(e);return t?I(t):void 0}async saveForm(e,t){if(!e.id)throw new Z("A form needs an id",422,{id:["required"]});const s=this.forms.get(e.id);if(t!=null&&s&&String(s.version)!==String(t))throw new Ee;const a=q({...e,version:(Number(s==null?void 0:s.version)||0)+1,updatedAt:new Date().toISOString()});return this.forms.set(a.id,a),await this.changed(`form:${a.id}`,a),I(a)}async deleteForm(e){if(this.forms.delete(e)){await this.changed(`form:${e}`,null);for(const[t,s]of[...this.submissions])s.formId===e&&(this.submissions.delete(t),await this.changed(`submission:${t}`,null))}}async submit(e,t,s){const a=this.forms.get(e);if(!a)throw new Z("No such form",404);const n=mt(a,t);if(n.spam)return{};if(!n.ok)throw new Z("The given data was invalid.",422,n.errors);const l=d=>typeof Blob<"u"&&d instanceof Blob,o=d=>l(d)?{name:d.name||"",size:d.size,type:d.type}:Array.isArray(d)?d.map(o):d,u=Object.fromEntries(Object.entries(n.data).map(([d,y])=>[d,o(y)])),r={id:De(),formId:e,data:u,createdAt:new Date().toISOString(),...s?{meta:I(s)}:{}};return this.submissions.set(r.id,r),await this.changed(`submission:${r.id}`,r),{id:r.id,createdAt:r.createdAt}}async listSubmissions(e,t={}){const s=[...this.submissions.values()].filter(l=>l.formId===e).sort((l,o)=>l.createdAt<o.createdAt?1:l.createdAt>o.createdAt?-1:0),a=Math.max(0,t.offset||0),n=Math.max(1,t.limit||50);return{items:s.slice(a,a+n).map(I),total:s.length}}async deleteSubmission(e,t){const s=this.submissions.get(t);!s||s.formId!==e||(this.submissions.delete(t),await this.changed(`submission:${t}`,null))}}const le="forms",ps=1;class He extends Ue{constructor(t="gjs-forms",s=typeof indexedDB<"u"?indexedDB:void 0){super();$(this,"dbp",null);$(this,"loaded",null);this.dbName=t,this.factory=s}open(){if(this.dbp)return this.dbp;const t=this.factory;return t?(this.dbp=new Promise((s,a)=>{const n=t.open(this.dbName,ps);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(le)||n.result.createObjectStore(le,{keyPath:"key"})},n.onsuccess=()=>{const l=n.result;l.onversionchange=()=>{l.close(),this.dbp=null},s(l)},n.onerror=()=>a(n.error)}),this.dbp.catch(()=>this.dbp=null),this.dbp):Promise.reject(new Error("IndexedDB is not available"))}load(){return this.loaded||(this.loaded=this.open().then(t=>new Promise((s,a)=>{const n=t.transaction(le,"readonly").objectStore(le).getAll();n.onsuccess=()=>{n.result.forEach(({key:l,value:o})=>{l.startsWith("form:")?this.forms.set(l.slice(5),o):l.startsWith("submission:")&&this.submissions.set(l.slice(11),o)}),s()},n.onerror=()=>a(n.error)})),this.loaded.catch(()=>this.loaded=null)),this.loaded}async changed(t,s){const a=await this.open();await new Promise((n,l)=>{const o=a.transaction(le,"readwrite"),u=o.objectStore(le);s===null?u.delete(t):u.put({key:t,value:s}),o.oncomplete=()=>n(),o.onerror=()=>l(o.error)})}close(){var t;(t=this.dbp)==null||t.then(s=>s.close()),this.dbp=null,this.loaded=null}}for(const i of["listForms","getForm","saveForm","deleteForm","submit","listSubmissions","deleteSubmission"]){const e=Ue.prototype[i];He.prototype[i]=async function(...t){return await this.load(),e.apply(this,t)}}const Je=i=>q({...i,updatedAt:i.updated_at}),us=i=>{if(!i)return;const{page_id:e,...t}=i;return{...t,...e!=null?{pageId:String(e)}:{}}},St=i=>{if(!i)return;const{pageId:e,...t}=i;return{...t,...e!=null?{page_id:e}:{}}},ms=i=>({id:i.id,formId:i.form_id,data:i.data||{},createdAt:i.created_at,...i.meta?{meta:us(i.meta)}:{}}),Et=i=>typeof Blob<"u"&&i instanceof Blob||Array.isArray(i)&&i.some(Et),ze=(i,e)=>`${(i||"").trim().replace(/\/+$/,"")}/forms/${encodeURIComponent(e)}/submissions`;class _t{constructor(e){this.opts=e}get base(){return(this.opts.url||"").trim().replace(/\/+$/,"")}async request(e,t,{body:s,version:a,raw:n}={}){var d,y;const l={Accept:"application/json"};s!==void 0&&(l["Content-Type"]="application/json"),a!=null&&(l["If-Match"]=`"${a}"`),Object.assign(l,((y=(d=this.opts).headers)==null?void 0:y.call(d))||{});const u=await(this.opts.fetch||globalThis.fetch.bind(globalThis))(this.base+t,{method:e,headers:l,credentials:this.opts.credentials,body:n??(s!==void 0?JSON.stringify(s):void 0)});if(u.status===412)throw new Ee;if(!u.ok){let h=`${e} ${t}: HTTP ${u.status}`,v={};try{const p=await u.json();p!=null&&p.error?h=p.error:p!=null&&p.message&&(h=p.message),p!=null&&p.errors&&(v=p.errors)}catch{}throw new Z(h,u.status,v)}if(u.status===204)return null;const r=await u.text();return r?JSON.parse(r):null}async listForms(){const e=await this.request("GET","/forms");return((e==null?void 0:e.items)||[]).map(Je)}async getForm(e){try{return Je(await this.request("GET",`/forms/${encodeURIComponent(e)}`))}catch(t){if(t instanceof Z&&t.status===404)return;throw t}}async saveForm(e,t){const s={name:e.name,fields:e.fields,settings:e.settings};return e.attrs&&(s.attrs=e.attrs),Je(await this.request("PUT",`/forms/${encodeURIComponent(e.id)}`,{body:s,version:t}))}async deleteForm(e){try{await this.request("DELETE",`/forms/${encodeURIComponent(e)}`)}catch(t){if(!(t instanceof Z&&t.status===404))throw t}}async submit(e,t,s){const a=`/forms/${encodeURIComponent(e)}/submissions`;let n;if(Object.values(t).some(Et)){const l=new FormData;Object.entries(t).forEach(([o,u])=>(Array.isArray(u)?u:[u]).forEach(r=>r instanceof Blob?l.append(o,r):r!=null&&l.append(o,String(r)))),s&&l.append("_meta",JSON.stringify(St(s))),n=await this.request("POST",a,{raw:l})}else n=await this.request("POST",a,{body:{data:t,...s?{meta:St(s)}:{}}});return{...n!=null&&n.id?{id:n.id}:{},...n!=null&&n.created_at?{createdAt:n.created_at}:{},...n!=null&&n.message?{message:n.message}:{},...n!=null&&n.redirect?{redirect:n.redirect}:{}}}async listSubmissions(e,t={}){const s=new URLSearchParams;t.limit&&s.set("limit",String(t.limit)),t.offset&&s.set("offset",String(t.offset));const a=s.toString(),n=await this.request("GET",`/forms/${encodeURIComponent(e)}/submissions${a?`?${a}`:""}`),l=((n==null?void 0:n.items)||[]).map(ms);return{items:l,total:typeof(n==null?void 0:n.total)=="number"?n.total:l.length}}async deleteSubmission(e,t){try{await this.request("DELETE",`/forms/${encodeURIComponent(e)}/submissions/${encodeURIComponent(t)}`)}catch(s){if(!(s instanceof Z&&s.status===404))throw s}}}const z=i=>{if(i!=null){if(typeof i=="string")return i;if(typeof i=="object"){const e=i,t=e.default??e.en??Object.values(e)[0];return typeof t=="string"?t:void 0}return String(i)}},Be=i=>i==null?void 0:i.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()||void 0,fe=i=>(Array.isArray(i)?i:[]).map(e=>e&&typeof e=="object"?{value:String(e.value??z(e.text)??""),label:z(e.text)??String(e.value??"")}:{value:String(e),label:String(e)}),fs={text:"text",email:"email",tel:"tel",url:"url",number:"number",password:"password",date:"date",time:"time","datetime-local":"datetime",range:"range",color:"color"};function hs(i){const e=[],t=s=>(Array.isArray(s)?s:[]).forEach(a=>{if(!(!a||typeof a!="object"))if(a.type==="panel"||a.type==="flowpanel"){const n=z(a.title);n&&e.push({type:"html",html:n,__heading:!0}),t(a.elements||a.questions)}else e.push(a)});return Array.isArray(i.pages)&&i.pages.forEach(s=>t((s==null?void 0:s.elements)||(s==null?void 0:s.questions))),t(i.elements||i.questions),e}function Ve(i,e=""){const t=[],s=[];hs(i||{}).forEach(n=>{const l={id:K(),name:n.name,label:z(n.title)??n.name};n.isRequired&&(l.required=!0);const o=z(n.placeholder??n.placeHolder);o&&(l.placeholder=o);const u=z(n.description);u&&(l.help=u),n.defaultValue!=null&&(l.value=Array.isArray(n.defaultValue)?n.defaultValue.join(","):String(n.defaultValue)),n.readOnly&&(l.readonly=!0);const r=typeof n.width=="string"?n.width.trim():"";switch(r==="50%"?l.width="1/2":/^33(\.3+)?%$/.test(r)?l.width="1/3":r==="25%"&&(l.width="1/4"),n.type){case"text":{const d=fs[n.inputType||"text"];if(!d){t.push(`${n.name} (text/${n.inputType})`);return}if(n.visible===!1){s.push({id:l.id,type:"hidden",name:n.name,value:l.value});return}const y={...l,type:d};n.min!=null&&(y.min=String(n.min)),n.max!=null&&(y.max=String(n.max)),n.step!=null&&(y.step=String(n.step)),n.maxLength>0&&(y.maxLength=n.maxLength),n.autocomplete&&(y.autocomplete=n.autocomplete);const h=(n.validators||[]).find(p=>(p==null?void 0:p.type)==="regex"&&p.regex);h&&(y.pattern=String(h.regex).replace(/^\^|\$$/g,""));const v=(n.validators||[]).find(p=>(p==null?void 0:p.type)==="text");(v==null?void 0:v.minLength)>0&&(y.minLength=v.minLength),(v==null?void 0:v.maxLength)>0&&(y.maxLength=v.maxLength),s.push(y);return}case"comment":s.push({...l,type:"textarea",...n.rows?{rows:n.rows}:{},...n.maxLength>0?{maxLength:n.maxLength}:{}});return;case"dropdown":s.push({...l,type:"select",options:fe(n.choices)});return;case"tagbox":s.push({...l,type:"select",multiple:!0,options:fe(n.choices)});return;case"radiogroup":s.push({...l,type:"radio",options:fe(n.choices)});return;case"checkbox":s.push({...l,type:"checkboxes",options:fe(n.choices)});return;case"boolean":s.push({...l,type:"checkbox",label:z(n.label)??l.label,value:n.defaultValue===!0?"1":void 0});return;case"rating":{const d=Array.isArray(n.rateValues)&&n.rateValues.length?fe(n.rateValues):null,y=Number(n.rateMin??1),h=Number(n.rateMax??5),v=Number(n.rateStep??1)||1,p=d||Array.from({length:Math.max(0,Math.floor((h-y)/v)+1)},(k,O)=>String(y+O*v)).map(k=>({value:k,label:k}));s.push({...l,type:"radio",options:p});return}case"file":s.push({...l,type:"file",...n.allowMultiple?{multiple:!0}:{},...n.acceptedTypes?{accept:n.acceptedTypes}:{}});return;case"html":{const d=Be(z(n.html));d&&s.push({id:l.id,type:n.__heading||/^\s*<h[1-6][\s>]/i.test(z(n.html)||"")?"heading":"paragraph",name:"",text:d});return}case"expression":n.name&&t.push(`${n.name} (expression)`);return;default:t.push(`${n.name||"?"} (${n.type})`)}});const a=q({id:e,name:z(i==null?void 0:i.title)||"Form",fields:s,settings:{submitLabel:z(i==null?void 0:i.completeText),successMessage:Be(z(i==null?void 0:i.completedHtml)),redirect:i==null?void 0:i.navigateToUrl}});return i!=null&&i.description&&a.fields.unshift({id:K(),type:"paragraph",name:"",text:Be(z(i.description))||""}),{form:a,skipped:t}}function qe(i){const e=[];i.fields.forEach(s=>{const a={name:s.name};s.label&&(a.title=s.label),s.required&&(a.isRequired=!0),s.placeholder&&(a.placeholder=s.placeholder),s.help&&(a.description=s.help),s.readonly&&(a.readOnly=!0),s.value&&(a.defaultValue=s.type==="checkboxes"?s.value.split(",").map(l=>l.trim()):s.type==="checkbox"?/^(1|true|on|yes)$/i.test(s.value):s.value),s.width==="1/2"&&(a.width="50%");const n=(s.options||[]).map(l=>l.label===l.value?l.value:{value:l.value,text:l.label});switch(s.type){case"heading":case"paragraph":e.push({type:"html",name:s.id,html:s.type==="heading"?`<h3>${Ye(s.text||"")}</h3>`:`<p>${Ye(s.text||"")}</p>`});return;case"hidden":e.push({type:"text",name:s.name,visible:!1,...s.value?{defaultValue:s.value}:{}});return;case"textarea":e.push({...a,type:"comment",...s.rows?{rows:s.rows}:{},...s.maxLength?{maxLength:s.maxLength}:{}});return;case"select":e.push({...a,type:s.multiple?"tagbox":"dropdown",choices:n});return;case"radio":e.push({...a,type:"radiogroup",choices:n});return;case"checkboxes":e.push({...a,type:"checkbox",choices:n});return;case"checkbox":e.push({...a,type:"boolean",renderAs:"checkbox",...s.label?{label:s.label}:{}});return;case"file":e.push({...a,type:"file",...s.multiple?{allowMultiple:!0}:{},...s.accept?{acceptedTypes:s.accept}:{},storeDataAsText:!1});return;default:{const l=s.type==="datetime"?"datetime-local":s.type,o={...a,type:"text",...l!=="text"?{inputType:l}:{}};s.min&&(o.min=s.min),s.max&&(o.max=s.max),s.step&&(o.step=s.step),s.maxLength&&(o.maxLength=s.maxLength),s.autocomplete&&(o.autocomplete=s.autocomplete);const u=[];s.pattern&&u.push({type:"regex",regex:`^${s.pattern}$`}),s.minLength&&u.push({type:"text",minLength:s.minLength}),u.length&&(o.validators=u),e.push(o)}}});const t={title:i.name,pages:[{name:"page1",elements:e}]};return i.settings.submitLabel&&(t.completeText=i.settings.submitLabel),i.settings.successMessage&&(t.completedHtml=`<p>${Ye(i.settings.successMessage)}</p>`),i.settings.redirect&&(t.navigateToUrl=i.settings.redirect),t}const Ye=i=>i.replace(/[&<>"]/g,e=>({"&":"&","<":"<",">":">",'"':"""})[e]);function f(i,e={},...t){const s=document.createElement(i);Object.entries(e).forEach(([n,l])=>{l===!1||l==null||(n==="class"?s.className=String(l):n.startsWith("on")&&typeof l=="function"?s.addEventListener(n.slice(2),l):s.setAttribute(n,l===!0?"":String(l)))});const a=n=>{if(Array.isArray(n))return n.forEach(a);n===!1||n==null||s.append(n instanceof Node?n:document.createTextNode(String(n)))};return t.forEach(a),s}const kt={text:"T",email:"@",tel:"☎",url:"🔗",number:"#",password:"•••",textarea:"¶",select:"▾",radio:"◉",checkbox:"☑",checkboxes:"☷",date:"📅",time:"⏱",datetime:"🗓",range:"⇔",color:"◐",file:"📎",hidden:"👁",heading:"H",paragraph:"≡"},gs=50;class bs{constructor(e){$(this,"root");$(this,"cur",null);$(this,"tab","fields");$(this,"selField",null);$(this,"statusEl",null);$(this,"body",null);$(this,"listEl",null);$(this,"propsEl",null);$(this,"sideEl",null);$(this,"subs",[]);$(this,"subsTotal",0);$(this,"flashTimer",null);this.d=e,this.root=f("div",{class:"gjsf gjsf-ed"})}get t(){return this.d.t}show(e){var a;const t=this.d.forms(),s=e&&this.d.form(e)||this.cur&&this.d.form(this.cur.id)||t[0]||null;this.cur=s?I(s):null,this.cur&&!this.cur.fields.some(n=>n.id===this.selField)&&(this.selField=((a=this.cur.fields[0])==null?void 0:a.id)||null),this.render()}get currentId(){var e;return((e=this.cur)==null?void 0:e.id)||null}setForms(e=!1){if(this.cur&&e){const t=this.d.form(this.cur.id);this.cur=t?I(t):this.d.forms()[0]?I(this.d.forms()[0]):null,this.render();return}if(this.cur&&!this.d.form(this.cur.id)){this.show(null);return}this.renderSide()}flash(e,t=!1){this.statusEl&&(this.statusEl.textContent=e,this.statusEl.classList.toggle("is-error",t),this.flashTimer&&clearTimeout(this.flashTimer),t||(this.flashTimer=setTimeout(()=>this.statusEl&&(this.statusEl.textContent=""),2500)))}destroy(){this.flashTimer&&clearTimeout(this.flashTimer),this.root.replaceChildren()}changed(){this.cur&&this.d.change(I(this.cur))}render(){const e=this.t;this.sideEl=f("div",{class:"gjsf-side"});const t=f("div",{class:"gjsf-main"});this.root.replaceChildren(this.sideEl,t),this.renderSide();const s=this.cur;if(!s){t.append(f("div",{class:"gjsf-empty"},e("noForms")));return}const a=f("input",{class:"gjsf-input",value:s.name,"aria-label":e("formName"),"data-role":"form-name"});a.addEventListener("input",()=>{s.name=a.value,this.changed(),this.renderSide()}),this.statusEl=f("span",{class:"gjsf-status","aria-live":"polite"});const n=f("div",{class:"gjsf-head"},a,this.statusEl,f("button",{class:"gjsf-btn",type:"button","data-role":"duplicate",title:e("duplicateForm"),onclick:()=>this.duplicate()},"⧉"),f("button",{class:"gjsf-btn is-danger",type:"button","data-role":"remove-form",title:e("removeForm"),onclick:()=>this.removeForm()},"🗑")),o=f("div",{class:"gjsf-tabs",role:"tablist"},...[["fields","fields"],["settings","settings"],["preview","preview"],["submissions","submissions"],["json","json"]].map(([u,r])=>f("button",{class:`gjsf-tab${this.tab===u?" is-active":""}`,type:"button",role:"tab","aria-selected":this.tab===u?"true":"false","data-tab":u,onclick:()=>{this.tab=u,this.render()}},e(r))));this.body=f("div",{class:"gjsf-body"}),t.append(n,o,this.body),this.tab==="fields"?this.renderFields():this.tab==="settings"?this.renderSettings():this.tab==="preview"?this.renderPreview():this.tab==="submissions"?this.renderSubmissions(!0):this.renderJson()}renderSide(){if(!this.sideEl)return;const e=this.t,t=f("ul",{class:"gjsf-side-list"},...this.d.forms().map(s=>{var n;const a=this.cur&&s.id===this.cur.id?this.cur.name:s.name;return f("li",{class:`gjsf-side-item${((n=this.cur)==null?void 0:n.id)===s.id?" is-active":""}`,tabindex:"0","data-form":s.id,onclick:()=>this.show(s.id),onkeydown:l=>l.key==="Enter"&&this.show(s.id)},a||s.id)}));this.sideEl.replaceChildren(f("button",{class:"gjsf-btn is-primary",type:"button","data-role":"new-form",onclick:()=>void this.d.create().then(s=>{this.tab="fields",this.show(s.id)}).catch(this.d.onError)},`+ ${e("newForm")}`),t)}duplicate(){this.cur&&this.d.duplicate(this.cur.id).then(e=>this.show(e.id)).catch(this.d.onError)}removeForm(){const e=this.cur;!e||!window.confirm(ee(this.t("confirmRemoveForm"),e.name))||this.d.remove(e.id).then(()=>{this.cur=null,this.show(null)}).catch(this.d.onError)}renderFields(){const e=this.t,t=f("div",{class:"gjsf-palette","aria-label":e("addField")},f("div",{class:"gjsf-sec"},e("addField")),...[...ye,...de].map(s=>f("button",{type:"button","data-add":s,title:e(`type_${s}`),onclick:()=>this.addField(s)},f("span",{class:"gjsf-ico"},kt[s]),e(`type_${s}`))));this.listEl=f("div",{class:"gjsf-list"}),this.propsEl=f("div",{class:"gjsf-props"}),this.body.replaceChildren(f("div",{class:"gjsf-cols"},t,this.listEl,this.propsEl)),this.renderList(),this.renderProps()}addField(e){var o,u;const t=this.cur,s=N(e)?"":this.t(`type_${e}`),a=new Set(t.fields.map(r=>r.name)),n={id:K(),type:e,name:N(e)?"":Q(G(s)||e,a)};N(e)?n.text=this.t(`type_${e}`):e!=="hidden"&&(n.label=s),pe.includes(e)&&(n.options=[1,2,3].map(r=>({label:`${this.t("optionLabel")} ${r}`,value:`option_${r}`})));const l=this.selField?t.fields.findIndex(r=>r.id===this.selField)+1:t.fields.length;t.fields.splice(l>0?l:t.fields.length,0,n),this.selField=n.id,this.changed(),this.renderList(),this.renderProps(),(u=(o=this.propsEl)==null?void 0:o.querySelector("input,textarea"))==null||u.focus()}renderList(){if(!this.listEl||!this.cur)return;const e=this.t,t=this.cur.fields;if(!t.length){this.listEl.replaceChildren(f("p",{class:"gjsf-hint"},e("noFields")));return}const s=(a,n)=>{const l=a+n;l<0||l>=t.length||([t[a],t[l]]=[t[l],t[a]],this.changed(),this.renderList())};this.listEl.replaceChildren(...t.map((a,n)=>f("div",{class:`gjsf-row${a.id===this.selField?" is-active":""}`,"data-field":a.id,tabindex:"0",onclick:()=>{this.selField=a.id,this.renderList(),this.renderProps()}},f("span",{class:"gjsf-ico",title:e(`type_${a.type}`)},kt[a.type]),f("div",{class:"gjsf-row-main"},f("div",{class:"gjsf-row-title"},Fe(a),a.required?" *":""),f("div",{class:"gjsf-row-sub"},N(a.type)?e(`type_${a.type}`):`${a.name} · ${a.type}`)),this.act("↑",e("moveUp"),n===0,()=>s(n,-1)),this.act("↓",e("moveDown"),n===t.length-1,()=>s(n,1)),this.act("⧉",e("duplicate"),!1,()=>{const l={...I(a),id:K()};N(a.type)||(l.name=Q(a.name,new Set(t.map(o=>o.name)))),t.splice(n+1,0,l),this.selField=l.id,this.changed(),this.renderList(),this.renderProps()}),this.act("✕",e("remove"),!1,()=>{var l;t.splice(n,1),this.selField===a.id&&(this.selField=((l=t[Math.min(n,t.length-1)])==null?void 0:l.id)||null),this.changed(),this.renderList(),this.renderProps()}))))}act(e,t,s,a){return f("button",{class:"gjsf-act",type:"button",title:t,"aria-label":t,disabled:s,onclick:n=>{n.stopPropagation(),a()}},e)}refreshRow(e){var n;const t=(n=this.listEl)==null?void 0:n.querySelector(`[data-field="${e.id}"]`);if(!t)return;const s=t.querySelector(".gjsf-row-title"),a=t.querySelector(".gjsf-row-sub");s&&(s.textContent=Fe(e)+(e.required?" *":"")),a&&!N(e.type)&&(a.textContent=`${e.name} · ${e.type}`)}text(e,t,s,a={}){const n=t[s],l={class:`gjsf-input${a.code?" gjsf-code":""}`,"data-prop":s,...a.placeholder?{placeholder:a.placeholder}:{}},o=a.area?f("textarea",{...l,rows:"3"}):f("input",{...l,type:a.type||"text"});return o.value=n==null?"":String(n),o.addEventListener("input",()=>{var r;const u=o.value;if(a.num){const d=u.trim()===""?NaN:Number(u);Number.isInteger(d)&&d>=0?t[s]=d:delete t[s]}else u===""?delete t[s]:t[s]=u;(r=a.onChange)==null||r.call(a),this.changed()}),f("label",{class:"gjsf-f"},f("span",{},e),o,a.hint?f("small",{},a.hint):null)}check(e,t,s,a={}){const n=f("input",{type:"checkbox","data-prop":s});return n.checked=a.invert?t[s]!==!1:t[s]===!0,n.addEventListener("change",()=>{var l;a.invert?n.checked?delete t[s]:t[s]=!1:n.checked?t[s]=!0:delete t[s],(l=a.onChange)==null||l.call(a),this.changed()}),f("label",{class:"gjsf-check"},n,e)}chips(e){const t=this.t;return f("div",{},f("small",{class:"gjsf-hint"},`${t("placeholders")}: ${t("placeholdersHint")}`),f("div",{class:"gjsf-chips"},...nt.map(s=>f("button",{class:`gjsf-chip${s.at==="build"?" is-build":""}`,type:"button","data-token":s.token,onclick:()=>{const a=e();if(!a)return;const n=a.selectionStart??a.value.length,l=a.selectionEnd??n;a.value=a.value.slice(0,n)+s.token+a.value.slice(l),a.dispatchEvent(new Event("input",{bubbles:!0})),a.focus()}},s.token))))}kv(e,t,s){const a=this.t,n=f("div",{class:"gjsf-kvs","data-prop":s}),l=Object.entries(t[s]||{}),o=()=>{const r={};l.forEach(([d,y])=>{d.trim()&&(r[d.trim()]=y)}),Object.keys(r).length?t[s]=r:delete t[s],this.changed()},u=()=>{n.replaceChildren(f("div",{class:"gjsf-sec"},e),...l.map((r,d)=>{const y=f("input",{class:"gjsf-input gjsf-code",placeholder:a("attrName"),value:r[0],"aria-label":a("attrName")}),h=f("input",{class:"gjsf-input",placeholder:a("attrValue"),value:r[1],"aria-label":a("attrValue")});return y.addEventListener("input",()=>{r[0]=y.value,o()}),h.addEventListener("input",()=>{r[1]=h.value,o()}),f("div",{class:"gjsf-kv"},y,h,this.act("✕",a("remove"),!1,()=>{l.splice(d,1),o(),u()}))}),f("button",{class:"gjsf-btn",type:"button","data-role":"add-attr",onclick:()=>{var r;l.push(["data-",""]),u(),(r=n.querySelectorAll(".gjsf-kv input")[l.length*2-2])==null||r.focus()}},`+ ${a("addAttr")}`))};return u(),n}optionsEditor(e){const t=this.t,s=f("div",{class:"gjsf-opts","data-prop":"options"}),a=e.options||(e.options=[]),n=()=>{s.replaceChildren(f("div",{class:"gjsf-sec"},t("options")),f("small",{class:"gjsf-hint"},t("optionsHint")),...a.map((l,o)=>{const u=f("input",{class:"gjsf-input",value:l.label,placeholder:t("optionLabel"),"aria-label":t("optionLabel")}),r=f("input",{class:"gjsf-input gjsf-code",value:l.value,placeholder:t("optionValue"),"aria-label":t("optionValue")});let d=l.value===G(l.label)||/^option_\d+$/.test(l.value);return u.addEventListener("input",()=>{l.label=u.value,d&&(l.value=G(u.value)||l.value,r.value=l.value),this.changed()}),r.addEventListener("input",()=>{d=!1,l.value=r.value,this.changed()}),f("div",{class:"gjsf-kv"},u,r,this.act("↑",t("moveUp"),o===0,()=>{[a[o-1],a[o]]=[a[o],a[o-1]],this.changed(),n()}),this.act("✕",t("remove"),!1,()=>{a.splice(o,1),this.changed(),n()}))}),f("button",{class:"gjsf-btn",type:"button","data-role":"add-option",onclick:()=>{const l=a.length+1;a.push({label:`${t("optionLabel")} ${l}`,value:`option_${l}`}),this.changed(),n()}},`+ ${t("addOption")}`))};return n(),s}renderProps(){if(!this.propsEl||!this.cur)return;const e=this.t,t=this.cur.fields.find(h=>h.id===this.selField);if(!t){this.propsEl.replaceChildren(f("p",{class:"gjsf-hint"},e("noFieldSelected")));return}const s=()=>this.refreshRow(t),a=f("select",{class:"gjsf-input","data-prop":"type","aria-label":e("fieldType")},...[...ye,...de].map(h=>f("option",{value:h,selected:h===t.type},e(`type_${h}`))));a.addEventListener("change",()=>{var p;const h=a.value,v=t.type;t.type=h,N(h)&&!N(v)?(t.text=t.label||t.text||"",t.name=""):!N(h)&&N(v)&&(t.label=t.text||e(`type_${h}`),t.name=Q(G(t.label)||h,new Set(this.cur.fields.filter(k=>k!==t).map(k=>k.name)))),pe.includes(h)&&!((p=t.options)!=null&&p.length)&&(t.options=[1,2].map(k=>({label:`${e("optionLabel")} ${k}`,value:`option_${k}`}))),this.changed(),this.renderList(),this.renderProps()});const n=[f("label",{class:"gjsf-f"},f("span",{},e("fieldType")),a)];if(N(t.type)){n.push(this.text(e("text"),t,"text",{area:t.type==="paragraph",onChange:s})),n.push(this.kv(e("attrs"),t,"attrs")),this.propsEl.replaceChildren(...n.filter(Boolean));return}let l=!!t.name&&t.name!==G(t.label||"")&&!/^(text|email|tel|url|number|password|textarea|select|radio|checkbox|checkboxes|date|time|datetime|range|color|file|hidden)(_\d+)?$/.test(t.name);const o=this.text(e("fieldName"),t,"name",{code:!0,hint:e("fieldNameHint"),onChange:()=>{l=!0,s()}}),u=o.querySelector("input");u.addEventListener("change",()=>{const h=new Set(this.cur.fields.filter(p=>p!==t&&!N(p.type)).map(p=>p.name)),v=Q(G(u.value)||(/^[A-Za-z_]/.test(u.value)?u.value:"")||t.type,h);(v!==t.name||u.value!==v)&&(t.name=v,u.value=v,this.changed(),s())}),t.type!=="hidden"&&n.push(this.text(e("fieldLabel"),t,"label",{onChange:()=>{if(!l){const h=new Set(this.cur.fields.filter(p=>p!==t&&!N(p.type)).map(p=>p.name)),v=G(t.label||"");v&&(t.name=Q(v,h),u.value=t.name)}s()}})),n.push(o);const r=this.text(t.type==="hidden"?e("hiddenValue"):e("defaultValue"),t,"value",{code:t.type==="hidden"}),d=()=>r.querySelector("input");if(t.type==="hidden"){n.push(r,this.chips(d)),n.push(this.kv(e("attrs"),t,"attrs")),this.propsEl.replaceChildren(...n.filter(Boolean));return}if(["checkbox","radio","checkboxes","range","color","file","date","time","datetime"].includes(t.type)||n.push(this.text(e("placeholder"),t,"placeholder")),n.push(this.text(e("help"),t,"help")),n.push(this.check(e("required"),t,"required",{onChange:s})),pe.includes(t.type)&&n.push(this.optionsEditor(t)),(t.type==="select"||t.type==="file")&&n.push(this.check(e("multiple"),t,"multiple")),t.type!=="file"&&t.type!=="password"&&n.push(r,this.chips(d)),rt.includes(t.type)){const h=t.type==="number"||t.type==="range"?"number":t.type==="datetime"?"datetime-local":t.type;n.push(f("div",{class:"gjsf-grid"},this.text(e("min"),t,"min",{type:h}),this.text(e("max"),t,"max",{type:h}),this.text(e("step"),t,"step",{type:"number"})))}ve.includes(t.type)&&(n.push(f("div",{class:"gjsf-grid2"},this.text(e("minLength"),t,"minLength",{type:"number",num:!0}),this.text(e("maxLength"),t,"maxLength",{type:"number",num:!0}))),t.type!=="textarea"&&n.push(this.text(e("pattern"),t,"pattern",{code:!0,placeholder:"[0-9]{5}"}))),t.type==="textarea"&&n.push(this.text(e("rows"),t,"rows",{type:"number",num:!0})),t.type==="file"&&n.push(this.text(e("accept"),t,"accept",{code:!0,placeholder:"image/*,.pdf"})),["checkbox","radio","checkboxes","file","range","color"].includes(t.type)||n.push(this.text(e("autocomplete"),t,"autocomplete",{code:!0,placeholder:t.type==="email"?"email":t.type==="tel"?"tel":"name"}));const y=f("select",{class:"gjsf-input","data-prop":"width","aria-label":e("width")},...ke.map(h=>f("option",{value:h,selected:(t.width||"full")===h},h==="full"?"100%":h)));y.addEventListener("change",()=>{y.value==="full"?delete t.width:t.width=y.value,this.changed()}),n.push(f("label",{class:"gjsf-f"},f("span",{},e("width")),y)),n.push(f("div",{class:"gjsf-grid2"},this.check(e("readonly"),t,"readonly"),this.check(e("disabled"),t,"disabled"))),n.push(this.kv(e("attrs"),t,"attrs")),this.propsEl.replaceChildren(...n.filter(Boolean))}renderSettings(){const e=this.t,t=this.cur,s=t.settings,a=this.d.defaultAction(t);this.body.replaceChildren(f("div",{class:"gjsf-pane"},this.text(e("endpoint"),s,"endpoint",{code:!0,placeholder:a||"https://…",hint:ee(e("endpointHint"),a||e("noEndpoint"))}),this.text(e("submitLabel"),s,"submitLabel",{placeholder:e("submit")}),this.text(e("successMessage"),s,"successMessage",{area:!0,placeholder:e("success")}),this.text(e("errorMessage"),s,"errorMessage",{area:!0,placeholder:e("error")}),this.text(e("redirect"),s,"redirect",{code:!0,placeholder:"/thank-you"}),this.check(e("reset"),s,"reset",{invert:!0}),this.check(e("honeypot"),s,"honeypot",{invert:!0}),this.kv(e("formAttrs"),t,"attrs")))}renderPreview(){const e=this.t,t=this.cur,{css:s,links:a}=this.d.previewStyles(),n=f("iframe",{class:"gjsf-frame",title:e("preview")}),l=f("span",{},e("previewHint"));this.body.replaceChildren(f("div",{class:"gjsf-frame-bar"},l),n);const o=y=>y.replace(/"/g,"""),u=`<!DOCTYPE html><html><head><meta charset="utf-8">${a.map(y=>`<link rel="stylesheet" href="${o(y)}">`).join("")}<style>${s.replace(/<\/style/gi,"<\\/style")}</style><style>body{padding:16px}</style></head><body>${this.d.previewHtml(t)}</body></html>`,r=()=>{const y=n.contentDocument,h=y==null?void 0:y.querySelector("form[data-gjsf-form]");!h||h.__gjsf||(h.addEventListener("gjsf:submit",v=>{const p=v.detail;p.promise=this.d.submit(t.id,p.data,{...p.meta,url:"editor:preview"}).then(k=>(l.textContent=e("previewSent"),{...k,message:k.message})).catch(k=>{throw k instanceof Z?{status:k.status,body:{error:k.message,errors:k.errors}}:{status:0,body:{error:k==null?void 0:k.message}}})}),we.call(h))},d=n.contentDocument;d&&(d.open(),d.write(u),d.close(),r(),n.addEventListener("load",r))}async renderSubmissions(e){var v;const t=this.t,s=this.cur,a=f("div",{class:"gjsf-pane",style:"max-width:none"});this.body.replaceChildren(a);const n=this.d.submissions(s.id,{limit:gs,offset:e?0:this.subs.length});if(!n){a.append(f("p",{class:"gjsf-hint"},t("submissionsUnsupported")));return}try{const p=await n;if(((v=this.cur)==null?void 0:v.id)!==s.id||this.tab!=="submissions")return;this.subs=e?p.items:[...this.subs,...p.items],this.subsTotal=p.total}catch(p){a.append(f("p",{class:"gjsf-err"},p.message));return}const l=s.fields.filter(p=>!N(p.type)),o=new Set(l.map(p=>p.name)),u=[...new Set(this.subs.flatMap(p=>Object.keys(p.data||{})))].filter(p=>!o.has(p)),r=[...l.map(p=>({key:p.name,title:p.label||p.name})),...u.map(p=>({key:p,title:p}))],d=p=>p==null?"":Array.isArray(p)?p.join(", "):typeof p=="boolean"?p?"✓":"":typeof p=="object"?JSON.stringify(p):String(p),y=f("div",{class:"gjsf-bar"},f("button",{class:"gjsf-btn",type:"button","data-role":"refresh",onclick:()=>void this.renderSubmissions(!0)},`↻ ${t("refresh")}`),f("button",{class:"gjsf-btn",type:"button","data-role":"csv",disabled:!this.subs.length,onclick:()=>At(`${s.name||s.id}.csv`,Ct([t("date"),...r.map(p=>p.title)],this.subs.map(p=>[p.createdAt,...r.map(k=>{var O;return d((O=p.data)==null?void 0:O[k.key])})])),"text/csv")},`⇩ ${t("downloadCsv")}`),f("span",{class:"gjsf-hint"},ee(t("shownOf"),this.subs.length,this.subsTotal)));if(a.append(y),!this.subs.length){a.append(f("p",{class:"gjsf-hint"},t("noSubmissions")));return}const h=f("table",{class:"gjsf-table"},f("thead",{},f("tr",{},f("th",{},t("date")),...r.map(p=>f("th",{},p.title)),f("th",{},""))),f("tbody",{},...this.subs.map(p=>{var k;return f("tr",{"data-submission":p.id},f("td",{title:String(((k=p.meta)==null?void 0:k.url)||"")},new Date(p.createdAt).toLocaleString()),...r.map(O=>{var D;return f("td",{},d((D=p.data)==null?void 0:D[O.key]))}),f("td",{},this.act("✕",t("remove"),!1,()=>{window.confirm(t("confirmDeleteSubmission"))&&this.d.deleteSubmission(s.id,p.id).then(()=>this.renderSubmissions(!0)).catch(this.d.onError)})))})));a.append(f("div",{class:"gjsf-table-wrap"},h)),this.subs.length<this.subsTotal&&a.append(f("button",{class:"gjsf-btn",type:"button","data-role":"more",onclick:()=>void this.renderSubmissions(!1)},t("loadMore")))}renderJson(){const e=this.t,t=this.cur,{id:s,version:a,updatedAt:n,...l}=t,o=f("textarea",{class:"gjsf-input gjsf-code",rows:"22","data-role":"json",spellcheck:"false"});o.value=JSON.stringify(l,null,2);const u=f("p",{class:"gjsf-hint","aria-live":"polite"});this.body.replaceChildren(f("div",{class:"gjsf-pane",style:"max-width:none"},f("p",{class:"gjsf-hint"},e("jsonHint")),o,f("div",{class:"gjsf-bar"},f("button",{class:"gjsf-btn is-primary",type:"button","data-role":"apply-json",onclick:()=>{let r;try{r=JSON.parse(o.value)}catch(d){u.textContent=ee(e("jsonError"),d.message),u.className="gjsf-err";return}this.d.applyJson(t.id,r).then(d=>{var y;this.cur=I(this.d.form(t.id)||t),this.selField=((y=this.cur.fields[0])==null?void 0:y.id)||null,this.render(),d.length?this.flash(ee(e("skipped"),d.join(", ")),!0):this.flash(e("saved"))}).catch(this.d.onError)}},e("applyJson")),f("button",{class:"gjsf-btn",type:"button","data-role":"export-surveyjs",onclick:()=>At(`${t.name||t.id}.survey.json`,JSON.stringify(this.d.exportSurveyJs(t.id),null,2),"application/json")},`⇩ ${e("exportSurveyJs")}`)),u))}}function Ct(i,e){const t=s=>/[",\r\n;]/.test(s)?`"${s.replace(/"/g,'""')}"`:s;return"\uFEFF"+[i,...e].map(s=>s.map(a=>t(String(a??""))).join(",")).join(`\r
|
|
6
|
+
`)}function At(i,e,t){try{const s=URL.createObjectURL(new Blob([e],{type:t})),a=f("a",{href:s,download:i.replace(/[\\/:*?"<>|]+/g,"_")});document.body.append(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(s),1e3)}catch{}}const Ft="gjsf-style",ys=`
|
|
7
|
+
.gjsf-modal .gjs-mdl-dialog{max-width:1180px;width:96%}
|
|
8
|
+
.gjsf-modal .gjs-mdl-content{padding:0}
|
|
9
|
+
.gjsf-ed{display:flex;height:min(78vh,760px);font-size:13px;text-align:start;font-family:var(--gjs-main-font,Helvetica,sans-serif)}
|
|
10
|
+
.gjsf-ed *{box-sizing:border-box}
|
|
11
|
+
.gjsf-side{width:200px;flex:none;border-inline-end:1px solid rgba(0,0,0,.25);display:flex;flex-direction:column;overflow:auto}
|
|
12
|
+
.gjsf-side-list{list-style:none;margin:0;padding:0;flex:1}
|
|
13
|
+
.gjsf-side-item{padding:8px 12px;cursor:pointer;border-inline-start:3px solid transparent;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
14
|
+
.gjsf-side-item:hover{background:rgba(255,255,255,.06)}
|
|
15
|
+
.gjsf-side-item.is-active{border-inline-start-color:var(--gjs-quaternary-color,#d278c9);background:rgba(255,255,255,.08)}
|
|
16
|
+
.gjsf-main{flex:1;min-width:0;display:flex;flex-direction:column}
|
|
17
|
+
.gjsf-head{display:flex;gap:8px;align-items:center;padding:8px 12px;border-bottom:1px solid rgba(0,0,0,.25)}
|
|
18
|
+
.gjsf-head .gjsf-input{flex:1;font-size:15px;font-weight:600}
|
|
19
|
+
.gjsf-status{font-size:11px;opacity:.75;white-space:nowrap}
|
|
20
|
+
.gjsf-status.is-error{color:#ff8a80;opacity:1}
|
|
21
|
+
.gjsf-tabs{display:flex;gap:2px;padding:0 8px;border-bottom:1px solid rgba(0,0,0,.25)}
|
|
22
|
+
.gjsf-tab{background:none;border:0;border-bottom:2px solid transparent;color:inherit;padding:8px 12px;cursor:pointer;font:inherit;opacity:.75}
|
|
23
|
+
.gjsf-tab.is-active{border-bottom-color:var(--gjs-quaternary-color,#d278c9);opacity:1}
|
|
24
|
+
.gjsf-body{flex:1;min-height:0;overflow:auto}
|
|
25
|
+
.gjsf-cols{display:flex;height:100%}
|
|
26
|
+
.gjsf-palette{width:150px;flex:none;padding:8px;border-inline-end:1px solid rgba(0,0,0,.2);overflow:auto}
|
|
27
|
+
.gjsf-palette button{display:flex;gap:6px;align-items:center;width:100%;text-align:start;margin:0 0 3px;padding:5px 8px;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);border-radius:3px;color:inherit;cursor:pointer;font:inherit}
|
|
28
|
+
.gjsf-palette button:hover{background:rgba(255,255,255,.14)}
|
|
29
|
+
.gjsf-ico{display:inline-block;width:18px;text-align:center;opacity:.8;font-size:12px}
|
|
30
|
+
.gjsf-list{flex:1;min-width:0;padding:8px;overflow:auto;border-inline-end:1px solid rgba(0,0,0,.2)}
|
|
31
|
+
.gjsf-row{display:flex;gap:6px;align-items:center;padding:6px 8px;margin-bottom:4px;border:1px solid rgba(255,255,255,.12);border-radius:4px;cursor:pointer}
|
|
32
|
+
.gjsf-row:hover{background:rgba(255,255,255,.05)}
|
|
33
|
+
.gjsf-row.is-active{border-color:var(--gjs-quaternary-color,#d278c9);background:rgba(255,255,255,.08)}
|
|
34
|
+
.gjsf-row-main{flex:1;min-width:0}
|
|
35
|
+
.gjsf-row-title{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
36
|
+
.gjsf-row-sub{font-size:10px;opacity:.6;font-family:ui-monospace,Menlo,Consolas,monospace}
|
|
37
|
+
.gjsf-row .gjsf-act{visibility:hidden}
|
|
38
|
+
.gjsf-row:hover .gjsf-act,.gjsf-row.is-active .gjsf-act{visibility:visible}
|
|
39
|
+
.gjsf-act{background:none;border:0;color:inherit;cursor:pointer;padding:2px 5px;border-radius:3px;font-size:12px}
|
|
40
|
+
.gjsf-act:hover{background:rgba(255,255,255,.15)}
|
|
41
|
+
.gjsf-act[disabled]{opacity:.3;cursor:default}
|
|
42
|
+
.gjsf-props{width:330px;flex:none;padding:8px 12px;overflow:auto}
|
|
43
|
+
.gjsf-pane{padding:12px;max-width:720px}
|
|
44
|
+
.gjsf-f{display:block;margin:0 0 8px}
|
|
45
|
+
.gjsf-f>span{display:block;font-size:11px;opacity:.85;margin-bottom:2px}
|
|
46
|
+
.gjsf-f small{display:block;font-size:10px;opacity:.6;margin-top:2px}
|
|
47
|
+
.gjsf-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px}
|
|
48
|
+
.gjsf-grid2{display:grid;grid-template-columns:1fr 1fr;gap:6px}
|
|
49
|
+
.gjsf-input{display:block;width:100%;margin:0;padding:5px 8px;background:rgba(0,0,0,.25);border:1px solid rgba(255,255,255,.2);color:inherit;border-radius:3px;font:inherit}
|
|
50
|
+
.gjsf-input option{color:#222}
|
|
51
|
+
textarea.gjsf-input{resize:vertical;min-height:54px}
|
|
52
|
+
.gjsf-code{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px}
|
|
53
|
+
.gjsf-check{display:flex;align-items:center;gap:6px;margin:0 0 6px;cursor:pointer}
|
|
54
|
+
.gjsf-kv{display:flex;gap:4px;margin-bottom:4px}
|
|
55
|
+
.gjsf-kv .gjsf-input{flex:1;min-width:0}
|
|
56
|
+
.gjsf-sec{margin:12px 0 6px;font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;opacity:.7}
|
|
57
|
+
.gjsf-hint{opacity:.7;font-size:12px;margin:4px 0}
|
|
58
|
+
.gjsf-chips{display:flex;flex-wrap:wrap;gap:3px;margin-top:4px}
|
|
59
|
+
.gjsf-chip{background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.15);border-radius:10px;padding:1px 7px;font-size:10px;cursor:pointer;color:inherit;font-family:ui-monospace,Menlo,Consolas,monospace}
|
|
60
|
+
.gjsf-chip.is-build{border-style:dashed}
|
|
61
|
+
.gjsf-btn{padding:6px 12px;border-radius:3px;border:0;cursor:pointer;color:inherit;font:inherit;background:rgba(255,255,255,.15)}
|
|
62
|
+
.gjsf-btn:hover{background:rgba(255,255,255,.22)}
|
|
63
|
+
.gjsf-btn.is-primary{background:var(--gjs-quaternary-color,#d278c9)}
|
|
64
|
+
.gjsf-btn.is-danger:hover{background:#c62828}
|
|
65
|
+
.gjsf-bar{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin:8px 0}
|
|
66
|
+
.gjsf-side .gjsf-btn{margin:8px}
|
|
67
|
+
.gjsf-empty{padding:24px;opacity:.7}
|
|
68
|
+
.gjsf-frame{width:100%;height:calc(100% - 36px);border:0;background:#fff;display:block}
|
|
69
|
+
.gjsf-frame-bar{display:flex;gap:8px;align-items:center;padding:6px 12px;font-size:11px;opacity:.85;height:36px}
|
|
70
|
+
.gjsf-table-wrap{overflow:auto;max-height:100%}
|
|
71
|
+
.gjsf-table{border-collapse:collapse;width:100%;font-size:12px}
|
|
72
|
+
.gjsf-table th,.gjsf-table td{border-bottom:1px solid rgba(255,255,255,.1);padding:5px 8px;text-align:start;vertical-align:top;max-width:280px;overflow-wrap:anywhere}
|
|
73
|
+
.gjsf-table th{position:sticky;top:0;background:var(--gjs-primary-color,#444);font-weight:600}
|
|
74
|
+
.gjsf-err{color:#ff8a80}
|
|
75
|
+
.gjsf-toggle{position:absolute;top:8px;right:96px;z-index:60;background:var(--gjs-primary-color,#444);color:var(--gjs-font-color,#ddd);border:1px solid rgba(255,255,255,.2);border-radius:4px;padding:6px 10px;cursor:pointer}
|
|
76
|
+
`;function Tt(i=document){if(i.getElementById(Ft))return;const e=i.createElement("style");e.id=Ft,e.textContent=ys,i.head.appendChild(e)}const Ke=`
|
|
77
|
+
.gjsf-form{display:flex;flex-wrap:wrap;gap:16px;position:relative}
|
|
78
|
+
.gjsf-field{flex:1 1 100%;min-width:0;margin:0;padding:0;border:0}
|
|
79
|
+
.gjsf-w-1-2{flex-basis:calc(50% - 8px)}
|
|
80
|
+
.gjsf-w-1-3{flex-basis:calc(33.333% - 11px)}
|
|
81
|
+
.gjsf-w-2-3{flex-basis:calc(66.666% - 6px)}
|
|
82
|
+
.gjsf-w-1-4{flex-basis:calc(25% - 12px)}
|
|
83
|
+
.gjsf-w-3-4{flex-basis:calc(75% - 4px)}
|
|
84
|
+
.gjsf-label{display:block;margin:0 0 6px;padding:0;font-weight:600}
|
|
85
|
+
.gjsf-req{margin-left:2px;color:#c62828}
|
|
86
|
+
.gjsf-input{display:block;width:100%;box-sizing:border-box;padding:10px 12px;font:inherit;color:inherit;background:transparent;border:1px solid rgba(127,127,127,.5);border-radius:4px}
|
|
87
|
+
.gjsf-input:focus{outline:2px solid rgba(127,127,127,.35);outline-offset:1px}
|
|
88
|
+
.gjsf-options{display:flex;flex-direction:column;gap:6px}
|
|
89
|
+
.gjsf-option{display:flex;gap:8px;align-items:center;cursor:pointer;font-weight:400}
|
|
90
|
+
.gjsf-help{margin-top:4px;font-size:.875em;opacity:.75}
|
|
91
|
+
.gjsf-error{margin-top:4px;font-size:.875em;color:#c62828}
|
|
92
|
+
.gjsf-error:empty{display:none}
|
|
93
|
+
.has-error .gjsf-input{border-color:#c62828}
|
|
94
|
+
.gjsf-heading{flex-basis:100%;margin:8px 0 0}
|
|
95
|
+
.gjsf-text{flex-basis:100%;margin:0}
|
|
96
|
+
.gjsf-actions{flex-basis:100%}
|
|
97
|
+
.gjsf-submit{font:inherit;padding:10px 24px;cursor:pointer}
|
|
98
|
+
.gjsf-message{flex-basis:100%}
|
|
99
|
+
.gjsf-message:empty{display:none}
|
|
100
|
+
.gjsf-form.is-sending{opacity:.7}
|
|
101
|
+
.gjsf-form.is-error .gjsf-message{color:#c62828}
|
|
102
|
+
`,We="gjsf-forms",Ge="gjsf-new",Ze=i=>`gjsf-form-${i}`;function vs(i){return i.Forms}function Xe(i={}){const e=(s,a)=>typeof s=="number"&&Number.isFinite(s)&&s>=0?s:a,t=i.rest&&i.rest.url?i.rest:null;return{store:i.store??null,rest:t,submitUrl:(i.submitUrl??(t==null?void 0:t.url)??null)||null,dbName:i.dbName||"gjs-forms",autosaveDelay:e(i.autosaveDelay,600),blocks:i.blocks!==!1,baseCss:i.baseCss!==!1,panelId:i.panelId||null,labels:{...i.labels||{}},injectCss:i.injectCss!==!1}}const Lt=i=>`<svg viewBox="0 0 24 24" style="display:block;width:${i}px;height:${i}px"><path fill="currentColor" d="M4 4h16v2H4zm0 4h10v2H4zm0 5h16v3H4zm0 5h7v2H4zm11 0h5v2h-5z"/></svg>`,Ot='<svg viewBox="0 0 24 24"><path fill="currentColor" d="M3 4h18v2H3zm0 4h11v2H3zm0 5h18v3H3zm0 5h8v3H3zm11 0h7v3h-7z"/></svg>',xs=["required","email","url","number","min","max","minLength","maxLength","pattern","option","date","time","color"];function js(i,e={}){var Pt;const t=i;(Pt=t.__gjsfCleanup)==null||Pt.call(t);const s=Xe(e);cs(i);const a=ds(i,s.labels),n=s.store||(s.rest?new _t(s.rest):new He(s.dbName)),l=()=>t.PagesManager;let o=[],u=null,r=null,d=!1;const y=[],h=(c,m)=>{i.on(c,m),y.push(()=>i.off(c,m))},v=(c,...m)=>{d||i.trigger(c,...m)},p=c=>c?o.find(m=>m.id===c):void 0,k=()=>void o.sort((c,m)=>c.name.localeCompare(m.name)||c.id.localeCompare(m.id)),O=c=>{r==null||r.flash(ee(a("saveError"),(c==null?void 0:c.message)||String(c)),!0),wt(c)},D=c=>{var b;const m=typeof c=="string"?p(c):c;return m?((b=m.settings)==null?void 0:b.endpoint)||(s.submitUrl?ze(s.submitUrl,m.id):""):""},W=()=>Object.fromEntries(xs.map(c=>[c,a(`problem_${c}`)])),H=()=>({submit:a("submit"),success:a("success"),error:a("error")}),B=()=>u&&typeof u.id=="string"?u.id:null,_=new vt(i,{form:p,formOptions:()=>o.map(c=>({id:c.id,name:c.name})),buildOptions:c=>({action:D(c),ctx:{page:u},texts:H(),codes:W(),pageId:B()}),labels:{chooseForm:()=>a("chooseForm"),editForm:()=>a("editForm"),noForm:()=>a("noForm"),missingForm:()=>a("missingForm")},editCommand:me.edit,onCreate:c=>void se().then(m=>{c.set("formId",m.id),ge(m.id)}).catch(O)}),x=(c,m)=>{const b=c.getAttributes();if(b["data-gjsf-version"]!==String(m.version??"")||"data-gjsf-missing"in b)return!0;const C=B();return(b["data-gjsf-page"]||null)!==C},j=()=>{d||_.rebuildAll(null,x)};let S=!1;const w=()=>{var m;if(!s.baseCss||S||!_.all().length)return;S=!0;const c=i.Css.getRule(".gjsf-input");(!c||!Object.keys(((m=c.getStyle)==null?void 0:m.call(c))||{}).length)&&i.Css.addRules(Ke)},M=()=>{if(!s.blocks||d)return;const c=i.Blocks,m=a("blocksCategory"),b=new Set([Ge,...o.map(F=>Ze(F.id))]);c.getAll().filter(F=>String(F.id).startsWith("gjsf-")&&!b.has(F.id)).forEach(F=>c.remove(F.id));const C=(F,P)=>{const be=c.get(F);be?be.set(P):c.add(F,P)};C(Ge,{label:`+ ${a("newFormBlock")}`,category:m,media:Ot,content:{type:Y,gjsfCreate:!0},select:!0}),o.forEach(F=>C(Ze(F.id),{label:F.name,category:m,media:Ot,content:{type:Y,formId:F.id},select:!0}))},L=()=>{if(d)return;k(),M();const c=i.getSelected();(c==null?void 0:c.get("type"))===Y&&_.refreshTraits(c),v(oe.forms,o)},R=async()=>(o=(await n.listForms()).map(q),L(),r==null||r.setForms(!0),j(),o),J=()=>[{id:K(),type:"text",name:"name",label:a("defaultName"),required:!0,autocomplete:"name",width:"1/2"},{id:K(),type:"email",name:"email",label:a("defaultEmail"),required:!0,autocomplete:"email",width:"1/2"},{id:K(),type:"textarea",name:"message",label:a("defaultMessage"),rows:5}],te=c=>({id:c.id,name:c.name,fields:c.fields,settings:c.settings,...c.attrs?{attrs:c.attrs}:{}}),X=c=>{const m=q(c);o=p(m.id)?o.map(b=>b.id===m.id?m:b):[...o,m]},se=async(c={})=>{const m=a("defaultFormName");let b=o.length+1;for(;o.some(P=>P.name===`${m} ${b}`);)b++;const C=q({id:c.id||De(),name:c.name||`${m} ${b}`,fields:c.fields||J(),settings:c.settings||{},attrs:c.attrs}),F=await n.saveForm(te(C));return X(F),L(),r==null||r.setForms(),v(oe.saved,p(F.id)),p(F.id)},V=new Map;let E=null;const A=async()=>{E&&clearTimeout(E),E=null;const c=[...V.values()];V.clear();for(const m of c){const b=p(m.id);r==null||r.flash(a("saving"));try{const C=await n.saveForm(te(q(m)),(b==null?void 0:b.version)??null);X(C),r==null||r.flash(a("saved")),v(oe.saved,p(C.id)),_.rebuildAll(C.id)}catch(C){if(C instanceof Ee){const F=await n.getForm(m.id).catch(()=>{});F&&X(F),r==null||r.setForms(!0),r==null||r.flash(a("conflict"),!0),_.rebuildAll(m.id)}else throw C}}c.length&&L(),r==null||r.setForms()},ie=c=>{const m=p(c.id);m&&X({...I(c),version:m.version,updatedAt:m.updatedAt}),V.set(c.id,I(c)),E&&clearTimeout(E),E=setTimeout(()=>void A().catch(O),s.autosaveDelay)},ce=async(c,m)=>{V.has(c)&&await A();const b=p(c);if(!b)throw new Error(`grapesjs-forms: no form ${c}`);return V.set(c,q({...I(b),...I(m),id:c})),await A(),p(c)},he=async c=>{V.delete(c),await n.deleteForm(c),o=o.filter(m=>m.id!==c),L(),r==null||r.setForms(),_.rebuildAll(c),v(oe.removed,c)},ne=async c=>{V.has(c)&&await A();const m=p(c);if(!m)throw new Error(`grapesjs-forms: no form ${c}`);return se({name:ee(a("copyOf"),m.name),fields:I(m.fields).map(b=>({...b,id:K()})),settings:I(m.settings),attrs:m.attrs&&I(m.attrs)})},et=async(c,m)=>{const b=!Array.isArray(m.fields)&&(Array.isArray(m.pages)||Array.isArray(m.elements)||Array.isArray(m.questions));let C,F=[];if(b){const P=Ve(m,c);C=P.form,F=P.skipped}else C=q({...m,id:c});return await ce(c,{name:C.name,fields:C.fields,settings:C.settings,attrs:C.attrs}),F},Ss=()=>{var C;const c=[];try{const F=i.Canvas.getDocument();F==null||F.querySelectorAll('link[rel="stylesheet"]').forEach(P=>P.href&&c.push(P.href))}catch{}const m=(C=i.getConfig().canvas)==null?void 0:C.styles;(Array.isArray(m)?m:[]).forEach(F=>{const P=typeof F=="string"?F:F==null?void 0:F.href;P&&!c.includes(P)&&c.push(P)});let b="";try{b=i.getCss()||""}catch{b=""}return s.baseCss&&!/\.gjsf-form\s*\{/.test(b)&&(b=Ke+b),{css:b,links:c}},Es=()=>new bs({t:a,forms:()=>o,form:p,create:()=>se(),duplicate:ne,remove:he,change:ie,defaultAction:c=>s.submitUrl?ze(s.submitUrl,c.id):"",previewHtml:c=>$e(q(c),{action:"",ctx:{page:u},texts:H(),codes:W(),key:"preview"}),previewStyles:Ss,submit:async(c,m,b)=>{V.has(c)&&await A();const C=await n.submit(c,m,{...b||{},...B()?{pageId:B()}:{}});return v(oe.submitted,{formId:c,result:C}),C},submissions:(c,m)=>n.listSubmissions?n.listSubmissions(c,m):null,deleteSubmission:(c,m)=>{var b;return((b=n.deleteSubmission)==null?void 0:b.call(n,c,m))??Promise.resolve()},applyJson:et,exportSurveyJs:c=>qe(p(c)||q({id:c})),onError:O}),ge=c=>{var b;if(d)return;s.injectCss&&Tt(),r||(r=Es()),r.show(c||null);const m=i.Modal;m.open({title:a("forms"),content:r.root,attributes:{class:"gjsf-modal"}}),(b=m.onceClose)==null||b.call(m,()=>{A().catch(O)})},_s=()=>{var c,m;r&&((m=(c=i.Modal).isOpen)!=null&&m.call(c))&&i.Modal.close()};i.Commands.add(me.open,{run(c,m,b={}){ge(b==null?void 0:b.id)}}),i.Commands.add(me.edit,{run(c,m,b={}){var P,be;const C=(b==null?void 0:b.component)||((P=b==null?void 0:b.trait)==null?void 0:P.target)||c.getSelected(),F=(b==null?void 0:b.id)||(((be=C==null?void 0:C.get)==null?void 0:be.call(C,"type"))===Y?String(C.get("formId")||""):"");ge(F||null)}});const ks={store:n,list:()=>o,get:c=>p(c),reload:R,create:se,update:ce,remove:he,duplicate:ne,open:c=>ge(c),close:_s,actionOf:D,html:(c,m={})=>{const b=p(c);if(!b)throw new Error(`grapesjs-forms: no form ${c}`);return $e(b,{action:D(b),ctx:{page:u},texts:H(),codes:W(),pageId:B(),...m})},submit:async(c,m,b)=>(V.has(c)&&await A(),n.submit(c,m,b)),rebuild:c=>_.rebuildAll(c||null),importSurveyJs:async(c,m)=>{if(m){const F=await et(m,c);return{form:p(m),skipped:F}}const b=Ve(c,De());return{form:await se({id:b.form.id,name:b.form.name,fields:b.form.fields,settings:b.form.settings}),skipped:b.skipped}},exportSurveyJs:c=>{const m=p(c);if(!m)throw new Error(`grapesjs-forms: no form ${c}`);return qe(m)},flush:A};t.Forms=ks,h("pages-manager:open",c=>{u=c&&typeof c=="object"?{...c}:null,setTimeout(()=>{j(),w()},0)}),h("pages-manager:detach",()=>{u=null}),h("component:add",c=>{var m;((m=c==null?void 0:c.get)==null?void 0:m.call(c,"type"))===Y&&setTimeout(w,0)});const Cs=()=>{const c=i.Panels,m=c.getPanel(s.panelId||"options")||c.getPanel("options")||c.getPanel("commands");if(m){c.addButton(m.id,{id:We,label:Lt(18),command:me.open,togglable:!1,attributes:{title:a("forms")}}),y.push(()=>{try{c.removeButton(m.id,We)}catch{}});return}const b=i.getContainer();if(!b)return;s.injectCss&&Tt();const C=f("button",{class:"gjsf-toggle",type:"button",title:a("forms"),onclick:()=>ge()});C.innerHTML=Lt(14),getComputedStyle(b).position==="static"&&(b.style.position="relative"),b.appendChild(C),y.push(()=>C.remove())};h("i18n:locale i18n:update",()=>setTimeout(()=>{var m,b;if(d)return;M();const c=i.getSelected();(c==null?void 0:c.get("type"))===Y&&_.refreshTraits(c),r&&((b=(m=i.Modal).isOpen)!=null&&b.call(m))&&r.render()},0));const tt=()=>{d||(d=!0,E&&clearTimeout(E),_.destroy(),r==null||r.destroy(),y.splice(0).forEach(c=>c()),t.__gjsfCleanup===tt&&delete t.__gjsfCleanup)};t.__gjsfCleanup=tt;const As=ss(i,Qe,()=>It(s),c=>{var m;"autosaveDelay"in c&&(s.autosaveDelay=Xe({autosaveDelay:c.autosaveDelay}).autosaveDelay),"submitUrl"in c&&(s.submitUrl=c.submitUrl||((m=s.rest)==null?void 0:m.url)||null,_.rebuildAll(null))});h("destroy",As),h("destroy",tt);const Mt=()=>void A().catch(wt);window.addEventListener("beforeunload",Mt),y.push(()=>window.removeEventListener("beforeunload",Mt)),i.onReady(()=>{d||(Cs(),R().then(async()=>{var b;const c=l();c!=null&&c.whenReady&&await c.whenReady();const m=(b=c==null?void 0:c.getActiveId)==null?void 0:b.call(c);c&&m&&!u&&(u=await c.store.get(m).catch(()=>{})||null),d||(j(),w())}).catch(O))})}const Nt="grapesjs-forms",$t="0.1.0",Qe={id:Nt,version:$t,title:"Forms",description:"A form editor of its own; a form is a component styled by the site; submissions go to a REST API.",options:[{key:"rest",type:"json",default:null,title:"REST backend",description:'{ "url": "/api/forms-admin" } (openapi.yaml); null — IndexedDB in the browser.'},{key:"submitUrl",type:"string",default:"",title:"Submit URL of the site",description:"Base the published forms post to (<url>/forms/<id>/submissions). Empty — rest.url.",live:!0},{key:"dbName",type:"string",default:"gjs-forms",title:"IndexedDB database",advanced:!0},{key:"autosaveDelay",type:"number",default:600,title:"Autosave delay, ms",live:!0},{key:"blocks",type:"boolean",default:!0,title:"Blocks of the forms"},{key:"baseCss",type:"boolean",default:!0,title:"Base form styles",description:"Adds a small stylesheet for forms to the project CSS once."},{key:"panelId",type:"string",default:"",title:'Panel of the "Forms" button',description:"Empty — options.",advanced:!0},{key:"labels",type:"json",default:{},title:"Texts",advanced:!0},{key:"injectCss",type:"boolean",default:!0,title:"Inject CSS",advanced:!0}]};function It(i){return{rest:i.rest?{url:i.rest.url,...i.rest.credentials?{credentials:i.rest.credentials}:{}}:null,submitUrl:i.submitUrl||"",dbName:i.dbName,autosaveDelay:i.autosaveDelay,blocks:i.blocks,baseCss:i.baseCss,panelId:i.panelId||"",labels:i.labels,injectCss:i.injectCss}}const Rt=es(js,Qe);function ws(i=document){let e=0;return i.querySelectorAll("form[data-gjsf-form]").forEach(t=>{t.__gjsf||(we.call(t),e++)}),e}g.BASE_FORM_CSS=Ke,g.CHOICE_TYPES=pe,g.CLS=T,g.COMMANDS=me,g.CONTENT_TYPES=de,g.ConflictError=Ee,g.DOM_EVENTS=rs,g.EVENTS=oe,g.FIELD_TYPES=at,g.FORM_ATTR=ue,g.FORM_TYPE=Y,g.FormComponents=vt,g.HONEYPOT=je,g.I18N_NS=Me,g.INPUT_TYPES=ye,g.IndexedDbFormStore=He,g.META=Qe,g.MemoryFormStore=Ue,g.NAME_RE=ot,g.NEW_BLOCK_ID=Ge,g.PANEL_BUTTON_ID=We,g.PART_ATTR=Ie,g.PART_TYPE=Se,g.PLACEHOLDERS=nt,g.PLUGIN_ID=Nt,g.RANGE_TYPES=rt,g.RestFormStore=_t,g.SUPPORTED_LOCALES=jt,g.StoreError=Z,g.TEXT_LIKE=ve,g.TOKEN_RE=U,g.VERSION=$t,g.WIDTHS=ke,g.blockIdOf=Ze,g.buildChildren=Oe,g.cleanAttrs=xe,g.default=Rt,g.elHtml=Ne,g.enhanceForms=ws,g.fieldId=K,g.fieldName=G,g.fieldTitle=Fe,g.formAttrs=Le,g.formHtml=$e,g.formScript=we,g.formsPlugin=Rt,g.fromSurveyJs=Ve,g.getForms=vs,g.hasOptions=_e,g.hasTokens=it,g.inputFields=Ae,g.isContent=N,g.isSafeUrl=Ce,g.locales=Pe,g.normalizeField=ct,g.normalizeFields=dt,g.normalizeForm=q,g.normalizeOptions=lt,g.normalizeSettings=pt,g.publicOptions=It,g.resolveBuild=st,g.resolveOptions=Xe,g.submitUrlOf=ze,g.toComponent=Re,g.toCsv=Ct,g.toSurveyJs=qe,g.uniqueName=Q,g.validateSubmission=mt,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
103
|
+
//# sourceMappingURL=grapesjs-forms.umd.cjs.map
|