@superdoc-dev/template-builder 0.2.0-next.4 → 0.2.0-next.5

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/README.md CHANGED
@@ -206,25 +206,77 @@ function TemplateEditor() {
206
206
 
207
207
  ## Export Template
208
208
 
209
- Get the complete template data for saving:
209
+ The `exportTemplate` method supports two modes of operation via the `ExportConfig` interface:
210
+
211
+ ### 1. Download Mode (Default)
212
+
213
+ Automatically downloads the template as a file in the browser:
214
+
215
+ ```jsx
216
+ const handleDownload = async () => {
217
+ // Download with default filename "document.docx"
218
+ await ref.current?.exportTemplate();
219
+
220
+ // Or with custom filename
221
+ await ref.current?.exportTemplate({
222
+ fileName: 'invoice-template.docx'
223
+ });
224
+ };
225
+ ```
226
+
227
+ ### 2. Blob Mode (for Database/API)
228
+
229
+ Get the template as a Blob for saving to your database or API:
210
230
 
211
231
  ```jsx
212
232
  const handleSave = async () => {
213
- await ref.current?.exportTemplate({ fileName: 'invoice.docx' });
233
+ // Get the blob without triggering download
234
+ const blob = await ref.current?.exportTemplate({
235
+ fileName: 'invoice-template.docx',
236
+ triggerDownload: false
237
+ });
238
+
239
+ if (blob) {
240
+ // Send to your API/database
241
+ const formData = new FormData();
242
+ formData.append('template', blob, 'invoice-template.docx');
243
+
244
+ await fetch('/api/templates', {
245
+ method: 'POST',
246
+ body: formData
247
+ });
248
+ }
214
249
  };
215
250
  ```
216
251
 
252
+ ### ExportConfig Interface
253
+
254
+ ```typescript
255
+ interface ExportConfig {
256
+ fileName?: string; // Default: "document"
257
+ triggerDownload?: boolean; // Default: true
258
+ }
259
+
260
+ // Method signature
261
+ exportTemplate(config?: ExportConfig): Promise<void | Blob>
262
+ ```
263
+
264
+ **Return value:**
265
+ - `Promise<void>` when `triggerDownload: true` (download happens automatically)
266
+ - `Promise<Blob>` when `triggerDownload: false` (returns the docx data)
267
+
217
268
  ## TypeScript
218
269
 
219
270
  Full TypeScript support included:
220
271
 
221
272
  ```typescript
222
273
  import SuperDocTemplateBuilder from '@superdoc-dev/template-builder';
223
- import type {
274
+ import type {
224
275
  TemplateField,
225
276
  FieldDefinition,
226
277
  TriggerEvent,
227
- SuperDocTemplateBuilderHandle
278
+ ExportConfig,
279
+ SuperDocTemplateBuilderHandle
228
280
  } from '@superdoc-dev/template-builder';
229
281
 
230
282
  const ref = useRef<SuperDocTemplateBuilderHandle>(null);
@@ -1 +1 @@
1
- {"version":3,"file":"FieldList.d.ts","sourceRoot":"","sources":["../../src/defaults/FieldList.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE/C,eAAO,MAAM,SAAS,EAAE,KAAK,CAAC,EAAE,CAAC,cAAc,CAsI9C,CAAC"}
1
+ {"version":3,"file":"FieldList.d.ts","sourceRoot":"","sources":["../../src/defaults/FieldList.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE/C,eAAO,MAAM,SAAS,EAAE,KAAK,CAAC,EAAE,CAAC,cAAc,CAuJ9C,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"FieldMenu.d.ts","sourceRoot":"","sources":["../../src/defaults/FieldMenu.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAmB,cAAc,EAAE,MAAM,UAAU,CAAC;AAEhE,eAAO,MAAM,SAAS,EAAE,KAAK,CAAC,EAAE,CAAC,cAAc,CAkV9C,CAAC"}
1
+ {"version":3,"file":"FieldMenu.d.ts","sourceRoot":"","sources":["../../src/defaults/FieldMenu.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAmB,cAAc,EAAE,MAAM,UAAU,CAAC;AAEhE,eAAO,MAAM,SAAS,EAAE,KAAK,CAAC,EAAE,CAAC,cAAc,CAmX9C,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.tsx"],"names":[],"mappings":"AASA,OAAO,KAAK,KAAK,KAAK,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAElD,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC;AAsGhC,QAAA,MAAM,uBAAuB,oJA4jB3B,CAAC;AAIH,eAAe,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.tsx"],"names":[],"mappings":"AASA,OAAO,KAAK,KAAK,KAAK,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAElD,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC;AA0GhC,QAAA,MAAM,uBAAuB,oJAokB3B,CAAC;AAIH,eAAe,uBAAuB,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ae=Object.create;var be=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var We=(o,u,f,d)=>{if(u&&typeof u=="object"||typeof u=="function")for(let r of Ie(u))!Le.call(o,r)&&r!==f&&be(o,r,{get:()=>u[r],enumerable:!(d=Me(u,r))||d.enumerable});return o};var Be=(o,u,f)=>(f=o!=null?Ae(De(o)):{},We(u||!o||!o.__esModule?be(f,"default",{value:o,enumerable:!0}):f,o));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("react");var ie={exports:{}},ne={};/**
1
+ "use strict";var Me=Object.create;var be=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var We=(o,u,f,p)=>{if(u&&typeof u=="object"||typeof u=="function")for(let r of Ie(u))!Le.call(o,r)&&r!==f&&be(o,r,{get:()=>u[r],enumerable:!(p=Ae(u,r))||p.enumerable});return o};var Be=(o,u,f)=>(f=o!=null?Me(De(o)):{},We(u||!o||!o.__esModule?be(f,"default",{value:o,enumerable:!0}):f,o));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("react");var le={exports:{}},oe={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var he;function Ve(){if(he)return ne;he=1;var o=Symbol.for("react.transitional.element"),u=Symbol.for("react.fragment");function f(d,r,l){var F=null;if(l!==void 0&&(F=""+l),r.key!==void 0&&(F=""+r.key),"key"in r){l={};for(var D in r)D!=="key"&&(l[D]=r[D])}else l=r;return r=l.ref,{$$typeof:o,type:d,key:F,ref:r!==void 0?r:null,props:l}}return ne.Fragment=u,ne.jsx=f,ne.jsxs=f,ne}var oe={};/**
9
+ */var he;function Ve(){if(he)return oe;he=1;var o=Symbol.for("react.transitional.element"),u=Symbol.for("react.fragment");function f(p,r,c){var S=null;if(c!==void 0&&(S=""+c),r.key!==void 0&&(S=""+r.key),"key"in r){c={};for(var N in r)N!=="key"&&(c[N]=r[N])}else c=r;return r=c.ref,{$$typeof:o,type:p,key:S,ref:r!==void 0?r:null,props:c}}return oe.Fragment=u,oe.jsx=f,oe.jsxs=f,oe}var se={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,9 +14,9 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var ye;function Ye(){return ye||(ye=1,process.env.NODE_ENV!=="production"&&(function(){function o(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===ce?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case O:return"Fragment";case v:return"Profiler";case Z:return"StrictMode";case b:return"Suspense";case E:return"SuspenseList";case W:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case q:return"Portal";case A:return e.displayName||"Context";case $:return(e._context.displayName||"Context")+".Consumer";case c:var a=e.render;return e=e.displayName,e||(e=a.displayName||a.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case T:return a=e.displayName||null,a!==null?a:o(e.type)||"Memo";case j:a=e._payload,e=e._init;try{return o(e(a))}catch{}}return null}function u(e){return""+e}function f(e){try{u(e);var a=!1}catch{a=!0}if(a){a=console;var m=a.error,p=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return m.call(a,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",p),u(e)}}function d(e){if(e===O)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===j)return"<...>";try{var a=o(e);return a?"<"+a+">":"<...>"}catch{return"<...>"}}function r(){var e=K.A;return e===null?null:e.getOwner()}function l(){return Error("react-stack-top-frame")}function F(e){if(se.call(e,"key")){var a=Object.getOwnPropertyDescriptor(e,"key").get;if(a&&a.isReactWarning)return!1}return e.key!==void 0}function D(e,a){function m(){M||(M=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",a))}m.isReactWarning=!0,Object.defineProperty(e,"key",{get:m,configurable:!0})}function z(){var e=o(this.type);return te[e]||(te[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function H(e,a,m,p,B,J){var h=m.ref;return e={$$typeof:L,type:e,key:a,props:m,_owner:p},(h!==void 0?h:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:z}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:B}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:J}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function P(e,a,m,p,B,J){var h=a.children;if(h!==void 0)if(p)if(ee(h)){for(p=0;p<h.length;p++)N(h[p]);Object.freeze&&Object.freeze(h)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else N(h);if(se.call(a,"key")){h=o(e);var _=Object.keys(a).filter(function(ue){return ue!=="key"});p=0<_.length?"{key: someKey, "+_.join(": ..., ")+": ...}":"{key: someKey}",G[h+p]||(_=0<_.length?"{"+_.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
17
+ */var ye;function Ye(){return ye||(ye=1,process.env.NODE_ENV!=="production"&&(function(){function o(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===W?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case z:return"Fragment";case x:return"Profiler";case G:return"StrictMode";case $:return"Suspense";case l:return"SuspenseList";case C:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case ee:return"Portal";case I:return e.displayName||"Context";case Y:return(e._context.displayName||"Context")+".Consumer";case J:var a=e.render;return e=e.displayName,e||(e=a.displayName||a.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case E:return a=e.displayName||null,a!==null?a:o(e.type)||"Memo";case R:a=e._payload,e=e._init;try{return o(e(a))}catch{}}return null}function u(e){return""+e}function f(e){try{u(e);var a=!1}catch{a=!0}if(a){a=console;var g=a.error,m=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return g.call(a,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",m),u(e)}}function p(e){if(e===z)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===R)return"<...>";try{var a=o(e);return a?"<"+a+">":"<...>"}catch{return"<...>"}}function r(){var e=P.A;return e===null?null:e.getOwner()}function c(){return Error("react-stack-top-frame")}function S(e){if(ae.call(e,"key")){var a=Object.getOwnPropertyDescriptor(e,"key").get;if(a&&a.isReactWarning)return!1}return e.key!==void 0}function N(e,a){function g(){D||(D=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",a))}g.isReactWarning=!0,Object.defineProperty(e,"key",{get:g,configurable:!0})}function H(){var e=o(this.type);return re[e]||(re[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function q(e,a,g,m,B,Q){var v=g.ref;return e={$$typeof:w,type:e,key:a,props:g,_owner:m},(v!==void 0?v:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:H}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:B}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:Q}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function M(e,a,g,m,B,Q){var v=a.children;if(v!==void 0)if(m)if(te(v)){for(m=0;m<v.length;m++)O(v[m]);Object.freeze&&Object.freeze(v)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else O(v);if(ae.call(a,"key")){v=o(e);var _=Object.keys(a).filter(function(de){return de!=="key"});m=0<_.length?"{key: someKey, "+_.join(": ..., ")+": ...}":"{key: someKey}",X[v+m]||(_=0<_.length?"{"+_.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
18
18
  let props = %s;
19
19
  <%s {...props} />
20
20
  React keys must be passed directly to JSX without using spread:
21
21
  let props = %s;
22
- <%s key={someKey} {...props} />`,p,h,_,h),G[h+p]=!0)}if(h=null,m!==void 0&&(f(m),h=""+m),F(a)&&(f(a.key),h=""+a.key),"key"in a){m={};for(var X in a)X!=="key"&&(m[X]=a[X])}else m=a;return h&&D(m,typeof e=="function"?e.displayName||e.name||"Unknown":e),H(e,h,m,r(),B,J)}function N(e){C(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===j&&(e._payload.status==="fulfilled"?C(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function C(e){return typeof e=="object"&&e!==null&&e.$$typeof===L}var Y=i,L=Symbol.for("react.transitional.element"),q=Symbol.for("react.portal"),O=Symbol.for("react.fragment"),Z=Symbol.for("react.strict_mode"),v=Symbol.for("react.profiler"),$=Symbol.for("react.consumer"),A=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),b=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),j=Symbol.for("react.lazy"),W=Symbol.for("react.activity"),ce=Symbol.for("react.client.reference"),K=Y.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,se=Object.prototype.hasOwnProperty,ee=Array.isArray,k=console.createTask?console.createTask:function(){return null};Y={react_stack_bottom_frame:function(e){return e()}};var M,te={},I=Y.react_stack_bottom_frame.bind(Y,l)(),re=k(d(l)),G={};oe.Fragment=O,oe.jsx=function(e,a,m){var p=1e4>K.recentlyCreatedOwnerStacks++;return P(e,a,m,!1,p?Error("react-stack-top-frame"):I,p?k(d(e)):re)},oe.jsxs=function(e,a,m){var p=1e4>K.recentlyCreatedOwnerStacks++;return P(e,a,m,!0,p?Error("react-stack-top-frame"):I,p?k(d(e)):re)}})()),oe}var ve;function $e(){return ve||(ve=1,process.env.NODE_ENV==="production"?ie.exports=Ve():ie.exports=Ye()),ie.exports}var s=$e();const Ce=({isVisible:o,position:u,availableFields:f,filteredFields:d,filterQuery:r,allowCreate:l,onSelect:F,onClose:D,onCreateField:z})=>{const[H,P]=i.useState(!1),[N,C]=i.useState("");i.useEffect(()=>{o||(P(!1),C(""))},[o]);const Y=i.useMemo(()=>({position:"absolute",left:u?.left,top:u?.top,zIndex:1e3,background:"white",border:"1px solid #ddd",borderRadius:"4px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",padding:"8px 0",minWidth:"200px"}),[u]),L=d??f,q=!!r,O=i.useMemo(()=>{const c=[],b=new Map;return L.forEach(E=>{const T=E.category?.trim()||"Uncategorized",j=b.get(T);if(j!==void 0){c[j].fields.push(E);return}b.set(T,c.length),c.push({category:T,fields:[E]})}),c},[L]),[Z,v]=i.useState({});i.useEffect(()=>{v(c=>{if(O.length===0)return Object.keys(c).length===0?c:{};const b={};let E=Object.keys(c).length!==O.length;return O.forEach(({category:T},j)=>{const W=q?!0:c[T]??j===0;b[T]=W,!E&&c[T]!==W&&(E=!0)}),E?b:c})},[O,q]);const $=i.useCallback(c=>{v(b=>({...b,[c]:!b[c]}))},[]);if(!o)return null;const A=async()=>{const c=N.trim();if(!c)return;const b={id:`custom_${Date.now()}`,label:c,category:"Custom"};try{if(z){const E=await z(b);F(E||b)}else F(b)}finally{P(!1),C("")}};return s.jsxs("div",{className:"superdoc-field-menu",style:Y,children:[q&&s.jsx("div",{style:{padding:"8px 16px",borderBottom:"1px solid #f0f0f0",marginBottom:"4px"},children:s.jsxs("div",{style:{fontSize:"12px",color:"#6b7280"},children:["Filtering results for",s.jsx("span",{style:{fontWeight:600,color:"#111827",marginLeft:"4px"},children:r})]})}),l&&!H&&s.jsx("div",{className:"field-menu-item",onClick:()=>P(!0),style:{padding:"8px 16px",cursor:"pointer",color:"#0066cc",fontWeight:500},children:"+ Create New Field"}),l&&H&&s.jsxs("div",{style:{padding:"8px 16px"},children:[s.jsx("input",{type:"text",value:N,placeholder:"Field name...",onChange:c=>C(c.target.value),onKeyDown:c=>{c.key==="Enter"&&A(),c.key==="Escape"&&(P(!1),C(""))},autoFocus:!0,style:{width:"100%",padding:"4px 8px",border:"1px solid #ddd",borderRadius:"3px"}}),s.jsxs("div",{style:{marginTop:"8px",display:"flex",gap:"8px"},children:[s.jsx("button",{onClick:A,disabled:!N.trim(),style:{padding:"4px 12px",background:N.trim()?"#0066cc":"#ccc",color:"white",border:"none",borderRadius:"3px",cursor:N.trim()?"pointer":"not-allowed"},children:"Create"}),s.jsx("button",{onClick:()=>{P(!1),C("")},style:{padding:"4px 12px",background:"white",border:"1px solid #ddd",borderRadius:"3px",cursor:"pointer"},children:"Cancel"})]})]}),l&&f.length>0&&s.jsx("div",{style:{borderTop:"1px solid #eee",margin:"4px 0"}}),O.length===0?s.jsx("div",{style:{padding:"16px",fontSize:"13px",color:"#6b7280",textAlign:"center"},children:"No matching fields"}):O.map(({category:c,fields:b},E)=>{const T=!!Z[c],j=`${Math.max(b.length*40,0)}px`;return s.jsxs("div",{style:{borderTop:E===0&&l?void 0:"1px solid #f0f0f0"},children:[s.jsxs("button",{type:"button",onClick:()=>$(c),style:{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 16px",background:"transparent",border:"none",cursor:"pointer",fontWeight:500,textAlign:"left"},children:[s.jsxs("span",{children:[c," (",b.length,")"]}),s.jsx("span",{"aria-hidden":!0,style:{display:"inline-block",width:"8px",height:"8px",borderRight:"2px solid #666",borderBottom:"2px solid #666",transform:T?"rotate(45deg)":"rotate(-45deg)",transition:"transform 0.2s ease",marginLeft:"12px"}})]}),s.jsx("div",{"data-category":c,"aria-hidden":!T,style:{overflow:"hidden",maxHeight:T?j:"0px",opacity:T?1:0,transition:"max-height 0.2s ease, opacity 0.2s ease",pointerEvents:T?"auto":"none"},children:s.jsx("div",{style:{padding:T?"4px 0":0},children:b.map(W=>s.jsx("div",{className:"field-menu-item",onClick:()=>F(W),style:{padding:"8px 16px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"space-between"},children:s.jsx("span",{style:{fontWeight:500},children:W.label})},W.id))})})]},c)}),s.jsx("div",{style:{borderTop:"1px solid #eee",marginTop:"4px"},children:s.jsx("button",{onClick:D,style:{width:"100%",padding:"6px 16px",background:"#f3f4f6",border:"none",borderRadius:"0 0 4px 4px",cursor:"pointer"},children:"Close"})})]})},Te=({fields:o,onSelect:u,onDelete:f,selectedFieldId:d})=>s.jsxs("div",{className:"superdoc-field-list",style:{width:"250px",background:"white",border:"1px solid #e5e7eb",borderRadius:"8px",padding:"16px"},children:[s.jsxs("h3",{style:{margin:"0 0 16px 0",fontSize:"16px",fontWeight:"600"},children:["Template Fields (",o.length,")"]}),o.length===0?s.jsxs("div",{style:{color:"#9ca3af",fontSize:"14px",textAlign:"center",padding:"20px 0"},children:["No fields yet. Type ","{{"," to add a field."]}):s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:o.map(r=>s.jsxs("div",{onClick:()=>u(r),style:{position:"relative",padding:"12px",background:d===r.id?"#eff6ff":"#f9fafb",border:d===r.id?"1px solid #3b82f6":"1px solid #e5e7eb",borderRadius:"6px",cursor:"pointer",transition:"all 0.2s"},onMouseEnter:l=>{d!==r.id&&(l.currentTarget.style.background="#f3f4f6")},onMouseLeave:l=>{d!==r.id&&(l.currentTarget.style.background="#f9fafb")},title:r.alias,children:[s.jsx("button",{onClick:l=>{l.stopPropagation(),f(r.id)},style:{position:"absolute",top:"8px",right:"8px",padding:"4px",background:"transparent",border:"none",cursor:"pointer",color:"#9ca3af",transition:"color 0.2s",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:l=>{l.currentTarget.style.color="#ef4444"},onMouseLeave:l=>{l.currentTarget.style.color="#9ca3af"},title:"Delete field",children:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:s.jsx("path",{d:"M6 2V1.5C6 1.22386 6.22386 1 6.5 1H9.5C9.77614 1 10 1.22386 10 1.5V2M2 4H14M12.6667 4L12.1991 11.0129C12.129 12.065 12.0939 12.5911 11.8667 12.99C11.6666 13.3412 11.3648 13.6235 11.0011 13.7998C10.588 14 10.0607 14 9.00623 14H6.99377C5.93927 14 5.41202 14 4.99889 13.7998C4.63517 13.6235 4.33339 13.3412 4.13332 12.99C3.90607 12.5911 3.871 12.065 3.80086 11.0129L3.33333 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),s.jsxs("div",{style:{paddingRight:"24px"},children:[s.jsx("div",{style:{fontWeight:"500",fontSize:"14px",marginBottom:r.alias&&r.alias!==r.id?"4px":"0"},children:r.id}),r.alias&&r.alias!==r.id&&s.jsx("div",{style:{fontSize:"12px",color:"#4b5563"},children:r.alias})]})]},r.id))})]}),fe=o=>{const u=o.helpers?.structuredContentCommands;return u?.getStructuredContentTags?(u.getStructuredContentTags(o.state)||[]).map(d=>{const l=(d?.node??d)?.attrs??{};return{id:l.id,alias:l.alias||l.label||"",tag:l.tag}}):[]},Ee=(o,u)=>{if(o===u)return!0;if(o.length!==u.length)return!1;for(let f=0;f<o.length;f+=1){const d=o[f],r=u[f];if(!r||d.id!==r.id||d.alias!==r.alias||d.tag!==r.tag||d.position!==r.position)return!1}return!0},Ue=o=>{if(!o)return null;if(o===!0)return{selector:"#superdoc-toolbar",config:{},renderDefaultContainer:!0};if(typeof o=="string")return{selector:o,config:{},renderDefaultContainer:!1};const{selector:u,...f}=o;return{selector:u||"#superdoc-toolbar",config:f,renderDefaultContainer:u===void 0}},le=10,ze=250,He=300,Re=o=>{const u=window.innerWidth-ze-le,f=window.innerHeight-He-le,d=Math.min(o.left,u),r=Math.min(o.top,f);return new DOMRect(Math.max(d,le),Math.max(r,le),o.width,o.height)},ke=i.forwardRef((o,u)=>{const{document:f,fields:d={},menu:r={},list:l={},toolbar:F,onReady:D,onTrigger:z,onFieldInsert:H,onFieldUpdate:P,onFieldDelete:N,onFieldsChange:C,onFieldSelect:Y,onFieldCreate:L,className:q,style:O,documentHeight:Z="600px"}=o,[v,$]=i.useState(d.initial||[]),[A,c]=i.useState(null),[b,E]=i.useState(!1),[T,j]=i.useState(),[W,ce]=i.useState(""),[K,se]=i.useState(()=>d.available||[]),ee=i.useRef(null),k=i.useRef(null),M=i.useRef(null),te=i.useRef(d);te.current=d;const I=i.useRef(null),re=i.useRef(b);i.useEffect(()=>{re.current=b},[b]);const G=r.trigger||"{{",e=te.current.available||[],a=i.useCallback(t=>{const n=t.trim().toLowerCase();return n?e.filter(y=>{const R=y.label.toLowerCase(),S=y.category?.toLowerCase()||"";return R.includes(n)||S.includes(n)}):e},[e]),m=i.useCallback(t=>{ce(t),se(a(t))},[a]),p=i.useCallback(()=>{m("")},[m]),B=i.useCallback((t,n)=>{if(!k.current?.activeEditor)return!1;const y=k.current.activeEditor,R=v,S=t==="inline"?y.commands.insertStructuredContentInline?.({attrs:{alias:n.alias,tag:n.metadata?JSON.stringify(n.metadata):n.category},text:n.defaultValue||n.alias}):y.commands.insertStructuredContentBlock?.({attrs:{alias:n.alias,tag:n.metadata?JSON.stringify(n.metadata):n.category},text:n.defaultValue||n.alias});if(S){const w=fe(y);$(w),C?.(w);const x=w.find(g=>!R.some(U=>U.id===g.id));x&&H?.(x)}return S},[H,C,v]),J=i.useCallback((t,n)=>{if(!k.current?.activeEditor)return!1;const R=k.current.activeEditor.commands.updateStructuredContentById?.(t,{attrs:n});return R&&$(S=>{const w=S.map(g=>g.id===t?{...g,...n}:g);C?.(w);const x=w.find(g=>g.id===t);return x&&P?.(x),w}),R},[P,C]),h=i.useCallback(t=>{const n=k.current?.activeEditor;if(!n){console.warn("[SuperDocTemplateBuilder] deleteField called without active editor");let x=!1;return $(g=>{if(!g.some(V=>V.id===t))return g;const U=g.filter(V=>V.id!==t);return x=!0,C?.(U),U}),x&&(N?.(t),c(g=>g===t?null:g)),x}let y=!1;try{y=n.commands.deleteStructuredContentById?.(t)??!1}catch(x){console.error("[SuperDocTemplateBuilder] Delete command failed:",x)}let R=fe(n);const S=R.some(x=>x.id===t);!y&&S&&(R=R.filter(x=>x.id!==t));let w=!1;return $(x=>{if(Ee(x,R))return x;const g=x.some(V=>V.id===t),U=R.some(V=>V.id===t);return g&&!U&&(w=!0),C?.(R),R}),w&&(N?.(t),c(x=>x===t?null:x)),y||w},[N,C]),_=i.useCallback(t=>{if(!k.current?.activeEditor)return;k.current.activeEditor.commands.selectStructuredContentById?.(t),c(t);const y=v.find(R=>R.id===t);y&&Y?.(y)},[v,Y]),X=i.useCallback(t=>{if(!t)return;const n=fe(t);$(y=>Ee(y,n)?y:(C?.(n),n))},[C]);i.useEffect(()=>ee.current?((async()=>{const{SuperDoc:n}=await import("superdoc"),y={selector:ee.current,document:f?.source,documentMode:f?.mode||"editing",onReady:()=>{if(R.activeEditor){const S=R.activeEditor;S.on("update",({editor:w})=>{const{state:x}=w,{from:g}=x.selection;if(g>=G.length){const de=g-G.length;if(x.doc.textBetween(de,g)===G){const me=w.view.coordsAtPos(g),xe=Re(new DOMRect(me.left,me.top,0,0)),ge=()=>{const ae=k.current?.activeEditor;if(!ae)return;const Oe=ae.state.selection.from,Pe=ae.state.tr.delete(de,Oe);ae.view.dispatch(Pe)};M.current=ge,I.current=g,j(xe),E(!0),p(),z?.({position:{from:de,to:g},bounds:xe,cleanup:ge});return}}if(!re.current)return;if(I.current==null){E(!1),p();return}if(g<I.current){E(!1),I.current=null,p();return}const U=x.doc.textBetween(I.current,g);m(U);const V=w.view.coordsAtPos(g),Ne=Re(new DOMRect(V.left,V.top,0,0));j(Ne)}),S.on("update",()=>{X(S)}),X(S)}D?.()}},R=new n({...y,...Q&&{toolbar:Q.selector,modules:{toolbar:{selector:Q.selector,toolbarGroups:Q.config.toolbarGroups||["center"],excludeItems:Q.config.excludeItems||[],...Q.config}}}});k.current=R})(),()=>{M.current=null,I.current=null;const n=k.current;n&&typeof n.destroy=="function"&&n.destroy(),k.current=null}):void 0,[f?.source,f?.mode,G,X,D,z,F]);const ue=i.useCallback(async t=>{if(M.current&&(M.current(),M.current=null),I.current=null,p(),t.id.startsWith("custom_")&&L)try{const n=await L(t);if(n){B("inline",{alias:n.label,category:n.category,metadata:n.metadata,defaultValue:n.defaultValue}),E(!1);return}}catch(n){console.error("Field creation failed:",n)}B("inline",{alias:t.label,category:t.category,metadata:t.metadata,defaultValue:t.defaultValue}),E(!1)},[B,L,p]),we=i.useCallback(()=>{E(!1),I.current=null,p(),M.current&&(M.current(),M.current=null)},[p]),_e=i.useCallback(()=>{if(!k.current?.activeEditor||v.length===0)return;const t=v.findIndex(y=>y.id===A),n=t>=0?(t+1)%v.length:0;_(v[n].id)},[v,A,_]),je=i.useCallback(()=>{if(!k.current?.activeEditor||v.length===0)return;const t=v.findIndex(y=>y.id===A),n=t>0?t-1:v.length-1;_(v[n].id)},[v,A,_]),Se=i.useCallback(async t=>{try{await k.current?.export({exportType:["docx"],exportedName:t?.fileName?t?.fileName:"document"})}catch(n){throw console.error("Failed to export DOCX",n),n}},[]);i.useImperativeHandle(u,()=>({insertField:t=>B("inline",t),insertBlockField:t=>B("block",t),updateField:J,deleteField:h,selectField:_,nextField:_e,previousField:je,getFields:()=>v,exportTemplate:Se}));const Fe=r.component||Ce,pe=l.component||Te,Q=Ue(F);return s.jsxs("div",{className:`superdoc-template-builder ${q||""}`,style:O,children:[s.jsxs("div",{style:{display:"flex",gap:"20px"},children:[l.position==="left"&&s.jsx("div",{className:"superdoc-template-builder-sidebar",children:s.jsx(pe,{fields:v,onSelect:t=>_(t.id),onDelete:h,onUpdate:t=>J(t.id,t),selectedFieldId:A||void 0})}),s.jsxs("div",{className:"superdoc-template-builder-document",style:{flex:1},children:[Q?.renderDefaultContainer&&s.jsx("div",{id:"superdoc-toolbar",className:"superdoc-template-builder-toolbar","data-testid":"template-builder-toolbar"}),s.jsx("div",{ref:ee,className:"superdoc-template-builder-editor",style:{height:Z},"data-testid":"template-builder-editor"})]}),l.position==="right"&&s.jsx("div",{className:"superdoc-template-builder-sidebar",children:s.jsx(pe,{fields:v,onSelect:t=>_(t.id),onDelete:h,onUpdate:t=>J(t.id,t),selectedFieldId:A||void 0})})]}),s.jsx(Fe,{isVisible:b,position:T,availableFields:d.available||[],filteredFields:K,filterQuery:W,allowCreate:d.allowCreate||!1,onSelect:ue,onClose:we,onCreateField:L})]})});ke.displayName="SuperDocTemplateBuilder";exports.FieldList=Te;exports.FieldMenu=Ce;exports.default=ke;
22
+ <%s key={someKey} {...props} />`,m,v,_,v),X[v+m]=!0)}if(v=null,g!==void 0&&(f(g),v=""+g),S(a)&&(f(a.key),v=""+a.key),"key"in a){g={};for(var Z in a)Z!=="key"&&(g[Z]=a[Z])}else g=a;return v&&N(g,typeof e=="function"?e.displayName||e.name||"Unknown":e),q(e,v,g,r(),B,Q)}function O(e){k(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===R&&(e._payload.status==="fulfilled"?k(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function k(e){return typeof e=="object"&&e!==null&&e.$$typeof===w}var A=i,w=Symbol.for("react.transitional.element"),ee=Symbol.for("react.portal"),z=Symbol.for("react.fragment"),G=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),Y=Symbol.for("react.consumer"),I=Symbol.for("react.context"),J=Symbol.for("react.forward_ref"),$=Symbol.for("react.suspense"),l=Symbol.for("react.suspense_list"),E=Symbol.for("react.memo"),R=Symbol.for("react.lazy"),C=Symbol.for("react.activity"),W=Symbol.for("react.client.reference"),P=A.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ae=Object.prototype.hasOwnProperty,te=Array.isArray,T=console.createTask?console.createTask:function(){return null};A={react_stack_bottom_frame:function(e){return e()}};var D,re={},L=A.react_stack_bottom_frame.bind(A,c)(),ne=T(p(c)),X={};se.Fragment=z,se.jsx=function(e,a,g){var m=1e4>P.recentlyCreatedOwnerStacks++;return M(e,a,g,!1,m?Error("react-stack-top-frame"):L,m?T(p(e)):ne)},se.jsxs=function(e,a,g){var m=1e4>P.recentlyCreatedOwnerStacks++;return M(e,a,g,!0,m?Error("react-stack-top-frame"):L,m?T(p(e)):ne)}})()),se}var ve;function $e(){return ve||(ve=1,process.env.NODE_ENV==="production"?le.exports=Ve():le.exports=Ye()),le.exports}var n=$e();const Re=({isVisible:o,position:u,availableFields:f,filteredFields:p,filterQuery:r,allowCreate:c,onSelect:S,onClose:N,onCreateField:H})=>{const[q,M]=i.useState(!1),[O,k]=i.useState(""),[A,w]=i.useState("inline");i.useEffect(()=>{o||(M(!1),k(""),w("inline"))},[o]);const ee=i.useMemo(()=>({position:"absolute",left:u?.left,top:u?.top,zIndex:1e3,background:"white",border:"1px solid #ddd",borderRadius:"4px",boxShadow:"0 2px 8px rgba(0,0,0,0.1)",padding:"8px 0",minWidth:"200px"}),[u]),z=p??f,G=!!r,x=i.useMemo(()=>{const l=[],E=new Map;return z.forEach(R=>{const C=R.category?.trim()||"Uncategorized",W=E.get(C);if(W!==void 0){l[W].fields.push(R);return}E.set(C,l.length),l.push({category:C,fields:[R]})}),l},[z]),[Y,I]=i.useState({});i.useEffect(()=>{I(l=>{if(x.length===0)return Object.keys(l).length===0?l:{};const E={};let R=Object.keys(l).length!==x.length;return x.forEach(({category:C},W)=>{const P=G?!0:l[C]??W===0;E[C]=P,!R&&l[C]!==P&&(R=!0)}),R?E:l})},[x,G]);const J=i.useCallback(l=>{I(E=>({...E,[l]:!E[l]}))},[]);if(!o)return null;const $=async()=>{const l=O.trim();if(!l)return;const E={id:`custom_${Date.now()}`,label:l,category:"Custom",metadata:{mode:A}};try{if(H){const R=await H(E);S(R||E)}else S(E)}finally{M(!1),k(""),w("inline")}};return n.jsxs("div",{className:"superdoc-field-menu",style:ee,children:[G&&n.jsx("div",{style:{padding:"8px 16px",borderBottom:"1px solid #f0f0f0",marginBottom:"4px"},children:n.jsxs("div",{style:{fontSize:"12px",color:"#6b7280"},children:["Filtering results for",n.jsx("span",{style:{fontWeight:600,color:"#111827",marginLeft:"4px"},children:r})]})}),c&&!q&&n.jsx("div",{className:"field-menu-item",onClick:()=>M(!0),style:{padding:"8px 16px",cursor:"pointer",color:"#0066cc",fontWeight:500},children:"+ Create New Field"}),c&&q&&n.jsxs("div",{style:{padding:"8px 16px"},children:[n.jsx("input",{type:"text",value:O,placeholder:"Field name...",onChange:l=>k(l.target.value),onKeyDown:l=>{l.key==="Enter"&&$(),l.key==="Escape"&&(M(!1),k(""),w("inline"))},autoFocus:!0,style:{width:"100%",padding:"4px 8px",border:"1px solid #ddd",borderRadius:"3px"}}),n.jsxs("div",{style:{marginTop:"8px",display:"flex",gap:"12px",fontSize:"13px"},children:[n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"4px",cursor:"pointer"},children:[n.jsx("input",{type:"radio",value:"inline",checked:A==="inline",onChange:()=>w("inline")}),"Inline"]}),n.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"4px",cursor:"pointer"},children:[n.jsx("input",{type:"radio",value:"block",checked:A==="block",onChange:()=>w("block")}),"Block"]})]}),n.jsxs("div",{style:{marginTop:"8px",display:"flex",gap:"8px"},children:[n.jsx("button",{onClick:$,disabled:!O.trim(),style:{padding:"4px 12px",background:O.trim()?"#0066cc":"#ccc",color:"white",border:"none",borderRadius:"3px",cursor:O.trim()?"pointer":"not-allowed"},children:"Create"}),n.jsx("button",{onClick:()=>{M(!1),k(""),w("inline")},style:{padding:"4px 12px",background:"white",border:"1px solid #ddd",borderRadius:"3px",cursor:"pointer"},children:"Cancel"})]})]}),c&&f.length>0&&n.jsx("div",{style:{borderTop:"1px solid #eee",margin:"4px 0"}}),x.length===0?n.jsx("div",{style:{padding:"16px",fontSize:"13px",color:"#6b7280",textAlign:"center"},children:"No matching fields"}):x.map(({category:l,fields:E},R)=>{const C=!!Y[l],W=`${Math.max(E.length*40,0)}px`;return n.jsxs("div",{style:{borderTop:R===0&&c?void 0:"1px solid #f0f0f0"},children:[n.jsxs("button",{type:"button",onClick:()=>J(l),style:{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 16px",background:"transparent",border:"none",cursor:"pointer",fontWeight:500,textAlign:"left"},children:[n.jsxs("span",{children:[l," (",E.length,")"]}),n.jsx("span",{"aria-hidden":!0,style:{display:"inline-block",width:"8px",height:"8px",borderRight:"2px solid #666",borderBottom:"2px solid #666",transform:C?"rotate(45deg)":"rotate(-45deg)",transition:"transform 0.2s ease",marginLeft:"12px"}})]}),n.jsx("div",{"data-category":l,"aria-hidden":!C,style:{overflow:"hidden",maxHeight:C?W:"0px",opacity:C?1:0,transition:"max-height 0.2s ease, opacity 0.2s ease",pointerEvents:C?"auto":"none"},children:n.jsx("div",{style:{padding:C?"4px 0":0},children:E.map(P=>n.jsx("div",{className:"field-menu-item",onClick:()=>S(P),style:{padding:"8px 16px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"space-between"},children:n.jsx("span",{style:{fontWeight:500},children:P.label})},P.id))})})]},l)}),n.jsx("div",{style:{borderTop:"1px solid #eee",marginTop:"4px"},children:n.jsx("button",{onClick:N,style:{width:"100%",padding:"6px 16px",background:"#f3f4f6",border:"none",borderRadius:"0 0 4px 4px",cursor:"pointer"},children:"Close"})})]})},Ce=({fields:o,onSelect:u,onDelete:f,selectedFieldId:p})=>n.jsxs("div",{className:"superdoc-field-list",style:{width:"250px",background:"white",border:"1px solid #e5e7eb",borderRadius:"8px",padding:"16px"},children:[n.jsxs("h3",{style:{margin:"0 0 16px 0",fontSize:"16px",fontWeight:"600"},children:["Template Fields (",o.length,")"]}),o.length===0?n.jsxs("div",{style:{color:"#9ca3af",fontSize:"14px",textAlign:"center",padding:"20px 0"},children:["No fields yet. Type ","{{"," to add a field."]}):n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:o.map(r=>n.jsxs("div",{onClick:()=>u(r),style:{position:"relative",padding:"12px",background:p===r.id?"#eff6ff":"#f9fafb",border:p===r.id?"1px solid #3b82f6":"1px solid #e5e7eb",borderRadius:"6px",cursor:"pointer",transition:"all 0.2s"},onMouseEnter:c=>{p!==r.id&&(c.currentTarget.style.background="#f3f4f6")},onMouseLeave:c=>{p!==r.id&&(c.currentTarget.style.background="#f9fafb")},title:r.alias,children:[n.jsx("button",{onClick:c=>{c.stopPropagation(),f(r.id)},style:{position:"absolute",top:"8px",right:"8px",padding:"4px",background:"transparent",border:"none",cursor:"pointer",color:"#9ca3af",transition:"color 0.2s",display:"flex",alignItems:"center",justifyContent:"center"},onMouseEnter:c=>{c.currentTarget.style.color="#ef4444"},onMouseLeave:c=>{c.currentTarget.style.color="#9ca3af"},title:"Delete field",children:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n.jsx("path",{d:"M6 2V1.5C6 1.22386 6.22386 1 6.5 1H9.5C9.77614 1 10 1.22386 10 1.5V2M2 4H14M12.6667 4L12.1991 11.0129C12.129 12.065 12.0939 12.5911 11.8667 12.99C11.6666 13.3412 11.3648 13.6235 11.0011 13.7998C10.588 14 10.0607 14 9.00623 14H6.99377C5.93927 14 5.41202 14 4.99889 13.7998C4.63517 13.6235 4.33339 13.3412 4.13332 12.99C3.90607 12.5911 3.871 12.065 3.80086 11.0129L3.33333 4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n.jsxs("div",{style:{paddingRight:"24px"},children:[n.jsx("div",{style:{fontWeight:"500",fontSize:"14px",marginBottom:r.alias&&r.alias!==r.id?"4px":"0"},children:r.id}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontSize:"12px",color:"#4b5563"},children:[r.alias&&r.alias!==r.id&&n.jsx("span",{children:r.alias}),r.mode&&n.jsx("span",{style:{fontSize:"10px",padding:"2px 6px",borderRadius:"4px",background:r.mode==="block"?"#dbeafe":"#f3f4f6",color:r.mode==="block"?"#1e40af":"#4b5563",fontWeight:"500"},children:r.mode})]})]})]},r.id))})]}),pe=o=>{const u=o.helpers?.structuredContentCommands;return u?.getStructuredContentTags?(u.getStructuredContentTags(o.state)||[]).map(p=>{const r=p?.node??p,c=r?.attrs??{},N=(r?.type?.name||"").includes("Block")?"block":"inline";return{id:c.id,alias:c.alias||c.label||"",tag:c.tag,mode:N}}):[]},Ee=(o,u)=>{if(o===u)return!0;if(o.length!==u.length)return!1;for(let f=0;f<o.length;f+=1){const p=o[f],r=u[f];if(!r||p.id!==r.id||p.alias!==r.alias||p.tag!==r.tag||p.position!==r.position||p.mode!==r.mode)return!1}return!0},ze=o=>{if(!o)return null;if(o===!0)return{selector:"#superdoc-toolbar",config:{},renderDefaultContainer:!0};if(typeof o=="string")return{selector:o,config:{},renderDefaultContainer:!1};const{selector:u,...f}=o;return{selector:u||"#superdoc-toolbar",config:f,renderDefaultContainer:u===void 0}},ce=10,Ue=250,He=300,ke=o=>{const u=window.innerWidth-Ue-ce,f=window.innerHeight-He-ce,p=Math.min(o.left,u),r=Math.min(o.top,f);return new DOMRect(Math.max(p,ce),Math.max(r,ce),o.width,o.height)},Te=i.forwardRef((o,u)=>{const{document:f,fields:p={},menu:r={},list:c={},toolbar:S,onReady:N,onTrigger:H,onFieldInsert:q,onFieldUpdate:M,onFieldDelete:O,onFieldsChange:k,onFieldSelect:A,onFieldCreate:w,className:ee,style:z,documentHeight:G="600px"}=o,[x,Y]=i.useState(p.initial||[]),[I,J]=i.useState(null),[$,l]=i.useState(!1),[E,R]=i.useState(),[C,W]=i.useState(""),[P,ae]=i.useState(()=>p.available||[]),te=i.useRef(null),T=i.useRef(null),D=i.useRef(null),re=i.useRef(p);re.current=p;const L=i.useRef(null),ne=i.useRef($);i.useEffect(()=>{ne.current=$},[$]);const X=r.trigger||"{{",e=re.current.available||[],a=i.useCallback(t=>{const s=t.trim().toLowerCase();return s?e.filter(d=>{const b=d.label.toLowerCase(),F=d.category?.toLowerCase()||"";return b.includes(s)||F.includes(s)}):e},[e]),g=i.useCallback(t=>{W(t),ae(a(t))},[a]),m=i.useCallback(()=>{g("")},[g]),B=i.useCallback((t,s)=>{if(!T.current?.activeEditor)return!1;const d=T.current.activeEditor,b=x,F=t==="inline"?d.commands.insertStructuredContentInline?.({attrs:{alias:s.alias,tag:s.metadata?JSON.stringify(s.metadata):s.category},text:s.defaultValue||s.alias}):d.commands.insertStructuredContentBlock?.({attrs:{alias:s.alias,tag:s.metadata?JSON.stringify(s.metadata):s.category},text:s.defaultValue||s.alias});if(F){const j=pe(d);Y(j),k?.(j);const h=j.find(y=>!b.some(U=>U.id===y.id));h&&q?.(h)}return F},[q,k,x]),Q=i.useCallback((t,s)=>{if(!T.current?.activeEditor)return!1;const b=T.current.activeEditor.commands.updateStructuredContentById?.(t,{attrs:s});return b&&Y(F=>{const j=F.map(y=>y.id===t?{...y,...s}:y);k?.(j);const h=j.find(y=>y.id===t);return h&&M?.(h),j}),b},[M,k]),v=i.useCallback(t=>{const s=T.current?.activeEditor;if(!s){console.warn("[SuperDocTemplateBuilder] deleteField called without active editor");let h=!1;return Y(y=>{if(!y.some(V=>V.id===t))return y;const U=y.filter(V=>V.id!==t);return h=!0,k?.(U),U}),h&&(O?.(t),J(y=>y===t?null:y)),h}let d=!1;try{d=s.commands.deleteStructuredContentById?.(t)??!1}catch(h){console.error("[SuperDocTemplateBuilder] Delete command failed:",h)}let b=pe(s);const F=b.some(h=>h.id===t);!d&&F&&(b=b.filter(h=>h.id!==t));let j=!1;return Y(h=>{if(Ee(h,b))return h;const y=h.some(V=>V.id===t),U=b.some(V=>V.id===t);return y&&!U&&(j=!0),k?.(b),b}),j&&(O?.(t),J(h=>h===t?null:h)),d||j},[O,k]),_=i.useCallback(t=>{if(!T.current?.activeEditor)return;T.current.activeEditor.commands.selectStructuredContentById?.(t),J(t);const d=x.find(b=>b.id===t);d&&A?.(d)},[x,A]),Z=i.useCallback(t=>{if(!t)return;const s=pe(t);Y(d=>Ee(d,s)?d:(k?.(s),s))},[k]);i.useEffect(()=>te.current?((async()=>{const{SuperDoc:s}=await import("superdoc"),d={selector:te.current,document:f?.source,documentMode:f?.mode||"editing",onReady:()=>{if(b.activeEditor){const F=b.activeEditor;F.on("update",({editor:j})=>{const{state:h}=j,{from:y}=h.selection;if(y>=X.length){const ue=y-X.length;if(h.doc.textBetween(ue,y)===X){const me=j.view.coordsAtPos(y),xe=ke(new DOMRect(me.left,me.top,0,0)),ge=()=>{const ie=T.current?.activeEditor;if(!ie)return;const Oe=ie.state.selection.from,Pe=ie.state.tr.delete(ue,Oe);ie.view.dispatch(Pe)};D.current=ge,L.current=y,R(xe),l(!0),m(),H?.({position:{from:ue,to:y},bounds:xe,cleanup:ge});return}}if(!ne.current)return;if(L.current==null){l(!1),m();return}if(y<L.current){l(!1),L.current=null,m();return}const U=h.doc.textBetween(L.current,y);g(U);const V=j.view.coordsAtPos(y),Ne=ke(new DOMRect(V.left,V.top,0,0));R(Ne)}),F.on("update",()=>{Z(F)}),Z(F)}N?.()}},b=new s({...d,...K&&{toolbar:K.selector,modules:{toolbar:{selector:K.selector,toolbarGroups:K.config.toolbarGroups||["center"],excludeItems:K.config.excludeItems||[],...K.config}}}});T.current=b})(),()=>{D.current=null,L.current=null;const s=T.current;s&&typeof s.destroy=="function"&&s.destroy(),T.current=null}):void 0,[f?.source,f?.mode,X,Z,N,H,S]);const de=i.useCallback(async t=>{D.current&&(D.current(),D.current=null),L.current=null,m();const s=t.metadata?.mode||"inline";if(t.id.startsWith("custom_")&&w)try{const d=await w(t);if(d){const b=d.metadata?.mode||s;B(b,{alias:d.label,category:d.category,metadata:d.metadata,defaultValue:d.defaultValue}),l(!1);return}}catch(d){console.error("Field creation failed:",d)}B(s,{alias:t.label,category:t.category,metadata:t.metadata,defaultValue:t.defaultValue}),l(!1)},[B,w,m]),je=i.useCallback(()=>{l(!1),L.current=null,m(),D.current&&(D.current(),D.current=null)},[m]),we=i.useCallback(()=>{if(!T.current?.activeEditor||x.length===0)return;const t=x.findIndex(d=>d.id===I),s=t>=0?(t+1)%x.length:0;_(x[s].id)},[x,I,_]),_e=i.useCallback(()=>{if(!T.current?.activeEditor||x.length===0)return;const t=x.findIndex(d=>d.id===I),s=t>0?t-1:x.length-1;_(x[s].id)},[x,I,_]),Se=i.useCallback(async t=>{const{fileName:s="document",triggerDownload:d=!0}=t||{};try{return await T.current?.export({exportType:["docx"],exportedName:s,triggerDownload:d})}catch(b){throw console.error("Failed to export DOCX",b),b}},[]);i.useImperativeHandle(u,()=>({insertField:t=>B("inline",t),insertBlockField:t=>B("block",t),updateField:Q,deleteField:v,selectField:_,nextField:we,previousField:_e,getFields:()=>x,exportTemplate:Se}));const Fe=r.component||Re,fe=c.component||Ce,K=ze(S);return n.jsxs("div",{className:`superdoc-template-builder ${ee||""}`,style:z,children:[n.jsxs("div",{style:{display:"flex",gap:"20px"},children:[c.position==="left"&&n.jsx("div",{className:"superdoc-template-builder-sidebar",children:n.jsx(fe,{fields:x,onSelect:t=>_(t.id),onDelete:v,onUpdate:t=>Q(t.id,t),selectedFieldId:I||void 0})}),n.jsxs("div",{className:"superdoc-template-builder-document",style:{flex:1},children:[K?.renderDefaultContainer&&n.jsx("div",{id:"superdoc-toolbar",className:"superdoc-template-builder-toolbar","data-testid":"template-builder-toolbar"}),n.jsx("div",{ref:te,className:"superdoc-template-builder-editor",style:{height:G},"data-testid":"template-builder-editor"})]}),c.position==="right"&&n.jsx("div",{className:"superdoc-template-builder-sidebar",children:n.jsx(fe,{fields:x,onSelect:t=>_(t.id),onDelete:v,onUpdate:t=>Q(t.id,t),selectedFieldId:I||void 0})})]}),n.jsx(Fe,{isVisible:$,position:E,availableFields:p.available||[],filteredFields:P,filterQuery:C,allowCreate:p.allowCreate||!1,onSelect:de,onClose:je,onCreateField:w})]})});Te.displayName="SuperDocTemplateBuilder";exports.FieldList=Ce;exports.FieldMenu=Re;exports.default=Te;