@8sheets/data-grid 1.1.0 → 1.1.1

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 (67) hide show
  1. package/README.md +1 -1
  2. package/api/serialize.js +1 -1
  3. package/calc/adjust.js +1 -1
  4. package/calc/compile.js +1 -1
  5. package/calc/engine.js +1 -1
  6. package/calc/functions/array.js +1 -1
  7. package/calc/functions/database.js +1 -1
  8. package/calc/functions/date.js +1 -1
  9. package/calc/functions/financial.js +1 -1
  10. package/calc/functions/helpers.js +1 -1
  11. package/calc/functions/info.js +1 -1
  12. package/calc/functions/logical.js +1 -1
  13. package/calc/functions/lookup.js +1 -1
  14. package/calc/functions/math.js +1 -1
  15. package/calc/functions/stat.js +1 -1
  16. package/calc/functions/text.js +1 -1
  17. package/calc/parser.js +3 -3
  18. package/calc/values.js +1 -1
  19. package/calcx/async.js +1 -1
  20. package/calcx/functions/dynamic.js +1 -1
  21. package/calcx/functions/ets.js +1 -1
  22. package/calcx/functions/misc.js +1 -1
  23. package/cells/axis-ops.js +1 -1
  24. package/cells/cf-engine.js +1 -1
  25. package/cells/outline-column.js +1 -1
  26. package/cells/panes.js +1 -1
  27. package/cells/rich-runs.js +2 -2
  28. package/cells/rich-values.js +1 -1
  29. package/celltypes/cell-types.js +2 -2
  30. package/celltypes/dropdowns.js +3 -2
  31. package/celltypes/file-cell.js +2 -2
  32. package/celltypes/range-template.js +2 -2
  33. package/core/cell-type-rules.js +1 -0
  34. package/core/changes.js +1 -1
  35. package/core/cond-format.js +1 -1
  36. package/core/input.js +1 -1
  37. package/core/numfmt.js +1 -1
  38. package/core/region-input.js +1 -1
  39. package/core/sheet.js +1 -1
  40. package/core/sparse.js +1 -1
  41. package/core/structure.js +1 -1
  42. package/core/validation-ranges.js +1 -0
  43. package/core/workbook.js +1 -1
  44. package/datasheets/manager.js +1 -1
  45. package/i18n/en/cells.js +1 -1
  46. package/i18n/en/misc.js +1 -1
  47. package/i18n/pl/cells.js +1 -1
  48. package/i18n/pl/misc.js +1 -1
  49. package/io/client.js +1 -1
  50. package/io/plan.js +1 -1
  51. package/io/xlsx-read.js +1 -1
  52. package/io/xlsx-write.js +1 -1
  53. package/io/xml-scan.js +2 -1
  54. package/io/zip-reader.js +1 -1
  55. package/package.json +1 -1
  56. package/pivot/engine.js +1 -1
  57. package/pivot/xml.js +2 -2
  58. package/print/render-page.js +3 -3
  59. package/slicers/format.js +2 -2
  60. package/slicers/structured.js +1 -1
  61. package/table-view/labels-de.js +1 -1
  62. package/table-view/labels-es.js +1 -1
  63. package/table-view/labels-fr.js +1 -1
  64. package/table-view/labels-ja.js +1 -1
  65. package/table-view/labels.js +1 -1
  66. package/table-view/version.js +1 -1
  67. package/ui/protection-ui.js +1 -1
package/core/changes.js CHANGED
@@ -1 +1 @@
1
- import{FORMULA as x,KIND_MASK as M,STR as y}from"./sheet.js";const i=16384;class m{constructor(){this.cells=new Map,this.rows={inserted:[],deleted:[]},this.cols={inserted:[],deleted:[]}}}const v=(s,t)=>(s?.f??s?.sf??null)===(t?.f??t?.sf??null);function T(s,t,n){const{cells:e}=t.changes;for(let c=0;c<n.count;c++){const a=n.rows[c],o=n.cols[c],r=a*i+o;let l=e.get(r);l===void 0&&(l={kind:n.kinds[c],value:n.values[c],formula:n.kinds[c]&x?n.formulas?.get(c):void 0},e.set(r,l));const u=t.kind(a,o)&-97;u===l.kind&&t.value(a,o)===l.value&&(!(u&x)||v(t.formula(a,o),l.formula))&&e.delete(r)}}function A(s){return s.changes===null&&(s.changes=new m),s.changes}function I(s){s.changes=null}function C(s,t){const n=[];for(const e of s){const c=e.at+e.count;if(t.n>0)e.at>=t.at?n.push({at:e.at+t.n,count:e.count}):c>t.at?n.push({at:e.at,count:e.count+t.n}):n.push(e);else{const a=t.at-t.n;if(c<=t.at)n.push(e);else if(e.at>=a)n.push({at:e.at+t.n,count:e.count});else{const o=Math.max(0,t.at-e.at)+Math.max(0,c-a);o>0&&n.push({at:Math.min(e.at,t.at),count:o})}}}return n}function K(s,t,n){const e=s.changes;if(e===null)return!1;for(const c of(t==="row"?e.rows:e.cols).inserted)if(n>=c.at&&n<c.at+c.count)return!0;return!1}function R(s,t){const n=s.changes;if(n===null)return null;const e={cells:n.cells,rows:n.rows,cols:n.cols},c=u=>()=>{const k={cells:n.cells,rows:n.rows,cols:n.cols};return Object.assign(n,u),c(k)},a=t.axis==="row"?"rows":"cols",o=n[a],r=C(o.inserted,t);n[a]=t.n>0?{inserted:[...r,{at:t.at,count:t.n}],deleted:o.deleted}:{inserted:r,deleted:[...o.deleted,{at:t.at,count:-t.n}]};const l=new Map;for(const[u,k]of n.cells){let d=Math.floor(u/i),h=u-d*i;const f=t.axis==="row"?d:h;let w=f;if(t.n>0)f>=t.at&&(w=f+t.n);else if(f>=t.at-t.n)w=f+t.n;else if(f>=t.at)continue;t.axis==="row"?d=w:h=w,l.set(d*i+h,k)}return n.cells=l,c(e)}const g=(s,t,n)=>!s||t>=s.r0&&t<=s.r1&&n>=s.c0&&n<=s.c1;function S(s,t,n=null){const e=t.changes;if(e===null)return[];const c=(o,r)=>{const l=o&M;return l===0?null:l===y?s.strings.get(r):l===3?r!==0:r},a=[];for(const[o,r]of e.cells){const l=Math.floor(o/i),u=o-l*i;g(n,l,u)&&a.push({row:l,col:u,oldValue:c(r.kind,r.value),newValue:c(t.kind(l,u),t.value(l,u))})}return a.sort((o,r)=>o.row-r.row||o.col-r.col)}const E=(s,t,n)=>s.changes!==null&&s.changes.cells.has(t*i+n);function F(s,t=null){const n=s.changes;if(n!==null){if(t===null){s.changes=new m;return}for(const e of[...n.cells.keys()]){const c=Math.floor(e/i);g(t,c,e-c*i)&&n.cells.delete(e)}}}export{m as ChangeTracker,F as clearDirty,S as getDirtyCells,E as isDirtyCell,K as isInsertedAxis,T as noteChanges,R as noteStructure,A as startTracking,I as stopTracking};
1
+ import{FORMULA as x,KIND_MASK as y,STR as M}from"./sheet.js";const i=16384;class g{constructor(){this.cells=new Map,this.rows={inserted:[],deleted:[]},this.cols={inserted:[],deleted:[]}}}const v=(s,t)=>(s?.f??s?.sf??null)===(t?.f??t?.sf??null);function R(s,t,n){const{cells:e}=t.changes;for(let c=0;c<n.count;c++){const a=n.rows[c],l=n.cols[c],r=a*i+l;let o=e.get(r);o===void 0&&(o={kind:n.kinds[c],value:n.values[c],formula:n.kinds[c]&x?n.formulas?.get(c):void 0},e.set(r,o));const u=t.kind(a,l)&-97;u===o.kind&&t.value(a,l)===o.value&&(!(u&x)||v(t.formula(a,l),o.formula))&&e.delete(r)}}function T(s){return s.changes===null&&(s.changes=new g),s.changes}function A(s){s.changes=null}function D(s,t){const n=[];for(const e of s){const c=e.at+e.count;if(t.n>0)e.at>=t.at?n.push({at:e.at+t.n,count:e.count}):c>t.at?n.push({at:e.at,count:e.count+t.n}):n.push(e);else{const a=t.at-t.n;if(c<=t.at)n.push(e);else if(e.at>=a)n.push({at:e.at+t.n,count:e.count});else{const l=Math.max(0,t.at-e.at)+Math.max(0,c-a);l>0&&n.push({at:Math.min(e.at,t.at),count:l})}}}return n}function I(s,t,n){const e=s.changes;if(e===null)return!1;for(const c of(t==="row"?e.rows:e.cols).inserted)if(n>=c.at&&n<c.at+c.count)return!0;return!1}function K(s,t){const n=s.changes;if(n===null)return null;const e={cells:n.cells,rows:n.rows,cols:n.cols},c=u=>()=>{const w={cells:n.cells,rows:n.rows,cols:n.cols};return Object.assign(n,u),c(w)},a=t.axis==="row"?"rows":"cols",l=n[a],r=D(l.inserted,t);n[a]=t.n>0?{inserted:[...r,{at:t.at,count:t.n}],deleted:l.deleted}:{inserted:r,deleted:[...l.deleted,{at:t.at,count:-t.n}]};const o=new Map;for(const[u,w]of n.cells){let d=Math.floor(u/i),h=u-d*i;const f=t.axis==="row"?d:h;let k=f;if(t.n>0)f>=t.at&&(k=f+t.n);else if(f>=t.at-t.n)k=f+t.n;else if(f>=t.at)continue;t.axis==="row"?d=k:h=k,o.set(d*i+h,w)}return n.cells=o,c(e)}const m=(s,t,n)=>!s||t>=s.r0&&t<=s.r1&&n>=s.c0&&n<=s.c1;function S(s,t,n=null){const e=t.changes;if(e===null)return[];const c=(l,r)=>{const o=l&y;return o===0?null:o===M?s.strings.get(r):o===3?r!==0:r},a=[];for(const[l,r]of e.cells){const o=Math.floor(l/i),u=l-o*i;m(n,o,u)&&a.push({row:o,col:u,oldValue:c(r.kind,r.value),newValue:c(t.kind(o,u),t.value(o,u))})}return a.sort((l,r)=>l.row-r.row||l.col-r.col)}function E(s,t){const n=s.changes;if(!(n===null||t.size===0))for(const e of[...n.cells.keys()])t.has(Math.floor(e/i))&&n.cells.delete(e)}const F=(s,t,n)=>s.changes!==null&&s.changes.cells.has(t*i+n);function O(s,t=null){const n=s.changes;if(n!==null){if(t===null){s.changes=new g;return}for(const e of[...n.cells.keys()]){const c=Math.floor(e/i);m(t,c,e-c*i)&&n.cells.delete(e)}}}export{g as ChangeTracker,O as clearDirty,E as clearDirtyRows,S as getDirtyCells,F as isDirtyCell,I as isInsertedAxis,R as noteChanges,K as noteStructure,T as startTracking,A as stopTracking};
@@ -1 +1 @@
1
- import{parseRangeRef as T}from"./address.js";import{BOOL as R,ERR as S,ERRORS as A,KIND_MASK as L,NUM as E,STR as h}from"./sheet.js";import{numberToText as O}from"../calc/values.js";import{formatGeneral as q,getFormatter as F}from"./numfmt.js";function N(u){return u.split(/\s+/).map(T).filter(Boolean)}import{CondFormats as j,cfEffectAt as w,evaluatorOf as z,iconAt as H}from"../cells/cf-engine.js";function b(u,n,e){const s=u.validations;if(!s)return null;for(const r of s)if(r._ranges===void 0&&(r._ranges=N(r.sqref)),r._ranges.some(t=>n>=t.r0&&n<=t.r1&&e>=t.c0&&e<=t.c1))return r;return null}function C(u,n,e,s,r){const t=e.formula1.trim();if(t.startsWith('"'))return t.slice(1,-1).split(",").map(o=>o.trim());const f=u.engine;let i=f.template(t,s,r).fn(s,r,n);return i&&i.sheet&&(i=f.toArr(i)),i&&i.data?i.data.filter(o=>o!==null):[]}function G(u,n,e,s,r){return B(u,n,e,s,r).map(t=>t.text)}function B(u,n,e,s,r){const t=e.formula1.trim(),f=()=>C(u,n,e,s,r).map(p=>({text:String(p),value:p}));if(t.startsWith('"'))return f();const l=u.engine.template(t,s,r).fn(s,r,n);if(!l||!l.sheet)return f();const i=[],o=l.sheet;for(let p=l.r0;p<=Math.min(l.r1,o.maxRow);p++)for(let a=l.c0;a<=Math.min(l.c1,o.maxCol);a++){const m=o.kind(p,a)&L;if(m===0)continue;const g=o.value(p,a),c=u.styles.get(o.style(p,a)).numFmt;m===E?i.push({text:c==="General"?q(g):F(c).number(g).replace(/\u0001.?\u0001/g," ").trim(),value:g}):m===h?i.push({text:u.strings.get(g),value:u.strings.get(g)}):m===R?i.push({text:g?"TRUE":"FALSE",value:g!==0}):i.push({text:A[g]??"#N/A",value:null})}return i}function K(u,n,e,s,r,t){if(e?.type!=="list"||typeof t!="string"||/^[='"]/.test(t))return null;const f=t.trim().toLowerCase(),l=C(u,n,e,s,r).find(i=>typeof i=="string"&&i.trim().toLowerCase()===f);return l!==void 0&&l.trim()!==t.trim()?l.trim():null}function W(u,n,e,s,r,t,f,l){if(e.type==="none"||e.type===void 0)return!0;if(t===0)return e.allowBlank;const i=u.engine,o=c=>{if(!c)return null;const x=i.template(c,s,r),y=i.legacy;i.legacy=!0;try{const d=x.fn(s,r,n);return d&&d.sheet?i.refAuto(d,s,r):d}finally{i.legacy=y}},p=t===E?O(f):t===R?f?"TRUE":"FALSE":String(l);if(e.type==="list"){if(t===S)return!1;const c=C(u,n,e,s,r);if(t===E&&c.some(y=>(typeof y=="number"?y:Number(y))===f))return!0;const x=p.trim().toLowerCase();return c.some(y=>String(y).trim().toLowerCase()===x)}if(e.type==="custom"){const c=[n.kind(s,r),n.value(s,r),n.maxRow,n.maxCol],x=t===h?u.strings.add(String(l)):t===R?f?1:0:f;n.setCell(s,r,t,x);try{const y=o(e.formula1);return y===!0||typeof y=="number"&&y!==0}finally{n.setCell(s,r,c[0],c[1]),n.maxRow=c[2],n.maxCol=c[3]}}let a;if(e.type==="textLength"){if(t===S)return!1;a=p.length}else if(t===R)a=1/0;else if(t!==E||(a=f,e.type==="whole"&&!Number.isInteger(a)))return!1;const m=o(e.formula1),g=o(e.formula2);switch(e.operator){case"notBetween":return a<m||a>g;case"equal":return a===m;case"notEqual":return a!==m;case"greaterThan":return a>m;case"lessThan":return a<m;case"greaterThanOrEqual":return a>=m;case"lessThanOrEqual":return a<=m;default:return a>=m&&a<=g}}export{R as BOOL,j as CondFormats,h as STR,w as cfEffectAt,z as evaluatorOf,H as iconAt,B as listEntries,G as listItems,K as listSpelling,C as listValues,N as rangesOf,W as validateEntry,b as validationAt};
1
+ import{parseRangeRef as L}from"./address.js";import{BOOL as x,ERR as T,ERRORS as O,KIND_MASK as q,NUM as E,STR as h}from"./sheet.js";import{numberToText as _}from"../calc/values.js";import{formatGeneral as F,getFormatter as N}from"./numfmt.js";function A(n){return n.split(/\s+/).map(L).filter(Boolean)}import{CondFormats as w,cfEffectAt as z,evaluatorOf as H,iconAt as J}from"../cells/cf-engine.js";function G(n,i,t){const r=n.validations;if(!r)return null;for(const s of r)if(s._ranges===void 0&&(s._ranges=A(s.sqref)),s._ranges.some(e=>i>=e.r0&&i<=e.r1&&t>=e.c0&&t<=e.c1))return s;return null}function C(n,i,t){n._ranges===void 0&&(n._ranges=n.sqref?A(n.sqref):[]);const r=n._ranges[0];return r?[r.r0,r.c0]:[i,t]}function S(n,i,t,r,s){const e=t.formula1.trim();if(e.startsWith('"'))return e.slice(1,-1).split(",").map(o=>o.trim());const l=n.engine;let a=l.template(e,...C(t,r,s)).fn(r,s,i);return a&&a.sheet&&(a=l.toArr(a)),a&&a.data?a.data.filter(o=>o!==null):[]}function K(n,i,t,r,s){return B(n,i,t,r,s).map(e=>e.text)}function B(n,i,t,r,s){const e=t.formula1.trim(),l=()=>S(n,i,t,r,s).map(p=>({text:String(p),value:p}));if(e.startsWith('"'))return l();const f=n.engine.template(e,...C(t,r,s)).fn(r,s,i);if(!f||!f.sheet)return l();const a=[],o=f.sheet;for(let p=f.r0;p<=Math.min(f.r1,o.maxRow);p++)for(let u=f.c0;u<=Math.min(f.c1,o.maxCol);u++){const m=o.kind(p,u)&q;if(m===0)continue;const g=o.value(p,u),c=n.styles.get(o.style(p,u)).numFmt;m===E?a.push({text:c==="General"?F(g):N(c).number(g).replace(/\u0001.?\u0001/g," ").trim(),value:g}):m===h?a.push({text:n.strings.get(g),value:n.strings.get(g)}):m===x?a.push({text:g?"TRUE":"FALSE",value:g!==0}):a.push({text:O[g]??"#N/A",value:null})}return a}function W(n,i,t,r,s,e){if(t?.type!=="list"||typeof e!="string"||/^[='"]/.test(e))return null;const l=e.trim().toLowerCase(),f=S(n,i,t,r,s).find(a=>typeof a=="string"&&a.trim().toLowerCase()===l);return f!==void 0&&f.trim()!==e.trim()?f.trim():null}function D(n,i,t,r,s,e,l,f){if(t.type==="none"||t.type===void 0)return!0;if(e===0)return t.allowBlank;const a=n.engine,o=c=>{if(!c)return null;const d=a.template(c,...C(t,r,s)),y=a.legacy;a.legacy=!0;try{const R=d.fn(r,s,i);return R&&R.sheet?a.refAuto(R,r,s):R}finally{a.legacy=y}},p=e===E?_(l):e===x?l?"TRUE":"FALSE":String(f);if(t.type==="list"){if(e===T)return!1;const c=S(n,i,t,r,s);if(e===E&&c.some(y=>(typeof y=="number"?y:Number(y))===l))return!0;const d=p.trim().toLowerCase();return c.some(y=>String(y).trim().toLowerCase()===d)}if(t.type==="custom"){const c=[i.kind(r,s),i.value(r,s),i.maxRow,i.maxCol],d=e===h?n.strings.add(String(f)):e===x?l?1:0:l;i.setCell(r,s,e,d);try{const y=o(t.formula1);return y===!0||typeof y=="number"&&y!==0}finally{i.setCell(r,s,c[0],c[1]),i.maxRow=c[2],i.maxCol=c[3]}}let u;if(t.type==="textLength"){if(e===T)return!1;u=p.length}else if(e===x)u=1/0;else if(e!==E||(u=l,t.type==="whole"&&!Number.isInteger(u)))return!1;const m=o(t.formula1),g=o(t.formula2);switch(t.operator){case"notBetween":return u<m||u>g;case"equal":return u===m;case"notEqual":return u!==m;case"greaterThan":return u>m;case"lessThan":return u<m;case"greaterThanOrEqual":return u>=m;case"lessThanOrEqual":return u<=m;default:return u>=m&&u<=g}}export{x as BOOL,w as CondFormats,h as STR,z as cfEffectAt,H as evaluatorOf,J as iconAt,B as listEntries,K as listItems,W as listSpelling,S as listValues,A as rangesOf,D as validateEntry,G as validationAt};
package/core/input.js CHANGED
@@ -1 +1 @@
1
- import{BOOL as g,EMPTY as C,ERR as D,ERRORS as I,FORMULA as L,NUM as s,STR as N}from"./sheet.js";import{partsToSerial as d}from"./numfmt.js";const M=["#NULL!","#DIV/0!","#VALUE!","#REF!","#NAME?","#NUM!","#N/A"],S=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],A=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/,Y=/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d*)?$/,F=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)[eE][+-]?\d+$/,j=/^[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)?(?:\.\d*)?%$/,y="(?:\\d{1,3}(?:,\\d{3})+|\\d+)(?:\\.\\d*)?|\\.\\d+",Z=/^([+-]?)[€£¥]\s?([+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d*)?)$/;let T={symbol:"$",symbolFirst:!0};function W(r){T={symbol:r.symbol,symbolFirst:r.symbolFirst}}const _=r=>`"${r.replace(/"/g,"")}"`;function q(r,e){const n=r?"#,##0.00":"#,##0",t=_(e.symbol);return e.symbolFirst?`${t}${n}_);[Red]\\(${t}${n}\\)`:`${n} ${t}`}function z(r,e){return e===2?r%4===0&&(r%100!==0||r%400===0||r===1900)?29:28:[4,6,9,11].includes(e)?30:31}const c=r=>r.length<=2?(Number(r)<30?2e3:1900)+Number(r):Number(r),m=(r,e,n)=>r>=1900&&r<=9999&&e>=1&&e<=12&&n>=1&&n<=z(r,e),O=r=>{const e=r.toLowerCase().replace(/\.$/,"");if(e.length<3)return 0;const n=S.indexOf(e.slice(0,3));return n<0?0:new Intl.DateTimeFormat("en-US",{month:"long",timeZone:"UTC"}).format(new Date(Date.UTC(2024,n,15))).toLowerCase().startsWith(e)?n+1:0},$=()=>new Date().getFullYear(),b=(r,e,n)=>r===1900&&e===2&&n===29?60:d(r,e,n);function U(r){let e;if(e=/^(\d{1,2})([/-])(\d{1,2})\2(\d{1,4})$/.exec(r)){const[n,t,o]=[Number(e[1]),Number(e[3]),c(e[4])];return m(o,n,t)?{value:b(o,n,t),format:"m/d/yyyy"}:null}if(e=/^(\d{4})([/-])(\d{1,2})\2(\d{1,2})$/.exec(r)){const[n,t,o]=[Number(e[1]),Number(e[3]),Number(e[4])];return m(n,t,o)?{value:b(n,t,o),format:"m/d/yyyy"}:null}if(e=/^(\d{1,2})[/-](\d{1,2})$/.exec(r)){const[n,t,o]=[Number(e[1]),Number(e[2]),$()];if(m(o,n,t))return{value:b(o,n,t),format:"d-mmm"};const u=c(e[2]);return e[2].length!==1&&m(u,n,1)?{value:d(u,n,1),format:"mmm-yy"}:null}if(e=/^(\d{1,2})[-\s]+([A-Za-z]+\.?)(?:[-\s,]+(\d{2}|\d{4}))?$/.exec(r)){const n=O(e[2]),t=Number(e[1]),o=e[3]?c(e[3]):$();return n&&m(o,n,t)?{value:b(o,n,t),format:e[3]?"d-mmm-yy":"d-mmm"}:null}if(e=/^([A-Za-z]+\.?)[-\s]+(\d{1,4})(?:,?\s*(\d{2}|\d{4}))?$/.exec(r)){const n=O(e[1]);if(!n)return null;const t=Number(e[2]);if(e[3]){const u=c(e[3]);return m(u,n,t)&&e[2].length<=2?{value:d(u,n,t),format:"d-mmm-yy"}:null}if(e[2].length<=2&&m($(),n,t))return{value:d($(),n,t),format:"d-mmm"};const o=c(e[2]);return m(o,n,1)&&e[2].length!==3?{value:d(o,n,1),format:"mmm-yy"}:null}return null}function x(r){let e=/^(\d{1,4}):(\d{1,2})(?::(\d{1,2}))?(?:\s+([AaPp][Mm]?))?$/.exec(r),n,t=0,o=0,u;if(e)[n,t,o]=[Number(e[1]),Number(e[2]),Number(e[3]??0)],u=e[4];else if(e=/^(\d{1,2})\s+([AaPp][Mm]?)$/.exec(r))n=Number(e[1]),u=e[2];else return null;if(t>59||o>59)return null;if(u){if(n<1||n>12)return null;const l=u[0].toLowerCase()==="p";n=n%12+(l?12:0)}const i=(n*3600+t*60+o)/86400;return u?{value:i,format:e[3]!==void 0?"h:mm:ss AM/PM":"h:mm AM/PM"}:n>=24?{value:i,format:"[h]:mm:ss"}:{value:i,format:e[3]!==void 0?"h:mm:ss":"h:mm"}}function B(r){const e=/^(.+?)\s+(\d{1,2}(?::\d{1,2}(?::\d{1,2})?)?\s*(?:[AaPp][Mm]?)?)$/.exec(r);if(!e||!/:|[AaPp]/.test(e[2]))return null;const n=U(e[1]),t=x(e[2]);return!n||!t||t.value>=1?null:{value:n.value+t.value,format:"m/d/yyyy h:mm"}}function G(r){const e=/^([+-]?)(\d+) (\d+)\/(\d+)$/.exec(r);if(!e)return null;const n=Number(e[4]);if(n===0)return null;const t=(Number(e[2])+Number(e[3])/n)*(e[1]==="-"?-1:1),o="?".repeat(Math.min(3,e[4].length));return{value:t,format:`# ${o}/${o}`}}function p(r){let e=0,n="";for(const t of r.replace(/,/g,""))t>="0"&&t<="9"?((e>0||t!=="0")&&e++,n+=e>15?"0":t):((t==="e"||t==="E")&&(e=-1/0),n+=t);return Number(n)}const f=p;function X(r){if(r.length<=32767)return r;const e=r.charCodeAt(32766);return r.slice(0,e>=55296&&e<=56319?32766:32767)}function J(r,e=T){if(r==="")return{kind:C};if(r[0]==="="&&r.length>1)return{kind:L,formula:r.slice(1)};if(r[0]==="'")return{kind:N,text:r.slice(1)};const n=r.trim(),t=r.toUpperCase();if(t==="TRUE")return{kind:g,value:1};if(t==="FALSE")return{kind:g,value:0};const o=M.indexOf(t);if(o>=0)return{kind:D,value:I.indexOf(M[o]),text:r};let u;if((A.test(n)||F.test(n))&&!Number.isFinite(p(n)))return{kind:N,text:r};if(A.test(n))return{kind:s,value:p(n)};if(Y.test(n))return{kind:s,value:f(n),format:n.includes(".")?"#,##0.00":"#,##0"};if(F.test(n))return{kind:s,value:p(n),format:"0.00E+00"};if(j.test(n)&&/\d/.test(n)){const a=n.slice(0,-1);return{kind:s,value:f(a)/100,format:/\.\d/.test(a)?"0.00%":"0%"}}if(u=/^\((\d{1,3}(?:,\d{3})+(?:\.\d*)?|\d+(?:\.\d*)?|\.\d+)\)$/.exec(n))return{kind:s,value:-f(u[1]),...u[1].includes(",")?{format:u[1].includes(".")?"#,##0.00":"#,##0"}:{}};const i=e.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=(a,k,w)=>{const P=f(k)*(a==="-"||w?-1:1);return{kind:s,value:P,format:q(/\.\d/.test(k),e)}};if(u=new RegExp(`^([+-]?)${i}\\s?([+-]?)(${y})$`).exec(n))return l(u[1]||u[2],u[3]);if(u=new RegExp(`^([+-]?)(${y})\\s?${i}$`).exec(n))return l(u[1],u[2]);if((u=new RegExp(`^\\(${i}\\s?(${y})\\)$`).exec(n))||(u=new RegExp(`^\\((${y})\\s?${i}\\)$`).exec(n)))return l("",u[1],!0);if(u=Z.exec(n))return{kind:s,value:f(u[2])*(u[1]==="-"?-1:1)};const v=G(n);if(v)return{kind:s,...v};const E=U(n);if(E)return{kind:s,...E};const h=x(n);if(h)return{kind:s,...h};const R=B(n);return R?{kind:s,...R}:{kind:N,text:r}}export{X as cellEntryText,J as parseInput,W as setEntryCurrency};
1
+ import{BOOL as F,EMPTY as I,ERR as C,ERRORS as L,FORMULA as S,NUM as i,STR as $}from"./sheet.js";import{getFormatter as Y,partsToSerial as a}from"./numfmt.js";const M=["#NULL!","#DIV/0!","#VALUE!","#REF!","#NAME?","#NUM!","#N/A"],j=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],A=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/,Z=/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d*)?$/,T=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)[eE][+-]?\d+$/,_=/^[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)?(?:\.\d*)?%$/,y="(?:\\d{1,3}(?:,\\d{3})+|\\d+)(?:\\.\\d*)?|\\.\\d+",q=/^([+-]?)[€£¥]\s?([+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d*)?)$/;let x={symbol:"$",symbolFirst:!0};function K(t){x={symbol:t.symbol,symbolFirst:t.symbolFirst}}const z=t=>`"${t.replace(/"/g,"")}"`;function B(t,e){const r=t?"#,##0.00":"#,##0",n=z(e.symbol);return e.symbolFirst?`${n}${r}_);[Red]\\(${n}${r}\\)`:`${r} ${n}`}function G(t,e){return e===2?t%4===0&&(t%100!==0||t%400===0||t===1900)?29:28:[4,6,9,11].includes(e)?30:31}const c=t=>t.length<=2?(Number(t)<30?2e3:1900)+Number(t):Number(t),m=(t,e,r)=>t>=1900&&t<=9999&&e>=1&&e<=12&&r>=1&&r<=G(t,e),U=t=>{const e=t.toLowerCase().replace(/\.$/,"");if(e.length<3)return 0;const r=j.indexOf(e.slice(0,3));return r<0?0:new Intl.DateTimeFormat("en-US",{month:"long",timeZone:"UTC"}).format(new Date(Date.UTC(2024,r,15))).toLowerCase().startsWith(e)?r+1:0},p=()=>new Date().getFullYear(),b=(t,e,r)=>t===1900&&e===2&&r===29?60:a(t,e,r);function O(t){let e;if(e=/^(\d{1,2})([/-])(\d{1,2})\2(\d{1,4})$/.exec(t)){const[r,n,u]=[Number(e[1]),Number(e[3]),c(e[4])];return m(u,r,n)?{value:b(u,r,n),format:"m/d/yyyy"}:null}if(e=/^(\d{4})([/-])(\d{1,2})\2(\d{1,2})$/.exec(t)){const[r,n,u]=[Number(e[1]),Number(e[3]),Number(e[4])];return m(r,n,u)?{value:b(r,n,u),format:"m/d/yyyy"}:null}if(e=/^(\d{1,2})[/-](\d{1,4})$/.exec(t)){const[r,n,u]=[Number(e[1]),Number(e[2]),p()];if(e[2].length<=2&&m(u,r,n))return{value:b(u,r,n),format:"d-mmm"};const s=c(e[2]);return e[2].length!==3&&m(s,r,1)?{value:a(s,r,1),format:"mmm-yy"}:null}if(e=/^(\d{1,2})[-\s]+([A-Za-z]+\.?)(?:[-\s,]+(\d{2}|\d{4}))?$/.exec(t)){const r=U(e[2]),n=Number(e[1]),u=e[3]?c(e[3]):p();return r&&m(u,r,n)?{value:b(u,r,n),format:e[3]?"d-mmm-yy":"d-mmm"}:null}if(e=/^([A-Za-z]+\.?)[-\s]+(\d{1,4})(?:,?\s*(\d{2}|\d{4}))?$/.exec(t)){const r=U(e[1]);if(!r)return null;const n=Number(e[2]);if(e[3]){const s=c(e[3]);return m(s,r,n)&&e[2].length<=2?{value:a(s,r,n),format:"d-mmm-yy"}:null}if(e[2].length<=2&&m(p(),r,n))return{value:a(p(),r,n),format:"d-mmm"};const u=c(e[2]);return m(u,r,1)&&e[2].length!==3?{value:a(u,r,1),format:"mmm-yy"}:null}return null}function w(t){let e=/^(\d{1,4}):(\d{1,2})(?::(\d{1,2}))?(?:\s+([AaPp][Mm]?))?$/.exec(t),r,n=0,u=0,s;if(e)[r,n,u]=[Number(e[1]),Number(e[2]),Number(e[3]??0)],s=e[4];else if(e=/^(\d{1,2})\s+([AaPp][Mm]?)$/.exec(t))r=Number(e[1]),s=e[2];else return null;if(n>59||u>59)return null;if(s){if(r<1||r>12)return null;const d=s[0].toLowerCase()==="p";r=r%12+(d?12:0)}const o=(r*3600+n*60+u)/86400;return s?{value:o,format:e[3]!==void 0?"h:mm:ss AM/PM":"h:mm AM/PM"}:r>=24?{value:o,format:"[h]:mm:ss"}:{value:o,format:e[3]!==void 0?"h:mm:ss":"h:mm"}}function V(t){const e=/^(.+?)\s+(\d{1,2}(?::\d{1,2}(?::\d{1,2})?)?\s*(?:[AaPp][Mm]?)?)$/.exec(t);if(!e||!/:|[AaPp]/.test(e[2]))return null;const r=O(e[1]),n=w(e[2]);return!r||!n||n.value>=1?null:{value:r.value+n.value,format:"m/d/yyyy h:mm"}}function H(t){const e=/^([+-]?)(\d+) (\d+)\/(\d+)$/.exec(t);if(!e)return null;const r=Number(e[4]);if(r===0)return null;const n=(Number(e[2])+Number(e[3])/r)*(e[1]==="-"?-1:1),u="?".repeat(Math.min(3,e[4].length));return{value:n,format:`# ${u}/${u}`}}function N(t){let e=0,r="";for(const n of t.replace(/,/g,""))n>="0"&&n<="9"?((e>0||n!=="0")&&e++,r+=e>15?"0":n):((n==="e"||n==="E")&&(e=-1/0),r+=n);return Number(r)}const f=N;function Q(t){if(t.length<=32767)return t;const e=t.charCodeAt(32766);return t.slice(0,e>=55296&&e<=56319?32766:32767)}function W(t,e=x,r=0){if(t==="")return{kind:I};if(t[0]==="="&&t.length>1)return{kind:S,formula:t.slice(1)};if(t[0]==="'")return{kind:$,text:t.slice(1)};const n=t.trim(),u=t.toUpperCase();if(u==="TRUE")return{kind:F,value:1};if(u==="FALSE")return{kind:F,value:0};const s=M.indexOf(u);if(s>=0)return{kind:C,value:L.indexOf(M[s]),text:t};let o;if((o=/^([+-])\s+(\S.*)$/.exec(n))&&!/^[-+(]/.test(o[2])){const l=W(o[2],e,r);return l.kind===i&&!(l.format&&Y(l.format).isDate)?o[1]==="-"?{...l,value:-l.value}:l:{kind:$,text:t}}if((A.test(n)||T.test(n))&&!Number.isFinite(N(n)))return{kind:$,text:t};if(A.test(n))return{kind:i,value:N(n)};if(Z.test(n))return{kind:i,value:f(n),format:n.includes(".")?"#,##0.00":"#,##0"};if(T.test(n))return{kind:i,value:N(n),format:"0.00E+00"};if(_.test(n)&&/\d/.test(n)){const l=n.slice(0,-1);return{kind:i,value:f(l)/100,format:/\.\d/.test(l)?"0.00%":"0%"}}if(o=/^\((\d{1,3}(?:,\d{3})+(?:\.\d*)?|\d+(?:\.\d*)?|\.\d+)\)$/.exec(n))return{kind:i,value:-f(o[1]),...o[1].includes(",")?{format:o[1].includes(".")?"#,##0.00":"#,##0"}:{}};const d=e.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),v=(l,g,D)=>{const P=f(g)*(l==="-"||D?-1:1);return{kind:i,value:P,format:B(/\.\d/.test(g),e)}};if(o=new RegExp(`^([+-]?)${d}\\s?([+-]?)(${y})$`).exec(n))return v(o[1]||o[2],o[3]);if(o=new RegExp(`^([+-]?)(${y})\\s?${d}$`).exec(n))return v(o[1],o[2]);if((o=new RegExp(`^\\(${d}\\s?(${y})\\)$`).exec(n))||(o=new RegExp(`^\\((${y})\\s?${d}\\)$`).exec(n)))return v("",o[1],!0);if(o=q.exec(n))return{kind:i,value:f(o[2])*(o[1]==="-"?-1:1)};const R=H(n);if(R)return{kind:i,...R};const E=O(n);if(E)return{kind:i,...E,value:E.value-r};const k=w(n);if(k)return{kind:i,...k};const h=V(n);return h?{kind:i,...h,value:h.value-r}:{kind:$,text:t}}export{Q as cellEntryText,c as fullYear,W as parseInput,K as setEntryCurrency};
package/core/numfmt.js CHANGED
@@ -1 +1 @@
1
- import{calendarParts as K,dbnumDigits as Z,dbnumPlaces as Q,eraAt as B,erasOf as G,hijriLocale as V,localeData as v,mapDigits as ee,numeralDigits as te,parseLocaleBracket as se}from"../calcx/culture/format-locale.js";const y={decimal:".",group:",",months:["January","February","March","April","May","June","July","August","September","October","November","December"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthsWithDay:null,shortMonths:null,shortDays:null,shortDate:"m/d/yyyy",longDate:"dddd, mmmm d, yyyy",longTime:"h:mm:ss AM/PM",amDesignator:"AM",pmDesignator:"PM",tag:null,eras:null,numerals:null};function ye(e){Object.assign(y,e),R.clear()}const C="",xe="[$-F800]dddd, mmmm d, yyyy",Me={0:"General",1:"0",2:"0.00",3:"#,##0",4:"#,##0.00",9:"0%",10:"0.00%",11:"0.00E+00",12:"# ?/?",13:"# ??/??",14:"m/d/yyyy",15:"d-mmm-yy",16:"d-mmm",17:"mmm-yy",18:"h:mm AM/PM",19:"h:mm:ss AM/PM",20:"h:mm",21:"h:mm:ss",22:"m/d/yyyy h:mm",37:"#,##0_);(#,##0)",38:"#,##0_);[Red](#,##0)",39:"#,##0.00_);(#,##0.00)",40:"#,##0.00_);[Red](#,##0.00)",41:'_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',42:'_($* #,##0_);_($* \\(#,##0\\);_($* "-"_);_(@_)',43:'_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',44:'_($* #,##0.00_);_($* \\(#,##0.00\\);_($* "-"??_);_(@_)',45:"mm:ss",46:"[h]:mm:ss",47:"mm:ss.0",48:"##0.0E+0",49:"@"},U={black:"#000000",blue:"#0000FF",cyan:"#00FFFF",green:"#00FF00",magenta:"#FF00FF",red:"#FF0000",white:"#FFFFFF",yellow:"#FFFF00"},ne=["000000","FFFFFF","FF0000","00FF00","0000FF","FFFF00","FF00FF","00FFFF","800000","008000","000080","808000","800080","008080","C0C0C0","808080","9999FF","993366","FFFFCC","CCFFFF","660066","FF8080","0066CC","CCCCFF","000080","FF00FF","FFFF00","00FFFF","800080","800000","008080","0000FF","00CCFF","CCFFFF","CCFFCC","FFFF99","99CCFF","FF99CC","CC99FF","FFCC99","3366FF","33CCCC","99CC00","FFCC00","FF9900","FF6600","666699","969696","003366","339966","003300","333300","993300","993366","333399","333333"];function W(e){const s=[[]];let n=s[0];const o=t=>{const i=n[n.length-1];i&&i.k==="lit"?i.s+=t:n.push({k:"lit",s:t})};for(let t=0;t<e.length;t++){const i=e[t];if((i==="G"||i==="g")&&e.slice(t,t+7).toLowerCase()==="general"){o("General"),t+=6;continue}switch(i){case";":n=[],s.push(n);break;case'"':{const a=e.indexOf('"',t+1);o(a<0?e.slice(t+1):e.slice(t+1,a)),t=a<0?e.length:a;break}case"\\":t+1<e.length&&o(e[++t]);break;case"_":t++,o(" ");break;case"*":n.push({k:"fill",c:e[++t]??" "});break;case"[":{const a=e.indexOf("]",t);if(a<0){o(i);break}const l=e.slice(t+1,a);t=a;const f=l.toLowerCase();if(/^dbnum[1-4]$/.test(f)){n.push({k:"dbnum",n:Number(f[5])});break}if(/^h+$/.test(f)||/^m+$/.test(f)||/^s+$/.test(f))n.push({k:"elapsed",c:f[0],n:f.length});else if(U[f])n.push({k:"color",v:U[f]});else if(/^color\s*\d+$/.test(f)){const d=ne[Number(f.replace(/\D/g,""))-1];d&&n.push({k:"color",v:`#${d}`})}else if(/^(<=|>=|<>|<|>|=)\s*-?[\d.]+/.test(l)){const d=/^(<=|>=|<>|<|>|=)\s*(-?[\d.]+(?:[eE][+-]?\d+)?)/.exec(l);n.push({k:"cond",op:d[1],v:Number(d[2])})}else if(l[0]==="$"){const d=se(l);d?.currency&&o(d.currency),d&&(d.tag||d.calendar||d.numerals||d.system||d.gannen)&&n.push({k:"loc",info:d})}break}case"@":n.push({k:"text"});break;case"#":case"0":case"?":n.push({k:"d",c:i});break;case".":n.push({k:"point"});break;case",":n.push({k:"comma"});break;case"%":n.push({k:"pct"});break;case"/":n.push({k:"slash"});break;case"E":case"e":{const a=e[t+1];if((a==="+"||a==="-")&&/[0#?]/.test(e[t+2]??""))n.push({k:"exp",plus:a==="+",upper:i==="E"}),t++;else if(i==="e"){let l=1;for(;e[t+l]==="e";)l++;n.push({k:"date",c:"e",n:l}),t+=l-1}else o(i);break}case"y":case"Y":case"m":case"M":case"d":case"D":case"h":case"H":case"s":case"S":{const a=i.toLowerCase();let l=1;for(;e[t+l]?.toLowerCase()===a;)l++;n.push({k:"date",c:a,n:l}),t+=l-1;break}case"g":case"G":case"b":case"B":{const a=i.toLowerCase();if(a==="b"&&e[t+1]==="2"){n.push({k:"hijri"}),t++;break}let l=1;for(;e[t+l]?.toLowerCase()===a;)l++;n.push({k:"date",c:a,n:l}),t+=l-1;break}case"A":case"a":{const a=e.slice(t,t+5).toUpperCase();if(/^AAA/.test(a)){let l=3;for(;e[t+l]?.toLowerCase()==="a";)l++;n.push({k:"date",c:"a",n:l}),t+=l-1}else a==="AM/PM"?(n.push({k:"ampm",long:!0}),t+=4):a.startsWith("A/P")?(n.push({k:"ampm",long:!1,lower:i==="a"}),t+=2):o(i);break}default:o(i)}}return s}function ie(e){const s={tokens:e,color:null,cond:null,isDate:!1,isText:!1,isNum:!1,isGeneral:!1},n=[];for(const t of e)t.k==="color"?s.color=t.v:t.k==="cond"?s.cond=t:t.k==="loc"?s.loc=t.info:t.k==="dbnum"?s.dbnum=t.n:t.k==="hijri"?s.hijri=!0:n.push(t);if(s.loc?.system){n.length=0;for(const t of W(s.loc.system==="date"?y.longDate:y.longTime)[0])n.push(t)}s.tokens=n;const o=n.filter(t=>t.k==="lit").map(t=>t.s).join("");if(s.isDate=n.some(t=>t.k==="date"||t.k==="elapsed"||t.k==="ampm"),s.isText=n.some(t=>t.k==="text"),s.isNum=!s.isDate&&n.some(t=>t.k==="d"),/general/i.test(o)){s.isGeneral=!0;for(const t of n)t.k==="lit"&&(t.s=t.s.replace(/general/i,""))}return s.isDate?ae(s):s.isNum&&re(s),s.digits=le(s),s}const oe=e=>e.op==="<"&&e.v<=0||e.op==="<="&&e.v<0||e.op==="="&&e.v<0;function Y(e,s){const n=E(s);return e.dbnum?Q(n,e.dbnum,e.loc?.tag??y.tag)??n:n}function le(e){if(e.dbnum){const s=Z(e.dbnum,e.loc?.tag??y.tag);if(s)return s}return e.loc?.numerals>1?te(e.loc.numerals):y.numerals??null}function ae(e){if(e.tokens.some(t=>t.k==="date"&&t.c==="g")&&G(e.loc,y)){let t=!1;for(const i of e.tokens)i.k==="date"&&i.c==="g"?t=!0:t&&i.k==="date"&&i.c==="y"&&(i.c="e",i.n=2)}const s=e.tokens;let n=null;for(let t=0;t<s.length;t++){const i=s[t];if(i.k==="date"&&i.c==="m"&&i.n<=2){let a=null;for(let l=t+1;l<s.length;l++)if(s[l].k!=="lit"){a=s[l];break}(n==="h"||a&&a.k==="date"&&a.c==="s"||a&&a.k==="elapsed"&&a.c==="s")&&(i.c="n"),n=null}else i.k==="date"&&i.c==="h"||i.k==="elapsed"&&i.c==="h"?n="h":(i.k==="date"||i.k==="elapsed")&&(n=null)}e.hasDay=s.some(t=>t.k==="date"&&t.c==="d"&&t.n<=2),e.hour12=s.some(t=>t.k==="ampm"),e.subDigits=0;const o=[];for(let t=0;t<s.length;t++){const i=s[t];if(i.k==="point"&&s[t+1]?.k==="d"){let a=0;for(;s[t+1+a]?.k==="d";)a++;o.push({k:"sub",n:a}),e.subDigits=Math.max(e.subDigits,a),t+=a}else i.k==="point"?o.push({k:"lit",s:"."}):i.k==="slash"?o.push({k:"lit",s:"/"}):i.k==="comma"?o.push({k:"lit",s:","}):i.k==="d"?o.push({k:"lit",s:i.c}):i.k==="pct"?o.push({k:"lit",s:"%"}):o.push(i)}e.tokens=o}function re(e){const s=e.tokens;let n=-1,o=-1,t=-1,i=-1,a=-1;s.forEach((c,k)=>{c.k==="d"?(o<0&&(o=k),n=k):c.k==="point"&&t<0?t=k:c.k==="exp"&&i<0?i=k:c.k==="slash"&&a<0&&o>=0&&(a=k)});let l=0,f=0,d=!1;const b=[];for(let c=0;c<s.length;c++){const k=s[c];if(k.k==="pct")l++,b.push({k:"lit",s:"%"});else if(k.k==="comma"){let m=!1;for(let h=c+1;h<s.length;h++){if(s[h].k==="d"){m=!0;break}if(s[h].k!=="comma")break}m&&c>o&&(t<0||c<t)?d=!0:c>o&&c<=n+8&&!m?f++:b.push({k:"lit",s:","})}else k.k==="slash"&&c!==a?b.push({k:"lit",s:"/"}):k.k==="point"&&c!==t?b.push({k:"lit",s:"."}):b.push(k)}e.tokens=b,e.pct=l,e.scale=f,e.grouping=d,e.fraction=a>=0,e.scientific=i>=0;let u="int";const p={int:0,dec:0,exp:0,num:0,den:0};let g="";for(const c of b)c.k==="point"?u="dec":c.k==="exp"?u="exp":c.k==="slash"?u="den":c.k==="d"?(c.part=u,p[u]++,u==="den"&&(g+=c.c)):c.k==="lit"&&u==="den"&&/^\d+$/.test(c.s)&&(g+=c.s);if(e.fraction){let k=b.findIndex(h=>h.k==="slash")-1,m=!1;for(;k>=0;){const h=b[k];if(h.k==="d")h.part="num",p.num++,p.int--,m=!0;else if(m)break;k--}e.fixedDen=/^\d+$/.test(g)?Number(g):0,e.denDigits=p.den}e.counts=p}function I(e,s){if(Number.isInteger(e)&&e<1e15)return{int:e===0?"":String(e),dec:"0".repeat(s)};const n=e.toExponential(14),o=n.indexOf("e"),t=n[0]+n.slice(2,o),a=Number(n.slice(o+1))+1+s;let l,f=!1;if(a<0?l="":a>=t.length?l=t+"0".repeat(a-t.length):(f=t.charCodeAt(a)>=53,l=t.slice(0,a)),f){let g=l.length-1;const c=l.split("");for(;g>=0;)if(c[g]==="9")c[g]="0",g--;else{c[g]=String.fromCharCode(c[g].charCodeAt(0)+1);break}l=c.join(""),g<0&&(l="1"+l)}const b=l.length-s;let u,p;return b<=0?(u="",p="0".repeat(-b)+l):(u=l.slice(0,b),p=l.slice(b)),u=u.replace(/^0+/,""),{int:u,dec:p}}function ce(e){if(e.length<=3)return e;let s="",n=e.length%3;for(n>0&&(s=e.slice(0,n));n<e.length;n+=3)s+=(s?y.group:"")+e.slice(n,n+3);return s}function fe(e,s){if(s.fixedDen>0)return[Math.round(e*s.fixedDen),s.fixedDen];const n=10**s.denDigits-1;let[o,t,i,a]=[0,1,1,0],l=e;for(let f=0;f<32;f++){const d=Math.floor(l),b=d*i+o,u=d*a+t;if(u>n)break;[o,t,i,a]=[i,a,b,u];const p=l-d;if(p<1e-10)break;l=1/p}return[i,a||1]}function ue(e,s){let n=s;e.pct&&(n*=100**e.pct),e.scale&&(n/=1e3**e.scale);const{counts:o}=e;let t="",i="",a="",l=!1,f="",d="";if(e.fraction){const r=o.int>0?Math.floor(n):0,[F,M]=fe(n-r,e);let S=r,_=F;_===M&&o.int>0&&(S+=1,_=0),t=S===0?_===0&&o.int>0?"0":"":String(S),f=_===0&&o.int>0?"":String(_),d=_===0&&o.int>0?"":String(M)}else if(e.scientific){let r=n===0?0:Math.floor(Math.log10(n));const F=Math.max(o.int,1);F>1&&(r=Math.floor(r/F)*F);let M=I(n/10**r,o.dec);M.int.length>F&&(r+=F>1?F:1,M=I(n/10**r,o.dec)),t=n===0&&F>1?"0".repeat(F):M.int,i=M.dec,l=r<0,a=String(Math.abs(r))}else{const r=I(n,o.dec);t=r.int,i=r.dec}let b=i.length,u="";const p=e.tokens,g=[];for(const r of p)r.k==="d"&&r.part==="int"&&g.push(r);const c=new Map;let k=t.length-1;for(let r=g.length-1;r>=0;r--){const F=g[r];if(k>=0){let M=t[k--];r===0&&k>=0&&(M=t.slice(0,k+1)+M,k=-1),c.set(F,M)}else c.set(F,F.c==="0"?"0":F.c==="?"?" ":"")}if(e.grouping&&g.length){let r="";for(const S of g)r+=c.get(S);const F=/^ */.exec(r)[0],M=ce(r.slice(F.length));c.forEach((S,_)=>c.set(_,"")),c.set(g[0],F+M)}const m=[];for(const r of p)r.k==="d"&&r.part==="dec"&&m.push(r);for(let r=m.length-1;r>=0&&!(m[r].c==="0"||i[r]!=="0");r--)b=r;let h=0,D=0;const x=p.filter(r=>r.k==="d"&&r.part==="exp").length,L=a.padStart(x,"0");let O=0;const P=p.filter(r=>r.k==="d"&&r.part==="num").length,T=f.padStart(P," ");let A=0;const N=p.filter(r=>r.k==="d"&&r.part==="den").length,j=d.padEnd(N," "),H=e.fraction&&f==="";for(const r of p)switch(r.k){case"lit":u+=r.s===""?"":r.s;break;case"fill":u+=C+r.c+C;break;case"point":g.length===0&&!e.fraction&&!e.scientific&&t!=="0"&&!u.includes(y.decimal)&&(u+=t),u+=y.decimal;break;case"exp":u+=(r.upper?"E":"e")+(l?"-":r.plus?"+":"");break;case"slash":u+=H?" ":"/";break;case"d":switch(r.part){case"int":u+=c.get(r);break;case"dec":{const F=h++;F<b?u+=i[F]:r.c==="?"?u+=" ":r.c==="0"&&(u+="0");break}case"exp":D===0&&(u+=L),D++;break;case"num":{O===0?u+=T.slice(0,T.length-P+1):u+=T[T.length-P+O],O++;break}case"den":{A<N&&(u+=j[A]),A++,A===N&&j.length>N&&(u+=j.slice(N));break}default:}break;default:}return u}function he(e){let s=Math.floor(e),n=e-s,o=Math.round(n*864e5);o>=864e5&&(s+=1,o-=864e5);let t,i,a;if(s===0)t=1900,i=1,a=0;else if(s===60)t=1900,i=2,a=29;else{const f=(s<60?s+1:s)-25569+719468,d=Math.floor(f/146097),b=f-d*146097,u=Math.floor((b-Math.floor(b/1460)+Math.floor(b/36524)-Math.floor(b/146096))/365),p=b-(365*u+Math.floor(u/4)-Math.floor(u/100)),g=Math.floor((5*p+2)/153);a=p-Math.floor((153*g+2)/5)+1,i=g<10?g+3:g-9,t=u+d*400+(i<=2?1:0)}const l=s===0?6:(s-1)%7;return{year:t,month:i,day:a,weekday:l,ms:o,serial:e}}function De(e,s){const n=e.trim().split(/[^0-9]+/).filter(Boolean).map(Number);if(n.length!==3)return null;const o=f=>n[s.indexOf(f)];let t=o("Y");const i=o("M"),a=o("D");if(t<100&&(t+=t<30?2e3:1900),!(i>=1&&i<=12&&a>=1&&a<=new Date(Date.UTC(t,i,0)).getUTCDate()))return null;const l=me(t,i,a);return Number.isFinite(l)?l:null}function me(e,s,n){const o=s<=2?e-1:e,t=s<=2?s+9:s-3,i=Math.floor(o/400),a=o-i*400,l=Math.floor((153*t+2)/5)+n-1,f=a*365+Math.floor(a/4)-Math.floor(a/100)+l,d=i*146097+f-719468+25569;return d<61?d-1:d}const w=e=>e<10?"0"+e:String(e);function q(e,s){const n=86400*10**(e.subDigits??0);s=Math.round(s*n)/n;const o=he(s),t=o.ms;let i=Math.floor(t/1e3);const a=t-i*1e3;let l="";e.subDigits>0?(l=(a/1e3).toFixed(e.subDigits).slice(2),l.length===0&&(l="")):a>=500&&(i+=1);let f=Math.floor(i/3600);const d=Math.floor(i%3600/60),b=i%60;f>=24&&(f=23);const u=e.hour12?f%12===0?12:f%12:f,{loc:p}=e,g=e.hijri&&!p?.tag,c=p?.tag?v(p.tag):g?V():y,k=p?.calendar||g?K(g?"hijri":p.calendar,s,o,p?.tag??null)??o:o;let m="";for(const h of e.tokens)switch(h.k){case"lit":m+=h.s;break;case"fill":m+=C+h.c+C;break;case"date":switch(h.c){case"y":m+=h.n<=2?w(k.year%100):String(k.year);break;case"e":{const D=G(p,y);if(D===null){m+=String(k.year);break}const x=o.year-B(D,s).firstYear+1;x===1&&p?.gannen?m+="元":m+=h.n===1?x:w(x);break}case"g":{const D=G(p,y);if(D===null)break;const x=B(D,s);m+=h.n===1?x.symbol:h.n===2?x.abbreviation:x.name;break}case"b":{const D=p?.tag?o.year:o.year+543;m+=h.n<=2?w(D%100):String(D);break}case"a":m+=h.n===3?c.shortDays?.[o.weekday]??c.days[o.weekday].slice(0,3):c.days[o.weekday];break;case"m":h.n===1?m+=k.month:h.n===2?m+=w(k.month):k.monthName?m+=h.n===5?k.monthName[0]:k.monthName:h.n===3?m+=c.shortMonths?.[k.month-1]??c.months[k.month-1].slice(0,3):h.n===5?m+=c.months[k.month-1][0]:m+=(e.hasDay?c.monthsWithDay??c.months:c.months)[k.month-1];break;case"d":h.n===1?m+=k.day:h.n===2?m+=w(k.day):h.n===3?m+=c.shortDays?.[o.weekday]??c.days[o.weekday].slice(0,3):m+=c.days[o.weekday];break;case"h":m+=h.n===1?u:w(u);break;case"n":m+=h.n===1?d:w(d);break;case"s":m+=h.n===1?b:w(b);break;default:}break;case"elapsed":{const x=Math.floor(s)*86400+i,L=h.c==="h"?Math.floor(x/3600):h.c==="m"?Math.floor(x/60):x;m+=String(L).padStart(h.n,"0");break}case"ampm":h.long?m+=f<12?p?.tag?c.am:y.amDesignator:p?.tag?c.pm:y.pmDesignator:m+=h.lower?f<12?"a":"p":f<12?"A":"P";break;case"sub":m+=y.decimal+l.slice(0,h.n);break;default:}return m}function de(e){return e.replace(/e([+-])(\d+)$/i,(s,n,o)=>`E${n}${o.padStart(2,"0")}`)}function $(e,s){const[n,o]=e.toExponential(s).split("e");return de(Number(n)+"e"+o).replace(".",y.decimal)}function J(e,s){const n=Number(e.toPrecision(15)).toFixed(s);return n.includes(".")?n.replace(/\.?0+$/,"").replace(".",y.decimal):n}function E(e,s=11){const n=Math.abs(e);if(Number.isInteger(e)&&n<1e11||!Number.isFinite(e))return String(e);const o=Math.max(s-6,0);if(n>=1e11||n<1e-9)return $(e,o);const t=Math.floor(Math.log10(n)),i=Math.max(0,s-(n<1?2:t+1));return t<0&&i+t<o&&Number(e.toFixed(i))!==e?$(e,o):J(e,i)}function Ce(e,s){const n=E(e);if(s(n))return n;const o=Math.abs(e);if(o===0)return n;const t=Math.floor(Math.log10(o)),i=!n.includes("E");for(let a=11;a>=1;a--){if(i&&a>t){const l=Math.min(20,a-1-t),f=J(e,l);if(s(f))return f}if(!i||t<0||a<=t){const l=$(e,a-1);if(s(l))return l}}return $(e,0)}class ke{constructor(s){this.code=s;const n=W(s);this.sections=n.slice(0,4).map(ie);const o=this.sections[0];if(this.general=this.sections.length===1&&o.isGeneral&&!o.dbnum&&o.tokens.every(t=>t.k==="lit"&&t.s===""),this.isDate=this.sections.some(t=>t.isDate),this.isText=this.sections.length===1&&o.isText,this.sections.some(t=>t.digits)){const t=this.number;this.number=i=>{const a=this.sections[this._pick(i)],l=t.call(this,i);return a.digits?ee(l,a.digits):l}}}_pick(s){const n=this.sections;if(n[0].cond!==null||n[1]&&n[1].cond!==null){for(let i=0;i<Math.min(n.length,3);i++){const a=n[i].cond;if(a===null){if(i===n.length-1||i===2||n[i].isText&&i===3)return i;continue}if(be(a,s))return i}return Math.min(n.length-1,2)}const t=n.length>1&&n.length<4&&n[n.length-1].isText?n.length-1:n.length;return t===1?0:t===2?s<0?1:0:s>0?0:s<0?1:2}number(s){if(this.general)return E(s);const n=this._pick(s),o=this.sections[n],t=this.sections[0].cond!==null||this.sections[1]&&this.sections[1].cond!==null,i=s<0&&(o.cond!==null?!oe(o.cond):n===0||t);if(o.isDate){const l=s<0&&n>0?-s:s;return z(o,l)?"#".repeat(8):l<0?`-${q(o,-l)}`:q(o,l)}if(o.isNum){const l=ue(o,Math.abs(s));return i&&ge(l)?"-"+l:l}if(o.isGeneral){let l="";for(const f of o.tokens)f.k==="lit"?l+=f.s===""?Y(o,Math.abs(s)):f.s.replace("",Y(o,Math.abs(s))):f.k==="fill"&&(l+=C+f.c+C);return s<0&&n===0?"-"+l:l}let a=i?"-":"";for(const l of o.tokens)l.k==="lit"?a+=l.s:l.k==="fill"?a+=C+l.c+C:l.k==="pct"?a+="%":l.k==="text"&&(a+=E(Math.abs(s)));return a}dateOverflow(s){if(this.general)return!1;const n=this._pick(s),o=this.sections[n];return!!o.isDate&&z(o,s<0&&n>0?-s:s)}text(s){const n=this.sections,o=n.length===4?n[3]:n.length===1&&n[0].isText?n[0]:null;if(o===null)return s;let t="";for(const i of o.tokens)i.k==="lit"?t+=i.s:i.k==="text"?t+=s:i.k==="fill"&&(t+=C+i.c+C);return t}color(s){return this.sections[this._pick(s)].color}}const pe=2958466;function z(e,s){return e.tokens.some(o=>o.k==="date"||o.k==="ampm")?s<0||s>=pe:!1}function ge(e){for(let s=0;s<e.length;s++){const n=e.charCodeAt(s);if(n>=49&&n<=57)return!0}return!1}function be(e,s){switch(e.op){case"<":return s<e.v;case"<=":return s<=e.v;case">":return s>e.v;case">=":return s>=e.v;case"=":return s===e.v;default:return s!==e.v}}const R=new Map;function X(e){let s=R.get(e);return s===void 0&&(s=new ke(e==="m/d/yyyy"?y.shortDate:e==="m/d/yyyy h:mm"?`${y.shortDate} h:mm`:e),R.set(e,s)),s}function _e(e,s){return X(e).number(s)}function we(e){return X("#,##0").number(e)}export{Me as BUILTIN_FORMATS,C as FILL_MARK,xe as SYSTEM_LONG_DATE,De as dateSerial,de as excelExponent,Ce as fitGeneral,we as formatCount,E as formatGeneral,_e as formatNumber,X as getFormatter,me as partsToSerial,he as serialToParts,ye as setNumberLocale};
1
+ import{calendarParts as K,dbnumDigits as Z,dbnumPlaces as Q,eraAt as R,erasOf as O,hijriLocale as V,localeData as v,mapDigits as ee,numeralDigits as te,parseLocaleBracket as ne}from"../calcx/culture/format-locale.js";const C={decimal:".",group:",",months:["January","February","March","April","May","June","July","August","September","October","November","December"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthsWithDay:null,shortMonths:null,shortDays:null,shortDate:"m/d/yyyy",longDate:"dddd, mmmm d, yyyy",longTime:"h:mm:ss AM/PM",amDesignator:"AM",pmDesignator:"PM",tag:null,eras:null,numerals:null};function ye(e){Object.assign(C,e),W.clear()}const N="",Me="[$-F800]dddd, mmmm d, yyyy",De={0:"General",1:"0",2:"0.00",3:"#,##0",4:"#,##0.00",9:"0%",10:"0.00%",11:"0.00E+00",12:"# ?/?",13:"# ??/??",14:"m/d/yyyy",15:"d-mmm-yy",16:"d-mmm",17:"mmm-yy",18:"h:mm AM/PM",19:"h:mm:ss AM/PM",20:"h:mm",21:"h:mm:ss",22:"m/d/yyyy h:mm",37:"#,##0_);(#,##0)",38:"#,##0_);[Red](#,##0)",39:"#,##0.00_);(#,##0.00)",40:"#,##0.00_);[Red](#,##0.00)",41:'_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)',42:'_($* #,##0_);_($* \\(#,##0\\);_($* "-"_);_(@_)',43:'_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)',44:'_($* #,##0.00_);_($* \\(#,##0.00\\);_($* "-"??_);_(@_)',45:"mm:ss",46:"[h]:mm:ss",47:"mm:ss.0",48:"##0.0E+0",49:"@"},q={black:"#000000",blue:"#0000FF",cyan:"#00FFFF",green:"#00FF00",magenta:"#FF00FF",red:"#FF0000",white:"#FFFFFF",yellow:"#FFFF00"},se=["000000","FFFFFF","FF0000","00FF00","0000FF","FFFF00","FF00FF","00FFFF","800000","008000","000080","808000","800080","008080","C0C0C0","808080","9999FF","993366","FFFFCC","CCFFFF","660066","FF8080","0066CC","CCCCFF","000080","FF00FF","FFFF00","00FFFF","800080","800000","008080","0000FF","00CCFF","CCFFFF","CCFFCC","FFFF99","99CCFF","FF99CC","CC99FF","FFCC99","3366FF","33CCCC","99CC00","FFCC00","FF9900","FF6600","666699","969696","003366","339966","003300","333300","993300","993366","333399","333333"];function B(e){const n=[[]];let s=n[0];const l=t=>{const o=s[s.length-1];o&&o.k==="lit"?o.s+=t:s.push({k:"lit",s:t})};for(let t=0;t<e.length;t++){const o=e[t];if((o==="G"||o==="g")&&e.slice(t,t+7).toLowerCase()==="general"){l("General"),t+=6;continue}switch(o){case";":s=[],n.push(s);break;case'"':{const a=e.indexOf('"',t+1);l(a<0?e.slice(t+1):e.slice(t+1,a)),t=a<0?e.length:a;break}case"\\":t+1<e.length&&l(e[++t]);break;case"_":t++,l(" ");break;case"*":s.push({k:"fill",c:e[++t]??" "});break;case"[":{const a=e.indexOf("]",t);if(a<0){l(o);break}const i=e.slice(t+1,a);t=a;const r=i.toLowerCase();if(/^dbnum[1-4]$/.test(r)){s.push({k:"dbnum",n:Number(r[5])});break}if(/^h+$/.test(r)||/^m+$/.test(r)||/^s+$/.test(r))s.push({k:"elapsed",c:r[0],n:r.length});else if(q[r])s.push({k:"color",v:q[r]});else if(/^color\s*\d+$/.test(r)){const u=se[Number(r.replace(/\D/g,""))-1];u&&s.push({k:"color",v:`#${u}`})}else if(/^(<=|>=|<>|<|>|=)\s*-?[\d.]+/.test(i)){const u=/^(<=|>=|<>|<|>|=)\s*(-?[\d.]+(?:[eE][+-]?\d+)?)/.exec(i);s.push({k:"cond",op:u[1],v:Number(u[2])})}else if(i[0]==="$"){const u=ne(i);u?.currency&&l(u.currency),u&&(u.tag||u.calendar||u.numerals||u.system||u.gannen)&&s.push({k:"loc",info:u})}break}case"@":s.push({k:"text"});break;case"#":case"0":case"?":s.push({k:"d",c:o});break;case".":s.push({k:"point"});break;case",":s.push({k:"comma"});break;case"%":s.push({k:"pct"});break;case"/":s.push({k:"slash"});break;case"E":case"e":{const a=e[t+1];if(a==="+"||a==="-")s.push({k:"expCandidate",plus:a==="+",upper:o==="E"}),t++;else if(o==="e"){let i=1;for(;e[t+i]==="e";)i++;s.push({k:"date",c:"e",n:i}),t+=i-1}else l(o);break}case"y":case"Y":case"m":case"M":case"d":case"D":case"h":case"H":case"s":case"S":{const a=o.toLowerCase();let i=1;for(;e[t+i]?.toLowerCase()===a;)i++;s.push({k:"date",c:a,n:i}),t+=i-1;break}case"n":case"N":s.push({k:"lit",s:o,invalidTextFormat:!0});break;case"g":case"G":case"b":case"B":{const a=o.toLowerCase();if(a==="b"&&e[t+1]==="2"){s.push({k:"hijri"}),t++;break}let i=1;for(;e[t+i]?.toLowerCase()===a;)i++;s.push({k:"date",c:a,n:i}),t+=i-1;break}case"A":case"a":case"Å":case"å":{const a=e.slice(t,t+5).toUpperCase();if(/^(?:AAA|ÅÅÅ)/.test(a)){const i=o.toLowerCase();let r=3;for(;e[t+r]?.toLowerCase()===i;)r++;s.push({k:"date",c:"a",n:r}),t+=r-1}else a==="AM/PM"?(s.push({k:"ampm",long:!0}),t+=4):a.startsWith("A/P")?(s.push({k:"ampm",long:!1,lower:o==="a"}),t+=2):l(o);break}default:l(o)}}return n}function ie(e){const n={tokens:e,color:null,cond:null,isDate:!1,isText:!1,isNum:!1,isGeneral:!1},s=[];for(const t of e)t.invalidTextFormat&&(n.invalidTextFormat=!0),t.k==="color"?n.color=t.v:t.k==="cond"?n.cond=t:t.k==="loc"?n.loc=t.info:t.k==="dbnum"?n.dbnum=t.n:t.k==="hijri"?n.hijri=!0:s.push(t);if(n.loc?.system){s.length=0;for(const t of B(n.loc.system==="date"?C.longDate:C.longTime)[0])s.push(t)}n.tokens=s;for(let t=0;t<s.length;t++){const o=s[t];if(o.k==="expCandidate")if(s.slice(0,t).some(a=>a.k==="d")&&s.slice(t+1).some(a=>a.k==="d"))o.k="exp",o.upper||(n.invalidTextFormat=!0);else{const a=o.plus?"+":"-",i=o.upper?[{k:"lit",s:"E"+a}]:[{k:"date",c:"e",n:1},{k:"lit",s:a}];s.splice(t,1,...i)}}const l=s.filter(t=>t.k==="lit").map(t=>t.s).join("");if(n.isDate=s.some(t=>t.k==="date"||t.k==="elapsed"||t.k==="ampm"),n.isText=s.some(t=>t.k==="text"),n.isNum=!n.isDate&&s.some(t=>t.k==="d"),/general/i.test(l)){n.isGeneral=!0;for(const t of s)t.k==="lit"&&(t.s=t.s.replace(/general/i,""))}return n.isDate?le(n):n.isNum&&re(n),n.digits=ae(n),n}const oe=e=>e.op==="<"&&e.v<=0||e.op==="<="&&e.v<0||e.op==="="&&e.v<0;function U(e,n){const s=P(n);return e.dbnum?Q(s,e.dbnum,e.loc?.tag??C.tag)??s:s}function ae(e){if(e.dbnum){const n=Z(e.dbnum,e.loc?.tag??C.tag);if(n)return n}return e.loc?.numerals>1?te(e.loc.numerals):C.numerals??null}function le(e){if(e.tokens.some(a=>a.k==="date"&&a.c==="g")&&O(e.loc,C)){let a=!1;for(const i of e.tokens)i.k==="date"&&i.c==="g"?a=!0:a&&i.k==="date"&&i.c==="y"&&(i.c="e",i.n=2)}const n=e.tokens;let s=null;const l=new Set;let t=!1;for(let a=0;a<n.length;a++){const i=n[a];if(i.k==="date"&&i.c==="m"&&i.n<=2){let r=null;for(let u=a+1;u<n.length;u++)if(n[u].k!=="lit"){r=n[u];break}(s==="h"||s==="s"||(r?.k==="date"||r?.k==="elapsed")&&r.c==="s")&&(i.c="n"),s=null}else(i.k==="date"||i.k==="elapsed")&&(s=i.c==="h"||i.c==="s"?i.c:null);if(i.k==="elapsed")t&&(i.c==="h"||i.c==="m")&&(i.afterSeconds=!0),l.add(i.c);else if(i.k==="date"){i.c==="s"&&(t=!0);const r=i.c==="n"?"m":i.c;l.has(r)&&(i.k="elapsed",i.c=r)}}e.hasDay=n.some(a=>a.k==="date"&&a.c==="d"&&a.n<=2),e.hasCalendar=n.some(a=>a.k==="date"&&"ymdageb".includes(a.c)),e.hour12=n.some(a=>a.k==="ampm"),e.subDigits=0;const o=[];for(let a=0;a<n.length;a++){const i=n[a];if(i.k==="point"&&n[a+1]?.k==="d"){let r=0;for(;n[a+1+r]?.k==="d";)r++;o.push({k:"sub",n:r}),e.subDigits=Math.max(e.subDigits,r),a+=r}else i.k==="point"?o.push({k:"lit",s:"."}):i.k==="slash"?o.push({k:"lit",s:"/"}):i.k==="comma"?o.push({k:"lit",s:","}):i.k==="d"?o.push({k:"lit",s:i.c}):i.k==="pct"?o.push({k:"lit",s:"%"}):o.push(i)}e.tokens=o}function re(e){const n=e.tokens;let s=-1,l=-1,t=-1,o=-1,a=-1;n.forEach((c,b)=>{c.k==="d"?(l<0&&(l=b),s=b):c.k==="point"&&t<0?t=b:c.k==="exp"&&o<0?o=b:c.k==="slash"&&a<0&&l>=0&&(a=b)});let i=0,r=0,u=!1;const m=[];for(let c=0;c<n.length;c++){const b=n[c];if(b.k==="pct")i++,m.push({k:"lit",s:"%"});else if(b.k==="comma"){let M=!1;for(let y=c+1;y<n.length;y++){if(n[y].k==="d"){M=!0;break}if(n[y].k!=="comma")break}if(M&&c>l&&(t<0||c<t))u=!0;else{if(M&&t>=0&&c>t&&(o<0||c<o))continue;c>l&&c<=s+8&&!M?r++:m.push({k:"lit",s:","})}}else b.k==="slash"&&c!==a?m.push({k:"lit",s:"/"}):b.k==="point"&&c!==t?m.push({k:"lit",s:"."}):m.push(b)}e.tokens=m,e.pct=i,e.scale=r,e.grouping=u,e.fraction=a>=0,e.scientific=o>=0,e.exponentPlus=o>=0&&n[o].plus;let h="int";const x={int:0,dec:0,exp:0,num:0,den:0};let F="";for(const c of m)c.k==="point"?h="dec":c.k==="exp"?h="exp":c.k==="slash"?h="den":c.k==="d"?(c.part=h,x[h]++,h==="den"&&(F+=c.c)):c.k==="lit"&&h==="den"&&/^\d+$/.test(c.s)&&(F+=c.s);if(e.fraction){const c=m.findIndex(d=>d.k==="slash");let b=c-1,M=!1;for(;b>=0;){const d=m[b];if(d.k==="d")d.part="num",x.num++,x.int--,M=!0;else if(M)break;b--}e.fixedDen=/^\d+$/.test(F)?Number(F):0,e.denDigits=x.den;const y=m.findLastIndex(d=>d.k==="d"&&d.part==="int"),p=m.findIndex(d=>d.k==="d"&&d.part==="num"),k=m.findLastIndex((d,$)=>$>c&&(d.k==="d"&&d.part==="den"||e.fixedDen&&d.k==="lit"&&/^\d+$/.test(d.s))),_=y<0?p:y+1,w=Math.max(k,c),T=m.slice(_,w+1);e.fractionParts={start:_,end:w,numStart:p,always:T.some(d=>d.part==="num"&&d.c==="0"),pad:m.some(d=>d.k==="d"&&d.c==="?"),width:T.reduce((d,$)=>d+($.k==="lit"?$.s.length:1),0),padWhole:y>=0&&m.slice(0,y+1).some(d=>d.k==="d"&&d.c==="?"),requiredWhole:y>=0&&m.slice(0,y+1).some(d=>d.k==="d"&&d.c==="0"),padNumerator:T.some(d=>d.part==="num"&&d.c==="?"),padDen:T.some(d=>d.part==="den"&&d.c==="0")}}e.counts=x}function G(e,n){if(Number.isInteger(e)&&e<1e15)return{int:e===0?"":String(e),dec:"0".repeat(n)};const s=e.toExponential(14),l=s.indexOf("e"),t=s[0]+s.slice(2,l),a=Number(s.slice(l+1))+1+n;let i,r=!1;if(a<0?i="":a>=t.length?i=t+"0".repeat(a-t.length):(r=t.charCodeAt(a)>=53,i=t.slice(0,a)),r){let F=i.length-1;const c=i.split("");for(;F>=0;)if(c[F]==="9")c[F]="0",F--;else{c[F]=String.fromCharCode(c[F].charCodeAt(0)+1);break}i=c.join(""),F<0&&(i="1"+i)}const m=i.length-n;let h,x;return m<=0?(h="",x="0".repeat(-m)+i):(h=i.slice(0,m),x=i.slice(m)),h=h.replace(/^0+/,""),{int:h,dec:x}}function ce(e){if(e.length<=3)return e;let n="",s=e.length%3;for(s>0&&(n=e.slice(0,s));s<e.length;s+=3)n+=(n?C.group:"")+e.slice(s,s+3);return n}function fe(e,n){if(n.fixedDen>0)return[Math.round(e*n.fixedDen),n.fixedDen];const s=10**n.denDigits-1;let[l,t,o,a]=[0,1,1,0],i=e;for(let r=0;r<32;r++){const u=Math.floor(i),m=u*o+l,h=u*a+t;if(h>s)break;[l,t,o,a]=[o,a,m,h];const x=i-u;if(x<1e-10)break;i=1/x}return[o,a||1]}function ue(e,n){let s=n;e.pct&&(s*=100**e.pct),e.scale&&(s/=1e3**e.scale);const{counts:l}=e;let t="",o="",a="",i=!1,r="",u="";if(e.fraction){const f=l.int>0?Math.floor(s):0,[g,D]=fe(s-f,e);let S=f,A=g;A===D&&l.int>0&&(S+=1,A=0);const L=e.fractionParts,j=A===0&&l.int>0&&!L.always;t=S===0?j||A===0&&(L.padWhole||L.requiredWhole)?"0":"":String(S),r=j?"":String(A),u=j?"":String(D)}else if(e.scientific){let f=s===0?0:Math.floor(Math.log10(s));const g=Math.max(l.int,1);g>1&&(f=Math.floor(f/g)*g);let D=G(s/10**f,l.dec);D.int.length>g&&(f+=g>1?g:1,D=G(s/10**f,l.dec)),t=s===0?"0".repeat(g):D.int,o=D.dec,i=f<0,a=String(Math.abs(f))}else{const f=G(s,l.dec);t=f.int,o=f.dec}let m=o.length,h="";const x=e.tokens,F=[];for(const f of x)f.k==="d"&&f.part==="int"&&F.push(f);const c=new Map;let b=t.length-1;for(let f=F.length-1;f>=0;f--){const g=F[f];if(b>=0){let D=t[b--];f===0&&b>=0&&(D=t.slice(0,b+1)+D,b=-1),c.set(g,D)}else c.set(g,g.c==="0"?"0":g.c==="?"?" ":"")}if(e.grouping&&F.length){let f="";for(const A of F)f+=c.get(A);const g=/^ */.exec(f)[0],D=ce(f.slice(g.length));c.forEach((A,L)=>c.set(L,""));const S=Math.max(0,Math.floor((f.length-1)/3)-Math.floor((f.length-g.length-1)/3));c.set(F[0],g+" ".repeat(S)+D)}const M=[];for(const f of x)f.k==="d"&&f.part==="dec"&&M.push(f);for(let f=M.length-1;f>=0&&o[f]==="0";f--)m=f;let y=0,p=0;const k=x.filter(f=>f.k==="d"&&f.part==="exp").length,_=a.padStart(k,"0");let w=0,T=0;const d=e.fractionParts?.padDen?u.padStart(l.den,"0"):u,$=e.fraction&&r==="",H=t!==""||F.some(f=>f.c==="0");for(let f=0;f<x.length;f++){const g=x[f],D=e.fractionParts;if(D&&f===D.start&&$){D.pad&&(h+=" ".repeat(D.width)),f=D.end;continue}if(D&&f>=D.start&&f<D.numStart&&!H){(D.padWhole||D.padNumerator&&r!=="0")&&g.k==="lit"&&(h+=" ".repeat(g.s.length));continue}switch(g.k){case"lit":h+=g.s===""?"":g.s;break;case"fill":h+=N+g.c+N;break;case"point":F.length===0&&!e.fraction&&!e.scientific&&t!=="0"&&!h.includes(C.decimal)&&(h+=t),h+=C.decimal;break;case"exp":h+=g.upper?"E":"e";break;case"slash":h+="/";break;case"d":switch(g.part){case"int":h+=c.get(g);break;case"dec":{const S=y++;S<m?h+=o[S]:g.c==="?"?h+=" ":g.c==="0"&&(h+="0");break}case"exp":p===0&&(h+=(i?"-":e.exponentPlus?"+":"")+_),p++;break;case"num":{const S=r.length-l.num+w++;S<0?h+=g.c==="#"?"":g.c==="?"?" ":"0":h+=w===1?r.slice(0,S+1):r[S];break}case"den":{h+=d[T++]??(g.c==="?"?" ":""),T===l.den&&d.length>l.den&&(h+=d.slice(l.den));break}default:}break;default:}}return h}const Ce=1462;function he(e,n=0){const s=Math.floor(e);let l=s+n;const t=e-s;let o=Math.round(t*864e5);o>=864e5&&(l+=1,o-=864e5);let a,i,r;if(l===0)a=1900,i=1,r=0;else if(l===60)a=1900,i=2,r=29;else{const m=(l<60?l+1:l)-25569+719468,h=Math.floor(m/146097),x=m-h*146097,F=Math.floor((x-Math.floor(x/1460)+Math.floor(x/36524)-Math.floor(x/146096))/365),c=x-(365*F+Math.floor(F/4)-Math.floor(F/100)),b=Math.floor((5*c+2)/153);r=c-Math.floor((153*b+2)/5)+1,i=b<10?b+3:b-9,a=F+h*400+(i<=2?1:0)}const u=l===0?6:(l-1)%7;return{year:a,month:i,day:r,weekday:u,ms:o,serial:e}}function we(e,n){const s=e.trim().split(/[^0-9]+/).filter(Boolean).map(Number);if(s.length!==3)return null;const l=r=>s[n.indexOf(r)];let t=l("Y");const o=l("M"),a=l("D");if(t<100&&(t+=t<30?2e3:1900),!(o>=1&&o<=12&&a>=1&&a<=new Date(Date.UTC(t,o,0)).getUTCDate()))return null;const i=de(t,o,a);return Number.isFinite(i)?i:null}function de(e,n,s){const l=n<=2?e-1:e,t=n<=2?n+9:n-3,o=Math.floor(l/400),a=l-o*400,i=Math.floor((153*t+2)/5)+s-1,r=a*365+Math.floor(a/4)-Math.floor(a/100)+i,u=o*146097+r-719468+25569;return u<61?u-1:u}const E=e=>e<10?"0"+e:String(e);function Y(e,n,s){const l=86400*10**(e.subDigits??0),t=n*86400;n=Math.round(n*l)/l;const o=he(n,s),a=o.ms;let i=Math.floor(a/1e3);const r=a-i*1e3;let u="";e.subDigits>0?(u=(r/1e3).toFixed(e.subDigits).slice(2),u.length===0&&(u="")):r>=500&&(i+=1);let m=Math.floor(i/3600);const h=Math.floor(i%3600/60),x=i%60;m>=24&&(m=23);const F=e.hour12?m%12===0?12:m%12:m,{loc:c}=e,b=e.hijri&&!c?.tag,M=c?.tag?v(c.tag):b?V():C,y=c?.calendar||b?K(b?"hijri":c.calendar,n+s,o,c?.tag??null)??o:o;let p="";for(const k of e.tokens)switch(k.k){case"lit":p+=k.s;break;case"fill":p+=N+k.c+N;break;case"date":switch(k.c){case"y":p+=k.n<=2?E(y.year%100):String(y.year);break;case"e":{const _=O(c,C);if(_===null){p+=String(y.year);break}const w=o.year-R(_,n+s).firstYear+1;w===1&&c?.gannen?p+="元":p+=k.n===1?w:E(w);break}case"g":{const _=O(c,C);if(_===null)break;const w=R(_,n+s);p+=k.n===1?w.symbol:k.n===2?w.abbreviation:w.name;break}case"b":{const _=c?.tag?o.year:o.year+543;p+=k.n<=2?E(_%100):String(_);break}case"a":p+=k.n===3?M.shortDays?.[o.weekday]??M.days[o.weekday].slice(0,3):M.days[o.weekday];break;case"m":k.n===1?p+=y.month:k.n===2?p+=E(y.month):y.monthName?p+=k.n===5?y.monthName[0]:y.monthName:k.n===3?p+=M.shortMonths?.[y.month-1]??M.months[y.month-1].slice(0,3):k.n===5?p+=M.months[y.month-1][0]:p+=(e.hasDay?M.monthsWithDay??M.months:M.months)[y.month-1];break;case"d":k.n===1?p+=y.day:k.n===2?p+=E(y.day):k.n===3?p+=M.shortDays?.[o.weekday]??M.days[o.weekday].slice(0,3):p+=M.days[o.weekday];break;case"h":p+=k.n===1?F:E(F);break;case"n":p+=k.n===1?h:E(h);break;case"s":p+=k.n===1?x:E(x);break;default:}break;case"elapsed":{const w=Math.floor(n)*86400+i;let T=k.c==="h"?Math.floor(w/3600):k.c==="m"?Math.floor(w/60):w;if(k.afterSeconds){const d=Math.abs(t-Math.round(t))<1e-7?0:t%1;T=Math.floor((x+.5+d)*(k.c==="h"?24:1440))}p+=String(T).padStart(k.n,"0");break}case"ampm":k.long?p+=m<12?c?.tag?M.am:C.amDesignator:c?.tag?M.pm:C.pmDesignator:p+=k.lower?m<12?"a":"p":m<12?"A":"P";break;case"sub":p+=C.decimal+u.slice(0,k.n);break;default:}return p}function me(e){return e.replace(/e([+-])(\d+)$/i,(n,s,l)=>`E${s}${l.padStart(2,"0")}`)}function I(e,n){const[s,l]=e.toExponential(n).split("e");return me(Number(s)+"e"+l).replace(".",C.decimal)}function J(e,n){const s=Number(e.toPrecision(15)).toFixed(n);return s.includes(".")?s.replace(/\.?0+$/,"").replace(".",C.decimal):s}function P(e,n=11){const s=Math.abs(e);if(Number.isInteger(e)&&s<1e11||!Number.isFinite(e))return String(e);const l=Math.max(n-6,0);if(s>=1e11||s<1e-9)return I(e,l);const t=Math.floor(Math.log10(s)),o=Math.max(0,n-(s<1?2:t+1));return t<0&&o+t<l&&Number(e.toFixed(o))!==e?I(e,l):J(e,o)}function pe(e,n){const s=P(e);if(n(s))return s;const l=Math.abs(e);if(l===0)return s;const t=Math.floor(Math.log10(l)),o=!s.includes("E");for(let a=11;a>=1;a--){if(o&&a>t){const i=Math.min(20,a-1-t),r=J(e,i);if(n(r))return r}if(!o||t<0||a<=t){const i=I(e,a-1);if(n(i))return i}}return I(e,0)}class ke{constructor(n){this.code=n;const s=B(n);this.sections=s.slice(0,4).map(ie);const l=this.sections[0];if(this.general=this.sections.length===1&&l.isGeneral&&!l.dbnum&&l.tokens.every(t=>t.k==="lit"&&t.s===""),this.isDate=this.sections.some(t=>t.isDate),this.isText=this.sections.length===1&&l.isText,this.sections.some(t=>t.digits)){const t=this.number;this.number=(o,a)=>{const i=this.sections[this._pick(o)],r=t.call(this,o,a);return i?.digits?ee(r,i.digits):r}}}_pick(n){const s=this.sections;if(s[0].cond!==null||s[1]&&s[1].cond!==null){for(let o=0;o<Math.min(s.length,3);o++){const a=s[o].cond;if(a===null){if(o===s.length-1||o===2||s[o].isText&&o===3)return o;continue}if(Fe(a,n))return o}return s.length===1?-1:Math.min(s.length-1,2)}const t=s.length>1&&s.length<4&&s[s.length-1].isText?s.length-1:s.length;return t===1?0:t===2?n<0?1:0:n>0?0:n<0?1:2}number(n,s=0){if(this.general)return P(n);const l=this._pick(n);if(l===-1)return P(n);const t=this.sections[l],o=this.sections[0].cond!==null||this.sections[1]&&this.sections[1].cond!==null,a=n<0&&(t.cond!==null?!oe(t.cond):l===0||o);if(t.isDate){const r=n<0&&l>0?-n:n;return z(t,r,s)?"#".repeat(8):r<0?`-${Y(t,-r,s)}`:Y(t,r,s)}if(t.isNum){const r=ue(t,Math.abs(n));return a&&be(r)?"-"+r:r}if(t.isGeneral){let r="";for(const u of t.tokens)u.k==="lit"?r+=u.s===""?U(t,Math.abs(n)):u.s.replace("",U(t,Math.abs(n))):u.k==="fill"&&(r+=N+u.c+N);return n<0&&l===0?"-"+r:r}let i=a?"-":"";for(const r of t.tokens)r.k==="lit"?i+=r.s:r.k==="fill"?i+=N+r.c+N:r.k==="pct"?i+="%":r.k==="text"&&(i+=P(Math.abs(n)));return i}dateOverflow(n,s=0){if(this.general)return!1;const l=this._pick(n),t=this.sections[l];return!!t?.isDate&&z(t,n<0&&l>0?-n:n,s)}hasCalendarDate(n){return this.sections[this._pick(n)]?.hasCalendar===!0}numberForText(n,s){const l=this.sections[this._pick(n)];return this.sections.some(t=>t.invalidTextFormat)||this.dateOverflow(n,s)?null:this.general||l===void 0?pe(n,t=>t.length<=(n<0?12:11)):this.number(n,s)}text(n){const s=this.sections,l=s.length===4?s[3]:s.length===1&&s[0].isText?s[0]:null;if(l===null)return n;let t="";for(const o of l.tokens)o.k==="lit"?t+=o.s:o.k==="text"?t+=n:o.k==="fill"&&(t+=N+o.c+N);return t}color(n){return this.sections[this._pick(n)]?.color??null}}const ge=2958466;function z(e,n,s){return e.tokens.some(t=>t.k==="date"||t.k==="ampm")?s===0&&n<0||Math.abs(n)>=ge-s:!1}function be(e){for(let n=0;n<e.length;n++){const s=e.charCodeAt(n);if(s>=49&&s<=57)return!0}return!1}function Fe(e,n){switch(e.op){case"<":return n<e.v;case"<=":return n<=e.v;case">":return n>e.v;case">=":return n>=e.v;case"=":return n===e.v;default:return n!==e.v}}const W=new Map;function X(e){let n=W.get(e);return n===void 0&&(n=new ke(e==="m/d/yyyy"?C.shortDate:e==="m/d/yyyy h:mm"?`${C.shortDate} h:mm`:e),W.set(e,n)),n}function _e(e,n,s=0){return X(e).number(n,s)}function Se(e){return X("#,##0").number(e)}export{De as BUILTIN_FORMATS,Ce as DATE_1904_OFFSET,N as FILL_MARK,Me as SYSTEM_LONG_DATE,we as dateSerial,me as excelExponent,pe as fitGeneral,Se as formatCount,P as formatGeneral,_e as formatNumber,X as getFormatter,de as partsToSerial,he as serialToParts,ye as setNumberLocale};
@@ -1 +1 @@
1
- import{parseInput as v}from"./input.js";import{NUM as F}from"./sheet.js";const u=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),M=new Set([" "," "," "]),O=r=>r.replace(/\B(?=(\d{3})+(?!\d))/g,",");function q(r){const{decimal:$,order:f}=r,a=r.group===$?"":r.group,c=M.has(a)?"[\\s\\u00a0\\u202f]":a?u(a):null,d=u($),l=`(?:\\d+(?:${d}\\d*)?|${d}\\d+)`,i=c?`(?:\\d{1,3}(?:${c}\\d{3})+(?:${d}\\d*)?|${l})`:l,S=c?new RegExp(c):null,g=c?new RegExp(c,"g"):null,B=new RegExp(`^([+-]?)(${i})(%?)$`),I=new RegExp(`^([+-]?${l})[eE]([+-]?\\d+)$`),y=r.currency?.symbol??"$",b=u(y),A=new RegExp(`^(${i})\\s?${b}$`),C=new RegExp(`^${b}\\s?(${i})$`),E=r.dateSep??"/",w=`(?:/|-|${u(E)})`,x=E==="."?"\\.?":"",D=new RegExp(`^(\\d{4})(${w})(\\d{1,2})\\2(\\d{1,2})${x}$`),G=new RegExp(`^(\\d{1,2})(${w})(\\d{1,2})(?:\\2(\\d{1,4}))?${x}$`),R=n=>Object.fromEntries(n.map((t,p)=>[t,[1,3,4][p]])),j=R(f),k=R(f.filter(n=>n!=="year")),h=n=>(g?n.replace(g,""):n).replace($,".");return n=>{if(n===""||n[0]==="'"||n[0]==="=")return n;const t=n.trim(),p=o=>v(o).kind===F?o:n;let e=B.exec(t);if(e){const o=h(e[2]);if(S?.test(e[2])){const[m,s]=o.split(".");return`${e[1]}${O(m)}${s===void 0?"":`.${s}`}${e[3]}`}return`${e[1]}${o}${e[3]}`}if(e=I.exec(t),e)return`${e[1].replace($,".")}e${e[2]}`;if(e=A.exec(t)??C.exec(t),e)return`${h(e[1])} ${y}`;if(e=D.exec(t),e)return p(`${e[1]}-${e[3]}-${e[4]}`);if(e=G.exec(t),e){const{month:o,day:m,year:s}=e[4]===void 0?k:j,N=`${Number(e[o])}/${Number(e[m])}`;return p(s?`${N}/${e[s]}`:N)}return n}}export{q as regionInput};
1
+ import{fullYear as U,parseInput as y}from"./input.js";import{NUM as k}from"./sheet.js";const l=r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),q=new Set([" "," "," "]),z=r=>r.replace(/\B(?=(\d{3})+(?!\d))/g,",");function K(r){const{decimal:$,order:E}=r,a=r.group===$?"":r.group,c=q.has(a)?"[\\s\\u00a0\\u202f]":a?l(a):null,p=l($),m=`(?:\\d+(?:${p}\\d*)?|${p}\\d+)`,i=c?`(?:\\d{1,3}(?:${c}\\d{3})+(?:${p}\\d*)?|${m})`:m,A=c?new RegExp(c):null,w=c?new RegExp(c,"g"):null,C=new RegExp(`^([+-]?)\\s*(${i})(%?)$`),D=new RegExp(`^([+-]?${m})[eE]([+-]?\\d+)$`),R=r.currency?.symbol??"$",x=l(R),G=new RegExp(`^(${i})\\s?${x}$`),Y=new RegExp(`^${x}\\s?(${i})$`),N=r.dateSep??"/",f=`(?:/|-|${l(N)})`,h=N==="."?"\\.?":"",j=new RegExp(`^(\\d{4})(${f})(\\d{1,2})\\2(\\d{1,2})${h}$`),v=new RegExp(`^(\\d{1,2})(${f})(\\d{1,2})(?:\\2(\\d{1,4}))?${h}$`),F=new RegExp(`^(\\d{1,2})${f}(\\d{4})$`),S=n=>Object.fromEntries(n.map((t,s)=>[t,[1,3,4][s]])),M=S(E),O=S(E.filter(n=>n!=="year")),B=n=>(w?n.replace(w,""):n).replace($,"."),P=$==="."?null:/\d[.,]|[.,]\d/,u=n=>P?.test(n)&&y(n).kind===k?`'${n}`:n;return n=>{if(n===""||n[0]==="'"||n[0]==="=")return n;const t=n.trim(),s=o=>y(o).kind===k?o:null;let e=C.exec(t);if(e){const o=B(e[2]);if(A?.test(e[2])){const[g,d]=o.split(".");return`${e[1]}${z(g)}${d===void 0?"":`.${d}`}${e[3]}`}return`${e[1]}${o}${e[3]}`}if(e=D.exec(t),e)return`${e[1].replace($,".")}e${e[2]}`;if(e=G.exec(t)??Y.exec(t),e)return`${B(e[1])} ${R}`;if(e=j.exec(t),e)return s(`${e[1]}-${e[3]}-${e[4]}`)??u(n);if(e=v.exec(t),e){const{month:o,day:g,year:d}=e[4]===void 0?O:M,b=`${Number(e[o])}/${Number(e[g])}`,I=d?s(`${b}/${e[d]}`):y(b).format==="d-mmm"?b:null;return I!==null?I:e[4]===void 0&&e[3].length===2?s(`${Number(e[1])}/${U(e[3])}`)??u(n):u(n)}return e=F.exec(t),e?s(`${Number(e[1])}/${e[2]}`)??u(n):u(n)}}export{K as regionInput};
package/core/sheet.js CHANGED
@@ -1 +1 @@
1
- import{Axis as A}from"./axis.js";import{MAX_COLS as R,MAX_ROWS as N}from"./address.js";import{FormulaStore as S}from"./formula-store.js";const u=10,M=1<<u,g=M-1,H=0,O=1,V=2,Y=3,j=4,W=8,X=16,Z=32,b=64,K=7,v=15,q=["#NULL!","#DIV/0!","#VALUE!","#REF!","#NAME?","#NUM!","#N/A","#GETTING_DATA","#SPILL!","#CALC!","#BUSY!","#CONNECT!","#BLOCKED!","#FIELD!","#UNKNOWN!"];class z{constructor(){this.kinds=new Uint8Array(M),this.values=new Float64Array(M),this.styles=null}}function E(a,t,e,s,n,l){const o=(h,m)=>{if(!s||h<0||h>=e||s.sizeOf(h)>0)return h;const x=s.offsetOf(h)-(m<0?1:0);return x<0?-1:x>=s.total?e:s.indexAt(x)},r=o(t>0?e-1:0,-t);if((r-a)*t<=0)return a;let i=o(a+t,t);if(n(a)&&n(i)){for(;i!==r;){const h=o(i+t,t);if(!n(h))break;i=h}return i}for(;(r-i)*t>=0;){if(n(i))return i;i=o(l(i),t)}return r}let D=1;class J{constructor(t){this.uid=D++,this.name=t,this.rowExtras=null,this.colExtras=null,this.valueMeta=null,this.columns=[],this.maxRow=-1,this.maxCol=-1,this.rows=new A(N,16),this.cols=new A(R,65),this._formulas=new S,this.spills=null,this.rowStyles=null,this.colStyles=null,this.merges=[],this.cellTypes=null,this.sparkRules=null,this.cellDropdowns=null,this.cellTags=null,this.cellPicOpts=null,this.cellButtons=null,this.cellStates=null,this.changes=null,this.autoMerges=null,this.background=null,this.outlineColumn=null,this.split=null,this.frozenTrailingRows=0,this.frozenTrailingCols=0,this.axisSizing=null,this.hideZeros=!1,this.mergeIndex=null,this.frozenRows=0,this.frozenCols=0,this.showGridlines=!0,this.zoom=1,this.sourceId=null,this.revision=0}_chunk(t,e){const s=this.columns[e];return s===void 0?void 0:s[t>>>u]}_ensure(t,e){let s=this.columns[e];s===void 0&&(s=[],this.columns[e]=s);const n=t>>>u;let l=s[n];return l===void 0&&(l=new z,s[n]=l),l}kind(t,e){const s=this._chunk(t,e);return s===void 0?0:s.kinds[t&g]}value(t,e){const s=this._chunk(t,e);return s===void 0?0:s.values[t&g]}style(t,e){const s=this._chunk(t,e);if(s!==void 0&&s.styles!==null){const n=s.styles[t&g];if(n!==0)return n}if(this.rowStyles!==null){const n=this.rowStyles.get(t);if(n!==void 0)return n}if(this.colStyles!==null){const n=this.colStyles.get(e);if(n!==void 0)return n}return 0}cellStyle(t,e){const s=this._chunk(t,e);return s===void 0||s.styles===null?0:s.styles[t&g]}get formulas(){return this._formulas}set formulas(t){this._formulas=t instanceof S?t:S.from(t)}formula(t,e){return this._formulas.at(t,e)}setCell(t,e,s,n){const l=this._ensure(t,e),o=t&g;l.kinds[o]=s,l.values[o]=n,t>this.maxRow&&(this.maxRow=t),e>this.maxCol&&(this.maxCol=e)}setStyle(t,e,s){const n=this._ensure(t,e);if(n.styles===null){if(s===0)return;n.styles=new Uint16Array(M)}n.styles[t&g]=s,t>this.maxRow&&(this.maxRow=t),e>this.maxCol&&(this.maxCol=e)}setFormula(t,e,s){s?this._formulas.put(t,e,s):this._formulas.remove(t,e)}applyBatch(t){const{rows:e,cols:s,kinds:n,values:l,styles:o,count:r}=t;let i=-1,h=-1,m=null,x=this.maxRow,p=this.maxCol;for(let c=0;c<r;c++){const d=e[c],f=s[c],y=d>>>u;(f!==i||y!==h)&&(m=this._ensure(d,f),i=f,h=y);const k=d&g;m.kinds[k]=n[c],m.values[k]=l[c];const _=o[c];_!==0&&(m.styles===null&&(m.styles=new Uint16Array(M)),m.styles[k]=_),f>p&&(p=f)}if(r>0&&e[r-1]>x&&(x=e[r-1]),this.maxRow=x,this.maxCol=p,t.formulas){const c=this._formulas;for(const[d,f]of t.formulas)c.set(d,f)}if(t.valueMeta){this.valueMeta===null&&(this.valueMeta=new Map);for(const[c,d]of t.valueMeta)this.valueMeta.set(c,d)}this.revision++}addMerge(t){this.merges.push(t),this.mergeIndex=null}removeMergesIn(t){const e=this.merges.length;this.merges=this.merges.filter(s=>!B(s,t)),this.merges.length!==e&&(this.mergeIndex=null)}_buildMergeIndex(){const t=new Map;for(const e of this.merges)for(let s=e.r0>>>u;s<=e.r1>>>u;s++){const n=t.get(s);n?n.push(e):t.set(s,[e])}this.mergeIndex=t}mergeAt(t,e){if(this.merges.length===0)return null;this.mergeIndex===null&&this._buildMergeIndex();const s=this.mergeIndex.get(t>>>u);if(s===void 0)return null;for(let n=0;n<s.length;n++){const l=s[n];if(t>=l.r0&&t<=l.r1&&e>=l.c0&&e<=l.c1)return l}return null}mergesInRows(t,e){if(this.merges.length===0)return[];this.mergeIndex===null&&this._buildMergeIndex();const s=new Set;for(let n=t>>>u;n<=e>>>u;n++){const l=this.mergeIndex.get(n);if(l)for(const o of l)o.r1>=t&&o.r0<=e&&s.add(o)}return[...s]}jumpRow(t,e,s,n=!1){const l=this.columns[e],o=i=>{const h=l?.[i>>>u];return h!==void 0&&(h.kinds[i&g]&v)!==0},r=i=>l?.[i>>>u]!==void 0?i+s:s>0?(i>>>u)+1<<u:(i>>>u<<u)-1;return E(t,s,n?this.rows.count:N,n&&this.rows,o,r)}jumpCol(t,e,s,n=!1){const l=r=>(this.kind(t,r)&v)!==0,o=r=>s>0&&r>=this.maxCol?R:r+s;return E(e,s,n?this.cols.count:R,n&&this.cols,l,o)}aggregate(t){let e=0,s=0,n=0,l=1/0,o=-1/0;for(const{r0:r,c0:i,r1:h,c1:m}of t){const x=Math.min(m,this.maxCol),p=Math.min(h,this.maxRow);for(let c=i;c<=x;c++){const d=this.columns[c];if(d!==void 0)for(let f=r>>>u;f<=p>>>u;f++){const y=d[f];if(y===void 0)continue;const k=f<<u,_=Math.max(r-k,0),T=Math.min(p-k,g),{kinds:U,values:L}=y;for(let I=_;I<=T;I++){const w=U[I]&K;if(w!==0&&(n++,w===O)){const C=L[I];e+=C,s++,C<l&&(l=C),C>o&&(o=C)}}}}}return{sum:e,numeric:s,filled:n,min:l,max:o}}}function B(a,t){return a.r0<=t.r1&&a.r1>=t.r0&&a.c0<=t.c1&&a.c1>=t.c0}export{Y as BOOL,u as CHUNK_BITS,g as CHUNK_MASK,M as CHUNK_SIZE,v as CONTENT_MASK,Z as DIRTY,H as EMPTY,j as ERR,q as ERRORS,b as EVALUATING,W as FORMULA,K as KIND_MASK,O as NUM,X as SPILL,V as STR,J as Sheet,B as rangesTouch};
1
+ import{Axis as w}from"./axis.js";import{MAX_COLS as I,MAX_ROWS as A}from"./address.js";import{FormulaStore as S}from"./formula-store.js";const u=10,M=1<<u,g=M-1,H=0,O=1,V=2,Y=3,j=4,W=8,X=16,Z=32,b=64,K=7,N=15,q=["#NULL!","#DIV/0!","#VALUE!","#REF!","#NAME?","#NUM!","#N/A","#GETTING_DATA","#SPILL!","#CALC!","#BUSY!","#CONNECT!","#BLOCKED!","#FIELD!","#UNKNOWN!"];class z{constructor(){this.kinds=new Uint8Array(M),this.values=new Float64Array(M),this.styles=null}}function E(m,t,e,s,n,l){const i=(f,d)=>{if(!s||f<0||f>=e||s.sizeOf(f)>0)return f;const x=s.offsetOf(f)-(d<0?1:0);return x<0?-1:x>=s.total?e:s.indexAt(x)},r=i(t>0?e-1:0,-t);if((r-m)*t<=0)return m;let o=i(m+t,t);if(n(m)&&n(o)){for(;o!==r;){const f=i(o+t,t);if(!n(f))break;o=f}return o}for(;(r-o)*t>=0;){if(n(o))return o;o=i(l(o),t)}return r}let D=1;class J{constructor(t){this.uid=D++,this.name=t,this.rowExtras=null,this.colExtras=null,this.valueMeta=null,this.columns=[],this.maxRow=-1,this.maxCol=-1,this.rows=new w(A,16),this.cols=new w(I,65),this._formulas=new S,this.spills=null,this.rowStyles=null,this.colStyles=null,this.merges=[],this.cellTypeRules=null,this.cellTypes=null,this.sparkRules=null,this.cellDropdowns=null,this.cellTags=null,this.cellPicOpts=null,this.cellButtons=null,this.cellStates=null,this.changes=null,this.autoMerges=null,this.background=null,this.outlineColumn=null,this.split=null,this.frozenTrailingRows=0,this.frozenTrailingCols=0,this.axisSizing=null,this.hideZeros=!1,this.mergeIndex=null,this.frozenRows=0,this.frozenCols=0,this.showGridlines=!0,this.zoom=1,this.sourceId=null,this.revision=0}_chunk(t,e){const s=this.columns[e];return s===void 0?void 0:s[t>>>u]}_ensure(t,e){let s=this.columns[e];s===void 0&&(s=[],this.columns[e]=s);const n=t>>>u;let l=s[n];return l===void 0&&(l=new z,s[n]=l),l}kind(t,e){const s=this._chunk(t,e);return s===void 0?0:s.kinds[t&g]}value(t,e){const s=this._chunk(t,e);return s===void 0?0:s.values[t&g]}style(t,e){const s=this._chunk(t,e);if(s!==void 0&&s.styles!==null){const n=s.styles[t&g];if(n!==0)return n}if(this.rowStyles!==null){const n=this.rowStyles.get(t);if(n!==void 0)return n}if(this.colStyles!==null){const n=this.colStyles.get(e);if(n!==void 0)return n}return 0}cellStyle(t,e){const s=this._chunk(t,e);return s===void 0||s.styles===null?0:s.styles[t&g]}get formulas(){return this._formulas}set formulas(t){this._formulas=t instanceof S?t:S.from(t)}formula(t,e){return this._formulas.at(t,e)}setCell(t,e,s,n){const l=this._ensure(t,e),i=t&g;if(this.valueListeners&&(l.kinds[i]!==s||l.values[i]!==n))for(const r of this.valueListeners)r(t,e,t,e);l.kinds[i]=s,l.values[i]=n,t>this.maxRow&&(this.maxRow=t),e>this.maxCol&&(this.maxCol=e)}setStyle(t,e,s){const n=this._ensure(t,e);if(n.styles===null){if(s===0)return;n.styles=new Uint16Array(M)}n.styles[t&g]=s,t>this.maxRow&&(this.maxRow=t),e>this.maxCol&&(this.maxCol=e)}setFormula(t,e,s){s?this._formulas.put(t,e,s):this._formulas.remove(t,e)}applyBatch(t){const{rows:e,cols:s,kinds:n,values:l,styles:i,count:r}=t;let o=-1,f=-1,d=null,x=this.maxRow,p=this.maxCol;for(let h=0;h<r;h++){const c=e[h],a=s[h],k=c>>>u;(a!==o||k!==f)&&(d=this._ensure(c,a),o=a,f=k);const y=c&g;d.kinds[y]=n[h],d.values[y]=l[h];const _=i[h];_!==0&&(d.styles===null&&(d.styles=new Uint16Array(M)),d.styles[y]=_),a>p&&(p=a)}if(this.valueListeners)for(const h of this.valueListeners)for(let c=0;c<r;c++)h(e[c],s[c],e[c],s[c]);if(r>0&&e[r-1]>x&&(x=e[r-1]),this.maxRow=x,this.maxCol=p,t.formulas){const h=this._formulas;for(const[c,a]of t.formulas)h.set(c,a)}if(t.valueMeta){this.valueMeta===null&&(this.valueMeta=new Map);for(const[h,c]of t.valueMeta)this.valueMeta.set(h,c)}this.revision++}addMerge(t){this.merges.push(t),this.mergeIndex=null}removeMergesIn(t){const e=this.merges.length;this.merges=this.merges.filter(s=>!B(s,t)),this.merges.length!==e&&(this.mergeIndex=null)}_buildMergeIndex(){const t=new Map;for(const e of this.merges)for(let s=e.r0>>>u;s<=e.r1>>>u;s++){const n=t.get(s);n?n.push(e):t.set(s,[e])}this.mergeIndex=t}mergeAt(t,e){if(this.merges.length===0)return null;this.mergeIndex===null&&this._buildMergeIndex();const s=this.mergeIndex.get(t>>>u);if(s===void 0)return null;for(let n=0;n<s.length;n++){const l=s[n];if(t>=l.r0&&t<=l.r1&&e>=l.c0&&e<=l.c1)return l}return null}mergesInRows(t,e){if(this.merges.length===0)return[];this.mergeIndex===null&&this._buildMergeIndex();const s=new Set;for(let n=t>>>u;n<=e>>>u;n++){const l=this.mergeIndex.get(n);if(l)for(const i of l)i.r1>=t&&i.r0<=e&&s.add(i)}return[...s]}jumpRow(t,e,s,n=!1){const l=this.columns[e],i=o=>{const f=l?.[o>>>u];return f!==void 0&&(f.kinds[o&g]&N)!==0},r=o=>l?.[o>>>u]!==void 0?o+s:s>0?(o>>>u)+1<<u:(o>>>u<<u)-1;return E(t,s,n?this.rows.count:A,n&&this.rows,i,r)}jumpCol(t,e,s,n=!1){const l=r=>(this.kind(t,r)&N)!==0,i=r=>s>0&&r>=this.maxCol?I:r+s;return E(e,s,n?this.cols.count:I,n&&this.cols,l,i)}aggregate(t){let e=0,s=0,n=0,l=1/0,i=-1/0;for(const{r0:r,c0:o,r1:f,c1:d}of t){const x=Math.min(d,this.maxCol),p=Math.min(f,this.maxRow);for(let h=o;h<=x;h++){const c=this.columns[h];if(c!==void 0)for(let a=r>>>u;a<=p>>>u;a++){const k=c[a];if(k===void 0)continue;const y=a<<u,_=Math.max(r-y,0),L=Math.min(p-y,g),{kinds:T,values:U}=k;for(let R=_;R<=L;R++){const v=T[R]&K;if(v!==0&&(n++,v===O)){const C=U[R];e+=C,s++,C<l&&(l=C),C>i&&(i=C)}}}}}return{sum:e,numeric:s,filled:n,min:l,max:i}}}function B(m,t){return m.r0<=t.r1&&m.r1>=t.r0&&m.c0<=t.c1&&m.c1>=t.c0}export{Y as BOOL,u as CHUNK_BITS,g as CHUNK_MASK,M as CHUNK_SIZE,N as CONTENT_MASK,Z as DIRTY,H as EMPTY,j as ERR,q as ERRORS,b as EVALUATING,W as FORMULA,K as KIND_MASK,O as NUM,X as SPILL,V as STR,J as Sheet,B as rangesTouch};
package/core/sparse.js CHANGED
@@ -1 +1 @@
1
- const H=16384,y=["cellTypes","cellDropdowns","cellTags","cellButtons"],k=new Set,U=(n,o)=>n*16384+o,b=[];function L(n,{moved:o=!0}={}){y.includes(n)||y.push(n),o||k.add(n)}const v=n=>{for(const o of y)if(n[o])return!0;return!1};function M(n){const o={};for(const t of y)o[t]=n[t]??null;return o}const C=n=>o=>{const t=C(M(o));for(const c of y)o[c]=n[c];return o.cellTypesChanged=!0,t},m=()=>m,N=n=>C(M(n)),O=n=>M(n);function V(n,o,t,c,p=2e6){const i=C(M(n)),r=new Map(n[o]??[]);let a=0;for(const{r0:l,c0:e,r1:s,c1:d}of t){const x=Math.min(s,Math.max(n.maxRow,l)),f=Math.min(d,Math.max(n.maxCol,e));for(let u=l;u<=x&&a<p;u++)for(let w=e;w<=f&&a<p;w++,a++)c===void 0?r.delete(u*16384+w):r.set(u*16384+w,c)}return n[o]=r.size>0?r:null,n.cellTypesChanged=!0,i}function B(n,o,t){return t>0?n>=o?n+t:n:n>=o-t?n+t:n>=o?-1:n}function W(n,o){if(!v(n))return m;const t=C(M(n)),c=o.axis==="row";for(const p of y){if(k.has(p))continue;const i=n[p];if(!i)continue;const r=new Map;for(const[a,l]of i){const e=Math.floor(a/16384),s=a-e*16384,d=c?s:e;if(o.span&&(d<o.span[0]||d>o.span[1])){r.set(a,l);continue}const x=B(c?e:s,o.at,o.n);x<0||r.set(c?x*16384+s:e*16384+x,l)}n[p]=r.size>0?r:null}return n.cellTypesChanged=!0,t}function X(n,o,t,c,p,i,r="row"){if(!v(n))return m;const a=C(M(n));for(const l of y){if(k.has(l))continue;const e=n[l];if(!e)continue;const s=new Map;for(const[d,x]of e){const f=Math.floor(d/16384),u=d-f*16384;f>=o&&f<=t&&u>=c&&u<=p?s.set(r==="row"?(o+i[f-o])*16384+u:f*16384+c+i[u-c],x):s.set(d,x)}n[l]=s}return n.cellTypesChanged=!0,a}function j(n,o,t,c,{cut:p=!1,transpose:i=!1}={}){if(!v(n)&&!v(o))return m;const r=C(M(o)),a=n===o?null:C(M(n)),l=t.r1-t.r0+1,e=t.c1-t.c0+1,s=c.r1-c.r0+1,d=c.c1-c.c0+1;for(const f of y){const u=n[f],w=o[f];if(!u&&!w)continue;const T=[];if(u)for(const[E,K]of u){const Y=Math.floor(E/16384),S=E-Y*16384;Y>=t.r0&&Y<=t.r1&&S>=t.c0&&S<=t.c1&&T.push([Y-t.r0,S-t.c0,K])}const h=new Map(w??[]);if(p&&n===o)for(const[E,K]of T)h.delete((t.r0+E)*16384+t.c0+K);for(let E=c.r0;E<=c.r1;E++)for(let K=c.c0;K<=c.c1;K++)h.delete(E*16384+K);if(T.length>0){const E=i?e:l,K=i?l:e;for(let Y=0;Y+E<=s||Y===0;Y+=E)for(let S=0;S+K<=d||S===0;S+=K)for(const[z,R,D]of T){const _=c.r0+Y+(i?R:z),A=c.c0+S+(i?z:R);h.set(_*16384+A,D)}}if(o[f]=h.size>0?h:null,p&&n!==o&&u){const E=new Map(u);for(const[K,Y]of T)E.delete((t.r0+K)*16384+t.c0+Y);n[f]=E.size>0?E:null}}if(o.cellTypesChanged=!0,n.cellTypesChanged=!0,a===null)return r;const x=(f,u)=>w=>x(f(o),u(n))??w;return x(r,a)}function q(n,o,t){if(!v(n))return m;const c=C(M(n)),p=o.r1-o.r0+1,i=o.c1-o.c0+1;for(const r of y){const a=n[r];if(!a)continue;const l=new Map(a);for(let e=t.r0;e<=t.r1;e++)for(let s=t.c0;s<=t.c1;s++){if(e>=o.r0&&e<=o.r1&&s>=o.c0&&s<=o.c1)continue;const d=o.r0+((e-o.r0)%p+p)%p,x=o.c0+((s-o.c0)%i+i)%i,f=a.get(d*16384+x);f===void 0?l.delete(e*16384+s):l.set(e*16384+s,f)}n[r]=l.size>0?l:null}return n.cellTypesChanged=!0,c}export{j as copySparseBlock,q as fillSparse,m as noUndo,X as permuteSparse,L as registerSparseMap,V as setSparse,b as sheetRenameHooks,W as shiftSparse,U as sparseKey,O as sparseState,N as sparseUndo};
1
+ import{copyTypeRules as h,shiftedTypeRules as O,sortedTypeRules as U}from"./cell-type-rules.js";const t=16384,v=["cellTypes","cellDropdowns","cellTags","cellButtons"],D=new Set,L=(n,o)=>n*t+o,N=[];function V(n,{moved:o=!0}={}){v.includes(n)||v.push(n),o||D.add(n)}const z=n=>{for(const o of v)if(n[o])return!0;return!!n.cellTypeRules};function S(n){const o={cellTypeRules:n.cellTypeRules??null};for(const c of v)o[c]=n[c]??null;return o}const E=n=>o=>{const c=E(S(o));return Object.assign(o,n),o.cellTypesChanged=!0,c},B=()=>B,W=n=>E(S(n)),X=n=>S(n);function q(n,o,c,e,i=2e6){const u=E(S(n)),f=new Map(n[o]??[]);let d=0;for(const{r0:p,c0:l,r1:s,c1:T}of c){const M=Math.min(s,Math.max(n.maxRow,p)),a=Math.min(T,Math.max(n.maxCol,l));for(let y=p;y<=M&&d<i;y++)for(let R=l;R<=a&&d<i;R++,d++)e===void 0?f.delete(y*t+R):f.set(y*t+R,e)}return n[o]=f.size>0?f:null,n.cellTypesChanged=!0,u}function Y(n,o,c){return c>0?n>=o?n+c:n:n>=o-c?n+c:n>=o?-1:n}function F(n,o){if(!z(n))return B;const c=E(S(n));n.cellTypeRules=O(n.cellTypeRules,o);const e=o.axis==="row";for(const i of v){if(D.has(i))continue;const u=n[i];if(!u)continue;const f=new Map;for(const[d,p]of u){const l=Math.floor(d/t),s=d-l*t,T=e?s:l;if(o.span&&(T<o.span[0]||T>o.span[1])){f.set(d,p);continue}const M=Y(e?l:s,o.at,o.n);M<0||f.set(e?M*t+s:l*t+M,p)}n[i]=f.size>0?f:null}return n.cellTypesChanged=!0,c}function G(n,o,c,e,i,u,f="row"){if(!z(n))return B;const d=E(S(n));n.cellTypeRules=U(n.cellTypeRules,{r0:o,r1:c,c0:e,c1:i},u,f);for(const p of v){if(D.has(p))continue;const l=n[p];if(!l)continue;const s=new Map;for(const[T,M]of l){const a=Math.floor(T/t),y=T-a*t;a>=o&&a<=c&&y>=e&&y<=i?s.set(f==="row"?(o+u[a-o])*t+y:a*t+e+u[y-e],M):s.set(T,M)}n[p]=s}return n.cellTypesChanged=!0,d}function I(n,o,c,e,{cut:i=!1,transpose:u=!1}={}){if(!z(n)&&!z(o))return B;const f=E(S(o)),d=n===o?null:E(S(n)),p=c.r1-c.r0+1,l=c.c1-c.c0+1;h(n,o,c,e,{cut:i,transpose:u});const s=e.r1-e.r0+1,T=e.c1-e.c0+1;for(const a of v){const y=n[a],R=o[a];if(!y&&!R)continue;const m=[];if(y)for(const[r,x]of y){const w=Math.floor(r/t),k=r-w*t;w>=c.r0&&w<=c.r1&&k>=c.c0&&k<=c.c1&&m.push([w-c.r0,k-c.c0,x])}const C=new Map(R??[]);if(i&&n===o)for(const[r,x]of m)C.delete((c.r0+r)*t+c.c0+x);if(C.size<s*T)for(const r of C.keys()){const x=Math.floor(r/t),w=r%t;x>=e.r0&&x<=e.r1&&w>=e.c0&&w<=e.c1&&C.delete(r)}else for(let r=e.r0;r<=e.r1;r++)for(let x=e.c0;x<=e.c1;x++)C.delete(r*t+x);if(m.length>0){const r=u?l:p,x=u?p:l;for(let w=0;w+r<=s||w===0;w+=r)for(let k=0;k+x<=T||k===0;k+=x)for(const[_,b,A]of m){const H=e.r0+w+(u?b:_),K=e.c0+k+(u?_:b);C.set(H*t+K,A)}}if(o[a]=C.size>0?C:null,i&&n!==o&&y){const r=new Map(y);for(const[x,w]of m)r.delete((c.r0+x)*t+c.c0+w);n[a]=r.size>0?r:null}}if(o.cellTypesChanged=!0,n.cellTypesChanged=!0,d===null)return f;const M=(a,y)=>R=>M(a(o),y(n))??R;return M(f,d)}function J(n,o,c){if(!z(n))return B;const e=E(S(n));h(n,n,o,c,{fill:!0});const i=o.r1-o.r0+1,u=o.c1-o.c0+1;for(const f of v){const d=n[f];if(!d)continue;const p=new Map(d);for(let l=c.r0;l<=c.r1;l++)for(let s=c.c0;s<=c.c1;s++){if(l>=o.r0&&l<=o.r1&&s>=o.c0&&s<=o.c1)continue;const T=o.r0+((l-o.r0)%i+i)%i,M=o.c0+((s-o.c0)%u+u)%u,a=d.get(T*t+M);a===void 0?p.delete(l*t+s):p.set(l*t+s,a)}n[f]=p.size>0?p:null}return n.cellTypesChanged=!0,e}export{I as copySparseBlock,J as fillSparse,B as noUndo,G as permuteSparse,V as registerSparseMap,q as setSparse,N as sheetRenameHooks,F as shiftSparse,L as sparseKey,X as sparseState,W as sparseUndo};
package/core/structure.js CHANGED
@@ -1 +1 @@
1
- import{CHUNK_BITS as v,CHUNK_MASK as A,CHUNK_SIZE as q,FORMULA as ln,STR as sn}from"./sheet.js";import{FormulaStore as D}from"./formula-store.js";import{cellRef as B,MAX_COLS as w,MAX_ROWS as k,parseCellRef as L,parseRangeRef as X,rangeRef as H}from"./address.js";import{translateFormula as on}from"./formula-refs.js";import{adjustFormula as T,adjustRange as O}from"../calc/adjust.js";import{clonePageSetup as en,shiftPageSetup as an}from"../print/page-setup.js";import{shiftSparse as cn}from"./sparse.js";import{shiftRuleFormulas as un}from"../cells/cf-file.js";import{noteStructure as fn}from"./changes.js";import{shiftHeaderColors as mn}from"../cells/header-colors.js";function V(t){return{kinds:new Uint8Array(q),values:new Float64Array(q),styles:t.styles===null?null:new Uint16Array(q)}}function W(t,n,r){if(!t||n===0)return;const s=/outlineLevel="\d+"/.exec(t.get(n-1)??"");if(s)for(let o=n;o<n+r;o++)t.set(o,s[0])}function Z(t,n,r,s,o,c){let l=s,e=r,u=c;for(;l>0;){const a=u>>>v,i=u&A,m=Math.min(l,q-i);let y=o[a];y===void 0&&(y=V(t),o[a]=y);const d=e-n;y.kinds.set(t.kinds.subarray(d,d+m),i),y.values.set(t.values.subarray(d,d+m),i),t.styles!==null&&(y.styles===null&&(y.styles=new Uint16Array(q)),y.styles.set(t.styles.subarray(d,d+m),i)),l-=m,e+=m,u+=m}}function G(t,n,r){const s=n>>>v,o=t.slice(0,s),c=t[s];c!==void 0&&(n&A)>0&&Z(c,s<<v,s<<v,n&A,o,s<<v);const l=r<0?n-r:n;for(let e=s;e<t.length;e++){const u=t[e];if(u===void 0)continue;const a=e<<v,i=Math.max(a,l),m=a+q;if(i>=m)continue;const y=i+r;if(y>=k)continue;const d=Math.min(m-i,k-y);Z(u,a,i,d,o,y)}return o}function dn(t,n,r){const s=[];for(let o=0;o<t.length;o++){const c=t[o];c!==void 0&&(o<n?s[o]=c:r>0?o+r<w&&(s[o+r]=c):o>=n-r&&(s[o+r]=c))}return s}function gn(t,n,r,s){const o=r-1,c=Math.min(s,(n?k:w)-r);if(c<=0)return;if(n){const u=c*t.columns.filter(Boolean).length<=4194304;for(let i=0;u&&i<t.columns.length;i++){if(t.columns[i]===void 0)continue;const m=t.cellStyle(o,i);if(m!==0)for(let y=0;y<c;y++)t.setStyle(r+y,i,m)}const a=t.rowStyles?.get(o);if(a!==void 0)for(let i=0;i<c;i++)t.rowStyles.set(r+i,a);return}const l=t.columns[o];if(l!==void 0&&l.some(u=>u?.styles)){for(let u=0;u<c;u++){const a=[];l.forEach((i,m)=>{if(i===void 0||i.styles===null)return;const y=V(i);y.styles.set(i.styles),a[m]=y}),t.columns[r+u]=a}r+c-1>t.maxCol&&(t.maxCol=r+c-1)}const e=t.colStyles?.get(o);if(e!==void 0)for(let u=0;u<c;u++)t.colStyles.set(r+u,e)}function N(t,n,r){if(t===null)return null;const s=new Map;for(const[o,c]of t)o<n?s.set(o,c):(r>0||o>=n-r)&&s.set(o+r,c);return s}const U=(t,n,r)=>r.axis==="row"?t<r.at?[t,n]:r.n>0?t+r.n<k?[t+r.n,n]:null:t>=r.at-r.n?[t+r.n,n]:null:n<r.at?[t,n]:r.n>0?n+r.n<w?[t,n+r.n]:null:n>=r.at-r.n?[t,n+r.n]:null;function J(t,n,r){if(t.f!==void 0)return t.f;if(t.sf!==void 0){const s=Math.floor(t.base/w);return on(t.sf,n-s,r-(t.base-s*w))}return null}const P=(t,n)=>(t.f??t.sf)?.toUpperCase().includes(n)===!0;function Q(t,n){for(const r of t.descriptors())if(P(r,n))return!0;return!1}function _(t,n){const r=X(t),s=r&&O(r,n);return s?H(s):t}function Y(t,n,r,s,o){if(t.t==="dataTable"){if(!s)return t;const l={...t,ref:_(t.ref,r),tpl:void 0};return t.r1&&(l.r1=_(t.r1,r)),t.r2&&(l.r2=_(t.r2,r)),l}const c={f:T(n,r,s,o)};return t.typed&&(c.typed=!0),t.ca&&(c.ca=t.ca),t.cm&&(c.cm=t.cm),t.t==="array"&&(c.t="array",c.ref=s&&t.ref?_(t.ref,r):t.ref),c}function Un(t,n,r){t.collab?.structure(n,r);const{at:s,n:o}=r,c=r.axis==="row",l=$(t,n),e=fn(n,r);if(c){const d=[];n.columns.forEach((p,R)=>{d[R]=G(p,s,o)}),n.columns=d,n.rows=n.rows.shifted(s,o),n.rowStyles=N(n.rowStyles,s,o),n.rowExtras=N(n.rowExtras,s,o),o>0&&W(n.rowExtras,s,o),n.maxRow=n.maxRow>=s?Math.max(s-1,n.maxRow+o):n.maxRow,n.maxRow>=k&&(n.maxRow=k-1),n.frozenRows>s&&(n.frozenRows=Math.max(s,n.frozenRows+o))}else n.columns=dn(n.columns,s,o),n.cols=n.cols.shifted(s,o),n.colStyles=N(n.colStyles,s,o),n.colExtras=N(n.colExtras,s,o),o>0&&W(n.colExtras,s,o),n.colsChanged=!0,n.maxCol=n.maxCol>=s?Math.max(s-1,n.maxCol+o):n.maxCol,n.maxCol>=w&&(n.maxCol=w-1),n.frozenCols>s&&(n.frozenCols=Math.max(s,n.frozenCols+o));if(o>0&&s>0&&!r.noFormat&&gn(n,c,s,o),n.merges=n.merges.map(d=>O(d,r)).filter(d=>d!==null&&(d.r0!==d.r1||d.c0!==d.c1)),n.mergeIndex=null,n.spills){const d=new Map;for(const[p,R]of n.spills){const f=Math.floor(p/w),x=U(f,p-f*w,r),g=O(R,r);x&&g&&d.set(x[0]*w+x[1],{...R,...g})}n.spills=d}if(n.valueMeta){const d=new Map;for(const[p,R]of n.valueMeta){const f=Math.floor(p/w),x=U(f,p-f*w,r);x&&d.set(x[0]*w+x[1],R)}n.valueMeta=d}const u=n.name.toUpperCase();for(const d of t.sheets){const p=d===n;if(!p&&!Q(d.formulas,u))continue;const R=new D;d.formulas.forEachCell((f,x,g)=>{const C=p?U(f,x,r):[f,x];if(C===null)return;if(!p&&!P(g,u)){R.put(C[0],C[1],g);return}const S=J(g,f,x);if(S===null||!p&&!S.toUpperCase().includes(u)){R.put(C[0],C[1],g);return}const M=Y(g,S,r,p,n.name);if(M.t==="array"&&M.ref&&p){const z=d.spills?.get(C[0]*w+C[1]);z&&(M.ref=H(z))}R.put(C[0],C[1],M)}),d.formulas=R}const a=tn(t,n,r),i=t.engine;if(i){for(const d of i.names.values())d.text=T(d.text,r,!1,n.name);i.names.size>0&&(t.namesChanged=!0),i.nameTemplates.clear(),i.rebuild()}n.structureOps=[...n.structureOps??[],r],n.pageSetup&&(an(n.pageSetup,r),n.pageSetupChanged=!0),n.viewChanged=!0,n.revision++,t.collab?.structureDone(n);const m=(d,p)=>()=>m(d(),p()),y=m(a,b(t,n,l));return e===null?y:m(y,e)}const E=(t,n)=>{if(n.span){const[r,s]=n.span;if(!(n.axis==="row"?t.c0>=r&&t.c1<=s:t.r0>=r&&t.r1<=s))return t}return O(t,n)};function j(t,n){return t.split(/\s+/).map(X).filter(Boolean).map(r=>E(r,n)).filter(Boolean).map(H).join(" ")}function F(t,n,r){if(r.span){const[s,o]=r.span,c=r.axis==="row"?n:t;if(c<s||c>o)return[t,n]}return U(t,n,r)}function h(t,n){if(!t)return t;const r=E(t,n);if(r===null)return null;let{columns:s}=t;if(n.axis==="col"&&s?.size>0){s=new Map;for(const[c,l]of t.columns){const e=F(t.r0,c,n);e&&s.set(e[1],l)}}let{buttons:o}=t;if(n.axis==="col"&&o?.size>0){o=new Map;for(const[c,l]of t.buttons){const e=F(t.r0,c,n);e&&o.set(e[1],l)}}return{...t,...r,columns:s,buttons:o,sortState:nn(t.sortState,n)}}function nn(t,n){if(!t)return t??null;const r=E(t,n);if(r===null)return null;const s=[];for(const o of t.conditions){const c=E(o,n);c!==null&&s.push({...o,...c})}return s.length>0?{...t,...r,conditions:s}:null}const I=t=>({sheets:t.sheets.map(n=>[n,{cf:n.cf,cellStates:n.cellStates,headerColors:n.headerColors,validations:n.validations,hyperlinks:n.hyperlinks,ignoredErrors:n.ignoredErrors,comments:n.comments,sparklines:n.sparklines,sparkRules:n.sparkRules,autoFilter:n.autoFilter,advancedFilter:n.advancedFilter,outlineColumn:n.outlineColumn,outlineVersion:(n.outlineVersion??0)+1,sortState:n.sortState,filteredRows:n.filteredRows,scenarios:n.scenarios,threads:n.threads}]),tables:t.engine?[...t.engine.tables.values()].map(n=>[n,{r0:n.r0,c0:n.c0,r1:n.r1,c1:n.c1,columns:n.columns,filter:n.filter,totals:n.totals,dirty:n.dirty,columnsChanged:n.columnsChanged}]):[]}),rn=t=>{for(const[n,r]of t.sheets)Object.assign(n,r),n.cfEval?.invalidate();for(const[n,r]of t.tables)Object.assign(n,r)};function tn(t,n,r){const s=I(t),o=n.name;for(const l of t.sheets){const e=l===n,u=a=>typeof a=="string"&&a!==""?T(a,r,e,o):a;if(l.cf?.length>0&&(l.cf=l.cf.map(({_ranges:a,...i})=>({...i,sqref:e?j(i.sqref,r):i.sqref,rules:i.rules.map(m=>un(m,u))})).filter(a=>a.sqref!==""),l.cfChanged=!0,l.cfEval?.invalidate()),e&&l.headerColors&&!r.span&&(l.headerColors=mn(l.headerColors,r)),e&&l.cellStates?.length>0){const a=l.cellStates.map(i=>({...i,ranges:i.ranges.map(m=>E(m,r)).filter(Boolean)})).filter(i=>i.ranges.length>0);l.cellStates=a.length>0?a:null}l.validations?.length>0&&(l.validations=l.validations.map(({_ranges:a,...i})=>({...i,sqref:e?j(i.sqref,r):i.sqref,formula1:u(i.formula1),formula2:u(i.formula2)})).filter(a=>a.sqref!==""),l.validationsChanged=!0),e&&l.ignoredErrors?.length>0&&(l.ignoredErrors=l.ignoredErrors.map(a=>({...a,sqref:j(a.sqref,r)})).filter(a=>a.sqref!==""),l.ignoredErrorsChanged=!0),l.hyperlinks?.length>0&&(l.hyperlinks=l.hyperlinks.map(({_ranges:a,...i})=>{const m=e?j(i.ref,r):i.ref;return{...i,ref:m,...i.location?{location:u(i.location)}:{}}}).filter(a=>a.ref!==""),l.hyperlinksChanged=!0),l.sparkRules?.length>0&&(l.sparkRules=l.sparkRules.map(a=>({...a,sqref:e?j(a.sqref,r):a.sqref,formula:u(a.formula)})).filter(a=>a.sqref!=="")),l.sparklines?.length>0&&(l.sparklines=l.sparklines.map(a=>({...a,items:a.items.map(i=>{const m=L(i.cell),y=e&&m?F(m.row,m.col,r):m?[m.row,m.col]:null;return y?{...i,cell:B(y[0],y[1]),source:u(i.source)}:null}).filter(Boolean)})).filter(a=>a.items.length>0),l.sparklinesChanged=!0)}if(n.comments?.size>0){const l=new Map;for(const[e,u]of n.comments){const a=Math.floor(e/w),i=F(a,e-a*w,r);i&&l.set(i[0]*w+i[1],{...u,ref:B(i[0],i[1])})}n.comments=l,n.commentsChanged=!0}if(n.scenarios?.items.length>0&&(n.scenarios={...n.scenarios,items:n.scenarios.items.map(l=>({...l,cells:l.cells.map(e=>{const u=L(e.r),a=u&&F(u.row,u.col,r);return a?{...e,r:B(a[0],a[1])}:null}).filter(Boolean)}))},n.scenariosChanged=!0),n.threads?.length>0&&(n.threads=n.threads.map(l=>{const e=L(l.ref),u=e&&F(e.row,e.col,r);return u?{...l,ref:B(u[0],u[1])}:null}).filter(Boolean),n.threadsChanged=!0),n.outlineColumn){const l=n.outlineColumn;if(r.axis==="col"&&!r.span){const e=U(0,l.col,r);n.outlineColumn=e?{...l,col:e[1]}:null}else if(r.axis==="row"&&!r.span&&l.checks){const e={};for(const u of Object.keys(l.checks)){const a=U(Number(u),0,r);a&&(e[a[0]]=l.checks[u])}n.outlineColumn={...l,checks:e}}}if(n.outlineVersion=(n.outlineVersion??0)+1,n.sortState&&(n.sortState=nn(n.sortState,r),n.filterChanged=!0),n.autoFilter&&(n.autoFilter=h(n.autoFilter,r),n.filterChanged=!0),n.advancedFilter){const l=n.advancedFilter,e=l.listSheet===n?E(l,r):l;n.advancedFilter=e===null?null:{...l,r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1,criteria:l.criteria&&l.criteriaSheet===n?E(l.criteria,r):l.criteria,extract:l.extract?E(l.extract,r):null},n.filterChanged=!0}if(n.filteredRows&&r.axis==="row"&&!r.span){const l=new Set;for(const e of n.filteredRows){const u=U(e,0,r);u&&l.add(u[0])}n.filteredRows=l}if(t.engine)for(const l of[...t.engine.tables.values()]){if(l.sheet!==n)continue;const e=E(l,r);if(e===null)continue;const u=!r.span||r.span[0]<=l.r0&&r.span[1]>=l.r1;r.axis==="col"&&u&&e.c1-e.c0!==l.c1-l.c0&&Cn(t,l,r),Object.assign(l,{r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1}),l.filter=h(l.filter,r),l.dirty=!0}const c=l=>()=>{const e=I(t);return rn(l),c(e)};return c(s)}function On(t){const n=r=>()=>{const s=I(t);return rn(r),n(s)};return n(I(t))}function xn(t,n){return b(t,n,$(t,n))}function yn(t,n,r,s){if(t===void 0&&n===void 0)return;const o=t===void 0?[]:t.slice();for(let c=r>>>v;c<=s>>>v;c++){const l=t?.[c],e=n?.[c];if(l===void 0&&e===void 0)continue;const u=c<<v,a=Math.max(r,u)-u,i=Math.min(s,u+A)-u+1,m=l===void 0?V({styles:null}):{kinds:l.kinds.slice(),values:l.values.slice(),styles:l.styles?l.styles.slice():null};e===void 0?(m.kinds.fill(0,a,i),m.values.fill(0,a,i),m.styles!==null&&m.styles.fill(0,a,i)):(m.kinds.set(e.kinds.subarray(a,i),a),m.values.set(e.values.subarray(a,i),a),e.styles!==null?(m.styles===null&&(m.styles=new Uint16Array(q)),m.styles.set(e.styles.subarray(a,i),a)):m.styles!==null&&m.styles.fill(0,a,i)),o[c]=m}return o}function wn(t){if(t===void 0)return-1;for(let n=t.length-1;n>=0;n--){const r=t[n];if(r!==void 0){for(let s=A;s>=0;s--)if(r.kinds[s]!==0||r.styles!==null&&r.styles[s]!==0)return(n<<v)+s}}return-1}function An(t,n,r){t.collab?.structure(n,r);const{at:s,n:o}=r,[c,l]=r.span,e=r.axis==="row",u=xn(t,n),a=n.columns.slice();if(e)for(let f=c;f<=Math.min(l,n.columns.length-1);f++)n.columns[f]!==void 0&&(a[f]=G(n.columns[f],s,o),o>0&&(n.maxRow=Math.min(k-1,Math.max(n.maxRow,wn(a[f])))));else{const f=n.columns.length-1,x=o>0?Math.min(f+o,w-1):f;for(let g=s;g<=x;g++){const C=g-o,S=o>0&&g<s+o?void 0:n.columns[C],M=yn(n.columns[g],S,c,l);M!==void 0&&(a[g]=M)}o>0&&(n.maxCol=Math.min(w-1,Math.max(n.maxCol,Math.min(n.maxCol+o,x))))}if(n.columns=a,o>0&&s>0&&!r.noFormat){const f=Math.min(o,(e?k:w)-s),x=Math.min(l,e?n.maxCol:n.maxRow);if(f>0&&f*(x-c+1)<=1<<22)for(let g=c;g<=x;g++){const C=e?n.cellStyle(s-1,g):n.cellStyle(g,s-1);if(C!==0)for(let S=0;S<f;S++)e?n.setStyle(s+S,g,C):n.setStyle(g,s+S,C)}}const i=f=>e?f.c0>=c&&f.c1<=l:f.r0>=c&&f.r1<=l;if(n.merges=n.merges.map(f=>i(f)?O(f,r):f).filter(f=>f!==null&&(f.r0!==f.r1||f.c0!==f.c1)),n.mergeIndex=null,n.spills){const f=new Map;for(const[x,g]of n.spills){const C=Math.floor(x/w),S=F(C,x-C*w,r),M=i(g)?O(g,r):g;S&&M&&f.set(S[0]*w+S[1],{...g,...M})}n.spills=f}if(n.valueMeta){const f=new Map;for(const[x,g]of n.valueMeta){const C=Math.floor(x/w),S=F(C,x-C*w,r);S&&f.set(S[0]*w+S[1],g)}n.valueMeta=f}const m=n.name.toUpperCase();for(const f of t.sheets){const x=f===n;if(!x&&!Q(f.formulas,m))continue;const g=new D;f.formulas.forEachCell((C,S,M)=>{const z=x?F(C,S,r):[C,S];if(z===null)return;const K=x||P(M,m)?J(M,C,S):null;K===null||!x&&!K.toUpperCase().includes(m)?g.put(z[0],z[1],M):g.put(z[0],z[1],Y(M,K,r,x,n.name))}),f.formulas=g}const y=tn(t,n,r),d=cn(n,r),p=t.engine;if(p){for(const f of p.names.values())f.text=T(f.text,r,!1,n.name);p.names.size>0&&(t.namesChanged=!0),p.nameTemplates.clear(),p.rebuild()}n.viewChanged=!0,n.revision++,t.collab?.structureDone(n);const R=(f,x,g)=>()=>R(f(n),x(n),g(n));return R(d,y,u)}function Cn(t,n,r){const s=r.at-n.c0,o=n.columns.slice(),c=n.totals?.slice()??null;if(r.n>0){const l=new Set(o.map(u=>u.toLowerCase())),e=[];for(let u=0,a=1;u<r.n;u++){for(;l.has(`column${a}`);)a++;l.add(`column${a}`),e.push(`Column${a}`)}o.splice(s,0,...e),c?.splice(s,0,...e.map(()=>null)),n.headerRows>0&&e.forEach((u,a)=>n.sheet.setCell(n.r0,r.at+a,sn,t.strings.add(u)))}else{const l=Math.max(s,0),e=Math.min(-r.n-Math.max(0,n.c0-r.at),o.length-l);o.splice(l,e),c?.splice(l,e)}n.columns=o,n.totals=c,n.columnsChanged=!0}function $(t,n){const r=t.engine;return{columns:n.columns,rows:n.rows,cols:n.cols,rowStyles:n.rowStyles,colStyles:n.colStyles,rowExtras:n.rowExtras,colExtras:n.colExtras,valueMeta:n.valueMeta,merges:n.merges,spills:n.spills,maxRow:n.maxRow,maxCol:n.maxCol,frozenRows:n.frozenRows,frozenCols:n.frozenCols,colsChanged:n.colsChanged,structureOps:n.structureOps,pageSetup:n.pageSetup?en(n.pageSetup):null,formulas:t.sheets.map(s=>[s,s.formulas]),names:r?[...r.names].map(([s,o])=>[s,{...o}]):null}}function b(t,n,r){return()=>{const s=$(t,n);n.columns=r.columns,n.rows=r.rows,n.cols=r.cols,n.rowStyles=r.rowStyles,n.colStyles=r.colStyles,n.rowExtras=r.rowExtras,n.colExtras=r.colExtras,n.valueMeta=r.valueMeta,n.merges=r.merges,n.mergeIndex=null,n.spills=r.spills,n.maxRow=r.maxRow,n.maxCol=r.maxCol,n.frozenRows=r.frozenRows,n.frozenCols=r.frozenCols,n.colsChanged=r.colsChanged,n.structureOps=r.structureOps,r.pageSetup&&(n.pageSetup=r.pageSetup);for(const[c,l]of r.formulas)c.formulas=l;const o=t.engine;return o&&(o.names=new Map(r.names),o.nameTemplates.clear(),o.rebuild()),n.revision++,b(t,n,s)}}export{ln as FORMULA,I as captureFeatures,On as featuresUndo,rn as restoreFeatures,An as shiftBand,tn as shiftFeatures,Un as shiftStructure,xn as structureUndo};
1
+ import{CHUNK_BITS as v,CHUNK_MASK as A,CHUNK_SIZE as q,FORMULA as ln,STR as sn}from"./sheet.js";import{FormulaStore as X}from"./formula-store.js";import{cellRef as B,MAX_COLS as w,MAX_ROWS as k,parseCellRef as L,parseRangeRef as b,rangeRef as H}from"./address.js";import{translateFormula as on}from"./formula-refs.js";import{adjustFormula as T,adjustRange as O}from"../calc/adjust.js";import{clonePageSetup as en,shiftPageSetup as an}from"../print/page-setup.js";import{shiftSparse as cn}from"./sparse.js";import{shiftRuleFormulas as un}from"../cells/cf-file.js";import{noteStructure as fn}from"./changes.js";import{shiftHeaderColors as mn}from"../cells/header-colors.js";function V(t){return{kinds:new Uint8Array(q),values:new Float64Array(q),styles:t.styles===null?null:new Uint16Array(q)}}function W(t,n,r){if(!t||n===0)return;const s=/outlineLevel="\d+"/.exec(t.get(n-1)??"");if(s)for(let o=n;o<n+r;o++)t.set(o,s[0])}function Z(t,n,r,s,o,c){let l=s,e=r,u=c;for(;l>0;){const a=u>>>v,i=u&A,m=Math.min(l,q-i);let y=o[a];y===void 0&&(y=V(t),o[a]=y);const d=e-n;y.kinds.set(t.kinds.subarray(d,d+m),i),y.values.set(t.values.subarray(d,d+m),i),t.styles!==null&&(y.styles===null&&(y.styles=new Uint16Array(q)),y.styles.set(t.styles.subarray(d,d+m),i)),l-=m,e+=m,u+=m}}function G(t,n,r){const s=n>>>v,o=t.slice(0,s),c=t[s];c!==void 0&&(n&A)>0&&Z(c,s<<v,s<<v,n&A,o,s<<v);const l=r<0?n-r:n;for(let e=s;e<t.length;e++){const u=t[e];if(u===void 0)continue;const a=e<<v,i=Math.max(a,l),m=a+q;if(i>=m)continue;const y=i+r;if(y>=k)continue;const d=Math.min(m-i,k-y);Z(u,a,i,d,o,y)}return o}function dn(t,n,r){const s=[];for(let o=0;o<t.length;o++){const c=t[o];c!==void 0&&(o<n?s[o]=c:r>0?o+r<w&&(s[o+r]=c):o>=n-r&&(s[o+r]=c))}return s}function gn(t,n,r,s){const o=r-1,c=Math.min(s,(n?k:w)-r);if(c<=0)return;if(n){const u=c*t.columns.filter(Boolean).length<=4194304;for(let i=0;u&&i<t.columns.length;i++){if(t.columns[i]===void 0)continue;const m=t.cellStyle(o,i);if(m!==0)for(let y=0;y<c;y++)t.setStyle(r+y,i,m)}const a=t.rowStyles?.get(o);if(a!==void 0)for(let i=0;i<c;i++)t.rowStyles.set(r+i,a);return}const l=t.columns[o];if(l!==void 0&&l.some(u=>u?.styles)){for(let u=0;u<c;u++){const a=[];l.forEach((i,m)=>{if(i===void 0||i.styles===null)return;const y=V(i);y.styles.set(i.styles),a[m]=y}),t.columns[r+u]=a}r+c-1>t.maxCol&&(t.maxCol=r+c-1)}const e=t.colStyles?.get(o);if(e!==void 0)for(let u=0;u<c;u++)t.colStyles.set(r+u,e)}function N(t,n,r){if(t===null)return null;const s=new Map;for(const[o,c]of t)o<n?s.set(o,c):(r>0||o>=n-r)&&s.set(o+r,c);return s}const U=(t,n,r)=>r.axis==="row"?t<r.at?[t,n]:r.n>0?t+r.n<k?[t+r.n,n]:null:t>=r.at-r.n?[t+r.n,n]:null:n<r.at?[t,n]:r.n>0?n+r.n<w?[t,n+r.n]:null:n>=r.at-r.n?[t,n+r.n]:null;function J(t,n,r){if(t.f!==void 0)return t.f;if(t.sf!==void 0){const s=Math.floor(t.base/w);return on(t.sf,n-s,r-(t.base-s*w))}return null}const P=(t,n)=>(t.f??t.sf)?.toUpperCase().includes(n)===!0;function Q(t,n){for(const r of t.descriptors())if(P(r,n))return!0;return!1}function _(t,n){const r=b(t),s=r&&O(r,n);return s?H(s):t}function Y(t,n,r,s,o){if(t.t==="dataTable"){if(!s)return t;const l={...t,ref:_(t.ref,r),tpl:void 0};return t.r1&&(l.r1=_(t.r1,r)),t.r2&&(l.r2=_(t.r2,r)),l}const c={f:T(n,r,s,o)};return t.typed&&(c.typed=!0),t.ca&&(c.ca=t.ca),t.cm&&(c.cm=t.cm),t.t==="array"&&(c.t="array",c.ref=s&&t.ref?_(t.ref,r):t.ref),c}function Un(t,n,r){t.collab?.structure(n,r);const{at:s,n:o}=r,c=r.axis==="row",l=$(t,n),e=fn(n,r);if(c){const d=[];n.columns.forEach((p,R)=>{d[R]=G(p,s,o)}),n.columns=d,n.rows=n.rows.shifted(s,o),n.rowStyles=N(n.rowStyles,s,o),n.rowExtras=N(n.rowExtras,s,o),o>0&&W(n.rowExtras,s,o),n.maxRow=n.maxRow>=s?Math.max(s-1,n.maxRow+o):n.maxRow,n.maxRow>=k&&(n.maxRow=k-1),n.frozenRows>s&&(n.frozenRows=Math.max(s,n.frozenRows+o))}else n.columns=dn(n.columns,s,o),n.cols=n.cols.shifted(s,o),n.colStyles=N(n.colStyles,s,o),n.colExtras=N(n.colExtras,s,o),o>0&&W(n.colExtras,s,o),n.colsChanged=!0,n.maxCol=n.maxCol>=s?Math.max(s-1,n.maxCol+o):n.maxCol,n.maxCol>=w&&(n.maxCol=w-1),n.frozenCols>s&&(n.frozenCols=Math.max(s,n.frozenCols+o));if(o>0&&s>0&&!r.noFormat&&gn(n,c,s,o),n.merges=n.merges.map(d=>O(d,r)).filter(d=>d!==null&&(d.r0!==d.r1||d.c0!==d.c1)),n.mergeIndex=null,n.spills){const d=new Map;for(const[p,R]of n.spills){const f=Math.floor(p/w),x=U(f,p-f*w,r),g=O(R,r);x&&g&&d.set(x[0]*w+x[1],{...R,...g})}n.spills=d}if(n.valueMeta){const d=new Map;for(const[p,R]of n.valueMeta){const f=Math.floor(p/w),x=U(f,p-f*w,r);x&&d.set(x[0]*w+x[1],R)}n.valueMeta=d}const u=n.name.toUpperCase();for(const d of t.sheets){const p=d===n;if(!p&&!Q(d.formulas,u))continue;const R=new X;d.formulas.forEachCell((f,x,g)=>{const C=p?U(f,x,r):[f,x];if(C===null)return;if(!p&&!P(g,u)){R.put(C[0],C[1],g);return}const S=J(g,f,x);if(S===null||!p&&!S.toUpperCase().includes(u)){R.put(C[0],C[1],g);return}const M=Y(g,S,r,p,n.name);if(M.t==="array"&&M.ref&&p){const z=d.spills?.get(C[0]*w+C[1]);z&&(M.ref=H(z))}R.put(C[0],C[1],M)}),d.formulas=R}const a=tn(t,n,r),i=t.engine;if(i){for(const d of i.names.values())d.text=T(d.text,r,!1,n.name);i.names.size>0&&(t.namesChanged=!0),i.nameTemplates.clear(),i.rebuild()}n.structureOps=[...n.structureOps??[],r],n.pageSetup&&(an(n.pageSetup,r),n.pageSetupChanged=!0),n.viewChanged=!0,n.revision++,t.collab?.structureDone(n);const m=(d,p)=>()=>m(d(),p()),y=m(a,D(t,n,l));return e===null?y:m(y,e)}const E=(t,n)=>{if(n.span){const[r,s]=n.span;if(!(n.axis==="row"?t.c0>=r&&t.c1<=s:t.r0>=r&&t.r1<=s))return t}return O(t,n)};function j(t,n){return t.split(/\s+/).map(b).filter(Boolean).map(r=>E(r,n)).filter(Boolean).map(H).join(" ")}function F(t,n,r){if(r.span){const[s,o]=r.span,c=r.axis==="row"?n:t;if(c<s||c>o)return[t,n]}return U(t,n,r)}function h(t,n){if(!t)return t;const r=E(t,n);if(r===null)return null;let{columns:s}=t;if(n.axis==="col"&&s?.size>0){s=new Map;for(const[c,l]of t.columns){const e=F(t.r0,c,n);e&&s.set(e[1],l)}}let{buttons:o}=t;if(n.axis==="col"&&o?.size>0){o=new Map;for(const[c,l]of t.buttons){const e=F(t.r0,c,n);e&&o.set(e[1],l)}}return{...t,...r,columns:s,buttons:o,sortState:nn(t.sortState,n)}}function nn(t,n){if(!t)return t??null;const r=E(t,n);if(r===null)return null;const s=[];for(const o of t.conditions){const c=E(o,n);c!==null&&s.push({...o,...c})}return s.length>0?{...t,...r,conditions:s}:null}const I=t=>({sheets:t.sheets.map(n=>[n,{cf:n.cf,cellStates:n.cellStates,headerColors:n.headerColors,validations:n.validations,hyperlinks:n.hyperlinks,ignoredErrors:n.ignoredErrors,comments:n.comments,sparklines:n.sparklines,sparkRules:n.sparkRules,autoFilter:n.autoFilter,advancedFilter:n.advancedFilter,outlineColumn:n.outlineColumn,outlineVersion:(n.outlineVersion??0)+1,sortState:n.sortState,filteredRows:n.filteredRows,scenarios:n.scenarios,threads:n.threads}]),tables:t.engine?[...t.engine.tables.values()].map(n=>[n,{r0:n.r0,c0:n.c0,r1:n.r1,c1:n.c1,columns:n.columns,filter:n.filter,totals:n.totals,dirty:n.dirty,columnsChanged:n.columnsChanged}]):[]}),rn=t=>{for(const[n,r]of t.sheets)Object.assign(n,r),n.cfEval?.invalidate();for(const[n,r]of t.tables)Object.assign(n,r)};function tn(t,n,r){const s=I(t),o=n.name;for(const l of t.sheets){const e=l===n,u=a=>typeof a=="string"&&a!==""?T(a,r,e,o):a;if(l.cf?.length>0&&(l.cf=l.cf.map(({_ranges:a,...i})=>({...i,sqref:e?j(i.sqref,r):i.sqref,rules:i.rules.map(m=>un(m,u))})).filter(a=>a.sqref!==""),l.cfChanged=!0,l.cfEval?.invalidate()),e&&l.headerColors&&!r.span&&(l.headerColors=mn(l.headerColors,r)),e&&l.cellStates?.length>0){const a=l.cellStates.map(i=>({...i,ranges:i.ranges.map(m=>E(m,r)).filter(Boolean)})).filter(i=>i.ranges.length>0);l.cellStates=a.length>0?a:null}l.validations?.length>0&&(l.validations=l.validations.map(({_ranges:a,...i})=>({...i,sqref:e?j(i.sqref,r):i.sqref,formula1:u(i.formula1),formula2:u(i.formula2)})).filter(a=>a.sqref!==""),l.validationsChanged=!0),e&&l.ignoredErrors?.length>0&&(l.ignoredErrors=l.ignoredErrors.map(a=>({...a,sqref:j(a.sqref,r)})).filter(a=>a.sqref!==""),l.ignoredErrorsChanged=!0),l.hyperlinks?.length>0&&(l.hyperlinks=l.hyperlinks.map(({_ranges:a,...i})=>{const m=e?j(i.ref,r):i.ref;return{...i,ref:m,...i.location?{location:u(i.location)}:{}}}).filter(a=>a.ref!==""),l.hyperlinksChanged=!0),l.sparkRules?.length>0&&(l.sparkRules=l.sparkRules.map(a=>({...a,sqref:e?j(a.sqref,r):a.sqref,formula:u(a.formula)})).filter(a=>a.sqref!=="")),l.sparklines?.length>0&&(l.sparklines=l.sparklines.map(a=>({...a,items:a.items.map(i=>{const m=L(i.cell),y=e&&m?F(m.row,m.col,r):m?[m.row,m.col]:null;return y?{...i,cell:B(y[0],y[1]),source:u(i.source)}:null}).filter(Boolean)})).filter(a=>a.items.length>0),l.sparklinesChanged=!0)}if(n.comments?.size>0){const l=new Map;for(const[e,u]of n.comments){const a=Math.floor(e/w),i=F(a,e-a*w,r);i&&l.set(i[0]*w+i[1],{...u,ref:B(i[0],i[1])})}n.comments=l,n.commentsChanged=!0}if(n.scenarios?.items.length>0&&(n.scenarios={...n.scenarios,items:n.scenarios.items.map(l=>({...l,cells:l.cells.map(e=>{const u=L(e.r),a=u&&F(u.row,u.col,r);return a?{...e,r:B(a[0],a[1])}:null}).filter(Boolean)}))},n.scenariosChanged=!0),n.threads?.length>0&&(n.threads=n.threads.map(l=>{const e=L(l.ref),u=e&&F(e.row,e.col,r);return u?{...l,ref:B(u[0],u[1])}:null}).filter(Boolean),n.threadsChanged=!0),n.outlineColumn){const l=n.outlineColumn;if(r.axis==="col"&&!r.span){const e=U(0,l.col,r);n.outlineColumn=e?{...l,col:e[1]}:null}else if(r.axis==="row"&&!r.span&&l.checks){const e={};for(const u of Object.keys(l.checks)){const a=U(Number(u),0,r);a&&(e[a[0]]=l.checks[u])}n.outlineColumn={...l,checks:e}}}if(n.outlineVersion=(n.outlineVersion??0)+1,n.sortState&&(n.sortState=nn(n.sortState,r),n.filterChanged=!0),n.autoFilter&&(n.autoFilter=h(n.autoFilter,r),n.filterChanged=!0),n.advancedFilter){const l=n.advancedFilter,e=l.listSheet===n?E(l,r):l;n.advancedFilter=e===null?null:{...l,r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1,criteria:l.criteria&&l.criteriaSheet===n?E(l.criteria,r):l.criteria,extract:l.extract?E(l.extract,r):null},n.filterChanged=!0}if(n.filteredRows&&r.axis==="row"&&!r.span){const l=new Set;for(const e of n.filteredRows){const u=U(e,0,r);u&&l.add(u[0])}n.filteredRows=l}if(t.engine)for(const l of[...t.engine.tables.values()]){if(l.sheet!==n)continue;const e=E(l,r);if(e===null)continue;const u=!r.span||r.span[0]<=l.r0&&r.span[1]>=l.r1;r.axis==="col"&&u&&e.c1-e.c0!==l.c1-l.c0&&Cn(t,l,r),Object.assign(l,{r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1}),l.filter=h(l.filter,r),l.dirty=!0}const c=l=>()=>{const e=I(t);return rn(l),c(e)};return c(s)}function On(t){const n=r=>()=>{const s=I(t);return rn(r),n(s)};return n(I(t))}function xn(t,n){return D(t,n,$(t,n))}function yn(t,n,r,s){if(t===void 0&&n===void 0)return;const o=t===void 0?[]:t.slice();for(let c=r>>>v;c<=s>>>v;c++){const l=t?.[c],e=n?.[c];if(l===void 0&&e===void 0)continue;const u=c<<v,a=Math.max(r,u)-u,i=Math.min(s,u+A)-u+1,m=l===void 0?V({styles:null}):{kinds:l.kinds.slice(),values:l.values.slice(),styles:l.styles?l.styles.slice():null};e===void 0?(m.kinds.fill(0,a,i),m.values.fill(0,a,i),m.styles!==null&&m.styles.fill(0,a,i)):(m.kinds.set(e.kinds.subarray(a,i),a),m.values.set(e.values.subarray(a,i),a),e.styles!==null?(m.styles===null&&(m.styles=new Uint16Array(q)),m.styles.set(e.styles.subarray(a,i),a)):m.styles!==null&&m.styles.fill(0,a,i)),o[c]=m}return o}function wn(t){if(t===void 0)return-1;for(let n=t.length-1;n>=0;n--){const r=t[n];if(r!==void 0){for(let s=A;s>=0;s--)if(r.kinds[s]!==0||r.styles!==null&&r.styles[s]!==0)return(n<<v)+s}}return-1}function An(t,n,r){t.collab?.structure(n,r);const{at:s,n:o}=r,[c,l]=r.span,e=r.axis==="row",u=xn(t,n),a=n.columns.slice();if(e)for(let f=c;f<=Math.min(l,n.columns.length-1);f++)n.columns[f]!==void 0&&(a[f]=G(n.columns[f],s,o),o>0&&(n.maxRow=Math.min(k-1,Math.max(n.maxRow,wn(a[f])))));else{const f=n.columns.length-1,x=o>0?Math.min(f+o,w-1):f;for(let g=s;g<=x;g++){const C=g-o,S=o>0&&g<s+o?void 0:n.columns[C],M=yn(n.columns[g],S,c,l);M!==void 0&&(a[g]=M)}o>0&&(n.maxCol=Math.min(w-1,Math.max(n.maxCol,Math.min(n.maxCol+o,x))))}if(n.columns=a,o>0&&s>0&&!r.noFormat){const f=Math.min(o,(e?k:w)-s),x=Math.min(l,e?n.maxCol:n.maxRow);if(f>0&&f*(x-c+1)<=1<<22)for(let g=c;g<=x;g++){const C=e?n.cellStyle(s-1,g):n.cellStyle(g,s-1);if(C!==0)for(let S=0;S<f;S++)e?n.setStyle(s+S,g,C):n.setStyle(g,s+S,C)}}const i=f=>e?f.c0>=c&&f.c1<=l:f.r0>=c&&f.r1<=l;if(n.merges=n.merges.map(f=>i(f)?O(f,r):f).filter(f=>f!==null&&(f.r0!==f.r1||f.c0!==f.c1)),n.mergeIndex=null,n.spills){const f=new Map;for(const[x,g]of n.spills){const C=Math.floor(x/w),S=F(C,x-C*w,r),M=i(g)?O(g,r):g;S&&M&&f.set(S[0]*w+S[1],{...g,...M})}n.spills=f}if(n.valueMeta){const f=new Map;for(const[x,g]of n.valueMeta){const C=Math.floor(x/w),S=F(C,x-C*w,r);S&&f.set(S[0]*w+S[1],g)}n.valueMeta=f}const m=n.name.toUpperCase();for(const f of t.sheets){const x=f===n;if(!x&&!Q(f.formulas,m))continue;const g=new X;f.formulas.forEachCell((C,S,M)=>{const z=x?F(C,S,r):[C,S];if(z===null)return;const K=x||P(M,m)?J(M,C,S):null;K===null||!x&&!K.toUpperCase().includes(m)?g.put(z[0],z[1],M):g.put(z[0],z[1],Y(M,K,r,x,n.name))}),f.formulas=g}const y=tn(t,n,r),d=cn(n,r),p=t.engine;if(p){for(const f of p.names.values())f.text=T(f.text,r,!1,n.name);p.names.size>0&&(t.namesChanged=!0),p.nameTemplates.clear(),p.rebuild()}n.viewChanged=!0,n.revision++,t.collab?.structureDone(n);const R=(f,x,g)=>()=>R(f(n),x(n),g(n));return R(d,y,u)}function Cn(t,n,r){const s=r.at-n.c0,o=n.columns.slice(),c=n.totals?.slice()??null;if(r.n>0){const l=new Set(o.map(u=>u.toLowerCase())),e=[];for(let u=0,a=1;u<r.n;u++){for(;l.has(`column${a}`);)a++;l.add(`column${a}`),e.push(`Column${a}`)}o.splice(s,0,...e),c?.splice(s,0,...e.map(()=>null)),n.headerRows>0&&e.forEach((u,a)=>n.sheet.setCell(n.r0,r.at+a,sn,t.strings.add(u)))}else{const l=Math.max(s,0),e=Math.min(-r.n-Math.max(0,n.c0-r.at),o.length-l);o.splice(l,e),c?.splice(l,e)}n.columns=o,n.totals=c,n.columnsChanged=!0}function $(t,n){const r=t.engine;return{columns:n.columns,rows:n.rows,cols:n.cols,rowStyles:n.rowStyles,colStyles:n.colStyles,rowExtras:n.rowExtras,colExtras:n.colExtras,valueMeta:n.valueMeta,merges:n.merges,spills:n.spills,maxRow:n.maxRow,maxCol:n.maxCol,frozenRows:n.frozenRows,frozenCols:n.frozenCols,colsChanged:n.colsChanged,structureOps:n.structureOps,pageSetup:n.pageSetup?en(n.pageSetup):null,formulas:t.sheets.map(s=>[s,s.formulas]),names:r?[...r.names].map(([s,o])=>[s,{...o}]):null}}function D(t,n,r){return()=>{const s=$(t,n);n.columns=r.columns,n.rows=r.rows,n.cols=r.cols,n.rowStyles=r.rowStyles,n.colStyles=r.colStyles,n.rowExtras=r.rowExtras,n.colExtras=r.colExtras,n.valueMeta=r.valueMeta,n.merges=r.merges,n.mergeIndex=null,n.spills=r.spills,n.maxRow=r.maxRow,n.maxCol=r.maxCol,n.frozenRows=r.frozenRows,n.frozenCols=r.frozenCols,n.colsChanged=r.colsChanged,n.structureOps=r.structureOps,r.pageSetup&&(n.pageSetup=r.pageSetup);for(const[c,l]of r.formulas)c.formulas=l;const o=t.engine;return o&&((o.names.size||r.names.length)&&(t.namesChanged=!0),o.names=new Map(r.names),o.nameTemplates.clear(),o.rebuild()),n.revision++,D(t,n,s)}}export{ln as FORMULA,I as captureFeatures,On as featuresUndo,rn as restoreFeatures,An as shiftBand,tn as shiftFeatures,Un as shiftStructure,xn as structureUndo};
@@ -0,0 +1 @@
1
+ import{parseRangeRef as h,rangeRef as p}from"./address.js";const m=(n,r)=>n.r0<=r.r1&&n.r1>=r.r0&&n.c0<=r.c1&&n.c1>=r.c0;function u(n,r){if(!m(n,r))return[n];const s=[],o=Math.max(n.c0,r.c0),f=Math.min(n.c1,r.c1);return n.c0<r.c0&&s.push({...n,c1:r.c0-1}),n.c1>r.c1&&s.push({...n,c0:r.c1+1}),n.r0<r.r0&&s.push({r0:n.r0,c0:o,r1:r.r0-1,c1:f}),n.r1>r.r1&&s.push({r0:r.r1+1,c0:o,r1:n.r1,c1:f}),s}function d(n,r){let s=String(n).split(/\s+/).map(h).filter(Boolean);for(const o of r)s=s.flatMap(f=>u(f,o));return s.map(p).join(" ")}const a=({sqref:n,_ranges:r,...s})=>JSON.stringify(s,Object.keys(s).sort());function q(n,r,s){const o=[];for(const t of n??[]){const e=d(t.sqref,r);e!==""&&o.push(e===t.sqref?t:c(t,e))}if(s===null)return o;const f=r.map(p).join(" "),i=o.findIndex(t=>a(t)===a(s));return i>=0?o[i]=c(o[i],`${o[i].sqref} ${f}`):o.push(c(s,f)),o}function c(n,r){const{_ranges:s,...o}=n;return{...o,sqref:r}}export{d as subtractFromSqref,u as subtractRect,q as withRuleOn};
package/core/workbook.js CHANGED
@@ -1 +1 @@
1
- import{expandBareTables as ue}from"../slicers/structured.js";import{syncTableHeaders as fe,tablesOf as de}from"./tables.js";import{BOOL as D,CHUNK_BITS as z,CHUNK_MASK as K,EMPTY as T,ERR as U,ERRORS as me,FORMULA as F,DIRTY as W,EVALUATING as J,KIND_MASK as Z,NUM as P,Sheet as B,SPILL as pe,STR as A}from"./sheet.js";import{cellRef as ge,isValidName as ye,MAX_COLS as b,MAX_ROWS as Y,quoteSheetName as X,rangeRef as Se,renameSheetInFormula as Q,sheetReferencePattern as ee}from"./address.js";import{translateFormula as we}from"./formula-refs.js";import{sheetStem as te}from"./default-names.js";import{StringTable as Ce}from"./strings.js";import{formatAxis as se,formatSheetColumns as ve}from"./axis-styles.js";import{autoRowHeight as ke}from"./row-fit.js";import{StyleTable as xe}from"./styles.js";import{cellEntryText as ne,parseInput as ie}from"./input.js";import{noteChanges as oe}from"./changes.js";import{overrideRuns as _e}from"../cells/rich-runs.js";import{sheetRenameHooks as be}from"./sparse.js";import{shiftRuleFormulas as re}from"../cells/cf-file.js";import{expandStructured as Re,formulaEntryLimit as Me,FormulaSyntaxError as L,tokenize as Fe,toDisplayFormula as le,toFileFormula as Ae}from"../calc/parser.js";const Ie=200,Ee=new Set(["entry","clear","format","borders","fill"]);class Te{constructor(){this.ids=new Int32Array(1024),this.list=[]}set(t,e){if(t>=this.ids.length){let i=this.ids.length*2;for(;i<=t;)i*=2;const r=new Int32Array(i);r.set(this.ids),this.ids=r}const n=this.list.length;(n===0||this.list[n-1]!==e)&&this.list.push(e),this.ids[t]=this.list.length}get(t){const e=t<this.ids.length?this.ids[t]:0;return e===0?void 0:this.list[e-1]}}class ${constructor(){this.capacity=1024,this.count=0,this.rows=new Uint32Array(this.capacity),this.cols=new Uint16Array(this.capacity),this.kinds=new Uint8Array(this.capacity),this.styles=new Uint16Array(this.capacity),this.values=new Float64Array(this.capacity),this.formulas=null,this.vms=null}_grow(){const t=this.capacity*2,e=(n,i)=>{const r=new n(t);return r.set(i),r};this.rows=e(Uint32Array,this.rows),this.cols=e(Uint16Array,this.cols),this.kinds=e(Uint8Array,this.kinds),this.styles=e(Uint16Array,this.styles),this.values=e(Float64Array,this.values),this.capacity=t}push(t,e,n){this.count===this.capacity&&this._grow();const i=this.count++,r=t.kind(e,n)&~(W|J);if(this.rows[i]=e,this.cols[i]=n,this.kinds[i]=r,this.styles[i]=t.cellStyle(e,n),this.values[i]=t.value(e,n),r&F&&(this.formulas===null&&(this.formulas=new Te),this.formulas.set(i,t.formula(e,n))),t.valueMeta!==null){const s=t.valueMeta.get(e*b+n);s!==void 0&&(this.vms??=new Map).set(i,s)}}}class Ye{constructor(){this.sheets=[new B(`${te()}1`)],this.activeSheet=0,this.strings=new Ce,this.styles=new xe,this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.source=null,this.formulasEdited=!1,this.edits=0,this._dirty=!1,this.engine=null,this.selectedSheets=null}get sheet(){return this.sheets[this.activeSheet]}get dirty(){return this._dirty}set dirty(t){t&&this.edits++,this._dirty=!!t}onChange(t){this.listeners.add(t)}_emit(t){this.dirty=!0;for(const e of this.listeners)e(t)}addSheet(t){const e=te();let n=1,i=t??`${e}${n}`;const r=o=>this.sheets.some(l=>l.name.toLowerCase()===o.toLowerCase());for(;r(i);)i=`${e}${++n}`;const s=new B(i);return this.sheets.push(s),this.activeSheet=this.sheets.length-1,this.engine?.sheetsChanged(),this._emit("sheets"),s}deleteSheet(t){return this.sheets.filter(e=>!e.hidden).length<=1?!1:(this._shrink3D(t),this._refErrorsFor(t),this._removeSheet(t))}_removeSheet(t){if(this.sheets.length<=1)return!1;const[e]=this.sheets.splice(t,1);if(this.selectedSheets?.delete(e),this._forgetSheet(e,t),this.engine)for(const[i,r]of this.engine.tables)r.sheet===e&&this.engine.tables.delete(i);this._reindexNames(i=>i===t?-1:i>t?i-1:i),this.activeSheet>=this.sheets.length&&(this.activeSheet=this.sheets.length-1);const n=this.activeSheet;for(;this.sheets[this.activeSheet].hidden&&(this.activeSheet=(this.activeSheet+1)%this.sheets.length,this.activeSheet!==n););return this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),!0}_forgetSheet(t,e){const n=r=>r.sheet===t||r.sheet===void 0&&r.sheetIndex===e||(r.extra?.parts??[]).some(n),i=r=>{r.sheetIndex>e&&r.sheetIndex--;for(const s of r.extra?.parts??[])i(s)};for(const r of[this.undoStack,this.redoStack]){const s=r.filter(o=>!n(o));s.forEach(i),r.splice(0,r.length,...s)}}moveSheet(t,e){if(t===e)return;const n=this.sheet,[i]=this.sheets.splice(t,1);this.sheets.splice(e,0,i),this.activeSheet=this.sheets.indexOf(n);const r=o=>o===t?e:t<e?o>t&&o<=e?o-1:o:o>=e&&o<t?o+1:o,s=o=>{o.sheetIndex=r(o.sheetIndex);for(const l of o.extra?.parts??[])s(l)};for(const o of this.undoStack)s(o);for(const o of this.redoStack)s(o);this.structureEdited=!0,this._reindexNames(r),this.engine?.orderChanged(),this._emit("sheets")}_copyTables(t,e){const n=new Map,i=new Set;for(const r of de(this,t)){const{sheet:s,part:o,id:l,source:a,sheetIndex:c,...h}=r;let u=this.engine.tables.size+n.size+2,p,f;do{const d=String(u++),g=r.name.slice(0,255-d.length);p=g+d,ye(p)||(p=g.slice(0,254-d.length)+"_"+d),f=p.toUpperCase()}while(i.has(f)||this.engine.tables.has(f)||this.engine.names.has(f));i.add(f),n.set(r.name.toUpperCase(),{...I(h),name:p,sheet:e,isNew:!0,dirty:!0})}return n}_copyScopedNames(t,e,n,i){const{engine:r}=this;if(!r||r.names.size===0)return;const s=`${t}!`;let o=!1;for(const[l,a]of[...r.names])l.startsWith(s)&&(r.names.set(`${t+1}!${l.slice(s.length)}`,{...a,text:i(Q(a.text,e.name,n.name))}),o=!0);o&&(this.namesChanged=!0)}_reindexNames(t){const{engine:e}=this;if(!e||e.names.size===0)return;const n=[];let i=!1;for(const[r,s]of e.names){const o=r.indexOf("!"),l=o<0?0:t(Number(r.slice(0,o)));o>=0&&l!==Number(r.slice(0,o))&&(i=!0),o<0?n.push([r,s]):l>=0&&n.push([`${l}!${r.slice(o+1)}`,s])}if(i){e.names.clear();for(const[r,s]of n)e.names.set(r,s);e.nameTemplates.clear(),this.namesChanged=!0,e.rebuild()}}duplicateSheet(t){const e=this.sheets[t];let i=`${e.name} (2)`,r=2;for(;this.sheets.some(h=>h.name.toLowerCase()===i.toLowerCase());)i=`${e.name} (${++r})`;const s=new B(i),o=this._copyTables(e,s),l=h=>ze(h,o,e.name,s.name);for(const h of o.values())for(const u of h.totals??[])u?.formula&&(u.formula=l(u.formula));e.columns.forEach((h,u)=>{const p=[];h.forEach((f,d)=>{p[d]={kinds:f.kinds.slice(),values:f.values.slice(),styles:f.styles?f.styles.slice():null}}),s.columns[u]=p}),s.maxRow=e.maxRow,s.maxCol=e.maxCol,s.rows=e.rows.shifted(0,0),s.cols=e.cols.shifted(0,0);const a=new Map;e.formulas.forEachCell((h,u,p)=>{let f=a.get(p);f===void 0&&(f={...p,tpl:void 0},p.f!==void 0&&(f.f=l(p.f)),p.sf!==void 0&&(f.sf=l(p.sf)),a.set(p,f)),s.setFormula(h,u,f)}),s.merges=e.merges.map(h=>({...h})),s.rowStyles=e.rowStyles?new Map(e.rowStyles):null,s.colStyles=e.colStyles?new Map(e.colStyles):null,s.frozenRows=e.frozenRows,s.frozenCols=e.frozenCols,s.showGridlines=e.showGridlines,s.cellTypes=e.cellTypes?new Map(e.cellTypes):null,s.sparkRules=e.sparkRules,s.cellDropdowns=e.cellDropdowns?new Map(e.cellDropdowns):null,s.cellTags=e.cellTags?new Map(e.cellTags):null,s.cellButtons=e.cellButtons?new Map(e.cellButtons):null,s.cellStates=e.cellStates?e.cellStates.slice():null,s.autoMerges=e.autoMerges?e.autoMerges.map(h=>({...h})):null,s.background=e.background,s.outlineColumn=e.outlineColumn?{...e.outlineColumn}:null,s.frozenTrailingRows=e.frozenTrailingRows,s.frozenTrailingCols=e.frozenTrailingCols,s.hideZeros=e.hideZeros,s.hideHeadings=e.hideHeadings,s.isChartSheet=e.isChartSheet,s.hideOutline=e.hideOutline,s.gridColorId=e.gridColorId,s.areaOffset=e.areaOffset,s.selectionPolicy=e.selectionPolicy,s.selectionUnit=e.selectionUnit,s.gridlineAxes=e.gridlineAxes,s.gridColor=e.gridColor,s.tabStyles=e.tabStyles;const c=I;if(s.cf=c(e.cf),s.validations=c(e.validations),o.size){for(const h of s.cf??[])h.rules=h.rules.map(u=>re(u,l));for(const h of s.validations??[])h.formula1&&(h.formula1=l(h.formula1)),h.formula2&&(h.formula2=l(h.formula2))}s.comments=c(e.comments),s.threads=c(e.threads),s.hyperlinks=e.hyperlinks?e.hyperlinks.map(h=>({...c({...h,_ranges:void 0})})):e.hyperlinks,s.autoFilter=c(e.autoFilter),s.filteredRows=e.filteredRows?new Set(e.filteredRows):e.filteredRows,s.pageSetup=c(e.pageSetup),s.tabColor=e.tabColor,s.protection=c(e.protection),s.rtl=e.rtl,s.zoom=e.zoom,s.valueMeta=e.valueMeta?new Map(e.valueMeta):null,s.colsChanged=!0,s.viewChanged=!0,this.sheets.splice(t+1,0,s);for(const h of o.values())this.engine.tables.set(h.name.toUpperCase(),h);return this.activeSheet=t+1,this._reindexNames(h=>h>t?h+1:h),this._copyScopedNames(t,e,s,l),this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),s}sheetNameProblem(t,e){const n=e.trim().slice(0,31);return!n||/[\\/?*[\]:]/.test(n)||/^'|'$/.test(n)?"rules":n.toLowerCase()==="history"?"reserved":this.sheets.some((i,r)=>r!==t&&i.name.toLowerCase()===n.toLowerCase())?"taken":null}renameSheet(t,e){const n=e.trim().slice(0,31);if(this.sheetNameProblem(t,e)!==null)return!1;const i=this.sheets[t].name;this.sheets[t].name=n,this.engine?.sheetsChanged(),this._renameInFormulas(i,n);for(const r of be)r(this,i,n);return this._emit("sheets"),!0}_shrink3D(t){const e=this.sheets[t].name.toLowerCase(),n=l=>this.sheets.findIndex(a=>a.name.toLowerCase()===l.toLowerCase()),i=l=>l[0]==="'"?l.slice(1,-1).replace(/''/g,"'"):l,r=/((?:'(?:[^']|'')+'|[A-Za-z_\u00C0-\uFFFF][\w.\u00C0-\uFFFF]*)):((?:'(?:[^']|'')+'|[A-Za-z_\u00C0-\uFFFF][\w.\u00C0-\uFFFF]*))!/g,s=l=>l.replace(r,(a,c,h,u)=>{if(l[u-1]==="]")return a;const p=i(c),f=i(h);if(p.toLowerCase()!==e&&f.toLowerCase()!==e)return a;let d=n(p),g=n(f);if(d<0||g<0||(d>g&&([d,g]=[g,d]),d===t&&d++,g===t&&g--,d>g))return a;const y=w=>X(this.sheets[w].name);return d===g?`${y(d)}!`:`${y(d)}:${y(g)}!`}),o=l=>l.includes(":")&&l.includes("!")?l.split(/("(?:[^"]|"")*")/).map((a,c)=>c%2?a:s(a)).join(""):l;for(const l of this.sheets){const a=new Map;l.formulas.forEachCell((c,h,u)=>{let p=a.get(u);if(p===void 0){const f=u.f??u.sf,d=typeof f=="string"?o(f):f;p=d===f?null:u.f!==void 0?{...u,f:d,tpl:void 0}:{...u,sf:d,tpl:void 0},a.set(u,p)}p!==null&&l.setFormula(c,h,p)})}for(const l of this.engine?.names.values()??[])typeof l.text=="string"&&(l.text=o(l.text));this.engine?.templates.clear()}_refErrorsFor(t){const e=ee(this.sheets[t].name),n=s=>s.split(/("(?:[^"]|"")*")/).map((o,l)=>l%2?o:o.replace(e,"#REF!")).join(""),i=s=>typeof s=="string"&&s!==""?n(s):s,r=this.sheets[t];for(const s of this.sheets){if(s===r)continue;s.cf?.length>0&&(s.cf=s.cf.map(l=>({...l,rules:l.rules.map(a=>re(a,i))})),s.cfChanged=!0,s.cfEval?.invalidate()),s.validations?.length>0&&(s.validations=s.validations.map(l=>({...l,formula1:i(l.formula1),formula2:i(l.formula2)})),s.validationsChanged=!0);const o=new Map;s.formulas.forEachCell((l,a,c)=>{let h=o.get(c);if(h===void 0){const u=c.f??c.sf,p=typeof u=="string"?n(u):u;h=p===u?null:c.f!==void 0?{...c,f:p,tpl:void 0}:{...c,sf:p,tpl:void 0},o.set(c,h)}h!==null&&(s.setFormula(l,a,h),this.formulasEdited=!0)})}for(const s of this.engine?.names.values()??[])typeof s.text=="string"&&(s.text=n(s.text));this.engine?.templates.clear()}_renameInFormulas(t,e){const n=ee(t);let i=!1;for(const r of this.sheets){const s=new Map;r.formulas.forEachCell((o,l,a)=>{let c=s.get(a);if(c===void 0){const h=a.f??a.sf;if(h===void 0||!n.test(h))n.lastIndex=0,c=null;else{n.lastIndex=0;const u=Q(h,t,e);c=a.f!==void 0?{...a,f:u,tpl:void 0}:{...a,sf:u,tpl:void 0}}s.set(a,c)}c!==null&&(r.setFormula(o,l,c),i=!0)})}i&&(this.formulasEdited=!0,this.engine?.templates.clear(),this.engine?.rebuild())}editText(t,e,n){const i=t.kind(e,n);if(this.engine?.dataTables.length){const o=this.engine.dataTableAt(t,e,n);if(o){const{info:l}=o,a=l.dt2D==="1",c=l.dtr==="1";return`{=TABLE(${a||c?l.r1:""},${a?l.r2:c?"":l.r1})}`}}if(i&pe&&this.engine){const o=this.engine.spillMaster(t,e,n);if(o)return this.editText(t,o.row,o.col)}if(i&F){const o=t.formula(e,n),l=o&&!o.typed&&o.t!=="array"&&o.tpl?.rangeResult?"=@":"=";if(o&&o.f!==void 0){const a=l+le(o.f);return o.t==="array"&&!o.cm?`{${a}}`:a}if(o&&o.sf!==void 0){const a=Math.floor(o.base/b),c=o.base-a*b;return l+le(we(o.sf,e-a,n-c))}}const r=i&Z;if(r===T)return"";const s=t.value(e,n);if(r===U&&t.valueMeta!==null&&!(i&F)){const o=this.richImages?.get(t.valueMeta.get(e*b+n));if(o!==void 0)return o.alt??"";const l=this.richValues?.indexOfVm(t.valueMeta.get(e*b+n))??-1,a=l>=0?this.richValues.view(l):null;if(a!==null)return a.text}return r===A?this.styles.get(t.style(e,n)).quotePrefix?`'${this.strings.get(s)}`:this.strings.get(s):r===D?s?"TRUE":"FALSE":r===U?me[s]??"#N/A":String(s)}transact(t,e,n=null){if(this.guard&&!this.guard(t))return;const i=this.selectedSheets;!n&&i?.size>1&&Ee.has(t)&&(n=this.sheets.filter(s=>i.has(s)&&(!s.protection||s===this.sheet)));const r=n?this._runGroup(t,e,n):this._runOn(this.sheet,t,e);r!==null&&this._pushUndo(r)}transactOn(t,e,n){const i=this._runOn(t,e,n);i!==null&&this._pushUndo(i)}_runOn(t,e,n){const i=new $,r={sheet:t,log:i,saveCell:(f,d)=>i.push(t,f,d)},{maxRow:s,maxCol:o}=t,l=this.recorder?.length,a=this.formulasEdited;let c;try{c=n(r)??null}catch(f){throw f instanceof L&&(ae(t,i),t.maxRow=s,t.maxCol=o,this.formulasEdited=a,l!==void 0&&(this.recorder.length=l),this.engine?.cellsChanged(t,i.rows,i.cols,i.count)),f}e!=="entry"&&this.engine?.presentationChanged(),t.changes!==null&&i.count>0&&oe(this,t,i),i.vms!==null&&Oe(t,i);const h=i.count>0&&this.engine?.tables.size>0?fe(this,r,i):null,u=(f,d)=>g=>u(f(g),d(g)),p=c&&h?u(c,h):c??h;return i.count===0&&p===null?null:(t.revision++,this.engine?.cellsChanged(t,i.rows,i.cols,i.count),{sheetIndex:t===this.sheet?this.activeSheet:this.sheets.indexOf(t),sheet:t,log:i,label:e,extra:p})}_runGroup(t,e,n){const i=[],r=this.activeSheet,s=this.recorder?.length,o=this.formulasEdited,l=[];try{for(const a of n){const{maxRow:c,maxCol:h}=a,u=this._runOn(a,t,e);u!==null&&(i.push(u),l.push([a,c,h]))}}catch(a){if(a instanceof L){this.rollbackSlices(i);for(const[c,h,u]of l)c.maxRow=h,c.maxCol=u;this.activeSheet=r,this.formulasEdited=o,s!==void 0&&(this.recorder.length=s)}throw a}return i.length===0?null:{sheetIndex:this.activeSheet,sheet:this.sheet,log:new $,label:t,extra:H(this,i)}}runSlice(t,e,n){const i=this._runOn(t,e,n);return i!==null&&this._emit("cells"),i}pushFolded(t,e,n){t.length!==0&&this._pushUndo({sheetIndex:this.sheets.indexOf(n),sheet:n,log:new $,label:e,extra:H(this,t)})}rollbackSlices(t){for(let e=t.length-1;e>=0;e--)this._restore(t[e]);this._emit("cells")}_pushUndo(t){this.allowUndo===!1?this.undoStack.length=0:(this.undoStack.push(t),this.undoStack.length>(this.historyLimit??Ie)&&this.undoStack.shift()),this.redoStack.length=0,this._emit("cells")}_restore(t){const e=t.sheet??this.sheets[t.sheetIndex],{log:n}=t,i=new $;if(ae(e,n,i),n.vms!==null){e.valueMeta=new Map(e.valueMeta??[]);for(const[o,l]of n.vms)e.valueMeta.set(n.rows[o]*b+n.cols[o],l)}let r=null;t.extra&&(r=t.extra(e)),this.engine?.presentationChanged(),e.changes!==null&&n.count>0&&oe(this,e,i),e.revision++,this.engine?.cellsChanged(e,n.rows,n.cols,n.count);const s=this.sheets.indexOf(e);return s>=0&&(this.activeSheet=s),{sheetIndex:s>=0?s:t.sheetIndex,sheet:e,log:i,label:t.label,extra:r}}undo(){const t=this.undoStack.pop();return t?(this.redoStack.push(this._restore(t)),this._emit("cells"),!0):!1}redo(){const t=this.redoStack.pop();return t?(this.undoStack.push(this._restore(t)),this._emit("cells"),!0):!1}setInput(t,e,n,i,{overLimitAsText:r=!1}={}){const{sheet:s}=t,o=s.style(e,n),l=i!==""&&this.styles.get(o).numFmt==="@";let a=l?{kind:A,text:i[0]==="'"?i.slice(1):i}:ie(i);if(a.kind===F){const h=Me(a.formula);if(h){if(!r)throw new L(h);a={kind:A,text:i}}}if(this.recorder){const h=a.kind===A&&i.startsWith("=")&&!l?`'${i}`:i;this.recorder.push(`sheet.setValue(${JSON.stringify(ge(e,n))}, ${JSON.stringify(h)});`)}t.saveCell(e,n),s.setFormula(e,n,null);const c=i[0]==="'"&&i.length>1;switch((c||this.styles.get(o).quotePrefix)&&s.setStyle(e,n,this.styles.derive(o,{quotePrefix:c})),a.kind){case T:s.setCell(e,n,T,0);break;case P:s.setCell(e,n,P,a.value),a.format&&this.styles.get(o).numFmt==="General"&&s.setStyle(e,n,this.styles.derive(s.style(e,n),{numFmt:a.format}));break;case D:s.setCell(e,n,D,a.value);break;case U:s.setCell(e,n,U,a.value);break;case F:s.setCell(e,n,F|T,0),s.setFormula(e,n,{f:Ae(this._expandTableRefs(ue(a.formula,this.engine?.tables),s,e,n),this.engine?.names??null),typed:this.dynamicArrays!==!1}),this.formulasEdited=!0;break;default:s.setCell(e,n,A,this.strings.add(ne(a.text)))}}setRichInput(t,e,n,i,r){const{sheet:s}=t;t.saveCell(e,n),s.setFormula(e,n,null);const o=ne(i);s.setCell(e,n,A,this.strings.addRich(o,o===i?r:r?.filter(l=>l.at<o.length)))}_expandTableRefs(t,e,n,i){const r=this.engine;return!r||r.tables.size===0?t:Re(t,()=>{for(const s of r.tables.values())if(s.sheet===e&&n>=s.r0&&n<=s.r1&&i>=s.c0&&i<=s.c1)return s;return null})}clearRange(t,e="contents",{visibleOnly:n=!1}={}){this.sheet.dataRanges?.cleared(t)||this.transact("clear",i=>{const{sheet:r}=i,s=[];if(e!=="contents")for(const{r0:l,c0:a,r1:c,c1:h}of t){const u=l===0&&c===Y-1,p=a===0&&h===b-1,f=(d,g,y,w)=>{for(const[C,x]of[...g])C<y||C>w||(s.push([d,C,x]),g.delete(C))};u&&r.colStyles!==null&&f("col",r.colStyles,a,h),p&&r.rowStyles!==null&&f("row",r.rowStyles,l,c)}const o=n&&r.filteredRows?.size>0?r.filteredRows:null;for(const{r0:l,c0:a,r1:c,c1:h}of t){const u=Math.min(h,r.maxCol),p=Math.min(c,r.maxRow);for(let f=a;f<=u;f++)if(r.columns[f]!==void 0)for(let d=l;d<=p;d++){if(r._chunk(d,f)===void 0){d|=1023;continue}if(o!==null&&o.has(d))continue;const y=r.kind(d,f)!==0,w=r.cellStyle(d,f)!==0;if(e==="formats"){if(!w)continue;i.saveCell(d,f),r.setStyle(d,f,0);continue}!y&&!(e==="all"&&w)||(i.saveCell(d,f),r.setCell(d,f,T,0),r.setFormula(d,f,null),e==="all"&&r.setStyle(d,f,0))}}return s.length>0?V([],s):void 0})}applyStyle(t,e,{measureRow:n,numberFit:i}={}){const r=JSON.stringify(e);if(this.recorder)for(const s of t)this.recorder.push(`sheet.setFormat(${JSON.stringify(Se(s))}, ${r});`);this.transact("format",s=>{const{sheet:o}=s;this.strings.rich!==null&&_e(this,s,t,e);const l=[],a=new Set,c=[],h=[],u=(g,y,w)=>{const C=g*2048+y;a.has(C)||(a.add(C),l.push(g,y,w.styles===null?null:w.styles.slice()))},p=(g,y,w)=>{w===0&&(o.rowStyles?.has(g)||o.colStyles?.has(y))&&(w=this.styles.explicitDefault()),o.setStyle(g,y,w)};for(const{r0:g,c0:y,r1:w,c1:C}of t){const x=g===0&&w===Y-1,v=y===0&&C===b-1,k=x||v,R=k?Math.min(w,o.maxRow):w,he=k?Math.min(C,o.maxCol):C;for(let S=y;S<=he&&g<=R;S++){const _=o.columns[S];if(!(k&&!_))for(let M=g>>>z;M<=R>>>z;M++){const q=M<<z,G=Math.max(g,q),ce=Math.min(R,q+K),N=k?_[M]:o._ensure(G,S);if(!(k&&!N?.styles)){u(S,M,N);for(let E=G;E<=ce;E++)(!k||N.styles[E&K])&&p(E,S,this.styles.derive(o.style(E,S),e,r))}}}const O=S=>this.styles.derive(S,e,r),j=(S,_,M)=>{u(_,S>>>z,o._ensure(S,_)),o.setStyle(S,_,M||this.styles.explicitDefault())};if(v&&x){ve(o,O,c);for(const[S,_]of o.rowStyles??[])c.push(["row",S,_]),o.rowStyles.set(S,O(_))}else if(x)for(let S=y;S<=C;S++)se(o,"col",S,O,c,j);else if(v)for(let S=g;S<=w;S++)se(o,"row",S,O,c,j)}const f=(g,y,w)=>{const C=o[g];w!==C.sizeOf(y)&&(h.push([g,y,C.isCustom(y)?C.sizeOf(y):null,C.isAuto(y)]),C.setSize(y,w,!0),g==="cols"&&(o.colsChanged=!0))},d=e.fontSize!==void 0||e.wrap!==void 0||e.rotation!==void 0||["justify","distributed"].includes(e.hAlign)||["justify","distributed"].includes(e.vAlign);for(const{r0:g,r1:y,c0:w,c1:C}of t){const x=Math.min(y,o.maxRow);if(d&&x-g<=2e3)for(let v=g;v<=x;v++)f("rows",v,ke(o,this,v,n));if(i)for(const v of i.cols){if(v<w||v>C||!o.columns[v]||o.cols.isCustom(v)&&!o.cols.isAuto(v))continue;let k=o.cols.sizeOf(v);for(const R of i.rows)R>=g&&R<=x&&(o.kind(R,v)&Z)===P&&(k=Math.max(k,i.measure(o,R,v)));f("cols",v,k)}}return V(l,c,h)})}}function ae(m,t,e){for(let n=t.count-1;n>=0;n--){const i=t.rows[n],r=t.cols[n];e?.push(m,i,r),m.setCell(i,r,t.kinds[n],t.values[n]),m.setStyle(i,r,t.styles[n]),m.setFormula(i,r,t.kinds[n]&F?t.formulas.get(n):null)}}function H(m,t){const e=()=>{const n=[];for(let i=t.length-1;i>=0;i--)n.push(m._restore(t[i]));return H(m,n)};return e.parts=t,e}function Oe(m,t){let e=null;for(const n of t.vms.keys()){const i=t.rows[n],r=t.cols[n];(m.kind(i,r)&~(W|J))===t.kinds[n]&&m.value(i,r)===t.values[n]||(e??=new Map(m.valueMeta),e.delete(i*b+r))}e!==null&&(m.valueMeta=e.size>0?e:null)}function ze(m,t,e,n){if(!t.size||typeof m!="string")return m;let i;try{i=Fe(m)}catch(o){if(o instanceof L)return m;throw o}let r="",s=0;for(let o=0;o<i.length;o++){const l=i[o],a=l.t==="name"?m.slice(l.s,l.e):l.t==="table"?l.v.name:null;if(!a)continue;const c=t.get(a.toUpperCase());if(!c)continue;let h=o-1;for(;i[h]?.t==="ws";)h--;const u=i[h];if(u?.t==="sheet"){const{book:p,sheet:f,sheet2:d}=u.v;if(p!==null||d!==null)continue;if(f.toUpperCase()===e.toUpperCase())r+=m.slice(s,u.s)+X(n)+"!",s=u.e;else if(f.toUpperCase()!==n.toUpperCase())continue}r+=m.slice(s,l.s)+c.name,s=l.s+a.length}return s?r+m.slice(s):m}function I(m){if(m===null||typeof m!="object")return m;if(Array.isArray(m))return m.map(I);if(m instanceof Map)return new Map([...m].map(([e,n])=>[e,I(n)]));if(m instanceof Set)return new Set([...m].map(I));if(ArrayBuffer.isView(m))return m.slice();const t={};for(const[e,n]of Object.entries(m))!e.startsWith("_")&&typeof n!="function"&&(t[e]=I(n));return t}function V(m,t,e=[]){return n=>{const i=[];for(let o=0;o<m.length;o+=3){const l=m[o],a=m[o+1],c=n.columns[l]?.[a];c!==void 0&&(i.push(l,a,c.styles),c.styles=m[o+2])}const r=[];for(let o=t.length-1;o>=0;o--){const[l,a,c]=t[o];if(l==="columns"){r.push([l,a,n.colStyles]),n.colStyles=c,n.colsChanged=!0;continue}l==="col"&&(n.colsChanged=!0);const h=l==="col"?"colStyles":"rowStyles",u=n[h]??=new Map;r.push([l,a,u.get(a)]),c===void 0?u.delete(a):u.set(a,c)}const s=[];for(let o=e.length-1;o>=0;o--){const[l,a,c,h]=e[o],u=n[l];s.push([l,a,u.isCustom(a)?u.sizeOf(a):null,u.isAuto(a)]),u.setSize(a,c,h),l==="cols"&&(n.colsChanged=!0)}return V(i,r,s)}}export{$ as CellLog,Ee as GROUP_LABELS,Ye as Workbook,H as foldEntries,ie as parseInput,V as swapStyles};
1
+ import{expandBareTables as ue}from"../slicers/structured.js";import{syncTableHeaders as fe,tablesOf as de}from"./tables.js";import{BOOL as D,CHUNK_BITS as z,CHUNK_MASK as W,EMPTY as I,ERR as U,ERRORS as me,FORMULA as F,DIRTY as J,EVALUATING as Z,KIND_MASK as Y,NUM as P,Sheet as B,SPILL as pe,STR as T}from"./sheet.js";import{cellRef as ge,isValidName as ye,MAX_COLS as R,MAX_ROWS as X,quoteSheetName as Q,rangeRef as Se,renameSheetInFormula as V,sheetReferencePattern as ee}from"./address.js";import{translateFormula as we}from"./formula-refs.js";import{sheetStem as te}from"./default-names.js";import{StringTable as Ce}from"./strings.js";import{formatAxis as se,formatSheetColumns as ve}from"./axis-styles.js";import{autoRowHeight as ke}from"./row-fit.js";import{StyleTable as xe}from"./styles.js";import{cellEntryText as ne,parseInput as ie}from"./input.js";import{DATE_1904_OFFSET as _e}from"./numfmt.js";import{noteChanges as oe}from"./changes.js";import{overrideRuns as Re}from"../cells/rich-runs.js";import{sheetRenameHooks as be}from"./sparse.js";import{shiftRuleFormulas as re}from"../cells/cf-file.js";import{expandStructured as Me,formulaEntryLimit as Fe,FormulaSyntaxError as L,tokenize as Te,toDisplayFormula as le,toFileFormula as Ae}from"../calc/parser.js";const Ee=200,Ie=new Set(["entry","clear","format","borders","fill"]);class Oe{constructor(){this.ids=new Int32Array(1024),this.list=[]}set(t,e){if(t>=this.ids.length){let o=this.ids.length*2;for(;o<=t;)o*=2;const r=new Int32Array(o);r.set(this.ids),this.ids=r}const i=this.list.length;(i===0||this.list[i-1]!==e)&&this.list.push(e),this.ids[t]=this.list.length}get(t){const e=t<this.ids.length?this.ids[t]:0;return e===0?void 0:this.list[e-1]}}class ${constructor(){this.capacity=1024,this.count=0,this.rows=new Uint32Array(this.capacity),this.cols=new Uint16Array(this.capacity),this.kinds=new Uint8Array(this.capacity),this.styles=new Uint16Array(this.capacity),this.values=new Float64Array(this.capacity),this.formulas=null,this.vms=null}_grow(){const t=this.capacity*2,e=(i,o)=>{const r=new i(t);return r.set(o),r};this.rows=e(Uint32Array,this.rows),this.cols=e(Uint16Array,this.cols),this.kinds=e(Uint8Array,this.kinds),this.styles=e(Uint16Array,this.styles),this.values=e(Float64Array,this.values),this.capacity=t}push(t,e,i){this.count===this.capacity&&this._grow();const o=this.count++,r=t.kind(e,i)&~(J|Z);if(this.rows[o]=e,this.cols[o]=i,this.kinds[o]=r,this.styles[o]=t.cellStyle(e,i),this.values[o]=t.value(e,i),r&F&&(this.formulas===null&&(this.formulas=new Oe),this.formulas.set(o,t.formula(e,i))),t.valueMeta!==null){const s=t.valueMeta.get(e*R+i);s!==void 0&&(this.vms??=new Map).set(o,s)}}}class Qe{get namesChanged(){return this._namesChanged}set namesChanged(t){this._namesChanged=t,t&&(this.namesRevision=(this.namesRevision??0)+1)}constructor(){this.sheets=[new B(`${te()}1`)],this.activeSheet=0,this.date1904=!1,this.strings=new Ce,this.styles=new xe,this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.source=null,this.formulasEdited=!1,this.edits=0,this._dirty=!1,this.engine=null,this.selectedSheets=null}get sheet(){return this.sheets[this.activeSheet]}get dateOffset(){return this.date1904?_e:0}get dirty(){return this._dirty}set dirty(t){t&&this.edits++,this._dirty=!!t}onChange(t){this.listeners.add(t)}clearHistory(){if(this.historyCleared=(this.historyCleared??0)+1,!(this.undoStack.length===0&&this.redoStack.length===0)){this.undoStack.length=0,this.redoStack.length=0;for(const t of this.listeners)t("history")}}_emit(t){(t==="cells"||t==="bulk")&&(this.formatValueRevision=(this.formatValueRevision??0)+1),this.dirty=!0;for(const e of this.listeners)e(t)}addSheet(t){const e=te();let i=1,o=t??`${e}${i}`;const r=n=>this.sheets.some(l=>l.name.toLowerCase()===n.toLowerCase());for(;r(o);)o=`${e}${++i}`;const s=new B(o);return this.sheets.push(s),this.activeSheet=this.sheets.length-1,this.engine?.sheetsChanged(),this._emit("sheets"),s}deleteSheet(t){return this.sheets.filter(e=>!e.hidden).length<=1?!1:(this._shrink3D(t),this._refErrorsFor(t),this._removeSheet(t))}_removeSheet(t){if(this.sheets.length<=1)return!1;const[e]=this.sheets.splice(t,1);if(this.selectedSheets?.delete(e),this._forgetSheet(e,t),this.engine)for(const[o,r]of this.engine.tables)r.sheet===e&&this.engine.tables.delete(o);this._reindexNames(o=>o===t?-1:o>t?o-1:o),this.activeSheet>=this.sheets.length&&(this.activeSheet=this.sheets.length-1);const i=this.activeSheet;for(;this.sheets[this.activeSheet].hidden&&(this.activeSheet=(this.activeSheet+1)%this.sheets.length,this.activeSheet!==i););return this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),!0}_forgetSheet(t,e){const i=r=>r.sheet===t||r.sheet===void 0&&r.sheetIndex===e||(r.extra?.parts??[]).some(i),o=r=>{r.sheetIndex>e&&r.sheetIndex--;for(const s of r.extra?.parts??[])o(s)};for(const r of[this.undoStack,this.redoStack]){const s=r.filter(n=>!i(n));s.forEach(o),r.splice(0,r.length,...s)}}moveSheet(t,e){if(t===e)return;const i=this.sheet,[o]=this.sheets.splice(t,1);this.sheets.splice(e,0,o),this.activeSheet=this.sheets.indexOf(i);const r=n=>n===t?e:t<e?n>t&&n<=e?n-1:n:n>=e&&n<t?n+1:n,s=n=>{n.sheetIndex=r(n.sheetIndex);for(const l of n.extra?.parts??[])s(l)};for(const n of this.undoStack)s(n);for(const n of this.redoStack)s(n);this.structureEdited=!0,this._reindexNames(r),this.engine?.orderChanged(),this._emit("sheets")}_copyTables(t,e){const i=new Map,o=new Set;for(const r of de(this,t)){const{sheet:s,part:n,id:l,source:c,sheetIndex:a,...h}=r;let u=this.engine.tables.size+i.size+2,p,f;do{const d=String(u++),g=r.name.slice(0,255-d.length);p=g+d,ye(p)||(p=g.slice(0,254-d.length)+"_"+d),f=p.toUpperCase()}while(o.has(f)||this.engine.tables.has(f)||this.engine.names.has(f));o.add(f),i.set(r.name.toUpperCase(),{...A(h),name:p,sheet:e,isNew:!0,dirty:!0})}return i}_copyScopedNames(t,e,i,o){const{engine:r}=this;if(!r||r.names.size===0)return;const s=`${t}!`;let n=!1;for(const[l,c]of[...r.names])l.startsWith(s)&&(r.names.set(`${t+1}!${l.slice(s.length)}`,{...c,text:o(V(c.text,e.name,i.name))}),n=!0);n&&(this.namesChanged=!0)}_reindexNames(t){const{engine:e}=this;if(!e||e.names.size===0)return;const i=[];let o=!1;for(const[r,s]of e.names){const n=r.indexOf("!"),l=n<0?0:t(Number(r.slice(0,n)));n>=0&&l!==Number(r.slice(0,n))&&(o=!0),n<0?i.push([r,s]):l>=0&&i.push([`${l}!${r.slice(n+1)}`,s])}if(o){e.names.clear();for(const[r,s]of i)e.names.set(r,s);e.nameTemplates.clear(),this.namesChanged=!0,e.rebuild()}}duplicateSheet(t){const e=this.sheets[t];let o=`${e.name} (2)`,r=2;for(;this.sheets.some(h=>h.name.toLowerCase()===o.toLowerCase());)o=`${e.name} (${++r})`;const s=new B(o),n=this._copyTables(e,s),l=h=>Ue(h,n,e.name,s.name);for(const h of n.values())for(const u of h.totals??[])u?.formula&&(u.formula=l(u.formula));e.columns.forEach((h,u)=>{const p=[];h.forEach((f,d)=>{p[d]={kinds:f.kinds.slice(),values:f.values.slice(),styles:f.styles?f.styles.slice():null}}),s.columns[u]=p}),s.maxRow=e.maxRow,s.maxCol=e.maxCol,s.rows=e.rows.shifted(0,0),s.cols=e.cols.shifted(0,0);const c=new Map;e.formulas.forEachCell((h,u,p)=>{let f=c.get(p);f===void 0&&(f={...p,tpl:void 0},p.f!==void 0&&(f.f=l(p.f)),p.sf!==void 0&&(f.sf=l(p.sf)),c.set(p,f)),s.setFormula(h,u,f)}),s.merges=e.merges.map(h=>({...h})),s.rowStyles=e.rowStyles?new Map(e.rowStyles):null,s.colStyles=e.colStyles?new Map(e.colStyles):null,s.frozenRows=e.frozenRows,s.frozenCols=e.frozenCols,s.showGridlines=e.showGridlines,s.cellTypeRules=e.cellTypeRules,s.cellTypes=e.cellTypes?new Map(e.cellTypes):null,s.sparkRules=e.sparkRules,s.cellDropdowns=e.cellDropdowns?new Map(e.cellDropdowns):null,s.cellTags=e.cellTags?new Map(e.cellTags):null,s.cellButtons=e.cellButtons?new Map(e.cellButtons):null,s.cellStates=e.cellStates?e.cellStates.slice():null,s.autoMerges=e.autoMerges?e.autoMerges.map(h=>({...h})):null,s.background=e.background,s.outlineColumn=e.outlineColumn?{...e.outlineColumn}:null,s.frozenTrailingRows=e.frozenTrailingRows,s.frozenTrailingCols=e.frozenTrailingCols,s.hideZeros=e.hideZeros,s.hideHeadings=e.hideHeadings,s.isChartSheet=e.isChartSheet,s.hideOutline=e.hideOutline,s.gridColorId=e.gridColorId,s.areaOffset=e.areaOffset,s.selectionPolicy=e.selectionPolicy,s.selectionUnit=e.selectionUnit,s.gridlineAxes=e.gridlineAxes,s.gridColor=e.gridColor,s.tabStyles=e.tabStyles;const a=A;if(s.cf=a(e.cf),s.validations=a(e.validations),n.size){for(const h of s.cf??[])h.rules=h.rules.map(u=>re(u,l));for(const h of s.validations??[])h.formula1&&(h.formula1=l(h.formula1)),h.formula2&&(h.formula2=l(h.formula2))}s.comments=a(e.comments),s.threads=a(e.threads),s.hyperlinks=e.hyperlinks?e.hyperlinks.map(h=>({...a({...h,_ranges:void 0})})):e.hyperlinks,s.autoFilter=a(e.autoFilter),s.filteredRows=e.filteredRows?new Set(e.filteredRows):e.filteredRows,s.pageSetup=a(e.pageSetup),s.tabColor=e.tabColor,s.protection=a(e.protection),s.rtl=e.rtl,s.zoom=e.zoom,s.valueMeta=e.valueMeta?new Map(e.valueMeta):null,s.colsChanged=!0,s.viewChanged=!0,this.sheets.splice(t+1,0,s);for(const h of n.values())this.engine.tables.set(h.name.toUpperCase(),h);return this.activeSheet=t+1,this._reindexNames(h=>h>t?h+1:h),this._copyScopedNames(t,e,s,l),this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),s}sheetNameProblem(t,e){const i=e.trim().slice(0,31);return!i||/[\\/?*[\]:]/.test(i)||/^'|'$/.test(i)?"rules":i.toLowerCase()==="history"?"reserved":this.sheets.some((o,r)=>r!==t&&o.name.toLowerCase()===i.toLowerCase())?"taken":null}renameSheet(t,e){const i=e.trim().slice(0,31);if(this.sheetNameProblem(t,e)!==null)return!1;const o=this.sheets[t].name;this.sheets[t].name=i,this.engine?.sheetsChanged(),this._renameInFormulas(o,i);for(const r of be)r(this,o,i);return this._emit("sheets"),!0}_shrink3D(t){const e=this.sheets[t].name.toLowerCase(),i=l=>this.sheets.findIndex(c=>c.name.toLowerCase()===l.toLowerCase()),o=l=>l[0]==="'"?l.slice(1,-1).replace(/''/g,"'"):l,r=/((?:'(?:[^']|'')+'|[A-Za-z_\u00C0-\uFFFF][\w.\u00C0-\uFFFF]*)):((?:'(?:[^']|'')+'|[A-Za-z_\u00C0-\uFFFF][\w.\u00C0-\uFFFF]*))!/g,s=l=>l.replace(r,(c,a,h,u)=>{if(l[u-1]==="]")return c;const p=o(a),f=o(h);if(p.toLowerCase()!==e&&f.toLowerCase()!==e)return c;let d=i(p),g=i(f);if(d<0||g<0||(d>g&&([d,g]=[g,d]),d===t&&d++,g===t&&g--,d>g))return c;const y=w=>Q(this.sheets[w].name);return d===g?`${y(d)}!`:`${y(d)}:${y(g)}!`}),n=l=>l.includes(":")&&l.includes("!")?l.split(/("(?:[^"]|"")*")/).map((c,a)=>a%2?c:s(c)).join(""):l;for(const l of this.sheets){const c=new Map;l.formulas.forEachCell((a,h,u)=>{let p=c.get(u);if(p===void 0){const f=u.f??u.sf,d=typeof f=="string"?n(f):f;p=d===f?null:u.f!==void 0?{...u,f:d,tpl:void 0}:{...u,sf:d,tpl:void 0},c.set(u,p)}p!==null&&l.setFormula(a,h,p)})}for(const l of this.engine?.names.values()??[])typeof l.text=="string"&&(l.text=n(l.text));this.engine?.templates.clear()}_refErrorsFor(t){const e=ee(this.sheets[t].name),i=s=>s.split(/("(?:[^"]|"")*")/).map((n,l)=>l%2?n:n.replace(e,"#REF!")).join(""),o=s=>typeof s=="string"&&s!==""?i(s):s,r=this.sheets[t];for(const s of this.sheets){if(s===r)continue;s.cf?.length>0&&(s.cf=s.cf.map(l=>({...l,rules:l.rules.map(c=>re(c,o))})),s.cfChanged=!0,s.cfEval?.invalidate()),s.validations?.length>0&&(s.validations=s.validations.map(l=>({...l,formula1:o(l.formula1),formula2:o(l.formula2)})),s.validationsChanged=!0);const n=new Map;s.formulas.forEachCell((l,c,a)=>{let h=n.get(a);if(h===void 0){const u=a.f??a.sf,p=typeof u=="string"?i(u):u;h=p===u?null:a.f!==void 0?{...a,f:p,tpl:void 0}:{...a,sf:p,tpl:void 0},n.set(a,h)}h!==null&&(s.setFormula(l,c,h),this.formulasEdited=!0)})}for(const s of this.engine?.names.values()??[])typeof s.text=="string"&&(s.text=i(s.text));this.engine?.templates.clear()}_renameInFormulas(t,e){const i=ee(t);let o=!1;for(const s of this.sheets){const n=new Map;s.formulas.forEachCell((l,c,a)=>{let h=n.get(a);if(h===void 0){const u=a.f??a.sf;if(u===void 0||!i.test(u))i.lastIndex=0,h=null;else{i.lastIndex=0;const p=V(u,t,e);h=a.f!==void 0?{...a,f:p,tpl:void 0}:{...a,sf:p,tpl:void 0}}n.set(a,h)}h!==null&&(s.setFormula(l,c,h),o=!0)})}let r=!1;for(const s of this.engine?.names.values()??[]){if(typeof s.text!="string")continue;const n=V(s.text,t,e);n!==s.text&&(s.text=n,r=!0)}r&&(this.namesChanged=!0,this.engine.nameTemplates.clear()),(o||r)&&(o&&(this.formulasEdited=!0),this.engine?.templates.clear(),this.engine?.rebuild())}editText(t,e,i){const o=t.kind(e,i);if(this.engine?.dataTables.length){const n=this.engine.dataTableAt(t,e,i);if(n){const{info:l}=n,c=l.dt2D==="1",a=l.dtr==="1";return`{=TABLE(${c||a?l.r1:""},${c?l.r2:a?"":l.r1})}`}}if(o&pe&&this.engine){const n=this.engine.spillMaster(t,e,i);if(n)return this.editText(t,n.row,n.col)}if(o&F){const n=t.formula(e,i),l=n&&!n.typed&&n.t!=="array"&&n.tpl?.rangeResult?"=@":"=";if(n&&n.f!==void 0){const c=l+le(n.f);return n.t==="array"&&!n.cm?`{${c}}`:c}if(n&&n.sf!==void 0){const c=Math.floor(n.base/R),a=n.base-c*R;return l+le(we(n.sf,e-c,i-a))}}const r=o&Y;if(r===I)return"";const s=t.value(e,i);if(r===U&&t.valueMeta!==null&&!(o&F)){const n=this.richImages?.get(t.valueMeta.get(e*R+i));if(n!==void 0)return n.alt??"";const l=this.richValues?.indexOfVm(t.valueMeta.get(e*R+i))??-1,c=l>=0?this.richValues.view(l):null;if(c!==null)return c.text}return r===T?this.styles.get(t.style(e,i)).quotePrefix?`'${this.strings.get(s)}`:this.strings.get(s):r===D?s?"TRUE":"FALSE":r===U?me[s]??"#N/A":String(s)}transact(t,e,i=null){if(this.guard&&!this.guard(t))return;const o=this.selectedSheets;!i&&o?.size>1&&Ie.has(t)&&(i=this.sheets.filter(s=>o.has(s)&&(!s.protection||s===this.sheet)));const r=i?this._runGroup(t,e,i):this._runOn(this.sheet,t,e);r!==null&&this._pushUndo(r)}transactOn(t,e,i){const o=this._runOn(t,e,i);o!==null&&this._pushUndo(o)}_runOn(t,e,i){const o=new $,r={sheet:t,log:o,saveCell:(f,d)=>o.push(t,f,d)},{maxRow:s,maxCol:n}=t,l=this.recorder?.length,c=this.formulasEdited;let a;try{a=i(r)??null}catch(f){throw f instanceof L&&(ae(t,o),t.maxRow=s,t.maxCol=n,this.formulasEdited=c,l!==void 0&&(this.recorder.length=l),this.engine?.cellsChanged(t,o.rows,o.cols,o.count)),f}e!=="entry"&&this.engine?.presentationChanged(),t.changes!==null&&o.count>0&&oe(this,t,o),o.vms!==null&&ze(t,o);const h=o.count>0&&this.engine?.tables.size>0?fe(this,r,o):null,u=(f,d)=>g=>u(f(g),d(g)),p=a&&h?u(a,h):a??h;return o.count===0&&p===null?null:(t.revision++,this.engine?.cellsChanged(t,o.rows,o.cols,o.count),{sheetIndex:t===this.sheet?this.activeSheet:this.sheets.indexOf(t),sheet:t,log:o,label:e,extra:p})}_runGroup(t,e,i){const o=[],r=this.activeSheet,s=this.recorder?.length,n=this.formulasEdited,l=[];try{for(const c of i){const{maxRow:a,maxCol:h}=c,u=this._runOn(c,t,e);u!==null&&(o.push(u),l.push([c,a,h]))}}catch(c){if(c instanceof L){this.rollbackSlices(o);for(const[a,h,u]of l)a.maxRow=h,a.maxCol=u;this.activeSheet=r,this.formulasEdited=n,s!==void 0&&(this.recorder.length=s)}throw c}return o.length===0?null:{sheetIndex:this.activeSheet,sheet:this.sheet,log:new $,label:t,extra:H(this,o)}}runSlice(t,e,i){const o=this._runOn(t,e,i);return o!==null&&this._emit("cells"),o}pushFolded(t,e,i){t.length!==0&&this._pushUndo({sheetIndex:this.sheets.indexOf(i),sheet:i,log:new $,label:e,extra:H(this,t)})}rollbackSlices(t){for(let e=t.length-1;e>=0;e--)this._restore(t[e]);this._emit("cells")}_pushUndo(t){this.allowUndo===!1?this.undoStack.length=0:(this.undoStack.push(t),this.undoStack.length>(this.historyLimit??Ee)&&this.undoStack.shift()),this.redoStack.length=0,this._emit("cells")}_restore(t){const e=t.sheet??this.sheets[t.sheetIndex],{log:i}=t,o=new $;if(ae(e,i,o),i.vms!==null){e.valueMeta=new Map(e.valueMeta??[]);for(const[n,l]of i.vms)e.valueMeta.set(i.rows[n]*R+i.cols[n],l)}let r=null;t.extra&&(r=t.extra(e)),this.engine?.presentationChanged(),e.changes!==null&&i.count>0&&oe(this,e,o),e.revision++,this.engine?.cellsChanged(e,i.rows,i.cols,i.count);const s=this.sheets.indexOf(e);return s>=0&&(this.activeSheet=s),{sheetIndex:s>=0?s:t.sheetIndex,sheet:e,log:o,label:t.label,extra:r}}undo(){const t=this.undoStack.pop();return t?(this.redoStack.push(this._restore(t)),this._emit("cells"),!0):!1}redo(){const t=this.redoStack.pop();return t?(this.undoStack.push(this._restore(t)),this._emit("cells"),!0):!1}setInput(t,e,i,o,{overLimitAsText:r=!1,typedQuote:s=!0}={}){const{sheet:n}=t,l=n.style(e,i),c=o!==""&&this.styles.get(l).numFmt==="@";let a=c?{kind:T,text:o[0]==="'"?o.slice(1):o}:ie(o,void 0,this.dateOffset);if(a.kind===F){const u=Fe(a.formula);if(u){if(!r)throw new L(u);a={kind:T,text:o}}}if(this.recorder){const u=a.kind===T&&o.startsWith("=")&&!c?`'${o}`:o;this.recorder.push(`sheet.setValue(${JSON.stringify(ge(e,i))}, ${JSON.stringify(u)});`)}t.saveCell(e,i),n.setFormula(e,i,null);const h=s&&o[0]==="'"&&o.length>1;switch((h||this.styles.get(l).quotePrefix)&&n.setStyle(e,i,this.styles.derive(l,{quotePrefix:h})),a.kind){case I:n.setCell(e,i,I,0);break;case P:n.setCell(e,i,P,a.value),a.format&&this.styles.get(l).numFmt==="General"&&n.setStyle(e,i,this.styles.derive(n.style(e,i),{numFmt:a.format}));break;case D:n.setCell(e,i,D,a.value);break;case U:n.setCell(e,i,U,a.value);break;case F:n.setCell(e,i,F|I,0),n.setFormula(e,i,{f:Ae(this._expandTableRefs(ue(a.formula,this.engine?.tables),n,e,i),this.engine?.names??null),typed:this.dynamicArrays!==!1}),this.formulasEdited=!0;break;default:n.setCell(e,i,T,this.strings.add(ne(a.text)))}}setRichInput(t,e,i,o,r){const{sheet:s}=t;t.saveCell(e,i),s.setFormula(e,i,null);const n=ne(o);s.setCell(e,i,T,this.strings.addRich(n,n===o?r:r?.filter(l=>l.at<n.length)))}_expandTableRefs(t,e,i,o){const r=this.engine;return!r||r.tables.size===0?t:Me(t,()=>{for(const s of r.tables.values())if(s.sheet===e&&i>=s.r0&&i<=s.r1&&o>=s.c0&&o<=s.c1)return s;return null})}clearRange(t,e="contents",{visibleOnly:i=!1}={}){this.sheet.dataRanges?.cleared(t)||this.transact("clear",o=>{const{sheet:r}=o,s=[];if(e!=="contents")for(const{r0:l,c0:c,r1:a,c1:h}of t){const u=l===0&&a===X-1,p=c===0&&h===R-1,f=(d,g,y,w)=>{for(const[C,x]of[...g])C<y||C>w||(s.push([d,C,x]),g.delete(C))};u&&r.colStyles!==null&&f("col",r.colStyles,c,h),p&&r.rowStyles!==null&&f("row",r.rowStyles,l,a)}const n=i&&r.filteredRows?.size>0?r.filteredRows:null;for(const{r0:l,c0:c,r1:a,c1:h}of t){const u=Math.min(h,r.maxCol),p=Math.min(a,r.maxRow);for(let f=c;f<=u;f++)if(r.columns[f]!==void 0)for(let d=l;d<=p;d++){if(r._chunk(d,f)===void 0){d|=1023;continue}if(n!==null&&n.has(d))continue;const y=r.kind(d,f)!==0,w=r.cellStyle(d,f)!==0;if(e==="formats"){if(!w)continue;o.saveCell(d,f),r.setStyle(d,f,0);continue}!y&&!(e==="all"&&w)||(o.saveCell(d,f),r.setCell(d,f,I,0),r.setFormula(d,f,null),e==="all"&&r.setStyle(d,f,0))}}return s.length>0?j([],s):void 0})}applyStyle(t,e,{measureRow:i,numberFit:o}={}){const r=JSON.stringify(e);if(this.recorder)for(const s of t)this.recorder.push(`sheet.setFormat(${JSON.stringify(Se(s))}, ${r});`);this.transact("format",s=>{const{sheet:n}=s;this.strings.rich!==null&&Re(this,s,t,e);const l=[],c=new Set,a=[],h=[],u=(g,y,w)=>{const C=g*2048+y;c.has(C)||(c.add(C),l.push(g,y,w.styles===null?null:w.styles.slice()))},p=(g,y,w)=>{w===0&&(n.rowStyles?.has(g)||n.colStyles?.has(y))&&(w=this.styles.explicitDefault()),n.setStyle(g,y,w)};for(const{r0:g,c0:y,r1:w,c1:C}of t){const x=g===0&&w===X-1,v=y===0&&C===R-1,k=x||v,b=k?Math.min(w,n.maxRow):w,he=k?Math.min(C,n.maxCol):C;for(let S=y;S<=he&&g<=b;S++){const _=n.columns[S];if(!(k&&!_))for(let M=g>>>z;M<=b>>>z;M++){const G=M<<z,K=Math.max(g,G),ce=Math.min(b,G+W),N=k?_[M]:n._ensure(K,S);if(!(k&&!N?.styles)){u(S,M,N);for(let E=K;E<=ce;E++)(!k||N.styles[E&W])&&p(E,S,this.styles.derive(n.style(E,S),e,r))}}}const O=S=>this.styles.derive(S,e,r),q=(S,_,M)=>{u(_,S>>>z,n._ensure(S,_)),n.setStyle(S,_,M||this.styles.explicitDefault())};if(v&&x){ve(n,O,a);for(const[S,_]of n.rowStyles??[])a.push(["row",S,_]),n.rowStyles.set(S,O(_))}else if(x)for(let S=y;S<=C;S++)se(n,"col",S,O,a,q);else if(v)for(let S=g;S<=w;S++)se(n,"row",S,O,a,q)}const f=(g,y,w)=>{const C=n[g];w!==C.sizeOf(y)&&(h.push([g,y,C.isCustom(y)?C.sizeOf(y):null,C.isAuto(y)]),C.setSize(y,w,!0),g==="cols"&&(n.colsChanged=!0))},d=e.fontSize!==void 0||e.wrap!==void 0||e.rotation!==void 0||["justify","distributed"].includes(e.hAlign)||["justify","distributed"].includes(e.vAlign);for(const{r0:g,r1:y,c0:w,c1:C}of t){const x=Math.min(y,n.maxRow);if(d&&x-g<=2e3)for(let v=g;v<=x;v++)f("rows",v,ke(n,this,v,i));if(o)for(const v of o.cols){if(v<w||v>C||!n.columns[v]||n.cols.isCustom(v)&&!n.cols.isAuto(v))continue;let k=n.cols.sizeOf(v);for(const b of o.rows)b>=g&&b<=x&&(n.kind(b,v)&Y)===P&&(k=Math.max(k,o.measure(n,b,v)));f("cols",v,k)}}return j(l,a,h)})}}function ae(m,t,e){for(let i=t.count-1;i>=0;i--){const o=t.rows[i],r=t.cols[i];e?.push(m,o,r),m.setCell(o,r,t.kinds[i],t.values[i]),m.setStyle(o,r,t.styles[i]),m.setFormula(o,r,t.kinds[i]&F?t.formulas.get(i):null)}}function H(m,t){const e=()=>{const i=[];for(let o=t.length-1;o>=0;o--)i.push(m._restore(t[o]));return H(m,i)};return e.parts=t,e}function ze(m,t){let e=null;for(const i of t.vms.keys()){const o=t.rows[i],r=t.cols[i];(m.kind(o,r)&~(J|Z))===t.kinds[i]&&m.value(o,r)===t.values[i]||(e??=new Map(m.valueMeta),e.delete(o*R+r))}e!==null&&(m.valueMeta=e.size>0?e:null)}function Ue(m,t,e,i){if(!t.size||typeof m!="string")return m;let o;try{o=Te(m)}catch(n){if(n instanceof L)return m;throw n}let r="",s=0;for(let n=0;n<o.length;n++){const l=o[n],c=l.t==="name"?m.slice(l.s,l.e):l.t==="table"?l.v.name:null;if(!c)continue;const a=t.get(c.toUpperCase());if(!a)continue;let h=n-1;for(;o[h]?.t==="ws";)h--;const u=o[h];if(u?.t==="sheet"){const{book:p,sheet:f,sheet2:d}=u.v;if(p!==null||d!==null)continue;if(f.toUpperCase()===e.toUpperCase())r+=m.slice(s,u.s)+Q(i)+"!",s=u.e;else if(f.toUpperCase()!==i.toUpperCase())continue}r+=m.slice(s,l.s)+a.name,s=l.s+c.length}return s?r+m.slice(s):m}function A(m){if(m===null||typeof m!="object")return m;if(Array.isArray(m))return m.map(A);if(m instanceof Map)return new Map([...m].map(([e,i])=>[e,A(i)]));if(m instanceof Set)return new Set([...m].map(A));if(ArrayBuffer.isView(m))return m.slice();const t={};for(const[e,i]of Object.entries(m))!e.startsWith("_")&&typeof i!="function"&&(t[e]=A(i));return t}function j(m,t,e=[]){return i=>{const o=[];for(let n=0;n<m.length;n+=3){const l=m[n],c=m[n+1],a=i.columns[l]?.[c];a!==void 0&&(o.push(l,c,a.styles),a.styles=m[n+2])}const r=[];for(let n=t.length-1;n>=0;n--){const[l,c,a]=t[n];if(l==="columns"){r.push([l,c,i.colStyles]),i.colStyles=a,i.colsChanged=!0;continue}l==="col"&&(i.colsChanged=!0);const h=l==="col"?"colStyles":"rowStyles",u=i[h]??=new Map;r.push([l,c,u.get(c)]),a===void 0?u.delete(c):u.set(c,a)}const s=[];for(let n=e.length-1;n>=0;n--){const[l,c,a,h]=e[n],u=i[l];s.push([l,c,u.isCustom(c)?u.sizeOf(c):null,u.isAuto(c)]),u.setSize(c,a,h),l==="cols"&&(i.colsChanged=!0)}return j(o,r,s)}}export{$ as CellLog,Ie as GROUP_LABELS,Qe as Workbook,H as foldEntries,ie as parseInput,j as swapStyles};
@@ -1 +1 @@
1
- import"./query-function.js";import{Sheet as d}from"../core/sheet.js";import{DataManager as u}from"./data.js";import{TableView as o}from"./view.js";import{TableSheet as l}from"./table-sheet.js";import{createPlanTable as m,GanttSheet as c}from"./gantt.js";import{ReportTemplate as f}from"./report.js";import{TableBinding as g}from"./bind.js";import{CellPathBinding as p,RowsBinding as S}from"./path-binding.js";import{attachDataEntry as b}from"./report-entry.js";import{buildDataSheetPackage as _,dataSheetsFromJSON as w,dataSheetsToJSON as v,readDataSheetPackage as T}from"./persist.js";class E{constructor(e){this.book=e,this.manager=new u(e),e.dataSheets=this,this.sheets=[],this.bindings=[],this.reports=[],this.loaded=!1,this.onSheetAdded=null,this.savedSheets=null,this.loadNotes=[],this._hookInput(e)}_hookInput(e){if(e.setInputRouted)return;e.setInputRouted=!0;const t=e.setInput;e.setInput=function(i,r,n,h){const{sheet:a}=i;if(!(a.routeInput!==void 0&&a.routeInput(i,r,n,h)))return t.call(this,i,r,n,h)}}_uniqueName(e){const t=i=>this.book.sheets.some(r=>r.name.toLowerCase()===i.toLowerCase());let s=e;for(let i=2;t(s);i++)s=`${e}${i}`;return s}_insert(e,t=!0,s=null){const{book:i}=this;i.sheets.push(e),t&&(i.activeSheet=i.sheets.length-1),i.structureEdited=!0,i.engine?.sheetsChanged(),s?.(),i._emit("sheets")}_registerSheet(e){this.sheets.push(e),this.onSheetAdded?.(e)}_registerBinding(e){this.bindings.push(e),this.onSheetAdded?.(e.sheet)}isDataSheet(e){return e.isVirtual===!0}addTableFromSheetTable(e,t=null){const s=e,i=this.manager.addTable(t??`${s.name} Data`);return i.loadSheet(this.book,s.sheet,{r0:s.r0,c0:s.c0,r1:s.r1-s.totalsRows,c1:s.c1}),i}addTable(e,t){return this.manager.addTable(e,t)}addTableSheet(e,t,s={},i={}){const r=this.manager.table(t),n=s instanceof o?s:new o(r,s),h=new l(this.book,this._uniqueName(e),n,i);return this._insert(h,i.activate!==!1,()=>this._registerSheet(h)),h}addGanttSheet(e,t=null,s={}){const i=Array.isArray(t)?t:[],r=t&&!Array.isArray(t)?this.manager.table(t):m(this.manager,this._freeTable(`${e} Tasks`),i),n=new c(this.book,this._uniqueName(e),r,s);return this._insert(n,s.activate!==!1,()=>this._registerSheet(n)),n}_freeTable(e){let t=e;for(let s=2;this.manager.tables.has(t);s++)t=`${e} ${s}`;return t}addReportSheet(e,t={}){const s=new d(this._uniqueName(e));let i=null;return this._insert(s,t.activate!==!1,()=>{i=new f(this.manager,s,t),this.reports.push(i),this.onSheetAdded?.(s)}),i}bindPaths(e,t=null,s={}){const i=new p(this.book,e,t,s);return this._registerBinding(i),i}bindRows(e,t,s,i={}){const r=new S(this.book,e,t,s,i);return this._registerBinding(r),r}dataEntry(e){if(!e.output)throw new Error("Generate the report first.");return b(this.book,e,e.output)}toJSON(){return v(this)}fromJSON(e){return w(e,this),this}bindTable(e,t,s,i={}){const r=new g(this.book,e,t,s,i);return this._registerBinding(r),r}removeBinding(e){e.unbind(),this.bindings=this.bindings.filter(t=>t!==e)}_pruneDeleted(){const e=new Set(this.book.sheets);this.sheets=this.sheets.filter(t=>e.has(t)),this.bindings=this.bindings.filter(t=>e.has(t.sheet)),this.reports=this.reports.filter(t=>e.has(t.sheet))}prepareSave(){this._pruneDeleted();for(const e of this.sheets)e.prepareSave();this.savedSheets=this.sheets.slice()}async savePackage(){for(const t of this.sheets)t.savePlanned?.();const e=await _(this);return e.parts.length===0&&!this.loaded?null:e}finishSave(){for(const e of this.savedSheets??[])e.finishSave();this.savedSheets=null}async load(e){return T(e,this)}}export{E as DataSheets};
1
+ import"./query-function.js";import{Sheet as u}from"../core/sheet.js";import{DataManager as l}from"./data.js";import{TableView as o}from"./view.js";import{TableSheet as m}from"./table-sheet.js";import{createPlanTable as c,GanttSheet as f}from"./gantt.js";import{ReportTemplate as g}from"./report.js";import{TableBinding as p}from"./bind.js";import{CellPathBinding as S,RowsBinding as b}from"./path-binding.js";import{attachDataEntry as _}from"./report-entry.js";import{buildDataSheetPackage as w,dataSheetsFromJSON as v,dataSheetsToJSON as T,readDataSheetPackage as k}from"./persist.js";class J{constructor(e){this.book=e,this.manager=new l(e),e.dataSheets=this,this.sheets=[],this.bindings=[],this.reports=[],this.loaded=!1,this.onSheetAdded=null,this.savedSheets=null,this.loadNotes=[],this._hookInput(e)}_hookInput(e){if(e.setInputRouted)return;e.setInputRouted=!0;const t=e.setInput;e.setInput=function(i,r,n,h,d){const{sheet:a}=i;if(!(a.routeInput!==void 0&&a.routeInput(i,r,n,h)))return t.call(this,i,r,n,h,d)}}_uniqueName(e){const t=i=>this.book.sheets.some(r=>r.name.toLowerCase()===i.toLowerCase());let s=e;for(let i=2;t(s);i++)s=`${e}${i}`;return s}_insert(e,t=!0,s=null){const{book:i}=this;i.sheets.push(e),t&&(i.activeSheet=i.sheets.length-1),i.structureEdited=!0,i.engine?.sheetsChanged(),s?.(),i._emit("sheets")}_registerSheet(e){this.sheets.push(e),this.onSheetAdded?.(e)}_registerBinding(e){this.bindings.push(e),this.onSheetAdded?.(e.sheet)}isDataSheet(e){return e.isVirtual===!0}addTableFromSheetTable(e,t=null){const s=e,i=this.manager.addTable(t??`${s.name} Data`);return i.loadSheet(this.book,s.sheet,{r0:s.r0,c0:s.c0,r1:s.r1-s.totalsRows,c1:s.c1}),i}addTable(e,t){return this.manager.addTable(e,t)}addTableSheet(e,t,s={},i={}){const r=this.manager.table(t),n=s instanceof o?s:new o(r,s),h=new m(this.book,this._uniqueName(e),n,i);return this._insert(h,i.activate!==!1,()=>this._registerSheet(h)),h}addGanttSheet(e,t=null,s={}){const i=Array.isArray(t)?t:[],r=t&&!Array.isArray(t)?this.manager.table(t):c(this.manager,this._freeTable(`${e} Tasks`),i),n=new f(this.book,this._uniqueName(e),r,s);return this._insert(n,s.activate!==!1,()=>this._registerSheet(n)),n}_freeTable(e){let t=e;for(let s=2;this.manager.tables.has(t);s++)t=`${e} ${s}`;return t}addReportSheet(e,t={}){const s=new u(this._uniqueName(e));let i=null;return this._insert(s,t.activate!==!1,()=>{i=new g(this.manager,s,t),this.reports.push(i),this.onSheetAdded?.(s)}),i}bindPaths(e,t=null,s={}){const i=new S(this.book,e,t,s);return this._registerBinding(i),i}bindRows(e,t,s,i={}){const r=new b(this.book,e,t,s,i);return this._registerBinding(r),r}dataEntry(e){if(!e.output)throw new Error("Generate the report first.");return _(this.book,e,e.output)}toJSON(){return T(this)}fromJSON(e){return v(e,this),this}bindTable(e,t,s,i={}){const r=new p(this.book,e,t,s,i);return this._registerBinding(r),r}removeBinding(e){e.unbind(),this.bindings=this.bindings.filter(t=>t!==e)}_pruneDeleted(){const e=new Set(this.book.sheets);this.sheets=this.sheets.filter(t=>e.has(t)),this.bindings=this.bindings.filter(t=>e.has(t.sheet)),this.reports=this.reports.filter(t=>e.has(t.sheet))}prepareSave(){this._pruneDeleted();for(const e of this.sheets)e.prepareSave();this.savedSheets=this.sheets.slice()}async savePackage(){for(const t of this.sheets)t.savePlanned?.();const e=await w(this);return e.parts.length===0&&!this.loaded?null:e}finishSave(){for(const e of this.savedSheets??[])e.finishSave();this.savedSheets=null}async load(e){return k(e,this)}}export{J as DataSheets};