react-minimal-survey-builder 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/LICENSE +21 -0
- package/README.md +435 -0
- package/dist/builder/index.d.mts +31 -0
- package/dist/builder/index.d.ts +31 -0
- package/dist/builder/index.js +1 -0
- package/dist/builder/index.mjs +1 -0
- package/dist/chunk-5CMRPHVX.mjs +1 -0
- package/dist/chunk-JWOXQRNV.js +1 -0
- package/dist/chunk-M6YT7KIF.js +1 -0
- package/dist/chunk-Q5PYPUG5.js +1 -0
- package/dist/chunk-RZFNCNBO.mjs +1 -0
- package/dist/chunk-YTSJTAP2.mjs +1 -0
- package/dist/core/index.d.mts +111 -0
- package/dist/core/index.d.ts +111 -0
- package/dist/core/index.js +1 -0
- package/dist/core/index.mjs +1 -0
- package/dist/index-Q8KHOfHv.d.mts +192 -0
- package/dist/index-Q8KHOfHv.d.ts +192 -0
- package/dist/index.d.mts +124 -0
- package/dist/index.d.ts +124 -0
- package/dist/index.js +1 -0
- package/dist/index.mjs +1 -0
- package/package.json +62 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkJWOXQRNV_js=require('./chunk-JWOXQRNV.js'),react=require('react'),jsxRuntime=require('react/jsx-runtime');function ce(e,r={}){let o=react.useRef(r);o.current=r;let t=react.useMemo(()=>chunkJWOXQRNV_js.a(e),[e]),d=react.useMemo(()=>{let s={};for(let x of chunkJWOXQRNV_js.b(t))x.defaultValue!==void 0&&(s[x.id]=x.defaultValue);return {...s,...r.initialAnswers}},[t]),[i,a]=react.useState(d),[l,u]=react.useState([]),[m,g]=react.useState(0),[p,b]=react.useState(false),c=react.useMemo(()=>chunkJWOXQRNV_js.j(t,i),[t,i]),P=react.useMemo(()=>chunkJWOXQRNV_js.k(t,i),[t,i]),Q=react.useCallback((s,x)=>{a(I=>{let A={...I,[s]:x};return o.current.onChange?.(A,s),A}),u(I=>I.filter(A=>A.questionId!==s));},[]),D=react.useCallback(s=>{a(x=>({...x,...s}));},[]),$=react.useCallback(()=>{let s=chunkJWOXQRNV_js.h(t,i,c);return u(s),o.current.onValidate?.(s),s},[t,i,c]),G=react.useCallback(()=>{let s=chunkJWOXQRNV_js.g(t,m,i,c);return u(s),s},[t,m,i,c]),M=react.useCallback(s=>l.find(x=>x.questionId===s)?.message,[l]),w=t.pages.length,V=m<w-1,L=m>0,H=react.useCallback(()=>{if(m>=w-1)return false;if(t.settings?.validateOnPageChange){let x=chunkJWOXQRNV_js.g(t,m,i,c);if(x.length>0)return u(x),false}let s=m+1;return g(s),u([]),o.current.onPageChange?.(s),true},[m,w,t,i,c]),B=react.useCallback(()=>{if(m<=0||!t.settings?.allowBack)return false;let s=m-1;return g(s),u([]),o.current.onPageChange?.(s),true},[m,t.settings?.allowBack]),W=react.useCallback(s=>s<0||s>=w?false:(g(s),u([]),o.current.onPageChange?.(s),true),[w]),T=react.useCallback(()=>chunkJWOXQRNV_js.b(t).filter(s=>c.has(s.id)),[t,c]),n=react.useCallback(s=>{let x=t.pages[s];return x?chunkJWOXQRNV_js.l(x,i):[]},[t,i]),y=react.useCallback(async()=>{let s=chunkJWOXQRNV_js.h(t,i,c);if(s.length>0)return u(s),{success:false,errors:s};try{return await o.current.onSubmit?.(i),b(!0),{success:!0,errors:[]}}catch(x){let I={questionId:"__submit__",message:x instanceof Error?x.message:"Submission failed",rule:"custom"};return u([I]),{success:false,errors:[I]}}},[t,i,c]),C=react.useCallback(()=>{a(d),u([]),g(0),b(false);},[d]),Y=react.useMemo(()=>{let s=chunkJWOXQRNV_js.b(t).filter(I=>c.has(I.id));if(s.length===0)return 100;let x=s.filter(I=>{let A=i[I.id];return A!=null&&A!==""&&!(Array.isArray(A)&&A.length===0)}).length;return Math.round(x/s.length*100)},[t,i,c]),K=l.length===0;return {survey:t,answers:i,setAnswer:Q,setAnswers:D,errors:l,getError:M,isValid:K,validate:$,validateCurrentPage:G,getVisibleQuestions:T,getPageQuestions:n,visiblePages:P,currentPageIndex:m,totalPages:w,hasNextPage:V,hasPrevPage:L,nextPage:H,prevPage:B,goToPage:W,submit:y,isSubmitted:p,reset:C,progress:Y}}var ae=({question:e,value:r,onChange:o,error:t,disabled:d})=>jsxRuntime.jsx("input",{type:e.type==="email"?"email":e.type==="number"?"number":"text",id:e.id,value:r??"",onChange:i=>o(i.target.value),placeholder:e.placeholder,disabled:d,"aria-invalid":!!t,"aria-describedby":t?`${e.id}-error`:void 0,style:q}),Ce=({question:e,value:r,onChange:o,error:t,disabled:d})=>jsxRuntime.jsx("textarea",{id:e.id,value:r??"",onChange:i=>o(i.target.value),placeholder:e.placeholder,disabled:d,rows:4,"aria-invalid":!!t,"aria-describedby":t?`${e.id}-error`:void 0,style:{...q,resize:"vertical"}}),Ie=({question:e,value:r,onChange:o,disabled:t})=>jsxRuntime.jsx("div",{role:"radiogroup","aria-labelledby":`${e.id}-label`,style:{display:"flex",flexDirection:"column",gap:"8px"},children:e.options?.map(d=>jsxRuntime.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:t?"default":"pointer"},children:[jsxRuntime.jsx("input",{type:"radio",name:e.id,value:d.value,checked:r===d.value,onChange:()=>o(d.value),disabled:t}),jsxRuntime.jsx("span",{children:d.label})]},d.value))}),Re=({question:e,value:r,onChange:o,disabled:t})=>{let d=Array.isArray(r)?r:[],i=a=>{let l=d.includes(a)?d.filter(u=>u!==a):[...d,a];o(l);};return jsxRuntime.jsx("div",{role:"group","aria-labelledby":`${e.id}-label`,style:{display:"flex",flexDirection:"column",gap:"8px"},children:e.options?.map(a=>jsxRuntime.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:t?"default":"pointer"},children:[jsxRuntime.jsx("input",{type:"checkbox",value:a.value,checked:d.includes(a.value),onChange:()=>i(a.value),disabled:t}),jsxRuntime.jsx("span",{children:a.label})]},a.value))})},Ee=({question:e,value:r,onChange:o,error:t,disabled:d})=>jsxRuntime.jsxs("select",{id:e.id,value:r??"",onChange:i=>o(i.target.value),disabled:d,"aria-invalid":!!t,"aria-describedby":t?`${e.id}-error`:void 0,style:q,children:[jsxRuntime.jsx("option",{value:"",children:e.placeholder??"Select..."}),e.options?.map(i=>jsxRuntime.jsx("option",{value:i.value,children:i.label},i.value))]}),Qe=({question:e,value:r,onChange:o,error:t,disabled:d})=>jsxRuntime.jsx("input",{type:"date",id:e.id,value:r??"",onChange:i=>o(i.target.value),disabled:d,"aria-invalid":!!t,"aria-describedby":t?`${e.id}-error`:void 0,style:q}),we=({question:e,value:r,onChange:o,disabled:t})=>{let d=e.meta?.max??5;return jsxRuntime.jsx("div",{style:{display:"flex",gap:"4px"},children:Array.from({length:d},(i,a)=>a+1).map(i=>jsxRuntime.jsx("button",{type:"button",onClick:()=>o(i),disabled:t,"aria-label":`Rate ${i} of ${d}`,style:{background:(r??0)>=i?"#fbbf24":"#e5e7eb",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:t?"default":"pointer",fontSize:"16px"},children:"\u2605"},i))})},Te={text:ae,email:ae,number:ae,textarea:Ce,radio:Ie,checkbox:Re,select:Ee,date:Qe,rating:we},ie=react.memo(({question:e,value:r,onChange:o,error:t,disabled:d=false,components:i={},className:a,hideLabel:l=false,questionNumber:u})=>{let m=i[e.type]??Te[e.type];return m?jsxRuntime.jsxs("div",{className:a,style:{marginBottom:"20px"},"data-question-id":e.id,"data-question-type":e.type,children:[!l&&jsxRuntime.jsxs("label",{id:`${e.id}-label`,htmlFor:e.id,style:{display:"block",marginBottom:"6px",fontWeight:500,fontSize:"14px"},children:[u!==void 0&&jsxRuntime.jsxs("span",{style:{marginRight:"4px",color:"#6b7280"},children:[u,"."]}),e.label,e.required&&jsxRuntime.jsx("span",{style:{color:"#ef4444",marginLeft:"4px"},"aria-label":"required",children:"*"})]}),e.description&&jsxRuntime.jsx("p",{style:{margin:"0 0 8px",fontSize:"13px",color:"#6b7280"},children:e.description}),jsxRuntime.jsx(m,{question:e,value:r,onChange:o,error:t,disabled:d}),t&&jsxRuntime.jsx("p",{id:`${e.id}-error`,role:"alert",style:{margin:"4px 0 0",fontSize:"13px",color:"#ef4444"},children:t})]}):jsxRuntime.jsxs("div",{style:{color:"#ef4444",padding:"8px",border:"1px solid #ef4444",borderRadius:"4px"},children:['Unknown question type: "',e.type,'"']})});ie.displayName="QuestionRenderer";var q={width:"100%",padding:"8px 12px",fontSize:"14px",border:"1px solid #d1d5db",borderRadius:"6px",outline:"none",boxSizing:"border-box",fontFamily:"inherit"};var ee=react.memo(({schema:e,options:r,components:o,className:t,children:d,disabled:i=false,renderHeader:a,renderFooter:l,renderComplete:u})=>{let m=ce(e,r),{survey:g,answers:p,setAnswer:b,errors:c,getError:P,currentPageIndex:Q,totalPages:D,hasNextPage:$,hasPrevPage:G,nextPage:M,prevPage:w,submit:V,isSubmitted:L,isValid:H,progress:B,getPageQuestions:W}=m,T=g.pages[Q],n=react.useMemo(()=>W(Q),[W,Q]),y=Q===D-1,C=react.useCallback(s=>{s?.preventDefault(),V();},[V]);if(d)return jsxRuntime.jsx(jsxRuntime.Fragment,{children:d(m)});if(L)return u?jsxRuntime.jsx(jsxRuntime.Fragment,{children:u()}):jsxRuntime.jsxs("div",{style:{textAlign:"center",padding:"40px 20px"},children:[jsxRuntime.jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"\u2713"}),jsxRuntime.jsx("h2",{style:{margin:"0 0 8px",fontSize:"20px",fontWeight:600},children:"Thank you!"}),jsxRuntime.jsx("p",{style:{margin:0,color:"#6b7280"},children:"Your response has been submitted."})]});let Y=g.settings?.showQuestionNumbers??true,K=0;if(Y)for(let s=0;s<Q;s++)K+=g.pages[s].questions.length;return jsxRuntime.jsxs("form",{className:t,onSubmit:C,noValidate:true,style:{maxWidth:"640px",margin:"0 auto",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:[a?a({title:g.title,description:g.description,progress:B,currentPage:Q+1,totalPages:D}):jsxRuntime.jsxs("div",{style:{marginBottom:"24px"},children:[g.title&&jsxRuntime.jsx("h1",{style:{margin:"0 0 4px",fontSize:"24px",fontWeight:700},children:g.title}),g.description&&jsxRuntime.jsx("p",{style:{margin:"0 0 12px",color:"#6b7280",fontSize:"14px"},children:g.description}),g.settings?.showProgress&&D>1&&jsxRuntime.jsxs("div",{style:{marginBottom:"16px"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"12px",color:"#6b7280",marginBottom:"4px"},children:[jsxRuntime.jsxs("span",{children:["Page ",Q+1," of ",D]}),jsxRuntime.jsxs("span",{children:[B,"% complete"]})]}),jsxRuntime.jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden"},children:jsxRuntime.jsx("div",{style:{width:`${B}%`,height:"100%",backgroundColor:"#3b82f6",borderRadius:"2px",transition:"width 0.3s ease"}})})]}),T?.title&&jsxRuntime.jsx("h2",{style:{margin:"0 0 4px",fontSize:"18px",fontWeight:600},children:T.title}),T?.description&&jsxRuntime.jsx("p",{style:{margin:"0 0 8px",color:"#6b7280",fontSize:"13px"},children:T.description})]}),n.map((s,x)=>jsxRuntime.jsx(ie,{question:s,value:p[s.id],onChange:I=>b(s.id,I),error:P(s.id),disabled:i,components:o,questionNumber:Y?K+x+1:void 0},s.id)),l?l({hasPrevPage:G,hasNextPage:$,isLastPage:y,prevPage:w,nextPage:()=>M(),submit:()=>V(),isValid:H}):jsxRuntime.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"24px",gap:"12px"},children:[G&&g.settings?.allowBack?jsxRuntime.jsx("button",{type:"button",onClick:w,style:Oe,children:g.settings?.prevText??"Previous"}):jsxRuntime.jsx("div",{}),y?jsxRuntime.jsx("button",{type:"submit",style:ge,children:g.settings?.submitText??"Submit"}):jsxRuntime.jsx("button",{type:"button",onClick:()=>M(),style:ge,children:g.settings?.nextText??"Next"})]}),c.some(s=>s.questionId==="__submit__")&&jsxRuntime.jsx("p",{role:"alert",style:{color:"#ef4444",fontSize:"14px",marginTop:"12px"},children:c.find(s=>s.questionId==="__submit__")?.message})]})});ee.displayName="SurveyRenderer";var ge={padding:"10px 24px",fontSize:"14px",fontWeight:600,color:"#fff",backgroundColor:"#3b82f6",border:"none",borderRadius:"6px",cursor:"pointer",fontFamily:"inherit"},Oe={padding:"10px 24px",fontSize:"14px",fontWeight:600,color:"#374151",backgroundColor:"#f3f4f6",border:"1px solid #d1d5db",borderRadius:"6px",cursor:"pointer",fontFamily:"inherit"};function me(e){let r=e??{id:chunkJWOXQRNV_js.d("survey"),title:"Untitled Survey",pages:[{id:chunkJWOXQRNV_js.d("page"),title:"Page 1",questions:[]}]};return {schema:r,selectedQuestionId:null,selectedPageId:r.pages[0]?.id??null,isDragging:false}}function be(e,r){switch(r.type){case "SET_SCHEMA":return {...e,schema:r.payload};case "ADD_PAGE":{let o={id:chunkJWOXQRNV_js.d("page"),title:`Page ${e.schema.pages.length+1}`,questions:[],...r.payload};return {...e,schema:{...e.schema,pages:[...e.schema.pages,o]},selectedPageId:o.id}}case "REMOVE_PAGE":{let o=e.schema.pages.filter(t=>t.id!==r.payload.pageId);return o.length===0?e:{...e,schema:{...e.schema,pages:o},selectedPageId:o[0].id,selectedQuestionId:null}}case "UPDATE_PAGE":return {...e,schema:{...e.schema,pages:e.schema.pages.map(o=>o.id===r.payload.pageId?{...o,...r.payload.updates}:o)}};case "ADD_QUESTION":{let o={id:chunkJWOXQRNV_js.d("q"),type:"text",label:"New Question",required:false,options:[],validation:[],...r.payload.question};return {...e,schema:{...e.schema,pages:e.schema.pages.map(t=>t.id===r.payload.pageId?{...t,questions:[...t.questions,o]}:t)},selectedQuestionId:o.id}}case "REMOVE_QUESTION":return {...e,schema:{...e.schema,pages:e.schema.pages.map(o=>o.id===r.payload.pageId?{...o,questions:o.questions.filter(t=>t.id!==r.payload.questionId)}:o)},selectedQuestionId:e.selectedQuestionId===r.payload.questionId?null:e.selectedQuestionId};case "UPDATE_QUESTION":return {...e,schema:{...e.schema,pages:e.schema.pages.map(o=>o.id===r.payload.pageId?{...o,questions:o.questions.map(t=>t.id===r.payload.questionId?{...t,...r.payload.updates}:t)}:o)}};case "REORDER_QUESTIONS":return {...e,schema:{...e.schema,pages:e.schema.pages.map(o=>{if(o.id!==r.payload.pageId)return o;let t=[...o.questions],[d]=t.splice(r.payload.fromIndex,1);return t.splice(r.payload.toIndex,0,d),{...o,questions:t}})}};case "REORDER_PAGES":{let o=[...e.schema.pages],[t]=o.splice(r.payload.fromIndex,1);return o.splice(r.payload.toIndex,0,t),{...e,schema:{...e.schema,pages:o}}}case "MOVE_QUESTION":{let o=null,t=e.schema.pages.map(i=>{if(i.id!==r.payload.fromPageId)return i;let a=[...i.questions];return [o]=a.splice(r.payload.fromIndex,1),{...i,questions:a}});if(!o)return e;let d=t.map(i=>{if(i.id!==r.payload.toPageId)return i;let a=[...i.questions];return a.splice(r.payload.toIndex,0,o),{...i,questions:a}});return {...e,schema:{...e.schema,pages:d}}}case "SELECT_QUESTION":return {...e,selectedQuestionId:r.payload.questionId};case "SELECT_PAGE":return {...e,selectedPageId:r.payload.pageId,selectedQuestionId:null};case "SET_DRAGGING":return {...e,isDragging:r.payload};default:return e}}var Ne=[{value:"text",label:"Text Input"},{value:"textarea",label:"Textarea"},{value:"number",label:"Number"},{value:"email",label:"Email"},{value:"radio",label:"Radio Group"},{value:"checkbox",label:"Checkbox Group"},{value:"select",label:"Dropdown"},{value:"date",label:"Date"},{value:"rating",label:"Rating"}],fe=["radio","checkbox","select"],se=react.memo(({question:e,pageId:r,onUpdate:o,onDelete:t})=>{let[d,i]=react.useState(false),a=fe.includes(e.type),l=react.useCallback(p=>{o(e.id,r,p);},[o,e.id,r]),u=react.useCallback(()=>{let p=[...e.options??[]],b=p.length+1;p.push({label:`Option ${b}`,value:`option_${b}`}),l({options:p});},[e.options,l]),m=react.useCallback((p,b,c)=>{let P=[...e.options??[]];P[p]={...P[p],[b]:c},l({options:P});},[e.options,l]),g=react.useCallback(p=>{let b=[...e.options??[]];b.splice(p,1),l({options:b});},[e.options,l]);return jsxRuntime.jsxs("div",{style:Ve,children:[jsxRuntime.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"12px"},children:[jsxRuntime.jsx("span",{style:{fontSize:"12px",color:"#9ca3af",fontFamily:"monospace"},children:e.id}),jsxRuntime.jsx("button",{type:"button",onClick:()=>t(e.id,r),style:xe,title:"Delete question",children:"\u2715"})]}),jsxRuntime.jsxs("div",{style:_,children:[jsxRuntime.jsx("label",{style:U,children:"Question Label"}),jsxRuntime.jsx("input",{type:"text",value:e.label,onChange:p=>l({label:p.target.value}),style:z,placeholder:"Enter question label"})]}),jsxRuntime.jsxs("div",{style:_,children:[jsxRuntime.jsx("label",{style:U,children:"Type"}),jsxRuntime.jsx("select",{value:e.type,onChange:p=>{let b=p.target.value,c={type:b};fe.includes(b)&&(!e.options||e.options.length===0)&&(c.options=[{label:"Option 1",value:"option_1"},{label:"Option 2",value:"option_2"}]),l(c);},style:z,children:Ne.map(p=>jsxRuntime.jsx("option",{value:p.value,children:p.label},p.value))})]}),jsxRuntime.jsxs("div",{style:{..._,flexDirection:"row",alignItems:"center",gap:"8px"},children:[jsxRuntime.jsx("input",{type:"checkbox",id:`${e.id}-required`,checked:e.required??false,onChange:p=>l({required:p.target.checked})}),jsxRuntime.jsx("label",{htmlFor:`${e.id}-required`,style:{fontSize:"13px",cursor:"pointer"},children:"Required"})]}),a&&jsxRuntime.jsxs("div",{style:_,children:[jsxRuntime.jsx("label",{style:U,children:"Options"}),e.options?.map((p,b)=>jsxRuntime.jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",alignItems:"center"},children:[jsxRuntime.jsx("input",{type:"text",value:p.label,onChange:c=>m(b,"label",c.target.value),placeholder:"Label",style:{...z,flex:1}}),jsxRuntime.jsx("input",{type:"text",value:p.value,onChange:c=>m(b,"value",c.target.value),placeholder:"Value",style:{...z,flex:1}}),jsxRuntime.jsx("button",{type:"button",onClick:()=>g(b),style:{...xe,fontSize:"14px"},title:"Remove option",children:"\u2715"})]},b)),jsxRuntime.jsx("button",{type:"button",onClick:u,style:Be,children:"+ Add Option"})]}),jsxRuntime.jsx("button",{type:"button",onClick:()=>i(!d),style:{background:"none",border:"none",color:"#3b82f6",fontSize:"13px",cursor:"pointer",padding:"4px 0",fontFamily:"inherit"},children:d?"\u25BE Hide Advanced":"\u25B8 Show Advanced"}),d&&jsxRuntime.jsxs("div",{style:{marginTop:"8px"},children:[jsxRuntime.jsxs("div",{style:_,children:[jsxRuntime.jsx("label",{style:U,children:"Description"}),jsxRuntime.jsx("input",{type:"text",value:e.description??"",onChange:p=>l({description:p.target.value||void 0}),style:z,placeholder:"Optional helper text"})]}),jsxRuntime.jsxs("div",{style:_,children:[jsxRuntime.jsx("label",{style:U,children:"Placeholder"}),jsxRuntime.jsx("input",{type:"text",value:e.placeholder??"",onChange:p=>l({placeholder:p.target.value||void 0}),style:z,placeholder:"Input placeholder"})]}),jsxRuntime.jsxs("div",{style:_,children:[jsxRuntime.jsx("label",{style:U,children:"Visible If (condition)"}),jsxRuntime.jsx("input",{type:"text",value:e.visibleIf??"",onChange:p=>l({visibleIf:p.target.value||void 0}),style:{...z,fontFamily:"monospace",fontSize:"12px"},placeholder:"{q1} === 'yes'"}),jsxRuntime.jsxs("span",{style:{fontSize:"11px",color:"#9ca3af"},children:["Use ","{questionId}"," to reference other answers"]})]}),jsxRuntime.jsxs("div",{style:_,children:[jsxRuntime.jsx("label",{style:U,children:"Default Value"}),jsxRuntime.jsx("input",{type:"text",value:String(e.defaultValue??""),onChange:p=>l({defaultValue:p.target.value||void 0}),style:z,placeholder:"Default answer"})]})]})]})});se.displayName="QuestionEditor";var Ve={padding:"16px",border:"1px solid #e5e7eb",borderRadius:"8px",backgroundColor:"#fff"},_={display:"flex",flexDirection:"column",marginBottom:"12px"},U={fontSize:"12px",fontWeight:600,color:"#374151",marginBottom:"4px",textTransform:"uppercase",letterSpacing:"0.5px"},z={padding:"6px 10px",fontSize:"13px",border:"1px solid #d1d5db",borderRadius:"4px",outline:"none",fontFamily:"inherit",boxSizing:"border-box"},xe={background:"none",border:"none",color:"#ef4444",cursor:"pointer",fontSize:"16px",padding:"2px 6px",borderRadius:"4px",lineHeight:1},Be={background:"none",border:"1px dashed #d1d5db",borderRadius:"4px",padding:"6px 12px",fontSize:"13px",color:"#6b7280",cursor:"pointer",width:"100%",fontFamily:"inherit"};var Me=react.memo(({value:e,onChange:r,className:o,showPreview:t=true,showJson:d=false,layout:i="horizontal"})=>{let[a,l]=react.useReducer(be,e,n=>me(n)),[u,m]=react.useState("editor"),g=react.useRef(null),p=react.useRef(null),b=react.useRef(e);react.useEffect(()=>{e&&e!==b.current&&(l({type:"SET_SCHEMA",payload:e}),b.current=e);},[e]);let c=react.useRef(a.schema);react.useEffect(()=>{a.schema!==c.current&&(r?.(a.schema),c.current=a.schema);},[a.schema,r]);let P=react.useMemo(()=>a.schema.pages.find(n=>n.id===a.selectedPageId)??a.schema.pages[0],[a.schema.pages,a.selectedPageId]),Q=react.useCallback(n=>{l({type:"ADD_QUESTION",payload:{pageId:n}});},[]),D=react.useCallback((n,y,C)=>{l({type:"UPDATE_QUESTION",payload:{pageId:y,questionId:n,updates:C}});},[]),$=react.useCallback((n,y)=>{l({type:"REMOVE_QUESTION",payload:{pageId:y,questionId:n}});},[]),G=react.useCallback(n=>{l({type:"SELECT_QUESTION",payload:{questionId:n}});},[]),M=react.useCallback((n,y)=>{g.current={pageId:n,index:y},l({type:"SET_DRAGGING",payload:true});},[]),w=react.useCallback((n,y,C)=>{n.preventDefault(),p.current={pageId:y,index:C};},[]),V=react.useCallback(n=>{n.preventDefault();let y=g.current,C=p.current;y&&C&&(y.pageId===C.pageId?l({type:"REORDER_QUESTIONS",payload:{pageId:y.pageId,fromIndex:y.index,toIndex:C.index}}):l({type:"MOVE_QUESTION",payload:{fromPageId:y.pageId,toPageId:C.pageId,fromIndex:y.index,toIndex:C.index}})),g.current=null,p.current=null,l({type:"SET_DRAGGING",payload:false});},[]),L=react.useCallback(()=>{g.current=null,p.current=null,l({type:"SET_DRAGGING",payload:false});},[]),H=react.useCallback(n=>{l({type:"SET_SCHEMA",payload:{...a.schema,title:n.target.value}});},[a.schema]),B=react.useMemo(()=>JSON.stringify(a.schema,null,2),[a.schema]),W=react.useCallback(n=>{try{let y=JSON.parse(n.target.value);l({type:"SET_SCHEMA",payload:y});}catch{}},[]),T=i==="horizontal";return jsxRuntime.jsxs("div",{className:o,style:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',display:"flex",flexDirection:T?"row":"column",gap:"16px",minHeight:"500px"},children:[jsxRuntime.jsxs("div",{style:{flex:T?"1 1 50%":"auto",minWidth:0,display:"flex",flexDirection:"column"},children:[jsxRuntime.jsx("div",{style:{display:"flex",gap:"0",borderBottom:"1px solid #e5e7eb",marginBottom:"16px"},children:["editor","preview","json"].filter(n=>!(n==="preview"&&!t||n==="json"&&!d)).map(n=>jsxRuntime.jsx("button",{type:"button",onClick:()=>m(n),style:{padding:"8px 16px",fontSize:"13px",fontWeight:u===n?600:400,color:u===n?"#3b82f6":"#6b7280",background:"none",border:"none",borderBottom:u===n?"2px solid #3b82f6":"2px solid transparent",cursor:"pointer",fontFamily:"inherit",textTransform:"capitalize"},children:n},n))}),u==="editor"&&jsxRuntime.jsxs("div",{style:{flex:1,overflow:"auto"},children:[jsxRuntime.jsx("div",{style:{marginBottom:"16px"},children:jsxRuntime.jsx("input",{type:"text",value:a.schema.title??"",onChange:H,placeholder:"Survey Title",style:{width:"100%",padding:"10px 12px",fontSize:"18px",fontWeight:700,border:"1px solid #e5e7eb",borderRadius:"6px",outline:"none",boxSizing:"border-box",fontFamily:"inherit"}})}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"8px",marginBottom:"16px",flexWrap:"wrap",alignItems:"center"},children:[a.schema.pages.map((n,y)=>jsxRuntime.jsx("button",{type:"button",onClick:()=>l({type:"SELECT_PAGE",payload:{pageId:n.id}}),style:{padding:"6px 14px",fontSize:"13px",fontWeight:a.selectedPageId===n.id?600:400,backgroundColor:a.selectedPageId===n.id?"#3b82f6":"#f3f4f6",color:a.selectedPageId===n.id?"#fff":"#374151",border:"none",borderRadius:"16px",cursor:"pointer",fontFamily:"inherit"},children:n.title||`Page ${y+1}`},n.id)),jsxRuntime.jsx("button",{type:"button",onClick:()=>l({type:"ADD_PAGE"}),style:{padding:"6px 14px",fontSize:"13px",backgroundColor:"transparent",color:"#3b82f6",border:"1px dashed #3b82f6",borderRadius:"16px",cursor:"pointer",fontFamily:"inherit"},children:"+ Page"}),a.schema.pages.length>1&&a.selectedPageId&&jsxRuntime.jsx("button",{type:"button",onClick:()=>l({type:"REMOVE_PAGE",payload:{pageId:a.selectedPageId}}),style:{padding:"4px 8px",fontSize:"12px",backgroundColor:"transparent",color:"#ef4444",border:"none",cursor:"pointer",fontFamily:"inherit"},title:"Remove current page",children:"Remove Page"})]}),P&&jsxRuntime.jsx("div",{style:{marginBottom:"12px"},children:jsxRuntime.jsx("input",{type:"text",value:P.title??"",onChange:n=>l({type:"UPDATE_PAGE",payload:{pageId:P.id,updates:{title:n.target.value}}}),placeholder:"Page Title",style:{width:"100%",padding:"6px 10px",fontSize:"14px",border:"1px solid #e5e7eb",borderRadius:"4px",outline:"none",boxSizing:"border-box",fontFamily:"inherit"}})}),jsxRuntime.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[P?.questions.map((n,y)=>jsxRuntime.jsxs("div",{draggable:true,onDragStart:()=>M(P.id,y),onDragOver:C=>w(C,P.id,y),onDrop:V,onDragEnd:L,onClick:()=>G(n.id),style:{cursor:"grab",opacity:a.isDragging?.8:1,border:a.selectedQuestionId===n.id?"2px solid #3b82f6":"1px solid transparent",borderRadius:"10px",transition:"border-color 0.15s ease"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:"#f9fafb",borderRadius:a.selectedQuestionId===n.id?"8px 8px 0 0":"8px",borderBottom:a.selectedQuestionId===n.id?"1px solid #e5e7eb":"none"},children:[jsxRuntime.jsx("span",{style:{color:"#9ca3af",cursor:"grab",userSelect:"none"},children:"\u283F"}),jsxRuntime.jsx("span",{style:{flex:1,fontSize:"14px",fontWeight:500},children:n.label||"Untitled"}),jsxRuntime.jsx("span",{style:{fontSize:"11px",padding:"2px 8px",backgroundColor:"#e5e7eb",borderRadius:"10px",color:"#6b7280"},children:n.type})]}),a.selectedQuestionId===n.id&&jsxRuntime.jsx(se,{question:n,pageId:P.id,onUpdate:D,onDelete:$})]},n.id)),jsxRuntime.jsx("button",{type:"button",onClick:()=>Q(P?.id??a.schema.pages[0].id),style:{padding:"12px",fontSize:"14px",fontWeight:500,color:"#6b7280",backgroundColor:"#fff",border:"2px dashed #d1d5db",borderRadius:"8px",cursor:"pointer",fontFamily:"inherit",transition:"border-color 0.15s ease, color 0.15s ease"},onMouseEnter:n=>{n.currentTarget.style.borderColor="#3b82f6",n.currentTarget.style.color="#3b82f6";},onMouseLeave:n=>{n.currentTarget.style.borderColor="#d1d5db",n.currentTarget.style.color="#6b7280";},children:"+ Add Question"})]})]}),u==="preview"&&t&&jsxRuntime.jsx("div",{style:{flex:1,overflow:"auto",padding:"16px",backgroundColor:"#f9fafb",borderRadius:"8px"},children:jsxRuntime.jsx(ee,{schema:a.schema,options:{onSubmit:n=>console.log("Preview submit:",n)}})}),u==="json"&&jsxRuntime.jsx("div",{style:{flex:1},children:jsxRuntime.jsx("textarea",{value:B,onChange:W,style:{width:"100%",height:"100%",minHeight:"400px",padding:"12px",fontSize:"12px",fontFamily:'"SF Mono", "Fira Code", monospace',border:"1px solid #e5e7eb",borderRadius:"6px",resize:"vertical",outline:"none",boxSizing:"border-box",backgroundColor:"#fafafa",lineHeight:1.5}})})]}),T&&t&&u==="editor"&&jsxRuntime.jsxs("div",{style:{flex:"1 1 50%",minWidth:0,padding:"20px",backgroundColor:"#f9fafb",borderRadius:"8px",border:"1px solid #e5e7eb",overflow:"auto"},children:[jsxRuntime.jsx("div",{style:{fontSize:"12px",color:"#9ca3af",marginBottom:"12px",textTransform:"uppercase",letterSpacing:"0.5px",fontWeight:600},children:"Live Preview"}),jsxRuntime.jsx(ee,{schema:a.schema,options:{onSubmit:n=>console.log("Preview submit:",n)}})]})]})});Me.displayName="SurveyBuilder";exports.a=ce;exports.b=Te;exports.c=ie;exports.d=ee;exports.e=me;exports.f=be;exports.g=se;exports.h=Me;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a,j,g,h,b}from'./chunk-YTSJTAP2.mjs';var n=class{constructor(e,t={}){this.schema=a(e),this.options=t,this.listeners=new Map,this.stateChangeCallbacks=new Set;let s=this.buildInitialAnswers(t.initialAnswers),r=j(this.schema,s);this.state={answers:s,currentPageIndex:0,errors:[],isValid:true,isSubmitted:false,visibleQuestionIds:r};}getState(){return {...this.state}}getSchema(){return this.schema}getAnswers(){return {...this.state.answers}}getCurrentPage(){return this.schema.pages[this.state.currentPageIndex]??null}getCurrentPageIndex(){return this.state.currentPageIndex}getTotalPages(){return this.schema.pages.length}getErrors(){return [...this.state.errors]}isValid(){return this.state.isValid}isSubmitted(){return this.state.isSubmitted}getVisibleQuestionIds(){return new Set(this.state.visibleQuestionIds)}setAnswer(e,t){let s={...this.state.answers,[e]:t},r=j(this.schema,s);this.updateState({answers:s,visibleQuestionIds:r,errors:this.state.errors.filter(d=>d.questionId!==e)}),this.emit("answerChanged",{questionId:e,value:t,answers:s}),this.options.onChange?.(s,e);}nextPage(){let{currentPageIndex:e}=this.state,t=e+1;if(t>=this.schema.pages.length)return false;if(this.schema.settings?.validateOnPageChange){let s=g(this.schema,e,this.state.answers,this.state.visibleQuestionIds);if(s.length>0)return this.updateState({errors:s,isValid:false}),this.emit("validated",{errors:s,isValid:false}),false}return this.updateState({currentPageIndex:t,errors:[]}),this.emit("pageChanged",{pageIndex:t}),this.options.onPageChange?.(t),true}prevPage(){let{currentPageIndex:e}=this.state;if(e<=0||!this.schema.settings?.allowBack)return false;let t=e-1;return this.updateState({currentPageIndex:t,errors:[]}),this.emit("pageChanged",{pageIndex:t}),this.options.onPageChange?.(t),true}goToPage(e){return e<0||e>=this.schema.pages.length?false:(this.updateState({currentPageIndex:e,errors:[]}),this.emit("pageChanged",{pageIndex:e}),this.options.onPageChange?.(e),true)}validate(){let e=h(this.schema,this.state.answers,this.state.visibleQuestionIds),t=e.length===0;return this.updateState({errors:e,isValid:t}),this.emit("validated",{errors:e,isValid:t}),this.options.onValidate?.(e),e}validateCurrentPage(){let e=g(this.schema,this.state.currentPageIndex,this.state.answers,this.state.visibleQuestionIds),t=e.length===0;return this.updateState({errors:e,isValid:t}),this.emit("validated",{errors:e,isValid:t}),e}async submit(){let e=this.validate();if(e.length>0)return {success:false,errors:e};try{return await this.options.onSubmit?.(this.state.answers),this.updateState({isSubmitted:!0}),this.emit("submitted",{answers:this.state.answers}),{success:!0,errors:[]}}catch(t){return {success:false,errors:[{questionId:"__submit__",message:t instanceof Error?t.message:"Submission failed",rule:"custom"}]}}}reset(e){let t=this.buildInitialAnswers(e??this.options.initialAnswers),s=j(this.schema,t);this.updateState({answers:t,currentPageIndex:0,errors:[],isValid:true,isSubmitted:false,visibleQuestionIds:s});}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.listeners.get(e)?.delete(t)}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>this.stateChangeCallbacks.delete(e)}updateState(e){this.state={...this.state,...e},this.stateChangeCallbacks.forEach(t=>t(this.getState()));}emit(e,t){let s={type:e,payload:t,timestamp:Date.now()};this.listeners.get(e)?.forEach(r=>r(s));}buildInitialAnswers(e){let t={};for(let s of b(this.schema))s.defaultValue!==void 0&&(t[s.id]=s.defaultValue);return e&&Object.assign(t,e),t}};function S(o,e){return new n(o,e)}export{n as a,S as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function A(e){if(!e||typeof e!="object")throw new u("Schema must be a valid object");if(!e.id||typeof e.id!="string")throw new u('Schema must have a string "id"');if(!Array.isArray(e.pages)||e.pages.length===0)throw new u("Schema must have at least one page");return {...e,title:e.title??"",description:e.description??"",pages:e.pages.map(h),settings:{showProgress:true,allowBack:true,validateOnPageChange:true,showQuestionNumbers:true,submitText:"Submit",nextText:"Next",prevText:"Previous",...e.settings}}}function h(e,t){if(!e.id)throw new u(`Page at index ${t} must have an "id"`);if(!Array.isArray(e.questions))throw new u(`Page "${e.id}" must have a "questions" array`);return {...e,title:e.title??"",description:e.description??"",questions:e.questions.map((r,i)=>v(r,i,e.id))}}function v(e,t,r){if(!e.id)throw new u(`Question at index ${t} in page "${r}" must have an "id"`);if(!e.type)throw new u(`Question "${e.id}" in page "${r}" must have a "type"`);if(!e.label)throw new u(`Question "${e.id}" in page "${r}" must have a "label"`);return {required:false,...e,options:e.options??[],validation:e.validation??[],meta:e.meta??{}}}function g(e){return e.pages.flatMap(t=>t.questions)}function $(e,t){for(let r=0;r<e.pages.length;r++){let i=e.pages[r],s=i.questions.findIndex(n=>n.id===t);if(s!==-1)return {question:i.questions[s],page:i,pageIndex:r,questionIndex:s}}return null}function P(e="item"){return `${e}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}var u=class extends Error{constructor(t){super(`[react-minimal-survey-builder] ${t}`),this.name="SurveySchemaError";}};function p(e,t,r){let i=[];if(e.required&&m(t))return i.push({questionId:e.id,message:`"${e.label}" is required`,rule:"required"}),i;if(m(t))return i;let s=e.validation??[];for(let n of s){let a=S(n,t,e,r);a&&i.push(a);}return i}function N(e,t,r,i){let s=e.pages[t];return s?s.questions.filter(n=>i.has(n.id)).flatMap(n=>p(n,r[n.id],r)):[]}function E(e,t,r){return g(e).filter(i=>r.has(i.id)).flatMap(i=>p(i,t[i.id],t))}function S(e,t,r,i){let s=String(t??"");switch(e.type){case "required":if(m(t))return o(r.id,e,`"${r.label}" is required`);break;case "minLength":if(typeof e.value=="number"&&s.length<e.value)return o(r.id,e,`"${r.label}" must be at least ${e.value} characters`);break;case "maxLength":if(typeof e.value=="number"&&s.length>e.value)return o(r.id,e,`"${r.label}" must be at most ${e.value} characters`);break;case "min":if(typeof e.value=="number"&&Number(t)<e.value)return o(r.id,e,`"${r.label}" must be at least ${e.value}`);break;case "max":if(typeof e.value=="number"&&Number(t)>e.value)return o(r.id,e,`"${r.label}" must be at most ${e.value}`);break;case "pattern":{if(!(e.value instanceof RegExp?e.value:new RegExp(String(e.value))).test(s))return o(r.id,e,`"${r.label}" does not match the required pattern`);break}case "email":{if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))return o(r.id,e,`"${r.label}" must be a valid email`);break}case "custom":if(e.validator){let n=e.validator(t,i);if(n!==true&&typeof n=="string")return o(r.id,e,n);if(n===false)return o(r.id,e,e.message??`"${r.label}" is invalid`)}break}return null}function m(e){return !!(e==null||e===""||Array.isArray(e)&&e.length===0)}function o(e,t,r){return {questionId:e,message:t.message??r,rule:t.type}}function c(e,t){if(!e||e.trim()==="")return true;try{let r=e.replace(/\{([^}]+)\}/g,(i,s)=>{let n=t[s.trim()];return n==null?"undefined":typeof n=="string"||Array.isArray(n)?JSON.stringify(n):String(n)});return f(r)}catch{return console.warn(`[react-minimal-survey-builder] Failed to evaluate condition: "${e}"`),true}}function k(e,t){let r=new Set;for(let i of e.pages)if(c(i.visibleIf,t))for(let s of i.questions)c(s.visibleIf,t)&&r.add(s.id);return r}function W(e,t){return e.pages.filter(r=>c(r.visibleIf,t))}function R(e,t){return c(e.visibleIf,t)?e.questions.filter(r=>c(r.visibleIf,t)):[]}function f(e){let t=e.trim(),r=b(t,"||");if(r.length>1)return r.some(n=>f(n));let i=b(t,"&&");if(i.length>1)return i.every(n=>f(n));if(t.startsWith("!"))return !f(t.slice(1));if(t.startsWith("(")&&t.endsWith(")"))return f(t.slice(1,-1));for(let n of ["===","!==",">=","<=",">","<","==","!="]){let a=t.indexOf(n);if(a!==-1){let d=l(t.slice(0,a).trim()),y=l(t.slice(a+n.length).trim());return w(d,y,n)}}if(t.includes(".includes(")){let n=t.match(/^(.+)\.includes\((.+)\)$/);if(n){let a=l(n[1].trim()),d=l(n[2].trim());if(Array.isArray(a))return a.includes(d);if(typeof a=="string")return a.includes(String(d))}}let s=l(t);return x(s)}function b(e,t){let r=[],i=0,s="";for(let n=0;n<e.length;n++)e[n]==="("&&i++,e[n]===")"&&i--,i===0&&e.startsWith(t,n)?(r.push(s),s="",n+=t.length-1):s+=e[n];return r.push(s),r.map(n=>n.trim()).filter(Boolean)}function l(e){let t=e.trim();if(t==="undefined")return;if(t==="null")return null;if(t==="true")return true;if(t==="false")return false;if(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))return t.slice(1,-1);if(t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return t}let r=Number(t);return !isNaN(r)&&t!==""?r:t}function w(e,t,r){switch(r){case "===":case "==":return e===t;case "!==":case "!=":return e!==t;case ">":return Number(e)>Number(t);case "<":return Number(e)<Number(t);case ">=":return Number(e)>=Number(t);case "<=":return Number(e)<=Number(t);default:return false}}function x(e){return !(e==null||e===""||e===false||e===0||Array.isArray(e)&&e.length===0)}export{A as a,g as b,$ as c,P as d,u as e,p as f,N as g,E as h,c as i,k as j,W as k,R as l};
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { S as SurveySchema, Q as Question, P as Page, b as SurveyAnswers, V as ValidationError, A as AnswerValue, a as SurveyOptions, m as SurveyState, j as SurveyEventType, i as SurveyEventHandler } from '../index-Q8KHOfHv.mjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Parses and validates a survey schema, returning a normalized version.
|
|
5
|
+
* Ensures all required fields exist and applies defaults.
|
|
6
|
+
*/
|
|
7
|
+
declare function parseSchema(schema: SurveySchema): SurveySchema;
|
|
8
|
+
/**
|
|
9
|
+
* Extracts all questions from all pages in flat array form.
|
|
10
|
+
*/
|
|
11
|
+
declare function getAllQuestions(schema: SurveySchema): Question[];
|
|
12
|
+
/**
|
|
13
|
+
* Finds a question by ID across all pages.
|
|
14
|
+
*/
|
|
15
|
+
declare function findQuestion(schema: SurveySchema, questionId: string): {
|
|
16
|
+
question: Question;
|
|
17
|
+
page: Page;
|
|
18
|
+
pageIndex: number;
|
|
19
|
+
questionIndex: number;
|
|
20
|
+
} | null;
|
|
21
|
+
/**
|
|
22
|
+
* Generates a unique ID for questions/pages.
|
|
23
|
+
*/
|
|
24
|
+
declare function generateId(prefix?: string): string;
|
|
25
|
+
declare class SurveySchemaError extends Error {
|
|
26
|
+
constructor(message: string);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Validates a single answer against a question's validation rules.
|
|
31
|
+
*/
|
|
32
|
+
declare function validateQuestion(question: Question, value: AnswerValue, answers: SurveyAnswers): ValidationError[];
|
|
33
|
+
/**
|
|
34
|
+
* Validates all questions on a specific page.
|
|
35
|
+
*/
|
|
36
|
+
declare function validatePage(schema: SurveySchema, pageIndex: number, answers: SurveyAnswers, visibleQuestionIds: Set<string>): ValidationError[];
|
|
37
|
+
/**
|
|
38
|
+
* Validates the entire survey.
|
|
39
|
+
*/
|
|
40
|
+
declare function validateSurvey(schema: SurveySchema, answers: SurveyAnswers, visibleQuestionIds: Set<string>): ValidationError[];
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Evaluates a condition expression against the current answers.
|
|
44
|
+
*
|
|
45
|
+
* Supported syntax:
|
|
46
|
+
* "{questionId} === 'value'"
|
|
47
|
+
* "{q1} !== 'no'"
|
|
48
|
+
* "{q1} === 'yes' && {q2} === 'male'"
|
|
49
|
+
* "{q1} === 'yes' || {q2} === 'yes'"
|
|
50
|
+
* "{q1}" (truthy check)
|
|
51
|
+
*
|
|
52
|
+
* Variables are wrapped in curly braces: {questionId}
|
|
53
|
+
*/
|
|
54
|
+
declare function evaluateCondition(condition: string | undefined, answers: SurveyAnswers): boolean;
|
|
55
|
+
/**
|
|
56
|
+
* Returns the set of visible question IDs based on conditional logic.
|
|
57
|
+
*/
|
|
58
|
+
declare function getVisibleQuestionIds(schema: SurveySchema, answers: SurveyAnswers): Set<string>;
|
|
59
|
+
/**
|
|
60
|
+
* Returns visible pages (pages whose visibleIf condition evaluates to true).
|
|
61
|
+
*/
|
|
62
|
+
declare function getVisiblePages(schema: SurveySchema, answers: SurveyAnswers): Page[];
|
|
63
|
+
/**
|
|
64
|
+
* Returns visible questions for a specific page.
|
|
65
|
+
*/
|
|
66
|
+
declare function getVisibleQuestionsForPage(page: Page, answers: SurveyAnswers): Question[];
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Framework-agnostic survey state manager.
|
|
70
|
+
* Manages answers, validation, visibility, and events.
|
|
71
|
+
*/
|
|
72
|
+
declare class SurveyStateManager {
|
|
73
|
+
private schema;
|
|
74
|
+
private state;
|
|
75
|
+
private options;
|
|
76
|
+
private listeners;
|
|
77
|
+
private stateChangeCallbacks;
|
|
78
|
+
constructor(schema: SurveySchema, options?: SurveyOptions);
|
|
79
|
+
getState(): SurveyState;
|
|
80
|
+
getSchema(): SurveySchema;
|
|
81
|
+
getAnswers(): SurveyAnswers;
|
|
82
|
+
getCurrentPage(): Page;
|
|
83
|
+
getCurrentPageIndex(): number;
|
|
84
|
+
getTotalPages(): number;
|
|
85
|
+
getErrors(): ValidationError[];
|
|
86
|
+
isValid(): boolean;
|
|
87
|
+
isSubmitted(): boolean;
|
|
88
|
+
getVisibleQuestionIds(): Set<string>;
|
|
89
|
+
setAnswer(questionId: string, value: AnswerValue): void;
|
|
90
|
+
nextPage(): boolean;
|
|
91
|
+
prevPage(): boolean;
|
|
92
|
+
goToPage(pageIndex: number): boolean;
|
|
93
|
+
validate(): ValidationError[];
|
|
94
|
+
validateCurrentPage(): ValidationError[];
|
|
95
|
+
submit(): Promise<{
|
|
96
|
+
success: boolean;
|
|
97
|
+
errors: ValidationError[];
|
|
98
|
+
}>;
|
|
99
|
+
reset(initialAnswers?: SurveyAnswers): void;
|
|
100
|
+
on(event: SurveyEventType, handler: SurveyEventHandler): () => void;
|
|
101
|
+
onStateChange(callback: (state: SurveyState) => void): () => void;
|
|
102
|
+
private updateState;
|
|
103
|
+
private emit;
|
|
104
|
+
private buildInitialAnswers;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Factory function to create a survey state manager.
|
|
108
|
+
*/
|
|
109
|
+
declare function createSurveyManager(schema: SurveySchema, options?: SurveyOptions): SurveyStateManager;
|
|
110
|
+
|
|
111
|
+
export { SurveySchemaError, SurveyStateManager, createSurveyManager, evaluateCondition, findQuestion, generateId, getAllQuestions, getVisiblePages, getVisibleQuestionIds, getVisibleQuestionsForPage, parseSchema, validatePage, validateQuestion, validateSurvey };
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { S as SurveySchema, Q as Question, P as Page, b as SurveyAnswers, V as ValidationError, A as AnswerValue, a as SurveyOptions, m as SurveyState, j as SurveyEventType, i as SurveyEventHandler } from '../index-Q8KHOfHv.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Parses and validates a survey schema, returning a normalized version.
|
|
5
|
+
* Ensures all required fields exist and applies defaults.
|
|
6
|
+
*/
|
|
7
|
+
declare function parseSchema(schema: SurveySchema): SurveySchema;
|
|
8
|
+
/**
|
|
9
|
+
* Extracts all questions from all pages in flat array form.
|
|
10
|
+
*/
|
|
11
|
+
declare function getAllQuestions(schema: SurveySchema): Question[];
|
|
12
|
+
/**
|
|
13
|
+
* Finds a question by ID across all pages.
|
|
14
|
+
*/
|
|
15
|
+
declare function findQuestion(schema: SurveySchema, questionId: string): {
|
|
16
|
+
question: Question;
|
|
17
|
+
page: Page;
|
|
18
|
+
pageIndex: number;
|
|
19
|
+
questionIndex: number;
|
|
20
|
+
} | null;
|
|
21
|
+
/**
|
|
22
|
+
* Generates a unique ID for questions/pages.
|
|
23
|
+
*/
|
|
24
|
+
declare function generateId(prefix?: string): string;
|
|
25
|
+
declare class SurveySchemaError extends Error {
|
|
26
|
+
constructor(message: string);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Validates a single answer against a question's validation rules.
|
|
31
|
+
*/
|
|
32
|
+
declare function validateQuestion(question: Question, value: AnswerValue, answers: SurveyAnswers): ValidationError[];
|
|
33
|
+
/**
|
|
34
|
+
* Validates all questions on a specific page.
|
|
35
|
+
*/
|
|
36
|
+
declare function validatePage(schema: SurveySchema, pageIndex: number, answers: SurveyAnswers, visibleQuestionIds: Set<string>): ValidationError[];
|
|
37
|
+
/**
|
|
38
|
+
* Validates the entire survey.
|
|
39
|
+
*/
|
|
40
|
+
declare function validateSurvey(schema: SurveySchema, answers: SurveyAnswers, visibleQuestionIds: Set<string>): ValidationError[];
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Evaluates a condition expression against the current answers.
|
|
44
|
+
*
|
|
45
|
+
* Supported syntax:
|
|
46
|
+
* "{questionId} === 'value'"
|
|
47
|
+
* "{q1} !== 'no'"
|
|
48
|
+
* "{q1} === 'yes' && {q2} === 'male'"
|
|
49
|
+
* "{q1} === 'yes' || {q2} === 'yes'"
|
|
50
|
+
* "{q1}" (truthy check)
|
|
51
|
+
*
|
|
52
|
+
* Variables are wrapped in curly braces: {questionId}
|
|
53
|
+
*/
|
|
54
|
+
declare function evaluateCondition(condition: string | undefined, answers: SurveyAnswers): boolean;
|
|
55
|
+
/**
|
|
56
|
+
* Returns the set of visible question IDs based on conditional logic.
|
|
57
|
+
*/
|
|
58
|
+
declare function getVisibleQuestionIds(schema: SurveySchema, answers: SurveyAnswers): Set<string>;
|
|
59
|
+
/**
|
|
60
|
+
* Returns visible pages (pages whose visibleIf condition evaluates to true).
|
|
61
|
+
*/
|
|
62
|
+
declare function getVisiblePages(schema: SurveySchema, answers: SurveyAnswers): Page[];
|
|
63
|
+
/**
|
|
64
|
+
* Returns visible questions for a specific page.
|
|
65
|
+
*/
|
|
66
|
+
declare function getVisibleQuestionsForPage(page: Page, answers: SurveyAnswers): Question[];
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Framework-agnostic survey state manager.
|
|
70
|
+
* Manages answers, validation, visibility, and events.
|
|
71
|
+
*/
|
|
72
|
+
declare class SurveyStateManager {
|
|
73
|
+
private schema;
|
|
74
|
+
private state;
|
|
75
|
+
private options;
|
|
76
|
+
private listeners;
|
|
77
|
+
private stateChangeCallbacks;
|
|
78
|
+
constructor(schema: SurveySchema, options?: SurveyOptions);
|
|
79
|
+
getState(): SurveyState;
|
|
80
|
+
getSchema(): SurveySchema;
|
|
81
|
+
getAnswers(): SurveyAnswers;
|
|
82
|
+
getCurrentPage(): Page;
|
|
83
|
+
getCurrentPageIndex(): number;
|
|
84
|
+
getTotalPages(): number;
|
|
85
|
+
getErrors(): ValidationError[];
|
|
86
|
+
isValid(): boolean;
|
|
87
|
+
isSubmitted(): boolean;
|
|
88
|
+
getVisibleQuestionIds(): Set<string>;
|
|
89
|
+
setAnswer(questionId: string, value: AnswerValue): void;
|
|
90
|
+
nextPage(): boolean;
|
|
91
|
+
prevPage(): boolean;
|
|
92
|
+
goToPage(pageIndex: number): boolean;
|
|
93
|
+
validate(): ValidationError[];
|
|
94
|
+
validateCurrentPage(): ValidationError[];
|
|
95
|
+
submit(): Promise<{
|
|
96
|
+
success: boolean;
|
|
97
|
+
errors: ValidationError[];
|
|
98
|
+
}>;
|
|
99
|
+
reset(initialAnswers?: SurveyAnswers): void;
|
|
100
|
+
on(event: SurveyEventType, handler: SurveyEventHandler): () => void;
|
|
101
|
+
onStateChange(callback: (state: SurveyState) => void): () => void;
|
|
102
|
+
private updateState;
|
|
103
|
+
private emit;
|
|
104
|
+
private buildInitialAnswers;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Factory function to create a survey state manager.
|
|
108
|
+
*/
|
|
109
|
+
declare function createSurveyManager(schema: SurveySchema, options?: SurveyOptions): SurveyStateManager;
|
|
110
|
+
|
|
111
|
+
export { SurveySchemaError, SurveyStateManager, createSurveyManager, evaluateCondition, findQuestion, generateId, getAllQuestions, getVisiblePages, getVisibleQuestionIds, getVisibleQuestionsForPage, parseSchema, validatePage, validateQuestion, validateSurvey };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkM6YT7KIF_js=require('../chunk-M6YT7KIF.js'),chunkJWOXQRNV_js=require('../chunk-JWOXQRNV.js');Object.defineProperty(exports,"SurveyStateManager",{enumerable:true,get:function(){return chunkM6YT7KIF_js.a}});Object.defineProperty(exports,"createSurveyManager",{enumerable:true,get:function(){return chunkM6YT7KIF_js.b}});Object.defineProperty(exports,"SurveySchemaError",{enumerable:true,get:function(){return chunkJWOXQRNV_js.e}});Object.defineProperty(exports,"evaluateCondition",{enumerable:true,get:function(){return chunkJWOXQRNV_js.i}});Object.defineProperty(exports,"findQuestion",{enumerable:true,get:function(){return chunkJWOXQRNV_js.c}});Object.defineProperty(exports,"generateId",{enumerable:true,get:function(){return chunkJWOXQRNV_js.d}});Object.defineProperty(exports,"getAllQuestions",{enumerable:true,get:function(){return chunkJWOXQRNV_js.b}});Object.defineProperty(exports,"getVisiblePages",{enumerable:true,get:function(){return chunkJWOXQRNV_js.k}});Object.defineProperty(exports,"getVisibleQuestionIds",{enumerable:true,get:function(){return chunkJWOXQRNV_js.j}});Object.defineProperty(exports,"getVisibleQuestionsForPage",{enumerable:true,get:function(){return chunkJWOXQRNV_js.l}});Object.defineProperty(exports,"parseSchema",{enumerable:true,get:function(){return chunkJWOXQRNV_js.a}});Object.defineProperty(exports,"validatePage",{enumerable:true,get:function(){return chunkJWOXQRNV_js.g}});Object.defineProperty(exports,"validateQuestion",{enumerable:true,get:function(){return chunkJWOXQRNV_js.f}});Object.defineProperty(exports,"validateSurvey",{enumerable:true,get:function(){return chunkJWOXQRNV_js.h}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{a as SurveyStateManager,b as createSurveyManager}from'../chunk-RZFNCNBO.mjs';export{e as SurveySchemaError,i as evaluateCondition,c as findQuestion,d as generateId,b as getAllQuestions,k as getVisiblePages,j as getVisibleQuestionIds,l as getVisibleQuestionsForPage,a as parseSchema,g as validatePage,f as validateQuestion,h as validateSurvey}from'../chunk-YTSJTAP2.mjs';
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
interface Option {
|
|
2
|
+
label: string;
|
|
3
|
+
value: string;
|
|
4
|
+
}
|
|
5
|
+
type ValidationRuleType = "required" | "minLength" | "maxLength" | "pattern" | "min" | "max" | "email" | "custom";
|
|
6
|
+
interface ValidationRule {
|
|
7
|
+
type: ValidationRuleType;
|
|
8
|
+
value?: string | number | RegExp;
|
|
9
|
+
message?: string;
|
|
10
|
+
/** Custom validator function (for 'custom' type) */
|
|
11
|
+
validator?: (value: AnswerValue, answers: SurveyAnswers) => boolean | string;
|
|
12
|
+
}
|
|
13
|
+
interface ValidationError {
|
|
14
|
+
questionId: string;
|
|
15
|
+
message: string;
|
|
16
|
+
rule: ValidationRuleType;
|
|
17
|
+
}
|
|
18
|
+
type BuiltInQuestionType = "text" | "textarea" | "radio" | "checkbox" | "select" | "number" | "email" | "date" | "rating";
|
|
19
|
+
type QuestionType = BuiltInQuestionType | (string & {});
|
|
20
|
+
interface Question {
|
|
21
|
+
id: string;
|
|
22
|
+
type: QuestionType;
|
|
23
|
+
label: string;
|
|
24
|
+
description?: string;
|
|
25
|
+
placeholder?: string;
|
|
26
|
+
required?: boolean;
|
|
27
|
+
defaultValue?: AnswerValue;
|
|
28
|
+
options?: Option[];
|
|
29
|
+
validation?: ValidationRule[];
|
|
30
|
+
/** Condition expression: e.g. "{q1} === 'yes'" */
|
|
31
|
+
visibleIf?: string;
|
|
32
|
+
/** Additional metadata for custom question types */
|
|
33
|
+
meta?: Record<string, unknown>;
|
|
34
|
+
}
|
|
35
|
+
interface Page {
|
|
36
|
+
id: string;
|
|
37
|
+
title?: string;
|
|
38
|
+
description?: string;
|
|
39
|
+
questions: Question[];
|
|
40
|
+
visibleIf?: string;
|
|
41
|
+
}
|
|
42
|
+
interface SurveySchema {
|
|
43
|
+
id: string;
|
|
44
|
+
title?: string;
|
|
45
|
+
description?: string;
|
|
46
|
+
pages: Page[];
|
|
47
|
+
/** Settings for the survey behavior */
|
|
48
|
+
settings?: SurveySettings;
|
|
49
|
+
}
|
|
50
|
+
interface SurveySettings {
|
|
51
|
+
/** Show progress bar */
|
|
52
|
+
showProgress?: boolean;
|
|
53
|
+
/** Allow going back to previous pages */
|
|
54
|
+
allowBack?: boolean;
|
|
55
|
+
/** Validate on each page change */
|
|
56
|
+
validateOnPageChange?: boolean;
|
|
57
|
+
/** Show question numbers */
|
|
58
|
+
showQuestionNumbers?: boolean;
|
|
59
|
+
/** Custom submit button text */
|
|
60
|
+
submitText?: string;
|
|
61
|
+
/** Custom next button text */
|
|
62
|
+
nextText?: string;
|
|
63
|
+
/** Custom previous button text */
|
|
64
|
+
prevText?: string;
|
|
65
|
+
}
|
|
66
|
+
type AnswerValue = string | string[] | number | boolean | null | undefined;
|
|
67
|
+
type SurveyAnswers = Record<string, AnswerValue>;
|
|
68
|
+
type SurveyEventType = "answerChanged" | "pageChanged" | "validated" | "submitted" | "questionVisibilityChanged";
|
|
69
|
+
interface SurveyEvent<T = unknown> {
|
|
70
|
+
type: SurveyEventType;
|
|
71
|
+
payload: T;
|
|
72
|
+
timestamp: number;
|
|
73
|
+
}
|
|
74
|
+
type SurveyEventHandler<T = unknown> = (event: SurveyEvent<T>) => void;
|
|
75
|
+
interface SurveyState {
|
|
76
|
+
answers: SurveyAnswers;
|
|
77
|
+
currentPageIndex: number;
|
|
78
|
+
errors: ValidationError[];
|
|
79
|
+
isValid: boolean;
|
|
80
|
+
isSubmitted: boolean;
|
|
81
|
+
visibleQuestionIds: Set<string>;
|
|
82
|
+
}
|
|
83
|
+
interface SurveyOptions {
|
|
84
|
+
/** Initial answers */
|
|
85
|
+
initialAnswers?: SurveyAnswers;
|
|
86
|
+
/** Called when an answer changes */
|
|
87
|
+
onChange?: (answers: SurveyAnswers, questionId: string) => void;
|
|
88
|
+
/** Called on submit */
|
|
89
|
+
onSubmit?: (answers: SurveyAnswers) => void | Promise<void>;
|
|
90
|
+
/** Called on validation */
|
|
91
|
+
onValidate?: (errors: ValidationError[]) => void;
|
|
92
|
+
/** Called on page change */
|
|
93
|
+
onPageChange?: (pageIndex: number) => void;
|
|
94
|
+
/** Custom validators by question type */
|
|
95
|
+
validators?: Record<string, (value: AnswerValue, question: Question) => string | null>;
|
|
96
|
+
}
|
|
97
|
+
type QuestionComponentProps<V = AnswerValue> = {
|
|
98
|
+
question: Question;
|
|
99
|
+
value: V;
|
|
100
|
+
onChange: (value: V) => void;
|
|
101
|
+
error?: string;
|
|
102
|
+
disabled?: boolean;
|
|
103
|
+
};
|
|
104
|
+
type QuestionComponents = Partial<Record<QuestionType, React.ComponentType<QuestionComponentProps>>>;
|
|
105
|
+
interface SurveyPlugin {
|
|
106
|
+
name: string;
|
|
107
|
+
/** Register custom question types */
|
|
108
|
+
questionTypes?: Record<string, React.ComponentType<QuestionComponentProps>>;
|
|
109
|
+
/** Extend validation */
|
|
110
|
+
validators?: Record<string, (value: AnswerValue, question: Question) => string | null>;
|
|
111
|
+
/** Middleware to intercept events */
|
|
112
|
+
middleware?: (event: SurveyEvent, next: () => void) => void;
|
|
113
|
+
}
|
|
114
|
+
interface BuilderState {
|
|
115
|
+
schema: SurveySchema;
|
|
116
|
+
selectedQuestionId: string | null;
|
|
117
|
+
selectedPageId: string | null;
|
|
118
|
+
isDragging: boolean;
|
|
119
|
+
}
|
|
120
|
+
type BuilderAction = {
|
|
121
|
+
type: "ADD_PAGE";
|
|
122
|
+
payload?: Partial<Page>;
|
|
123
|
+
} | {
|
|
124
|
+
type: "REMOVE_PAGE";
|
|
125
|
+
payload: {
|
|
126
|
+
pageId: string;
|
|
127
|
+
};
|
|
128
|
+
} | {
|
|
129
|
+
type: "UPDATE_PAGE";
|
|
130
|
+
payload: {
|
|
131
|
+
pageId: string;
|
|
132
|
+
updates: Partial<Page>;
|
|
133
|
+
};
|
|
134
|
+
} | {
|
|
135
|
+
type: "ADD_QUESTION";
|
|
136
|
+
payload: {
|
|
137
|
+
pageId: string;
|
|
138
|
+
question?: Partial<Question>;
|
|
139
|
+
};
|
|
140
|
+
} | {
|
|
141
|
+
type: "REMOVE_QUESTION";
|
|
142
|
+
payload: {
|
|
143
|
+
pageId: string;
|
|
144
|
+
questionId: string;
|
|
145
|
+
};
|
|
146
|
+
} | {
|
|
147
|
+
type: "UPDATE_QUESTION";
|
|
148
|
+
payload: {
|
|
149
|
+
pageId: string;
|
|
150
|
+
questionId: string;
|
|
151
|
+
updates: Partial<Question>;
|
|
152
|
+
};
|
|
153
|
+
} | {
|
|
154
|
+
type: "REORDER_QUESTIONS";
|
|
155
|
+
payload: {
|
|
156
|
+
pageId: string;
|
|
157
|
+
fromIndex: number;
|
|
158
|
+
toIndex: number;
|
|
159
|
+
};
|
|
160
|
+
} | {
|
|
161
|
+
type: "REORDER_PAGES";
|
|
162
|
+
payload: {
|
|
163
|
+
fromIndex: number;
|
|
164
|
+
toIndex: number;
|
|
165
|
+
};
|
|
166
|
+
} | {
|
|
167
|
+
type: "MOVE_QUESTION";
|
|
168
|
+
payload: {
|
|
169
|
+
fromPageId: string;
|
|
170
|
+
toPageId: string;
|
|
171
|
+
fromIndex: number;
|
|
172
|
+
toIndex: number;
|
|
173
|
+
};
|
|
174
|
+
} | {
|
|
175
|
+
type: "SELECT_QUESTION";
|
|
176
|
+
payload: {
|
|
177
|
+
questionId: string | null;
|
|
178
|
+
};
|
|
179
|
+
} | {
|
|
180
|
+
type: "SELECT_PAGE";
|
|
181
|
+
payload: {
|
|
182
|
+
pageId: string | null;
|
|
183
|
+
};
|
|
184
|
+
} | {
|
|
185
|
+
type: "SET_SCHEMA";
|
|
186
|
+
payload: SurveySchema;
|
|
187
|
+
} | {
|
|
188
|
+
type: "SET_DRAGGING";
|
|
189
|
+
payload: boolean;
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
export type { AnswerValue as A, BuilderAction as B, Option as O, Page as P, Question as Q, SurveySchema as S, ValidationError as V, SurveyOptions as a, SurveyAnswers as b, QuestionComponents as c, QuestionComponentProps as d, BuilderState as e, BuiltInQuestionType as f, QuestionType as g, SurveyEvent as h, SurveyEventHandler as i, SurveyEventType as j, SurveyPlugin as k, SurveySettings as l, SurveyState as m, ValidationRule as n, ValidationRuleType as o };
|