@json-to-office/jto 1.11.1 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +444 -99
- package/dist/cli.js.map +1 -1
- package/dist/client/assets/HomePage-DMpdYyZ0.js +251 -0
- package/dist/client/assets/HomePage-DMpdYyZ0.js.map +1 -0
- package/dist/client/assets/JsonEditorPage-Ct7wb9iA.js +3 -0
- package/dist/client/assets/JsonEditorPage-Ct7wb9iA.js.map +1 -0
- package/dist/client/assets/MonacoPluginProvider-B2fWYflh.js +85 -0
- package/dist/client/assets/MonacoPluginProvider-B2fWYflh.js.map +1 -0
- package/dist/client/assets/_virtual_jto-plugin-type-libs-BlMraosv.js +25700 -0
- package/dist/client/assets/_virtual_jto-plugin-type-libs-BlMraosv.js.map +1 -0
- package/dist/client/assets/_virtual_jto-sandbox-runtime-CNoAasd3.js +2 -0
- package/dist/client/assets/_virtual_jto-sandbox-runtime-CNoAasd3.js.map +1 -0
- package/dist/client/assets/editor-DFnlAOyt.js +16 -0
- package/dist/client/assets/editor-DFnlAOyt.js.map +1 -0
- package/dist/client/assets/{editor-monaco-json-BYUK4OUI.js → editor-monaco-json-B_1-Wxq5.js} +5 -5
- package/dist/client/assets/{editor-monaco-json-BYUK4OUI.js.map → editor-monaco-json-B_1-Wxq5.js.map} +1 -1
- package/dist/client/assets/{editor-refs-store-ChL2fzuX.js → editor-refs-store-DHeIvmr6.js} +2 -2
- package/dist/client/assets/{editor-refs-store-ChL2fzuX.js.map → editor-refs-store-DHeIvmr6.js.map} +1 -1
- package/dist/client/assets/index-Bj6ZAKUc.css +1 -0
- package/dist/client/assets/index-CeZaIyj_.js +5 -0
- package/dist/client/assets/index-CeZaIyj_.js.map +1 -0
- package/dist/client/assets/preview-CugO7y1j.js +4 -0
- package/dist/client/assets/preview-CugO7y1j.js.map +1 -0
- package/dist/client/assets/radix-ui-BzbaiLpZ.js +51 -0
- package/dist/client/assets/radix-ui-BzbaiLpZ.js.map +1 -0
- package/dist/client/assets/{ui-vendor-Bq4-oNFL.js → ui-vendor-BsAtAN16.js} +94 -64
- package/dist/client/assets/ui-vendor-BsAtAN16.js.map +1 -0
- package/dist/client/assets/useQualityAnalysis-DH2idzAY.js +6 -0
- package/dist/client/assets/useQualityAnalysis-DH2idzAY.js.map +1 -0
- package/dist/client/index.html +4 -4
- package/dist/client/templates/modern-annual-report-1.docx.json +0 -1
- package/dist/client/templates/modern-annual-report-2.docx.json +2 -4
- package/dist/client/templates/modern-annual-report-3.docx.json +1 -2
- package/dist/client/templates/standard-annual-report.docx.json +0 -1
- package/dist/client/templates/vermilion-annual-report.docx.json +0 -9
- package/dist/render-server.js.map +1 -1
- package/package.json +8 -6
- package/dist/client/assets/HomePage-r7ryeW_v.js +0 -106
- package/dist/client/assets/HomePage-r7ryeW_v.js.map +0 -1
- package/dist/client/assets/JsonEditorPage-BxUyYH8Z.js +0 -3
- package/dist/client/assets/JsonEditorPage-BxUyYH8Z.js.map +0 -1
- package/dist/client/assets/MonacoPluginProvider-CGvtVJKz.js +0 -3
- package/dist/client/assets/MonacoPluginProvider-CGvtVJKz.js.map +0 -1
- package/dist/client/assets/editor-gT4UjmPk.js +0 -9
- package/dist/client/assets/editor-gT4UjmPk.js.map +0 -1
- package/dist/client/assets/index-CgCY8SiY.js +0 -5
- package/dist/client/assets/index-CgCY8SiY.js.map +0 -1
- package/dist/client/assets/index-CrzIwHLS.css +0 -1
- package/dist/client/assets/preview-ZqhmQZJG.js +0 -2
- package/dist/client/assets/preview-ZqhmQZJG.js.map +0 -1
- package/dist/client/assets/radix-ui-DFNP5I4e.js +0 -51
- package/dist/client/assets/radix-ui-DFNP5I4e.js.map +0 -1
- package/dist/client/assets/ui-vendor-Bq4-oNFL.js.map +0 -1
- package/dist/client/assets/useQualityAnalysis-eKT8VcIt.js +0 -6
- package/dist/client/assets/useQualityAnalysis-eKT8VcIt.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_virtual_jto-sandbox-runtime-CNoAasd3.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import{c as Y,r as u,j as t}from"./react-vendor-BmQ2Ko_D.js";import{g as it,c as lt,V as Et,a as Rt,E as Qt}from"./editor-monaco-json-B_1-Wxq5.js";import{h as Tt,r as Mt,q as Ee,F as te,c as B,e as Ce,f as je,g as we,n as Xt,u as Yt,S as ct}from"./index-CeZaIyj_.js";import Dt,{DiffEditor as Zt}from"./monaco-editor-DJsdM0WK.js";import{a as le,f as xe,g as Qe,u as ge,P as en,B as Be,p as tn,n as Ue,o as nn,q as sn,r as rn,t as on,w as an,b as Pt,d as ln,x as cn,y as un,T as dn,z as mn}from"./MonacoPluginProvider-B2fWYflh.js";import{u as be,B as ve,d as Lt}from"./editor-refs-store-DHeIvmr6.js";import{I as Ae,S as Te,a as Me,b as De,c as Pe,d as ye,e as fn,t as hn,B as qe,D as pn,f as gn,g as xn,h as bn,i as yn,j as Cn,k as At,l as jn,T as wn,m as vn,u as Nn,n as Sn,Q as kn,o as En}from"./HomePage-DMpdYyZ0.js";import{r as fe,n as Xe,u as It,I as Ye,c as ut,E as he,C as dt,G as Ot,a as Rn,b as ce,H as ae,d as _t,i as Tn,e as Mn,Q as me,D as zt,g as ie,P as Dn,F as Ft,f as Le,h as Ie,S as Ke,j as mt,M as Vt,k as Pn,t as Ln,l as An,s as In,m as On,o as _n,p as zn,q as $t,v as Fn,w as Vn,x as $n,y as Hn,z as ft,T as Gn,A as Bn,B as Un,J as qn,K as Kn,L as Jn,N as Wn,O as ht,R as Qn,U as Xn,V as Yn}from"./useQualityAnalysis-DH2idzAY.js";import{ad as Zn,ae as es,af as ts,ag as Ht}from"./radix-ui-BzbaiLpZ.js";import{a8 as ns,X as ss,a as Ze,a9 as rs,T as os,aa as as,O as is,e as pt,_ as ls,x as Gt,B as Bt,h as cs,y as us,t as ds,v as ms,ab as fs,ac as hs}from"./ui-vendor-BsAtAN16.js";import{u as gt}from"./state-vendor-Cq67_JbF.js";import"./query-vendor--rhYD8mC.js";const ps={initWith:function(e){const s=document.createElement("div"),n=e.editor.create(s),r=n.constructor.name,o=n.getModel().constructor.name;return{isInstanceValid:function(c){return c.constructor.name===r},isModelValid:function(c){return c.constructor.name===o},isRangesValid:function(c){return Array.isArray(c)?c.every(function(h){return typeof h=="object"&&h.constructor.name==="Object"?!(!h.hasOwnProperty("range")||!Array.isArray(h.range)||h.range.length!==4||!h.range.every(p=>p>0&&parseInt(p)===p)||h.hasOwnProperty("allowMultiline")&&typeof h.allowMultiline!="boolean"||h.hasOwnProperty("label")&&typeof h.label!="string"||h.hasOwnProperty("validate")&&typeof h.validate!="function"):!1}):!1}}}},ke=function(e,s,n){return"The value for the "+s+" should be of type "+(Array.isArray(e)?e.join(" | "):e)+". "+(n||"")},ze=function(){const e=function(a,l){return typeof a!="object"||a===null?this.freeze?Object.freeze(a):a:a instanceof Date?this.freeze?Object.freeze(new Date(a)):new Date(a):l.call(this,a)},s=function(a,l){const c=Object.keys(a),h=new Array(c.length);for(let p=0;p<c.length;p++)h[c[p]]=e.call(this,a[c[p]],l);return h},n=function(a){return e.call(this,a,function(l){if(Array.isArray(l))return s.call(this,l,n);const c={};for(let h in l)!this.withProto&&Object.hasOwnProperty.call(l,h)===!1||(c[h]=e.call(this,l[h],n));return c})},r=function(){const a=function(c){const h=["withProto","freeze"];this[c]=h.reduce((function(p,m){return(p[m]=c>=this[m])&&(c-=this[m]),p}).bind(this),{})},l=Object.create(Object.defineProperties({},{withProto:{value:1},freeze:{value:2}}));for(let c=0;c<=3;c++)a.call(l,c);return l}(),o={withProto:n.bind(r[1]),andFreeze:n.bind(r[2]),withProtoAndFreeze:n.bind(r[3])},i=n.bind(r[0]);for(let a in o)Object.defineProperty(i,a,{enumerable:!1,writable:!1,configurable:!1,value:o[a]});return i}(),xt={SINGLE_LINE_HIGHLIGHT_CLASS:"editableArea--single-line",MULTI_LINE_HIGHLIGHT_CLASS:"editableArea--multi-line"},gs=function(e,s,n){const r=n.Range,o=function(d,b){const x=d.range,S=b.range;if(x[0]<S[0]||x[0]===S[0]&&x[3]<S[1])return-1},i=function(d,b){const x=b.split(`
|
|
2
|
+
`),S=x.length,E=[];return d.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 _=M;const V=E[0],$=x[V-1].length;if(_<0){if(_=$-Math.abs(_),_<0)throw new Error("Provided Start Column("+M+") is out of bounds. Max Column in line "+V+" is "+$)}else if(_>$+1)throw new Error("Provided Start Column("+M+") is out of bounds. Max Column in line "+V+" is "+$);E[P]=_}break;case 2:{let _=M;if(_<0){if(_=S-Math.abs(M),_<0)throw new Error("Provided End Line("+M+") is out of bounds. Max Lines in content is "+S);_<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]=_}break;case 3:{let _=M;const V=E[2],$=x[V-1].length;if(_<0){if(_=$-Math.abs(_),_<0)throw new Error("Provided End Column("+M+") is out of bounds. Max Column in line "+V+" is "+$)}else if(_>$+1)throw new Error("Provided Start Column("+M+") is out of bounds. Max Column in line "+V+" is "+$);E[P]=_}break}}),E};let a=ze(s).sort(o);const l=function(d){const b=e.getValue();d.forEach(function(x,S){const E=i(x.range,b),M=E[0],P=E[1],_=E[2],V=E[3];x._originalRange=E.slice(),x.range=new r(M,P,_,V),x.index=S,x.allowMultiline||(x.allowMultiline=r.spansMultipleLines(x.range)),x.label||(x.label=`[${M},${P} -> ${_}${V}]`)})},c=function(){return a.reduce(function(d,b){return d[b.label]={allowMultiline:b.allowMultiline||!1,index:b.index,range:Object.assign({},b.range),originalRange:b._originalRange.slice()},d},{})},h=function(){return a.reduce(function(d,b){return d[b.label]=e.getValueInRange(b.range),d},{})},p=function(d,b){if(typeof d=="object"&&!Array.isArray(d)){b=typeof b=="boolean"?b:!1;const x=a.reduce(function(S,E){return E.label&&(S[E.label]=E),S},{});for(let S in d){const E=x[S];if(E){const M=d[S];if(D(E,M))throw new Error("Multiline change is not allowed for "+S);const P=ze(E.range);if(P.endLine=P.startLine+M.split(`
|
|
3
|
+
`).length-1,P.endColumn=M.split(`
|
|
4
|
+
`).pop().length,R(E,M,P))throw new Error("Change is invalidated by validate function of "+S);e.applyEdits([{forceMoveMarkers:!!b,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",I),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},y=function(d){d.some(function(b){const x=b.lineNumber,S=b.column,E=a.length;for(let M=0;M<E;M++){const P=a[M].range;if(P.startLineNumber===x&&P.startColumn===S||P.endLineNumber===x&&P.endColumn===S)return e.pushStackElement(),!0}})},j=function(d){typeof d=="function"&&e._editableRangeChangeListener.push(d)},g=function(d,b){const x=c();e._editableRangeChangeListener.forEach(function(S){S.call(e,d,b,x)})},C=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(d){d.range=e.getDecorationRange(d.id)}))})},v=function(d,b,x,S,E,M){let P=b.endLineNumber,_=b.endColumn;d.prevRange=b,d.range=b.setEndPosition(x,S);const V=a.length;let $=E.length;const H=S-_,X=x-P,Z=e._currentCursorPositions||[],ue=Z.length;if($!==ue&&(E=E.filter(function(q){const G=q.range;for(let f=0;f<ue;f++){const k=Z[f];if(G.startLineNumber===k.startLineNumber&&G.endLineNumber===k.endLineNumber&&G.startColumn===k.startColumn&&G.endColumn===k.endColumn)return!0}return!1}),$=E.length),X!==0){for(let q=d.index+1;q<V;q++){const G=a[q],f=G.range;P===f.startLineNumber&&(f.startColumn+=H),P===f.endLineNumber&&(f.endColumn+=H),f.startLineNumber+=X,f.endLineNumber+=X,G.range=f}for(let q=M+1;q<$;q++){const G=E[q],f=G.range,k=f.toString(),N=rangeMap[k];delete rangeMap[k],P===f.startLineNumber&&(f.startColumn+=H),P===f.endLineNumber&&(f.endColumn+=H),f.startLineNumber+=X,f.endLineNumber+=X,G.range=f,rangeMap[f.toString()]=N}}else{for(let q=d.index+1;q<V;q++){const G=a[q],f=G.range;if(f.startLineNumber>P)break;f.startColumn+=H,f.endColumn+=H,G.range=f}for(let q=M+1;q<$;q++){const G=E[q],f=G.range,k=f.toString(),N=rangeMap[k];if(delete rangeMap[k],f.startLineNumber>P){rangeMap[f.toString()]=N;break}else f.startColumn+=H,f.endColumn+=H,G.range=f,rangeMap[f.toString()]=N}}},A=function(d,b){const x={},S=d.range;return d.text===""?x.isDeletion=!0:S.startLineNumber===S.endLineNumber&&S.startColumn===S.endColumn?x.isAddition=!0:x.isReplacement=!0,x.startLineOfRange=S.startLineNumber===b.startLineNumber,x.startColumnOfRange=S.startColumn===b.startColumn,x.endLineOfRange=S.endLineNumber===b.endLineNumber,x.endColumnOfRange=S.endColumn===b.endColumn,x.middleLineOfRange=!x.startLineOfRange&&!x.endLineOfRange,b.startLineNumber===b.endLineNumber?x.rangeIsSingleLine=!0:x.rangeIsMultiLine=!0,x},L=function(d){a=ze(d).sort(o),l(a)},U=function(d){if(e._hasHighlight)e.deltaDecorations(e._oldDecorations,[]),delete e._oldDecorations,delete e._oldDecorationsSource,e._hasHighlight=!1;else{const b=d.cssClassForSingleLine||xt.SINGLE_LINE_HIGHLIGHT_CLASS,x=d.cssClassForMultiLine||xt.MULTI_LINE_HIGHLIGHT_CLASS,S=a.map(function(E){const M={range:E.range,options:{className:E.allowMultiline?x:b}};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}},I=function(){console.debug("handler for unhandled promise rejection")},ne=function(d){for(let b in d){const x=d[b];x.range=x.prevRange}},D=function(d,b){return!d.allowMultiline&&b.includes(`
|
|
5
|
+
`)},R=function(d,b,x){return d.validate&&!d.validate(b,x,d.lastInfo)},F={_isRestrictedModel:!0,_isRestrictedValueValid:!0,_editableRangeChangeListener:[],_isCursorAtCheckPoint:y,_currentCursorPositions:[]};l(a),e._hasHighlight=!1,F._restrictionChangeListener=e.onDidChangeContent(function(d){const b=d.isUndoing;if(e._isRestrictedValueValid=!0,b&&e.editInRestrictedArea)e.editInRestrictedArea&&(e._isRestrictedValueValid=!1);else{const x=d.changes.sort(o),S={},E=a.length;if(x.every(function(P){const _=P.range,V=_.toString();S[V]=null;for(let $=0;$<E;$++){const H=a[$];if(H.range.containsRange(_))return D(H,P.text)?!1:(S[V]=H,!0)}return!1})){x.forEach(function(V,$){const H=V.range,X=S[H.toString()],Z=X.range,ue=V.text||"",q=(ue.match(/\n/g)||[]).length,G=ue.split(/\n/g).pop().length,f=H.endLineNumber-H.startLineNumber,k=H.endColumn-H.startColumn;let N=Z.endLineNumber,T=Z.endColumn,z=0;(Z.endLineNumber===H.startLineNumber||Z.endLineNumber===H.endLineNumber)&&(z+=Z.endColumn-H.startColumn+1);const O=A(V,Z);X.lastInfo=O,(O.isAddition||O.isReplacement)&&(O.rangeIsSingleLine&&(q===0?T+=G:(N+=q,O.startColumnOfRange?T+=G:O.endColumnOfRange?T=G+1:T=G+z)),O.rangeIsMultiLine&&(N+=q,O.endLineOfRange&&(q===0?T+=G:T=z+G))),(O.isDeletion||O.isReplacement)&&(O.rangeIsSingleLine&&(T-=k),O.rangeIsMultiLine&&(O.endLineOfRange?(N-=f,T-=k):N-=f)),v(X,Z,N,T,x,$)});const P=e.getValueInEditableRanges(),_={};for(let V in S){const $=S[V],H=$.range,X=$.label||H.toString(),Z=P[X];if(R($,Z,H)){ne(S),C();return}_[X]=Z}e._hasHighlight&&e._oldDecorationsSource.forEach(function(V){V.range=e.getDecorationRange(V.id)}),g(_,P)}else C()}}),window.onerror=I;const w={editInRestrictedArea:!1,getCurrentEditableRanges:c,getValueInEditableRanges:h,disposeRestrictions:m,onDidChangeContentInEditableRange:j,updateRestrictions:L,updateValueInEditableRanges:p,toggleHighlightOfEditableAreas:U};for(let d in F)Object.defineProperty(e,d,{enumerable:!1,configurable:!0,writable:!0,value:F[d]});for(let d in w)Object.defineProperty(e,d,{enumerable:!1,configurable:!0,writable:!0,value:w[d]});return e};function xs(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 s=function(g){const C=g.getModel();if(C._isCursorAtCheckPoint){const v=g.getSelections(),A=v.map(function(L){return{lineNumber:L.positionLineNumber,column:L.positionColumn}});C._isCursorAtCheckPoint(A),C._currentCursorPositions=v}},n={},{isInstanceValid:r,isModelValid:o,isRangesValid:i}=ps.initWith(e),a=function(g){if(r(g)){let C=g.getDomNode();return m._listener=s.bind(y,g),m._editorInstance=g,m._editorInstance._isInDevMode=!1,C.addEventListener("keydown",m._listener,!0),m._onChangeModelDisposable=g.onDidChangeModel(function(){C&&C.removeEventListener("keydown",m._listener,!0);const v=g.getDomNode();v&&v.addEventListener("keydown",m._listener,!0),C=v}),!0}else throw new Error(ke("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},l=function(g,C){if(o(g))if(i(C)){const v=gs(g,C,e);return n[v.uri.toString()]=v,v}else throw new Error(ke("Array<RangeRestrictionObject>","ranges","Please refer constrained editor documentation for proper structure"));else throw new Error(ke("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},c=function(g){if(o(g)){const C=g.uri.toString(),v=n[C];return v?v.disposeRestrictions():(console.warn("Current Model is not a restricted Model"),!1)}else throw new Error(ke("ICodeEditor","editorInstance","This type interface can be found in monaco editor documentation"))},h=function(){if(m._editorInstance){const C=m._editorInstance.getDomNode();C&&C.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 n)delete n[v];return!0}return!1},p=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(g){const v=g.getSelections().reduce(function(A,{startLineNumber:L,endLineNumber:U,startColumn:I,endColumn:ne}){return A.push("range : "+JSON.stringify([L,I,U,ne])),A},[]).join(`
|
|
7
|
+
`);console.log(`Selected Ranges :
|
|
8
|
+
`+JSON.stringify(v,null,2))}}))},m={_listener:null,_editorInstance:null,_uriRestrictionMap:n,_injectedResources:e},y=Object.create(m),j={initializeIn:a,addRestrictionsTo:l,removeRestrictionsIn:c,disposeConstrainer:h,toggleDevMode:p};for(let g in j)Object.defineProperty(y,g,{enumerable:!1,writable:!1,configurable:!1,value:j[g]});return Object.freeze(y)}function bs(e){const s=`.${te}.theme.json`;return e.endsWith(s)?e:e.replace(/\.\w+\.theme\.json$/,"").replace(/\.theme\.json$/,"").replace(/\.json$/,"")+s}function ys({document:e,readOnly:s=!1,onChange:n}){const r=u.useRef(null),o=u.useRef(null),i=u.useRef(null),{theme:a}=Tt(),[l,c]=u.useState([]),[h,p]=u.useState(!0),[m,y]=u.useState(!1),j=u.useRef(!1),g=le(d=>d.pendingDiffs[e.name]),C=le(d=>d.clearPendingDiff),v=le(d=>d.saveDocument),{registerEditor:A,unregisterEditor:L,setActiveEditor:U}=be(),I=a==="system"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":a,ne=u.useCallback(d=>{o.current=d,Mt(d)},[]),D=u.useCallback((d,b)=>{r.current=d,i.current=d.getModel(),A(e.name,d,b),U(e.name);const x=xs(b);d.getModel()&&x.initializeIn(d),d.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}}),d.addCommand(b.KeyMod.CtrlCmd|b.KeyCode.KeyK,()=>{const E=it(d,b);if(E){const M=lt(E);window.dispatchEvent(new CustomEvent("monaco-selection-to-ai",{detail:{documentName:e.name,selection:E,snippet:M,isTheme:!0}}))}}),d.addCommand(b.KeyMod.CtrlCmd|b.KeyCode.KeyS,()=>{console.log("Save command triggered in theme editor")}),d.addAction({id:"send-theme-to-ai-assistant",label:"Send to AI Assistant (⌘K)",contextMenuGroupId:"navigation",contextMenuOrder:1.5,keybindings:[b.KeyMod.CtrlCmd|b.KeyCode.KeyK],run:function(){const E=it(d,b);if(E){const M=lt(E);window.dispatchEvent(new CustomEvent("monaco-selection-to-ai",{detail:{documentName:e.name,selection:E,snippet:M,isTheme:!0}}))}}}),setTimeout(()=>{var E;(E=d.getAction("editor.action.formatDocument"))==null||E.run()},100),console.log("Monaco theme editor mounted")},[e.name,A,U]);u.useEffect(()=>()=>{L(e.name)},[e.name,L]);const R=u.useCallback((d,b)=>{d!==void 0&&n&&n(d)},[n]),F=u.useCallback(d=>{const b=d.map(x=>{var S;return{path:"",message:x.message,code:typeof x.code=="string"?x.code:((S=x.code)==null?void 0:S.value)||"validation_error",startLineNumber:x.startLineNumber,startColumn:x.startColumn,endLineNumber:x.endLineNumber,endColumn:x.endColumn,severity:x.severity>=8?"error":x.severity>=4?"warning":"info"}});c(b),b.length>0&&!j.current&&(p(!0),y(!1)),b.length===0&&(j.current=!1)},[]),w=u.useCallback(d=>{r.current&&d.startLineNumber&&d.startColumn&&(r.current.setPosition({lineNumber:d.startLineNumber,column:d.startColumn}),r.current.revealLineInCenter(d.startLineNumber),r.current.focus())},[]);return u.useEffect(()=>{r.current&&r.current.updateOptions({theme:Ee(I)})},[I]),t.jsxs("div",{className:"relative h-full",children:[g?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(ve,{variant:"secondary",size:"sm",onClick:()=>C(e.name),children:"Discard"}),t.jsx(ve,{size:"sm",onClick:()=>{v(e.name,g.modified),C(e.name,!0)},children:"Apply Changes"})]})]}),t.jsx(Zt,{height:"calc(100% - 32px)",original:g.original,modified:g.modified,language:"json",theme:Ee(I),options:{readOnly:!0,renderSideBySide:!0,originalEditable:!1,automaticLayout:!0,minimap:{enabled:!1}},beforeMount:ne})]}):t.jsx(Dt,{height:"100%",language:"json",defaultPath:bs(e.name),value:e.text,theme:Ee(I),onChange:R,beforeMount:ne,onMount:D,onValidate:F,options:{readOnly:s,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(Et,{errors:l,onClick:()=>{p(!0),y(!1)}})}),h&&l.length>0&&t.jsx(Rt,{errors:l,isMinimized:m,onToggleMinimize:()=>y(!m),onErrorClick:w,onClose:()=>{p(!1),j.current=!0},className:"z-40"})]})}const Cs=Y.memo(ys),et=Zn,tt=es,Oe=u.forwardRef(({className:e,align:s="start",sideOffset:n=4,...r},o)=>t.jsx(ts,{children:t.jsx(Ht,{ref:o,align:s,sideOffset:n,className:B("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})}));Oe.displayName=Ht.displayName;function Ut(e){const s=e.match(/^#?([0-9A-Fa-f]{6})$/);if(!s)return null;const n=parseInt(s[1],16);return{r:n>>16&255,g:n>>8&255,b:n&255}}function js({r:e,g:s,b:n}){const r=o=>Math.max(0,Math.min(255,Math.round(o))).toString(16).padStart(2,"0").toUpperCase();return`#${r(e)}${r(s)}${r(n)}`}function ws({r:e,g:s,b:n}){const r=e/255,o=s/255,i=n/255,a=Math.max(r,o,i),l=Math.min(r,o,i),c=a-l;let h=0;return c!==0&&(a===r?h=(o-i)/c%6:a===o?h=(i-r)/c+2:h=(r-o)/c+4,h*=60,h<0&&(h+=360)),{h,s:a===0?0:c/a,v:a}}function vs({h:e,s,v:n}){const r=(e%360+360)%360,o=n*s,i=o*(1-Math.abs(r/60%2-1)),a=n-o,[l,c,h]=r<60?[o,i,0]:r<120?[i,o,0]:r<180?[0,o,i]:r<240?[0,i,o]:r<300?[i,0,o]:[o,0,i];return{r:(l+a)*255,g:(c+a)*255,b:(h+a)*255}}function bt(e){const s=Ut(e);return s?ws(s):null}function Ne(e){return js(vs(e))}function Ns(e){const s=Ut(e);return s?(s.r*299+s.g*587+s.b*114)/1e3>140?"#000000":"#FFFFFF":"#000000"}const Ss=/^[a-zA-Z][a-zA-Z0-9]*$/,Re="#D4D4D8";function ks(e){const s=u.useRef(null),n=u.useRef(null),r=u.useRef(e);r.current=e;const o=u.useCallback(()=>{n.current=null;const l=s.current;s.current=null,l!==null&&r.current(l)},[]),i=u.useCallback(l=>{s.current=l,n.current===null&&(n.current=requestAnimationFrame(o))},[o]),a=u.useCallback(()=>{n.current!==null&&(cancelAnimationFrame(n.current),o())},[o]);return u.useEffect(()=>()=>{n.current!==null&&cancelAnimationFrame(n.current)},[]),{schedule:i,finish:a}}function qt(e,s){const n=u.useRef(null),r=u.useCallback(l=>{var m;const c=(m=n.current)==null?void 0:m.getBoundingClientRect();if(!c||c.width===0||c.height===0)return;const h=(l.clientX-c.left)/c.width,p=(l.clientY-c.top)/c.height;e(Math.min(1,Math.max(0,h)),Math.min(1,Math.max(0,p)))},[e]),o=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]),a=u.useCallback(l=>{l.currentTarget.hasPointerCapture(l.pointerId)&&l.currentTarget.releasePointerCapture(l.pointerId),s()},[s]);return{ref:n,onPointerDown:o,onPointerMove:i,onPointerUp:a}}function Es({hsv:e,onChange:s,onEnd:n}){const r=u.useCallback((a,l)=>s({...e,s:a,v:1-l}),[e,s]),o=qt(r,n),i=u.useCallback(a=>{const l=a.shiftKey?.1:.02,h={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)}}[a.key];h&&(a.preventDefault(),s({...e,...h}),n())},[e,s,n]);return t.jsxs("div",{ref:o.ref,role:"application","aria-label":"Saturation and brightness",tabIndex:0,onPointerDown:o.onPointerDown,onPointerMove:o.onPointerMove,onPointerUp:o.onPointerUp,onKeyDown:i,className:B("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:Ne({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:Ne(e)}})]})}const Rs="linear-gradient(to right,#FF0000,#FFFF00,#00FF00,#00FFFF,#0000FF,#FF00FF,#FF0000)";function Ts({hsv:e,onChange:s,onEnd:n}){const r=u.useCallback(i=>s({...e,h:i*360}),[e,s]),o=qt(r,n);return t.jsx("div",{ref:o.ref,role:"slider","aria-label":"Hue","aria-valuemin":0,"aria-valuemax":360,"aria-valuenow":Math.round(e.h),tabIndex:0,onPointerDown:o.onPointerDown,onPointerMove:o.onPointerMove,onPointerUp:o.onPointerUp,onKeyDown:i=>{const a=i.key==="ArrowLeft"?-1:i.key==="ArrowRight"?1:0;a&&(i.preventDefault(),s({...e,h:(e.h+a*(i.shiftKey?10:2)+360)%360}),n())},className:B("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:Rs},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:Ne({h:e.h,s:1,v:1})}})})}function Ms({tokens:e,active:s,onPick:n}){return t.jsx("div",{className:"flex flex-wrap gap-1",children:e.map(r=>{const o=r.key===s;return t.jsxs(Ce,{children:[t.jsx(je,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>n(r.key),"aria-label":`Use token ${r.key}`,"aria-pressed":o,className:B("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",o?"ring-1 ring-ring ring-offset-1 ring-offset-popover":"border-border/70"),style:{backgroundColor:r.hex},children:o&&t.jsx(Ze,{className:"size-3",style:{color:Ns(r.hex)},"aria-hidden":!0})})}),t.jsx(we,{side:"bottom",children:t.jsxs("p",{className:"font-mono text-xs",children:[r.key," ",r.hex]})})]},r.key)})})}function nt({id:e,label:s,value:n,resolved:r,onCommit:o,allowReference:i=!0,tokens:a,className:l}){const[c,h]=u.useState(!1),p=u.useCallback(g=>{const C=g.trim();if(C===""){o(null);return}const v=Xe(C);if(/^#[0-9A-F]{6}$/.test(v)){o(v);return}i&&Ss.test(C)&&o(C)},[i,o]),{props:m}=It(n??"",p),y=r??Re,j=n&&!n.startsWith("#")?n:null;return t.jsxs("div",{className:B("flex min-w-0 items-center gap-1.5",l),children:[t.jsxs(et,{open:c,onOpenChange:h,children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button","aria-label":`${s} picker`,className:B("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:y}})}),t.jsx(Oe,{className:"w-64",children:t.jsx(Ds,{label:s,value:n,resolved:r,tokens:i?a:void 0,onCommit:o,onDone:()=>h(!1)})})]}),t.jsx(Ae,{id:e,type:"text","aria-label":s,autoComplete:"off",spellCheck:!1,placeholder:"#RRGGBB",title:j&&r?`${j} → ${r}`:void 0,className:B(Ye,"w-full min-w-0 font-mono",j?"lowercase":"uppercase"),...m})]})}function Ds({label:e,value:s,resolved:n,tokens:r,onCommit:o,onDone:i}){const[a,l]=u.useState(()=>bt(n??Re)??{h:0,s:0,v:.8}),c=u.useRef(n);if(n!==c.current){c.current=n;const C=bt(n??Re);C&&l(C)}const h=u.useCallback(C=>o(C),[o]),{schedule:p,finish:m}=ks(h),y=u.useCallback(C=>{l(C);const v=Ne(C);c.current=v,p(v)},[p]),j=Ne(a),g=typeof window<"u"&&"EyeDropper"in window?async()=>{try{const C=window.EyeDropper,v=await new C().open(),A=Xe(v.sRGBHex);/^#[0-9A-F]{6}$/.test(A)&&o(A)}catch{}}:null;return t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx(Es,{hsv:a,onChange:y,onEnd:m}),t.jsx(Ts,{hsv:a,onChange:y,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:n??Re}}),t.jsx(Ps,{hex:j,onCommit:o,label:e}),g&&t.jsxs(Ce,{children:[t.jsx(je,{asChild:!0,children:t.jsx("button",{type:"button",onClick:g,"aria-label":"Pick a colour from the screen",className:B("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(ns,{className:"size-3.5","aria-hidden":!0})})}),t.jsx(we,{side:"bottom",children:t.jsx("p",{children:"Pick from the screen"})})]}),t.jsxs(Ce,{children:[t.jsx(je,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{o(null),i()},"aria-label":`Clear ${e}`,disabled:s===void 0,className:B("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(ss,{className:"size-3.5","aria-hidden":!0})})}),t.jsx(we,{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(Ms,{tokens:r,active:s&&!s.startsWith("#")?s:null,onPick:C=>o(C)}),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 Ps({hex:e,label:s,onCommit:n}){const r=u.useCallback(i=>{const a=Xe(i);/^#[0-9A-F]{6}$/.test(a)&&n(a)},[n]),{props:o}=It(e,r);return t.jsx(Ae,{type:"text","aria-label":`${s} hex`,autoComplete:"off",spellCheck:!1,className:B(Ye,"h-7 min-w-0 flex-1 bg-transparent font-mono uppercase"),...o})}function st(e){const s=JSON.stringify(e.colors??null);return u.useMemo(()=>{const n=JSON.parse(s);return n?Ls({colors:n}):[]},[s])}function Ls(e){const s=e.colors;if(!s||typeof s!="object")return[];const n=[];for(const[r,o]of Object.entries(s)){const i=fe(e,o);i&&n.push({key:r,hex:i})}return n}const Je=Rn(te),As=Array.from(new Set(Je.map(e=>e.group)));function Is(e,s){const n=e.colors,r=n==null?void 0:n[s.key],o=typeof r=="string"?r:void 0,i=fe(e,o),a=o!==void 0&&!Tn(o)&&i?o:null;let l=null;return o===void 0&&r!==void 0?l="Must be a string":o===void 0&&s.required?l="Required":o!==void 0&&!i&&(l=/^[a-zA-Z][a-zA-Z0-9]*$/.test(o)?`No token named "${o}"`:"Not a hex colour"),{raw:o,resolved:i,reference:a,error:l}}const Os=Y.memo(function({token:s,raw:n,resolved:r,reference:o,error:i,tokens:a}){const{set:l,remove:c}=ce(),h=u.useCallback(y=>{y===null?c(["colors",s.key]):l(["colors",s.key],y)},[c,l,s.key]),p=u.useCallback(()=>c(["colors",s.key]),[c,s.key]),m=`theme-color-${s.key}`;return t.jsxs("div",{className:"flex min-h-8 items-center gap-2",children:[t.jsx(nt,{id:m,label:s.label,value:n,resolved:r,onCommit:h,tokens:a,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:s.label}),t.jsx("code",{className:"truncate text-[10px] text-muted-foreground",children:s.key}),s.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:B(ae,"truncate"),children:i?t.jsx("span",{className:"text-destructive",children:i}):o?t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(rs,{className:"size-3","aria-hidden":!0}),t.jsx("code",{children:o}),t.jsx("span",{children:r})]}):s.hint})]}),n!==void 0&&!s.required?t.jsx(_t,{label:`Clear ${s.label}`,onClick:p}):t.jsx("span",{className:"size-6 shrink-0","aria-hidden":!0})]})});function _s({theme:e}){const s=u.useMemo(()=>Je.map(i=>({token:i,...Is(e,i)})),[e]),n=u.useMemo(()=>{const i=e.colors,a=fe(e,i==null?void 0:i.background),l=fe(e,i==null?void 0:i.text),c=fe(e,i==null?void 0:i.primary);return{text:a&&l?ut(l,a):null,primary:a&&c?ut(c,a):null}},[e]),r=st(e),o=s.filter(i=>i.raw!==void 0).length;return t.jsxs(he,{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.",actions:t.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[o,"/",Je.length]}),children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1",children:[t.jsx(dt,{label:"Text on background",ratio:n.text}),t.jsx(dt,{label:"Primary on background",ratio:n.primary})]}),As.map(i=>t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx(Ot,{children:i}),s.filter(a=>a.token.group===i).map(a=>t.jsx(Os,{token:a.token,raw:a.raw,resolved:a.resolved,reference:a.reference,error:a.error,tokens:r},a.token.key))]},i))]})}const Fe=40;function zs(e){return[...e.safe.map(s=>({family:s,tag:"safe",safe:!0})),...e.google.map(s=>({family:s.family,tag:s.category,safe:!1}))]}function Fs(e,s){const n=e.toLowerCase();if(n===s)return 0;if(n.startsWith(s))return 1;const r=n.indexOf(s);return r===-1?-1:2+r}function Vs(e,s,n){const r=s.trim().toLowerCase();if(!r){if(!n)return e.slice(0,Fe);const i=e.find(l=>l.family===n),a=e.filter(l=>l.family!==n);return[i??{family:n,tag:"current",safe:!1},...a].slice(0,Fe)}const o=[];for(const i of e){const a=Fs(i.family,r);a!==-1&&o.push({option:i,rank:a})}return o.sort((i,a)=>i.rank-a.rank||Number(a.option.safe)-Number(i.option.safe)),o.slice(0,Fe).map(i=>i.option)}function rt({id:e,label:s,value:n,onCommit:r,pickerPath:o,className:i}){const[a,l]=u.useState(!1),[c,h]=u.useState(""),[p,m]=u.useState(0),y=u.useRef(null),j=Mn(),g=u.useMemo(()=>zs(j),[j]),C=u.useMemo(()=>Vs(g,c,n),[g,c,n]),v=c.trim(),A=C.some(R=>R.family.toLowerCase()===v.toLowerCase()),L=v&&!A?v:null,U=L?[L,...C.map(R=>R.family)]:C.map(R=>R.family),I=u.useCallback(R=>{r(R),l(!1),h("")},[r]),ne=u.useCallback(()=>{l(!1),Xt.getState().openFor({jsonPath:o,currentValue:n})},[o,n]),D=u.useCallback(R=>{if(R.key==="ArrowDown"||R.key==="ArrowUp")R.preventDefault(),m(F=>{var x,S;const w=F<0?R.key==="ArrowDown"?0:U.length-1:F+(R.key==="ArrowDown"?1:-1),d=U.length-1,b=w<0?d:w>d?0:w;return(S=(x=y.current)==null?void 0:x.querySelector(`[data-row="${b}"]`))==null||S.scrollIntoView({block:"nearest"}),b});else if(R.key==="Enter"){R.preventDefault();const F=U[p];F&&I(F)}else R.key==="Escape"&&l(!1)},[p,I,U]);return t.jsx("div",{className:B("flex min-w-0 items-center gap-1",i),children:t.jsxs(et,{open:a,onOpenChange:R=>{l(R),R&&(h(""),m(n?0:-1))},children:[t.jsx(tt,{asChild:!0,children:t.jsxs("button",{id:e,type:"button",role:"combobox","aria-expanded":a,"aria-label":s,className:B("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(os,{className:"size-3 shrink-0 opacity-50","aria-hidden":!0}),t.jsx("span",{className:B("min-w-0 flex-1 truncate text-left",!n&&"text-muted-foreground"),style:n?{fontFamily:`"${n.replace(/"/g,"")}", system-ui`}:void 0,children:n||"Inherit"}),t.jsx(as,{className:"size-3 shrink-0 opacity-50","aria-hidden":!0})]})}),t.jsxs(Oe,{className:"w-72 p-0",onKeyDown:D,children:[t.jsxs("div",{className:"flex items-center gap-1.5 border-b px-2",children:[t.jsx(is,{className:"size-3.5 shrink-0 opacity-50","aria-hidden":!0}),t.jsx(Ae,{autoFocus:!0,value:c,onChange:R=>{h(R.target.value),m(0)},placeholder:"Search fonts…","aria-label":`Search fonts for ${s}`,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:y,role:"listbox","aria-label":`${s} options`,className:"max-h-64 overflow-y-auto p-1",children:[L&&t.jsx(yt,{index:0,active:p===0,family:L,tag:"use as typed",selected:n===L,onPick:I,onHover:m}),C.map((R,F)=>{const w=L?F+1:F;return t.jsx(yt,{index:w,active:p===w,family:R.family,tag:R.tag,selected:n===R.family,onPick:I,onHover:m},`${R.safe?"s":"g"}:${R.family}`)}),U.length===0&&t.jsx("p",{className:B(ae,"px-2 py-3 text-center"),children:j.safe.length+j.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(me,{onClick:ne,children:"Browse all fonts…"}),n&&t.jsx(me,{onClick:()=>{r(null),l(!1)},children:"Clear"})]})]})]})})}const yt=Y.memo(function({index:s,active:n,family:r,tag:o,selected:i,onPick:a,onHover:l}){return t.jsxs("button",{type:"button",role:"option","aria-selected":i,"data-row":s,onMouseMove:()=>l(s),onClick:()=>a(r),className:B("flex h-7 w-full cursor-pointer items-center gap-2 rounded-sm px-2 text-left text-xs",n&&"bg-accent text-accent-foreground"),children:[t.jsx(Ze,{className:B("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:o})]})});function We(e){return typeof e=="string"?e:void 0}function Kt(e){return typeof e=="number"?e:void 0}const $s=Y.memo(function({role:s,family:n,size:r}){const{set:o,remove:i}=ce(),a=u.useCallback(p=>p===null?i(["fonts",s,"family"]):o(["fonts",s,"family"],p),[i,s,o]),l=u.useCallback(p=>p===null?i(["fonts",s,"size"]):o(["fonts",s,"size"],p),[i,s,o]),c=`theme-font-${s}-family`,h=`theme-font-${s}-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:s}),t.jsx("span",{className:ae,children:Ft[s]})]}),t.jsx("label",{htmlFor:c,className:Le,children:"Family"}),t.jsx("label",{htmlFor:h,className:Le,children:"Size"}),t.jsx(rt,{id:c,label:`${s} family`,value:n,onCommit:a,pickerPath:["fonts",s,"family"]}),t.jsx(Ie,{id:h,"aria-label":`${s} size`,value:r,onCommit:l,unit:"pt",min:8,max:120,step:.5})]})}),Hs=Y.memo(function({role:s,family:n}){const{set:r,remove:o}=ce(),i=u.useCallback(l=>l===null?o(["fonts",s]):r(["fonts",s],l),[o,s,r]),a=`theme-font-${s}`;return t.jsxs("div",{className:"grid grid-cols-[6rem_minmax(0,1fr)] items-center gap-2",children:[t.jsxs("label",{htmlFor:a,className:"flex flex-col",children:[t.jsx("span",{className:"text-sm capitalize",children:s}),t.jsx("span",{className:ae,children:Ft[s]})]}),t.jsx(rt,{id:a,label:`${s} family`,value:n,onCommit:i,pickerPath:["fonts",s]})]})});function Gs({theme:e}){const{set:s,remove:n}=ce(),r=Kt(ie(e,["defaults","fontSize"])),o=We(ie(e,["defaults","fontColor"])),i=u.useMemo(()=>fe(e,o),[e,o]),a=st(e),l=u.useCallback(h=>h===null?n(["defaults","fontSize"]):s(["defaults","fontSize"],h),[n,s]),c=u.useCallback(h=>h===null?n(["defaults","fontColor"]):s(["defaults","fontColor"],h),[n,s]);return t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Ot,{children:"Defaults"}),t.jsx("p",{className:ae,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(Ie,{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(nt,{id:"theme-defaults-color",label:"Default font colour",value:o,resolved:i,onCommit:c,allowReference:!1,tokens:a,className:"max-w-[12rem]"})]})]})}function Bs({theme:e}){return te==="docx"?t.jsx(he,{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.",children:t.jsx("div",{className:"grid grid-cols-1 gap-2 @[34rem]:grid-cols-2",children:zt.map(s=>{const n=ie(e,["fonts",s]),r=n&&typeof n=="object"?n:void 0;return t.jsx($s,{role:s,family:We(r==null?void 0:r.family),size:Kt(r==null?void 0:r.size)},s)})})}):t.jsxs(he,{title:"Typography",hint:"Two families; every style uses one or names its own face.",children:[t.jsx("div",{className:"flex flex-col gap-2",children:Dn.map(s=>t.jsx(Hs,{role:s,family:We(ie(e,["fonts",s]))},s))}),t.jsx(Gs,{theme:e})]})}const Ve="__custom__",Us=[{value:"in",label:"in"},{value:"cm",label:"cm"},{value:"pt",label:"pt"},{value:"twips",label:"twips"}],qs={in:.05,cm:.1,pt:1,twips:10},Ct=Object.fromEntries(Vt.map(e=>[e,["page","margins",e]])),jt=["page","size","width"],wt=["page","size","height"];function $e(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}const He=Y.memo(function({id:s,label:n,path:r,value:o,unit:i}){const{set:a,remove:l}=ce(),c=u.useCallback(h=>h===null?l(r):a(r,Pn(h,i)),[r,l,a,i]);return t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("label",{htmlFor:s,className:Le,children:n}),t.jsx(Ie,{id:s,value:o===void 0?void 0:Ln(o,i),onCommit:c,unit:i,min:0,step:qs[i]})]})});function Ks({theme:e}){const{set:s}=ce(),[n,r]=u.useState("in"),o=ie(e,["page","size"]),i=!!o&&typeof o=="object",a=typeof o=="string"&&mt.includes(o)?o:i?Ve:"",l=u.useCallback(c=>{c===Ve?s(["page","size"],{width:11906,height:16838}):s(["page","size"],c)},[s]);return t.jsxs(he,{title:"Page",hint:"Paper and margins. Stored in twips (1/1440 in); shown in the unit you pick here.",actions:t.jsxs(Te,{value:n,onValueChange:c=>r(c),children:[t.jsx(Me,{"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(De,{})}),t.jsx(Pe,{children:Us.map(c=>t.jsx(ye,{value:c.value,className:"text-xs",children:c.label},c.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(Te,{value:a,onValueChange:l,children:[t.jsx(Me,{id:"theme-page-size",className:Ke,children:t.jsx(De,{placeholder:"Choose a size"})}),t.jsxs(Pe,{children:[mt.map(c=>t.jsx(ye,{value:c,className:"text-xs",children:c},c)),t.jsx(ye,{value:Ve,className:"text-xs",children:"Custom"})]})]})]}),i&&t.jsxs("div",{className:"grid grid-cols-2 gap-2 @[34rem]:max-w-[24rem]",children:[t.jsx(He,{id:"theme-page-width",label:"Width",path:jt,value:$e(ie(e,jt)),unit:n}),t.jsx(He,{id:"theme-page-height",label:"Height",path:wt,value:$e(ie(e,wt)),unit:n})]}),t.jsx("div",{className:"grid grid-cols-2 gap-2 @[30rem]:grid-cols-4",children:Vt.map(c=>t.jsx(He,{id:`theme-margin-${c}`,label:c.charAt(0).toUpperCase()+c.slice(1),path:Ct[c],value:$e(ie(e,Ct[c])),unit:n},c))})]})}const vt=On(te),ot=In(te),Js=ot.filter(e=>!e.advanced),Ge=ot.filter(e=>e.advanced),Ws=2,Qs=[{value:"unset",label:"Unset"},{value:"off",label:"Off"},{value:"on",label:"On"}];function Se(e){return e.path.join(".")}function Xs(e){const s=[],n=r=>{typeof r=="string"&&r&&s.push(r)};if(te==="docx"?(n(e.font),typeof e.size=="number"&&s.push(`${e.size}pt`)):(n(e.fontFace),typeof e.fontSize=="number"&&s.push(`${e.fontSize}pt`)),e.bold===!0&&s.push("bold"),typeof e.fontWeight=="number"&&s.push(`w${e.fontWeight}`),e.italic===!0&&s.push("italic"),e.underline===!0&&s.push("underline"),n(te==="docx"?e.color:e.fontColor),n(te==="docx"?e.alignment:e.align),s.length===0){const r=Object.keys(e);return r.length===0?"Defined, nothing set":r.join(" · ")}return s.join(" · ")}function Ys({styleName:e,field:s,value:n,tokens:r,resolved:o,onCommit:i}){return t.jsx(nt,{id:`theme-style-${e}-${Se(s)}`,label:s.label,value:typeof n=="string"?n:void 0,resolved:o,onCommit:i,tokens:r,className:"min-w-0"})}const Zs=Y.memo(function(s){const{styleName:n,field:r,value:o}=s,{set:i,remove:a}=ce(),l=u.useMemo(()=>["styles",n,...r.path],[r.path,n]),c=u.useCallback(()=>a(l,{keepDepth:Ws}),[l,a]),h=u.useCallback(g=>g===null?c():i(l,g),[c,l,i]),p=u.useCallback(g=>g===null?c():i(l,g),[c,l,i]),m=`theme-style-${n}-${Se(r)}`,y=o!==void 0;let j;switch(r.kind){case"text":j=t.jsx($t,{id:m,value:typeof o=="string"?o:void 0,onCommit:h});break;case"number":j=t.jsx(Ie,{id:m,value:typeof o=="number"?o:void 0,onCommit:p,unit:r.unit,min:r.min,max:r.max,step:r.step});break;case"boolean":j=t.jsx(zn,{label:r.label,value:o===void 0?"unset":o===!0?"on":"off",options:Qs,onChange:g=>g==="unset"?c():i(l,g==="on"),className:"h-7"});break;case"select":j=t.jsxs(Te,{value:typeof o=="string"?o:"",onValueChange:g=>i(l,g),children:[t.jsx(Me,{id:m,className:Ke,children:t.jsx(De,{placeholder:"Unset"})}),t.jsx(Pe,{children:(r.options??[]).map(g=>t.jsx(ye,{value:g,className:"text-xs",children:g},g))})]});break;case"fontRole":j=t.jsxs(Te,{value:typeof o=="string"?o:"",onValueChange:g=>i(l,g),children:[t.jsx(Me,{id:m,className:Ke,children:t.jsx(De,{placeholder:"Unset"})}),t.jsx(Pe,{children:zt.map(g=>t.jsx(ye,{value:g,className:"text-xs",children:g},g))})]});break;case"fontFamily":j=t.jsx(rt,{id:m,label:r.label,value:typeof o=="string"?o:void 0,onCommit:h,pickerPath:l});break;case"color":j=t.jsx(Ys,{...s,onCommit:h});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:B(Le,y&&"text-foreground"),title:r.hint,children:r.label}),y&&r.kind!=="boolean"&&t.jsx(_t,{label:`Clear ${r.label}`,onClick:c,className:"size-5"})]}),j,r.hint&&t.jsx("p",{className:ae,children:r.hint})]})}),er=Y.memo(function({name:s,custom:n,styleJson:r,tokensJson:o,resolvedJson:i}){const{set:a,remove:l}=ce(),[c,h]=u.useState(!1),[p,m]=u.useState(!1),y=u.useMemo(()=>r===void 0?void 0:JSON.parse(r),[r]),j=u.useMemo(()=>JSON.parse(o),[o]),g=u.useMemo(()=>JSON.parse(i),[i]),C=u.useCallback(()=>a(["styles",s],{}),[s,a]),v=u.useCallback(()=>l(["styles",s]),[s,l]),A=_n(s),L=y?Object.keys(y).length:0,U=I=>t.jsx(Zs,{styleName:s,field:I,value:y?ie(y,I.path):void 0,tokens:j,resolved:g[Se(I)]??null},Se(I));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:()=>h(I=>!I),"aria-expanded":c,className:B("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(pt,{"aria-hidden":!0,className:B("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}),n&&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:B(ae,"min-w-0 flex-1 truncate"),children:y?Xs(y):"Not defined — inherits defaults"})]}),n&&t.jsx("button",{type:"button",onClick:v,"aria-label":`Remove style ${s}`,title:"Remove style",className:B("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(ls,{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:y?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 @[30rem]:grid-cols-2",children:Js.map(U)}),Ge.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs(me,{onClick:()=>m(I=>!I),"aria-expanded":p,children:[t.jsx(pt,{"aria-hidden":!0,className:B("size-3 transition-transform duration-150 ease-out",p&&"rotate-90")}),"More"]}),t.jsxs("span",{className:ae,children:[Ge.length," more fields",L>0&&` · ${L} key${L===1?"":"s"} set`]})]}),p&&t.jsx("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 @[30rem]:grid-cols-2",children:Ge.map(U)})]})]}):t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:ae,children:"Not defined — inherits defaults."}),t.jsxs(me,{onClick:C,children:[t.jsx(Gt,{className:"size-3","aria-hidden":!0}),"Define"]})]})})]})});function tr({existing:e}){const{set:s}=ce(),[n,r]=u.useState(!1),[o,i]=u.useState(""),a=o.trim(),l=a?e.has(a)?"A style with this name exists":/\s/.test(a)?"No spaces — this is the style id a document names":null:null,c=()=>{!a||l||(s(["styles",a],{}),i(""),r(!1))};return n?t.jsxs("form",{className:"flex flex-wrap items-center gap-2",onSubmit:h=>{h.preventDefault(),c()},children:[t.jsx("label",{htmlFor:"theme-new-style",className:"text-xs",children:"New style"}),t.jsx(Ae,{id:"theme-new-style",type:"text",value:o,onChange:h=>i(h.target.value),placeholder:"e.g. callout",autoComplete:"off",spellCheck:!1,autoFocus:!0,className:B(Ye,"w-40"),onKeyDown:h=>{h.key==="Escape"&&r(!1)}}),t.jsx(me,{type:"submit",disabled:!a||!!l,children:"Add"}),t.jsx(me,{onClick:()=>r(!1),children:"Cancel"}),l&&t.jsx("span",{className:"text-[11px] text-destructive",children:l})]}):t.jsxs(me,{onClick:()=>r(!0),children:[t.jsx(Gt,{className:"size-3","aria-hidden":!0}),"Add custom style"]})}function nr({theme:e}){const s=st(e),n=u.useMemo(()=>JSON.stringify(s),[s]),r=u.useMemo(()=>An(e,te),[e]),o=u.useMemo(()=>{const l=e.styles,c=l&&typeof l=="object"&&!Array.isArray(l)?l:{},h=ot.filter(m=>m.kind==="color"),p=(m,y)=>{const j=c[m],g=!!j&&typeof j=="object",C={};for(const v of h)C[Se(v)]=g?fe(e,ie(j,v.path)):null;return{name:m,custom:y,styleJson:g?JSON.stringify(j):void 0,tokensJson:n,resolvedJson:JSON.stringify(C)}};return[...vt.map(m=>p(m,!1)),...r.map(m=>p(m,!0))]},[e,n,r]),i=u.useMemo(()=>new Set([...vt,...r]),[r]),a=o.filter(l=>l.styleJson!==void 0).length;return t.jsxs(he,{title:"Styles",hint:te==="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.",actions:t.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[a,"/",o.length]}),children:[t.jsx("div",{className:"flex flex-col gap-1",children:o.map(l=>t.jsx(er,{...l},l.name))}),te==="docx"&&t.jsx(tr,{existing:i})]})}function Jt({docName:e,text:s,onChange:n,onOpenJson:r,usedBy:o=[],nameClash:i=[]}){const a=u.useMemo(()=>Fn(s),[s]),l=u.useRef({theme:null,onChange:n});l.current.theme=a.ok?a.theme:null,l.current.onChange=n;const c=u.useCallback(j=>{const g=l.current.theme;if(!g)return;const C=j(g);C!==g&&(l.current.theme=C,l.current.onChange(Vn(C)))},[]),h=u.useCallback((j,g)=>c(C=>{const v=j[0],A=typeof v=="string"?C[v]:void 0,L=j.length>1&&(!A||typeof A!="object")?$n(C,te):C;return Hn(L,j,g)}),[c]),p=u.useCallback((j,g)=>c(C=>{let v=ft(C,j);if(!g)return v;let A=j.slice(0,-1);for(;A.length>g.keepDepth;){const L=ie(v,A);if(!(!!L&&typeof L=="object"&&!Array.isArray(L)&&Object.keys(L).length===0))break;v=ft(v,A),A=A.slice(0,-1)}return v}),[c]),m=u.useMemo(()=>({set:h,remove:p}),[h,p]);if(!a.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:a.error})]}),t.jsx("p",{className:ae,children:"The form stays read-only until the file parses, so nothing you typed in JSON is overwritten."}),t.jsxs(ve,{variant:"outline",size:"sm",onClick:r,children:[t.jsx(Bt,{"aria-hidden":!0}),"Open JSON"]})]});const y=a.theme;return t.jsx(Gn,{value:m,children:t.jsx(fn,{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.jsx(or,{theme:y,usedBy:o,nameClash:i}),t.jsx(_s,{theme:y}),t.jsx(Bs,{theme:y}),te==="docx"&&t.jsx(Ks,{theme:y}),t.jsx(nr,{theme:y}),t.jsx(ar,{theme:y,onOpenJson:r})]},e)})})}const sr={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"'}]};function rr({fieldKey:e,label:s,hint:n,value:r}){const{set:o,remove:i}=ce(),a=u.useCallback(c=>c===null?i([e]):o([e],c),[e,i,o]),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:[s,n&&t.jsx("span",{className:ae,children:n})]}),t.jsx($t,{id:l,value:r,onCommit:a,className:e==="name"?"font-mono":void 0})]})}function or({theme:e,usedBy:s,nameClash:n}){const r=sr[te];return t.jsxs(he,{title:"Identity",hint:"A document picks this theme by its name; the rest is what the library shows.",children:[t.jsx("div",{className:"grid grid-cols-[7rem_minmax(0,1fr)] items-start gap-x-3 gap-y-2",children:r.map(o=>{const i=e[o.key];return t.jsx(rr,{fieldKey:o.key,label:o.label,hint:o.hint,value:typeof i=="string"?i:void 0},o.key)})}),t.jsx("p",{className:B(ae,"mt-2"),children:s.length>0?t.jsxs(t.Fragment,{children:["Used by"," ",s.map((o,i)=>t.jsxs(Y.Fragment,{children:[i>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."}),n.length>0&&t.jsxs("p",{className:"mt-1 text-xs text-warning",children:[n.join(", ")," also declare",n.length===1?"s":""," ","this name; only one of them can win when a document asks for it."]})]})}function ar({theme:e,onOpenJson:s}){const n=u.useMemo(()=>Bn(e,te),[e]);return t.jsx(he,{title:"Advanced",hint:"Keys the form has no field for. They travel untouched through every edit here.",actions:n.length>0?t.jsxs(me,{onClick:s,children:[t.jsx(Bt,{className:"size-3","aria-hidden":!0}),"Edit in JSON"]}):void 0,children:n.length===0?t.jsx("p",{className:ae,children:"Nothing beyond the fields above."}):t.jsx("ul",{className:"flex flex-col gap-1",children:n.map(r=>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:r.key}),t.jsx("span",{className:"truncate text-muted-foreground",children:r.summary})]},r.key))})})}Y.memo(Jt);function ir({document:e,onChange:s}){const n=xe(m=>m.themeEditorView),r=xe(m=>m.setSettings),o=le(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]),a=i?Qe(i):null,l=le(m=>{if(!a)return pe;const y=m.documents.filter(j=>(m.documentTypes[j.name]??"application/json+report")==="application/json+report"&&lr(j.text)===a).map(j=>j.name);return y.length===0?pe:y.join(`
|
|
9
|
+
`)}),c=le(m=>{if(!a)return pe;const y=m.documents.filter(j=>j.name!==e.name&&m.documentTypes[j.name]==="application/json+theme"&&cr(j.text)===a).map(j=>j.name);return y.length===0?pe:y.join(`
|
|
10
|
+
`)}),{view:h}=hn({preferred:n,parses:i!==null,hasPendingDiff:o}),p=u.useCallback(()=>r({themeEditorView:"json"}),[r]);return t.jsx("div",{className:"h-full",children:h==="visual"?t.jsx(Jt,{docName:e.name,text:e.text,onChange:s,onOpenJson:p,usedBy:l===pe?Nt:l.split(`
|
|
11
|
+
`),nameClash:c===pe?Nt:c.split(`
|
|
12
|
+
`)}):t.jsx(Cs,{document:e,onChange:s})})}const pe="",Nt=[];function lr(e){var s,n;try{const r=(n=(s=JSON.parse(e))==null?void 0:s.props)==null?void 0:n.theme;return typeof r=="string"?r:null}catch{return null}}function cr(e){try{return Qe(JSON.parse(e))}catch{return null}}const ur=Y.memo(ir);function dr(){const[e,s]=u.useState(nn);return u.useEffect(()=>sn(()=>s(!0)),[]),e}function mr({docName:e,text:s}){const n=ge(D=>D.records[e]),r=ge(D=>D.setEnabled),o=ge(D=>D.setAllowNetwork),i=ge(D=>D.setNetworkOrigins),{toast:a}=Yt(),[l,c]=u.useState(null),h=dr(),p=n==null?void 0:n.metadata,m=(n==null?void 0:n.status)??"idle",y=((n==null?void 0:n.diagnostics)??[]).filter(D=>D.severity==="error").length,j=(p==null?void 0:p.name)??e.replace(new RegExp(`${en}$`,"i"),""),g=(p==null?void 0:p.examples)??[],C=u.useCallback(()=>{window.dispatchEvent(new CustomEvent(Be,{detail:{docName:e}}))},[e]),v=u.useCallback(D=>{r(e,D),C()},[C,e,r]),A=u.useCallback(()=>{tn.dispose(e),ge.getState().upsert(e,{status:"idle"}),Ue.run(e)},[e]),L=u.useCallback(D=>{o(e,D),A()},[e,A,o]),U=u.useCallback(D=>{i(e,D),A()},[e,A,i]),I=u.useCallback(async D=>{const R=g[D];if(!R||!p)return;const F=JSON.stringify({name:p.name,props:R.props},null,2);try{await navigator.clipboard.writeText(F),c(D),setTimeout(()=>c(null),1500)}catch{a({title:"Clipboard unavailable",description:"Could not copy the example to the clipboard.",variant:"destructive"})}},[g,p,a]),ne=(()=>{if(!h&&m!=="ready"&&m!=="error")return t.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[t.jsx(ct,{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(ct,{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"}),y>0?`${y} error${y===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(cs,{className:"size-3.5 shrink-0 text-sidebar-foreground/60"}),t.jsx("span",{className:"truncate text-[13px] font-medium",children:j}),(p==null?void 0:p.latest)&&t.jsxs(qe,{variant:"outline",className:"h-4 px-1.5 font-mono text-[10px]",children:["v",p.latest]}),t.jsx("span",{className:"mx-1 h-4 w-px bg-border/60"}),ne,t.jsxs(Ce,{children:[t.jsx(je,{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(us,{className:"size-3.5 text-muted-foreground"})})}),t.jsxs(we,{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(pn,{children:[t.jsx(gn,{asChild:!0,children:t.jsxs(ve,{variant:"ghost",size:"sm",className:"h-7 gap-1.5 px-2 text-xs",disabled:g.length===0,title:g.length===0?"Add a JSDoc @example with a JSON block to list usage examples here":void 0,children:[t.jsx(ds,{className:"size-3.5"}),"Examples",g.length>0&&t.jsx(qe,{variant:"secondary",className:"h-4 px-1 text-[10px]",children:g.length})]})}),t.jsxs(xn,{align:"end",className:"w-64",children:[t.jsx(bn,{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Copy as component JSON"}),t.jsx(yn,{}),g.map((D,R)=>t.jsxs(Cn,{onClick:F=>{F.preventDefault(),I(R)},className:"gap-2",children:[l===R?t.jsx(Ze,{className:"size-3.5 text-success"}):t.jsx(ms,{className:"size-3.5 text-muted-foreground"}),t.jsx("span",{className:"truncate",children:D.title??`Example ${R+1}`})]},R))]})]}),t.jsxs("label",{htmlFor:`plugin-enabled-${e}`,className:B("flex h-7 cursor-pointer items-center gap-1.5 rounded-sm px-1.5 text-xs",n!=null&&n.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(At,{id:`plugin-enabled-${e}`,checked:(n==null?void 0:n.enabled)??!0,onCheckedChange:v,"aria-label":"Enable plugin"})]}),t.jsx(hr,{docName:e,allowNetwork:(n==null?void 0:n.allowNetwork)??!1,origins:(n==null?void 0:n.networkOrigins)??[],onToggle:L,onCommitOrigins:U}),t.jsxs(Ce,{children:[t.jsx(je,{asChild:!0,children:t.jsx(ve,{variant:"ghost",size:"icon",className:"size-7","aria-label":"Download plugin source",onClick:()=>jn(e,new Blob([s],{type:"text/typescript"})),children:t.jsx(fs,{className:"size-3.5"})})}),t.jsx(we,{children:t.jsxs("p",{children:["Download ",t.jsx("code",{children:e})," to use it on disk with the CLI"]})})]})]})}const fr=Y.memo(mr);function hr({docName:e,allowNetwork:s,origins:n,onToggle:r,onCommitOrigins:o}){const[i,a]=u.useState(!1),[l,c]=u.useState(()=>n.join(`
|
|
13
|
+
`));u.useEffect(()=>{i||c(n.join(`
|
|
14
|
+
`))},[i,n]);const h=rn(l),p=s&&n.length>0,m=s?n.length===0?"Network on, no hosts listed":`Network: ${n.join(", ")}`:"Network off";return t.jsxs(et,{open:i,onOpenChange:a,children:[t.jsx(tt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":m,title:m,className:B("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",p?"text-foreground":"text-muted-foreground"),children:[t.jsx(hs,{className:"size-3.5","aria-hidden":"true"}),t.jsx("span",{className:"hidden sm:inline",children:"Network"}),p&&t.jsx(qe,{variant:"outline",className:"h-4 px-1 font-mono text-[10px] tabular-nums",children:n.length}),s&&n.length===0&&t.jsx("span",{className:"text-[10px] text-amber-600 dark:text-amber-500",children:"no hosts"})]})}),t.jsxs(Oe,{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(At,{id:`plugin-network-${e}`,checked:s,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."]}),s&&t.jsxs(t.Fragment,{children:[t.jsx(wn,{value:l,onChange:y=>c(y.target.value),onBlur:()=>o(h.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."]}),h.errors.length>0&&t.jsx("ul",{className:"space-y-0.5 text-xs text-destructive",children:h.errors.map(y=>t.jsx("li",{children:y},y))}),h.errors.length===0&&h.origins.length===0&&t.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-500",children:"Nothing listed, so nothing is reachable."})]})]})]})}function pr({name:e,value:s,saveDocumentDebounceWait:n}){const r=u.useRef(null),{resolvedTheme:o}=Tt(),i=le(w=>w.saveDocument),a=le(w=>w.closeDocument),{registerEditor:l,unregisterEditor:c,setActiveEditor:h}=be(),p=ge(w=>{var d;return(d=w.records[e])==null?void 0:d.diagnostics}),m=u.useRef(null),[y,j]=u.useState(s),g=u.useRef(Lt(w=>{m.current=w,i(e,w)},n)),[C,v]=u.useState(!0),[A,L]=u.useState(!1),U=u.useRef(!1),I=u.useMemo(()=>(p??[]).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}:{}})),[p]);u.useEffect(()=>{I.length>0&&!U.current&&(v(!0),L(!1)),I.length===0&&(U.current=!1)},[I.length]);const ne=u.useCallback(w=>{Mt(w),on(w)},[]),D=u.useCallback(()=>{g.current.flush()},[]),R=u.useCallback((w,d)=>{r.current=w,l(e,w,d,void 0,void 0,D),h(e);const b=()=>{const x=w.getValue();g.current.cancel(),m.current=x,i(e,x)};w.addCommand(d.KeyMod.CtrlCmd|d.KeyCode.KeyS,b),w.addCommand(d.KeyMod.CtrlCmd|d.KeyCode.KeyW,()=>{b(),a(e)}),w.addCommand(d.KeyMod.Shift|d.KeyMod.Alt|d.KeyCode.KeyF,()=>{var x;(x=w.getAction("editor.action.formatDocument"))==null||x.run()})},[a,D,e,l,i,h]);u.useEffect(()=>{const w=g.current;return()=>{w.flush(),c(e)}},[e,c]),u.useEffect(()=>{var d;if(s===m.current)return;const w=(d=r.current)==null?void 0:d.getModel();w&&w.getValue()!==s&&w.setValue(s),j(s)},[s]);const F=u.useCallback(w=>{const d=r.current;!d||!w.startLineNumber||(d.setPosition({lineNumber:w.startLineNumber,column:w.startColumn??1}),d.revealLineInCenter(w.startLineNumber),d.focus())},[]);return t.jsxs("div",{className:"flex h-full flex-col",children:[t.jsx(fr,{docName:e,text:s}),t.jsxs("div",{className:"relative min-h-0 flex-1",children:[t.jsx(Dt,{height:"100%",defaultLanguage:"typescript",path:an(e),value:y,theme:Ee(o),beforeMount:ne,onMount:R,keepCurrentModel:!0,onChange:w=>{w!==void 0&&g.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(Et,{errors:I,onClick:()=>{v(!0),L(!1)}})}),C&&I.length>0&&t.jsx(Rt,{errors:I,isMinimized:A,onToggleMinimize:()=>L(w=>!w),onErrorClick:F,onClose:()=>{v(!1),U.current=!0},className:"z-40"})]})]})}const gr=Y.memo(pr);function xr({name:e,text:s,buildError:n,saveDocumentDebounceWait:r,documentType:o}){const{saveDocument:i}=le(p=>p),{updateTheme:a}=Pt(p=>p),l=Y.useMemo(()=>Lt(a,r),[a,r]);Y.useEffect(()=>()=>{l.flush()},[l]);const c=Y.useCallback(p=>{i(e,p),o==="application/json+theme"&&(console.log("TabContent: Theme document change detected, debouncing update",{documentName:e,debounceWait:r}),l(e,p))},[e,i,l,o,r]),h=Y.useMemo(()=>({name:e,type:"application/json",text:s,mtime:new Date,ctime:new Date,atime:new Date}),[e,s]);return t.jsx(vn,{value:e,className:"mt-0 h-full p-0",tabIndex:-1,children:o==="application/json+theme"?t.jsx(ur,{document:h,onChange:c}):o==="application/typescript+plugin"?t.jsx(gr,{name:e,value:s,saveDocumentDebounceWait:r}):t.jsx(Qt,{name:e,value:s,saveDocumentDebounceWait:r})})}const br=Y.memo(xr);function yr({openTabs:e,documents:s,buildErrors:n,saveDocumentDebounceWait:r}){const{documentTypes:o}=le(i=>i);return e.map(i=>s.find(a=>a.name===i)).filter(i=>i!==void 0).map(i=>{const a=o[i.name]||"application/json+report";return t.jsx(br,{name:i.name,text:i.text,buildError:n[i.name],saveDocumentDebounceWait:r,documentType:a},i.name)})}const Cr=Y.memo(yr);class jr extends Error{constructor(s,n,r){super(s),this.lastError=n,this.attempts=r,this.name="RetryError"}}async function wr(e,s={}){const{maxRetries:n=3,initialDelay:r=1e3,maxDelay:o=3e4,backoffFactor:i=2,onRetry:a,shouldRetry:l=()=>!0,signal:c}=s;let h;for(let p=0;p<=n;p++)try{if(c!=null&&c.aborted)throw new Error("Operation cancelled");return await e()}catch(m){if(h=m instanceof Error?m:new Error(String(m)),p===n)break;if(!l(h))throw h;const j=Math.min(r*Math.pow(i,p),o)*(.5+Math.random()*.5);a&&a(h,p+1),await new Promise(g=>{const C=setTimeout(g,j);c&&c.addEventListener("abort",()=>{clearTimeout(C),g(void 0)},{once:!0})})}throw new jr(`Failed after ${n+1} attempts`,h,n+1)}const St={networkErrors:e=>["NetworkError","Failed to fetch","ERR_NETWORK","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","fetch failed"].some(n=>e.message.includes(n)||e.name.includes(n)),httpStatusCodes:e=>s=>{var n;return(n=s.response)!=null&&n.status?e.includes(s.response.status):!1},temporaryErrors:e=>["EBUSY","EAGAIN","temporarily unavailable","too many requests","rate limit"].some(n=>e.message.toLowerCase().includes(n.toLowerCase())),combine:(...e)=>s=>e.some(n=>n(s))},vr="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.",Nr={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 Wt(e){return e?Un(e):[]}function kt(e,s){const n=e==null?void 0:e.styles;return!!n&&typeof n=="object"&&s in n}function Sr(e,s){const n=Wt(s),r=[];return r.push(kt(s,"title")?{name:"paragraph",props:{text:"Theme specimen",themeStyle:"title"}}:{name:"heading",props:{text:"Theme specimen",level:1}}),kt(s,"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:vr}},{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"}}),n.length>0&&r.push({name:"heading",props:{text:"Colours",level:2}},{name:"table",props:{columns:[{header:{content:"Token"},cells:n.map(o=>({content:o}))},{header:{content:"Swatch"},cells:n.map(o=>({content:" ",backgroundColor:o}))},{header:{content:"Role"},cells:n.map(o=>({content:Nr[o]??""}))}]}}),{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 kr(e,s){const n=Wt(s),r=(i,a,l,c,h,p)=>({name:"text",props:{text:i,style:a,x:l,y:c,w:h,h:p}}),o=[{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(n.length>0){const a=[];n.forEach((l,c)=>{const h=c%6,p=Math.floor(c/6),m=.5+h*1.5,y=1.3+p*1.6;a.push({name:"shape",props:{type:"rect",x:m,y,w:1.3,h:.9,fill:{color:l}}},r(l,"caption",m,y+.95,1.3,.4))}),o.push({name:"slide",props:{meta:{title:"Colours"}},children:[r("Colours","heading1",.5,.4,9,.8),...a]})}return o.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:o}}function Er(e){return`Sample · ${e}`}function Rr(e){return e.startsWith("Sample · ")}function Tr(e,s,n){return e==="docx"?Sr(s,n):kr(s,n)}function Mr(){const e=ln(f=>f.setOutput),s=u.useContext(cn),n=u.useContext(un),r=u.useContext(dn),o=xe(f=>f.saveDocumentDebounceWait),{openTabs:i,activeTab:a,setActiveTab:l,documents:c,buildErrors:h,setBuildError:p,documentTypes:m}=le(gt(f=>({openTabs:f.openTabs,activeTab:f.activeTab,setActiveTab:f.setActiveTab,documents:f.documents,buildErrors:f.buildErrors,setBuildError:f.setBuildError,documentTypes:f.documentTypes}))),{customThemes:y}=Pt(gt(f=>({customThemes:f.customThemes}))),{generatePresentation:j,cancelGeneration:g}=Nn(),C=xe(f=>f.qualityProfileIds),v=qn(C),A=xe(f=>f.qualityGate),L=xe(f=>{var k;return(k=f.qualityPolicies)==null?void 0:k[te]}),U=u.useMemo(()=>Kn(v,A,L),[v,A,L]),{analyze:I,cancel:ne}=Jn(),D=u.useRef(new Map),R=u.useRef(new Map),F=u.useRef(null),w=u.useRef(""),d=u.useRef(new Map),b=u.useCallback(()=>{w.current=`cancelled-${Date.now()}`;for(const f of R.current.values())clearTimeout(f);R.current.clear(),F.current&&(clearTimeout(F.current),F.current=null);for(const f of D.current.values())f.abort();D.current.clear(),g(),e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0})},[g,e]);u.useEffect(()=>{e({cancelGeneration:b})},[b,e]);const x=u.useCallback(f=>{const N=(d.current.get(f)||0)+1;return d.current.set(f,N),N},[]),S=u.useMemo(()=>{const f=Object.entries(y).map(([k,N])=>{let T=0;return N.lastModified&&(N.lastModified instanceof Date?T=N.lastModified.getTime():typeof N.lastModified=="string"&&(T=new Date(N.lastModified).getTime())),{key:k,name:N.name,content:N.content,valid:N.valid,lastModified:T}});return JSON.stringify(f)},[y]),E=u.useMemo(()=>{const f={};return Object.values(y).forEach(k=>{k.valid&&k.parsed&&(f[k.name]=k.parsed)}),f},[S]),M=u.useCallback(()=>{const f={},{customThemes:k}=r.getState();return Object.values(k).forEach(N=>{N.valid&&N.parsed&&(f[N.name]=N.parsed)}),f},[r]),P=u.useCallback(async(f,k,N)=>{if(!f||!j)return;const T=D.current.get(f.name);T&&(T.abort(),D.current.delete(f.name));const z=k?null:new AbortController,O=k||z.signal;z&&D.current.set(f.name,z);const ee=`${f.name}-${Date.now()}-${Math.random()}`,de=x(f.name);w.current=ee;const W={id:ee,docName:f.name,doc:f,signal:O,timestamp:Date.now(),qualityTicket:Xn()};await V.current(W,de,N)},[j,e,x]),_=u.useCallback(async(f,k,N)=>{var Q;const{doc:T,signal:z,id:O,qualityTicket:ee}=f,de=J=>Yn(s.getState().quality,ee)?{}:{quality:J};if(w.current!==O){console.log("Skipping outdated build request for:",T.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 W=(J,se)=>{if(z.aborted||w.current!==O)return;if((d.current.get(T.name)||0)!==k){console.log("Document version changed, aborting build"),z.dispatchEvent(new Event("abort"));return}e({isGenerating:!0,generationProgress:{stage:J,message:se}})};try{const J=M();console.log("Editor: Using themes for document build",{docName:T.name,freshThemeCount:Object.keys(J).length,freshThemeNames:Object.keys(J),memoizedCount:Object.keys(E).length,requestId:O}),W("parsing","Expanding plugins...");const se=await Sn(T.text,{customThemes:J,signal:z});if(Rr(T.name)||(H.current=null),z.aborted||w.current!==O){e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0});return}const K=await wr(async()=>{if(z.aborted)throw new Error("Build cancelled");return await j(T.name,se.text,J,W,{...N,...U?{quality:U}:{}})},{maxRetries:2,initialDelay:500,shouldRetry:re=>re.message.includes("cancelled")||re.message.includes("JSON")||re.message.includes("parse")||re.message.includes("syntax")?!1:St.combine(St.temporaryErrors,oe=>oe.message.includes("Worker")||oe.message.includes("Proxy"))(re),onRetry:(re,oe)=>{console.log(`Retrying presentation generation (attempt ${oe}):`,re.message),e({isGenerating:!0,generationProgress:{stage:"parsing",message:`Retrying generation (attempt ${oe})...`}})},signal:z});if(z.aborted||w.current!==O){console.log("Build cancelled for:",T.name),e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0});return}if(K&&typeof K=="object"&&"name"in K&&"text"in K&&"blob"in K){console.log("Editor: Build completed",{docName:K.name,blobSize:(Q=K.blob)==null?void 0:Q.size,timestamp:Date.now(),requestId:O,version:k});const{findings:re,others:oe}=Wn(K.warnings);e({name:K.name,text:K.text,blob:K.blob,renderer:K.renderer,globalError:void 0,isGenerating:!1,isPreviewStale:!1,generationProgress:void 0,generationStartedAt:void 0,lastBuiltSequence:s.getState().editSequence,cacheStatus:K.cacheStatus,cacheHitRate:K.cacheHitRate,warnings:[...se.warnings,...oe],...de({findings:re,counts:ht(re),...v?{profileId:v}:{},documentName:T.name,seq:ee,source:"generate",analyzedAt:Date.now()})}),p(K.name,void 0)}}catch(J){if(z.aborted||w.current!==O){console.log("Build cancelled with error for:",T.name),e({isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0});return}const se=J instanceof Error?J.message:String(J),K=J instanceof kn?Qn(J.quality):null;e({globalError:se,isGenerating:!1,generationProgress:void 0,generationStartedAt:void 0,...K?de({findings:K,counts:ht(K),...v?{profileId:v}:{},documentName:T.name,seq:ee,blocked:!0,source:"generate",analyzedAt:Date.now(),gateError:se}):{}}),p(T.name,se)}finally{D.current.delete(T.name)}},[j,M,U,v,e,p,s]),V=u.useRef(_);u.useEffect(()=>{V.current=_});const $=u.useRef(null),H=u.useRef(null);u.useEffect(()=>{console.log("Editor: Document rebuild effect triggered",{activeTab:a});const f=c.find(T=>T.name===a),k=m[a]||"application/json+report";k==="application/json+report"&&f&&($.current=a);const N=R.current.get(a);return N&&(clearTimeout(N),R.current.delete(a)),f&&k==="application/json+report"?s.getState().isGenerating||e({isPreviewStale:!0}):f&&k!=="application/json+report"&&g(),()=>{const T=R.current.get(a);T&&(clearTimeout(T),R.current.delete(a))}},[c,a,e,m,P,g]),u.useEffect(()=>{const f=c.find(N=>N.name===a),k=m[a]||"application/json+report";if(!f||k!=="application/json+report"){ne(),e({quality:null});return}return I(a,f.text),ne},[a,I,ne,c,m,e]);const X=u.useMemo(()=>{var N;const f=new Map,k=c.find(T=>T.name===a);if(k&&m[k.name]==="application/json+report")try{const z=(N=JSON.parse(k.text).props)==null?void 0:N.theme;typeof z=="string"&&Object.values(y).some(ee=>ee.name===z&&ee.valid)&&f.set(k.name,z)}catch{}return f},[a,c,m,y]);u.useEffect(()=>(console.log("Editor: Setting up theme change listener",{documentCount:c.length,dependencyCount:X.size,dependencies:Array.from(X.entries()),customThemes:Object.entries(y).map(([k,N])=>({key:k,name:N.name,valid:N.valid}))}),mn.onThemeChange(k=>{console.log("Editor: Theme change detected",{event:k,dependencies:Array.from(X.entries()),activeTab:a,customThemes:Object.entries(y).map(([T,z])=>({key:T,name:z.name,valid:z.valid}))});const N=[];if(X.forEach((T,z)=>{if(T===k.themeName){const O=c.find(ee=>ee.name===z);O&&N.push(O)}}),console.log("Editor: Documents using changed theme",{themeName:k.themeName,documentCount:N.length,documentNames:N.map(T=>T.name)}),N.length===0){console.log("Editor: No documents use this theme, skipping rebuild");return}s.getState().isGenerating||e({isPreviewStale:!0})})),[X,c,P,x,a,e]);const Z=u.useRef(P);u.useEffect(()=>{Z.current=P});const ue=u.useRef(x);u.useEffect(()=>{ue.current=x}),u.useEffect(()=>{const f=()=>{var de;e({isGenerating:!0});let k=!1;const N=be.getState().getActiveEditor();if(N&&!n.getState().pendingDiffs[N.documentName]){const Q=N.toStorageValue(N.editor.getValue());n.getState().saveDocument(N.documentName,Q)}const{documents:T,documentTypes:z}=n.getState();for(const W of T)if(z[W.name]==="application/json+theme"){const Q=be.getState().getEditor(W.name);if(Q){const J=Q.toStorageValue(Q.editor.getValue()),se=r.getState().customThemes[W.name];(!se||se.content!==J)&&(r.getState().updateTheme(W.name,J),k=!0)}}else if(z[W.name]==="application/typescript+plugin"){const Q=be.getState().getEditor(W.name);if(Q){(de=Q.flushPendingSave)==null||de.call(Q);const J=Q.toStorageValue(Q.editor.getValue());J!==W.text&&n.getState().saveDocument(W.name,J)}}Ue.flush();const O=n.getState().activeTab,ee=R.current.get(O);ee&&(clearTimeout(ee),R.current.delete(O)),F.current&&clearTimeout(F.current),F.current=setTimeout(async()=>{F.current=null,await Ue.whenIdle();const{documents:W,activeTab:Q,documentTypes:J}=n.getState();let se=Q;const K=J[Q]||"application/json+report";if(K!=="application/json+report"){const oe=H.current;if(oe&&K==="application/json+theme"&&oe.themeDocName===Q){G.current(Q);return}if($.current)se=$.current;else{e({isGenerating:!1});return}}const re=W.find(oe=>oe.name===se);if(re){const oe=n.getState().pendingDiffs[se],_e=be.getState().getEditor(se),at=oe?{...re,text:oe.modified}:_e?{...re,text:_e.toStorageValue(_e.editor.getValue())}:re;ue.current(at.name),Z.current(at,void 0,k?{bypassCache:!0}:void 0)}else e({isGenerating:!1})},150)};return window.addEventListener("preview:flushAndBuild",f),()=>{window.removeEventListener("preview:flushAndBuild",f),F.current&&clearTimeout(F.current)}},[e,n,r]);const q=u.useCallback(f=>{const{documents:k}=n.getState(),N=k.find(W=>W.name===f);if(!N){e({isGenerating:!1});return}let T,z=null,O=null;try{T=JSON.parse(N.text),z=Qe(T)}catch(W){O=W instanceof Error?W.message:"Invalid JSON"}if(!z){e({isGenerating:!1,globalError:O?`The theme is not valid JSON: ${O}`:"The theme has no name"});return}const ee=Er(z),de=JSON.stringify(Tr(te,z,T),null,2);H.current={themeDocName:f},e({isGenerating:!0}),ue.current(ee),Z.current({name:ee,text:de},void 0,{bypassCache:!0})},[n,e]),G=u.useRef(q);return u.useEffect(()=>{G.current=q}),u.useEffect(()=>{const f=k=>{const N=k.detail;N!=null&&N.themeDocName&&G.current(N.themeDocName)};return window.addEventListener("preview:buildSpecimen",f),()=>window.removeEventListener("preview:buildSpecimen",f)},[]),u.useEffect(()=>{const f=()=>{s.getState().isGenerating||e({isPreviewStale:!0})};return window.addEventListener(Be,f),()=>window.removeEventListener(Be,f)},[s,e]),u.useEffect(()=>()=>{D.current.forEach(f=>f.abort()),D.current.clear(),R.current.forEach(f=>clearTimeout(f)),R.current.clear(),g()},[g]),i.length?t.jsx(En,{value:a,onValueChange:l,className:"h-full",children:t.jsx(Cr,{openTabs:i,documents:c,buildErrors:h,saveDocumentDebounceWait:o})}):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 Gr=u.memo(Mr);export{Gr as Editor};
|
|
16
|
+
//# sourceMappingURL=editor-DFnlAOyt.js.map
|