@json-to-office/jto 2.3.1 → 3.0.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.
Files changed (57) hide show
  1. package/dist/cli.js +123 -39
  2. package/dist/cli.js.map +1 -1
  3. package/dist/client/assets/HomePage-BlzZ7qG4.js +245 -0
  4. package/dist/client/assets/HomePage-BlzZ7qG4.js.map +1 -0
  5. package/dist/client/assets/{JsonEditorPage-DR9E7ul1.js → JsonEditorPage-kWuP_kL3.js} +3 -3
  6. package/dist/client/assets/{JsonEditorPage-DR9E7ul1.js.map → JsonEditorPage-kWuP_kL3.js.map} +1 -1
  7. package/dist/client/assets/{MonacoPluginProvider-CdHBp1cD.js → MonacoPluginProvider-Dbv1PrO2.js} +6 -6
  8. package/dist/client/assets/{MonacoPluginProvider-CdHBp1cD.js.map → MonacoPluginProvider-Dbv1PrO2.js.map} +1 -1
  9. package/dist/client/assets/{_virtual_jto-plugin-type-libs-BlMraosv.js → _virtual_jto-plugin-type-libs-B6KyD9RL.js} +7912 -3250
  10. package/dist/client/assets/{_virtual_jto-plugin-type-libs-BlMraosv.js.map → _virtual_jto-plugin-type-libs-B6KyD9RL.js.map} +1 -1
  11. package/dist/client/assets/_virtual_jto-sandbox-runtime-Bzo2M5U7.js +2 -0
  12. package/dist/client/assets/_virtual_jto-sandbox-runtime-Bzo2M5U7.js.map +1 -0
  13. package/dist/client/assets/editor-CwEocOY2.js +16 -0
  14. package/dist/client/assets/editor-CwEocOY2.js.map +1 -0
  15. package/dist/client/assets/editor-monaco-json-D_oiidNg.js +24 -0
  16. package/dist/client/assets/editor-monaco-json-D_oiidNg.js.map +1 -0
  17. package/dist/client/assets/index--kF4jVbp.css +1 -0
  18. package/dist/client/assets/index-DFJaEoi0.js +27 -0
  19. package/dist/client/assets/index-DFJaEoi0.js.map +1 -0
  20. package/dist/client/assets/index-UheDso2P.js +2 -0
  21. package/dist/client/assets/index-UheDso2P.js.map +1 -0
  22. package/dist/client/assets/preview-CWdUATNl.js +4 -0
  23. package/dist/client/assets/preview-CWdUATNl.js.map +1 -0
  24. package/dist/client/assets/useQualityAnalysis-Cl4QPeOT.js +6 -0
  25. package/dist/client/assets/useQualityAnalysis-Cl4QPeOT.js.map +1 -0
  26. package/dist/client/index.html +2 -2
  27. package/dist/client/templates/client-report-blocks.docx.json +791 -0
  28. package/dist/client/templates/consulting-deck-blocks.pptx.json +455 -0
  29. package/dist/client/templates/data-report-presentation.pptx.json +108 -36
  30. package/dist/client/templates/management-plan.pptx.json +100 -22
  31. package/dist/client/templates/minimalist-pitch-deck.pptx.json +172 -101
  32. package/dist/prompts/instructions-edit-document-pptx-blocks.md +77 -0
  33. package/dist/prompts/instructions-edit-document-pptx-slides.md +15 -21
  34. package/dist/prompts/instructions-edit-document-pptx.md +34 -53
  35. package/dist/prompts/instructions-edit-pptx.md +9 -8
  36. package/dist/prompts/instructions-generate-pptx.md +13 -17
  37. package/dist/prompts/pptx-core.md +104 -127
  38. package/dist/prompts/pptx-design.md +115 -109
  39. package/package.json +10 -9
  40. package/dist/client/assets/HomePage-Cq_CI7_t.js +0 -251
  41. package/dist/client/assets/HomePage-Cq_CI7_t.js.map +0 -1
  42. package/dist/client/assets/_virtual_jto-sandbox-runtime-XWrhySEO.js +0 -2
  43. package/dist/client/assets/_virtual_jto-sandbox-runtime-XWrhySEO.js.map +0 -1
  44. package/dist/client/assets/editor-D-LgWzQZ.js +0 -16
  45. package/dist/client/assets/editor-D-LgWzQZ.js.map +0 -1
  46. package/dist/client/assets/editor-monaco-json-BVkSRpj1.js +0 -24
  47. package/dist/client/assets/editor-monaco-json-BVkSRpj1.js.map +0 -1
  48. package/dist/client/assets/editor-refs-store-COFjkOeo.js +0 -2
  49. package/dist/client/assets/editor-refs-store-COFjkOeo.js.map +0 -1
  50. package/dist/client/assets/index-B9j3hDSy.js +0 -5
  51. package/dist/client/assets/index-B9j3hDSy.js.map +0 -1
  52. package/dist/client/assets/index-Bj6ZAKUc.css +0 -1
  53. package/dist/client/assets/preview-D0HsunpU.js +0 -4
  54. package/dist/client/assets/preview-D0HsunpU.js.map +0 -1
  55. package/dist/client/assets/useQualityAnalysis-PZsxJDvP.js +0 -6
  56. package/dist/client/assets/useQualityAnalysis-PZsxJDvP.js.map +0 -1
  57. package/dist/prompts/instructions-edit-document-pptx-templates.md +0 -63
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_virtual_jto-sandbox-runtime-Bzo2M5U7.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,16 @@
1
+ import{c as W,r as u,j as t}from"./react-vendor-BmQ2Ko_D.js";import{g as Nt,c as St,V as Ut,a as Kt,E as bn}from"./editor-monaco-json-D_oiidNg.js";import{i as Jt,h as ye,t as Wt,v as He,F as Z,c as _,e as Ee,f as Te,g as Re,o as yn,u as jn,S as kt}from"./index-DFJaEoi0.js";import Qt,{DiffEditor as Cn}from"./monaco-editor-DJsdM0WK.js";import{a as ue,f as je,g as dt,u as be,P as wn,B as rt,p as vn,n as ot,o as Nn,q as Sn,r as kn,t as En,w as Tn,b as qt,d as Rn,x as Mn,y as An,T as Dn,z as Ln}from"./MonacoPluginProvider-Dbv1PrO2.js";import{B as Me,d as Xt}from"./index-UheDso2P.js";import{I as _e,S as Ce,a as we,b as ve,c as Ne,d as he,e as Pn,t as On,B as at,D as In,f as _n,g as zn,h as Fn,i as $n,j as Vn,k as Yt,l as Hn,T as Bn,m as Gn,u as Un,n as Kn,Q as Jn,o as Wn}from"./HomePage-BlzZ7qG4.js";import{r as pe,i as Zt,n as mt,u as en,I as Ue,c as Et,E as ge,C as Tt,G as ft,a as Qn,b as ie,H as ne,d as ze,e as qn,Q as de,D as tn,g as ce,P as Xn,F as pt,f as Ge,h as Se,M as it,j as Xe,S as Ae,k as Yn,t as Zn,l as es,s as nn,m as ts,o as ns,p as sn,q as Ke,v as ss,w as rs,x as os,y as as,z as Rt,T as is,A as ls,B as cs,J as us,K as ds,L as ms,N as fs,O as ps,R as Mt,U as hs,V as gs,W as xs}from"./useQualityAnalysis-Cl4QPeOT.js";import{ad as bs,ae as ys,af as js,ag as rn}from"./radix-ui-BzbaiLpZ.js";import{a8 as Cs,X as on,a as ht,a9 as ws,T as vs,aa as Ns,O as an,e as At,_ as Ss,x as gt,B as Je,h as ks,y as Es,t as Ts,v as Rs,ab as Ms,ac as As}from"./ui-vendor-BsAtAN16.js";import{u as Dt}from"./state-vendor-Cq67_JbF.js";import"./query-vendor--rhYD8mC.js";const Ds={initWith:function(e){const n=document.createElement("div"),s=e.editor.create(n),r=s.constructor.name,a=s.getModel().constructor.name;return{isInstanceValid:function(c){return c.constructor.name===r},isModelValid:function(c){return c.constructor.name===a},isRangesValid:function(c){return Array.isArray(c)?c.every(function(d){return typeof d=="object"&&d.constructor.name==="Object"?!(!d.hasOwnProperty("range")||!Array.isArray(d.range)||d.range.length!==4||!d.range.every(f=>f>0&&parseInt(f)===f)||d.hasOwnProperty("allowMultiline")&&typeof d.allowMultiline!="boolean"||d.hasOwnProperty("label")&&typeof d.label!="string"||d.hasOwnProperty("validate")&&typeof d.validate!="function"):!1}):!1}}}},$e=function(e,n,s){return"The value for the "+n+" should be of type "+(Array.isArray(e)?e.join(" | "):e)+". "+(s||"")},Ye=function(){const e=function(o,l){return typeof o!="object"||o===null?this.freeze?Object.freeze(o):o:o instanceof Date?this.freeze?Object.freeze(new Date(o)):new Date(o):l.call(this,o)},n=function(o,l){const c=Object.keys(o),d=new Array(c.length);for(let f=0;f<c.length;f++)d[c[f]]=e.call(this,o[c[f]],l);return d},s=function(o){return e.call(this,o,function(l){if(Array.isArray(l))return n.call(this,l,s);const c={};for(let d in l)!this.withProto&&Object.hasOwnProperty.call(l,d)===!1||(c[d]=e.call(this,l[d],s));return c})},r=function(){const o=function(c){const d=["withProto","freeze"];this[c]=d.reduce((function(f,m){return(f[m]=c>=this[m])&&(c-=this[m]),f}).bind(this),{})},l=Object.create(Object.defineProperties({},{withProto:{value:1},freeze:{value:2}}));for(let c=0;c<=3;c++)o.call(l,c);return l}(),a={withProto:s.bind(r[1]),andFreeze:s.bind(r[2]),withProtoAndFreeze:s.bind(r[3])},i=s.bind(r[0]);for(let o in a)Object.defineProperty(i,o,{enumerable:!1,writable:!1,configurable:!1,value:a[o]});return i}(),Lt={SINGLE_LINE_HIGHLIGHT_CLASS:"editableArea--single-line",MULTI_LINE_HIGHLIGHT_CLASS:"editableArea--multi-line"},Ls=function(e,n,s){const r=s.Range,a=function(h,C){const b=h.range,S=C.range;if(b[0]<S[0]||b[0]===S[0]&&b[3]<S[1])return-1},i=function(h,C){const b=C.split(`
2
+ `),S=b.length,E=[];return h.forEach(function(M,P){if(M===0)throw new Error("Range values cannot be zero");switch(P){case 0:{if(M<0)throw new Error("Start Line of Range cannot be negative");if(M>S)throw new Error("Provided Start Line("+M+") is out of bounds. Max Lines in content is "+S);E[P]=M}break;case 1:{let z=M;const H=E[0],B=b[H-1].length;if(z<0){if(z=B-Math.abs(z),z<0)throw new Error("Provided Start Column("+M+") is out of bounds. Max Column in line "+H+" is "+B)}else if(z>B+1)throw new Error("Provided Start Column("+M+") is out of bounds. Max Column in line "+H+" is "+B);E[P]=z}break;case 2:{let z=M;if(z<0){if(z=S-Math.abs(M),z<0)throw new Error("Provided End Line("+M+") is out of bounds. Max Lines in content is "+S);z<E[0]&&console.warn("Provided End Line("+M+") is less than the start Line, the Restriction may not behave as expected")}else if(M>S)throw new Error("Provided End Line("+M+") is out of bounds. Max Lines in content is "+S);E[P]=z}break;case 3:{let z=M;const H=E[2],B=b[H-1].length;if(z<0){if(z=B-Math.abs(z),z<0)throw new Error("Provided End Column("+M+") is out of bounds. Max Column in line "+H+" is "+B)}else if(z>B+1)throw new Error("Provided Start Column("+M+") is out of bounds. Max Column in line "+H+" is "+B);E[P]=z}break}}),E};let o=Ye(n).sort(a);const l=function(h){const C=e.getValue();h.forEach(function(b,S){const E=i(b.range,C),M=E[0],P=E[1],z=E[2],H=E[3];b._originalRange=E.slice(),b.range=new r(M,P,z,H),b.index=S,b.allowMultiline||(b.allowMultiline=r.spansMultipleLines(b.range)),b.label||(b.label=`[${M},${P} -> ${z}${H}]`)})},c=function(){return o.reduce(function(h,C){return h[C.label]={allowMultiline:C.allowMultiline||!1,index:C.index,range:Object.assign({},C.range),originalRange:C._originalRange.slice()},h},{})},d=function(){return o.reduce(function(h,C){return h[C.label]=e.getValueInRange(C.range),h},{})},f=function(h,C){if(typeof h=="object"&&!Array.isArray(h)){C=typeof C=="boolean"?C:!1;const b=o.reduce(function(S,E){return E.label&&(S[E.label]=E),S},{});for(let S in h){const E=b[S];if(E){const M=h[S];if(L(E,M))throw new Error("Multiline change is not allowed for "+S);const P=Ye(E.range);if(P.endLine=P.startLine+M.split(`
3
+ `).length-1,P.endColumn=M.split(`
4
+ `).pop().length,T(E,M,P))throw new Error("Change is invalidated by validate function of "+S);e.applyEdits([{forceMoveMarkers:!!C,range:E.range,text:M}])}else console.error("No restriction found for "+S)}}else throw new Error("Value must be an object")},m=function(){return e._restrictionChangeListener.dispose(),window.removeEventListener("error",O),delete e.editInRestrictedArea,delete e.disposeRestrictions,delete e.getValueInEditableRanges,delete e.updateValueInEditableRanges,delete e.updateRestrictions,delete e.getCurrentEditableRanges,delete e.toggleHighlightOfEditableAreas,delete e._hasHighlight,delete e._isRestrictedModel,delete e._isCursorAtCheckPoint,delete e._currentCursorPositions,delete e._editableRangeChangeListener,delete e._restrictionChangeListener,delete e._oldDecorations,delete e._oldDecorationsSource,e},x=function(h){h.some(function(C){const b=C.lineNumber,S=C.column,E=o.length;for(let M=0;M<E;M++){const P=o[M].range;if(P.startLineNumber===b&&P.startColumn===S||P.endLineNumber===b&&P.endColumn===S)return e.pushStackElement(),!0}})},y=function(h){typeof h=="function"&&e._editableRangeChangeListener.push(h)},p=function(h,C){const b=c();e._editableRangeChangeListener.forEach(function(S){S.call(e,h,C,b)})},j=function(){return Promise.resolve().then(function(){e.editInRestrictedArea=!0,e.undo(),e.editInRestrictedArea=!1,e._hasHighlight&&e._oldDecorationsSource&&(e.deltaDecorations(e._oldDecorations,e._oldDecorationsSource),e._oldDecorationsSource.forEach(function(h){h.range=e.getDecorationRange(h.id)}))})},v=function(h,C,b,S,E,M){let P=C.endLineNumber,z=C.endColumn;h.prevRange=C,h.range=C.setEndPosition(b,S);const H=o.length;let B=E.length;const G=S-z,Y=b-P,ee=e._currentCursorPositions||[],me=ee.length;if(B!==me&&(E=E.filter(function(K){const U=K.range;for(let g=0;g<me;g++){const k=ee[g];if(U.startLineNumber===k.startLineNumber&&U.endLineNumber===k.endLineNumber&&U.startColumn===k.startColumn&&U.endColumn===k.endColumn)return!0}return!1}),B=E.length),Y!==0){for(let K=h.index+1;K<H;K++){const U=o[K],g=U.range;P===g.startLineNumber&&(g.startColumn+=G),P===g.endLineNumber&&(g.endColumn+=G),g.startLineNumber+=Y,g.endLineNumber+=Y,U.range=g}for(let K=M+1;K<B;K++){const U=E[K],g=U.range,k=g.toString(),N=rangeMap[k];delete rangeMap[k],P===g.startLineNumber&&(g.startColumn+=G),P===g.endLineNumber&&(g.endColumn+=G),g.startLineNumber+=Y,g.endLineNumber+=Y,U.range=g,rangeMap[g.toString()]=N}}else{for(let K=h.index+1;K<H;K++){const U=o[K],g=U.range;if(g.startLineNumber>P)break;g.startColumn+=G,g.endColumn+=G,U.range=g}for(let K=M+1;K<B;K++){const U=E[K],g=U.range,k=g.toString(),N=rangeMap[k];if(delete rangeMap[k],g.startLineNumber>P){rangeMap[g.toString()]=N;break}else g.startColumn+=G,g.endColumn+=G,U.range=g,rangeMap[g.toString()]=N}}},A=function(h,C){const b={},S=h.range;return h.text===""?b.isDeletion=!0:S.startLineNumber===S.endLineNumber&&S.startColumn===S.endColumn?b.isAddition=!0:b.isReplacement=!0,b.startLineOfRange=S.startLineNumber===C.startLineNumber,b.startColumnOfRange=S.startColumn===C.startColumn,b.endLineOfRange=S.endLineNumber===C.endLineNumber,b.endColumnOfRange=S.endColumn===C.endColumn,b.middleLineOfRange=!b.startLineOfRange&&!b.endLineOfRange,C.startLineNumber===C.endLineNumber?b.rangeIsSingleLine=!0:b.rangeIsMultiLine=!0,b},D=function(h){o=Ye(h).sort(a),l(o)},V=function(h){if(e._hasHighlight)e.deltaDecorations(e._oldDecorations,[]),delete e._oldDecorations,delete e._oldDecorationsSource,e._hasHighlight=!1;else{const C=h.cssClassForSingleLine||Lt.SINGLE_LINE_HIGHLIGHT_CLASS,b=h.cssClassForMultiLine||Lt.MULTI_LINE_HIGHLIGHT_CLASS,S=o.map(function(E){const M={range:E.range,options:{className:E.allowMultiline?b:C}};return E.label&&(M.hoverMessage=E.label),M});e._oldDecorations=e.deltaDecorations([],S),e._oldDecorationsSource=S.map(function(E,M){return Object.assign({},E,{id:e._oldDecorations[M]})}),e._hasHighlight=!0}},O=function(){console.debug("handler for unhandled promise rejection")},se=function(h){for(let C in h){const b=h[C];b.range=b.prevRange}},L=function(h,C){return!h.allowMultiline&&C.includes(`
5
+ `)},T=function(h,C,b){return h.validate&&!h.validate(C,b,h.lastInfo)},$={_isRestrictedModel:!0,_isRestrictedValueValid:!0,_editableRangeChangeListener:[],_isCursorAtCheckPoint:x,_currentCursorPositions:[]};l(o),e._hasHighlight=!1,$._restrictionChangeListener=e.onDidChangeContent(function(h){const C=h.isUndoing;if(e._isRestrictedValueValid=!0,C&&e.editInRestrictedArea)e.editInRestrictedArea&&(e._isRestrictedValueValid=!1);else{const b=h.changes.sort(a),S={},E=o.length;if(b.every(function(P){const z=P.range,H=z.toString();S[H]=null;for(let B=0;B<E;B++){const G=o[B];if(G.range.containsRange(z))return L(G,P.text)?!1:(S[H]=G,!0)}return!1})){b.forEach(function(H,B){const G=H.range,Y=S[G.toString()],ee=Y.range,me=H.text||"",K=(me.match(/\n/g)||[]).length,U=me.split(/\n/g).pop().length,g=G.endLineNumber-G.startLineNumber,k=G.endColumn-G.startColumn;let N=ee.endLineNumber,R=ee.endColumn,F=0;(ee.endLineNumber===G.startLineNumber||ee.endLineNumber===G.endLineNumber)&&(F+=ee.endColumn-G.startColumn+1);const I=A(H,ee);Y.lastInfo=I,(I.isAddition||I.isReplacement)&&(I.rangeIsSingleLine&&(K===0?R+=U:(N+=K,I.startColumnOfRange?R+=U:I.endColumnOfRange?R=U+1:R=U+F)),I.rangeIsMultiLine&&(N+=K,I.endLineOfRange&&(K===0?R+=U:R=F+U))),(I.isDeletion||I.isReplacement)&&(I.rangeIsSingleLine&&(R-=k),I.rangeIsMultiLine&&(I.endLineOfRange?(N-=g,R-=k):N-=g)),v(Y,ee,N,R,b,B)});const P=e.getValueInEditableRanges(),z={};for(let H in S){const B=S[H],G=B.range,Y=B.label||G.toString(),ee=P[Y];if(T(B,ee,G)){se(S),j();return}z[Y]=ee}e._hasHighlight&&e._oldDecorationsSource.forEach(function(H){H.range=e.getDecorationRange(H.id)}),p(z,P)}else j()}}),window.onerror=O;const w={editInRestrictedArea:!1,getCurrentEditableRanges:c,getValueInEditableRanges:d,disposeRestrictions:m,onDidChangeContentInEditableRange:y,updateRestrictions:D,updateValueInEditableRanges:f,toggleHighlightOfEditableAreas:V};for(let h in $)Object.defineProperty(e,h,{enumerable:!1,configurable:!0,writable:!0,value:$[h]});for(let h in w)Object.defineProperty(e,h,{enumerable:!1,configurable:!0,writable:!0,value:w[h]});return e};function Ps(e){if(e===void 0)throw new Error(["Please pass the monaco global variable into function as","(eg:)constrainedEditor({ range : monaco.range });"].join(`
6
+ `));const n=function(p){const j=p.getModel();if(j._isCursorAtCheckPoint){const v=p.getSelections(),A=v.map(function(D){return{lineNumber:D.positionLineNumber,column:D.positionColumn}});j._isCursorAtCheckPoint(A),j._currentCursorPositions=v}},s={},{isInstanceValid:r,isModelValid:a,isRangesValid:i}=Ds.initWith(e),o=function(p){if(r(p)){let j=p.getDomNode();return m._listener=n.bind(x,p),m._editorInstance=p,m._editorInstance._isInDevMode=!1,j.addEventListener("keydown",m._listener,!0),m._onChangeModelDisposable=p.onDidChangeModel(function(){j&&j.removeEventListener("keydown",m._listener,!0);const v=p.getDomNode();v&&v.addEventListener("keydown",m._listener,!0),j=v}),!0}else throw new Error($e("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},l=function(p,j){if(a(p))if(i(j)){const v=Ls(p,j,e);return s[v.uri.toString()]=v,v}else throw new Error($e("Array<RangeRestrictionObject>","ranges","Please refer constrained editor documentation for proper structure"));else throw new Error($e("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},c=function(p){if(a(p)){const j=p.uri.toString(),v=s[j];return v?v.disposeRestrictions():(console.warn("Current Model is not a restricted Model"),!1)}else throw new Error($e("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},d=function(){if(m._editorInstance){const j=m._editorInstance.getDomNode();j&&j.removeEventListener("keydown",m._listener),m._onChangeModelDisposable&&m._onChangeModelDisposable.dispose(),delete m._listener,delete m._editorInstance._isInDevMode,delete m._editorInstance._devModeAction,delete m._editorInstance,delete m._onChangeModelDisposable;for(let v in s)delete s[v];return!0}return!1},f=function(){m._editorInstance._isInDevMode?(m._editorInstance._isInDevMode=!1,m._editorInstance._devModeAction.dispose(),delete m._editorInstance._devModeAction):(m._editorInstance._isInDevMode=!0,m._editorInstance._devModeAction=m._editorInstance.addAction({id:"showRange",label:"Show Range in console",contextMenuGroupId:"navigation",contextMenuOrder:1.5,run:function(p){const v=p.getSelections().reduce(function(A,{startLineNumber:D,endLineNumber:V,startColumn:O,endColumn:se}){return A.push("range : "+JSON.stringify([D,O,V,se])),A},[]).join(`
7
+ `);console.log(`Selected Ranges :
8
+ `+JSON.stringify(v,null,2))}}))},m={_listener:null,_editorInstance:null,_uriRestrictionMap:s,_injectedResources:e},x=Object.create(m),y={initializeIn:o,addRestrictionsTo:l,removeRestrictionsIn:c,disposeConstrainer:d,toggleDevMode:f};for(let p in y)Object.defineProperty(x,p,{enumerable:!1,writable:!1,configurable:!1,value:y[p]});return Object.freeze(x)}function Os(e){const n=`.${Z}.theme.json`;return e.endsWith(n)?e:e.replace(/\.\w+\.theme\.json$/,"").replace(/\.theme\.json$/,"").replace(/\.json$/,"")+n}function Is({document:e,readOnly:n=!1,onChange:s}){const r=u.useRef(null),a=u.useRef(null),i=u.useRef(null),{theme:o}=Jt(),[l,c]=u.useState([]),[d,f]=u.useState(!0),[m,x]=u.useState(!1),y=u.useRef(!1),p=ue(h=>h.pendingDiffs[e.name]),j=ue(h=>h.clearPendingDiff),v=ue(h=>h.saveDocument),{registerEditor:A,unregisterEditor:D,setActiveEditor:V}=ye(),O=o==="system"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":o,se=u.useCallback(h=>{a.current=h,Wt(h)},[]),L=u.useCallback((h,C)=>{r.current=h,i.current=h.getModel(),A(e.name,h,C),V(e.name);const b=Ps(C);h.getModel()&&b.initializeIn(h),h.updateOptions({formatOnType:!0,formatOnPaste:!0,automaticLayout:!0,minimap:{enabled:!1},scrollBeyondLastLine:!0,wordWrap:"on",folding:!0,foldingStrategy:"indentation",suggest:{showColors:!0,showConstants:!0,showEnums:!0,showFields:!0,showFunctions:!0,showKeywords:!0,showModules:!0,showProperties:!0,showSnippets:!0,showStructs:!0,showTypeParameters:!0,showUnits:!0,showValues:!0,showVariables:!0}}),h.addCommand(C.KeyMod.CtrlCmd|C.KeyCode.KeyK,()=>{const E=Nt(h,C);if(E){const M=St(E);window.dispatchEvent(new CustomEvent("monaco-selection-to-ai",{detail:{documentName:e.name,selection:E,snippet:M,isTheme:!0}}))}}),h.addCommand(C.KeyMod.CtrlCmd|C.KeyCode.KeyS,()=>{console.log("Save command triggered in theme editor")}),h.addAction({id:"send-theme-to-ai-assistant",label:"Send to AI Assistant (⌘K)",contextMenuGroupId:"navigation",contextMenuOrder:1.5,keybindings:[C.KeyMod.CtrlCmd|C.KeyCode.KeyK],run:function(){const E=Nt(h,C);if(E){const M=St(E);window.dispatchEvent(new CustomEvent("monaco-selection-to-ai",{detail:{documentName:e.name,selection:E,snippet:M,isTheme:!0}}))}}}),setTimeout(()=>{var E;(E=h.getAction("editor.action.formatDocument"))==null||E.run()},100),console.log("Monaco theme editor mounted")},[e.name,A,V]);u.useEffect(()=>()=>{D(e.name)},[e.name,D]);const T=u.useCallback((h,C)=>{h!==void 0&&s&&s(h)},[s]),$=u.useCallback(h=>{const C=h.map(b=>{var S;return{path:"",message:b.message,code:typeof b.code=="string"?b.code:((S=b.code)==null?void 0:S.value)||"validation_error",startLineNumber:b.startLineNumber,startColumn:b.startColumn,endLineNumber:b.endLineNumber,endColumn:b.endColumn,severity:b.severity>=8?"error":b.severity>=4?"warning":"info"}});c(C),C.length>0&&!y.current&&(f(!0),x(!1)),C.length===0&&(y.current=!1)},[]),w=u.useCallback(h=>{r.current&&h.startLineNumber&&h.startColumn&&(r.current.setPosition({lineNumber:h.startLineNumber,column:h.startColumn}),r.current.revealLineInCenter(h.startLineNumber),r.current.focus())},[]);return u.useEffect(()=>{r.current&&r.current.updateOptions({theme:He(O)})},[O]),t.jsxs("div",{className:"relative h-full",children:[p?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center justify-between px-2 py-1 border-b bg-muted/40 text-xs",children:[t.jsxs("div",{children:["Review changes for"," ",t.jsx("span",{className:"font-medium",children:e.name})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>j(e.name),children:"Discard"}),t.jsx(Me,{size:"sm",onClick:()=>{v(e.name,p.modified),j(e.name,!0)},children:"Apply Changes"})]})]}),t.jsx(Cn,{height:"calc(100% - 32px)",original:p.original,modified:p.modified,language:"json",theme:He(O),options:{readOnly:!0,renderSideBySide:!0,originalEditable:!1,automaticLayout:!0,minimap:{enabled:!1}},beforeMount:se})]}):t.jsx(Qt,{height:"100%",language:"json",defaultPath:Os(e.name),value:e.text,theme:He(O),onChange:T,beforeMount:se,onMount:L,onValidate:$,options:{readOnly:n,lineNumbers:"on",glyphMargin:!0,folding:!0,lineDecorationsWidth:5,lineNumbersMinChars:3,renderValidationDecorations:"on",quickSuggestions:{other:!0,comments:!1,strings:!0},acceptSuggestionOnCommitCharacter:!0,acceptSuggestionOnEnter:"on",accessibilitySupport:"auto",autoIndent:"advanced",formatOnType:!0,formatOnPaste:!0,automaticLayout:!0,minimap:{enabled:!1},scrollBeyondLastLine:!0,wordWrap:"on"}}),t.jsx("div",{className:"absolute top-0 right-0",children:t.jsx(Ut,{errors:l,onClick:()=>{f(!0),x(!1)}})}),d&&l.length>0&&t.jsx(Kt,{errors:l,isMinimized:m,onToggleMinimize:()=>x(!m),onErrorClick:w,onClose:()=>{f(!1),y.current=!0},className:"z-40"})]})}const _s=W.memo(Is);function ln(e){if(/^[a-z]\d+$/.test(e))return e.toUpperCase();const n=e.replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)}const zs=/\[0-9A-Fa-f\]\{6\}/;function cn(e){if(Array.isArray(e.enum))return e.enum.every(s=>typeof s=="string")?e.enum:void 0;const n=e.anyOf??e.oneOf;if(Array.isArray(n)&&n.length>0&&n.every(s=>s&&typeof s=="object"&&typeof s.const=="string"))return n.map(s=>s.const)}function Pt(e){if(cn(e))return"enum";switch(e.type){case"string":return typeof e.pattern=="string"&&zs.test(e.pattern)?"color":"text";case"number":case"integer":return"number";case"boolean":return"boolean";default:return}}function lt(e,n,s,r=!1){const a={kind:"json",key:e,path:s,label:ln(e),...typeof(n==null?void 0:n.description)=="string"&&{hint:n.description},...r&&{required:r}};if(!n||typeof n!="object")return a;const i=Pt(n);if(i){const o={...a,kind:i};if(i==="enum"&&(o.options=cn(n)),i==="number"){const l=n.type==="integer",c=l?1:.5,d=n.minimum??(typeof n.exclusiveMinimum=="number"?n.exclusiveMinimum+c:void 0),f=n.maximum??(typeof n.exclusiveMaximum=="number"?n.exclusiveMaximum-c:void 0);d!==void 0&&(o.min=d),f!==void 0&&(o.max=f),l&&(o.integer=!0)}return o}if(n.type==="object"&&n.properties){const o=new Set(n.required??[]);return{...a,kind:"group",children:Object.entries(n.properties).filter(([l])=>l!=="$schema").map(([l,c])=>lt(l,c,[...s,l],o.has(l)))}}return n.type==="array"&&n.items&&typeof n.items=="object"&&!Array.isArray(n.items)&&Pt(n.items)?{...a,kind:"list",item:lt("item",n.items,[...s,0]),...typeof n.maxItems=="number"&&{max:n.maxItems},...typeof n.minItems=="number"&&{min:n.minItems}}:a}const Fs={palette:"Palette",typography:"Type roles & scale",spacing:"Spacing",chrome:"Chrome recipes",motif:"Motif",componentDefaults:"Component defaults"};function $s(e,n){if(!(e!=null&&e.properties))return[];const s=new Set(n);return Object.entries(e.properties).filter(([r,a])=>!s.has(r)&&r!=="$schema"&&a&&typeof a=="object"&&a.type==="object"&&a.properties).map(([r,a])=>{const i=lt(r,a,[r]);return{key:r,title:Fs[r]??ln(r),...i.hint&&{hint:i.hint},fields:i.children??[]}})}function le(e,...n){const s=e.trim().toLowerCase();return s?n.some(r=>r==null?void 0:r.toLowerCase().includes(s)):!0}function un(e,n){if(!n.trim())return[...e];const s=[];for(const r of e){const a=le(n,r.key,r.label,r.hint,r.path.join("."));if(r.kind==="group"&&r.children)if(a)s.push(r);else{const i=un(r.children,n);i.length&&s.push({...r,children:i})}else a&&s.push(r)}return s}function xt(e,n){if(n===void 0)return null;switch(e.kind){case"text":case"color":case"enum":return typeof n=="string"?null:"Not a string";case"number":return typeof n=="number"?null:"Not a number";case"boolean":return typeof n=="boolean"?null:"Not a boolean";case"list":return Array.isArray(n)?null:"Not a list";case"group":return n&&typeof n=="object"&&!Array.isArray(n)?null:"Not an object";default:return null}}function dn(e,n){const s=pe(e,n);if(s)return s;if(typeof n!="string")return null;const r=e.palette,a=r==null?void 0:r[n];return typeof a!="string"||a===n?null:Zt(a)?a:pe(e,a)}function De(e){if(e===void 0)return"Not set";if(Array.isArray(e))return`${e.length} item${e.length===1?"":"s"}`;if(e&&typeof e=="object"){const s=Object.keys(e);return s.length===0?"Empty":s.slice(0,4).join(", ")+(s.length>4?", …":"")}const n=String(e);return n.length>40?`${n.slice(0,40)}…`:n}let Ve=null;async function Vs(){if(Ve)return Ve;const n=await(await fetch("/api/discovery/schemas/theme")).json();if(!n.success)throw new Error(n.error??"Failed to fetch theme schema");return Ve=n.data,Ve}const bt=bs,yt=ys,We=u.forwardRef(({className:e,align:n="start",sideOffset:s=4,...r},a)=>t.jsx(js,{children:t.jsx(rn,{ref:a,align:n,sideOffset:s,className:_("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 rounded-lg border p-3 shadow-lg outline-none",e),...r})}));We.displayName=rn.displayName;function mn(e){const n=e.match(/^#?([0-9A-Fa-f]{6})$/);if(!n)return null;const s=parseInt(n[1],16);return{r:s>>16&255,g:s>>8&255,b:s&255}}function Hs({r:e,g:n,b:s}){const r=a=>Math.max(0,Math.min(255,Math.round(a))).toString(16).padStart(2,"0").toUpperCase();return`#${r(e)}${r(n)}${r(s)}`}function Bs({r:e,g:n,b:s}){const r=e/255,a=n/255,i=s/255,o=Math.max(r,a,i),l=Math.min(r,a,i),c=o-l;let d=0;return c!==0&&(o===r?d=(a-i)/c%6:o===a?d=(i-r)/c+2:d=(r-a)/c+4,d*=60,d<0&&(d+=360)),{h:d,s:o===0?0:c/o,v:o}}function Gs({h:e,s:n,v:s}){const r=(e%360+360)%360,a=s*n,i=a*(1-Math.abs(r/60%2-1)),o=s-a,[l,c,d]=r<60?[a,i,0]:r<120?[i,a,0]:r<180?[0,a,i]:r<240?[0,i,a]:r<300?[i,0,a]:[a,0,i];return{r:(l+o)*255,g:(c+o)*255,b:(d+o)*255}}function Ot(e){const n=mn(e);return n?Bs(n):null}function Le(e){return Hs(Gs(e))}function Us(e){const n=mn(e);return n?(n.r*299+n.g*587+n.b*114)/1e3>140?"#000000":"#FFFFFF":"#000000"}const Ks=/^[a-zA-Z][a-zA-Z0-9]*$/,Be="#D4D4D8";function Js(e){const n=u.useRef(null),s=u.useRef(null),r=u.useRef(e);r.current=e;const a=u.useCallback(()=>{s.current=null;const l=n.current;n.current=null,l!==null&&r.current(l)},[]),i=u.useCallback(l=>{n.current=l,s.current===null&&(s.current=requestAnimationFrame(a))},[a]),o=u.useCallback(()=>{s.current!==null&&(cancelAnimationFrame(s.current),a())},[a]);return u.useEffect(()=>()=>{s.current!==null&&cancelAnimationFrame(s.current)},[]),{schedule:i,finish:o}}function fn(e,n){const s=u.useRef(null),r=u.useCallback(l=>{var m;const c=(m=s.current)==null?void 0:m.getBoundingClientRect();if(!c||c.width===0||c.height===0)return;const d=(l.clientX-c.left)/c.width,f=(l.clientY-c.top)/c.height;e(Math.min(1,Math.max(0,d)),Math.min(1,Math.max(0,f)))},[e]),a=u.useCallback(l=>{l.preventDefault(),l.currentTarget.setPointerCapture(l.pointerId),r(l)},[r]),i=u.useCallback(l=>{l.currentTarget.hasPointerCapture(l.pointerId)&&r(l)},[r]),o=u.useCallback(l=>{l.currentTarget.hasPointerCapture(l.pointerId)&&l.currentTarget.releasePointerCapture(l.pointerId),n()},[n]);return{ref:s,onPointerDown:a,onPointerMove:i,onPointerUp:o}}function Ws({hsv:e,onChange:n,onEnd:s}){const r=u.useCallback((o,l)=>n({...e,s:o,v:1-l}),[e,n]),a=fn(r,s),i=u.useCallback(o=>{const l=o.shiftKey?.1:.02,d={ArrowLeft:{s:Math.max(0,e.s-l)},ArrowRight:{s:Math.min(1,e.s+l)},ArrowUp:{v:Math.min(1,e.v+l)},ArrowDown:{v:Math.max(0,e.v-l)}}[o.key];d&&(o.preventDefault(),n({...e,...d}),s())},[e,n,s]);return t.jsxs("div",{ref:a.ref,role:"application","aria-label":"Saturation and brightness",tabIndex:0,onPointerDown:a.onPointerDown,onPointerMove:a.onPointerMove,onPointerUp:a.onPointerUp,onKeyDown:i,className:_("relative h-32 w-full cursor-crosshair touch-none overflow-hidden rounded-sm border","focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"),style:{backgroundColor:Le({h:e.h,s:1,v:1})},children:[t.jsx("div",{className:"absolute inset-0 bg-[linear-gradient(to_right,#fff,transparent)]"}),t.jsx("div",{className:"absolute inset-0 bg-[linear-gradient(to_top,#000,transparent)]"}),t.jsx("span",{"aria-hidden":!0,className:"absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.45)]",style:{left:`${e.s*100}%`,top:`${(1-e.v)*100}%`,backgroundColor:Le(e)}})]})}const Qs="linear-gradient(to right,#FF0000,#FFFF00,#00FF00,#00FFFF,#0000FF,#FF00FF,#FF0000)";function qs({hsv:e,onChange:n,onEnd:s}){const r=u.useCallback(i=>n({...e,h:i*360}),[e,n]),a=fn(r,s);return t.jsx("div",{ref:a.ref,role:"slider","aria-label":"Hue","aria-valuemin":0,"aria-valuemax":360,"aria-valuenow":Math.round(e.h),tabIndex:0,onPointerDown:a.onPointerDown,onPointerMove:a.onPointerMove,onPointerUp:a.onPointerUp,onKeyDown:i=>{const o=i.key==="ArrowLeft"?-1:i.key==="ArrowRight"?1:0;o&&(i.preventDefault(),n({...e,h:(e.h+o*(i.shiftKey?10:2)+360)%360}),s())},className:_("relative h-3 w-full cursor-ew-resize touch-none rounded-full border","focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"),style:{background:Qs},children:t.jsx("span",{"aria-hidden":!0,className:"absolute top-1/2 size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgba(0,0,0,0.45)]",style:{left:`${e.h/360*100}%`,backgroundColor:Le({h:e.h,s:1,v:1})}})})}function Xs({tokens:e,active:n,onPick:s}){return t.jsx("div",{className:"flex flex-wrap gap-1",children:e.map(r=>{const a=r.key===n;return t.jsxs(Ee,{children:[t.jsx(Te,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>s(r.key),"aria-label":`Use token ${r.key}`,"aria-pressed":a,className:_("flex size-6 cursor-pointer items-center justify-center rounded-sm border","transition-shadow focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none",a?"ring-1 ring-ring ring-offset-1 ring-offset-popover":"border-border/70"),style:{backgroundColor:r.hex},children:a&&t.jsx(ht,{className:"size-3",style:{color:Us(r.hex)},"aria-hidden":!0})})}),t.jsx(Re,{side:"bottom",children:t.jsxs("p",{className:"font-mono text-xs",children:[r.key," ",r.hex]})})]},r.key)})})}function Fe({id:e,label:n,value:s,resolved:r,onCommit:a,allowReference:i=!0,tokens:o,className:l}){const[c,d]=u.useState(!1),f=u.useCallback(p=>{const j=p.trim();if(j===""){a(null);return}const v=mt(j);if(/^#[0-9A-F]{6}$/.test(v)){a(v);return}i&&Ks.test(j)&&a(j)},[i,a]),{props:m}=en(s??"",f),x=r??Be,y=s&&!s.startsWith("#")?s:null;return t.jsxs("div",{className:_("flex min-w-0 items-center gap-1.5",l),children:[t.jsxs(bt,{open:c,onOpenChange:d,children:[t.jsx(yt,{asChild:!0,children:t.jsx("button",{type:"button","aria-label":`${n} picker`,className:_("relative size-6 shrink-0 cursor-pointer overflow-hidden rounded-sm border","transition-shadow focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none",r?"border-border hover:ring-1 hover:ring-ring/50":"border-dashed border-muted-foreground/40 opacity-60"),style:{backgroundColor:x}})}),t.jsx(We,{className:"w-64",children:t.jsx(Ys,{label:n,value:s,resolved:r,tokens:i?o:void 0,onCommit:a,onDone:()=>d(!1)})})]}),t.jsx(_e,{id:e,type:"text","aria-label":n,autoComplete:"off",spellCheck:!1,placeholder:"#RRGGBB",title:y&&r?`${y} → ${r}`:void 0,className:_(Ue,"w-full min-w-0 font-mono",y?"lowercase":"uppercase"),...m})]})}function Ys({label:e,value:n,resolved:s,tokens:r,onCommit:a,onDone:i}){const[o,l]=u.useState(()=>Ot(s??Be)??{h:0,s:0,v:.8}),c=u.useRef(s);if(s!==c.current){c.current=s;const j=Ot(s??Be);j&&l(j)}const d=u.useCallback(j=>a(j),[a]),{schedule:f,finish:m}=Js(d),x=u.useCallback(j=>{l(j);const v=Le(j);c.current=v,f(v)},[f]),y=Le(o),p=typeof window<"u"&&"EyeDropper"in window?async()=>{try{const j=window.EyeDropper,v=await new j().open(),A=mt(v.sRGBHex);/^#[0-9A-F]{6}$/.test(A)&&a(A)}catch{}}:null;return t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx(Ws,{hsv:o,onChange:x,onEnd:m}),t.jsx(qs,{hsv:o,onChange:x,onEnd:m}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{"aria-hidden":!0,className:"size-6 shrink-0 rounded-sm border",style:{backgroundColor:s??Be}}),t.jsx(Zs,{hex:y,onCommit:a,label:e}),p&&t.jsxs(Ee,{children:[t.jsx(Te,{asChild:!0,children:t.jsx("button",{type:"button",onClick:p,"aria-label":"Pick a colour from the screen",className:_("flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-sm","text-muted-foreground transition-colors hover:bg-accent hover:text-foreground","focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"),children:t.jsx(Cs,{className:"size-3.5","aria-hidden":!0})})}),t.jsx(Re,{side:"bottom",children:t.jsx("p",{children:"Pick from the screen"})})]}),t.jsxs(Ee,{children:[t.jsx(Te,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{a(null),i()},"aria-label":`Clear ${e}`,disabled:n===void 0,className:_("flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-sm","text-muted-foreground transition-colors hover:bg-accent hover:text-foreground","focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none","disabled:pointer-events-none disabled:opacity-40"),children:t.jsx(on,{className:"size-3.5","aria-hidden":!0})})}),t.jsx(Re,{side:"bottom",children:t.jsx("p",{children:"Clear"})})]})]}),r&&r.length>0&&t.jsxs("div",{className:"flex flex-col gap-1.5 border-t pt-2",children:[t.jsx("span",{className:"text-[10px] font-medium tracking-[0.08em] text-muted-foreground uppercase",children:"Theme colours"}),t.jsx(Xs,{tokens:r,active:n&&!n.startsWith("#")?n:null,onPick:j=>a(j)}),t.jsx("p",{className:"text-[11px] leading-snug text-muted-foreground",children:"A token follows the theme when that colour changes; a hex does not."})]})]})}function Zs({hex:e,label:n,onCommit:s}){const r=u.useCallback(i=>{const o=mt(i);/^#[0-9A-F]{6}$/.test(o)&&s(o)},[s]),{props:a}=en(e,r);return t.jsx(_e,{type:"text","aria-label":`${n} hex`,autoComplete:"off",spellCheck:!1,className:_(Ue,"h-7 min-w-0 flex-1 bg-transparent font-mono uppercase"),...a})}function Qe(e){const n=JSON.stringify(e.colors??null);return u.useMemo(()=>{const s=JSON.parse(n);return s?er({colors:s}):[]},[n])}function er(e){const n=e.colors;if(!n||typeof n!="object")return[];const s=[];for(const[r,a]of Object.entries(n)){const i=pe(e,a);i&&s.push({key:r,hex:i})}return s}const ct=Qn(Z),tr=Array.from(new Set(ct.map(e=>e.group)));function nr(e,n){const s=e.colors,r=s==null?void 0:s[n.key],a=typeof r=="string"?r:void 0,i=pe(e,a),o=a!==void 0&&!Zt(a)&&i?a:null;let l=null;return a===void 0&&r!==void 0?l="Must be a string":a===void 0&&n.required?l="Required":a!==void 0&&!i&&(l=/^[a-zA-Z][a-zA-Z0-9]*$/.test(a)?`No token named "${a}"`:"Not a hex colour"),{raw:a,resolved:i,reference:o,error:l}}const sr=W.memo(function({token:n,raw:s,resolved:r,reference:a,error:i,tokens:o}){const{set:l,remove:c}=ie(),d=u.useCallback(x=>{x===null?c(["colors",n.key]):l(["colors",n.key],x)},[c,l,n.key]),f=u.useCallback(()=>c(["colors",n.key]),[c,n.key]),m=`theme-color-${n.key}`;return t.jsxs("div",{className:"flex min-h-8 items-center gap-2",children:[t.jsx(Fe,{id:m,label:n.label,value:s,resolved:r,onCommit:d,tokens:o,className:"w-[8.5rem] shrink-0 @[30rem]:w-[10.5rem]"}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col justify-center",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("label",{htmlFor:m,className:"truncate text-sm",children:n.label}),t.jsx("code",{className:"truncate text-[10px] text-muted-foreground",children:n.key}),n.required&&t.jsx("span",{className:"shrink-0 rounded-sm bg-muted px-1 text-[10px] tracking-wide text-muted-foreground uppercase",children:"required"})]}),t.jsx("p",{className:_(ne,"truncate"),children:i?t.jsx("span",{className:"text-destructive",children:i}):a?t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(ws,{className:"size-3","aria-hidden":!0}),t.jsx("code",{children:a}),t.jsx("span",{children:r})]}):n.hint})]}),s!==void 0&&!n.required?t.jsx(ze,{label:`Clear ${n.label}`,onClick:f}):t.jsx("span",{className:"size-6 shrink-0","aria-hidden":!0})]})});function rr({theme:e,query:n=""}){const s=n.trim()!=="",r=u.useMemo(()=>ct.filter(l=>le(n,"colours","colors")||le(n,l.key,l.label,l.group,l.hint)).map(l=>({token:l,...nr(e,l)})),[n,e]),a=u.useMemo(()=>{const l=e.colors,c=pe(e,l==null?void 0:l.background),d=pe(e,l==null?void 0:l.text),f=pe(e,l==null?void 0:l.primary);return{text:c&&d?Et(d,c):null,primary:c&&f?Et(f,c):null}},[e]),i=Qe(e),o=r.filter(l=>l.raw!==void 0).length;return s&&r.length===0?null:t.jsxs(ge,{title:"Colours",hint:"Hex values, or the name of another token to reuse it. Required tokens are what the compiler reads directly; the rest are optional slots.",forceOpen:s?!0:void 0,actions:t.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[o,"/",ct.length]}),children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1",children:[t.jsx(Tt,{label:"Text on background",ratio:a.text}),t.jsx(Tt,{label:"Primary on background",ratio:a.primary})]}),tr.filter(l=>r.some(c=>c.token.group===l)).map(l=>t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx(ft,{children:l}),r.filter(c=>c.token.group===l).map(c=>t.jsx(sr,{token:c.token,raw:c.raw,resolved:c.resolved,reference:c.reference,error:c.error,tokens:i},c.token.key))]},l))]})}const Ze=40;function or(e){return[...e.safe.map(n=>({family:n,tag:"safe",safe:!0})),...e.google.map(n=>({family:n.family,tag:n.category,safe:!1}))]}function ar(e,n){const s=e.toLowerCase();if(s===n)return 0;if(s.startsWith(n))return 1;const r=s.indexOf(n);return r===-1?-1:2+r}function ir(e,n,s){const r=n.trim().toLowerCase();if(!r){if(!s)return e.slice(0,Ze);const i=e.find(l=>l.family===s),o=e.filter(l=>l.family!==s);return[i??{family:s,tag:"current",safe:!1},...o].slice(0,Ze)}const a=[];for(const i of e){const o=ar(i.family,r);o!==-1&&a.push({option:i,rank:o})}return a.sort((i,o)=>i.rank-o.rank||Number(o.option.safe)-Number(i.option.safe)),a.slice(0,Ze).map(i=>i.option)}function jt({id:e,label:n,value:s,onCommit:r,pickerPath:a,className:i}){const[o,l]=u.useState(!1),[c,d]=u.useState(""),[f,m]=u.useState(0),x=u.useRef(null),y=qn(),p=u.useMemo(()=>or(y),[y]),j=u.useMemo(()=>ir(p,c,s),[p,c,s]),v=c.trim(),A=j.some(T=>T.family.toLowerCase()===v.toLowerCase()),D=v&&!A?v:null,V=D?[D,...j.map(T=>T.family)]:j.map(T=>T.family),O=u.useCallback(T=>{r(T),l(!1),d("")},[r]),se=u.useCallback(()=>{l(!1),yn.getState().openFor({jsonPath:a,currentValue:s})},[a,s]),L=u.useCallback(T=>{if(T.key==="ArrowDown"||T.key==="ArrowUp")T.preventDefault(),m($=>{var b,S;const w=$<0?T.key==="ArrowDown"?0:V.length-1:$+(T.key==="ArrowDown"?1:-1),h=V.length-1,C=w<0?h:w>h?0:w;return(S=(b=x.current)==null?void 0:b.querySelector(`[data-row="${C}"]`))==null||S.scrollIntoView({block:"nearest"}),C});else if(T.key==="Enter"){T.preventDefault();const $=V[f];$&&O($)}else T.key==="Escape"&&l(!1)},[f,O,V]);return t.jsx("div",{className:_("flex min-w-0 items-center gap-1",i),children:t.jsxs(bt,{open:o,onOpenChange:T=>{l(T),T&&(d(""),m(s?0:-1))},children:[t.jsx(yt,{asChild:!0,children:t.jsxs("button",{id:e,type:"button",role:"combobox","aria-expanded":o,"aria-label":n,className:_("flex h-7 min-w-0 flex-1 cursor-pointer items-center gap-1.5 rounded-sm border","border-input bg-background px-2 text-xs shadow-none transition-colors","hover:bg-accent/40 focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"),children:[t.jsx(vs,{className:"size-3 shrink-0 opacity-50","aria-hidden":!0}),t.jsx("span",{className:_("min-w-0 flex-1 truncate text-left",!s&&"text-muted-foreground"),style:s?{fontFamily:`"${s.replace(/"/g,"")}", system-ui`}:void 0,children:s||"Inherit"}),t.jsx(Ns,{className:"size-3 shrink-0 opacity-50","aria-hidden":!0})]})}),t.jsxs(We,{className:"w-72 p-0",onKeyDown:L,children:[t.jsxs("div",{className:"flex items-center gap-1.5 border-b px-2",children:[t.jsx(an,{className:"size-3.5 shrink-0 opacity-50","aria-hidden":!0}),t.jsx(_e,{autoFocus:!0,value:c,onChange:T=>{d(T.target.value),m(0)},placeholder:"Search fonts…","aria-label":`Search fonts for ${n}`,autoComplete:"off",spellCheck:!1,className:"h-8 border-0 bg-transparent px-0 text-xs shadow-none focus-visible:ring-0"})]}),t.jsxs("div",{ref:x,role:"listbox","aria-label":`${n} options`,className:"max-h-64 overflow-y-auto p-1",children:[D&&t.jsx(It,{index:0,active:f===0,family:D,tag:"use as typed",selected:s===D,onPick:O,onHover:m}),j.map((T,$)=>{const w=D?$+1:$;return t.jsx(It,{index:w,active:f===w,family:T.family,tag:T.tag,selected:s===T.family,onPick:O,onHover:m},`${T.safe?"s":"g"}:${T.family}`)}),V.length===0&&t.jsx("p",{className:_(ne,"px-2 py-3 text-center"),children:y.safe.length+y.google.length===0?"The font catalog is unavailable — type a family name.":"No family matches."})]}),t.jsxs("div",{className:"flex items-center justify-between border-t px-1.5 py-1",children:[t.jsx(de,{onClick:se,children:"Browse all fonts…"}),s&&t.jsx(de,{onClick:()=>{r(null),l(!1)},children:"Clear"})]})]})]})})}const It=W.memo(function({index:n,active:s,family:r,tag:a,selected:i,onPick:o,onHover:l}){return t.jsxs("button",{type:"button",role:"option","aria-selected":i,"data-row":n,onMouseMove:()=>l(n),onClick:()=>o(r),className:_("flex h-7 w-full cursor-pointer items-center gap-2 rounded-sm px-2 text-left text-xs",s&&"bg-accent text-accent-foreground"),children:[t.jsx(ht,{className:_("size-3 shrink-0",i?"opacity-100":"opacity-0"),"aria-hidden":!0}),t.jsx("span",{className:"min-w-0 flex-1 truncate",children:r}),t.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:a})]})});function ut(e){return typeof e=="string"?e:void 0}function pn(e){return typeof e=="number"?e:void 0}const lr=W.memo(function({role:n,family:s,size:r}){const{set:a,remove:i}=ie(),o=u.useCallback(f=>f===null?i(["fonts",n,"family"]):a(["fonts",n,"family"],f),[i,n,a]),l=u.useCallback(f=>f===null?i(["fonts",n,"size"]):a(["fonts",n,"size"],f),[i,n,a]),c=`theme-font-${n}-family`,d=`theme-font-${n}-size`;return t.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_6.5rem] gap-x-2 gap-y-1 rounded-sm border border-border/70 p-2",children:[t.jsxs("div",{className:"col-span-2 flex items-baseline gap-2",children:[t.jsx("span",{className:"text-sm capitalize",children:n}),t.jsx("span",{className:ne,children:pt[n]})]}),t.jsx("label",{htmlFor:c,className:Ge,children:"Family"}),t.jsx("label",{htmlFor:d,className:Ge,children:"Size"}),t.jsx(jt,{id:c,label:`${n} family`,value:s,onCommit:o,pickerPath:["fonts",n,"family"]}),t.jsx(Se,{id:d,"aria-label":`${n} size`,value:r,onCommit:l,unit:"pt",min:8,max:120,step:.5})]})}),cr=W.memo(function({role:n,family:s}){const{set:r,remove:a}=ie(),i=u.useCallback(l=>l===null?a(["fonts",n]):r(["fonts",n],l),[a,n,r]),o=`theme-font-${n}`;return t.jsxs("div",{className:"grid grid-cols-[6rem_minmax(0,1fr)] items-center gap-2",children:[t.jsxs("label",{htmlFor:o,className:"flex flex-col",children:[t.jsx("span",{className:"text-sm capitalize",children:n}),t.jsx("span",{className:ne,children:pt[n]})]}),t.jsx(jt,{id:o,label:`${n} family`,value:s,onCommit:i,pickerPath:["fonts",n]})]})});function ur({theme:e}){const{set:n,remove:s}=ie(),r=pn(ce(e,["defaults","fontSize"])),a=ut(ce(e,["defaults","fontColor"])),i=u.useMemo(()=>pe(e,a),[e,a]),o=Qe(e),l=u.useCallback(d=>d===null?s(["defaults","fontSize"]):n(["defaults","fontSize"],d),[s,n]),c=u.useCallback(d=>d===null?s(["defaults","fontColor"]):n(["defaults","fontColor"],d),[s,n]);return t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ft,{children:"Defaults"}),t.jsx("p",{className:ne,children:"What text falls back to when no style says otherwise."}),t.jsxs("div",{className:"grid grid-cols-[6rem_minmax(0,1fr)] items-center gap-2",children:[t.jsx("label",{htmlFor:"theme-defaults-size",className:"text-sm",children:"Font size"}),t.jsx(Se,{id:"theme-defaults-size",value:r,onCommit:l,unit:"pt",min:1,max:200,step:1,className:"max-w-[7rem]"}),t.jsx("label",{htmlFor:"theme-defaults-color",className:"text-sm",children:"Font colour"}),t.jsx(Fe,{id:"theme-defaults-color",label:"Default font colour",value:a,resolved:i,onCommit:c,allowReference:!1,tokens:o,className:"max-w-[12rem]"})]})]})}function dr({theme:e,query:n=""}){const s=n.trim()!=="",r=le(n,"typography","fonts","font"),a=c=>r||le(n,c,pt[c]),i=s?!0:void 0;if(Z==="docx"){const c=tn.filter(a);return s&&c.length===0?null:t.jsx(ge,{title:"Typography",hint:"Four roles the styles point at. A family beyond the safe list needs a fontRegistry entry on the document to embed; the specimen shows what the browser has.",forceOpen:i,children:t.jsx("div",{className:"grid grid-cols-1 gap-2 @[34rem]:grid-cols-2",children:c.map(d=>{const f=ce(e,["fonts",d]),m=f&&typeof f=="object"?f:void 0;return t.jsx(lr,{role:d,family:ut(m==null?void 0:m.family),size:pn(m==null?void 0:m.size)},d)})})})}const o=Xn.filter(a),l=r||le(n,"defaults","font size","font colour");return s&&o.length===0&&!l?null:t.jsxs(ge,{title:"Typography",hint:"Two families; every style uses one or names its own face.",forceOpen:i,children:[o.length>0&&t.jsx("div",{className:"flex flex-col gap-2",children:o.map(c=>t.jsx(cr,{role:c,family:ut(ce(e,["fonts",c]))},c))}),l&&t.jsx(ur,{theme:e})]})}const et="__custom__",mr=[{value:"in",label:"in"},{value:"cm",label:"cm"},{value:"pt",label:"pt"},{value:"twips",label:"twips"}],fr={in:.05,cm:.1,pt:1,twips:10},_t=Object.fromEntries(it.map(e=>[e,["page","margins",e]])),zt=["page","size","width"],Ft=["page","size","height"];function tt(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}const nt=W.memo(function({id:n,label:s,path:r,value:a,unit:i}){const{set:o,remove:l}=ie(),c=u.useCallback(d=>d===null?l(r):o(r,Yn(d,i)),[r,l,o,i]);return t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:n,className:Ge,children:s}),t.jsx(Se,{id:n,value:a===void 0?void 0:Zn(a,i),onCommit:c,unit:i,min:0,step:fr[i]})]})});function pr({theme:e,query:n=""}){const s=n.trim()!=="";if(s&&!le(n,"page","size","margins","width","height",...it,...Xe))return null;const{set:r}=ie(),[a,i]=u.useState("in"),o=ce(e,["page","size"]),l=!!o&&typeof o=="object",c=typeof o=="string"&&Xe.includes(o)?o:l?et:"",d=u.useCallback(f=>{f===et?r(["page","size"],{width:11906,height:16838}):r(["page","size"],f)},[r]);return t.jsxs(ge,{title:"Page",hint:"Paper and margins. Stored in twips (1/1440 in); shown in the unit you pick here.",forceOpen:s?!0:void 0,actions:t.jsxs(Ce,{value:a,onValueChange:f=>i(f),children:[t.jsx(we,{"aria-label":"Length unit",className:"h-6 min-h-0 w-auto gap-1 border-transparent bg-transparent px-1.5 text-[11px] shadow-none hover:bg-accent",children:t.jsx(ve,{})}),t.jsx(Ne,{children:mr.map(f=>t.jsx(he,{value:f.value,className:"text-xs",children:f.label},f.value))})]}),children:[t.jsxs("div",{className:"grid grid-cols-[6rem_minmax(0,12rem)] items-center gap-2",children:[t.jsx("label",{htmlFor:"theme-page-size",className:"text-sm",children:"Size"}),t.jsxs(Ce,{value:c,onValueChange:d,children:[t.jsx(we,{id:"theme-page-size",className:Ae,children:t.jsx(ve,{placeholder:"Choose a size"})}),t.jsxs(Ne,{children:[Xe.map(f=>t.jsx(he,{value:f,className:"text-xs",children:f},f)),t.jsx(he,{value:et,className:"text-xs",children:"Custom"})]})]})]}),l&&t.jsxs("div",{className:"grid grid-cols-2 gap-2 @[34rem]:max-w-[24rem]",children:[t.jsx(nt,{id:"theme-page-width",label:"Width",path:zt,value:tt(ce(e,zt)),unit:a}),t.jsx(nt,{id:"theme-page-height",label:"Height",path:Ft,value:tt(ce(e,Ft)),unit:a})]}),t.jsx("div",{className:"grid grid-cols-2 gap-2 @[30rem]:grid-cols-4",children:it.map(f=>t.jsx(nt,{id:`theme-margin-${f}`,label:f.charAt(0).toUpperCase()+f.slice(1),path:_t[f],value:tt(ce(e,_t[f])),unit:a},f))})]})}const $t=ns(Z),Ct=ts(Z),hr=Ct.filter(e=>!e.advanced),st=Ct.filter(e=>e.advanced),gr=2,xr=[{value:"unset",label:"Unset"},{value:"off",label:"Off"},{value:"on",label:"On"}];function Pe(e){return e.path.join(".")}function br(e){const n=[],s=r=>{typeof r=="string"&&r&&n.push(r)};if(Z==="docx"?(s(e.font),typeof e.size=="number"&&n.push(`${e.size}pt`)):(s(e.fontFace),typeof e.fontSize=="number"&&n.push(`${e.fontSize}pt`)),e.bold===!0&&n.push("bold"),typeof e.fontWeight=="number"&&n.push(`w${e.fontWeight}`),e.italic===!0&&n.push("italic"),e.underline===!0&&n.push("underline"),s(Z==="docx"?e.color:e.fontColor),s(Z==="docx"?e.alignment:e.align),n.length===0){const r=Object.keys(e);return r.length===0?"Defined, nothing set":r.join(" · ")}return n.join(" · ")}function yr({styleName:e,field:n,value:s,tokens:r,resolved:a,onCommit:i}){return t.jsx(Fe,{id:`theme-style-${e}-${Pe(n)}`,label:n.label,value:typeof s=="string"?s:void 0,resolved:a,onCommit:i,tokens:r,className:"min-w-0"})}const jr=W.memo(function(n){const{styleName:s,field:r,value:a}=n,{set:i,remove:o}=ie(),l=u.useMemo(()=>["styles",s,...r.path],[r.path,s]),c=u.useCallback(()=>o(l,{keepDepth:gr}),[l,o]),d=u.useCallback(p=>p===null?c():i(l,p),[c,l,i]),f=u.useCallback(p=>p===null?c():i(l,p),[c,l,i]),m=`theme-style-${s}-${Pe(r)}`,x=a!==void 0;let y;switch(r.kind){case"text":y=t.jsx(Ke,{id:m,value:typeof a=="string"?a:void 0,onCommit:d});break;case"number":y=t.jsx(Se,{id:m,value:typeof a=="number"?a:void 0,onCommit:f,unit:r.unit,min:r.min,max:r.max,step:r.step});break;case"boolean":y=t.jsx(sn,{label:r.label,value:a===void 0?"unset":a===!0?"on":"off",options:xr,onChange:p=>p==="unset"?c():i(l,p==="on"),className:"h-7"});break;case"select":y=t.jsxs(Ce,{value:typeof a=="string"?a:"",onValueChange:p=>i(l,p),children:[t.jsx(we,{id:m,className:Ae,children:t.jsx(ve,{placeholder:"Unset"})}),t.jsx(Ne,{children:(r.options??[]).map(p=>t.jsx(he,{value:p,className:"text-xs",children:p},p))})]});break;case"fontRole":y=t.jsxs(Ce,{value:typeof a=="string"?a:"",onValueChange:p=>i(l,p),children:[t.jsx(we,{id:m,className:Ae,children:t.jsx(ve,{placeholder:"Unset"})}),t.jsx(Ne,{children:tn.map(p=>t.jsx(he,{value:p,className:"text-xs",children:p},p))})]});break;case"fontFamily":y=t.jsx(jt,{id:m,label:r.label,value:typeof a=="string"?a:void 0,onCommit:d,pickerPath:l});break;case"color":y=t.jsx(yr,{...n,onCommit:d});break}return t.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[t.jsxs("div",{className:"flex h-4 items-center justify-between gap-1",children:[t.jsx("label",{htmlFor:r.kind==="boolean"?void 0:m,className:_(Ge,x&&"text-foreground"),title:r.hint,children:r.label}),x&&r.kind!=="boolean"&&t.jsx(ze,{label:`Clear ${r.label}`,onClick:c,className:"size-5"})]}),y,r.hint&&t.jsx("p",{className:ne,children:r.hint})]})}),Cr=W.memo(function({name:n,custom:s,styleJson:r,tokensJson:a,resolvedJson:i}){const{set:o,remove:l}=ie(),[c,d]=u.useState(!1),[f,m]=u.useState(!1),x=u.useMemo(()=>r===void 0?void 0:JSON.parse(r),[r]),y=u.useMemo(()=>JSON.parse(a),[a]),p=u.useMemo(()=>JSON.parse(i),[i]),j=u.useCallback(()=>o(["styles",n],{}),[n,o]),v=u.useCallback(()=>l(["styles",n]),[n,l]),A=nn(n),D=x?Object.keys(x).length:0,V=O=>t.jsx(jr,{styleName:n,field:O,value:x?ce(x,O.path):void 0,tokens:y,resolved:p[Pe(O)]??null},Pe(O));return t.jsxs("div",{className:"rounded-sm border border-border/70",children:[t.jsxs("div",{className:"flex h-8 items-center gap-1 pr-1",children:[t.jsxs("button",{type:"button",onClick:()=>d(O=>!O),"aria-expanded":c,className:_("flex h-8 min-w-0 flex-1 cursor-pointer items-center gap-1.5 rounded-sm px-2 text-left","transition-colors hover:bg-accent","focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"),children:[t.jsx(At,{"aria-hidden":!0,className:_("size-3 shrink-0 text-muted-foreground transition-transform duration-150 ease-out",c&&"rotate-90")}),t.jsx("span",{className:"shrink-0 text-sm",children:A}),s&&t.jsx("span",{className:"shrink-0 rounded-sm bg-muted px-1 text-[10px] tracking-wide text-muted-foreground uppercase",children:"custom"}),t.jsx("span",{className:_(ne,"min-w-0 flex-1 truncate"),children:x?br(x):"Not defined — inherits defaults"})]}),s&&t.jsx("button",{type:"button",onClick:v,"aria-label":`Remove style ${n}`,title:"Remove style",className:_("flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-sm","text-muted-foreground/70 transition-colors hover:bg-accent hover:text-destructive","focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"),children:t.jsx(Ss,{className:"size-3.5","aria-hidden":!0})})]}),c&&t.jsx("div",{className:"flex flex-col gap-3 border-t border-border/60 px-2 pt-2 pb-3",children:x?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 @[30rem]:grid-cols-2",children:hr.map(V)}),st.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs(de,{onClick:()=>m(O=>!O),"aria-expanded":f,children:[t.jsx(At,{"aria-hidden":!0,className:_("size-3 transition-transform duration-150 ease-out",f&&"rotate-90")}),"More"]}),t.jsxs("span",{className:ne,children:[st.length," more fields",D>0&&` · ${D} key${D===1?"":"s"} set`]})]}),f&&t.jsx("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 @[30rem]:grid-cols-2",children:st.map(V)})]})]}):t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:ne,children:"Not defined — inherits defaults."}),t.jsxs(de,{onClick:j,children:[t.jsx(gt,{className:"size-3","aria-hidden":!0}),"Define"]})]})})]})});function wr({existing:e}){const{set:n}=ie(),[s,r]=u.useState(!1),[a,i]=u.useState(""),o=a.trim(),l=o?e.has(o)?"A style with this name exists":/\s/.test(o)?"No spaces — this is the style id a document names":null:null,c=()=>{!o||l||(n(["styles",o],{}),i(""),r(!1))};return s?t.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:d=>{d.preventDefault(),c()},children:[t.jsx("label",{htmlFor:"theme-new-style",className:"text-xs",children:"New style"}),t.jsx(_e,{id:"theme-new-style",type:"text",value:a,onChange:d=>i(d.target.value),placeholder:"e.g. callout",autoComplete:"off",spellCheck:!1,autoFocus:!0,className:_(Ue,"w-40"),onKeyDown:d=>{d.key==="Escape"&&r(!1)}}),t.jsx(de,{type:"submit",disabled:!o||!!l,children:"Add"}),t.jsx(de,{onClick:()=>r(!1),children:"Cancel"}),l&&t.jsx("span",{className:"text-[11px] text-destructive",children:l})]}):t.jsxs(de,{onClick:()=>r(!0),children:[t.jsx(gt,{className:"size-3","aria-hidden":!0}),"Add custom style"]})}function vr({theme:e,query:n=""}){const s=n.trim()!=="",r=Qe(e),a=u.useMemo(()=>JSON.stringify(r),[r]),i=u.useMemo(()=>es(e,Z),[e]),o=u.useMemo(()=>{const d=e.styles,f=d&&typeof d=="object"&&!Array.isArray(d)?d:{},m=Ct.filter(p=>p.kind==="color"),x=(p,j)=>{const v=f[p],A=!!v&&typeof v=="object",D={};for(const V of m)D[Pe(V)]=A?pe(e,ce(v,V.path)):null;return{name:p,custom:j,styleJson:A?JSON.stringify(v):void 0,tokensJson:a,resolvedJson:JSON.stringify(D)}},y=[...$t.map(p=>x(p,!1)),...i.map(p=>x(p,!0))];return le(n,"styles","style")?y:y.filter(p=>le(n,p.name,nn(p.name)))},[e,a,i,n]),l=u.useMemo(()=>new Set([...$t,...i]),[i]),c=o.filter(d=>d.styleJson!==void 0).length;return s&&o.length===0?null:t.jsxs(ge,{title:"Styles",hint:Z==="docx"?"Paragraph styles a document names with themeStyle. A colour may be a token or a hex; sizes are points.":"Text presets a slide names by style. Sizes are points; a colour may be a token or a hex.",forceOpen:s?!0:void 0,actions:t.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[c,"/",o.length]}),children:[t.jsx("div",{className:"flex flex-col gap-1",children:o.map(d=>t.jsx(Cr,{...d},d.name))}),Z==="docx"&&t.jsx(wr,{existing:l})]})}const ke="__unset__",Nr=[{value:"unset",label:"Unset"},{value:"off",label:"Off"},{value:"on",label:"On"}];function wt(e){return`theme-schema-${e.join("-")}`}const Oe=1,Sr=W.memo(function({field:n,value:s,theme:r,tokens:a,onOpenJson:i}){const{set:o,remove:l}=ie(),c=n.path,d=u.useCallback(()=>l(c,{keepDepth:Oe}),[c,l]),f=u.useCallback(p=>p===null?d():o(c,p),[d,c,o]),m=u.useCallback(p=>p===null?d():o(c,p),[d,c,o]),x=wt(c),y=xt(n,s);if(y)return t.jsx(Ie,{summary:`${y}: ${De(s)}`,onOpenJson:i,onClear:d});switch(n.kind){case"text":return t.jsx(Ke,{id:x,value:typeof s=="string"?s:void 0,onCommit:f});case"number":return t.jsx(Se,{id:x,value:typeof s=="number"?s:void 0,onCommit:m,min:n.min,max:n.max,step:n.integer?1:.5});case"boolean":return t.jsx(sn,{label:n.label,value:s===void 0?"unset":s===!0?"on":"off",options:Nr,onChange:p=>p==="unset"?d():o(c,p==="on"),className:"h-7"});case"enum":return t.jsxs(Ce,{value:typeof s=="string"?s:ke,onValueChange:p=>p===ke?d():o(c,p),children:[t.jsx(we,{id:x,"aria-label":n.label,className:Ae,children:t.jsx(ve,{placeholder:"Unset"})}),t.jsxs(Ne,{children:[t.jsx(he,{value:ke,children:"Unset"}),(n.options??[]).map(p=>t.jsx(he,{value:p,children:p},p))]})]});case"color":return t.jsx(Fe,{id:x,label:n.label,value:typeof s=="string"?s:void 0,resolved:dn(r,s),onCommit:f,tokens:a,className:"min-w-0"});default:return t.jsx(Ie,{summary:De(s),onOpenJson:i,onClear:s===void 0?void 0:d})}});function Ie({summary:e,onOpenJson:n,onClear:s}){return t.jsxs("div",{className:"flex h-7 min-w-0 items-center gap-1",children:[t.jsx("span",{className:"min-w-0 flex-1 truncate text-xs text-muted-foreground",children:e}),t.jsxs(de,{onClick:n,children:[t.jsx(Je,{className:"size-3","aria-hidden":!0}),"JSON"]}),s&&t.jsx(ze,{label:"Clear",onClick:s})]})}const kr=W.memo(function({field:n,value:s,theme:r,tokens:a,onOpenJson:i}){const{set:o,remove:l}=ie(),c=Array.isArray(s)?s:[],d=n.item,f=u.useCallback(()=>{const x=d.kind==="number"?d.min??0:d.kind==="boolean"?!0:"";o(n.path,[...c,x])},[c,n.path,d.kind,d.min,o]),m=n.max!==void 0&&c.length>=n.max;return s!==void 0&&!Array.isArray(s)?t.jsx(Ie,{summary:`Not a list: ${De(s)}`,onOpenJson:i,onClear:()=>l(n.path,{keepDepth:Oe})}):t.jsxs("div",{className:"flex flex-col gap-1",children:[c.map((x,y)=>{const p={...d,key:String(y),label:`${n.label} ${y+1}`,path:[...n.path,y]};return t.jsx("div",{className:"flex items-center gap-1",children:t.jsx("div",{className:"min-w-0 flex-1",children:t.jsx(Er,{field:p,value:x,theme:r,tokens:a,onOpenJson:i,onRemove:()=>{const j=c.filter((v,A)=>A!==y);j.length===0?l(n.path,{keepDepth:Oe}):o(n.path,j)}})})},y)}),!m&&t.jsxs(de,{onClick:f,className:"self-start",children:[t.jsx(gt,{className:"size-3","aria-hidden":!0}),"Add"]})]})});function Er({field:e,value:n,theme:s,tokens:r,onOpenJson:a,onRemove:i}){const{set:o}=ie(),l=u.useCallback(m=>m===null?i():o(e.path,m),[e.path,i,o]),c=u.useCallback(m=>m===null?i():o(e.path,m),[e.path,i,o]),d=wt(e.path);let f;switch(e.kind){case"color":f=t.jsx(Fe,{id:d,label:e.label,value:typeof n=="string"?n:void 0,resolved:dn(s,n),onCommit:l,tokens:r,className:"min-w-0"});break;case"number":f=t.jsx(Se,{id:d,value:typeof n=="number"?n:void 0,onCommit:c,min:e.min,max:e.max,step:e.integer?1:.5});break;case"enum":f=t.jsxs(Ce,{value:typeof n=="string"?n:ke,onValueChange:m=>m===ke?i():o(e.path,m),children:[t.jsx(we,{id:d,"aria-label":e.label,className:Ae,children:t.jsx(ve,{placeholder:"Unset"})}),t.jsx(Ne,{children:(e.options??[]).map(m=>t.jsx(he,{value:m,children:m},m))})]});break;case"text":f=t.jsx(Ke,{id:d,value:typeof n=="string"?n:void 0,onCommit:l});break;default:f=t.jsx(Ie,{summary:De(n),onOpenJson:a})}return t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx("div",{className:"min-w-0 flex-1",children:f}),t.jsx(ze,{label:`Remove ${e.label}`,onClick:i})]})}const Tr=W.memo(function({field:n,value:s,theme:r,tokens:a,onOpenJson:i}){const{remove:o}=ie(),l=s!==void 0,c=wt(n.path),d=u.useCallback(()=>o(n.path,{keepDepth:Oe}),[n.path,o]),f=l&&n.kind!=="list"&&n.kind!=="json"&&!xt(n,s);return t.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,12rem)_1.5rem] items-start gap-x-2 gap-y-0.5 @[30rem]:grid-cols-[minmax(0,1fr)_minmax(0,16rem)_1.5rem]",children:[t.jsxs("label",{htmlFor:c,className:"flex min-w-0 flex-col pt-1.5",children:[t.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:_("truncate text-sm",!l&&"text-muted-foreground"),children:n.label}),t.jsx("code",{className:"truncate text-[10px] text-muted-foreground",children:n.key}),n.required&&t.jsx("span",{className:"shrink-0 rounded-sm bg-muted px-1 text-[10px] tracking-wide text-muted-foreground uppercase",children:"required"})]}),n.hint&&t.jsx("span",{className:_(ne,"line-clamp-2"),children:n.hint})]}),t.jsx("div",{className:"min-w-0 pt-0.5",children:n.kind==="list"?t.jsx(kr,{field:n,value:s,theme:r,tokens:a,onOpenJson:i}):t.jsx(Sr,{field:n,value:s,theme:r,tokens:a,onOpenJson:i})}),t.jsx("div",{className:"pt-0.5",children:f&&t.jsx(ze,{label:`Clear ${n.label}`,onClick:d})})]})});function Rr({field:e,theme:n,tokens:s,onOpenJson:r,depth:a}){const i=ce(n,e.path),o=xt(e,i),{remove:l}=ie();return t.jsxs("div",{className:_("flex flex-col gap-2",a>0&&"border-l border-border/60 pl-3"),"data-crumb":e.label,children:[t.jsxs("div",{className:"flex items-baseline gap-2",children:[t.jsx(ft,{children:e.label}),t.jsx("code",{className:"text-[10px] text-muted-foreground",children:e.key}),i===void 0&&t.jsx("span",{className:ne,children:"Not defined — inherits defaults"})]}),e.hint&&t.jsx("p",{className:_(ne,"-mt-1"),children:e.hint}),o?t.jsx(Ie,{summary:`${o}: ${De(i)}`,onOpenJson:r,onClear:()=>l(e.path,{keepDepth:Oe})}):t.jsx(hn,{fields:e.children??[],theme:n,tokens:s,onOpenJson:r,depth:a+1})]})}function hn({fields:e,theme:n,tokens:s,onOpenJson:r,depth:a}){return t.jsx("div",{className:"flex flex-col gap-2",children:e.map(i=>i.kind==="group"?t.jsx(Rr,{field:i,theme:n,tokens:s,onOpenJson:r,depth:a},i.key):t.jsx(Tr,{field:i,value:ce(n,i.path),theme:n,tokens:s,onOpenJson:r},i.key))})}function Mr({section:e,theme:n,query:s,onOpenJson:r}){const a=Qe(n),i=n[e.key]!==void 0,o=u.useMemo(()=>le(s,e.key,e.title,e.hint)?e.fields:un(e.fields,s),[s,e]);return s.trim()&&o.length===0?null:t.jsxs(ge,{title:e.title,hint:e.hint,defaultOpen:i,forceOpen:s.trim()?!0:void 0,actions:t.jsxs(de,{onClick:r,children:[t.jsx(Je,{className:"size-3","aria-hidden":!0}),"JSON"]}),children:[!i&&t.jsx("p",{className:ne,children:"Not defined — inherits defaults. Set a field to define it."}),t.jsx(hn,{fields:o,theme:n,tokens:a,onOpenJson:r,depth:0})]})}function Ar(){const[e,n]=u.useState([]);return u.useEffect(()=>{let s=!1;return Vs().then(r=>{s||n($s(r,cs(Z)))}).catch(r=>{console.warn("[theme editor] schema unavailable:",r)}),()=>{s=!0}},[]),e}function gn({docName:e,text:n,onChange:s,onOpenJson:r,usedBy:a=[],nameClash:i=[]}){const o=u.useMemo(()=>ss(n),[n]),l=u.useRef({theme:null,onChange:s});l.current.theme=o.ok?o.theme:null,l.current.onChange=s;const c=u.useCallback(y=>{const p=l.current.theme;if(!p)return;const j=y(p);j!==p&&(l.current.theme=j,l.current.onChange(rs(j)))},[]),d=u.useCallback((y,p)=>c(j=>{const v=y[0],A=typeof v=="string"?j[v]:void 0,D=y.length>1&&(!A||typeof A!="object")?os(j,Z):j;return as(D,y,p)}),[c]),f=u.useCallback((y,p)=>c(j=>{let v=Rt(j,y);if(!p)return v;let A=y.slice(0,-1);for(;A.length>p.keepDepth;){const D=ce(v,A);if(!(!!D&&typeof D=="object"&&!Array.isArray(D)&&Object.keys(D).length===0))break;v=Rt(v,A),A=A.slice(0,-1)}return v}),[c]),m=u.useMemo(()=>({set:d,remove:f}),[d,f]);if(!o.ok)return t.jsxs("div",{className:"flex h-full flex-col items-start gap-3 p-4",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["The theme JSON has an error:"," ",t.jsx("span",{className:"text-destructive",children:o.error})]}),t.jsx("p",{className:ne,children:"The form stays read-only until the file parses, so nothing you typed in JSON is overwritten."}),t.jsxs(Me,{variant:"outline",size:"sm",onClick:r,children:[t.jsx(Je,{"aria-hidden":!0}),"Open JSON"]})]});const x=o.theme;return t.jsx(is,{value:m,children:t.jsx(Lr,{docName:e,theme:x,usedBy:a,nameClash:i,onOpenJson:r})})}function Dr(e){const[n,s]=u.useState([]);return u.useEffect(()=>{const r=e.current,a=r==null?void 0:r.closest("[data-radix-scroll-area-viewport]");if(!r||!a)return;let i=null;const o=()=>{i=null;const d=r.getBoundingClientRect().bottom+1,f=[];for(const m of a.querySelectorAll("[data-crumb]")){const x=m.getBoundingClientRect();x.top<=d&&x.bottom>d&&f.push(m.dataset.crumb??"")}s(m=>m.length===f.length&&m.every((x,y)=>x===f[y])?m:f)},l=()=>{i===null&&(i=requestAnimationFrame(o))};o(),a.addEventListener("scroll",l,{passive:!0});const c=new ResizeObserver(l);c.observe(a);for(const d of a.children)c.observe(d);return()=>{i!==null&&cancelAnimationFrame(i),a.removeEventListener("scroll",l),c.disconnect()}},[e]),n}function Lr({docName:e,theme:n,usedBy:s,nameClash:r,onOpenJson:a}){const[i,o]=u.useState(""),l=Ar(),c=u.useMemo(()=>l.map(m=>m.key),[l]),d=u.useRef(null),f=Dr(d);return t.jsx(Pn,{className:"h-full",children:t.jsxs("div",{className:"@container mx-auto flex w-full max-w-[760px] flex-col gap-2 px-4 pt-1 pb-8",children:[t.jsxs("div",{ref:d,className:"sticky top-0 z-10 -mx-1 bg-background/95 px-1 py-1.5 backdrop-blur",children:[t.jsx("div",{"aria-live":"polite",className:_("flex h-4 items-center gap-1 truncate px-1 text-[10px] tracking-[0.08em] text-muted-foreground uppercase",f.length===0&&"invisible"),children:f.map((m,x)=>t.jsxs(W.Fragment,{children:[x>0&&t.jsx("span",{"aria-hidden":!0,className:"text-muted-foreground/50",children:"›"}),t.jsx("span",{className:_(x===f.length-1&&"text-foreground/80"),children:m})]},`${x}-${m}`))}),t.jsxs("div",{className:"relative",children:[t.jsx(an,{"aria-hidden":!0,className:"pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground"}),t.jsx(_e,{type:"search",value:i,onChange:m=>o(m.target.value),onKeyDown:m=>{m.key==="Escape"&&o("")},placeholder:"Find a setting… (motif, tracking, safe area)","aria-label":"Find a theme setting",autoComplete:"off",spellCheck:!1,className:_(Ue,"h-8 pr-7 pl-7")}),i&&t.jsx("button",{type:"button",onClick:()=>o(""),"aria-label":"Clear search",className:"absolute top-1/2 right-1 flex size-6 -translate-y-1/2 cursor-pointer items-center justify-center rounded-sm text-muted-foreground hover:text-foreground",children:t.jsx(on,{className:"size-3.5","aria-hidden":!0})})]})]}),t.jsx(Or,{theme:n,usedBy:s,nameClash:r,query:i}),t.jsx(rr,{theme:n,query:i}),t.jsx(dr,{theme:n,query:i}),Z==="docx"&&t.jsx(pr,{theme:n,query:i}),t.jsx(vr,{theme:n,query:i}),l.map(m=>t.jsx(Mr,{section:m,theme:n,query:i,onOpenJson:a},m.key)),t.jsx(Ir,{theme:n,onOpenJson:a,alsoHandled:c,query:i})]},e)})}const Vt={docx:[{key:"name",label:"Name",hint:'What a document puts in "theme"'},{key:"displayName",label:"Display name"},{key:"description",label:"Description"},{key:"version",label:"Version"}],pptx:[{key:"name",label:"Name",hint:'What a document puts in "theme"'},{key:"displayName",label:"Display name"},{key:"description",label:"Description"},{key:"version",label:"Version"}]};function Pr({fieldKey:e,label:n,hint:s,value:r}){const{set:a,remove:i}=ie(),o=u.useCallback(c=>c===null?i([e]):a([e],c),[e,i,a]),l=`theme-identity-${e}`;return t.jsxs(t.Fragment,{children:[t.jsxs("label",{htmlFor:l,className:"flex flex-col pt-1.5 text-sm",children:[n,s&&t.jsx("span",{className:ne,children:s})]}),t.jsx(Ke,{id:l,value:r,onCommit:o,className:e==="name"?"font-mono":void 0})]})}function Or({theme:e,usedBy:n,nameClash:s,query:r=""}){const a=r.trim()!=="",i=le(r,"identity","name")?Vt[Z]:Vt[Z].filter(o=>le(r,o.key,o.label,o.hint));return a&&i.length===0?null:t.jsxs(ge,{title:"Identity",hint:"A document picks this theme by its name; the rest is what the library shows.",forceOpen:a?!0:void 0,children:[t.jsx("div",{className:"grid grid-cols-[7rem_minmax(0,1fr)] items-start gap-x-3 gap-y-2",children:i.map(o=>{const l=e[o.key];return t.jsx(Pr,{fieldKey:o.key,label:o.label,hint:o.hint,value:typeof l=="string"?l:void 0},o.key)})}),t.jsx("p",{className:_(ne,"mt-2"),children:n.length>0?t.jsxs(t.Fragment,{children:["Used by"," ",n.map((o,l)=>t.jsxs(W.Fragment,{children:[l>0&&", ",t.jsx("code",{className:"rounded-sm bg-muted px-1 py-0.5 text-[11px]",children:o})]},o)),". Renaming the theme breaks that reference until the document is updated."]}):"Not used by any open document yet — Run sample shows it anyway."}),s.length>0&&t.jsxs("p",{className:"mt-1 text-xs text-warning",children:[s.join(", ")," also declare",s.length===1?"s":""," ","this name; only one of them can win when a document asks for it."]})]})}function Ir({theme:e,onOpenJson:n,alsoHandled:s,query:r=""}){const a=r.trim()!=="",i=u.useMemo(()=>ls(e,Z,s).filter(o=>le(r,"advanced")||le(r,o.key,o.summary)),[s,r,e]);return a&&i.length===0?null:t.jsx(ge,{title:"Advanced",hint:"Keys the form has no field for. They travel untouched through every edit here.",forceOpen:a?!0:void 0,actions:i.length>0?t.jsxs(de,{onClick:n,children:[t.jsx(Je,{className:"size-3","aria-hidden":!0}),"Edit in JSON"]}):void 0,children:i.length===0?t.jsx("p",{className:ne,children:"Nothing beyond the fields above."}):t.jsx("ul",{className:"flex flex-col gap-1",children:i.map(o=>t.jsxs("li",{className:"flex min-w-0 items-baseline gap-2 text-xs",children:[t.jsx("code",{className:"shrink-0 rounded-sm bg-muted px-1 py-0.5 text-[11px]",children:o.key}),t.jsx("span",{className:"truncate text-muted-foreground",children:o.summary})]},o.key))})})}W.memo(gn);function _r({document:e,onChange:n}){const s=je(m=>m.themeEditorView),r=je(m=>m.setSettings),a=ue(m=>m.pendingDiffs[e.name]!==void 0),i=u.useMemo(()=>{try{const m=JSON.parse(e.text);return m&&typeof m=="object"&&!Array.isArray(m)?m:null}catch{return null}},[e.text]),o=i?dt(i):null,l=ue(m=>{if(!o)return xe;const x=m.documents.filter(y=>(m.documentTypes[y.name]??"application/json+report")==="application/json+report"&&zr(y.text)===o).map(y=>y.name);return x.length===0?xe:x.join(`
9
+ `)}),c=ue(m=>{if(!o)return xe;const x=m.documents.filter(y=>y.name!==e.name&&m.documentTypes[y.name]==="application/json+theme"&&Fr(y.text)===o).map(y=>y.name);return x.length===0?xe:x.join(`
10
+ `)}),{view:d}=On({preferred:s,parses:i!==null,hasPendingDiff:a}),f=u.useCallback(()=>r({themeEditorView:"json"}),[r]);return t.jsx("div",{className:"h-full",children:d==="visual"?t.jsx(gn,{docName:e.name,text:e.text,onChange:n,onOpenJson:f,usedBy:l===xe?Ht:l.split(`
11
+ `),nameClash:c===xe?Ht:c.split(`
12
+ `)}):t.jsx(_s,{document:e,onChange:n})})}const xe="",Ht=[];function zr(e){var n,s;try{const r=(s=(n=JSON.parse(e))==null?void 0:n.props)==null?void 0:s.theme;return typeof r=="string"?r:null}catch{return null}}function Fr(e){try{return dt(JSON.parse(e))}catch{return null}}const $r=W.memo(_r);function Vr(){const[e,n]=u.useState(Nn);return u.useEffect(()=>Sn(()=>n(!0)),[]),e}function Hr({docName:e,text:n}){const s=be(L=>L.records[e]),r=be(L=>L.setEnabled),a=be(L=>L.setAllowNetwork),i=be(L=>L.setNetworkOrigins),{toast:o}=jn(),[l,c]=u.useState(null),d=Vr(),f=s==null?void 0:s.metadata,m=(s==null?void 0:s.status)??"idle",x=((s==null?void 0:s.diagnostics)??[]).filter(L=>L.severity==="error").length,y=(f==null?void 0:f.name)??e.replace(new RegExp(`${wn}$`,"i"),""),p=(f==null?void 0:f.examples)??[],j=u.useCallback(()=>{window.dispatchEvent(new CustomEvent(rt,{detail:{docName:e}}))},[e]),v=u.useCallback(L=>{r(e,L),j()},[j,e,r]),A=u.useCallback(()=>{vn.dispose(e),be.getState().upsert(e,{status:"idle"}),ot.run(e)},[e]),D=u.useCallback(L=>{a(e,L),A()},[e,A,a]),V=u.useCallback(L=>{i(e,L),A()},[e,A,i]),O=u.useCallback(async L=>{const T=p[L];if(!T||!f)return;const $=JSON.stringify({name:f.name,props:T.props},null,2);try{await navigator.clipboard.writeText($),c(L),setTimeout(()=>c(null),1500)}catch{o({title:"Clipboard unavailable",description:"Could not copy the example to the clipboard.",variant:"destructive"})}},[p,f,o]),se=(()=>{if(!d&&m!=="ready"&&m!=="error")return t.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[t.jsx(kt,{size:"sm"}),"Loading types…"]});switch(m){case"compiling":return t.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[t.jsx(kt,{size:"sm"}),"Compiling…"]});case"ready":return t.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[t.jsx("span",{"aria-hidden":!0,className:"size-1.5 rounded-full bg-success"}),"Ready"]});case"error":return t.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-destructive",children:[t.jsx("span",{"aria-hidden":!0,className:"size-1.5 rounded-full bg-destructive"}),x>0?`${x} error${x===1?"":"s"}`:"Failed"]});default:return t.jsx("span",{className:"text-xs text-muted-foreground",children:"Not compiled"})}})();return t.jsxs("div",{className:"flex h-9 shrink-0 items-center gap-2 border-b bg-sidebar px-3",children:[t.jsx(ks,{className:"size-3.5 shrink-0 text-sidebar-foreground/60"}),t.jsx("span",{className:"truncate text-[13px] font-medium",children:y}),(f==null?void 0:f.latest)&&t.jsxs(at,{variant:"outline",className:"h-4 px-1.5 font-mono text-[10px]",children:["v",f.latest]}),t.jsx("span",{className:"mx-1 h-4 w-px bg-border/60"}),se,t.jsxs(Ee,{children:[t.jsx(Te,{asChild:!0,children:t.jsx("button",{type:"button","aria-label":"How plugins run",className:"inline-flex size-6 cursor-help items-center justify-center rounded-sm hover:bg-muted/60",children:t.jsx(Es,{className:"size-3.5 text-muted-foreground"})})}),t.jsxs(Re,{className:"max-w-sm",children:[t.jsx("p",{className:"text-sm",children:"Compiled in your browser and run in a worker inside a sandboxed frame with its own origin: no page, no cookies, no storage, and nothing on the network it has not been given. The server only ever receives the standard components it produces."}),t.jsx("p",{className:"mt-2 text-sm",children:"Network is per host. A plugin allowed to call a host can also load code from it and send it anything it renders, so list only hosts you would trust with the document."})]})]}),t.jsx("span",{className:"flex-1"}),t.jsxs(In,{children:[t.jsx(_n,{asChild:!0,children:t.jsxs(Me,{variant:"ghost",size:"sm",className:"h-7 gap-1.5 px-2 text-xs",disabled:p.length===0,title:p.length===0?"Add a JSDoc @example with a JSON block to list usage examples here":void 0,children:[t.jsx(Ts,{className:"size-3.5"}),"Examples",p.length>0&&t.jsx(at,{variant:"secondary",className:"h-4 px-1 text-[10px]",children:p.length})]})}),t.jsxs(zn,{align:"end",className:"w-64",children:[t.jsx(Fn,{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Copy as component JSON"}),t.jsx($n,{}),p.map((L,T)=>t.jsxs(Vn,{onClick:$=>{$.preventDefault(),O(T)},className:"gap-2",children:[l===T?t.jsx(ht,{className:"size-3.5 text-success"}):t.jsx(Rs,{className:"size-3.5 text-muted-foreground"}),t.jsx("span",{className:"truncate",children:L.title??`Example ${T+1}`})]},T))]})]}),t.jsxs("label",{htmlFor:`plugin-enabled-${e}`,className:_("flex h-7 cursor-pointer items-center gap-1.5 rounded-sm px-1.5 text-xs",s!=null&&s.enabled?"text-foreground":"text-muted-foreground"),title:"On: the component is offered in completions and expanded in every build. Off: a document that still names it fails to build with a message pointing here.",children:["Enabled",t.jsx(Yt,{id:`plugin-enabled-${e}`,checked:(s==null?void 0:s.enabled)??!0,onCheckedChange:v,"aria-label":"Enable plugin"})]}),t.jsx(Gr,{docName:e,allowNetwork:(s==null?void 0:s.allowNetwork)??!1,origins:(s==null?void 0:s.networkOrigins)??[],onToggle:D,onCommitOrigins:V}),t.jsxs(Ee,{children:[t.jsx(Te,{asChild:!0,children:t.jsx(Me,{variant:"ghost",size:"icon",className:"size-7","aria-label":"Download plugin source",onClick:()=>Hn(e,new Blob([n],{type:"text/typescript"})),children:t.jsx(Ms,{className:"size-3.5"})})}),t.jsx(Re,{children:t.jsxs("p",{children:["Download ",t.jsx("code",{children:e})," to use it on disk with the CLI"]})})]})]})}const Br=W.memo(Hr);function Gr({docName:e,allowNetwork:n,origins:s,onToggle:r,onCommitOrigins:a}){const[i,o]=u.useState(!1),[l,c]=u.useState(()=>s.join(`
13
+ `));u.useEffect(()=>{i||c(s.join(`
14
+ `))},[i,s]);const d=kn(l),f=n&&s.length>0,m=n?s.length===0?"Network on, no hosts listed":`Network: ${s.join(", ")}`:"Network off";return t.jsxs(bt,{open:i,onOpenChange:o,children:[t.jsx(yt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":m,title:m,className:_("flex h-7 cursor-pointer items-center gap-1.5 rounded-sm px-1.5 text-xs","transition-colors hover:bg-muted/60","focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none",f?"text-foreground":"text-muted-foreground"),children:[t.jsx(As,{className:"size-3.5","aria-hidden":"true"}),t.jsx("span",{className:"hidden sm:inline",children:"Network"}),f&&t.jsx(at,{variant:"outline",className:"h-4 px-1 font-mono text-[10px] tabular-nums",children:s.length}),n&&s.length===0&&t.jsx("span",{className:"text-[10px] text-amber-600 dark:text-amber-500",children:"no hosts"})]})}),t.jsxs(We,{align:"end",className:"w-80 space-y-3",children:[t.jsxs("label",{htmlFor:`plugin-network-${e}`,className:"flex cursor-pointer items-center justify-between gap-2",children:[t.jsx("span",{className:"text-sm font-medium",children:"Allow network"}),t.jsx(Yt,{id:`plugin-network-${e}`,checked:n,onCheckedChange:r,"aria-label":"Allow network access"})]}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:["Off: ",t.jsx("code",{children:"fetch"}),", ",t.jsx("code",{children:"XMLHttpRequest"}),","," ",t.jsx("code",{children:"WebSocket"})," and ",t.jsx("code",{children:"EventSource"})," throw inside the sandbox. On: only the hosts below are reachable — everything else is refused by the browser, not by the plugin."]}),n&&t.jsxs(t.Fragment,{children:[t.jsx(Bn,{value:l,onChange:x=>c(x.target.value),onBlur:()=>a(d.origins),spellCheck:!1,rows:3,"aria-label":"Hosts this plugin may call",placeholder:`api.open-meteo.com
15
+ geocoding-api.open-meteo.com`,className:"font-mono text-xs"}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:["One host per line. ",t.jsx("code",{children:"https"})," is assumed;"," ",t.jsx("code",{children:"*.example.com"})," matches subdomains."]}),d.errors.length>0&&t.jsx("ul",{className:"space-y-0.5 text-xs text-destructive",children:d.errors.map(x=>t.jsx("li",{children:x},x))}),d.errors.length===0&&d.origins.length===0&&t.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-500",children:"Nothing listed, so nothing is reachable."})]})]})]})}function Ur({name:e,value:n,saveDocumentDebounceWait:s}){const r=u.useRef(null),{resolvedTheme:a}=Jt(),i=ue(w=>w.saveDocument),o=ue(w=>w.closeDocument),{registerEditor:l,unregisterEditor:c,setActiveEditor:d}=ye(),f=be(w=>{var h;return(h=w.records[e])==null?void 0:h.diagnostics}),m=u.useRef(null),[x,y]=u.useState(n),p=u.useRef(Xt(w=>{m.current=w,i(e,w)},s)),[j,v]=u.useState(!0),[A,D]=u.useState(!1),V=u.useRef(!1),O=u.useMemo(()=>(f??[]).map(w=>({path:w.source==="typescript"?"":w.source,message:w.message,code:w.source,severity:w.severity,...w.line!==void 0?{startLineNumber:w.line,startColumn:w.column,endLineNumber:w.endLine,endColumn:w.endColumn}:{}})),[f]);u.useEffect(()=>{O.length>0&&!V.current&&(v(!0),D(!1)),O.length===0&&(V.current=!1)},[O.length]);const se=u.useCallback(w=>{Wt(w),En(w)},[]),L=u.useCallback(()=>{p.current.flush()},[]),T=u.useCallback((w,h)=>{r.current=w,l(e,w,h,void 0,void 0,L),d(e);const C=()=>{const b=w.getValue();p.current.cancel(),m.current=b,i(e,b)};w.addCommand(h.KeyMod.CtrlCmd|h.KeyCode.KeyS,C),w.addCommand(h.KeyMod.CtrlCmd|h.KeyCode.KeyW,()=>{C(),o(e)}),w.addCommand(h.KeyMod.Shift|h.KeyMod.Alt|h.KeyCode.KeyF,()=>{var b;(b=w.getAction("editor.action.formatDocument"))==null||b.run()})},[o,L,e,l,i,d]);u.useEffect(()=>{const w=p.current;return()=>{w.flush(),c(e)}},[e,c]),u.useEffect(()=>{var h;if(n===m.current)return;const w=(h=r.current)==null?void 0:h.getModel();w&&w.getValue()!==n&&w.setValue(n),y(n)},[n]);const $=u.useCallback(w=>{const h=r.current;!h||!w.startLineNumber||(h.setPosition({lineNumber:w.startLineNumber,column:w.startColumn??1}),h.revealLineInCenter(w.startLineNumber),h.focus())},[]);return t.jsxs("div",{className:"flex h-full flex-col",children:[t.jsx(Br,{docName:e,text:n}),t.jsxs("div",{className:"relative min-h-0 flex-1",children:[t.jsx(Qt,{height:"100%",defaultLanguage:"typescript",path:Tn(e),value:x,theme:He(a),beforeMount:se,onMount:T,keepCurrentModel:!0,onChange:w=>{w!==void 0&&p.current(w)},options:{lineNumbers:"on",glyphMargin:!0,folding:!0,lineDecorationsWidth:5,lineNumbersMinChars:3,renderValidationDecorations:"on",quickSuggestions:{other:!0,comments:!1,strings:!0},acceptSuggestionOnCommitCharacter:!0,acceptSuggestionOnEnter:"on",autoIndent:"advanced",formatOnType:!0,formatOnPaste:!0,automaticLayout:!0,minimap:{enabled:!1},scrollBeyondLastLine:!0,tabSize:2,wordWrap:"off"}}),t.jsx("div",{className:"absolute top-0 right-0",children:t.jsx(Ut,{errors:O,onClick:()=>{v(!0),D(!1)}})}),j&&O.length>0&&t.jsx(Kt,{errors:O,isMinimized:A,onToggleMinimize:()=>D(w=>!w),onErrorClick:$,onClose:()=>{v(!1),V.current=!0},className:"z-40"})]})]})}const Kr=W.memo(Ur);function Jr({name:e,text:n,buildError:s,saveDocumentDebounceWait:r,documentType:a}){const{saveDocument:i}=ue(f=>f),{updateTheme:o}=qt(f=>f),l=W.useMemo(()=>Xt(o,r),[o,r]);W.useEffect(()=>()=>{l.flush()},[l]);const c=W.useCallback(f=>{i(e,f),a==="application/json+theme"&&(console.log("TabContent: Theme document change detected, debouncing update",{documentName:e,debounceWait:r}),l(e,f))},[e,i,l,a,r]),d=W.useMemo(()=>({name:e,type:"application/json",text:n,mtime:new Date,ctime:new Date,atime:new Date}),[e,n]);return t.jsx(Gn,{value:e,className:"mt-0 h-full p-0",tabIndex:-1,children:a==="application/json+theme"?t.jsx($r,{document:d,onChange:c}):a==="application/typescript+plugin"?t.jsx(Kr,{name:e,value:n,saveDocumentDebounceWait:r}):t.jsx(bn,{name:e,value:n,saveDocumentDebounceWait:r})})}const Wr=W.memo(Jr);function Qr({openTabs:e,documents:n,buildErrors:s,saveDocumentDebounceWait:r}){const{documentTypes:a}=ue(i=>i);return e.map(i=>n.find(o=>o.name===i)).filter(i=>i!==void 0).map(i=>{const o=a[i.name]||"application/json+report";return t.jsx(Wr,{name:i.name,text:i.text,buildError:s[i.name],saveDocumentDebounceWait:r,documentType:o},i.name)})}const qr=W.memo(Qr);class Xr extends Error{constructor(n,s,r){super(n),this.lastError=s,this.attempts=r,this.name="RetryError"}}async function Yr(e,n={}){const{maxRetries:s=3,initialDelay:r=1e3,maxDelay:a=3e4,backoffFactor:i=2,onRetry:o,shouldRetry:l=()=>!0,signal:c}=n;let d;for(let f=0;f<=s;f++)try{if(c!=null&&c.aborted)throw new Error("Operation cancelled");return await e()}catch(m){if(d=m instanceof Error?m:new Error(String(m)),f===s)break;if(!l(d))throw d;const y=Math.min(r*Math.pow(i,f),a)*(.5+Math.random()*.5);o&&o(d,f+1),await new Promise(p=>{const j=setTimeout(p,y);c&&c.addEventListener("abort",()=>{clearTimeout(j),p(void 0)},{once:!0})})}throw new Xr(`Failed after ${s+1} attempts`,d,s+1)}const Bt={networkErrors:e=>["NetworkError","Failed to fetch","ERR_NETWORK","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","fetch failed"].some(s=>e.message.includes(s)||e.name.includes(s)),httpStatusCodes:e=>n=>{var s;return(s=n.response)!=null&&s.status?e.includes(n.response.status):!1},temporaryErrors:e=>["EBUSY","EAGAIN","temporarily unavailable","too many requests","rate limit"].some(s=>e.message.toLowerCase().includes(s.toLowerCase())),combine:(...e)=>n=>e.some(s=>s(n))},Zr="Body text in the normal style, with **bold**, *italic* and `mono` runs beside plain words so weight and the mono role read next to each other. A second sentence gives the line spacing and paragraph spacing room to show.",eo={primary:"Headings and the strongest brand colour",secondary:"Supporting brand colour",accent:"Highlights and emphasis",text:"Body text",textPrimary:"Primary text",textSecondary:"Secondary text",textMuted:"Captions and muted text",text2:"Secondary text and captions",background:"Page background",backgroundPrimary:"Primary surface",backgroundSecondary:"Alternate surface",background2:"Alternate surface and rules",border:"Rules and borders",borderPrimary:"Primary rules",borderSecondary:"Subtle rules",accent4:"Chart series 4",accent5:"Chart series 5",accent6:"Chart series 6"};function xn(e){return e?us(e):[]}function Gt(e,n){const s=e==null?void 0:e.styles;return!!s&&typeof s=="object"&&n in s}function to(e,n){const s=xn(n),r=[];return r.push(Gt(n,"title")?{name:"paragraph",props:{text:"Theme specimen",themeStyle:"title"}}:{name:"heading",props:{text:"Theme specimen",level:1}}),Gt(n,"subtitle")?r.push({name:"paragraph",props:{text:`Every named style, colour and font of "${e}", on one page.`,themeStyle:"subtitle"}}):r.push({name:"paragraph",props:{text:`Every named style, colour and font of "${e}", on one page.`}}),r.push({name:"heading",props:{text:"Heading 1 — Typography",level:1}},{name:"paragraph",props:{text:Zr}},{name:"heading",props:{text:"Heading 2 — Structure",level:2}},{name:"paragraph",props:{text:"A second paragraph under a second-level heading, so the spacing before and after headings can be judged against running text."}},{name:"heading",props:{text:"Heading 3 — Detail",level:3}},{name:"list",props:{items:["Primary carries the headings","Secondary supports it","Accent marks emphasis"]}},{name:"divider",props:{}},{name:"heading",props:{text:"Figures",level:2}},{name:"statistic",props:{number:"42%",description:"A statistic: the number in the heading font, the caption below it"}}),s.length>0&&r.push({name:"heading",props:{text:"Colours",level:2}},{name:"table",props:{columns:[{header:{content:"Token"},cells:s.map(a=>({content:a}))},{header:{content:"Swatch"},cells:s.map(a=>({content:" ",backgroundColor:a}))},{header:{content:"Role"},cells:s.map(a=>({content:eo[a]??""}))}]}}),{name:"docx",props:{theme:e,metadata:{title:`${e} sample`,author:"json-to-office playground",description:`Sample rendered in the "${e}" theme`}},children:[{name:"section",props:{},children:r}]}}function no(e,n){const s=xn(n),r=(i,o,l,c,d,f)=>({name:"text",props:{text:i,style:o,x:l,y:c,w:d,h:f}}),a=[{name:"slide",props:{meta:{title:"Title"}},children:[r("Theme specimen","title",.5,1.6,9,1.2),r(`Named styles, colours and fonts of "${e}"`,"subtitle",.5,2.9,9,.8)]},{name:"slide",props:{meta:{title:"Typography"}},children:[r("Typography","heading1",.5,.4,9,.8),r("Heading 2 — the section style","heading2",.5,1.3,9,.6),r("Heading 3 — the detail style","heading3",.5,1.95,9,.5),r("Body text in the body style. It runs long enough to wrap onto a second line, so the line spacing and the body size can be judged against the headings above it.","body",.5,2.55,9,1.4),r("Caption — the smallest voice on the slide","caption",.5,4.1,9,.4)]}];if(s.length>0){const o=[];s.forEach((l,c)=>{const d=c%6,f=Math.floor(c/6),m=.5+d*1.5,x=1.3+f*1.6;o.push({name:"shape",props:{type:"rect",x:m,y:x,w:1.3,h:.9,fill:{color:l}}},r(l,"caption",m,x+.95,1.3,.4))}),a.push({name:"slide",props:{meta:{title:"Colours"}},children:[r("Colours","heading1",.5,.4,9,.8),...o]})}return a.push({name:"slide",props:{meta:{title:"Chart and table"}},children:[r("Chart and table","heading1",.5,.4,9,.8),{name:"chart",props:{type:"bar",x:.5,y:1.3,w:4.6,h:3.6,showLegend:!0,data:[{name:"Revenue",labels:["Q1","Q2","Q3","Q4"],values:[120,132,145,160]},{name:"Cost",labels:["Q1","Q2","Q3","Q4"],values:[80,84,91,95]},{name:"Margin",labels:["Q1","Q2","Q3","Q4"],values:[40,48,54,65]}]}},{name:"table",props:{x:5.4,y:1.3,w:4.1,headerRow:!0,rows:[[{text:"Metric"},{text:"Value"}],[{text:"Revenue"},{text:"$4.2M"}],[{text:"Users"},{text:"12,847"}],[{text:"Retention"},{text:"94%"}]]}}]}),{name:"pptx",props:{title:`${e} sample`,theme:e},children:a}}function so(e){return`Sample · ${e}`}function ro(e){return e.startsWith("Sample · ")}function oo(e,n,s){return e==="docx"?to(n,s):no(n,s)}function ao(){const e=Rn(g=>g.setOutput),n=u.useContext(Mn),s=u.useContext(An),r=u.useContext(Dn),a=je(g=>g.saveDocumentDebounceWait),{openTabs:i,activeTab:o,setActiveTab:l,documents:c,buildErrors:d,setBuildError:f,documentTypes:m}=ue(Dt(g=>({openTabs:g.openTabs,activeTab:g.activeTab,setActiveTab:g.setActiveTab,documents:g.documents,buildErrors:g.buildErrors,setBuildError:g.setBuildError,documentTypes:g.documentTypes}))),{customThemes:x}=qt(Dt(g=>({customThemes:g.customThemes}))),{generatePresentation:y,cancelGeneration:p}=Un(),j=je(g=>g.qualityProfileIds),v=ds(j),A=je(g=>g.qualityGate),D=je(g=>{var k;return(k=g.qualityPolicies)==null?void 0:k[Z]}),V=u.useMemo(()=>ms(v,A,D),[v,A,D]),{analyze:O,cancel:se}=fs(),L=u.useRef(new Map),T=u.useRef(new Map),$=u.useRef(null),w=u.useRef(""),h=u.useRef(new Map),C=u.useCallback(()=>{w.current=`cancelled-${Date.now()}`;for(const g of T.current.values())clearTimeout(g);T.current.clear(),$.current&&(clearTimeout($.current),$.current=null);for(const g of L.current.values())g.abort();L.current.clear(),p(),e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0})},[p,e]);u.useEffect(()=>{e({cancelGeneration:C})},[C,e]);const b=u.useCallback(g=>{const N=(h.current.get(g)||0)+1;return h.current.set(g,N),N},[]),S=u.useMemo(()=>{const g=Object.entries(x).map(([k,N])=>{let R=0;return N.lastModified&&(N.lastModified instanceof Date?R=N.lastModified.getTime():typeof N.lastModified=="string"&&(R=new Date(N.lastModified).getTime())),{key:k,name:N.name,content:N.content,valid:N.valid,lastModified:R}});return JSON.stringify(g)},[x]),E=u.useMemo(()=>{const g={};return Object.values(x).forEach(k=>{k.valid&&k.parsed&&(g[k.name]=k.parsed)}),g},[S]),M=u.useCallback(()=>{const g={},{customThemes:k}=r.getState();return Object.values(k).forEach(N=>{N.valid&&N.parsed&&(g[N.name]=N.parsed)}),g},[r]),P=u.useCallback(async(g,k,N)=>{if(!g||!y)return;const R=L.current.get(g.name);R&&(R.abort(),L.current.delete(g.name));const F=k?null:new AbortController,I=k||F.signal;F&&L.current.set(g.name,F);const te=`${g.name}-${Date.now()}-${Math.random()}`,fe=b(g.name);w.current=te;const q={id:te,docName:g.name,doc:g,signal:I,timestamp:Date.now(),qualityTicket:gs()};await H.current(q,fe,N)},[y,e,b]),z=u.useCallback(async(g,k,N)=>{var X;const{doc:R,signal:F,id:I,qualityTicket:te}=g,fe=Q=>xs(n.getState().quality,te)?{}:{quality:Q};if(w.current!==I){console.log("Skipping outdated build request for:",R.name),e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0});return}e({globalError:void 0,isGenerating:!0,generationStartedAt:Date.now(),generationProgress:{stage:"parsing",message:"Validating JSON structure..."}});const q=(Q,re)=>{if(F.aborted||w.current!==I)return;if((h.current.get(R.name)||0)!==k){console.log("Document version changed, aborting build"),F.dispatchEvent(new Event("abort"));return}e({isGenerating:!0,generationProgress:{stage:Q,message:re}})};try{const Q=M();console.log("Editor: Using themes for document build",{docName:R.name,freshThemeCount:Object.keys(Q).length,freshThemeNames:Object.keys(Q),memoizedCount:Object.keys(E).length,requestId:I}),q("parsing","Expanding plugins...");const re=await Kn(R.text,{customThemes:Q,signal:F});if(ro(R.name)||(G.current=null),F.aborted||w.current!==I){e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0});return}const J=await Yr(async()=>{if(F.aborted)throw new Error("Build cancelled");return await y(R.name,re.text,Q,q,{...N,...V?{quality:V}:{}})},{maxRetries:2,initialDelay:500,shouldRetry:oe=>oe.message.includes("cancelled")||oe.message.includes("JSON")||oe.message.includes("parse")||oe.message.includes("syntax")?!1:Bt.combine(Bt.temporaryErrors,ae=>ae.message.includes("Worker")||ae.message.includes("Proxy"))(oe),onRetry:(oe,ae)=>{console.log(`Retrying presentation generation (attempt ${ae}):`,oe.message),e({isGenerating:!0,generationProgress:{stage:"parsing",message:`Retrying generation (attempt ${ae})...`}})},signal:F});if(F.aborted||w.current!==I){console.log("Build cancelled for:",R.name),e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0});return}if(J&&typeof J=="object"&&"name"in J&&"text"in J&&"blob"in J){console.log("Editor: Build completed",{docName:J.name,blobSize:(X=J.blob)==null?void 0:X.size,timestamp:Date.now(),requestId:I,version:k});const{findings:oe,others:ae}=ps(J.warnings);e({name:J.name,text:J.text,blob:J.blob,renderer:J.renderer,globalError:void 0,isGenerating:!1,isPreviewStale:!1,generationProgress:void 0,generationStartedAt:void 0,lastBuiltSequence:n.getState().editSequence,cacheStatus:J.cacheStatus,cacheHitRate:J.cacheHitRate,warnings:[...re.warnings,...ae],...fe({findings:oe,counts:Mt(oe),...v?{profileId:v}:{},documentName:R.name,seq:te,source:"generate",analyzedAt:Date.now()})}),f(J.name,void 0)}}catch(Q){if(F.aborted||w.current!==I){console.log("Build cancelled with error for:",R.name),e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0});return}const re=Q instanceof Error?Q.message:String(Q),J=Q instanceof Jn?hs(Q.quality):null;e({globalError:re,isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0,...J?fe({findings:J,counts:Mt(J),...v?{profileId:v}:{},documentName:R.name,seq:te,blocked:!0,source:"generate",analyzedAt:Date.now(),gateError:re}):{}}),f(R.name,re)}finally{L.current.delete(R.name)}},[y,M,V,v,e,f,n]),H=u.useRef(z);u.useEffect(()=>{H.current=z});const B=u.useRef(null),G=u.useRef(null);u.useEffect(()=>{console.log("Editor: Document rebuild effect triggered",{activeTab:o});const g=c.find(R=>R.name===o),k=m[o]||"application/json+report";k==="application/json+report"&&g&&(B.current=o);const N=T.current.get(o);return N&&(clearTimeout(N),T.current.delete(o)),g&&k==="application/json+report"?n.getState().isGenerating||e({isPreviewStale:!0}):g&&k!=="application/json+report"&&p(),()=>{const R=T.current.get(o);R&&(clearTimeout(R),T.current.delete(o))}},[c,o,e,m,P,p]),u.useEffect(()=>{const g=c.find(N=>N.name===o),k=m[o]||"application/json+report";if(!g||k!=="application/json+report"){se(),e({quality:null});return}return O(o,g.text),se},[o,O,se,c,m,e]);const Y=u.useMemo(()=>{var N;const g=new Map,k=c.find(R=>R.name===o);if(k&&m[k.name]==="application/json+report")try{const F=(N=JSON.parse(k.text).props)==null?void 0:N.theme;typeof F=="string"&&Object.values(x).some(te=>te.name===F&&te.valid)&&g.set(k.name,F)}catch{}return g},[o,c,m,x]);u.useEffect(()=>(console.log("Editor: Setting up theme change listener",{documentCount:c.length,dependencyCount:Y.size,dependencies:Array.from(Y.entries()),customThemes:Object.entries(x).map(([k,N])=>({key:k,name:N.name,valid:N.valid}))}),Ln.onThemeChange(k=>{console.log("Editor: Theme change detected",{event:k,dependencies:Array.from(Y.entries()),activeTab:o,customThemes:Object.entries(x).map(([R,F])=>({key:R,name:F.name,valid:F.valid}))});const N=[];if(Y.forEach((R,F)=>{if(R===k.themeName){const I=c.find(te=>te.name===F);I&&N.push(I)}}),console.log("Editor: Documents using changed theme",{themeName:k.themeName,documentCount:N.length,documentNames:N.map(R=>R.name)}),N.length===0){console.log("Editor: No documents use this theme, skipping rebuild");return}n.getState().isGenerating||e({isPreviewStale:!0})})),[Y,c,P,b,o,e]);const ee=u.useRef(P);u.useEffect(()=>{ee.current=P});const me=u.useRef(b);u.useEffect(()=>{me.current=b}),u.useEffect(()=>{const g=()=>{var fe;e({isGenerating:!0});let k=!1;const N=ye.getState().getActiveEditor();if(N&&!s.getState().pendingDiffs[N.documentName]){const X=N.toStorageValue(N.editor.getValue());s.getState().saveDocument(N.documentName,X)}const{documents:R,documentTypes:F}=s.getState();for(const q of R)if(F[q.name]==="application/json+theme"){const X=ye.getState().getEditor(q.name);if(X){const Q=X.toStorageValue(X.editor.getValue()),re=r.getState().customThemes[q.name];(!re||re.content!==Q)&&(r.getState().updateTheme(q.name,Q),k=!0)}}else if(F[q.name]==="application/typescript+plugin"){const X=ye.getState().getEditor(q.name);if(X){(fe=X.flushPendingSave)==null||fe.call(X);const Q=X.toStorageValue(X.editor.getValue());Q!==q.text&&s.getState().saveDocument(q.name,Q)}}ot.flush();const I=s.getState().activeTab,te=T.current.get(I);te&&(clearTimeout(te),T.current.delete(I)),$.current&&clearTimeout($.current),$.current=setTimeout(async()=>{$.current=null,await ot.whenIdle();const{documents:q,activeTab:X,documentTypes:Q}=s.getState();let re=X;const J=Q[X]||"application/json+report";if(J!=="application/json+report"){const ae=G.current;if(ae&&J==="application/json+theme"&&ae.themeDocName===X){U.current(X);return}if(B.current)re=B.current;else{e({isGenerating:!1});return}}const oe=q.find(ae=>ae.name===re);if(oe){const ae=s.getState().pendingDiffs[re],qe=ye.getState().getEditor(re),vt=ae?{...oe,text:ae.modified}:qe?{...oe,text:qe.toStorageValue(qe.editor.getValue())}:oe;me.current(vt.name),ee.current(vt,void 0,k?{bypassCache:!0}:void 0)}else e({isGenerating:!1})},150)};return window.addEventListener("preview:flushAndBuild",g),()=>{window.removeEventListener("preview:flushAndBuild",g),$.current&&clearTimeout($.current)}},[e,s,r]);const K=u.useCallback(g=>{const{documents:k}=s.getState(),N=k.find(q=>q.name===g);if(!N){e({isGenerating:!1});return}let R,F=null,I=null;try{R=JSON.parse(N.text),F=dt(R)}catch(q){I=q instanceof Error?q.message:"Invalid JSON"}if(!F){e({isGenerating:!1,globalError:I?`The theme is not valid JSON: ${I}`:"The theme has no name"});return}const te=so(F),fe=JSON.stringify(oo(Z,F,R),null,2);G.current={themeDocName:g},e({isGenerating:!0}),me.current(te),ee.current({name:te,text:fe},void 0,{bypassCache:!0})},[s,e]),U=u.useRef(K);return u.useEffect(()=>{U.current=K}),u.useEffect(()=>{const g=k=>{const N=k.detail;N!=null&&N.themeDocName&&U.current(N.themeDocName)};return window.addEventListener("preview:buildSpecimen",g),()=>window.removeEventListener("preview:buildSpecimen",g)},[]),u.useEffect(()=>{const g=()=>{n.getState().isGenerating||e({isPreviewStale:!0})};return window.addEventListener(rt,g),()=>window.removeEventListener(rt,g)},[n,e]),u.useEffect(()=>()=>{L.current.forEach(g=>g.abort()),L.current.clear(),T.current.forEach(g=>clearTimeout(g)),T.current.clear(),p()},[p]),i.length?t.jsx(Wn,{value:o,onValueChange:l,className:"h-full",children:t.jsx(qr,{openTabs:i,documents:c,buildErrors:d,saveDocumentDebounceWait:a})}):t.jsx("div",{className:"flex flex-col text-muted-foreground h-full items-center justify-center",children:c!=null&&c.length?"Open a document...":"Create a new document..."})}const jo=u.memo(ao);export{jo as Editor};
16
+ //# sourceMappingURL=editor-CwEocOY2.js.map