@8sheets/data-grid 1.1.1 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/api/serialize.js +1 -1
- package/calc/engine.js +1 -1
- package/calc/functions/info.js +1 -1
- package/calcx/lang/convert.js +1 -1
- package/cells/book-css.js +7 -2
- package/cells/cf-engine.js +1 -1
- package/cells/find-engine.js +2 -2
- package/cells/find.js +1 -1
- package/cells/goto.js +1 -1
- package/cells/link-model.js +1 -0
- package/cells/selection-modes.js +1 -1
- package/celltypes/dropdowns.js +2 -2
- package/core/cond-format.js +1 -1
- package/core/culture.js +1 -1
- package/core/edit-ranges.js +1 -0
- package/core/host-rules.js +1 -0
- package/core/protection.js +1 -1
- package/core/sheet.js +1 -1
- package/core/structure.js +1 -1
- package/core/workbook.js +1 -1
- package/datasheets/manager.js +1 -1
- package/datasheets/persist.js +1 -1
- package/extras/getdata/persist.js +2 -2
- package/i18n/en/cells.js +1 -1
- package/i18n/en/format.js +1 -1
- package/i18n/en/misc.js +1 -1
- package/i18n/en/ribbon.js +1 -1
- package/i18n/pl/cells.js +1 -1
- package/i18n/pl/format.js +1 -1
- package/i18n/pl/misc.js +1 -1
- package/i18n/pl/ribbon.js +1 -1
- package/io/client.js +1 -1
- package/io/csv.js +7 -7
- package/io/encoding.js +1 -0
- package/io/foreign-sheets.js +2 -2
- package/io/plan.js +1 -1
- package/io/xlsx-tail.js +1 -1
- package/io/xlsx-write.js +2 -2
- package/package.json +1 -1
- package/pivot/engine.js +1 -1
- package/pivot/xml.js +2 -2
- package/print/note-pages.js +2 -0
- package/print/paginate.js +1 -1
- package/print/pdf-links.js +1 -0
- package/print/pdf.js +11 -11
- package/print/render-page.js +3 -3
- package/table-view/files.js +1 -1
- package/table-view/mount.js +1 -1
- package/table-view/version.js +1 -1
- package/ui/dialogs.js +3 -3
- package/ui/icons.js +1 -1
- package/ui/protection-ui.js +1 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
A data grid for the web in plain JavaScript modules with no runtime dependencies. Open a CSV or Excel file, or pass your records, and search, filter, sort, group, total, pivot and export them as CSV, Excel or PDF. Files are read in a Worker as a stream, the page keeps a bounded DOM, and a million records stay responsive. Server data plugs in through a query contract, so search, filters and totals cover the whole result.
|
|
4
4
|
|
|
5
|
-
This is version 1.1.
|
|
5
|
+
This is version 1.1.2. Components for [React](https://www.npmjs.com/package/@8sheets/data-grid-react), [Vue](https://www.npmjs.com/package/@8sheets/data-grid-vue) and [Angular](https://www.npmjs.com/package/@8sheets/data-grid-angular) build on it. For a full Excel-compatible workbook, see the Spreadsheet, [`@8sheets/core`](https://www.npmjs.com/package/@8sheets/core).
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
package/api/serialize.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BOOL as E,CHUNK_BITS as Y,CHUNK_MASK as Z,CHUNK_SIZE as F,ERR as M,ERRORS as I,FORMULA as b,KIND_MASK as J,NUM as T,SPILL as v,STR as R,Sheet as G}from"../core/sheet.js";import{MAX_COLS as L}from"../core/address.js";import{defaultStyle as U}from"../core/styles.js";import{Workbook as k}from"../core/workbook.js";import{Engine as ee}from"../calc/engine.js";const j="8sheets",B=3,ne=new Set(["uid","name","columns","maxRow","maxCol","rows","cols","formulas","spills","rowStyles","colStyles","merges","mergeIndex","frozenRows","frozenCols","showGridlines","zoom","sourceId","sourceIndex","revision","hidden","tabColor","rtl"]),te=new Set(["apiObjects","cfEval","structureOps","dataBindings","report","isVirtual","split","onRefresh","onRejected","recorder"]),K={cf:"cfChanged",comments:"commentsChanged",hyperlinks:"hyperlinksChanged",validations:"validationsChanged",pageSetup:"pageSetupChanged",protection:"protectionChanged",scenarios:"scenariosChanged",sparklines:"sparklinesChanged",threads:"threadsChanged",autoFilter:"filterChanged",cellTypes:"cellTypesChanged",cellTypeRules:"cellTypesChanged"},_=new Map;function Ne(e,n){_.set(e,n)}function se(e,n){return _.has(e)?_.get(e)(n):n}const re=new G(""),oe=e=>{if(e===null||typeof e!="object")return!0;const n=Object.getPrototypeOf(e);return n===Object.prototype||n===null};function m(e,n,t){if(e===null||typeof e=="number"||typeof e=="string"||typeof e=="boolean")return e;if(e===void 0)return;if(typeof e=="function"){n?.push(`${t}: a function was left out`);return}if(Array.isArray(e))return e.map((o,s)=>m(o,n,`${t}[${s}]`)??null);if(e instanceof Map)return{$map:[...e].map(([o,s],i)=>[m(o,n,t),m(s,n,`${t}.${i}`)??null])};if(e instanceof Set)return{$set:[...e].map(o=>m(o,n,t))};if(ArrayBuffer.isView(e))return{$typed:e.constructor.name,v:[...e]};if(e instanceof Date)return{$date:e.toISOString()};if(!oe(e)){if(typeof e.toJSON=="function")return m(e.toJSON(),n,t);n?.push(`${t}: a ${e.constructor?.name??"class"} instance was left out`);return}if("$map"in e||"$set"in e)throw new Error(`${t}: a key starting with $ can't be stored`);const r={};for(const o of Object.keys(e)){if(o[0]==="_")continue;const s=m(e[o],n,`${t}.${o}`);s!==void 0&&(r[o]=s)}return r}const ie={Uint8Array,Int8Array,Uint16Array,Int16Array,Uint32Array,Int32Array,Float32Array,Float64Array};function g(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(g);if(e.$map)return new Map(e.$map.map(([t,r])=>[g(t),g(r)]));if(e.$set)return new Set(e.$set.map(g));if(e.$typed)return ie[e.$typed].from(e.v);if(e.$date)return new Date(e.$date);const n={};for(const t of Object.keys(e))n[t]=g(e[t]);return n}function V(e){const n={size:e.defaultSize};if(e.sizes!==null){const t=[],{sizes:r}=e;for(let o=0;o<r.length;o++){if(!e.isCustom(o)||e.isHidden(o))continue;const s=r[o],i=e.isAuto(o);let f=o;for(;f+1<r.length&&r[f+1]===s&&e.isCustom(f+1)&&!e.isHidden(f+1)&&e.isAuto(f+1)===i;)f++;t.push(i?[o,f-o+1,s,1]:[o,f-o+1,s]),o=f}t.length&&(n.runs=t)}return e.hiddenSizes!==null&&e.hiddenSizes.size>0&&(n.hidden=[...e.hiddenSizes]),n}function P(e,n){if(n){n.size!==void 0&&n.size!==e.defaultSize&&e.setDefaultSize(n.size);for(const[t,r,o,s]of n.runs??[])for(let i=t;i<t+r;i++)e.setSize(i,o,s===1);for(const[t,r]of n.hidden??[])r>=0&&e.setSize(t,r),e.setHidden(t,!0)}}function le(e){const n=[];let t;for(const r of[...e.keys()].sort((o,s)=>o-s)){const o=e.get(r);t&&r===t[0]+t[1]&&o===t[2]?t[1]++:(t=[r,1,o],n.push(t))}return n}function fe(e){const n=new Map;for(const t of e){if(t.length===2){const[i,f]=t;n.set(i,f);continue}const[r,o,s]=t;if(t.length!==3||!Number.isInteger(r)||!Number.isInteger(o)||r<0||o<1||r+o>L)throw new RangeError("Column style run exceeds the sheet or has invalid bounds");for(let i=r;i<r+o;i++)n.set(i,s)}return n}const ce=16;function ue(e){const n={};for(const t of Object.keys(e))t!=="tpl"&&t[0]!=="_"&&(n[t]=e[t]);return n}function q(e,n,t){switch(n&J){case T:return t;case R:return e.strings.get(t);case E:return t!==0;case M:return{e:I[t]??"#N/A"};default:return null}}function ae(e,n,t,r,o){const s=[],i=[];let f=null,c=-2,d=-1,l=0,u=-1;const{formulas:y}=n,{rich:a}=e.strings,S=o.styles===!1,C=o.formulas===!1;for(let p=0;p<r.length;p++){const D=r[p];if(D===void 0)continue;const W=p*F,{kinds:X,values:x,styles:$}=D;for(let h=0;h<F;h++){const O=X[h],w=W+h;if($!==null&&!S&&$[h]!==0&&($[h]===l&&w===u+1?u=w:(l!==0&&i.push([d,u-d+1,l]),d=w,u=w,l=$[h])),O===0||O&v)continue;let z;if(O&b){const N=y.get(w*L+t),A=q(e,O,x[h]);N&&!C?(z={f:ue(N)},A!==null&&(z.v=A)):z=A}else(O&J)===R?(z=e.strings.get(x[h]),a!==null&&a.has(x[h])&&(z={s:z,rich:a.get(x[h])})):z=q(e,O,x[h]);const H=w-c-1;if(f===null||H>ce)f={r:w,v:[]},s.push(f);else for(let N=0;N<H;N++)f.v.push(null);f.v.push(z),c=w}}return l!==0&&i.push([d,u-d+1,l]),{blocks:s,styles:i}}function de(e,n,t,r){for(const{r:o,v:s}of r){let i=null,f=-1;for(let d=0;d<s.length;d++){const l=s[d];if(l===null)continue;const u=o+d,y=u>>>Y;y!==f&&(i=n._ensure(u,t),f=y);const a=u&Z;if(typeof l=="number")i.kinds[a]=T,i.values[a]=l;else if(typeof l=="string")i.kinds[a]=R,i.values[a]=e.strings.add(l);else if(typeof l=="boolean")i.kinds[a]=E,i.values[a]=l?1:0;else if(l.e!==void 0)i.kinds[a]=M,i.values[a]=Math.max(0,I.indexOf(l.e));else if(l.s!==void 0){const S=e.strings.add(l.s);i.kinds[a]=R,i.values[a]=S,e.strings.rich??=new Map,e.strings.rich.set(S,l.rich)}else if(l.f!==void 0){let S=b,C=0;const p=l.v;typeof p=="number"?(S|=T,C=p):typeof p=="string"?(S|=R,C=e.strings.add(p)):typeof p=="boolean"?(S|=E,C=p?1:0):p&&p.e!==void 0&&(S|=M,C=Math.max(0,I.indexOf(p.e))),i.kinds[a]=S,i.values[a]=C,n.setFormula(u,t,typeof l.f=="string"?{f:l.f,typed:!0}:l.f)}}const c=o+s.length-1;c>n.maxRow&&(n.maxRow=c)}t>n.maxCol&&(n.maxCol=t)}function me(e,n,t){for(const[r,o,s]of t)for(let i=r;i<r+o;i++)e.setStyle(i,n,s)}function Q(e,n){const t={};for(const r of Object.keys(e)){if(r[0]==="_")continue;const o=e[r];o!==n[r]&&!(typeof o=="object"&&o!==null&&JSON.stringify(o)===JSON.stringify(n[r]))&&(t[r]=o)}return t}function pe(e,n,t,r,o){const s={name:n.name};n.hidden&&(s.hidden=!0),n.hidden&&n.veryHidden&&(s.veryHidden=!0),n.tabColor&&(s.tabColor=n.tabColor),n.rtl&&(s.rtl=!0),n.zoom!==1&&(s.zoom=n.zoom),n.frozenRows&&(s.frozenRows=n.frozenRows),n.frozenCols&&(s.frozenCols=n.frozenCols),n.showGridlines===!1&&(s.showGridlines=!1),s.rows=V(n.rows),s.cols=V(n.cols),n.rowStyles?.size&&(s.rowStyles=[...n.rowStyles]),n.colStyles?.size&&(s.colStyles=le(n.colStyles)),n.merges.length&&(s.merges=n.merges.map(({r0:l,c0:u,r1:y,c1:a})=>[l,u,y,a]));const i=[],f=[];n.columns.forEach((l,u)=>{if(r.cells===!1)return;const{blocks:y,styles:a}=ae(e,n,u,l,r);y.length&&i.push({c:u,blocks:y}),a.length&&f.push({c:u,runs:a})}),i.length&&(s.cells=i),f.length&&(s.styles=f);const c={};for(const l of Object.keys(n)){if(ne.has(l)||te.has(l)||l[0]==="_"||l.endsWith("Changed"))continue;const u=n[l];if(u==null||u===re[l])continue;const y=m(u,o,`${n.name}.${l}`);y!==void 0&&(c[l]=y)}Object.keys(c).length&&(s.features=c);const d=t?.objectsOf?.(n);if(d?.length){const l=m(d.map(ye),o,`${n.name}.objects`);l.length&&(s.objects=l)}return s}function ye(e){const{bitmap:n,blob:t,canvas:r,modelEpoch:o,...s}=e;return t&&(s.imageType=t.type),s}function Re(e,n=null,t={}){const r=t.warnings??[],o=U(),s={format:j,version:1};s.activeSheet=e.activeSheet,e.fileName&&(s.fileName=e.fileName),e.themeInfo?s.theme=m(e.themeInfo,r,"theme"):e.theme&&(s.themeColors=e.theme);const i=e.styles.list;s.styles=i.length===1&&Object.keys(Q(i[0],o)).length===0?[]:i.map(c=>Q(c,o)),e.dxfs?.length&&(s.dxfs=m(e.dxfs,r,"dxfs")),e.persons?.length&&(s.persons=m(e.persons,r,"persons")),e.protection&&(s.protection=m(e.protection,r,"protection")),e.calcMode&&(s.calcMode=e.calcMode),e.getDataQueries&&(s.queries=m(e.getDataQueries,r,"queries")),e.customData&&(s.custom=m(e.customData,r,"custom"));const f=e.engine;if(f&&(f.manual&&(s.manualCalc=!0),f.names.size&&(s.names=[...f.names].map(([c,d])=>{const l=c.indexOf("!");return{name:d.name??(l>=0?c.slice(l+1):c),text:d.text,...l>=0?{sheet:Number(c.slice(0,l))}:{}}})),f.tables.size&&(s.tables=[...f.tables.values()].map(c=>{const{sheet:d,source:l,part:u,id:y,isNew:a,dirty:S,...C}=c;return{...m(C,r,`table ${c.name}`),sheet:e.sheets.indexOf(d)}}))),s.sheets=e.sheets.map(c=>pe(e,c,n,t,r)),s.sheets.some(c=>c.colStyles)&&(s.version=2),s.sheets.some(c=>c.features?.cellTypeRules)&&(s.version=3),n?.extrasToJSON){const c=n.extrasToJSON(r);c&&(s.extras=c)}return r.length&&(s.warnings=r),s}function he(e,n){n.hidden&&(e.hidden=!0),n.hidden&&n.veryHidden&&(e.veryHidden=!0),n.tabColor&&(e.tabColor=n.tabColor,e.tabColorChanged=!0),n.rtl&&(e.rtl=!0),n.zoom&&(e.zoom=n.zoom),e.frozenRows=n.frozenRows??0,e.frozenCols=n.frozenCols??0,n.showGridlines===!1&&(e.showGridlines=!1),P(e.rows,n.rows),P(e.cols,n.cols),(n.cols?.runs||n.cols?.hidden)&&(e.colsChanged=!0),n.rowStyles&&(e.rowStyles=new Map(n.rowStyles)),n.colStyles&&(e.colStyles=fe(n.colStyles)),n.merges&&(e.merges=n.merges.map(([t,r,o,s])=>({r0:t,c0:r,r1:o,c1:s}))),e.viewChanged=!0;for(const[t,r]of Object.entries(n.features??{})){const o=g(r);e[t]=se(t,o),K[t]&&(e[K[t]]=!0)}}function ge(e,n){const t=U();n.styles?.length&&e.styles.load(n.styles.map(r=>({...t,...r}))),n.dxfs&&(e.dxfs=g(n.dxfs),e.sourceDxfs=0),n.persons&&(e.persons=g(n.persons),e.personsChanged=!0),n.protection&&(e.protection=g(n.protection),e.protectionChanged=!0),n.calcMode&&(e.calcMode=n.calcMode,e.calcModeChanged=!0),n.queries&&(e.getDataQueries=g(n.queries)),n.custom&&(e.customData=g(n.custom)),n.fileName&&(e.fileName=n.fileName),n.themeColors&&(e.theme=n.themeColors)}function Se(e,n,t={}){const{engine:r}=e;e.formulasEdited=!0,e.activeSheet=Math.min(n.activeSheet??0,e.sheets.length-1),r.sheetsChanged(),n.manualCalc&&(r.manual=!0),r.setNames((n.names??[]).map(o=>({name:o.name,text:o.text,localSheetId:o.sheet}))),n.names?.length&&(e.namesChanged=!0),r.setTables((n.tables??[]).map(o=>{const{sheet:s,...i}=o;return{...g(i),sheet:e.sheets[s],isNew:!0,dirty:!0}})),r.buildGraph({fullCalc:t.recalculate===!0}),e.dirty=!1}function $e(e,n={}){if(e?.format!==j)throw new Error(`This isn't ${j} JSON`);if(e.version>B)throw new Error(`This JSON has version ${e.version}; this code reads up to ${B}`);const t=new k;return t.engine=new ee(t),ge(t,n.styles===!1?{...e,styles:[]}:e),t.sheets=e.sheets.map(r=>new G(r.name)),e.sheets.forEach((r,o)=>{const s=t.sheets[o];he(s,r);for(const i of r.cells??[])de(t,s,i.c,i.blocks);if(n.styles!==!1)for(const i of r.styles??[])me(s,i.c,i.runs);if(r.styles?.length)for(const i of r.styles)i.c>s.maxCol&&(s.maxCol=i.c)}),Se(t,e,n),t}export{j as FORMAT_NAME,B as FORMAT_VERSION,ge as applyBookMeta,he as applySheetMeta,$e as bookFromJSON,Re as bookToJSON,g as decodeData,m as encodeData,Se as finishLoad,Ne as registerFeatureReviver,se as reviveSheetFeature};
|
|
1
|
+
import{BOOL as $,CHUNK_BITS as Y,CHUNK_MASK as Z,CHUNK_SIZE as F,ERR as T,ERRORS as M,FORMULA as J,KIND_MASK as b,NUM as I,SPILL as k,STR as x,Sheet as U}from"../core/sheet.js";import{MAX_COLS as v}from"../core/address.js";import{defaultStyle as G}from"../core/styles.js";import{Workbook as ee}from"../core/workbook.js";import{Engine as te}from"../calc/engine.js";const j="8sheets",L=4,ne=new Set(["uid","name","columns","maxRow","maxCol","rows","cols","formulas","spills","rowStyles","colStyles","merges","mergeIndex","frozenRows","frozenCols","showGridlines","zoom","sourceId","sourceIndex","revision","hidden","tabColor","rtl"]),se=new Set(["apiObjects","cfEval","structureOps","dataBindings","report","isVirtual","split","onRefresh","onRejected","recorder","hostRules"]),B={cf:"cfChanged",comments:"commentsChanged",hyperlinks:"hyperlinksChanged",validations:"validationsChanged",pageSetup:"pageSetupChanged",protection:"protectionChanged",protectedRanges:"protectedRangesChanged",scenarios:"scenariosChanged",sparklines:"sparklinesChanged",threads:"threadsChanged",autoFilter:"filterChanged",cellTypes:"cellTypesChanged",cellTypeRules:"cellTypesChanged"},_=new Map;function Ee(e,t){_.set(e,t)}function re(e,t){return _.has(e)?_.get(e)(t):t}const ie=new U(""),oe=e=>{if(e===null||typeof e!="object")return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null};function m(e,t,n){if(e===null||typeof e=="number"||typeof e=="string"||typeof e=="boolean")return e;if(e===void 0)return;if(typeof e=="function"){t?.push(`${n}: a function was left out`);return}if(Array.isArray(e))return e.map((i,s)=>m(i,t,`${n}[${s}]`)??null);if(e instanceof Map)return{$map:[...e].map(([i,s],o)=>[m(i,t,n),m(s,t,`${n}.${o}`)??null])};if(e instanceof Set)return{$set:[...e].map(i=>m(i,t,n))};if(ArrayBuffer.isView(e))return{$typed:e.constructor.name,v:[...e]};if(e instanceof Date)return{$date:e.toISOString()};if(!oe(e)){if(typeof e.toJSON=="function")return m(e.toJSON(),t,n);t?.push(`${n}: a ${e.constructor?.name??"class"} instance was left out`);return}if("$map"in e||"$set"in e)throw new Error(`${n}: a key starting with $ can't be stored`);const r={};for(const i of Object.keys(e)){if(i[0]==="_")continue;const s=m(e[i],t,`${n}.${i}`);s!==void 0&&(r[i]=s)}return r}const le={Uint8Array,Int8Array,Uint16Array,Int16Array,Uint32Array,Int32Array,Float32Array,Float64Array};function h(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(h);if(e.$map)return new Map(e.$map.map(([n,r])=>[h(n),h(r)]));if(e.$set)return new Set(e.$set.map(h));if(e.$typed)return le[e.$typed].from(e.v);if(e.$date)return new Date(e.$date);const t={};for(const n of Object.keys(e))t[n]=h(e[n]);return t}function V(e){const t={size:e.defaultSize};if(e.sizes!==null){const n=[],{sizes:r}=e;for(let i=0;i<r.length;i++){if(!e.isCustom(i)||e.isHidden(i))continue;const s=r[i],o=e.isAuto(i);let l=i;for(;l+1<r.length&&r[l+1]===s&&e.isCustom(l+1)&&!e.isHidden(l+1)&&e.isAuto(l+1)===o;)l++;n.push(o?[i,l-i+1,s,1]:[i,l-i+1,s]),i=l}n.length&&(t.runs=n)}return e.hiddenSizes!==null&&e.hiddenSizes.size>0&&(t.hidden=[...e.hiddenSizes]),t}function K(e,t){if(t){t.size!==void 0&&t.size!==e.defaultSize&&e.setDefaultSize(t.size);for(const[n,r,i,s]of t.runs??[])for(let o=n;o<n+r;o++)e.setSize(o,i,s===1);for(const[n,r]of t.hidden??[])r>=0&&e.setSize(n,r),e.setHidden(n,!0)}}function fe(e){const t=[];let n;for(const r of[...e.keys()].sort((i,s)=>i-s)){const i=e.get(r);n&&r===n[0]+n[1]&&i===n[2]?n[1]++:(n=[r,1,i],t.push(n))}return t}function ce(e){const t=new Map;for(const n of e){if(n.length===2){const[o,l]=n;t.set(o,l);continue}const[r,i,s]=n;if(n.length!==3||!Number.isInteger(r)||!Number.isInteger(i)||r<0||i<1||r+i>v)throw new RangeError("Column style run exceeds the sheet or has invalid bounds");for(let o=r;o<r+i;o++)t.set(o,s)}return t}const ue=16;function ae(e){const t={};for(const n of Object.keys(e))n!=="tpl"&&n[0]!=="_"&&(t[n]=e[n]);return t}function P(e,t,n){switch(t&b){case I:return n;case x:return e.strings.get(n);case $:return n!==0;case T:return{e:M[n]??"#N/A"};default:return null}}function de(e,t,n,r,i){const s=[],o=[];let l=null,f=-2,u=-1,c=0,d=-1;const{formulas:S}=t,{rich:a}=e.strings,g=i.styles===!1,C=i.formulas===!1;for(let p=0;p<r.length;p++){const D=r[p];if(D===void 0)continue;const W=p*F,{kinds:X,values:N,styles:E}=D;for(let y=0;y<F;y++){const z=X[y],w=W+y;if(E!==null&&!g&&E[y]!==0&&(E[y]===c&&w===d+1?d=w:(c!==0&&o.push([u,d-u+1,c]),u=w,d=w,c=E[y])),z===0||z&k)continue;let O;if(z&J){const R=S.get(w*v+n),A=P(e,z,N[y]);R&&!C?(O={f:ae(R)},A!==null&&(O.v=A)):O=A}else(z&b)===x?(O=e.strings.get(N[y]),a!==null&&a.has(N[y])&&(O={s:O,rich:a.get(N[y])})):O=P(e,z,N[y]);const H=w-f-1;if(l===null||H>ue)l={r:w,v:[]},s.push(l);else for(let R=0;R<H;R++)l.v.push(null);l.v.push(O),f=w}}return c!==0&&o.push([u,d-u+1,c]),{blocks:s,styles:o}}function me(e,t,n,r){for(const{r:i,v:s}of r){let o=null,l=-1;for(let u=0;u<s.length;u++){const c=s[u];if(c===null)continue;const d=i+u,S=d>>>Y;S!==l&&(o=t._ensure(d,n),l=S);const a=d&Z;if(typeof c=="number")o.kinds[a]=I,o.values[a]=c;else if(typeof c=="string")o.kinds[a]=x,o.values[a]=e.strings.add(c);else if(typeof c=="boolean")o.kinds[a]=$,o.values[a]=c?1:0;else if(c.e!==void 0)o.kinds[a]=T,o.values[a]=Math.max(0,M.indexOf(c.e));else if(c.s!==void 0){const g=e.strings.add(c.s);o.kinds[a]=x,o.values[a]=g,e.strings.rich??=new Map,e.strings.rich.set(g,c.rich)}else if(c.f!==void 0){let g=J,C=0;const p=c.v;typeof p=="number"?(g|=I,C=p):typeof p=="string"?(g|=x,C=e.strings.add(p)):typeof p=="boolean"?(g|=$,C=p?1:0):p&&p.e!==void 0&&(g|=T,C=Math.max(0,M.indexOf(p.e))),o.kinds[a]=g,o.values[a]=C,t.setFormula(d,n,typeof c.f=="string"?{f:c.f,typed:!0}:c.f)}}const f=i+s.length-1;f>t.maxRow&&(t.maxRow=f)}n>t.maxCol&&(t.maxCol=n)}function pe(e,t,n){for(const[r,i,s]of n)for(let o=r;o<r+i;o++)e.setStyle(o,t,s)}function q(e,t){const n={};for(const r of Object.keys(e)){if(r[0]==="_")continue;const i=e[r];i!==t[r]&&!(typeof i=="object"&&i!==null&&JSON.stringify(i)===JSON.stringify(t[r]))&&(n[r]=i)}return n}function ye(e,t,n,r,i){const s={name:t.name};if(t.hidden&&(s.hidden=!0),t.hidden&&t.veryHidden&&(s.veryHidden=!0),t.tabColor&&(s.tabColor=t.tabColor),t.rtl&&(s.rtl=!0),t.zoom!==1&&(s.zoom=t.zoom),t.frozenRows&&(s.frozenRows=t.frozenRows),t.frozenCols&&(s.frozenCols=t.frozenCols),t.showGridlines===!1&&(s.showGridlines=!1),t.isVirtual&&r.dataSheets==="inline")return{...s,...Q(t,n,i,he)};s.rows=V(t.rows),s.cols=V(t.cols),t.rowStyles?.size&&(s.rowStyles=[...t.rowStyles]),t.colStyles?.size&&(s.colStyles=fe(t.colStyles)),t.merges.length&&(s.merges=t.merges.map(({r0:u,c0:c,r1:d,c1:S})=>[u,c,d,S]));const l=[],f=[];return t.columns.forEach((u,c)=>{if(r.cells===!1)return;const{blocks:d,styles:S}=de(e,t,c,u,r);d.length&&l.push({c,blocks:d}),S.length&&f.push({c,runs:S})}),l.length&&(s.cells=l),f.length&&(s.styles=f),{...s,...Q(t,n,i)}}const he=new Set(["pageSetup","cf","validations","hyperlinks","protection","comments","sparklines","rowExtras","colExtras"]);function Q(e,t,n,r=null){const i={},s={};for(const l of Object.keys(e)){if(ne.has(l)||se.has(l)||l[0]==="_"||l.endsWith("Changed")||r&&!r.has(l))continue;const f=e[l];if(f==null||f===ie[l])continue;const u=m(f,n,`${e.name}.${l}`);u!==void 0&&(s[l]=u)}Object.keys(s).length&&(i.features=s);const o=t?.objectsOf?.(e);if(o?.length){const l=m(o.map(ge),n,`${e.name}.objects`);l.length&&(i.objects=l)}return i}function ge(e){const{bitmap:t,blob:n,canvas:r,modelEpoch:i,...s}=e;return n&&(s.imageType=n.type),s}function Ae(e,t=null,n={}){const r=n.warnings??[],i=G(),s={format:j,version:1};s.activeSheet=e.activeSheet,e.fileName&&(s.fileName=e.fileName),e.themeInfo?s.theme=m(e.themeInfo,r,"theme"):e.theme&&(s.themeColors=e.theme);const o=e.styles.list;s.styles=o.length===1&&Object.keys(q(o[0],i)).length===0?[]:o.map(f=>q(f,i)),e.dxfs?.length&&(s.dxfs=m(e.dxfs,r,"dxfs")),e.persons?.length&&(s.persons=m(e.persons,r,"persons")),e.protection&&(s.protection=m(e.protection,r,"protection")),e.calcMode&&(s.calcMode=e.calcMode),e.getDataQueries&&(s.queries=m(e.getDataQueries,r,"queries")),e.customData&&(s.custom=m(e.customData,r,"custom"));const l=e.engine;if(l&&(l.manual&&(s.manualCalc=!0),l.names.size&&(s.names=[...l.names].map(([f,u])=>{const c=f.indexOf("!");return{name:u.name??(c>=0?f.slice(c+1):f),text:u.text,...c>=0?{sheet:Number(f.slice(0,c))}:{}}})),l.tables.size&&(s.tables=[...l.tables.values()].map(f=>{const{sheet:u,source:c,part:d,id:S,isNew:a,dirty:g,...C}=f;return{...m(C,r,`table ${f.name}`),sheet:e.sheets.indexOf(u)}}))),s.sheets=e.sheets.map(f=>ye(e,f,t,n,r)),s.sheets.some(f=>f.colStyles)&&(s.version=2),s.sheets.some(f=>f.features?.cellTypeRules)&&(s.version=3),n.pivots==="definitions"&&t?.pivotsToJSON){const f=t.pivotsToJSON(n);f&&(s.pivots=f,s.version=4)}if((n.dataSheets==="inline"||t?.keepsDataSheets)&&t?.dataSheetsToJSON){const f=t.dataSheetsToJSON({rows:n.rows!==!1});f&&(s.dataSheets=f,s.version=4)}if(t?.extrasToJSON){const f=t.extrasToJSON(r,n);f&&(s.extras=f)}return r.length&&(s.warnings=r),s}function Se(e,t){t.hidden&&(e.hidden=!0),t.hidden&&t.veryHidden&&(e.veryHidden=!0),t.tabColor&&(e.tabColor=t.tabColor,e.tabColorChanged=!0),t.rtl&&(e.rtl=!0),t.zoom&&(e.zoom=t.zoom),e.frozenRows=t.frozenRows??0,e.frozenCols=t.frozenCols??0,t.showGridlines===!1&&(e.showGridlines=!1),K(e.rows,t.rows),K(e.cols,t.cols),(t.cols?.runs||t.cols?.hidden)&&(e.colsChanged=!0),t.rowStyles&&(e.rowStyles=new Map(t.rowStyles)),t.colStyles&&(e.colStyles=ce(t.colStyles)),t.merges&&(e.merges=t.merges.map(([n,r,i,s])=>({r0:n,c0:r,r1:i,c1:s}))),e.viewChanged=!0;for(const[n,r]of Object.entries(t.features??{})){let i=h(r);(n==="cf"||n==="validations")&&Array.isArray(i)&&(i=i.filter(s=>!s?.managedBy)),e[n]=re(n,i),B[n]&&(e[B[n]]=!0)}}function Ce(e,t){const n=G();t.styles?.length&&e.styles.load(t.styles.map(r=>({...n,...r}))),t.dxfs&&(e.dxfs=h(t.dxfs),e.sourceDxfs=0),t.persons&&(e.persons=h(t.persons),e.personsChanged=!0),t.protection&&(e.protection=h(t.protection),e.protectionChanged=!0),t.calcMode&&(e.calcMode=t.calcMode,e.calcModeChanged=!0),t.queries&&(e.getDataQueries=h(t.queries)),t.custom&&(e.customData=h(t.custom)),t.fileName&&(e.fileName=t.fileName),t.themeColors&&(e.theme=t.themeColors)}function we(e,t,n={}){const{engine:r}=e;e.formulasEdited=!0,e.activeSheet=Math.min(t.activeSheet??0,e.sheets.length-1),r.sheetsChanged(),t.manualCalc&&(r.manual=!0),r.setNames((t.names??[]).map(i=>({name:i.name,text:i.text,localSheetId:i.sheet}))),t.names?.length&&(e.namesChanged=!0),r.setTables((t.tables??[]).map(i=>{const{sheet:s,...o}=i;return{...h(o),sheet:e.sheets[s],isNew:!0,dirty:!0}})),r.buildGraph({fullCalc:n.recalculate===!0}),e.dirty=!1}function $e(e,t={}){if(e?.format!==j)throw new Error(`This isn't ${j} JSON`);if(e.version>L)throw new Error(`This JSON has version ${e.version}; this code reads up to ${L}`);const n=new ee;return n.engine=new te(n),Ce(n,t.styles===!1?{...e,styles:[]}:e),n.sheets=e.sheets.map(r=>new U(r.name)),e.sheets.forEach((r,i)=>{const s=n.sheets[i];Se(s,r);for(const o of r.cells??[])me(n,s,o.c,o.blocks);if(t.styles!==!1)for(const o of r.styles??[])pe(s,o.c,o.runs);if(r.styles?.length)for(const o of r.styles)o.c>s.maxCol&&(s.maxCol=o.c)}),we(n,e,t),n}export{j as FORMAT_NAME,L as FORMAT_VERSION,Ce as applyBookMeta,Se as applySheetMeta,$e as bookFromJSON,Ae as bookToJSON,h as decodeData,m as encodeData,we as finishLoad,Ee as registerFeatureReviver,re as reviveSheetFeature};
|
package/calc/engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveStructuredSpec as gt}from"../slicers/structured.js";import{Arr as A,compareValues as O,ERR as g,ERR_BY_INDEX as Q,Lambda as bt,num as N,power as wt,Ref as V,RefArray as tt,RefList as B,RichValue as H,str as lt,XlError as C}from"./values.js";import{entityVm as ot,richValueAt as Mt}from"../cells/rich-values.js";import{Compiler as ct}from"./compile.js";import{formulaEntryLimit as Rt,FormulaSyntaxError as K,Parser as J,templateKey as At,tokenize as Z,toDisplayFormula as Ct}from"./parser.js";import{BOOL as W,CHUNK_BITS as T,CHUNK_MASK as x,CONTENT_MASK as et,DIRTY as w,EMPTY as v,EVALUATING as X,FORMULA as L,KIND_MASK as E,NUM as U,SPILL as Y,STR as G,ERR as I}from"../core/sheet.js";import{colName as ht,MAX_COLS as b,MAX_ROWS as D,parseRangeRef as P}from"../core/address.js";import{CellSet as xt}from"./cell-set.js";import{isRowBelow as Tt}from"./fill-shape.js";import{FUNCS as Lt}from"./functions/registry.js";import"./functions/index.js";const St=new Set(["range","rows","cols","rangeOp","intersect","union"]);function ut(p){for(;p.t==="paren";)p=p.e;if(St.has(p.t))return!0;if(p.t!=="call")return!1;const t=Lt.get(p.name),e=t?.refResult;return(typeof e=="function"?e(p.args):e===!0)?!0:t?.passes!==void 0&&p.args.some((s,n)=>t.passes(n,p.args.length)&&ut(s))}const st=Symbol("pending"),ft=200,Et=1e6,It=4096,Nt=64,nt=2147483647,$=4;class it{constructor(){this.n=0,this.data=new Int32Array($*8)}push(t,e,s,n){if((this.n+1)*$>this.data.length){const r=new Int32Array(this.data.length*2);r.set(this.data),this.data=r}const i=this.n++*$,a=this.data;a[i]=t,a[i+1]=e,a[i+2]=s,a[i+3]=n}}function Ut(p,t){if(!p.valueMeta.has(t))return;const e=new Map(p.valueMeta);e.delete(t),p.valueMeta=e.size>0?e:null}function dt(p,t,e){if(p.valueMeta?.get(t)===e)return;const s=new Map(p.valueMeta??[]);s.set(t,e),p.valueMeta=s}function j(p,t){let e=p.get(t);return e===void 0&&(e=new xt,p.set(t,e)),e}class Ft{constructor(){this.buckets=[],this.wide=[],this.all=new it,this.allCols=[]}}class Yt{constructor(t){this.book=t,this.sheetGen=0,this.sheetMap=new Map,this.deps=new Map,this.templates=new Map,this.lastOwn={row:-2,col:-1,text:"",tpl:{cacheKey:void 0}},this.frame=null,this.depth=0,this.legacy=!1,this.pendingSheet=null,this.pendingRow=0,this.pendingCol=0,this.circular=null,this.evalStack=new Int32Array(3*256),this.evalTop=0,this.cycleLow=nt,this.iterate=null,this.cycleFound=[],this.cycleMembers=null,this.iterating=!1,this.sliceMs=10,this.syncLimit=4e3,this.externalLinks=null,this.names=new Map,this.nameTemplates=new Map,this.tables=new Map,this.volatile=new Map,this.visibilityReaders=new Map,this.sheetReaders=new Map,this.styleReaders=new Map,this.wakePending=0,this.queue=new Int32Array(4096),this.qHead=0,this.qLen=0,this.sheetsByUid=new Map,this.running=!1,this.timer=0,this.manual=!1,this.graphReady=!0,this.pendingChanges=[],this.waiters=[],this.onChange=null,this.dataTables=[],this.tablesDirty=!1,this.inTables=!1,this.tablesForced=!1,this.onProgress=null,this.lookupCache=new Map,this.colRevisions=new Map,this.channel=null,this.sheetsChanged()}orderChanged(){this.sheetsChanged(),this.has3D&&this.rebuild()}sheetsChanged(){this.sheetGen++,this.sheetMap.clear(),this.sheetsByUid.clear();for(const t of this.book.sheets)this.sheetMap.set(t.name.toUpperCase(),t),this.sheetsByUid.set(t.uid,t),t.rows.watcher=this,t.cols.watcher=this;this._wakeReaders(this.sheetReaders)}sheetByName(t){return this.sheetMap.get(t.toUpperCase())??null}externalSheet(t,e){return this.externalLinks?.sheet(t,e)??null}sheetsBetween(t,e){const{sheets:s}=this.book,n=s.findIndex(a=>a.name.toUpperCase()===t.toUpperCase()),i=s.findIndex(a=>a.name.toUpperCase()===e.toUpperCase());return n<0||i<0?null:s.slice(Math.min(n,i),Math.max(n,i)+1)}setNames(t){this.names.clear(),this.nameTemplates.clear();for(const e of t){const s=e.localSheetId!==void 0?`${e.localSheetId}!${e.name.toUpperCase()}`:e.name.toUpperCase();this.names.set(s,{text:e.text,name:e.name,hidden:e.hidden,comment:e.comment})}}setTables(t){this.tables.clear();for(const e of t)this.tables.set(e.name.toUpperCase(),e)}template(t,e,s){let n;try{n=Z(t)}catch(r){if(r instanceof K)return this._broken(t);throw r}const i=At(n,e,s);let a=this.templates.get(i);if(a===void 0){try{const r=new J(n,e,s).parse();a=this._compile(r)}catch(r){if(!(r instanceof K))throw r;a=this._broken(t)}a.cacheKey=i,this.templates.set(i,a)}return a}_ownTemplate(t,e,s){const n=this.lastOwn;let i;return n.row===e-1&&n.col===s&&this.templates.get(n.tpl.cacheKey)===n.tpl&&Tt(n.text,t)?i=n.tpl:i=this.template(t,e,s),n.row=e,n.col=s,n.text=t,n.tpl=i,i}_compile(t,e=!1){const s=new ct(this,e);return{fn:s.compileTop(t),refs:s.refs,names:s.names,tables:s.tables,isVolatile:s.isVolatile,readsSheets:s.readsSheets,notInExcel:s.notInExcel===!0,mayArray:s.mayArray,rangeResult:ut(t),external:s.external,keepImportedResult:s.keepImportedResult}}_broken(){return{invalid:!0,fn:()=>g.NAME,refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1,external:!0}}validate(t){const e=Rt(t);if(e)throw new K(e);at(new J(Z(t),0,0).parse())}_templateFor(t,e,s,n){if(n.tpl!==void 0)return n.tpl;let i;return n.t==="dataTable"?i=this._dataTableTemplate():n.f!==void 0&&n.base===void 0?i=this._ownTemplate(n.f,e,s):n.f!==void 0?i=this.template(n.f,Math.floor(n.base/b),n.base%b):n.sf!==void 0?i=this.template(n.sf,Math.floor(n.base/b),n.base%b):i=this._broken(),n.tpl=i,i}_index(t){let e=this.deps.get(t);return e===void 0&&(e=new Ft,this.deps.set(t,e)),e}_addDep(t,e,s,n,i,a,r,o){const l=this._index(t),c=a.uid<<14|o;if(i-s>=Nt){l.all.push(r,c,e,n),l.allCols.push(s,i);return}if(n-e>=It){for(let m=s;m<=i;m++){let h=l.wide[m];h===void 0&&(h=new it,l.wide[m]=h),h.push(r,c,e,n)}return}const f=e>>>T,u=n>>>T;for(let m=s;m<=i;m++){let h=l.buckets[m];h===void 0&&(h=[],l.buckets[m]=h);for(let y=f;y<=u;y++){let _=h[y];_===void 0&&(_=new it,h[y]=_),_.push(r,c,e,n)}}}register(t,e,s,n){const i=this._templateFor(t,e,s,n);if(i.external||i.keepImportedResult&&!n.typed&&(t.kind(e,s)&E)!==v)return i;for(const a of i.refs)this._addRefDep(a,t,e,s);for(const a of i.names)this._addNameDeps(a,t,e,s);for(const a of i.tables)this._addTableDep(a,t,e,s);return i.readsSheets&&j(this.sheetReaders,t).add(e,s),i.isVolatile&&j(this.volatile,t).add(e,s),i.readsVisibility??=/SUBTOTAL|AGGREGATE|SPARK_/i.test(n.f??n.sf??""),i.readsVisibility&&j(this.visibilityReaders,t).add(e,s),i.readsStyles??=/SPARK_BLOCK/i.test(n.f??n.sf??""),i.readsStyles&&j(this.styleReaders,t).add(e,s),i}_addRefDep(t,e,s,n){const i=t.wrap?(t.rAbs0?t.r0:s+t.r0)%D:t.rAbs0?t.r0:s+t.r0,a=t.wrap?(t.rAbs1?t.r1:s+t.r1)%D:t.rAbs1?t.r1:s+t.r1,r=t.wrap?(t.cAbs0?t.c0:n+t.c0)%b:t.cAbs0?t.c0:n+t.c0,o=t.wrap?(t.cAbs1?t.c1:n+t.c1)%b:t.cAbs1?t.c1:n+t.c1,l=Math.max(0,Math.min(i,a)),c=Math.min(D-1,Math.max(i,a)),f=Math.max(0,Math.min(r,o)),u=Math.min(b-1,Math.max(r,o));if(l>c||f>u)return;if(t.sheet?.sheet2&&(t.sheet.book===null||t.sheet.book===void 0)){this.has3D=!0;for(const h of this.sheetsBetween(t.sheet.sheet,t.sheet.sheet2)??[])this._addDep(h,l,f,c,u,e,s,n);return}if(t.sheet?.book!==null&&t.sheet?.book!==void 0)return;const m=t.sheet?this.sheetByName(t.sheet.sheet):e;m&&this._addDep(m,l,f,c,u,e,s,n)}_addNameDeps(t,e,s,n){const i=this._nameTemplate(t,e);if(i!==null){i.readsSheets&&j(this.sheetReaders,e).add(s,n);for(const a of i.refs)this._addRefDep(a,e,s,n);for(const a of i.tables)this._addTableDep(a,e,s,n);for(const a of i.names)a.toUpperCase()!==t.toUpperCase()&&this._addNameDeps(a,e,s,n)}}_addTableDep(t,e,s,n){const i=this.resolveTable(t.name,t.spec,s,n,e);i instanceof V&&this._addDep(i.sheet,i.r0,i.c0,i.r1,i.c1,e,s,n)}rebuild(){this.has3D=!1,this.deps.clear(),this.volatile.clear(),this.visibilityReaders.clear(),this.styleReaders.clear(),this.sheetReaders.clear(),this.lookupCache.clear(),this.qHead=0,this.qLen=0,this.cycleFound=[],this.cycleMembers=null,this.sheetGen++,this.buildGraph({fullCalc:!0})}buildGraph({fullCalc:t=!1,onDone:e}={}){this.graphReady=!1,this.dataTables=[],t&&(this.tablesDirty=!0);const s=this,n=this.sheetGen,i=this.book.sheets.map(f=>[f,f.formulas]);let a=0,r=0,o=0,l=0;const c=()=>{const f=performance.now()+s.sliceMs;let u=0;for(;a<i.length;a++,r=0,o=0,l=0){const[h,y]=i[a],{columns:_}=y;for(;r<_.length;r++,o=0,l=0){const d=_[r];if(d!==void 0)for(;o<d.length;o++,l=0){const k=d[o];if(k===void 0)continue;const{ids:R}=k,S=o<<T;for(;l<=x;l++){const M=R[l];if(M===0)continue;const F=y.infos[M],q=S+l;F.t==="dataTable"&&s.dataTables.push({sheet:h,row:q,col:r,info:F});const _t=s.register(h,q,r,F);if(s._initFormula(h,q,r,F,_t,t),++u%256===0&&performance.now()>f){l++,s.onProgress?.({preparing:!0}),s._later(c);return}}}}}s.graphReady=!0,s.sheetGen!==n&&s._wakeReaders(s.sheetReaders);const m=s.pendingChanges;s.pendingChanges=[];for(const[h,y,_,d]of m)s.cellsChanged(h,y,_,d);s._schedule(),e?.()};c()}_initFormula(t,e,s,n,i,a){const r=t._chunk(e,s);if(r===void 0)return;const o=e&x;n.t==="array"&&n.ref&&this._markArrayChildren(t,e,s,n);const l=r.kinds[o];if(i.external||i.keepImportedResult&&!n.typed&&(l&E)!==v)return;const c=n.ca==="1"||n.ca==="true";(a||c||i.isVolatile||(l&E)===v||i.notInExcel&&(l&E)===I)&&(r.kinds[o]=l|w,this._enqueue(t,e,s))}_markArrayChildren(t,e,s,n){const i=P(n.ref);if(i!==null){t.spills||(t.spills=new Map),t.spills.set(e*b+s,{...i,blocked:!1,fixed:!n.cm});for(let a=i.r0;a<=i.r1;a++)for(let r=i.c0;r<=i.c1;r++){if(a===e&&r===s)continue;const o=t._ensure(a,r);o.kinds[a&x]|=Y}}}_enqueue(t,e,s){if(this.qLen+3>this.queue.length)if(this.qHead>this.queue.length>>>1)this.queue.copyWithin(0,this.qHead,this.qLen),this.qLen-=this.qHead,this.qHead=0;else{const n=new Int32Array(this.queue.length*2);n.set(this.queue),this.queue=n}this.queue[this.qLen++]=t.uid,this.queue[this.qLen++]=e,this.queue[this.qLen++]=s}_dirtyFrom(t,e,s,n,i){const a=[t,e,s,n,i];for(;a.length>0;){const r=a.pop(),o=a.pop(),l=a.pop(),c=a.pop(),f=a.pop(),u=this.deps.get(f);if(u===void 0)continue;const m=(_,d)=>{const k=this.sheetsByUid.get(d>>>14);if(k===void 0)return;const R=d&16383,S=k._chunk(_,R);if(S===void 0)return;const M=_&x,F=S.kinds[M];(F&L)===0||(F&w)!==0||(S.kinds[M]=F|w,this._enqueue(k,_,R),a.push(k,R,R,_,_))},h=o>>>T,y=r>>>T;for(let _=c;_<=l;_++){const d=u.buckets[_];if(d!==void 0)for(let R=h;R<=y;R++){const S=d[R];if(S===void 0)continue;const{data:M}=S,F=S.n*$;for(let q=0;q<F;q+=$)r>=M[q+2]&&o<=M[q+3]&&m(M[q],M[q+1])}const k=u.wide[_];if(k!==void 0){const{data:R}=k,S=k.n*$;for(let M=0;M<S;M+=$)r>=R[M+2]&&o<=R[M+3]&&m(R[M],R[M+1])}}if(u.all.n>0){const{data:_}=u.all;for(let d=0;d<u.all.n;d++){const k=d*$;r>=_[k+2]&&o<=_[k+3]&&l>=u.allCols[d*2]&&c<=u.allCols[d*2+1]&&m(_[k],_[k+1])}}}}cellsChanged(t,e,s,n){if(n===0)return;if(t.valueListeners)for(const a of t.valueListeners)for(let r=0;r<n;r++)a(e[r],s[r],e[r],s[r]);if(this.inTables||(this.tablesDirty=!0),!this.graphReady){this.pendingChanges.push([t,e.slice(0,n),s.slice(0,n),n]);return}this.lookupCache.clear();const i=new Map;for(let a=0;a<n;a++){const r=e[a],o=s[a],l=i.get(o);l===void 0?i.set(o,[r,r]):(r<l[0]&&(l[0]=r),r>l[1]&&(l[1]=r));const c=t._chunk(r,o);if(c===void 0)continue;const f=r&x,u=c.kinds[f];if(u&L){const m=t.formula(r,o);m&&(this.register(t,r,o,m),u&w||(c.kinds[f]=u|w,this._enqueue(t,r,o)))}t.spills&&this._spillTouched(t,r,o)}for(const[a,r]of i)this._dirtyFrom(t,a,a,r[0],r[1]);this._markVolatile(),this._schedule()}_spillTouched(t,e,s){const n=e*b+s;for(const[i,a]of t.spills){const r=Math.floor(i/b),o=i-r*b;if(i===n){(t.kind(r,o)&L)===0&&(this._clearSpill(t,a,r,o),t.spills.delete(i));continue}if(e>=a.r0&&e<=a.r1&&s>=a.c0&&s<=a.c1){const l=t._chunk(r,o);if(l===void 0)continue;const c=r&x,f=l.kinds[c];f&L&&!(f&w)&&(l.kinds[c]=f|w,this._enqueue(t,r,o),this._dirtyFrom(t,o,o,r,r))}}}_markVolatile(){for(const[t,e]of this.volatile)e.forEach((s,n)=>{const i=t._chunk(s,n);if(i===void 0)return;const a=s&x,r=i.kinds[a];if(!(r&L)){e.delete(s,n);return}r&w||(i.kinds[a]=r|w,this._enqueue(t,s,n),this._dirtyFrom(t,n,n,s,s))})}get pending(){return(this.qLen-this.qHead)/3}_later(t){if(this._next=t,typeof MessageChannel>"u"){setTimeout(()=>this._tick(),0);return}this.channel===null&&(this.channel=new MessageChannel,this.channel.port1.onmessage=()=>this._tick()),this.channel.port2.postMessage(0)}_tick(){const t=this._next;this._next=null,t?.(),this._next===null&&this.channel!==null&&(this.channel.port1.close(),this.channel=null)}_schedule(){if(this.manual||this.inTables||this.running||!this.graphReady)return;if(this.pending===0){this._finish();return}const t=this.pending;if(t<=this.syncLimit&&(this._slice(this.syncLimit===1/0?1/0:this.sliceMs),this.pending===0)){this._finish();return}this.running=!0,this._total=t;const e=()=>{this._slice(this.sliceMs),this.pending>0?(this.onProgress?.({remaining:this.pending,total:Math.max(this._total,this.pending)}),this._later(e)):(this.running=!1,this._finish())};this._later(e)}_slice(t){const e=t!==1/0;let s=e?performance.now():0;const n=s+t;let i=1,a=1;for(;this.qHead<this.qLen;){const r=this.queue[this.qHead++],o=this.queue[this.qHead++],l=this.queue[this.qHead++],c=this.sheetsByUid.get(r);if(c!==void 0&&(this._run(c,o,l),e&&--a===0)){const f=performance.now();if(f>n)break;i=f-s<.5?Math.min(i*2,16):1,a=i,s=f}}this.qHead>=this.qLen&&(this.qHead=0,this.qLen=0)}_finish(){for(;this.cycleFound.length>0;)this._iterateCycles();const t=this.tablesForced;this.tablesForced=!1,this.tablesDirty&&this.dataTables.length>0&&(!this.skipTables||t)&&(this.tablesDirty=!1,this._computeDataTables()),this.book.formatValueRevision=(this.book.formatValueRevision??0)+1,this.onChange?.();const e=this.waiters;this.waiters=[];for(const s of e)s()}_dataTableTemplate(){const t=this;return{fn:(s,n,i)=>t._plainValue(i,s,n),refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1}}_plainValue(t,e,s){const n=t.value(e,s);switch(t.kind(e,s)&E){case U:return n;case G:return this.book.strings.get(n);case W:return n!==0;case I:return Q[n];default:return null}}_writePlain(t,e,s,n){const i=t.kind(e,s)&L;n==null?t.setCell(e,s,i|U,0):typeof n=="number"?Number.isFinite(n)?t.setCell(e,s,i|U,n):t.setCell(e,s,i|I,g.NUM.index):typeof n=="boolean"?t.setCell(e,s,i|W,n?1:0):n instanceof C?t.setCell(e,s,i|I,n.index):t.setCell(e,s,i|G,this.book.strings.add(String(n)))}_setInputs(t,e){const s=new Uint32Array(e.length),n=new Uint32Array(e.length);e.forEach((i,a)=>{t.setCell(i.row,i.col,i.kind,i.value),s[a]=i.row,n[a]=i.col}),this.cellsChanged(t,s,n,e.length),this._slice(1/0)}evaluateWith(t,e,s){const n=e.map(({row:a,col:r})=>({row:a,col:r,kind:t.kind(a,r)&(E|L),value:t.value(a,r)})),i=this.inTables;this.inTables=!0;try{return this._setInputs(t,e.map(({row:a,col:r,text:o})=>{const l=Number(o);return o!==""&&Number.isFinite(l)?{row:a,col:r,kind:U,value:l}:{row:a,col:r,kind:G,value:this.book.strings.add(String(o))}})),s()}finally{this._setInputs(t,n),this.inTables=i}}_computeDataTables(){this.inTables=!0;const t=this.dataTables.filter(e=>e.sheet.formula(e.row,e.col)===e.info&&this.book.sheets.includes(e.sheet));this.dataTables=t;try{for(const e of t)this._computeDataTable(e)}finally{this.inTables=!1}}_computeDataTable({sheet:t,info:e}){const s=P(e.ref);if(!s)return;const n=P(e.r1??""),i=e.r2?P(e.r2):null,a=e.dt2D==="1"||e.dt2D==="true",r=e.dtr==="1"||e.dtr==="true",o=e.del1==="1"||e.del1==="true"||a&&(e.del2==="1"||e.del2==="true");if(!o&&(!n||a&&!i))return;const l=(d,k)=>({kind:t.kind(d,k)&E,value:t.value(d,k)}),f=(o?[]:[n,i].filter(Boolean)).map(d=>({row:d.r0,col:d.c0,kind:t.kind(d.r0,d.c0)&(E|L),value:t.value(d.r0,d.c0)})),u=[],m=(d,k,R,S)=>{const M=this.read(t,R,S);u.push(d,k,M instanceof A?M.data[0]:M)};try{if(o)for(let d=s.r0;d<=s.r1;d++)for(let k=s.c0;k<=s.c1;k++)u.push(d,k,g.REF);else if(a)for(let d=s.r0;d<=s.r1;d++)for(let k=s.c0;k<=s.c1;k++)this._setInputs(t,[{row:n.r0,col:n.c0,...l(s.r0-1,k)},{row:i.r0,col:i.c0,...l(d,s.c0-1)}]),m(d,k,s.r0-1,s.c0-1);else if(r)for(let d=s.c0;d<=s.c1;d++){this._setInputs(t,[{row:n.r0,col:n.c0,...l(s.r0-1,d)}]);for(let k=s.r0;k<=s.r1;k++)m(k,d,k,s.c0-1)}else for(let d=s.r0;d<=s.r1;d++){this._setInputs(t,[{row:n.r0,col:n.c0,...l(d,s.c0-1)}]);for(let k=s.c0;k<=s.c1;k++)m(d,k,s.r0-1,k)}}finally{f.length>0&&this._setInputs(t,f)}const h=u.length/3,y=new Uint32Array(h),_=new Uint32Array(h);for(let d=0;d<h;d++)y[d]=u[d*3],_[d]=u[d*3+1],this._writePlain(t,y[d],_[d],u[d*3+2]);this.cellsChanged(t,y,_,h),this._slice(1/0),t.revision++}dataTableAt(t,e,s){for(const n of this.dataTables){if(n.sheet!==t)continue;const i=P(n.info.ref);if(i&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1)return n}return null}calculateNow(){const{manual:t,skipTables:e}=this;this.manual=!1,this.skipTables=!1,this.tablesDirty=!0,this.tablesForced=!0,this._markVolatile(),this._markCycles(),this._schedule(),this.manual=t,this.skipTables=e}whenIdle(){return this.pending===0&&this.graphReady&&!this.running?Promise.resolve():new Promise(t=>{this.waiters.push(t),this._schedule()})}_iterateCycles(){const t=this.cycleFound;this.cycleFound=[];const e=new Map,s=(r,o,l)=>{let c=e.get(r.uid);c===void 0&&(c=new Map,e.set(r.uid,c)),c.set(o*b+l,[r,o,l])};for(let r=0;r<t.length;r+=3)s(t[r],t[r+1],t[r+2]);const n=[];for(const r of this.book.sheets){const o=e.get(r.uid);o&&n.push(...[...o.keys()].sort((l,c)=>l-c).map(l=>o.get(l)))}this.cycleMembers??=new Map;for(const r of n)this.cycleMembers.set(`${r[0].uid}:${r[1]}:${r[2]}`,r);const{count:i,delta:a}=this.iterate;for(let r=1;r<=i;r++){let o=0;for(const[l,c,f]of n){const u=l._chunk(c,f);if(u===void 0)continue;const m=c&x;if(!(u.kinds[m]&L))continue;const h=u.values[m];u.kinds[m]|=w,this.iterating=!0,this._run(l,c,f),this.iterating=!1;const y=Math.abs(u.values[m]-h);y>o&&(o=y)}if(this.onProgress?.({iteration:r,iterations:i}),o<a)break}for(const[r,o,l]of n)this._dirtyFrom(r,l,l,o,o);for(const[r,o,l]of n){const c=r._chunk(o,l);c!==void 0&&(c.kinds[o&x]&=~w)}this._slice(1/0)}_markCycles(){if(!(this.iterate===null||this.cycleMembers===null))for(const[t,e,s]of this.cycleMembers.values()){const n=t._chunk(e,s);n===void 0||!(n.kinds[e&x]&L)||(n.kinds[e&x]|=w,this._enqueue(t,e,s))}}_run(t,e,s){const n=[t,e,s];for(;n.length>0;){const i=n[n.length-1],a=n[n.length-2],r=n[n.length-3];try{this.depth=0,this.evalTop=0,this.cycleLow=nt,this._calc(r,a,i),n.length-=3}catch(o){if(o!==st)throw o;n.push(this.pendingSheet,this.pendingRow,this.pendingCol)}}}_calc(t,e,s){const n=t._chunk(e,s);if(n===void 0)return;const i=e&x,a=n.kinds[i];if(!(a&w))return;if(a&X){this.circular={sheet:t,row:e,col:s},this.iterating||this._cycleHit(t.uid,e,s);return}if(this.depth>=ft)throw this.pendingSheet=t,this.pendingRow=e,this.pendingCol=s,st;const r=t.formula(e,s);if(r===void 0||!(a&L)){n.kinds[i]=a&~w;return}const o=this._templateFor(t,e,s,r);if(o.external||o.keepImportedResult&&!r.typed&&(a&E)!==v){n.kinds[i]=a&~w;return}n.kinds[i]=a|X;const l=this.evalTop;l+3>this.evalStack.length&&this._growEvalStack(),this.evalStack[l]=t.uid,this.evalStack[l+1]=e,this.evalStack[l+2]=s,this.evalTop=l+3;const c=this.cycleLow;this.cycleLow=nt;const f=this.legacy,u=this.frame,m=r.typed!==!0&&r.t!=="array";this.legacy=m,this.depth++;let h;try{h=o.fn(e,s,t),(h instanceof V||h instanceof B)&&(h=this.refAuto(h,e,s)),h instanceof tt&&(h=this.toArr(h))}catch(_){if(n.kinds[i]&=~X,this.depth--,this.legacy=f,this.frame=u,this.evalTop=l,this.cycleLow=c,_===st)throw _;_ instanceof C?h=_:(console.error("Formula evaluation failed",_),h=g.VALUE),this._store(t,n,i,e,s,h,r,m);return}this.depth--,this.legacy=f,this.frame=u,this.evalTop=l;const y=this.cycleLow;if(this.cycleLow=y<l&&y<c?y:c,y<=l){if(this.iterate!==null){n.kinds[i]=a&~(w|X),this.cycleFound.push(t,e,s);return}if(r.typed===void 0&&(a&E)!==v){n.kinds[i]=a&~(w|X);return}h=0}this._store(t,n,i,e,s,h,r,m)}_cycleHit(t,e,s){const n=this.evalStack;for(let i=this.evalTop-3;i>=0;i-=3)if(n[i]===t&&n[i+1]===e&&n[i+2]===s){i<this.cycleLow&&(this.cycleLow=i);return}}_growEvalStack(){const t=new Int32Array(this.evalStack.length*2);t.set(this.evalStack),this.evalStack=t}_store(t,e,s,n,i,a,r,o){let l=a;l instanceof bt&&(l=g.CALC),l instanceof A?r.t==="array"&&!r.cm&&r.ref?l=this._fillFixedArray(t,n,i,r,l):o||l.spillRows===1&&l.spillCols===1?(l=l.data[0],t.spills&&this._releaseSpill(t,n,i)):l=this._spill(t,n,i,r,l):t.spills&&!(r.t==="array"&&!r.cm)&&this._releaseSpill(t,n,i),r.t==="array"&&!r.cm&&r.ref&&!(a instanceof A)&&(l=this._fillFixedArray(t,n,i,r,A.filled(1,1,l)));let c=L,f=0;if(typeof l=="number"?Number.isFinite(l)?(c|=U,f=l):(c|=I,f=g.NUM.index):typeof l=="string"?(c|=G,f=this.book.strings.add(l)):typeof l=="boolean"?(c|=W,f=l?1:0):l instanceof C?(c|=I,f=l.index):l instanceof H?(c|=I,f=g.VALUE.index):c|=U,l instanceof H?dt(t,n*b+i,ot(this.book,l.index)):t.valueMeta!==null&&((e.kinds[s]&et)!==c||e.values[s]!==f)&&!/IMAGE\(/i.test(r.f??r.sf??"")&&Ut(t,n*b+i),t.valueListeners&&((e.kinds[s]&et)!==c||e.values[s]!==f))for(const u of t.valueListeners)u(n,i,n,i);e.kinds[s]=c,e.values[s]=f,n>t.maxRow&&(t.maxRow=n),i>t.maxCol&&(t.maxCol=i)}_writeArrayCell(t,e,s,n){let i=Y,a=0;typeof n=="number"?(i|=Number.isFinite(n)?U:I,a=Number.isFinite(n)?n:g.NUM.index):typeof n=="string"?(i|=G,a=this.book.strings.add(n)):typeof n=="boolean"?(i|=W,a=n?1:0):n instanceof C?(i|=I,a=n.index):n==null?i|=U:(i|=I,a=g.VALUE.index,n instanceof H&&dt(t,e*b+s,ot(this.book,n.index))),t.setCell(e,s,i,a)}_fillFixedArray(t,e,s,n,i){const a=P(n.ref);if(a===null)return i.data[0];t.spills||(t.spills=new Map),t.spills.set(e*b+s,{...a,blocked:!1,fixed:!0});const r=(l,c)=>{const f=i.rows===1?0:l,u=i.cols===1?0:c;return f>=i.rows||u>=i.cols?g.NA:i.get(f,u)};for(let l=a.r0;l<=a.r1;l++)for(let c=a.c0;c<=a.c1;c++)l===e&&c===s||this._writeArrayCell(t,l,c,r(l-a.r0,c-a.c0));(a.r0!==a.r1||a.c0!==a.c1)&&this._dirtyFrom(t,a.c0,a.c1,a.r0,a.r1);const o=r(e-a.r0,s-a.c0);return o===null?0:o}_spill(t,e,s,n,i){const a=e*b+s;t.spills||(t.spills=new Map);const r=t.spills.get(a),o=e+i.rows-1,l=s+i.cols-1,c={r0:e,c0:s,r1:o,c1:l,blocked:!1,fixed:!1},f=(h,y)=>r&&h>=r.r0&&h<=r.r1&&y>=r.c0&&y<=r.c1;let u=e+i.spillRows>D||s+i.spillCols>b;if(!u)t:for(let h=e;h<=o;h++)for(let y=s;y<=l;y++){if(h===e&&y===s)continue;const _=t.kind(h,y);if((_&et)!==0&&!(_&Y&&f(h,y))){u=!0;break t}if(t.merges.length>0&&t.mergeAt(h,y)){u=!0;break t}}if(u)return r&&!r.blocked&&this._clearSpill(t,r,e,s),c.blocked=!0,c.r1=Math.min(o,D-1),c.c1=Math.min(l,b-1),t.spills.set(a,c),g.SPILL;if(r&&!r.blocked){for(let h=r.r0;h<=r.r1;h++)for(let y=r.c0;y<=r.c1;y++)h>=c.r0&&h<=c.r1&&y>=c.c0&&y<=c.c1||(t.kind(h,y)&Y)!==0&&t.setCell(h,y,v,0);this._dirtyFrom(t,r.c0,r.c1,r.r0,r.r1)}t.spills.set(a,c);for(let h=e;h<=o;h++)for(let y=s;y<=l;y++)h===e&&y===s||this._writeArrayCell(t,h,y,i.get(h-e,y-s));n.t="array",n.ref=`${pt(s)}${e+1}:${pt(l)}${o+1}`,n.cm=1,delete n.raw,this._dirtyFrom(t,s,l,e,o);const m=i.data[0];return m===null?0:m}_clearSpill(t,e,s,n){for(let i=e.r0;i<=e.r1;i++)for(let a=e.c0;a<=e.c1;a++)i===s&&a===n||(t.kind(i,a)&Y)!==0&&t.setCell(i,a,v,0);this._dirtyFrom(t,e.c0,e.c1,e.r0,e.r1)}_releaseSpill(t,e,s){const n=e*b+s,i=t.spills.get(n);if(i===void 0)return;i.blocked||this._clearSpill(t,i,e,s),t.spills.delete(n);const a=t.formula(e,s);a&&a.typed&&(delete a.ref,delete a.cm,delete a.t)}spillMaster(t,e,s){if(!t.spills)return null;for(const[n,i]of t.spills)if(!i.blocked&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1){const a=Math.floor(n/b);return{row:a,col:n-a*b,rect:i}}return null}spillRange(t){const{sheet:e,r0:s,c0:n}=t;this.read(e,s,n);const i=e.spills?.get(s*b+n);return!i||i.blocked?g.REF:new V(e,i.r0,i.c0,i.r1,i.c1)}read(t,e,s){const n=t.columns[s];if(n===void 0)return null;const i=n[e>>>T];if(i===void 0)return null;const a=e&x;let r=i.kinds[a];if(r===0)return null;switch(r&w&&(this._calc(t,e,s),r=i.kinds[a]),r&E){case U:return i.values[a];case G:return this.book.strings.get(i.values[a]);case W:return i.values[a]!==0;case I:{if(t.valueMeta!==null&&this.book.richValues){const o=Mt(this.book,t,e,s);if(o!==null)return o}return Q[i.values[a]]??g.NA}default:return null}}refToValue(t){return t instanceof B?t.refs.length===1?this.refToValue(t.refs[0]):g.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.toArr(t)}refAuto(t,e,s){return t instanceof B?t.refs.length===1?this.refAuto(t.refs[0],e,s):g.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.legacy?this.intersect(t,e,s):this.toArr(t)}intersect(t,e,s){return t.cols===1&&e>=t.r0&&e<=t.r1?this.read(t.sheet,e,t.c0):t.rows===1&&s>=t.c0&&s<=t.c1?this.read(t.sheet,t.r0,s):g.VALUE}trim(t){const{sheet:e}=t;return{r0:t.r0,c0:t.c0,r1:Math.min(t.r1,Math.max(e.maxRow,t.r0)),c1:Math.min(t.c1,Math.max(e.maxCol,t.c0))}}toArr(t){if(t instanceof tt)return new A(t.rows,t.cols,t.data.map(e=>e instanceof V?this.read(e.sheet,e.r0,e.c0):e));if(t instanceof A)return t;if(t instanceof V){const e=t.rows===D||t.cols===b,{r0:s,c0:n,r1:i,c1:a}=e||t.rows*t.cols>Et?this.trim(t):t,r=i-s+1,o=a-n+1,l=new Array(r*o);let c=0;for(let f=s;f<=i;f++)for(let u=n;u<=a;u++)l[c++]=this.read(t.sheet,f,u);return new A(r,o,l,t.rows===D?D:r,t.cols===b?b:o)}if(t instanceof B){if(t.refs.length===1)return this.toArr(t.refs[0]);throw g.VALUE}if(t instanceof C)throw t;return new A(1,1,[t])}scalar(t,e,s){return t instanceof V?t.isCell?this.read(t.sheet,t.r0,t.c0):this.intersect(t,e,s):t instanceof B?g.VALUE:t instanceof tt?this.scalar(t.data[0],e,s):t instanceof A?t.data[0]:t}scan(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);for(let a=t.c0;a<=n;a++){const r=s.columns[a];if(r!==void 0)for(let o=t.r0>>>T;o<=i>>>T;o++){const l=r[o];if(l===void 0)continue;const c=o<<T,f=Math.max(t.r0-c,0),u=Math.min(i-c,x),{kinds:m}=l;for(let h=f;h<=u;h++){if(m[h]===0)continue;const y=this.read(s,c+h,a);y!==null&&e(y,c+h,a)}}}}sumRange(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);let{sum:a,count:r}=e;for(let o=t.c0;o<=n;o++){const l=s.columns[o];if(l!==void 0)for(let c=t.r0>>>T;c<=i>>>T;c++){const f=l[c];if(f===void 0)continue;const u=c<<T,m=Math.max(t.r0-u,0),h=Math.min(i-u,x),{kinds:y,values:_}=f;for(let d=m;d<=h;d++){let k=y[d];if(k===0)continue;k&w&&(this._calc(s,u+d,o),k=y[d]);const R=k&E;if(R===U)a+=_[d],r++;else if(R===I)throw Q[_[d]]}}}e.sum=a,e.count=r}averageRange(t,e){if(t.cols===1)return this.sumRange(t,e);const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow),a=[],r=[];for(let o=t.r0>>>T;o<=i>>>T;o++){a.length=0,r.length=0;for(let u=t.c0;u<=n;u++){const m=s.columns[u]?.[o];m!==void 0&&(a.push(u),r.push(m))}if(r.length===0)continue;const l=o<<T,c=Math.max(t.r0-l,0),f=Math.min(i-l,x);for(let u=c;u<=f;u++)for(let m=0;m<r.length;m++){const{kinds:h,values:y}=r[m];h[u]&w&&this._calc(s,l+u,a[m]);const _=h[u]&E;if(_===U)e.sum+=y[u],e.count++;else if(_===I)throw Q[y[u]]}}}unary(t,e){if(t instanceof C)return t;if(t instanceof A)return new A(t.rows,t.cols,t.data.map(s=>{try{return s instanceof C?s:e(N(s))}catch(n){return n}}),t.spillRows,t.spillCols);try{return e(N(t))}catch(s){if(s instanceof C)return s;throw s}}slowBin(t,e,s){if(e instanceof A||s instanceof A)return this._binArr(t,e,s);if(e instanceof C)return e;if(s instanceof C)return s;try{return mt(t,e,s)}catch(n){if(n instanceof C)return n;throw n}}_binArr(t,e,s){const n=e instanceof A?e:null,i=s instanceof A?s:null,a=Math.max(n?n.rows:1,i?i.rows:1),r=Math.max(n?n.cols:1,i?i.cols:1),o=new Array(a*r);for(let l=0;l<a;l++)for(let c=0;c<r;c++){const f=rt(e,l,c),u=rt(s,l,c);let m;if(f instanceof C)m=f;else if(u instanceof C)m=u;else try{m=mt(t,f,u)}catch(h){m=h}o[l*r+c]=m}return new A(a,r,o,Math.max(n?.spillRows??1,i?.spillRows??1),Math.max(n?.spillCols??1,i?.spillCols??1))}liftArr(t,e,s){let n=1,i=1,a=1,r=1;for(const f of e)f instanceof A&&(f.rows>n&&(n=f.rows),f.cols>i&&(i=f.cols),f.spillRows>a&&(a=f.spillRows),f.spillCols>r&&(r=f.spillCols));const o=new Array(n*i),l=e.length,c=new Array(l);for(let f=0;f<n;f++)for(let u=0;u<i;u++){let m=null;for(let h=0;h<l;h++){const y=rt(e[h],f,u);c[h]=y,!s&&m===null&&y instanceof C&&(m=y)}if(m!==null){o[f*i+u]=m;continue}try{o[f*i+u]=t(...c)}catch(h){if(h instanceof C)o[f*i+u]=h;else throw h}}return new A(n,i,o,a,r)}invoke(t,e,s,n,i){if(t.native)return this._invokeNative(t.native,e,s,n,i);const a=t.frame?t.frame.slice():[],{params:r}=t;if(e.length>r.length)return g.VALUE;for(let l=0;l<r.length;l++)a[r[l]]=l<e.length?e[l]:void 0;const o=this.frame;if(this.frame=a,this.depth++,this.depth>=ft*4)return this.depth--,this.frame=o,g.NUM;try{return t.body(s,n,i)}finally{this.depth--,this.frame=o}}_invokeNative(t,e,s,n,i){if(e.length<t.min||e.length>t.max)return g.VALUE;try{if(t.kind==="raw")return t.fn(this,e,s,n,i);if(t.kind==="lazy")return t.fn(this,e.map(o=>()=>o),s,n,i);const a=t.dateSystem?(...o)=>t.fn(this.book.dateOffset,...o):t.fn,r=e.map(o=>o instanceof V||o instanceof B?this.refToValue(o):o);if(r.some(o=>o instanceof A))return this.liftArr(a,r,t.errors);if(!t.errors){for(const o of r)if(o instanceof C)return o}return a(...r)}catch(a){if(a instanceof C)return a;throw a}}_nameEntry(t,e){const s=t.toUpperCase();if(e){const i=this.book.sheets.indexOf(e),a=this.names.get(`${i}!${s}`);if(a)return{key:`${i}!${s}`,entry:a}}const n=this.names.get(s);return n?{key:s,entry:n}:null}_nameTemplate(t,e){const s=this._nameEntry(t,e);if(s===null)return null;let n=this.nameTemplates.get(s.key);if(n===void 0){try{n=this._compile(new J(Z(s.entry.text,!0),0,0).parse(!0),!0)}catch(i){if(!(i instanceof K))throw i;n=this._broken()}this.nameTemplates.set(s.key,n)}return n}nameMayYieldRange(t){const e=t.toUpperCase(),s=[];for(const[n,i]of this.names)(n===e||n.endsWith(`!${e}`))&&s.push(i);if(s.length===0||(this._rangeNames??=new Set,this._rangeNames.has(e)))return!0;this._rangeNames.add(e);try{return s.some(n=>{try{return new ct(this).mayYieldRange(new J(Z(n.text,!0),0,0).parse(!0))}catch(i){if(i instanceof K)return!1;throw i}})}finally{this._rangeNames.delete(e)}}evalName(t,e,s,n){const i=this._nameTemplate(t,n);return i===null?g.NAME:i.fn(e,s,n)}tableSpecToA1(t,e,s){const n=kt(t,e,s);if(!(n instanceof V))return null;const i=/#This Row|^\[\s*@/i.test(e),a=(r,o)=>i?`${ht(o)}${r+1}`:`$${ht(o)}$${r+1}`;return n.isCell?a(n.r0,n.c0):`${a(n.r0,n.c0)}:${a(n.r1,n.c1)}`}resolveTable(t,e,s,n,i){let a=t?this.tables.get(t.toUpperCase()):null;if(!t){for(const r of this.tables.values())if(r.sheet===i&&s>=r.r0&&s<=r.r1&&n>=r.c0&&n<=r.c1){a=r;break}}return a?kt(a,e,s):g.REF}exactIndex(t){const e=`${t.sheet.uid}:${t.r0}:${t.c0}:${t.r1}:${t.c1}`;let s=this.lookupCache.get(e);if(s!==void 0)return s;s=new Map;const n=t.cols===1;return this.scan(t,(i,a,r)=>{const o=typeof i=="string"?`s${i.toLowerCase()}`:typeof i=="number"?i:`b${i}`;if(i instanceof C)return;const l=n?a-t.r0:r-t.c0,c=s.get(o);(c===void 0||l<c)&&s.set(o,l)}),this.lookupCache.set(e,s),s}visibilityChanged(){this._wakeReaders(this.visibilityReaders)}presentationChanged(){this._wakeLater(2)}axisHiddenChanged(){this._wakeLater(1)}axisResized(){this._wakeLater(2)}_wakeLater(t){(t===1?this.visibilityReaders:this.styleReaders).size!==0&&(this.wakePending===0&&queueMicrotask(()=>{const e=this.wakePending;this.wakePending=0,e&1&&this._wakeReaders(this.visibilityReaders),e&2&&this._wakeReaders(this.styleReaders)}),this.wakePending|=t)}_wakeReaders(t){if(!this.graphReady||t.size===0)return;let e=!1;for(const[s,n]of t)n.forEach((i,a)=>{const r=s._chunk(i,a);if(r===void 0)return;const o=i&x,l=r.kinds[o];if(!(l&L)){n.delete(i,a);return}l&w||(r.kinds[o]=l|w,this._enqueue(s,i,a)),this._dirtyFrom(s,a,a,i,i),e=!0});e&&this._schedule()}isSubtotalCell(t,e,s){if((t.kind(e,s)&L)===0)return!1;const n=t.formula(e,s),i=n?.f??n?.sf??"";return/^\s*(_xlfn\.)?(SUBTOTAL|AGGREGATE)\(/i.test(i)}displayFormula(t){return Ct(t)}}function pt(p){let t="";for(let e=p+1;e>0;e=Math.floor((e-1)/26))t=String.fromCharCode(65+(e-1)%26)+t;return t}function rt(p,t,e){if(!(p instanceof A))return p;const s=p.rows===1?0:t,n=p.cols===1?0:e;return s>=p.rows||n>=p.cols?g.NA:p.data[s*p.cols+n]}function mt(p,t,e){if((t instanceof H||e instanceof H)&&p!=="="&&p!=="<>"&&p!=="&")throw g.VALUE;switch(p){case"+":{const s=N(t),n=s+N(e);return Math.abs(n)<Math.abs(s)*yt?0:z(n)}case"-":{const s=N(t),n=s-N(e);return Math.abs(n)<Math.abs(s)*yt?0:z(n)}case"*":return z(N(t)*N(e));case"/":{const s=N(t),n=N(e);if(n===0)throw g.DIV0;return z(s/n)}case"^":{const s=N(t),n=N(e);if(s===0&&n===0)throw g.NUM;if(s===0&&n<0)throw g.DIV0;const i=wt(s,n);if(Number.isNaN(i))throw g.NUM;return z(i)}case"&":return lt(t)+lt(e);case"=":return O(t,e)===0;case"<>":return O(t,e)!==0;case"<":return O(t,e)<0;case">":return O(t,e)>0;case"<=":return O(t,e)<=0;case">=":return O(t,e)>=0;default:throw g.VALUE}}const yt=5e-16;function z(p){if(!Number.isFinite(p))throw g.NUM;return p}function kt(p,t,e){const s=gt(p,t,e);return s==="REF"?g.REF:s==="VALUE"?g.VALUE:new V(p.sheet,s.top,s.left,s.bottom,s.right)}const qt={COUNTIF:[0],COUNTIFS:["even",0],SUMIF:[0,2],SUMIFS:[0,"odd",1],AVERAGEIF:[0,2],AVERAGEIFS:[0,"odd",1],MAXIFS:[0,"odd",1],MINIFS:[0,"odd",1],COUNTBLANK:[0],RANK:[1],"RANK.EQ":[1],"RANK.AVG":[1]};function Vt(p,t){for(let e=0;e<p.length;e++){const s=p[e];if(s===t||s==="odd"&&t>=p[e+1]&&t%2===1||s==="even"&&t>=p[e+1]&&t%2===0)return!0}return!1}function at(p){if(!(p===null||typeof p!="object")){if(Array.isArray(p)){for(const t of p)at(t);return}if(p.t==="call"){const t=qt[String(p.name).replace(/^_xl(?:fn|ws)\./i,"").toUpperCase()];t&&p.args.forEach((e,s)=>{if(e?.t==="array"&&Vt(t,s))throw new Error(`${p.name} takes a range here`)})}for(const t of Object.values(p))t!==null&&typeof t=="object"&&at(t)}}export{Yt as Engine};
|
|
1
|
+
import{resolveStructuredSpec as bt}from"../slicers/structured.js";import{Arr as A,compareValues as $,ERR as g,ERR_BY_INDEX as J,Lambda as wt,num as N,power as Mt,Ref as V,RefArray as st,RefList as O,RichValue as H,str as ot,XlError as C}from"./values.js";import{entityVm as ct,richValueAt as Rt}from"../cells/rich-values.js";import{Compiler as ht}from"./compile.js";import{formulaEntryLimit as At,FormulaSyntaxError as K,Parser as Z,templateKey as Ct,tokenize as tt,toDisplayFormula as xt}from"./parser.js";import{BOOL as W,CHUNK_BITS as T,CHUNK_MASK as x,CONTENT_MASK as X,DIRTY as w,EMPTY as D,EVALUATING as Y,FORMULA as L,KIND_MASK as S,NUM as U,SPILL as j,STR as B,ERR as I}from"../core/sheet.js";import{colName as ut,MAX_COLS as b,MAX_ROWS as v,parseRangeRef as P}from"../core/address.js";import{CellSet as Tt}from"./cell-set.js";import{isRowBelow as Lt}from"./fill-shape.js";import{FUNCS as St}from"./functions/registry.js";import"./functions/index.js";const Et=new Set(["range","rows","cols","rangeOp","intersect","union"]);function ft(p){for(;p.t==="paren";)p=p.e;if(Et.has(p.t))return!0;if(p.t!=="call")return!1;const t=St.get(p.name),e=t?.refResult;return(typeof e=="function"?e(p.args):e===!0)?!0:t?.passes!==void 0&&p.args.some((s,n)=>t.passes(n,p.args.length)&&ft(s))}const nt=Symbol("pending"),dt=200,It=1e6,Nt=4096,Ut=64,it=2147483647,G=4;class rt{constructor(){this.n=0,this.data=new Int32Array(G*8)}push(t,e,s,n){if((this.n+1)*G>this.data.length){const a=new Int32Array(this.data.length*2);a.set(this.data),this.data=a}const i=this.n++*G,r=this.data;r[i]=t,r[i+1]=e,r[i+2]=s,r[i+3]=n}}function Ft(p,t){if(!p.valueMeta.has(t))return;const e=new Map(p.valueMeta);e.delete(t),p.valueMeta=e.size>0?e:null}function pt(p,t,e){if(p.valueMeta?.get(t)===e)return;const s=new Map(p.valueMeta??[]);s.set(t,e),p.valueMeta=s}function z(p,t){let e=p.get(t);return e===void 0&&(e=new Tt,p.set(t,e)),e}class Vt{constructor(){this.buckets=[],this.wide=[],this.all=new rt,this.allCols=[]}}class jt{constructor(t){this.book=t,this.sheetGen=0,this.sheetMap=new Map,this.deps=new Map,this.templates=new Map,this.lastOwn={row:-2,col:-1,text:"",tpl:{cacheKey:void 0}},this.frame=null,this.depth=0,this.legacy=!1,this.pendingSheet=null,this.pendingRow=0,this.pendingCol=0,this.circular=null,this.evalStack=new Int32Array(3*256),this.evalTop=0,this.cycleLow=it,this.iterate=null,this.cycleFound=[],this.cycleMembers=null,this.iterating=!1,this.sliceMs=10,this.syncLimit=4e3,this.externalLinks=null,this.names=new Map,this.nameTemplates=new Map,this.tables=new Map,this.volatile=new Map,this.visibilityReaders=new Map,this.sheetReaders=new Map,this.styleReaders=new Map,this.wakePending=0,this.queue=new Int32Array(4096),this.qHead=0,this.qLen=0,this.sheetsByUid=new Map,this.running=!1,this.timer=0,this.manual=!1,this.graphReady=!0,this.pendingChanges=[],this.waiters=[],this.onChange=null,this.dataTables=[],this.tablesDirty=!1,this.inTables=!1,this.trial=null,this.tablesForced=!1,this.onProgress=null,this.lookupCache=new Map,this.colRevisions=new Map,this.channel=null,this.sheetsChanged()}orderChanged(){this.sheetsChanged(),this.has3D&&this.rebuild()}sheetsChanged(){this.sheetGen++,this.sheetMap.clear(),this.sheetsByUid.clear();for(const t of this.book.sheets)this.sheetMap.set(t.name.toUpperCase(),t),this.sheetsByUid.set(t.uid,t),t.rows.watcher=this,t.cols.watcher=this;this._wakeReaders(this.sheetReaders)}sheetByName(t){return this.sheetMap.get(t.toUpperCase())??null}externalSheet(t,e){return this.externalLinks?.sheet(t,e)??null}sheetsBetween(t,e){const{sheets:s}=this.book,n=s.findIndex(r=>r.name.toUpperCase()===t.toUpperCase()),i=s.findIndex(r=>r.name.toUpperCase()===e.toUpperCase());return n<0||i<0?null:s.slice(Math.min(n,i),Math.max(n,i)+1)}setNames(t){this.names.clear(),this.nameTemplates.clear();for(const e of t){const s=e.localSheetId!==void 0?`${e.localSheetId}!${e.name.toUpperCase()}`:e.name.toUpperCase();this.names.set(s,{text:e.text,name:e.name,hidden:e.hidden,comment:e.comment})}}setTables(t){this.tables.clear();for(const e of t)this.tables.set(e.name.toUpperCase(),e)}template(t,e,s){let n;try{n=tt(t)}catch(a){if(a instanceof K)return this._broken(t);throw a}const i=Ct(n,e,s);let r=this.templates.get(i);if(r===void 0){try{const a=new Z(n,e,s).parse();r=this._compile(a)}catch(a){if(!(a instanceof K))throw a;r=this._broken(t)}r.cacheKey=i,this.templates.set(i,r)}return r}_ownTemplate(t,e,s){const n=this.lastOwn;let i;return n.row===e-1&&n.col===s&&this.templates.get(n.tpl.cacheKey)===n.tpl&&Lt(n.text,t)?i=n.tpl:i=this.template(t,e,s),n.row=e,n.col=s,n.text=t,n.tpl=i,i}_compile(t,e=!1){const s=new ht(this,e);return{fn:s.compileTop(t),refs:s.refs,names:s.names,tables:s.tables,isVolatile:s.isVolatile,readsSheets:s.readsSheets,notInExcel:s.notInExcel===!0,mayArray:s.mayArray,rangeResult:ft(t),external:s.external,keepImportedResult:s.keepImportedResult}}_broken(){return{invalid:!0,fn:()=>g.NAME,refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1,external:!0}}validate(t){const e=At(t);if(e)throw new K(e);lt(new Z(tt(t),0,0).parse())}_templateFor(t,e,s,n){if(n.tpl!==void 0)return n.tpl;let i;return n.t==="dataTable"?i=this._dataTableTemplate():n.f!==void 0&&n.base===void 0?i=this._ownTemplate(n.f,e,s):n.f!==void 0?i=this.template(n.f,Math.floor(n.base/b),n.base%b):n.sf!==void 0?i=this.template(n.sf,Math.floor(n.base/b),n.base%b):i=this._broken(),n.tpl=i,i}_index(t){let e=this.deps.get(t);return e===void 0&&(e=new Vt,this.deps.set(t,e)),e}_addDep(t,e,s,n,i,r,a,l){const o=this._index(t),c=r.uid<<14|l;if(i-s>=Ut){o.all.push(a,c,e,n),o.allCols.push(s,i);return}if(n-e>=Nt){for(let m=s;m<=i;m++){let u=o.wide[m];u===void 0&&(u=new rt,o.wide[m]=u),u.push(a,c,e,n)}return}const f=e>>>T,h=n>>>T;for(let m=s;m<=i;m++){let u=o.buckets[m];u===void 0&&(u=[],o.buckets[m]=u);for(let y=f;y<=h;y++){let _=u[y];_===void 0&&(_=new rt,u[y]=_),_.push(a,c,e,n)}}}register(t,e,s,n){const i=this._templateFor(t,e,s,n);if(i.external||i.keepImportedResult&&!n.typed&&(t.kind(e,s)&S)!==D)return i;for(const r of i.refs)this._addRefDep(r,t,e,s);for(const r of i.names)this._addNameDeps(r,t,e,s);for(const r of i.tables)this._addTableDep(r,t,e,s);return i.readsSheets&&z(this.sheetReaders,t).add(e,s),i.isVolatile&&z(this.volatile,t).add(e,s),i.readsVisibility??=/SUBTOTAL|AGGREGATE|SPARK_/i.test(n.f??n.sf??""),i.readsVisibility&&z(this.visibilityReaders,t).add(e,s),i.readsStyles??=/SPARK_BLOCK/i.test(n.f??n.sf??""),i.readsStyles&&z(this.styleReaders,t).add(e,s),i}_addRefDep(t,e,s,n){const i=t.wrap?(t.rAbs0?t.r0:s+t.r0)%v:t.rAbs0?t.r0:s+t.r0,r=t.wrap?(t.rAbs1?t.r1:s+t.r1)%v:t.rAbs1?t.r1:s+t.r1,a=t.wrap?(t.cAbs0?t.c0:n+t.c0)%b:t.cAbs0?t.c0:n+t.c0,l=t.wrap?(t.cAbs1?t.c1:n+t.c1)%b:t.cAbs1?t.c1:n+t.c1,o=Math.max(0,Math.min(i,r)),c=Math.min(v-1,Math.max(i,r)),f=Math.max(0,Math.min(a,l)),h=Math.min(b-1,Math.max(a,l));if(o>c||f>h)return;if(t.sheet?.sheet2&&(t.sheet.book===null||t.sheet.book===void 0)){this.has3D=!0;for(const u of this.sheetsBetween(t.sheet.sheet,t.sheet.sheet2)??[])this._addDep(u,o,f,c,h,e,s,n);return}if(t.sheet?.book!==null&&t.sheet?.book!==void 0)return;const m=t.sheet?this.sheetByName(t.sheet.sheet):e;m&&this._addDep(m,o,f,c,h,e,s,n)}_addNameDeps(t,e,s,n){const i=this._nameTemplate(t,e);if(i!==null){i.readsSheets&&z(this.sheetReaders,e).add(s,n);for(const r of i.refs)this._addRefDep(r,e,s,n);for(const r of i.tables)this._addTableDep(r,e,s,n);for(const r of i.names)r.toUpperCase()!==t.toUpperCase()&&this._addNameDeps(r,e,s,n)}}_addTableDep(t,e,s,n){const i=this.resolveTable(t.name,t.spec,s,n,e);i instanceof V&&this._addDep(i.sheet,i.r0,i.c0,i.r1,i.c1,e,s,n)}rebuild(){this.has3D=!1,this.deps.clear(),this.volatile.clear(),this.visibilityReaders.clear(),this.styleReaders.clear(),this.sheetReaders.clear(),this.lookupCache.clear(),this.qHead=0,this.qLen=0,this.cycleFound=[],this.cycleMembers=null,this.sheetGen++,this.buildGraph({fullCalc:!0})}buildGraph({fullCalc:t=!1,onDone:e}={}){const s=this.buildGeneration=(this.buildGeneration??0)+1;this.running=!1,this.graphReady=!1,this.dataTables=[],t&&(this.tablesDirty=!0);const n=this,i=this.sheetGen,r=this.book.sheets.map(h=>[h,h.formulas]);let a=0,l=0,o=0,c=0;const f=()=>{if(n.buildGeneration!==s)return;const h=performance.now()+n.sliceMs;let m=0;for(;a<r.length;a++,l=0,o=0,c=0){const[y,_]=r[a],{columns:d}=_;for(;l<d.length;l++,o=0,c=0){const k=d[l];if(k!==void 0)for(;o<k.length;o++,c=0){const M=k[o];if(M===void 0)continue;const{ids:E}=M,R=o<<T;for(;c<=x;c++){const q=E[c];if(q===0)continue;const F=_.infos[q],et=R+c;F.t==="dataTable"&&n.dataTables.push({sheet:y,row:et,col:l,info:F});const gt=n.register(y,et,l,F);if(n._initFormula(y,et,l,F,gt,t),++m%256===0&&performance.now()>h){c++,n.onProgress?.({preparing:!0}),n.buildGeneration===s&&n._later(f);return}}}}}n.graphReady=!0,n.sheetGen!==i&&n._wakeReaders(n.sheetReaders);const u=n.pendingChanges;n.pendingChanges=[];for(const[y,_,d,k]of u)n.cellsChanged(y,_,d,k);n._schedule(),e?.()};f()}_initFormula(t,e,s,n,i,r){const a=t._chunk(e,s);if(a===void 0)return;const l=e&x;n.t==="array"&&n.ref&&this._markArrayChildren(t,e,s,n);const o=a.kinds[l];if(i.external||i.keepImportedResult&&!n.typed&&(o&S)!==D)return;const c=n.ca==="1"||n.ca==="true";(r||c||i.isVolatile||(o&S)===D||i.notInExcel&&(o&S)===I)&&(a.kinds[l]=o|w,this._enqueue(t,e,s))}_markArrayChildren(t,e,s,n){const i=P(n.ref);if(i!==null){t.spills||(t.spills=new Map),t.spills.set(e*b+s,{...i,blocked:!1,fixed:!n.cm});for(let r=i.r0;r<=i.r1;r++)for(let a=i.c0;a<=i.c1;a++){if(r===e&&a===s)continue;const l=t._ensure(r,a);l.kinds[r&x]|=j}}}_enqueue(t,e,s){if(this.qLen+3>this.queue.length)if(this.qHead>this.queue.length>>>1)this.queue.copyWithin(0,this.qHead,this.qLen),this.qLen-=this.qHead,this.qHead=0;else{const n=new Int32Array(this.queue.length*2);n.set(this.queue),this.queue=n}this.queue[this.qLen++]=t.uid,this.queue[this.qLen++]=e,this.queue[this.qLen++]=s}_dirtyFrom(t,e,s,n,i){const r=[t,e,s,n,i];for(;r.length>0;){const a=r.pop(),l=r.pop(),o=r.pop(),c=r.pop(),f=r.pop(),h=this.deps.get(f);if(h===void 0)continue;const m=(_,d)=>{const k=this.sheetsByUid.get(d>>>14);if(k===void 0)return;const M=d&16383,E=k._chunk(_,M);if(E===void 0)return;const R=_&x,q=E.kinds[R];(q&L)===0||(q&w)!==0||(E.kinds[R]=q|w,this._enqueue(k,_,M),r.push(k,M,M,_,_))},u=l>>>T,y=a>>>T;for(let _=c;_<=o;_++){const d=h.buckets[_];if(d!==void 0)for(let M=u;M<=y;M++){const E=d[M];if(E===void 0)continue;const{data:R}=E,q=E.n*G;for(let F=0;F<q;F+=G)a>=R[F+2]&&l<=R[F+3]&&m(R[F],R[F+1])}const k=h.wide[_];if(k!==void 0){const{data:M}=k,E=k.n*G;for(let R=0;R<E;R+=G)a>=M[R+2]&&l<=M[R+3]&&m(M[R],M[R+1])}}if(h.all.n>0){const{data:_}=h.all;for(let d=0;d<h.all.n;d++){const k=d*G;a>=_[k+2]&&l<=_[k+3]&&o>=h.allCols[d*2]&&c<=h.allCols[d*2+1]&&m(_[k],_[k+1])}}}}cellsChanged(t,e,s,n){if(n===0)return;if(t.valueListeners)for(const r of t.valueListeners)for(let a=0;a<n;a++)r(e[a],s[a],e[a],s[a]);if(this.inTables||(this.tablesDirty=!0),!this.graphReady){this.pendingChanges.push([t,e.slice(0,n),s.slice(0,n),n]);return}this.lookupCache.clear();const i=new Map;for(let r=0;r<n;r++){const a=e[r],l=s[r],o=i.get(l);o===void 0?i.set(l,[a,a]):(a<o[0]&&(o[0]=a),a>o[1]&&(o[1]=a));const c=t._chunk(a,l);if(c===void 0)continue;const f=a&x,h=c.kinds[f];if(h&L){const m=t.formula(a,l);m&&(this.register(t,a,l,m),h&w||(c.kinds[f]=h|w,this._enqueue(t,a,l)))}t.spills&&this._spillTouched(t,a,l)}for(const[r,a]of i)this._dirtyFrom(t,r,r,a[0],a[1]);this._markVolatile(),this._schedule()}_spillTouched(t,e,s){const n=e*b+s;for(const[i,r]of t.spills){const a=Math.floor(i/b),l=i-a*b;if(i===n){(t.kind(a,l)&L)===0&&(this._clearSpill(t,r,a,l),t.spills.delete(i));continue}if(e>=r.r0&&e<=r.r1&&s>=r.c0&&s<=r.c1){const o=t._chunk(a,l);if(o===void 0)continue;const c=a&x,f=o.kinds[c];f&L&&!(f&w)&&(o.kinds[c]=f|w,this._enqueue(t,a,l),this._dirtyFrom(t,l,l,a,a))}}}_markVolatile(){for(const[t,e]of this.volatile)e.forEach((s,n)=>{const i=t._chunk(s,n);if(i===void 0)return;const r=s&x,a=i.kinds[r];if(!(a&L)){e.delete(s,n);return}a&w||(i.kinds[r]=a|w,this._enqueue(t,s,n),this._dirtyFrom(t,n,n,s,s))})}get pending(){return(this.qLen-this.qHead)/3}_later(t){if(this._next=t,typeof MessageChannel>"u"){setTimeout(()=>this._tick(),0);return}this.channel===null&&(this.channel=new MessageChannel,this.channel.port1.onmessage=()=>this._tick()),this.channel.port2.postMessage(0)}_tick(){const t=this._next;this._next=null,t?.(),this._next===null&&this.channel!==null&&(this.channel.port1.close(),this.channel=null)}_schedule(){if(this.manual&&!this.tablesForced||this.inTables||this.running||!this.graphReady)return;if(this.pending===0){this._finish();return}const t=this.pending,e=this.buildGeneration;if(t<=this.syncLimit){if(this._slice(this.syncLimit===1/0?1/0:this.sliceMs),this.buildGeneration!==e)return;if(this.pending===0){this._finish();return}}this.running=!0,this._total=t;const s=()=>{this.buildGeneration===e&&(this._slice(this.sliceMs),this.buildGeneration===e&&(this.pending>0?(this.onProgress?.({remaining:this.pending,total:Math.max(this._total,this.pending)}),this.buildGeneration===e&&this._later(s)):(this.running=!1,this._finish())))};this._later(s)}_slice(t){const e=t!==1/0;let s=e?performance.now():0;const n=s+t;let i=1,r=1;for(;this.qHead<this.qLen;){const a=this.queue[this.qHead++],l=this.queue[this.qHead++],o=this.queue[this.qHead++],c=this.sheetsByUid.get(a);if(c!==void 0&&(this._run(c,l,o),e&&--r===0)){const f=performance.now();if(f>n)break;i=f-s<.5?Math.min(i*2,16):1,r=i,s=f}}this.qHead>=this.qLen&&(this.qHead=0,this.qLen=0)}_finish(){for(;this.cycleFound.length>0;)this._iterateCycles();const t=this.tablesForced;this.tablesForced=!1,this.tablesDirty&&this.dataTables.length>0&&(!this.skipTables||t)&&(this.tablesDirty=!1,this._computeDataTables()),this.book.formatValueRevision=(this.book.formatValueRevision??0)+1,this.onChange?.();const e=this.waiters;this.waiters=[];for(const s of e)s()}_dataTableTemplate(){const t=this;return{fn:(s,n,i)=>t._plainValue(i,s,n),refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1}}_plainValue(t,e,s){const n=t.value(e,s);switch(t.kind(e,s)&S){case U:return n;case B:return this.book.strings.get(n);case W:return n!==0;case I:return J[n];default:return null}}_writePlain(t,e,s,n){const i=t.kind(e,s)&L;n==null?t.setCell(e,s,i|U,0):typeof n=="number"?Number.isFinite(n)?t.setCell(e,s,i|U,n):t.setCell(e,s,i|I,g.NUM.index):typeof n=="boolean"?t.setCell(e,s,i|W,n?1:0):n instanceof C?t.setCell(e,s,i|I,n.index):t.setCell(e,s,i|B,this.book.strings.add(String(n)))}_setInputs(t,e){const s=new Uint32Array(e.length),n=new Uint32Array(e.length);e.forEach((i,r)=>{t.setCell(i.row,i.col,i.kind,i.value),s[r]=i.row,n[r]=i.col}),this.cellsChanged(t,s,n,e.length),this._slice(1/0)}evaluateWith(t,e,s){const n=e.map(({row:a,col:l})=>({row:a,col:l,kind:t.kind(a,l)&(S|L),value:t.value(a,l)})),i=this.inTables,r=this.trial;this.inTables=!0,this.trial??=new Map;try{return this._setInputs(t,e.map(({row:a,col:l,text:o})=>{const c=Number(o);return o!==""&&Number.isFinite(c)?{row:a,col:l,kind:U,value:c}:{row:a,col:l,kind:B,value:this.book.strings.add(String(o))}})),s()}finally{this._setInputs(t,n),this.inTables=i,this.trial=r}}_computeDataTables(){this.inTables=!0;const t=this.dataTables.filter(e=>e.sheet.formula(e.row,e.col)===e.info&&this.book.sheets.includes(e.sheet));this.dataTables=t;try{for(const e of t)this._computeDataTable(e)}finally{this.inTables=!1}}_computeDataTable({sheet:t,info:e}){const s=P(e.ref);if(!s)return;const n=P(e.r1??""),i=e.r2?P(e.r2):null,r=e.dt2D==="1"||e.dt2D==="true",a=e.dtr==="1"||e.dtr==="true",l=e.del1==="1"||e.del1==="true"||r&&(e.del2==="1"||e.del2==="true");if(!l&&(!n||r&&!i))return;const o=(d,k)=>({kind:t.kind(d,k)&S,value:t.value(d,k)}),f=(l?[]:[n,i].filter(Boolean)).map(d=>({row:d.r0,col:d.c0,kind:t.kind(d.r0,d.c0)&(S|L),value:t.value(d.r0,d.c0)})),h=[];this.trial=new Map;const m=(d,k,M,E)=>{const R=this.read(t,M,E);h.push(d,k,R instanceof A?R.data[0]:R)};try{if(l)for(let d=s.r0;d<=s.r1;d++)for(let k=s.c0;k<=s.c1;k++)h.push(d,k,g.REF);else if(r)for(let d=s.r0;d<=s.r1;d++)for(let k=s.c0;k<=s.c1;k++)this._setInputs(t,[{row:n.r0,col:n.c0,...o(s.r0-1,k)},{row:i.r0,col:i.c0,...o(d,s.c0-1)}]),m(d,k,s.r0-1,s.c0-1);else if(a)for(let d=s.c0;d<=s.c1;d++){this._setInputs(t,[{row:n.r0,col:n.c0,...o(s.r0-1,d)}]);for(let k=s.r0;k<=s.r1;k++)m(k,d,k,s.c0-1)}else for(let d=s.r0;d<=s.r1;d++){this._setInputs(t,[{row:n.r0,col:n.c0,...o(d,s.c0-1)}]);for(let k=s.c0;k<=s.c1;k++)m(d,k,s.r0-1,k)}}finally{f.length>0&&this._setInputs(t,f),this.trial=null}const u=h.length/3,y=new Uint32Array(u),_=new Uint32Array(u);for(let d=0;d<u;d++)y[d]=h[d*3],_[d]=h[d*3+1],this._writePlain(t,y[d],_[d],h[d*3+2]);this.cellsChanged(t,y,_,u),this._slice(1/0),t.revision++}dataTableAt(t,e,s){for(const n of this.dataTables){if(n.sheet!==t)continue;const i=P(n.info.ref);if(i&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1)return n}return null}calculateNow(){const{manual:t,skipTables:e}=this;this.manual=!1,this.skipTables=!1,this.tablesDirty=!0,this.tablesForced=!0,this._markVolatile(),this._markCycles(),this._schedule(),this.manual=t,this.skipTables=e}whenIdle(){return this.pending===0&&this.graphReady&&!this.running?Promise.resolve():new Promise(t=>{this.waiters.push(t),this._schedule()})}_iterateCycles(){const t=this.cycleFound;this.cycleFound=[];const e=new Map,s=(a,l,o)=>{let c=e.get(a.uid);c===void 0&&(c=new Map,e.set(a.uid,c)),c.set(l*b+o,[a,l,o])};for(let a=0;a<t.length;a+=3)s(t[a],t[a+1],t[a+2]);const n=[];for(const a of this.book.sheets){const l=e.get(a.uid);l&&n.push(...[...l.keys()].sort((o,c)=>o-c).map(o=>l.get(o)))}this.cycleMembers??=new Map;for(const a of n)this.cycleMembers.set(`${a[0].uid}:${a[1]}:${a[2]}`,a);const{count:i,delta:r}=this.iterate;for(let a=1;a<=i;a++){let l=0;for(const[o,c,f]of n){const h=o._chunk(c,f);if(h===void 0)continue;const m=c&x;if(!(h.kinds[m]&L))continue;const u=h.values[m];h.kinds[m]|=w,this.iterating=!0,this._run(o,c,f),this.iterating=!1;const y=Math.abs(h.values[m]-u);y>l&&(l=y)}if(this.onProgress?.({iteration:a,iterations:i}),l<r)break}for(const[a,l,o]of n)this._dirtyFrom(a,o,o,l,l);for(const[a,l,o]of n){const c=a._chunk(l,o);c!==void 0&&(c.kinds[l&x]&=~w)}this._slice(1/0)}_markCycles(){if(!(this.iterate===null||this.cycleMembers===null))for(const[t,e,s]of this.cycleMembers.values()){const n=t._chunk(e,s);n===void 0||!(n.kinds[e&x]&L)||(n.kinds[e&x]|=w,this._enqueue(t,e,s))}}_run(t,e,s){const n=[t,e,s];for(;n.length>0;){const i=n[n.length-1],r=n[n.length-2],a=n[n.length-3];try{this.depth=0,this.evalTop=0,this.cycleLow=it,this._calc(a,r,i),n.length-=3}catch(l){if(l!==nt)throw l;n.push(this.pendingSheet,this.pendingRow,this.pendingCol)}}}_calc(t,e,s){const n=t._chunk(e,s);if(n===void 0)return;const i=e&x,r=n.kinds[i];if(!(r&w))return;if(r&Y){this.circular={sheet:t,row:e,col:s},this.iterating||this._cycleHit(t.uid,e,s);return}if(this.depth>=dt)throw this.pendingSheet=t,this.pendingRow=e,this.pendingCol=s,nt;const a=t.formula(e,s);if(a===void 0||!(r&L)){n.kinds[i]=r&~w;return}const l=this._templateFor(t,e,s,a);if(l.external||l.keepImportedResult&&!a.typed&&(r&S)!==D){n.kinds[i]=r&~w;return}n.kinds[i]=r|Y;const o=this.evalTop;o+3>this.evalStack.length&&this._growEvalStack(),this.evalStack[o]=t.uid,this.evalStack[o+1]=e,this.evalStack[o+2]=s,this.evalTop=o+3;const c=this.cycleLow;this.cycleLow=it;const f=this.legacy,h=this.frame,m=a.typed!==!0&&a.t!=="array";this.legacy=m,this.depth++;let u;try{u=l.fn(e,s,t),(u instanceof V||u instanceof O)&&(u=this.refAuto(u,e,s)),u instanceof st&&(u=this.toArr(u))}catch(_){if(n.kinds[i]&=~Y,this.depth--,this.legacy=f,this.frame=h,this.evalTop=o,this.cycleLow=c,_===nt)throw _;_ instanceof C?u=_:(console.error("Formula evaluation failed",_),u=g.VALUE),this._store(t,n,i,e,s,u,a,m);return}this.depth--,this.legacy=f,this.frame=h,this.evalTop=o;const y=this.cycleLow;if(this.cycleLow=y<o&&y<c?y:c,y<=o){if(this.iterate!==null){n.kinds[i]=r&~(w|Y),this.cycleFound.push(t,e,s);return}if((r&S)!==D&&this._keepsInCycle(t,e,s,a)){n.kinds[i]=r&~(w|Y),this._dropTrialValue(t,n,i,e,s);return}u=0}this._store(t,n,i,e,s,u,a,m)}_keepsInCycle(t,e,s,n){return n.typed===void 0?!0:this.book.collab===void 0&&!t.spills?.has(e*b+s)}_dropTrialValue(t,e,s,n,i){const r=this.trial?.get(t)?.get(n*b+i);if(!(r===void 0||!((e.kinds[s]&X)!==r[0]||e.values[s]!==r[1]))&&(e.kinds[s]=r[0],e.values[s]=r[1],t.valueListeners))for(const l of t.valueListeners)l(n,i,n,i)}_saveTrialValue(t,e,s,n,i){let r=this.trial.get(t);r===void 0&&(r=new Map,this.trial.set(t,r));const a=n*b+i;if(r.has(a))return;const l=e.kinds[s]&X;r.set(a,(l&S)===D?[L|U,0]:[l,e.values[s]])}_cycleHit(t,e,s){const n=this.evalStack;for(let i=this.evalTop-3;i>=0;i-=3)if(n[i]===t&&n[i+1]===e&&n[i+2]===s){i<this.cycleLow&&(this.cycleLow=i);return}}_growEvalStack(){const t=new Int32Array(this.evalStack.length*2);t.set(this.evalStack),this.evalStack=t}_store(t,e,s,n,i,r,a,l){let o=r;o instanceof wt&&(o=g.CALC),o instanceof A?a.t==="array"&&!a.cm&&a.ref?o=this._fillFixedArray(t,n,i,a,o):l||o.spillRows===1&&o.spillCols===1?(o=o.data[0],t.spills&&this._releaseSpill(t,n,i)):o=this._spill(t,n,i,a,o):t.spills&&!(a.t==="array"&&!a.cm)&&this._releaseSpill(t,n,i),a.t==="array"&&!a.cm&&a.ref&&!(r instanceof A)&&(o=this._fillFixedArray(t,n,i,a,A.filled(1,1,o)));let c=L,f=0;if(typeof o=="number"?Number.isFinite(o)?(c|=U,f=o):(c|=I,f=g.NUM.index):typeof o=="string"?(c|=B,f=this.book.strings.add(o)):typeof o=="boolean"?(c|=W,f=o?1:0):o instanceof C?(c|=I,f=o.index):o instanceof H?(c|=I,f=g.VALUE.index):c|=U,o instanceof H?pt(t,n*b+i,ct(this.book,o.index)):t.valueMeta!==null&&((e.kinds[s]&X)!==c||e.values[s]!==f)&&!/IMAGE\(/i.test(a.f??a.sf??"")&&Ft(t,n*b+i),t.valueListeners&&((e.kinds[s]&X)!==c||e.values[s]!==f))for(const h of t.valueListeners)h(n,i,n,i);this.trial!==null&&this.iterate===null&&this._saveTrialValue(t,e,s,n,i),e.kinds[s]=c,e.values[s]=f,n>t.maxRow&&(t.maxRow=n),i>t.maxCol&&(t.maxCol=i)}_writeArrayCell(t,e,s,n){let i=j,r=0;typeof n=="number"?(i|=Number.isFinite(n)?U:I,r=Number.isFinite(n)?n:g.NUM.index):typeof n=="string"?(i|=B,r=this.book.strings.add(n)):typeof n=="boolean"?(i|=W,r=n?1:0):n instanceof C?(i|=I,r=n.index):n==null?i|=U:(i|=I,r=g.VALUE.index,n instanceof H&&pt(t,e*b+s,ct(this.book,n.index))),t.setCell(e,s,i,r)}_fillFixedArray(t,e,s,n,i){const r=P(n.ref);if(r===null)return i.data[0];t.spills||(t.spills=new Map),t.spills.set(e*b+s,{...r,blocked:!1,fixed:!0});const a=(o,c)=>{const f=i.rows===1?0:o,h=i.cols===1?0:c;return f>=i.rows||h>=i.cols?g.NA:i.get(f,h)};for(let o=r.r0;o<=r.r1;o++)for(let c=r.c0;c<=r.c1;c++)o===e&&c===s||this._writeArrayCell(t,o,c,a(o-r.r0,c-r.c0));(r.r0!==r.r1||r.c0!==r.c1)&&this._dirtyFrom(t,r.c0,r.c1,r.r0,r.r1);const l=a(e-r.r0,s-r.c0);return l===null?0:l}_spill(t,e,s,n,i){const r=e*b+s;t.spills||(t.spills=new Map);const a=t.spills.get(r),l=e+i.rows-1,o=s+i.cols-1,c={r0:e,c0:s,r1:l,c1:o,blocked:!1,fixed:!1},f=(u,y)=>a&&u>=a.r0&&u<=a.r1&&y>=a.c0&&y<=a.c1;let h=e+i.spillRows>v||s+i.spillCols>b;if(!h)t:for(let u=e;u<=l;u++)for(let y=s;y<=o;y++){if(u===e&&y===s)continue;const _=t.kind(u,y);if((_&X)!==0&&!(_&j&&f(u,y))){h=!0;break t}if(t.merges.length>0&&t.mergeAt(u,y)){h=!0;break t}}if(h)return a&&!a.blocked&&this._clearSpill(t,a,e,s),c.blocked=!0,c.r1=Math.min(l,v-1),c.c1=Math.min(o,b-1),t.spills.set(r,c),g.SPILL;if(a&&!a.blocked){for(let u=a.r0;u<=a.r1;u++)for(let y=a.c0;y<=a.c1;y++)u>=c.r0&&u<=c.r1&&y>=c.c0&&y<=c.c1||(t.kind(u,y)&j)!==0&&t.setCell(u,y,D,0);this._dirtyFrom(t,a.c0,a.c1,a.r0,a.r1)}t.spills.set(r,c);for(let u=e;u<=l;u++)for(let y=s;y<=o;y++)u===e&&y===s||this._writeArrayCell(t,u,y,i.get(u-e,y-s));n.t="array",n.ref=`${mt(s)}${e+1}:${mt(o)}${l+1}`,n.cm=1,delete n.raw,this._dirtyFrom(t,s,o,e,l);const m=i.data[0];return m===null?0:m}_clearSpill(t,e,s,n){for(let i=e.r0;i<=e.r1;i++)for(let r=e.c0;r<=e.c1;r++)i===s&&r===n||(t.kind(i,r)&j)!==0&&t.setCell(i,r,D,0);this._dirtyFrom(t,e.c0,e.c1,e.r0,e.r1)}_releaseSpill(t,e,s){const n=e*b+s,i=t.spills.get(n);if(i===void 0)return;i.blocked||this._clearSpill(t,i,e,s),t.spills.delete(n);const r=t.formula(e,s);r&&r.typed&&(delete r.ref,delete r.cm,delete r.t)}spillMaster(t,e,s){if(!t.spills)return null;for(const[n,i]of t.spills)if(!i.blocked&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1){const r=Math.floor(n/b);return{row:r,col:n-r*b,rect:i}}return null}spillRange(t){const{sheet:e,r0:s,c0:n}=t;this.read(e,s,n);const i=e.spills?.get(s*b+n);return!i||i.blocked?g.REF:new V(e,i.r0,i.c0,i.r1,i.c1)}read(t,e,s){const n=t.columns[s];if(n===void 0)return null;const i=n[e>>>T];if(i===void 0)return null;const r=e&x;let a=i.kinds[r];if(a===0)return null;switch(a&w&&(this._calc(t,e,s),a=i.kinds[r]),a&S){case U:return i.values[r];case B:return this.book.strings.get(i.values[r]);case W:return i.values[r]!==0;case I:{if(t.valueMeta!==null&&this.book.richValues){const l=Rt(this.book,t,e,s);if(l!==null)return l}return J[i.values[r]]??g.NA}default:return null}}refToValue(t){return t instanceof O?t.refs.length===1?this.refToValue(t.refs[0]):g.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.toArr(t)}refAuto(t,e,s){return t instanceof O?t.refs.length===1?this.refAuto(t.refs[0],e,s):g.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.legacy?this.intersect(t,e,s):this.toArr(t)}intersect(t,e,s){return t.cols===1&&e>=t.r0&&e<=t.r1?this.read(t.sheet,e,t.c0):t.rows===1&&s>=t.c0&&s<=t.c1?this.read(t.sheet,t.r0,s):g.VALUE}trim(t){const{sheet:e}=t;return{r0:t.r0,c0:t.c0,r1:Math.min(t.r1,Math.max(e.maxRow,t.r0)),c1:Math.min(t.c1,Math.max(e.maxCol,t.c0))}}toArr(t){if(t instanceof st)return new A(t.rows,t.cols,t.data.map(e=>e instanceof V?this.read(e.sheet,e.r0,e.c0):e));if(t instanceof A)return t;if(t instanceof V){const e=t.rows===v||t.cols===b,{r0:s,c0:n,r1:i,c1:r}=e||t.rows*t.cols>It?this.trim(t):t,a=i-s+1,l=r-n+1,o=new Array(a*l);let c=0;for(let f=s;f<=i;f++)for(let h=n;h<=r;h++)o[c++]=this.read(t.sheet,f,h);return new A(a,l,o,t.rows===v?v:a,t.cols===b?b:l)}if(t instanceof O){if(t.refs.length===1)return this.toArr(t.refs[0]);throw g.VALUE}if(t instanceof C)throw t;return new A(1,1,[t])}scalar(t,e,s){return t instanceof V?t.isCell?this.read(t.sheet,t.r0,t.c0):this.intersect(t,e,s):t instanceof O?g.VALUE:t instanceof st?this.scalar(t.data[0],e,s):t instanceof A?t.data[0]:t}scan(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);for(let r=t.c0;r<=n;r++){const a=s.columns[r];if(a!==void 0)for(let l=t.r0>>>T;l<=i>>>T;l++){const o=a[l];if(o===void 0)continue;const c=l<<T,f=Math.max(t.r0-c,0),h=Math.min(i-c,x),{kinds:m}=o;for(let u=f;u<=h;u++){if(m[u]===0)continue;const y=this.read(s,c+u,r);y!==null&&e(y,c+u,r)}}}}sumRange(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);let{sum:r,count:a}=e;for(let l=t.c0;l<=n;l++){const o=s.columns[l];if(o!==void 0)for(let c=t.r0>>>T;c<=i>>>T;c++){const f=o[c];if(f===void 0)continue;const h=c<<T,m=Math.max(t.r0-h,0),u=Math.min(i-h,x),{kinds:y,values:_}=f;for(let d=m;d<=u;d++){let k=y[d];if(k===0)continue;k&w&&(this._calc(s,h+d,l),k=y[d]);const M=k&S;if(M===U)r+=_[d],a++;else if(M===I)throw J[_[d]]}}}e.sum=r,e.count=a}averageRange(t,e){if(t.cols===1)return this.sumRange(t,e);const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow),r=[],a=[];for(let l=t.r0>>>T;l<=i>>>T;l++){r.length=0,a.length=0;for(let h=t.c0;h<=n;h++){const m=s.columns[h]?.[l];m!==void 0&&(r.push(h),a.push(m))}if(a.length===0)continue;const o=l<<T,c=Math.max(t.r0-o,0),f=Math.min(i-o,x);for(let h=c;h<=f;h++)for(let m=0;m<a.length;m++){const{kinds:u,values:y}=a[m];u[h]&w&&this._calc(s,o+h,r[m]);const _=u[h]&S;if(_===U)e.sum+=y[h],e.count++;else if(_===I)throw J[y[h]]}}}unary(t,e){if(t instanceof C)return t;if(t instanceof A)return new A(t.rows,t.cols,t.data.map(s=>{try{return s instanceof C?s:e(N(s))}catch(n){return n}}),t.spillRows,t.spillCols);try{return e(N(t))}catch(s){if(s instanceof C)return s;throw s}}slowBin(t,e,s){if(e instanceof A||s instanceof A)return this._binArr(t,e,s);if(e instanceof C)return e;if(s instanceof C)return s;try{return yt(t,e,s)}catch(n){if(n instanceof C)return n;throw n}}_binArr(t,e,s){const n=e instanceof A?e:null,i=s instanceof A?s:null,r=Math.max(n?n.rows:1,i?i.rows:1),a=Math.max(n?n.cols:1,i?i.cols:1),l=new Array(r*a);for(let o=0;o<r;o++)for(let c=0;c<a;c++){const f=at(e,o,c),h=at(s,o,c);let m;if(f instanceof C)m=f;else if(h instanceof C)m=h;else try{m=yt(t,f,h)}catch(u){m=u}l[o*a+c]=m}return new A(r,a,l,Math.max(n?.spillRows??1,i?.spillRows??1),Math.max(n?.spillCols??1,i?.spillCols??1))}liftArr(t,e,s){let n=1,i=1,r=1,a=1;for(const f of e)f instanceof A&&(f.rows>n&&(n=f.rows),f.cols>i&&(i=f.cols),f.spillRows>r&&(r=f.spillRows),f.spillCols>a&&(a=f.spillCols));const l=new Array(n*i),o=e.length,c=new Array(o);for(let f=0;f<n;f++)for(let h=0;h<i;h++){let m=null;for(let u=0;u<o;u++){const y=at(e[u],f,h);c[u]=y,!s&&m===null&&y instanceof C&&(m=y)}if(m!==null){l[f*i+h]=m;continue}try{l[f*i+h]=t(...c)}catch(u){if(u instanceof C)l[f*i+h]=u;else throw u}}return new A(n,i,l,r,a)}invoke(t,e,s,n,i){if(t.native)return this._invokeNative(t.native,e,s,n,i);const r=t.frame?t.frame.slice():[],{params:a}=t;if(e.length>a.length)return g.VALUE;for(let o=0;o<a.length;o++)r[a[o]]=o<e.length?e[o]:void 0;const l=this.frame;if(this.frame=r,this.depth++,this.depth>=dt*4)return this.depth--,this.frame=l,g.NUM;try{return t.body(s,n,i)}finally{this.depth--,this.frame=l}}_invokeNative(t,e,s,n,i){if(e.length<t.min||e.length>t.max)return g.VALUE;try{if(t.kind==="raw")return t.fn(this,e,s,n,i);if(t.kind==="lazy")return t.fn(this,e.map(l=>()=>l),s,n,i);const r=t.dateSystem?(...l)=>t.fn(this.book.dateOffset,...l):t.fn,a=e.map(l=>l instanceof V||l instanceof O?this.refToValue(l):l);if(a.some(l=>l instanceof A))return this.liftArr(r,a,t.errors);if(!t.errors){for(const l of a)if(l instanceof C)return l}return r(...a)}catch(r){if(r instanceof C)return r;throw r}}_nameEntry(t,e){const s=t.toUpperCase();if(e){const i=this.book.sheets.indexOf(e),r=this.names.get(`${i}!${s}`);if(r)return{key:`${i}!${s}`,entry:r}}const n=this.names.get(s);return n?{key:s,entry:n}:null}_nameTemplate(t,e){const s=this._nameEntry(t,e);if(s===null)return null;let n=this.nameTemplates.get(s.key);if(n===void 0){try{n=this._compile(new Z(tt(s.entry.text,!0),0,0).parse(!0),!0)}catch(i){if(!(i instanceof K))throw i;n=this._broken()}this.nameTemplates.set(s.key,n)}return n}nameMayYieldRange(t){const e=t.toUpperCase(),s=[];for(const[n,i]of this.names)(n===e||n.endsWith(`!${e}`))&&s.push(i);if(s.length===0||(this._rangeNames??=new Set,this._rangeNames.has(e)))return!0;this._rangeNames.add(e);try{return s.some(n=>{try{return new ht(this).mayYieldRange(new Z(tt(n.text,!0),0,0).parse(!0))}catch(i){if(i instanceof K)return!1;throw i}})}finally{this._rangeNames.delete(e)}}evalName(t,e,s,n){const i=this._nameTemplate(t,n);return i===null?g.NAME:i.fn(e,s,n)}tableSpecToA1(t,e,s){const n=_t(t,e,s);if(!(n instanceof V))return null;const i=/#This Row|^\[\s*@/i.test(e),r=(a,l)=>i?`${ut(l)}${a+1}`:`$${ut(l)}$${a+1}`;return n.isCell?r(n.r0,n.c0):`${r(n.r0,n.c0)}:${r(n.r1,n.c1)}`}resolveTable(t,e,s,n,i){let r=t?this.tables.get(t.toUpperCase()):null;if(!t){for(const a of this.tables.values())if(a.sheet===i&&s>=a.r0&&s<=a.r1&&n>=a.c0&&n<=a.c1){r=a;break}}return r?_t(r,e,s):g.REF}exactIndex(t){const e=`${t.sheet.uid}:${t.r0}:${t.c0}:${t.r1}:${t.c1}`;let s=this.lookupCache.get(e);if(s!==void 0)return s;s=new Map;const n=t.cols===1;return this.scan(t,(i,r,a)=>{const l=typeof i=="string"?`s${i.toLowerCase()}`:typeof i=="number"?i:`b${i}`;if(i instanceof C)return;const o=n?r-t.r0:a-t.c0,c=s.get(l);(c===void 0||o<c)&&s.set(l,o)}),this.lookupCache.set(e,s),s}visibilityChanged(){this._wakeReaders(this.visibilityReaders)}presentationChanged(){this._wakeLater(2)}axisHiddenChanged(){this._wakeLater(1)}axisResized(){this._wakeLater(2)}_wakeLater(t){(t===1?this.visibilityReaders:this.styleReaders).size!==0&&(this.wakePending===0&&queueMicrotask(()=>{const e=this.wakePending;this.wakePending=0,e&1&&this._wakeReaders(this.visibilityReaders),e&2&&this._wakeReaders(this.styleReaders)}),this.wakePending|=t)}_wakeReaders(t){if(!this.graphReady||t.size===0)return;let e=!1;for(const[s,n]of t)n.forEach((i,r)=>{const a=s._chunk(i,r);if(a===void 0)return;const l=i&x,o=a.kinds[l];if(!(o&L)){n.delete(i,r);return}o&w||(a.kinds[l]=o|w,this._enqueue(s,i,r)),this._dirtyFrom(s,r,r,i,i),e=!0});e&&this._schedule()}isSubtotalCell(t,e,s){if((t.kind(e,s)&L)===0)return!1;const n=t.formula(e,s),i=n?.f??n?.sf??"";return/^\s*(_xlfn\.)?(SUBTOTAL|AGGREGATE)\(/i.test(i)}displayFormula(t){return xt(t)}}function mt(p){let t="";for(let e=p+1;e>0;e=Math.floor((e-1)/26))t=String.fromCharCode(65+(e-1)%26)+t;return t}function at(p,t,e){if(!(p instanceof A))return p;const s=p.rows===1?0:t,n=p.cols===1?0:e;return s>=p.rows||n>=p.cols?g.NA:p.data[s*p.cols+n]}function yt(p,t,e){if((t instanceof H||e instanceof H)&&p!=="="&&p!=="<>"&&p!=="&")throw g.VALUE;switch(p){case"+":{const s=N(t),n=s+N(e);return Math.abs(n)<Math.abs(s)*kt?0:Q(n)}case"-":{const s=N(t),n=s-N(e);return Math.abs(n)<Math.abs(s)*kt?0:Q(n)}case"*":return Q(N(t)*N(e));case"/":{const s=N(t),n=N(e);if(n===0)throw g.DIV0;return Q(s/n)}case"^":{const s=N(t),n=N(e);if(s===0&&n===0)throw g.NUM;if(s===0&&n<0)throw g.DIV0;const i=Mt(s,n);if(Number.isNaN(i))throw g.NUM;return Q(i)}case"&":return ot(t)+ot(e);case"=":return $(t,e)===0;case"<>":return $(t,e)!==0;case"<":return $(t,e)<0;case">":return $(t,e)>0;case"<=":return $(t,e)<=0;case">=":return $(t,e)>=0;default:throw g.VALUE}}const kt=5e-16;function Q(p){if(!Number.isFinite(p))throw g.NUM;return p}function _t(p,t,e){const s=bt(p,t,e);return s==="REF"?g.REF:s==="VALUE"?g.VALUE:new V(p.sheet,s.top,s.left,s.bottom,s.right)}const qt={COUNTIF:[0],COUNTIFS:["even",0],SUMIF:[0,2],SUMIFS:[0,"odd",1],AVERAGEIF:[0,2],AVERAGEIFS:[0,"odd",1],MAXIFS:[0,"odd",1],MINIFS:[0,"odd",1],COUNTBLANK:[0],RANK:[1],"RANK.EQ":[1],"RANK.AVG":[1]};function Dt(p,t){for(let e=0;e<p.length;e++){const s=p[e];if(s===t||s==="odd"&&t>=p[e+1]&&t%2===1||s==="even"&&t>=p[e+1]&&t%2===0)return!0}return!1}function lt(p){if(!(p===null||typeof p!="object")){if(Array.isArray(p)){for(const t of p)lt(t);return}if(p.t==="call"){const t=qt[String(p.name).replace(/^_xl(?:fn|ws)\./i,"").toUpperCase()];t&&p.args.forEach((e,s)=>{if(e?.t==="array"&&Dt(t,s))throw new Error(`${p.name} takes a range here`)})}for(const t of Object.values(p))t!==null&&typeof t=="object"&<(t)}}export{jt as Engine};
|
package/calc/functions/info.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setCategory as D}from"./registry.js";import{lift as l,raw as m}from"./registry.js";import{Arr as S,ERR as o,Lambda as w,num as p,OMITTED as d,Ref as i,RefList as E,RichValue as N,XlError as y}from"../values.js";import{CONTENT_MASK as I,FORMULA as R}from"../../core/sheet.js";import{cellRef as b,colName as g,sheetPrefix as k}from"../../core/address.js";import{newBookName as T}from"../../core/default-names.js";import{str as L}from"../values.js";D("Information");const s=(e,t)=>l(e,1,1,t,{errors:!0});s("ISERROR",e=>e instanceof y),s("ISERR",e=>e instanceof y&&e!==o.NA),s("ISNA",e=>e===o.NA),s("ISNUMBER",e=>typeof e=="number"),s("ISTEXT",e=>typeof e=="string"),s("ISNONTEXT",e=>typeof e!="string"),s("ISLOGICAL",e=>typeof e=="boolean"),s("ISBLANK",e=>e==null),l("ISEVEN",1,1,e=>Math.trunc(p(e))%2===0),l("ISODD",1,1,e=>Math.trunc(p(e))%2!==0),m("ISREF",1,1,(e,t)=>t[0]instanceof i||t[0]instanceof E),m("ISFORMULA",1,1,(e,t)=>{const r=t[0];if(!(r instanceof i))throw o.VALUE;return(r.sheet.kind(r.r0,r.c0)&R)!==0}),l("N",1,1,e=>{if(typeof e=="number")return e;if(typeof e=="boolean")return e?1:0;if(e instanceof N)throw o.VALUE;return 0}),l("NA",0,0,()=>o.NA),s("ERROR.TYPE",e=>{if(!(e instanceof y))throw o.NA;return{"#NULL!":1,"#DIV/0!":2,"#VALUE!":3,"#REF!":4,"#NAME?":5,"#NUM!":6,"#N/A":7,"#GETTING_DATA":8,"#SPILL!":9,"#FIELD!":13,"#CALC!":14}[e.code]}),m("TYPE",1,1,(e,t)=>{const r=t[0]instanceof i&&t[0].isCell?e.read(t[0].sheet,t[0].r0,t[0].c0):t[0];return r instanceof i||r instanceof E||r instanceof S?64:r===null||typeof r=="number"?1:typeof r=="string"?2:typeof r=="boolean"?4:r instanceof y?16:r instanceof w||r instanceof N?128:1}),m("SHEET",0,1,(e,t,r,f,
|
|
1
|
+
import{setCategory as D}from"./registry.js";import{lift as l,raw as m}from"./registry.js";import{Arr as S,ERR as o,Lambda as w,num as p,OMITTED as d,Ref as i,RefList as E,RichValue as N,XlError as y}from"../values.js";import{CONTENT_MASK as I,FORMULA as R}from"../../core/sheet.js";import{cellRef as b,colName as g,sheetPrefix as k}from"../../core/address.js";import{newBookName as T}from"../../core/default-names.js";import{str as L}from"../values.js";D("Information");const s=(e,t)=>l(e,1,1,t,{errors:!0});s("ISERROR",e=>e instanceof y),s("ISERR",e=>e instanceof y&&e!==o.NA),s("ISNA",e=>e===o.NA),s("ISNUMBER",e=>typeof e=="number"),s("ISTEXT",e=>typeof e=="string"),s("ISNONTEXT",e=>typeof e!="string"),s("ISLOGICAL",e=>typeof e=="boolean"),s("ISBLANK",e=>e==null),l("ISEVEN",1,1,e=>Math.trunc(p(e))%2===0),l("ISODD",1,1,e=>Math.trunc(p(e))%2!==0),m("ISREF",1,1,(e,t)=>t[0]instanceof i||t[0]instanceof E),m("ISFORMULA",1,1,(e,t)=>{const r=t[0];if(!(r instanceof i))throw o.VALUE;return(r.sheet.kind(r.r0,r.c0)&R)!==0}),l("N",1,1,e=>{if(typeof e=="number")return e;if(typeof e=="boolean")return e?1:0;if(e instanceof N)throw o.VALUE;return 0}),l("NA",0,0,()=>o.NA),s("ERROR.TYPE",e=>{if(!(e instanceof y))throw o.NA;return{"#NULL!":1,"#DIV/0!":2,"#VALUE!":3,"#REF!":4,"#NAME?":5,"#NUM!":6,"#N/A":7,"#GETTING_DATA":8,"#SPILL!":9,"#FIELD!":13,"#CALC!":14}[e.code]}),m("TYPE",1,1,(e,t)=>{const r=t[0]instanceof i&&t[0].isCell?e.read(t[0].sheet,t[0].r0,t[0].c0):t[0];return r instanceof i||r instanceof E||r instanceof S?64:r===null||typeof r=="number"?1:typeof r=="string"?2:typeof r=="boolean"?4:r instanceof y?16:r instanceof w||r instanceof N?128:1}),m("SHEET",0,1,(e,t,r,f,a)=>{if(t.length===0||t[0]===d)return e.book.sheets.indexOf(a)+1;if(t[0]instanceof i)return e.book.sheets.indexOf(t[0].sheet)+1;if(typeof t[0]=="string"){const u=e.sheetByName(t[0]);if(!u)throw o.NA;return e.book.sheets.indexOf(u)+1}throw o.VALUE},{readsSheets:!0}),m("SHEETS",0,1,(e,t)=>{if(t.length===0||t[0]===d)return e.book.sheets.length;if(t[0]instanceof E)return new Set(t[0].refs.map(r=>r.sheet)).size;if(t[0]instanceof i)return 1;throw o.REF},{readsSheets:!0}),m("INFO",1,1,(e,t,r,f)=>{switch(L(e.scalar(t[0],r,f)).toLowerCase()){case"numfile":return e.book.sheets.length;case"recalc":return e.manual?"Manual":"Automatic";case"release":return"16.0";case"system":return"mac";case"origin":return"$A:$A$1";case"directory":return"";default:throw o.VALUE}},{readsSheets:!0}),m("CELL",1,2,(e,t,r,f,a)=>{const u=L(e.scalar(t[0],r,f)).toLowerCase(),n=t[1]===void 0||t[1]===d?new i(a,r,f,r,f):t[1];if(n instanceof y)throw n;if(!(n instanceof i))throw o.VALUE;if(u==="filename")return e.book.fileName?`[${e.book.fileName}]${n.sheet.name}`:"";const c=e.read(n.sheet,n.r0,n.c0),h=e.book.styles.get(n.sheet.style(n.r0,n.c0));switch(u){case"address":{const A=`$${g(n.c0)}$${n.r0+1}`;return n.sheet===a?A:`${k(n.sheet.name,{book:e.book.fileName??T()})}${A}`}case"col":return n.c0+1;case"row":return n.r0+1;case"contents":return c===null?0:c;case"type":return c===null?"b":typeof c=="string"?"l":"v";case"width":return Math.max(0,Math.round((n.sheet.cols.sizeOf(n.c0)-5)/6));case"color":return/\[red\]/i.test(h.numFmt)?1:0;case"format":return O(h.numFmt);case"parentheses":return/\(/.test(h.numFmt)?1:0;case"prefix":return typeof c=="string"?h.hAlign==="right"?'"':h.hAlign==="center"?"^":"'":"";case"protect":return 1;default:throw o.VALUE}});const F=new Map([["d-mmm-yy","D1"],["dd-mmm-yy","D1"],["d-mmm","D2"],["dd-mmm","D2"],["mmm-yy","D3"],["m/d/yy","D4"],["m/d/yyyy","D4"],["mm/dd/yy","D4"],["m/d/yy h:mm","D4"],["m/d/yyyy h:mm","D4"],["mm/dd","D5"],["h:mm:ss am/pm","D6"],["h:mm am/pm","D7"],["h:mm:ss","D8"],["h:mm","D9"]]);function O(e){if(e==="General")return"G";if(e==="0")return"F0";if(e==="#,##0")return",0";if(e==="0.00")return"F2";if(e==="#,##0.00")return",2";if(/%/.test(e))return`P${(/\.(0+)/.exec(e)?.[1]??"").length}`;if(/E\+/i.test(e))return"S2";const t=F.get(e.toLowerCase());return t||(/[ymd]/i.test(e)?"D1":"G")}export{I as CONTENT_MASK,b as cellRef};
|
package/calcx/lang/convert.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const L=new Map;let p=null;function W(e,n){const r=e.toLowerCase(),
|
|
1
|
+
const L=new Map;let p=null;function W(e,n){const r=e.toLowerCase(),t=n.parent?L.get(n.parent.toLowerCase()):null;L.set(r,y(r,n,t)),p?.code===r&&(p=L.get(r))}function y(e,n,r){const t={...r?.source.functions??{},...n.functions??{}},u={...r?.source.errors??{},...n.errors??{}},f={...r?.source.booleans??{},...n.booleans??{}},i={...r?.source.structured??{},...n.structured??{}},d=h=>new Map(Object.entries(h).map(([s,l])=>[l.toUpperCase(),s]));return{code:e,name:n.name??e,source:{functions:t,errors:u,booleans:f,structured:i},fnToLocal:new Map(Object.entries(t)),fnToEnglish:d(t),errToLocal:new Map(Object.entries(u).map(([h,s])=>[h.toUpperCase(),s])),errToEnglish:d(u),boolToLocal:new Map(Object.entries(f)),boolToEnglish:d(f),structToLocal:new Map(Object.entries(i).map(([h,s])=>[h.toUpperCase(),s])),structToEnglish:d(i)}}const v=()=>[...L.values()].map(e=>({code:e.code,name:e.name}));function B(e){if(!e||e.toLowerCase()==="en")return p=null,!0;const n=L.get(e.toLowerCase());return n===void 0?!1:(p=n,!0)}const X=()=>p?.code??"en",b="_XLL.",S=new Set,A=e=>{for(const n of S)if(n(e))return!0;return!1};function z(e){return S.add(e),()=>S.delete(e)}function E(e,n){let r=n;for(;r.startsWith(b);)r=r.slice(b.length);if(e.fnToLocal.has(r))return!1;const t=e.fnToEnglish.get(r);return t!==void 0&&t!==r}function g(e,n){const r=n.toUpperCase();return E(e,r)?`_xll.${n}`:e.fnToLocal.get(r)??n}function j(e,n){const r=n.toUpperCase();return r.startsWith(b)&&E(e,r)?n.slice(b.length):e.fnToEnglish.get(r)??n}const H=e=>p?g(p,e):e,P=e=>(p?j(p,e):e).toUpperCase(),Q=e=>p?.structToLocal.get(e.toUpperCase())??e,$=e=>p?.errToLocal.get(e.toUpperCase())??e,G=e=>{const n=e?"TRUE":"FALSE";return p?.boolToLocal.get(n)??n},O=Object.freeze({decimal:".",listSep:",",arrayColSep:",",arrayRowSep:";"}),m=e=>e>="0"&&e<="9",_=/[\p{L}_\\]/u,D=/[\p{L}\p{N}_.\\?]/u;function F(e,n,r){let t=n+1;for(;t<e.length;)if(e[t]===r)if(e[t+1]===r)t+=2;else return t+1;else t++;return t}function M(e,n,r,t){if(/^\[\d+\]/.test(e)&&!e.includes("#"))return e;let u="",f=0,i=0;for(;i<e.length;){const d=e[i];if(d==="'"&&e[i+1]!==void 0)u+=d+e[i+1],i+=2;else if(d==="["){if(f++,u+=d,i++,e[i]==="#"){const h=e.indexOf("]",i),s=e.slice(i,h<0?e.length:h),l=t?n?t.structToLocal.get(s.toUpperCase()):t.structToEnglish.get(s.toUpperCase()):void 0;u+=l??s,i+=s.length}}else d==="]"?(f--,u+=d,i++):f===1&&d===(n?",":r)?(u+=n?r:",",i++):(u+=d,i++)}return u}function R(e,n,r,t){const{decimal:u,listSep:f,arrayColSep:i,arrayRowSep:d}=r,h=e.length;let s="",l=0,T=0;for(;l<h;){const c=e[l];if(c==='"'||c==="'"){const a=F(e,l,c);s+=e.slice(l,a),l=a}else if(c==="["){let a=0,o=l;for(;o<h;o++)if(e[o]==="'")o++;else if(e[o]==="[")a++;else if(e[o]==="]"&&(a--,a===0))break;s+=M(e.slice(l,o+1),n,f,t),l=o+1}else if(c==="{")T++,s+=c,l++;else if(c==="}")T--,s+=c,l++;else if(c==="#"){const a=/^#[^\s,;:()+\-*^&=<>{}\\|]*[!?]?/u.exec(e.slice(l,l+40));let o=null;if(a&&t){const w=n?t.errToLocal:t.errToEnglish;for(let C=a[0].length;C>1;C--){const U=w.get(a[0].slice(0,C).toUpperCase());if(U!==void 0){o={len:C,swapped:U};break}}}o?(s+=o.swapped,l+=o.len):(s+=c,l++)}else if(m(c)||c===(n?".":u)&&m(e[l+1]??"")){const a=n?".":u;let o=l;for(;o<h&&m(e[o]);)o++;if(e[o]===a)for(o++;o<h&&m(e[o]);)o++;if((e[o]==="e"||e[o]==="E")&&(m(e[o+1]??"")||(e[o+1]==="+"||e[o+1]==="-")&&m(e[o+2]??"")))for(o+=2;o<h&&m(e[o]);)o++;const w=e.slice(l,o);s+=a===(n?u:".")?w:w.replace(a,n?u:"."),l=o}else if(_.test(c)&&!(c==="\\"&&T>0)){let a=l+1;for(;a<h&&D.test(e[a]);)a++;const o=e.slice(l,a),w=e[a];if(t&&w==="(")A(o.toUpperCase())?s+=o:s+=n?g(t,o):j(t,o);else if(t&&w!=="!"&&w!=="["){const C=o.toUpperCase(),U=n?t.boolToLocal.get(C):t.boolToEnglish.get(C);s+=U??o}else s+=o;l=a}else n?(c===","?s+=T>0?i:f:c===";"&&T>0?s+=d:s+=c,l++):(T>0&&c===i?s+=",":T>0&&c===d?s+=";":T===0&&c===f?s+=",":s+=c,l++)}return s}const N=e=>e.decimal==="."&&e.listSep===","&&e.arrayColSep===","&&e.arrayRowSep===";";function I(e,n=O){return p===null&&N(n)?e:R(e,!0,n,p)}function J(e,n=O){return p===null&&N(n)?e:R(e,!1,n,p)}function K(e,n,r=40){const t=e.toUpperCase(),u=[];for(const f of n){if(f.startsWith("_"))continue;const i=p?g(p,f):f;i.toUpperCase().startsWith(t)&&u.push({local:i,english:f})}return u.sort((f,i)=>f.local.localeCompare(i.local)),u.slice(0,r)}export{O as STANDARD_SEPARATORS,z as addDefinedNameCheck,v as availableLanguages,K as completeFunctionName,P as englishFunctionName,J as formulaFromUser,X as formulaLanguage,I as formulaToUser,G as localBooleanText,$ as localErrorText,H as localFunctionName,Q as localSpecifier,W as registerLanguage,B as setFormulaLanguage};
|
package/cells/book-css.js
CHANGED
|
@@ -106,11 +106,16 @@ const r=`
|
|
|
106
106
|
.xl-tall[open] { display: flex; flex-direction: column; overflow: hidden; }
|
|
107
107
|
.xl-tall .dlg-body { flex: 1; min-height: 0; display: flex; }
|
|
108
108
|
.xl-tall .xl-tabbed { flex: 1; min-width: 0; }
|
|
109
|
+
.xl-dlg.dv-dialog {
|
|
110
|
+
--dv-height: calc(100dvh / var(--dv-scale, 1) - 24px);
|
|
111
|
+
min-height: min(386px, var(--dv-height));
|
|
112
|
+
max-height: var(--dv-height);
|
|
113
|
+
max-width: calc(100vw / var(--dv-scale, 1) - 24px);
|
|
114
|
+
}
|
|
109
115
|
.dv-grid { display: grid; grid-template-columns: minmax(0, 1fr) 118px; gap: 8px 16px; align-items: end; }
|
|
110
116
|
.dv-grid select.dlg-input { width: 100%; }
|
|
111
117
|
.dv-field { margin-top: 8px; }
|
|
112
|
-
.dv-apply {
|
|
113
|
-
.bk-box-tabs.dv-pane { position: relative; }
|
|
118
|
+
.dv-pane .dv-apply { margin-top: 12px; align-items: baseline; white-space: normal; }
|
|
114
119
|
.dv-pane .dlg-check { min-height: 22px; }
|
|
115
120
|
.dv-pane textarea { display: block; width: 100%; height: 60px; resize: none; }
|
|
116
121
|
.ln-top { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 8px; margin-bottom: 14px; }
|
package/cells/cf-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseRangeRef as R}from"../core/address.js";import{CHUNK_BITS as C,CHUNK_MASK as N,DIRTY as D,KIND_MASK as T,NUM as B}from"../core/sheet.js";import{partsToSerial as V,serialToParts as k}from"../core/numfmt.js";import{compareValues as v,XlError as b}from"../calc/values.js";import{wildcardRegex as q}from"../calc/functions/helpers.js";import{resolveColor as P}from"../io/xlsx-styles.js";const W=c=>c.split(/\s+/).map(R).filter(Boolean),K=1<<19,w=Object.freeze({}),E=new Set(["colorScale","dataBar","iconSet"]),$=c=>[parseInt(c.slice(1,3),16),parseInt(c.slice(3,5),16),parseInt(c.slice(5,7),16)],F=c=>(c<16?"0":"")+c.toString(16),I=c=>c<0?0:c>1?1:c;function U(c,s){const o={...s,...c};return(c.fill!==void 0||c.pattern!==void 0||c.gradient!==void 0||c.noFill)&&(c.pattern===void 0&&delete o.pattern,c.gradient===void 0&&delete o.gradient,c.fill===void 0&&delete o.fill,c.noFill||delete o.noFill),c.borders&&s.borders&&(o.borders={l:c.borders.l??s.borders.l,r:c.borders.r??s.borders.r,t:c.borders.t??s.borders.t,b:c.borders.b??s.borders.b}),o}const O=c=>c instanceof b?String(c.code??c.message??c).toLowerCase():typeof c=="boolean"?c?"true":"false":String(c).toLowerCase();class H{constructor(s,o,n){this.book=s,this.sheet=o,this.colorOf=n??(e=>P(e,s.theme??[])),this.cache=new Map,this.stats=new Map,this.data=new Map,this.flat=null,this.flatOf=null,this.today=0}invalidate(){this.cache.clear(),this.stats.clear(),this.data.clear(),this.flat=null,this.today=0}_rules(){const{cf:s}=this.sheet;if(this.flat!==null&&this.flatOf===s)return this.flat;const o=[];for(const n of s??[]){n._ranges===void 0&&(n._ranges=W(n.sqref));const e=n._ranges;if(e.length===0)continue;let t=1/0,r=1/0,i=-1,l=-1;for(const a of e)a.r0<t&&(t=a.r0),a.c0<r&&(r=a.c0),a.r1>i&&(i=a.r1),a.c1>l&&(l=a.c1);n._base={r0:t,c0:r};for(const a of n.rules)o.push({rule:a,block:n,r0:t,c0:r,r1:i,c1:l,single:e.length===1})}return o.sort((n,e)=>n.rule.priority-e.rule.priority),this.flat=o,this.flatOf=s,this.stoppers=o.filter(n=>n.rule.stopIfTrue&&!E.has(n.rule.type)),o}stoppedBefore(s,o,n){this._rules();for(const e of this.stoppers){if(e.rule.priority>=s)break;if(!(o<e.r0||o>e.r1||n<e.c0||n>e.c1)&&!(!e.single&&!e.block._ranges.some(t=>o>=t.r0&&o<=t.r1&&n>=t.c0&&n<=t.c1))&&this._evaluate(e.rule,e.block,o,n)!==null)return!0}return!1}at(s,o){this.valueRevision!==this.book.formatValueRevision&&(this.invalidate(),this.valueRevision=this.book.formatValueRevision);const n=s*16384+o,e=this.cache.get(n);if(e!==void 0)return e;const t=this._rules();let r=null;for(let i=0;i<t.length;i++){const l=t[i];if(s<l.r0||s>l.r1||o<l.c0||o>l.c1)continue;if(!l.single){const h=l.block._ranges;let d=!1;for(let f=0;f<h.length&&!d;f++){const m=h[f];d=s>=m.r0&&s<=m.r1&&o>=m.c0&&o<=m.c1}if(!d)continue}const a=this._evaluate(l.rule,l.block,s,o);if(a===null)continue;const u=l.block.managedBy?{...a,fieldWarning:a}:a;if(r=r===null?u:U(r,u),l.rule.stopIfTrue&&!E.has(l.rule.type))break}return this.cache.size>=K&&this.cache.clear(),this.cache.set(n,r),r}_value(s,o){return this.book.engine?this.book.engine.read(this.sheet,s,o):null}_stat(s){let o=this.stats.get(s);if(o!==void 0)return o;const{sheet:n}=this,{engine:e}=this.book;let t=new Float64Array(1024),r=0;for(const u of s._ranges){const h=Math.min(u.c1,n.maxCol),d=Math.min(u.r1,n.maxRow);for(let f=u.c0;f<=h;f++){const m=n.columns[f];if(m!==void 0)for(let p=u.r0>>>C;p<=d>>>C;p++){const _=m[p];if(_===void 0)continue;const x=p<<C,y=Math.max(u.r0-x,0),M=Math.min(d-x,N),{kinds:A,values:L}=_;if(r+(M-y+1)>t.length){const g=new Float64Array(Math.max(t.length*2,r+M-y+1));g.set(t),t=g}for(let g=y;g<=M;g++){const S=A[g];S!==0&&(S&D?(e&&e.read(n,x+g,f),(A[g]&T)===B&&(t[r++]=L[g])):(S&T)===B&&(t[r++]=L[g]))}}}}t=t.subarray(0,r).sort();let i=0;for(let u=0;u<r;u++)i+=t[u];const l=r?i/r:0;let a=0;for(let u=0;u<r;u++)a+=(t[u]-l)**2;return o={nums:t,n:r,mean:l,stdP:r>0?Math.sqrt(a/r):0,min:r?t[0]:0,max:r?t[r-1]:0,others:null,texts:null,wild:null},this.stats.set(s,o),o}_others(s){const o=this._stat(s);if(o.others!==null)return o.others;const n=new Map;for(const e of s._ranges)this.book.engine?.scan({sheet:this.sheet,r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1},t=>{if(typeof t=="number")return;const r=O(t);n.set(r,(n.get(r)??0)+1)});return o.others=n,n}_numberCount(s,o){const{nums:n,n:e}=this._stat(s);let t=0,r=e;for(;t<r;){const i=t+r>>>1;n[i]<o?t=i+1:r=i}return t>=e||n[t]!==o?0:t+1<e&&n[t+1]===o?2:1}_wildcardCount(s,o){const n=this._stat(s);if(n.texts===null){n.texts=new Map;for(const r of s._ranges)this.book.engine?.scan({sheet:this.sheet,r0:r.r0,c0:r.c0,r1:r.r1,c1:r.c1},i=>{typeof i=="string"&&n.texts.set(i.toLowerCase(),(n.texts.get(i.toLowerCase())??0)+1)})}n.wild??=new Map;const e=o.toLowerCase();let t=n.wild.get(e);if(t===void 0){const r=q(o);t=0;for(const[i,l]of n.texts)r.test(i)&&(t+=l);n.wild.set(e,t)}return t}_occurrences(s,o){if(typeof o=="string"&&/[*?]/.test(o))return this._wildcardCount(s,o);const n=this._others(s);if(typeof o=="number")return this._numberCount(s,o)+(n.get(String(o))??0);const e=O(o),t=n.get(e)??0;return typeof o=="string"&&e!==""&&!Number.isNaN(Number(e))?t+this._numberCount(s,Number(e)):t}_template(s,o,n,e){const t=this._ruleData(s),r=`t${o}`;if(t[r]===void 0){const i=e._base;t[r]=this.book.engine.template(n,i.r0,i.c0)}return t[r]}_formula(s,o,n,e,t){const{engine:r}=this.book,i=s.formulas?.[o];return i===void 0||!r?null:this._run(this._template(s,o,i,n),e,t)}_run(s,o,n){const{engine:e}=this.book,t=e.legacy;e.legacy=!0;try{let r=s.fn(o,n,this.sheet);return(r&&r.sheet||r&&r.refs)&&(r=e.refAuto(r,o,n)),r&&r.data&&([r]=r.data),r===void 0?null:r}catch(r){return r instanceof b?r:null}finally{e.legacy=t}}_dxf(s){return s.dxf?s.dxf:s.dxfId!==null&&s.dxfId!==void 0?this.book.dxfs?.[s.dxfId]??w:w}_threshold(s,o){const n=this._stat(o);switch(s.type){case"min":return n.min;case"max":return n.max;case"autoMin":return Math.min(n.min,0);case"autoMax":return Math.max(n.max,0);default:break}const e=s.val;let t;if(typeof e=="string"&&!/^\s*[-+]?[\d.]+(?:[eE][-+]?\d+)?\s*$/.test(e)){const{engine:r}=this.book;if(!r)return 0;const i=o._base,l=this._run(r.template(e,i.r0,i.c0),i.r0,i.c0);t=typeof l=="number"?l:0}else t=e==null?0:Number(e);switch(s.type){case"percent":return n.min+(n.max-n.min)*t/100;case"percentile":{if(n.n===0)return 0;const r=I(t/100)*(n.n-1),i=Math.floor(r);return i+1<n.n?n.nums[i]+(r-i)*(n.nums[i+1]-n.nums[i]):n.nums[i]}default:return t}}_ruleData(s){let o=this.data.get(s);return o===void 0&&(o={},this.data.set(s,o)),o}_evaluate(s,o,n,e){switch(s.type){case"cellIs":{const t=this._value(n,e);if(t instanceof b)return null;const r=this._formula(s,0,o,n,e);if(r instanceof b)return null;const i=s.operator;let l=!1;if(i==="between"||i==="notBetween"){const a=this._formula(s,1,o,n,e);if(a instanceof b)return null;const u=v(r,a)<=0,h=u?r:a,d=u?a:r,f=v(t,h)>=0&&v(t,d)<=0;l=i==="between"?f:!f}else{const a=v(t,r);l=i==="greaterThan"?a>0:i==="lessThan"?a<0:i==="greaterThanOrEqual"?a>=0:i==="lessThanOrEqual"?a<=0:i==="equal"?a===0:i==="notEqual"?a!==0:!1}return l?this._dxf(s):null}case"expression":{const t=this._formula(s,0,o,n,e);return typeof t=="boolean"?t?this._dxf(s):null:typeof t=="number"&&t!==0?this._dxf(s):null}case"containsText":case"notContainsText":case"beginsWith":case"endsWith":return this._textRule(s,o,n,e)?this._dxf(s):null;case"containsBlanks":{const t=this._value(n,e);return t===null||typeof t=="string"&&t.trim()===""?this._dxf(s):null}case"notContainsBlanks":{const t=this._value(n,e);return t!==null&&!(t instanceof b)&&!(typeof t=="string"&&t.trim()==="")?this._dxf(s):null}case"containsErrors":return this._value(n,e)instanceof b?this._dxf(s):null;case"notContainsErrors":return this._value(n,e)instanceof b?null:this._dxf(s);case"duplicateValues":case"uniqueValues":{const t=this._value(n,e);if(t===null)return null;const r=this._occurrences(o,t);return(s.type==="duplicateValues"?r>1:r===1)?this._dxf(s):null}case"top10":{const t=this._value(n,e);if(typeof t!="number")return null;const r=this._stat(o);let i=s.rank??10;return s.percent&&(i=Math.max(1,Math.floor(r.n*i/100))),i=Math.min(i,r.n),i<=0?null:(s.bottom?t<=r.nums[i-1]:t>=r.nums[r.n-i])?this._dxf(s):null}case"aboveAverage":{const t=this._value(n,e);if(typeof t!="number")return null;const r=this._stat(o),i=s.aboveAverage!==!1,l=r.mean+(i?1:-1)*(s.stdDev||0)*r.stdP;return(i?s.equalAverage?t>=l:t>l:s.equalAverage?t<=l:t<l)?this._dxf(s):null}case"timePeriod":{const t=this._value(n,e);return typeof t=="number"&&this._inPeriod(t,s.timePeriod)?this._dxf(s):null}case"colorScale":{const t=this._value(n,e);return typeof t=="number"?this._colorScale(s,o,t):null}case"dataBar":{const t=this._value(n,e);return typeof t=="number"?this._dataBar(s,o,t):null}case"iconSet":{const t=this._value(n,e);return typeof t=="number"?this._iconSet(s,o,t):null}default:return null}}_textRule(s,o,n,e){if(s.formulas&&s.formulas.length>0&&this.book.engine){const l=this._formula(s,0,o,n,e);return l===!0||typeof l=="number"&&l!==0}const t=this._value(n,e),r=String(s.text??"").toLowerCase();if(t instanceof b)return s.type==="notContainsText";const i=t===null?"":typeof t=="boolean"?t?"true":"false":String(t).toLowerCase();switch(s.type){case"containsText":return i.includes(r);case"notContainsText":return!i.includes(r);case"beginsWith":return i.startsWith(r);default:return i.endsWith(r)}}_colorScale(s,o,n){const e=this._ruleData(s);if(e.stops===void 0){const{cfvo:i,colors:l}=s.colorScale;e.stops=i.map(a=>this._threshold(a,o)),e.css=l.map(a=>this.colorOf({a})??"#FFFFFF"),e.rgb=e.css.map($),e.ends=e.css.map(a=>({fill:a}))}const{stops:t}=e,r=t.length-1;if(n>=t[r])return e.ends[r];if(n<=t[0])return e.ends[0];for(let i=1;i<=r;i++)if(n<t[i]){const l=t[i]-t[i-1],a=l===0?1:(n-t[i-1])/l,u=e.rgb[i-1],h=e.rgb[i];return{fill:`#${F(Math.round(u[0]+(h[0]-u[0])*a))}${F(Math.round(u[1]+(h[1]-u[1])*a))}${F(Math.round(u[2]+(h[2]-u[2])*a))}`}}return e.ends[r]}_barStyle(s,o){const n=this._ruleData(s);if(n.bar!==void 0)return n.bar;const e=s.dataBar,t=e.ext,r=t?.cfvo??e.cfvo;let i=this._threshold(r[0],o),l=this._threshold(r[1],o);l<i&&([i,l]=[l,i]);const a=this.colorOf({a:e.color})??"#638EC6",u=(_,x)=>_?this.colorOf({a:_})??x:x,h=(t?t.minLength:e.minLength??10)/100,d=(t?t.maxLength:e.maxLength??90)/100,f=t?t.axisPosition??"automatic":"none";let m=-1;f==="middle"?m=.5:f==="automatic"&&(i<0&&l>0?m=-i/(l-i):l<=0&&i<0&&(m=1));const p=t?.border?u(t.borderColor,a):null;return n.bar={lo:i,hi:l,minL:h,maxL:d,start:t?h/2:h,axisAt:m,color:a,gradient:t?t.gradient!==!1:!0,border:p,negColor:t&&!t.negFillSame?u(t.negFill,"#FF0000"):a,negBorder:t?.border&&t.negBorderSame===!1?u(t.negBorder,"#FF0000"):p,axisColor:t?u(t.axisColor,"#000000"):"#000000",direction:t?.direction??"context",hide:e.showValue===!1},n.bar}_dataBar(s,o,n){const e=this._barStyle(s,o),{lo:t,hi:r,minL:i,maxL:l,axisAt:a,start:u}=e,h=l-i;let d,f;if(a<0)d=0,f=u+h*(r===t?1:I((n-t)/(r-t)));else{const _=s.dataBar.ext?.axisPosition==="middle"?Math.max(Math.abs(t),Math.abs(r)):n>=0?r:-t,y=(n>=0?1-a:a)*(u+h*(_>0?I(Math.abs(n)/_):0));n>=0?(d=a,f=a+y):(f=a,d=a-y)}return{bar:{style:e,x0:d,x1:f,negative:n<0,pct:f-d,color:n<0?e.negColor:e.color},hideValue:e.hide}}_iconSet(s,o,n){const e=this._ruleData(s),t=s.iconSet;if(e.levels===void 0){e.thresholds=t.cfvo.map(u=>this._threshold(u,o));const a=t.cfvo.length;e.levels=t.cfvo.map((u,h)=>{const d=t.reverse?a-1-h:h,f=t.custom?.[h],m=f?f.iconSet:t.name,p=f?f.iconId:d,_=t.showValue===!1;return m==="NoIcons"?{hideValue:_}:{icon:{name:m,level:p,count:a},hideValue:_}})}const{thresholds:r,levels:i}=e;let l=0;for(let a=r.length-1;a>=1;a--){const u=r[a];if(t.cfvo[a].gte===!1?n>u:n>=u){l=a;break}}return i[l]}_inPeriod(s,o){if(this.today===0){const a=new Date;this.today=V(a.getFullYear(),a.getMonth()+1,a.getDate())}const{today:n}=this,e=Math.floor(s);if(e<0)return!1;switch(o){case"today":return e===n;case"yesterday":return e===n-1;case"tomorrow":return e===n+1;case"last7Days":return e<=n&&e>n-7;default:break}const t=a=>a-k(a).weekday;switch(o){case"thisWeek":return t(e)===t(n);case"lastWeek":return t(e)===t(n)-7;case"nextWeek":return t(e)===t(n)+7;default:break}const r=k(e),i=k(n),l=(r.year-i.year)*12+r.month-i.month;switch(o){case"thisMonth":return l===0;case"lastMonth":return l===-1;case"nextMonth":return l===1;default:return!1}}}function j(c,s){if(!c.cfEval){if(!s)return null;c.cfEval=new H(s,c)}return c.cfEval}function z(c,s,o,n){if(!c.cf||c.cf.length===0)return null;const e=j(c,n),t=e?e.at(s,o):null;return t===null?null:{fill:t.fill??null,noFill:t.noFill===!0,color:t.color??null,iconSet:t.icon?.name??null,iconId:t.icon?.level??null}}function tt(c,s,o,n){const e=z(c,s,o,n);return e&&e.iconSet!==null?{iconSet:e.iconSet,iconId:e.iconId}:null}export{H as CondFormats,z as cfEffectAt,j as evaluatorOf,tt as iconAt};
|
|
1
|
+
import{parseRangeRef as O}from"../core/address.js";import{CHUNK_BITS as S,CHUNK_MASK as N,DIRTY as D,KIND_MASK as T,NUM as B}from"../core/sheet.js";import{partsToSerial as P,serialToParts as F}from"../core/numfmt.js";import{compareValues as v,XlError as b}from"../calc/values.js";import{wildcardRegex as V}from"../calc/functions/helpers.js";import{hasConditionalFormats as q,hostFormats as W}from"../core/host-rules.js";import{resolveColor as H}from"../io/xlsx-styles.js";const K=c=>c.split(/\s+/).map(O).filter(Boolean),$=1<<19,R=Object.freeze({}),w=new Set(["colorScale","dataBar","iconSet"]),U=c=>[parseInt(c.slice(1,3),16),parseInt(c.slice(3,5),16),parseInt(c.slice(5,7),16)],k=c=>(c<16?"0":"")+c.toString(16),I=c=>c<0?0:c>1?1:c;function j(c,s){const o={...s,...c};return(c.fill!==void 0||c.pattern!==void 0||c.gradient!==void 0||c.noFill)&&(c.pattern===void 0&&delete o.pattern,c.gradient===void 0&&delete o.gradient,c.fill===void 0&&delete o.fill,c.noFill||delete o.noFill),c.borders&&s.borders&&(o.borders={l:c.borders.l??s.borders.l,r:c.borders.r??s.borders.r,t:c.borders.t??s.borders.t,b:c.borders.b??s.borders.b}),o}const E=c=>c instanceof b?String(c.code??c.message??c).toLowerCase():typeof c=="boolean"?c?"true":"false":String(c).toLowerCase();class z{constructor(s,o,n){this.book=s,this.sheet=o,this.colorOf=n??(e=>H(e,s.theme??[])),this.cache=new Map,this.stats=new Map,this.data=new Map,this.flat=null,this.flatOf=null,this.flatHost=null,this.today=0}invalidate(){this.cache.clear(),this.stats.clear(),this.data.clear(),this.flat=null,this.today=0}_rules(){const{cf:s,hostRules:o}=this.sheet;if(this.flat!==null&&this.flatOf===s&&this.flatHost===o)return this.flat;const n=(t,r)=>t.rule.priority-r.rule.priority,e=[...this._entries(s??[]).sort(n),...this._entries(W(this.sheet))];return this.flat=e,this.flatOf=s,this.flatHost=o,this.stoppers=e.filter(t=>t.rule.stopIfTrue&&!w.has(t.rule.type)),e}_entries(s){const o=[];for(const n of s){n._ranges===void 0&&(n._ranges=K(n.sqref));const e=n._ranges;if(e.length===0)continue;let t=1/0,r=1/0,i=-1,l=-1;for(const a of e)a.r0<t&&(t=a.r0),a.c0<r&&(r=a.c0),a.r1>i&&(i=a.r1),a.c1>l&&(l=a.c1);n._base={r0:t,c0:r};for(const a of n.rules)o.push({rule:a,block:n,r0:t,c0:r,r1:i,c1:l,single:e.length===1})}return o}stoppedBefore(s,o,n){this._rules();for(const e of this.stoppers){if(e.rule.priority>=s)break;if(!(o<e.r0||o>e.r1||n<e.c0||n>e.c1)&&!(!e.single&&!e.block._ranges.some(t=>o>=t.r0&&o<=t.r1&&n>=t.c0&&n<=t.c1))&&this._evaluate(e.rule,e.block,o,n)!==null)return!0}return!1}at(s,o){this.valueRevision!==this.book.formatValueRevision&&(this.invalidate(),this.valueRevision=this.book.formatValueRevision);const n=s*16384+o,e=this.cache.get(n);if(e!==void 0)return e;const t=this._rules();let r=null;for(let i=0;i<t.length;i++){const l=t[i];if(s<l.r0||s>l.r1||o<l.c0||o>l.c1)continue;if(!l.single){const h=l.block._ranges;let d=!1;for(let f=0;f<h.length&&!d;f++){const m=h[f];d=s>=m.r0&&s<=m.r1&&o>=m.c0&&o<=m.c1}if(!d)continue}const a=this._evaluate(l.rule,l.block,s,o);if(a===null)continue;const u=l.block.managedBy?{...a,fieldWarning:a}:a;if(r=r===null?u:j(r,u),l.rule.stopIfTrue&&!w.has(l.rule.type))break}return this.cache.size>=$&&this.cache.clear(),this.cache.set(n,r),r}_value(s,o){return this.book.engine?this.book.engine.read(this.sheet,s,o):null}_stat(s){let o=this.stats.get(s);if(o!==void 0)return o;const{sheet:n}=this,{engine:e}=this.book;let t=new Float64Array(1024),r=0;for(const u of s._ranges){const h=Math.min(u.c1,n.maxCol),d=Math.min(u.r1,n.maxRow);for(let f=u.c0;f<=h;f++){const m=n.columns[f];if(m!==void 0)for(let p=u.r0>>>S;p<=d>>>S;p++){const _=m[p];if(_===void 0)continue;const x=p<<S,y=Math.max(u.r0-x,0),M=Math.min(d-x,N),{kinds:A,values:L}=_;if(r+(M-y+1)>t.length){const g=new Float64Array(Math.max(t.length*2,r+M-y+1));g.set(t),t=g}for(let g=y;g<=M;g++){const C=A[g];C!==0&&(C&D?(e&&e.read(n,x+g,f),(A[g]&T)===B&&(t[r++]=L[g])):(C&T)===B&&(t[r++]=L[g]))}}}}t=t.subarray(0,r).sort();let i=0;for(let u=0;u<r;u++)i+=t[u];const l=r?i/r:0;let a=0;for(let u=0;u<r;u++)a+=(t[u]-l)**2;return o={nums:t,n:r,mean:l,stdP:r>0?Math.sqrt(a/r):0,min:r?t[0]:0,max:r?t[r-1]:0,others:null,texts:null,wild:null},this.stats.set(s,o),o}_others(s){const o=this._stat(s);if(o.others!==null)return o.others;const n=new Map;for(const e of s._ranges)this.book.engine?.scan({sheet:this.sheet,r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1},t=>{if(typeof t=="number")return;const r=E(t);n.set(r,(n.get(r)??0)+1)});return o.others=n,n}_numberCount(s,o){const{nums:n,n:e}=this._stat(s);let t=0,r=e;for(;t<r;){const i=t+r>>>1;n[i]<o?t=i+1:r=i}return t>=e||n[t]!==o?0:t+1<e&&n[t+1]===o?2:1}_wildcardCount(s,o){const n=this._stat(s);if(n.texts===null){n.texts=new Map;for(const r of s._ranges)this.book.engine?.scan({sheet:this.sheet,r0:r.r0,c0:r.c0,r1:r.r1,c1:r.c1},i=>{typeof i=="string"&&n.texts.set(i.toLowerCase(),(n.texts.get(i.toLowerCase())??0)+1)})}n.wild??=new Map;const e=o.toLowerCase();let t=n.wild.get(e);if(t===void 0){const r=V(o);t=0;for(const[i,l]of n.texts)r.test(i)&&(t+=l);n.wild.set(e,t)}return t}_occurrences(s,o){if(typeof o=="string"&&/[*?]/.test(o))return this._wildcardCount(s,o);const n=this._others(s);if(typeof o=="number")return this._numberCount(s,o)+(n.get(String(o))??0);const e=E(o),t=n.get(e)??0;return typeof o=="string"&&e!==""&&!Number.isNaN(Number(e))?t+this._numberCount(s,Number(e)):t}_template(s,o,n,e){const t=this._ruleData(s),r=`t${o}`;if(t[r]===void 0){const i=e._base;t[r]=this.book.engine.template(n,i.r0,i.c0)}return t[r]}_formula(s,o,n,e,t){const{engine:r}=this.book,i=s.formulas?.[o];return i===void 0||!r?null:this._run(this._template(s,o,i,n),e,t)}_run(s,o,n){const{engine:e}=this.book,t=e.legacy;e.legacy=!0;try{let r=s.fn(o,n,this.sheet);return(r&&r.sheet||r&&r.refs)&&(r=e.refAuto(r,o,n)),r&&r.data&&([r]=r.data),r===void 0?null:r}catch(r){return r instanceof b?r:null}finally{e.legacy=t}}_dxf(s){return s.dxf?s.dxf:s.dxfId!==null&&s.dxfId!==void 0?this.book.dxfs?.[s.dxfId]??R:R}_threshold(s,o){const n=this._stat(o);switch(s.type){case"min":return n.min;case"max":return n.max;case"autoMin":return Math.min(n.min,0);case"autoMax":return Math.max(n.max,0);default:break}const e=s.val;let t;if(typeof e=="string"&&!/^\s*[-+]?[\d.]+(?:[eE][-+]?\d+)?\s*$/.test(e)){const{engine:r}=this.book;if(!r)return 0;const i=o._base,l=this._run(r.template(e,i.r0,i.c0),i.r0,i.c0);t=typeof l=="number"?l:0}else t=e==null?0:Number(e);switch(s.type){case"percent":return n.min+(n.max-n.min)*t/100;case"percentile":{if(n.n===0)return 0;const r=I(t/100)*(n.n-1),i=Math.floor(r);return i+1<n.n?n.nums[i]+(r-i)*(n.nums[i+1]-n.nums[i]):n.nums[i]}default:return t}}_ruleData(s){let o=this.data.get(s);return o===void 0&&(o={},this.data.set(s,o)),o}_evaluate(s,o,n,e){switch(s.type){case"cellIs":{const t=this._value(n,e);if(t instanceof b)return null;const r=this._formula(s,0,o,n,e);if(r instanceof b)return null;const i=s.operator;let l=!1;if(i==="between"||i==="notBetween"){const a=this._formula(s,1,o,n,e);if(a instanceof b)return null;const u=v(r,a)<=0,h=u?r:a,d=u?a:r,f=v(t,h)>=0&&v(t,d)<=0;l=i==="between"?f:!f}else{const a=v(t,r);l=i==="greaterThan"?a>0:i==="lessThan"?a<0:i==="greaterThanOrEqual"?a>=0:i==="lessThanOrEqual"?a<=0:i==="equal"?a===0:i==="notEqual"?a!==0:!1}return l?this._dxf(s):null}case"expression":{const t=this._formula(s,0,o,n,e);return typeof t=="boolean"?t?this._dxf(s):null:typeof t=="number"&&t!==0?this._dxf(s):null}case"containsText":case"notContainsText":case"beginsWith":case"endsWith":return this._textRule(s,o,n,e)?this._dxf(s):null;case"containsBlanks":{const t=this._value(n,e);return t===null||typeof t=="string"&&t.trim()===""?this._dxf(s):null}case"notContainsBlanks":{const t=this._value(n,e);return t!==null&&!(t instanceof b)&&!(typeof t=="string"&&t.trim()==="")?this._dxf(s):null}case"containsErrors":return this._value(n,e)instanceof b?this._dxf(s):null;case"notContainsErrors":return this._value(n,e)instanceof b?null:this._dxf(s);case"duplicateValues":case"uniqueValues":{const t=this._value(n,e);if(t===null)return null;const r=this._occurrences(o,t);return(s.type==="duplicateValues"?r>1:r===1)?this._dxf(s):null}case"top10":{const t=this._value(n,e);if(typeof t!="number")return null;const r=this._stat(o);let i=s.rank??10;return s.percent&&(i=Math.max(1,Math.floor(r.n*i/100))),i=Math.min(i,r.n),i<=0?null:(s.bottom?t<=r.nums[i-1]:t>=r.nums[r.n-i])?this._dxf(s):null}case"aboveAverage":{const t=this._value(n,e);if(typeof t!="number")return null;const r=this._stat(o),i=s.aboveAverage!==!1,l=r.mean+(i?1:-1)*(s.stdDev||0)*r.stdP;return(i?s.equalAverage?t>=l:t>l:s.equalAverage?t<=l:t<l)?this._dxf(s):null}case"timePeriod":{const t=this._value(n,e);return typeof t=="number"&&this._inPeriod(t,s.timePeriod)?this._dxf(s):null}case"colorScale":{const t=this._value(n,e);return typeof t=="number"?this._colorScale(s,o,t):null}case"dataBar":{const t=this._value(n,e);return typeof t=="number"?this._dataBar(s,o,t):null}case"iconSet":{const t=this._value(n,e);return typeof t=="number"?this._iconSet(s,o,t):null}default:return null}}_textRule(s,o,n,e){if(s.formulas&&s.formulas.length>0&&this.book.engine){const l=this._formula(s,0,o,n,e);return l===!0||typeof l=="number"&&l!==0}const t=this._value(n,e),r=String(s.text??"").toLowerCase();if(t instanceof b)return s.type==="notContainsText";const i=t===null?"":typeof t=="boolean"?t?"true":"false":String(t).toLowerCase();switch(s.type){case"containsText":return i.includes(r);case"notContainsText":return!i.includes(r);case"beginsWith":return i.startsWith(r);default:return i.endsWith(r)}}_colorScale(s,o,n){const e=this._ruleData(s);if(e.stops===void 0){const{cfvo:i,colors:l}=s.colorScale;e.stops=i.map(a=>this._threshold(a,o)),e.css=l.map(a=>this.colorOf({a})??"#FFFFFF"),e.rgb=e.css.map(U),e.ends=e.css.map(a=>({fill:a}))}const{stops:t}=e,r=t.length-1;if(n>=t[r])return e.ends[r];if(n<=t[0])return e.ends[0];for(let i=1;i<=r;i++)if(n<t[i]){const l=t[i]-t[i-1],a=l===0?1:(n-t[i-1])/l,u=e.rgb[i-1],h=e.rgb[i];return{fill:`#${k(Math.round(u[0]+(h[0]-u[0])*a))}${k(Math.round(u[1]+(h[1]-u[1])*a))}${k(Math.round(u[2]+(h[2]-u[2])*a))}`}}return e.ends[r]}_barStyle(s,o){const n=this._ruleData(s);if(n.bar!==void 0)return n.bar;const e=s.dataBar,t=e.ext,r=t?.cfvo??e.cfvo;let i=this._threshold(r[0],o),l=this._threshold(r[1],o);l<i&&([i,l]=[l,i]);const a=this.colorOf({a:e.color})??"#638EC6",u=(_,x)=>_?this.colorOf({a:_})??x:x,h=(t?t.minLength:e.minLength??10)/100,d=(t?t.maxLength:e.maxLength??90)/100,f=t?t.axisPosition??"automatic":"none";let m=-1;f==="middle"?m=.5:f==="automatic"&&(i<0&&l>0?m=-i/(l-i):l<=0&&i<0&&(m=1));const p=t?.border?u(t.borderColor,a):null;return n.bar={lo:i,hi:l,minL:h,maxL:d,start:t?h/2:h,axisAt:m,color:a,gradient:t?t.gradient!==!1:!0,border:p,negColor:t&&!t.negFillSame?u(t.negFill,"#FF0000"):a,negBorder:t?.border&&t.negBorderSame===!1?u(t.negBorder,"#FF0000"):p,axisColor:t?u(t.axisColor,"#000000"):"#000000",direction:t?.direction??"context",hide:e.showValue===!1},n.bar}_dataBar(s,o,n){const e=this._barStyle(s,o),{lo:t,hi:r,minL:i,maxL:l,axisAt:a,start:u}=e,h=l-i;let d,f;if(a<0)d=0,f=u+h*(r===t?1:I((n-t)/(r-t)));else{const _=s.dataBar.ext?.axisPosition==="middle"?Math.max(Math.abs(t),Math.abs(r)):n>=0?r:-t,y=(n>=0?1-a:a)*(u+h*(_>0?I(Math.abs(n)/_):0));n>=0?(d=a,f=a+y):(f=a,d=a-y)}return{bar:{style:e,x0:d,x1:f,negative:n<0,pct:f-d,color:n<0?e.negColor:e.color},hideValue:e.hide}}_iconSet(s,o,n){const e=this._ruleData(s),t=s.iconSet;if(e.levels===void 0){e.thresholds=t.cfvo.map(u=>this._threshold(u,o));const a=t.cfvo.length;e.levels=t.cfvo.map((u,h)=>{const d=t.reverse?a-1-h:h,f=t.custom?.[h],m=f?f.iconSet:t.name,p=f?f.iconId:d,_=t.showValue===!1;return m==="NoIcons"?{hideValue:_}:{icon:{name:m,level:p,count:a},hideValue:_}})}const{thresholds:r,levels:i}=e;let l=0;for(let a=r.length-1;a>=1;a--){const u=r[a];if(t.cfvo[a].gte===!1?n>u:n>=u){l=a;break}}return i[l]}_inPeriod(s,o){if(this.today===0){const a=new Date;this.today=P(a.getFullYear(),a.getMonth()+1,a.getDate())}const{today:n}=this,e=Math.floor(s);if(e<0)return!1;switch(o){case"today":return e===n;case"yesterday":return e===n-1;case"tomorrow":return e===n+1;case"last7Days":return e<=n&&e>n-7;default:break}const t=a=>a-F(a).weekday;switch(o){case"thisWeek":return t(e)===t(n);case"lastWeek":return t(e)===t(n)-7;case"nextWeek":return t(e)===t(n)+7;default:break}const r=F(e),i=F(n),l=(r.year-i.year)*12+r.month-i.month;switch(o){case"thisMonth":return l===0;case"lastMonth":return l===-1;case"nextMonth":return l===1;default:return!1}}}function Y(c,s){if(!c.cfEval){if(!s)return null;c.cfEval=new z(s,c)}return c.cfEval}function X(c,s,o,n){if(!q(c))return null;const e=Y(c,n),t=e?e.at(s,o):null;return t===null?null:{fill:t.fill??null,noFill:t.noFill===!0,color:t.color??null,iconSet:t.icon?.name??null,iconId:t.icon?.level??null}}function st(c,s,o,n){const e=X(c,s,o,n);return e&&e.iconSet!==null?{iconSet:e.iconSet,iconId:e.iconId}:null}export{z as CondFormats,X as cfEffectAt,Y as evaluatorOf,st as iconAt};
|
package/cells/find-engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{formulaEntryLimit as
|
|
2
|
-
`);return{...t,text:s}}function z(e,t,n){if(!e.comments)return[];const s=[];for(const[o
|
|
1
|
+
import{cellEditable as J}from"../core/protection.js";import{formulaEntryLimit as W}from"../calc/parser.js";import{CHUNK_BITS as M,CHUNK_MASK as I,EMPTY as D,FORMULA as T,KIND_MASK as G,SPILL as X,STR as Y}from"../core/sheet.js";const H=/[.+^${}()|[\]\\]/g;function P(e){if(!/[*?~]/.test(e))return null;let t="";for(let n=0;n<e.length;n++){const s=e[n];s==="~"&&n+1<e.length&&"*?~".includes(e[n+1])?t+=e[++n].replace(/[*?]/,"\\$&"):s==="*"?t+="[\\s\\S]*":s==="?"?t+="[\\s\\S]":t+=s.replace(H,"\\$&")}return t}const U=(e,t,n,s)=>new RegExp(n?`^(?:${e})$`:e,`${s}${n?"":"m"}u${t?"":"i"}`);function ft(e){try{return U(e,!0,!1,""),null}catch(t){return t.message}}function v(e,{matchCase:t=!1,whole:n=!1,regex:s=!1}={}){if(s){const r=U(e,t,n,"");return c=>r.test(c)}const i=P(e);if(i===null&&!n){if(t)return c=>c.includes(e);const r=e.toLowerCase();return c=>c.toLowerCase().includes(r)}if(i===null){if(t)return c=>c===e;const r=e.toLowerCase();return c=>c.toLowerCase()===r}const o=new RegExp(n?`^(?:${i})$`:i,t?"":"i");return r=>o.test(r)}function q(e,t,{matchCase:n=!1,whole:s=!1,regex:i=!1}={}){if(i){const c=U(e,n,s,"g");return f=>f.replace(c,t)}const o=P(e)??e.replace(H,"\\$&").replace(/[*?]/g,"\\$&"),r=new RegExp(s?`^(?:${o})$`:o,n?"g":"gi");return c=>c.replace(r,()=>t)}const Q=(e,t)=>e===t||e&&t&&typeof e=="object"&&JSON.stringify(e)===JSON.stringify(t);function V(e,t,n){const{styles:s,strings:i}=e,{what:o,look:r,format:c}=t,f=o===""?null:v(o,t),d=new Uint8Array(i.size+1),l=new Map,m=u=>{let h=l.get(u);if(h===void 0){const g=s.get(u);h=Object.keys(c).every(x=>Q(g[x]??null,c[x]??null)),l.set(u,h)}return h};return(u,h,g,x,a)=>{if(r==="values"&&(u.rows.isHidden(h)||u.cols.isHidden(g)||u.filteredRows?.has(h))||c!==null&&!m(u.style(h,g)))return!1;if(f===null)return!0;const y=x&G,S=u.protection&&x&T&&s.get(u.style(h,g)).hiddenFormula;if(r==="formulas"&&x&T&&!S)return f(e.editText(u,h,g));if(y===D)return!1;if(y===Y){if(a>=d.length)return f(i.get(a));let w=d[a];return w===0&&(w=f(i.get(a))?1:2,d[a]=w),w===1}const p=r==="formulas"&&!S?e.editText(u,h,g):n(y,a,s.get(u.style(h,g)));return f(p)}}const F=12,K=()=>new Promise(e=>setTimeout(e,0));class _{constructor(t){this.ctrl=t,this.start=performance.now()}async pause(){return performance.now()-this.start<F?!this.ctrl.cancelled:(this.ctrl.onProgress?.(),await K(),this.start=performance.now(),!this.ctrl.cancelled)}}const A=(e,t,n)=>e?n*1048576+t:t*16384+n;function Z(e){const t=[];for(let n=0;n<=e.maxCol;n++)e.columns[n]!==void 0&&t.push(n);return t}async function j(e,{byCols:t,dir:n,from:s,to:i,withEmpty:o},r,c){const f=Z(e);n<0&&f.reverse();const d=s===null?-n*(1/0):s,l=i===null?n*(1/0):i,m=n>0?a=>a>=d&&a<=l:a=>a<=d&&a>=l,u=o===!0;if(t){for(const a of f){const y=e.columns[a],S=n>0?0:y.length-1,p=n>0?y.length:-1;for(let w=S;w!==p;w+=n){const L=y[w];if(L===void 0)continue;const $=w<<M,{kinds:R,values:E,styles:O}=L;for(let k=n>0?0:I;k>=0&&k<=I;k+=n){const C=R[k];if(C===0&&!(u&&O!==null&&O[k]!==0))continue;const N=$+k;if(m(A(!0,N,a))&&r(N,a,C,E[k]))return!0}if(!await c.pause())return!1}}return!1}const h=e.maxRow>>>M,g=n>0?0:h,x=n>0?h+1:-1;for(let a=g;a!==x;a+=n){const y=[];for(const p of f){const w=e.columns[p][a];w!==void 0&&y.push(p,w)}if(y.length===0)continue;const S=a<<M;for(let p=n>0?0:I;p>=0&&p<=I;p+=n){const w=S+p;for(let L=0;L<y.length;L+=2){const $=y[L+1],R=$.kinds[p];if(R===0&&!(u&&$.styles!==null&&$.styles[p]!==0))continue;const E=y[L];if(m(A(!1,w,E))&&r(w,E,R,$.values[p]))return!0}}if(!await c.pause())return!1}return!1}function b(e,t){if(!t.author?.startsWith("tc="))return t;const n=t.author.slice(3),s=(e.threads??[]).filter(i=>i.id===n||i.parentId===n).map(i=>i.text).join(`
|
|
2
|
+
`);return{...t,text:s}}function z(e,t,n){if(!e.comments)return[];const s=[];for(const[i,o]of e.comments){const r=Math.floor(i/16384);s.push({row:r,col:i-r*16384,note:b(e,o)})}return s.sort((i,o)=>n*(A(t,i.row,i.col)-A(t,o.row,o.col))),s}function tt(e,t,n){const s=e.sheets.filter(r=>!r.hidden);if(t.within!=="workbook")return[e.sheet];const i=s.indexOf(e.sheet),o=[];for(let r=0;r<s.length;r++)o.push(s[(i+n*r+s.length*2)%s.length]);return o}const et=(e,t,n)=>e.some(s=>t>=s.r0&&t<=s.r1&&n>=s.c0&&n<=s.c1);function B(e,t,n){const s=V(e,t,n);if(!t.ranges)return s;const i=t.sheet??e.sheet;return(o,r,c,f,d)=>(o!==i||et(t.ranges,r,c))&&s(o,r,c,f,d)}async function at(e,t,n,s,i,o={}){const r=t.byColumns===!0,c=new _(o),f=tt(e,t,s),d=A(r,n.row,n.col);if(t.look==="notes")return nt(e,t,f,d,r,s);const l=B(e,t,i),m=t.what===""&&t.format!==null;let u=null;const h=async(g,x,a,y)=>(await j(g,{byCols:r,dir:s,from:x,to:a,withEmpty:m},(S,p,w,L)=>y&&A(r,S,p)===d||!l(g,S,p,w,L)?!1:(u={sheet:g,row:S,col:p},!0),c),u!==null||o.cancelled===!0);if(await h(f[0],d,null,!0))return u;for(let g=1;g<f.length;g++)if(await h(f[g],null,null,!1))return u;return await h(f[0],null,d,!1),u}function nt(e,t,n,s,i,o){const r=v(t.what,t),c=l=>r(l.note.text??""),f=z(n[0],i,o),d=o>0?l=>l>s:l=>l<s;for(const l of f)if(d(A(i,l.row,l.col))&&c(l))return{sheet:n[0],row:l.row,col:l.col};for(let l=1;l<n.length;l++)for(const m of z(n[l],i,o))if(c(m))return{sheet:n[l],row:m.row,col:m.col};for(const l of f)if(!d(A(i,l.row,l.col))&&c(l))return{sheet:n[0],row:l.row,col:l.col};return null}class st{constructor(t){this.cap=t,this.count=0,this.overflow=!1,this.size=Math.min(t,1024),this.rows=new Uint32Array(this.size),this.cols=new Uint16Array(this.size),this.sheets=new Uint16Array(this.size),this.sheetList=[]}push(t,n,s){if(this.count===this.cap)return this.overflow=!0,!1;if(this.count===this.size){this.size=Math.min(this.cap,this.size*2);const r=(c,f)=>{const d=new c(this.size);return d.set(f),d};this.rows=r(Uint32Array,this.rows),this.cols=r(Uint16Array,this.cols),this.sheets=r(Uint16Array,this.sheets)}let i=this.sheetList.indexOf(t);i<0&&(i=this.sheetList.length,this.sheetList.push(t));const o=this.count++;return this.rows[o]=n,this.cols[o]=s,this.sheets[o]=i,!0}}async function rt(e,t,n,s={},i=1e5){const o=new st(i),r=t.byColumns===!0,c=new _(s),f=t.sheet?[t.sheet]:t.within==="workbook"?e.sheets.filter(m=>!m.hidden):[e.sheet];if(t.look==="notes"){const m=v(t.what,t);for(const u of f)for(const h of z(u,r,1))m(h.note.text??"")&&o.push(u,h.row,h.col);return o}const d=B(e,t,n),l=t.what===""&&t.format!==null;for(const m of f)if(await j(m,{byCols:r,dir:1,from:null,to:null,withEmpty:l},(h,g,x,a)=>d(m,h,g,x,a)?!o.push(m,h,g):!1,c)||s.cancelled)break;return o}function it(e,t,n,s,i,o,r=null){const{sheet:c}=t;let f=!1;if(i!==null){const d=c.formula(n,s);if(d&&d.t==="array")return!1;const l=c.kind(n,s);if(l&X&&!(l&T))return!1;const m=e.editText(c,n,s),u=i(m);if(u!==m&&u.startsWith("=")&&u.length>1&&!ot(e,u.slice(1)))return r!==null&&r.invalid++,!1;u!==m&&(e.setInput(t,n,s,u),f=!0)}return o&&(f||t.saveCell(n,s),c.setStyle(n,s,e.styles.derive(c.style(n,s),o)),f=!0),f}async function ht(e,t,n,s,i,o={}){const r=await rt(e,{...t,look:"formulas"},i,o,4294967295);if(o.cancelled)return{count:0,sheets:0,cancelled:!0};const c=t.what===""?null:q(t.what,n??"",t);let f=0,d=0;const l={locked:0,invalid:0},m=[];for(let u=0;u<r.sheetList.length;u++){const h=r.sheetList[u],g=[];let x=0,a=0;for(;a<r.count;){const y=performance.now(),S=e.runSlice(h,"replace",p=>{for(let w=0;a<r.count&&!(w%1024===1023&&performance.now()-y>F);a++,w++){if(r.sheets[a]!==u)continue;const L=r.rows[a],$=r.cols[a];if(h.protection&&!J(e,h,L,$)){l.locked++;continue}it(e,p,L,$,c,s,l)&&x++}});if(S!==null&&g.push(S),o.onProgress?.(),a<r.count&&await K(),o.cancelled)return e.rollbackSlices([...m,...g]),{count:0,sheets:0,cancelled:!0}}m.push(...g),x>0&&(f+=x,d++)}return e.pushFolded(m,"replace",e.sheet),{count:f,sheets:d,...l}}function ot(e,t){if(!e.engine)return!W(t);try{return e.engine.validate(t),!0}catch{return!1}}export{st as FoundList,rt as findAll,at as findNext,v as makeMatcher,q as makeReplacer,V as makeTest,ft as regexProblem,ht as replaceAll,it as replaceInCell};
|
package/cells/find.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{overlayRoot as S}from"../api/overlay.js";import{el as l,openFormatCells as T}from"../ui/dialogs.js";import{cellRef as _,MAX_COLS as L,MAX_ROWS as B}from"../core/address.js";import{KIND_MASK as E}from"../core/sheet.js";import{formatCount as g}from"../core/numfmt.js";import{findAll as $,findNext as b,makeReplacer as W,makeTest as O,replaceAll as N,replaceInCell as H}from"./find-engine.js";import{ensureBookCss as D}from"./book-css.js";import{svgNode as P}from"./format-tabs.js";import{t as a,tc as F}from"../i18n/index.js";const m=20,j=["fontName","fontSize","bold","italic","underline","strike","color","fill","pattern","borders","numFmt","hAlign","vAlign","wrap","indent","rotation","shrink","unlocked","hiddenFormula"];let p=null,v=null;const w=[];function R(c){const t=l("span",{class:"bk-fmt-chip",textContent:c?a("Preview*"):a("No Format Set")});return y(t,c),t}function y(c,t){c.textContent=t?a("Preview*"):a("No Format Set"),c.style.background=t?.fill??"",c.style.color=t?.color??"",c.style.fontWeight=t?.bold?"700":"",c.style.fontStyle=t?.italic?"italic":"",c.style.textDecoration=t?.underline?"underline":""}function I(c){const t={};for(const e of j)c[e]!==void 0&&c[e]!==null&&c[e]!==!1&&c[e]!==0&&c[e]!=="General"&&(t[e]=c[e]);return t}class V{constructor(t){this.app=t,this.findFormat=null,this.replaceFormat=null,this.ctrl=null,this.results=null,this.order=null,this.activeRow=-1,this.sort={key:null,dir:1},this._build()}_build(){D();const t=(i,d)=>{const u=l("select",{class:"dlg-input","aria-label":a(i)});for(const[f,k]of d)u.append(l("option",{value:k,textContent:a(f)}));return u},e=(i,d,u=!1)=>l("button",{class:`dlg-btn${u?" primary":""}`,type:"button",textContent:a(i),on:{click:d}}),s=l("button",{type:"button",class:"bk-find-history",title:a("Recent searches"),"aria-label":a("Recent searches"),on:{click:i=>this.app.ribbon.openMenu(i.currentTarget,{items:w.length?w.map(d=>[d,()=>{this.what.value=d,this.what.focus()},{raw:!0}]):[["No recent searches",()=>{}]]})}},P('<svg width="9" height="6" viewBox="0 0 9 6" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M1 1l3.5 3.5L8 1"/></svg>'));this.what=l("input",{class:"dlg-input","aria-label":a("Find what"),spellcheck:!1}),this.repl=l("input",{class:"dlg-input","aria-label":a("Replace with"),spellcheck:!1}),this.within=t("Within",[["Sheet","sheet"],["Workbook","workbook"]]),this.searchBy=t("Search",[["By Rows","rows"],["By Columns","cols"]]),this.look=t("Look in",[["Formulas","formulas"],["Values","values"],["Notes","notes"]]),this.matchCase=l("input",{type:"checkbox","aria-label":a("Match case")}),this.whole=l("input",{type:"checkbox","aria-label":a("Match entire cell contents")}),this.status=l("div",{class:"dlg-status",role:"status"}),this.progress=l("div",{class:"bk-progress",hidden:!0},l("div")),this.findChip=R(null),this.replaceChip=R(null);const o=i=>e("Format…",d=>this._formatMenu(i,d.currentTarget)),r=(...i)=>l("span",{class:"dlg-row bk-find-fmt",hidden:!0},...i);this.fmtFind=r(this.findChip,o("find")),this.fmtReplace=r(this.replaceChip,o("replace")),this.replaceRow=[l("span",{textContent:a("Replace with:")}),l("div",{class:"dlg-row"},this.repl,this.fmtReplace)],this.modeFind=l("button",{type:"button",role:"tab",class:"dlg-tab",textContent:a("Find"),on:{click:()=>this.setMode(!1)}}),this.modeReplace=l("button",{type:"button",role:"tab",class:"dlg-tab",textContent:a("Replace"),on:{click:()=>this.setMode(!0)}}),this.opts=l("div",{class:"bk-find-opts",hidden:!0},l("span",{textContent:a("Within:")}),this.within,l("label",{class:"dlg-row dlg-check"},this.matchCase,` ${a("Match case")}`),l("span",{textContent:a("Search:")}),this.searchBy,l("label",{class:"dlg-row dlg-check"},this.whole,` ${a("Match entire cell contents")}`),l("span",{textContent:a("Look in:")}),this.look,l("span")),this.btnReplaceAll=e("Replace All",()=>this.doReplaceAll()),this.btnReplace=e("Replace",()=>this.doReplace()),this.resultsHost=l("div",{class:"bk-results",hidden:!0});const n=l("h2",{class:"bk-panel-title",textContent:a("Find & Replace")});this.node=l("div",{class:"bk-panel xl-dlg",role:"dialog","aria-label":a("Find & Replace")},n,l("div",{class:"xl-tabbed"},l("div",{class:"dlg-tabs",role:"tablist"},this.modeFind,this.modeReplace),l("div",{class:"xl-box bk-find-box"},l("div",{class:"bk-find-grid"},l("span",{textContent:a("Find what:")}),l("div",{class:"dlg-row"},l("span",{class:"bk-find-field"},this.what,s),this.fmtFind),...this.replaceRow),this.opts,this.progress,this.resultsHost,l("div",{class:"bk-find-low"},this.status,e("Options",()=>this.toggleOptions())))),l("div",{class:"bk-find-foot"},this.btnReplaceAll,this.btnReplace,e("Find All",()=>this.doFindAll()),e(F("find","Previous"),()=>this.doFind(-1)),e(F("find","Next"),()=>this.doFind(1),!0),e("Close",()=>this.close()))),this.node.addEventListener("keydown",i=>{i.stopPropagation(),i.key==="Escape"?(i.preventDefault(),this.ctrl?this.cancel():this.close()):i.key==="Enter"&&i.target.tagName!=="BUTTON"&&(i.preventDefault(),this.doFind(i.shiftKey?-1:1))}),n.addEventListener("pointerdown",i=>{i.preventDefault(),n.setPointerCapture(i.pointerId);const d=this.node.getBoundingClientRect(),u=i.clientX-d.left,f=i.clientY-d.top,k=x=>{this.node.style.left=`${Math.max(0,Math.min(window.innerWidth-80,x.clientX-u))}px`,this.node.style.top=`${Math.max(0,Math.min(window.innerHeight-40,x.clientY-f))}px`},C=()=>{n.removeEventListener("pointermove",k),n.removeEventListener("pointerup",C)};n.addEventListener("pointermove",k),n.addEventListener("pointerup",C)}),this.node.style.right="24px",this.node.style.top="120px",S().append(this.node);const h=this.node.getBoundingClientRect();this.node.style.left=`${h.left}px`,this.node.style.right="auto"}toggleOptions(){const t=this.opts.hidden||!!(this.findFormat||this.replaceFormat);this.opts.hidden=!t,this.fmtFind.hidden=!t,this.fmtReplace.hidden=!t}setMode(t){this.withReplace=t,this.modeFind.setAttribute("aria-selected",String(!t)),this.modeReplace.setAttribute("aria-selected",String(t));for(const e of this.replaceRow)e.hidden=!t;this.btnReplaceAll.hidden=!t,this.btnReplace.hidden=!t,t&&(this.look.value="formulas"),this.look.querySelector('option[value="values"]').disabled=t,this.look.querySelector('option[value="notes"]').disabled=t}focus(){this.what.focus(),this.what.select()}close(){this.cancel(),(this.what.value!==""||this.findFormat)&&(v=this._options(!1)),this.node.remove(),p=null,this.app.controller.pickCell=null,this.app.controller.focusGrid()}cancel(){this.ctrl&&(this.ctrl.cancelled=!0)}_formatMenu(t,e){const{app:s}=this,o=r=>{t==="find"?(this.findFormat=r,y(this.findChip,r)):(this.replaceFormat=r,y(this.replaceChip,r))};s.ribbon.openMenu(e,{items:[["Format…",()=>T(s,"Number",{onPick:r=>o(Object.keys(r).length?r:null)})],["Choose Format from Cell…",()=>{this.status.textContent=a("Click the cell whose format you want."),s.controller.pickCell=(r,n)=>{const{book:h}=s;o(I(h.styles.get(h.sheet.style(r,n)))),this.status.textContent=""}}],["Clear Format",()=>o(null)]]})}_options(t=!0){const{app:e}=this,s=e.grid.selection,o=s.ranges.length===1&&s.ranges[0].r0===s.ranges[0].r1&&s.ranges[0].c0===s.ranges[0].c1,r=e.book.sheet.mergeAt(s.row,s.col),n=o||r&&s.ranges.length===1;return{what:this.what.value,matchCase:this.matchCase.checked,whole:this.whole.checked,look:this.look.value,format:this.findFormat,byColumns:this.searchBy.value==="cols",within:this.within.value,ranges:t&&!n?s.ranges:null}}_display(){const{grid:t}=this.app;return(e,s,o)=>t.displayText(e,s,o)}_ready(t){if(t.what===""&&t.format===null)return this.status.textContent=a("Enter what to find, or choose a format."),this.what.focus(),!1;if(t.what!==""){const e=w.indexOf(t.what);e>=0&&w.splice(e,1),w.unshift(t.what),w.length=Math.min(w.length,12)}return!0}_begin(){this.cancel();const t={cancelled:!1};this.ctrl=t;const e=this.progress,s=performance.now();return t.onProgress=()=>{if(performance.now()-s>150){e.hidden=!1;const o=e.firstChild;o.style.width=`${((performance.now()-s)/40%100).toFixed(0)}%`,this.status.textContent=a("Searching… Press Esc to stop.")}},t}_end(t){this.ctrl===t&&(this.ctrl=null),this.progress.hidden=!0}_jump(t){const{app:e}=this,{book:s}=e;t.sheet!==s.sheet&&(s.selectedSheets&&!s.selectedSheets.has(t.sheet)&&(s.selectedSheets=null),e.switchSheet(s.sheets.indexOf(t.sheet)));const o=e.grid.selection;o.ranges.some(n=>(n.r0!==n.r1||n.c0!==n.c1)&&t.row>=n.r0&&t.row<=n.r1&&t.col>=n.c0&&t.col<=n.c1)?(e.grid.setSelection({ranges:o.ranges,row:t.row,col:t.col}),e.grid.ensureVisible(t.row,t.col)):e.controller.moveTo(t.row,t.col)}async doFind(t){const e=this._options();if(!this._ready(e))return null;const s=this._begin(),o=performance.now(),r=this.app.grid.selection,n=await b(this.app.book,e,{row:r.row,col:r.col},t,this._display(),s);return this._end(s),s.cancelled?(this.status.textContent=a("Stopped."),null):(this.lastMs=performance.now()-o,n?(this._jump(n),this.status.textContent=`${n.sheet===this.app.book.sheet?"":`${n.sheet.name}!`}${_(n.row,n.col)}`,n):(this.status.textContent=a("We couldn't find what you were looking for."),null))}async doFindAll(){const t=this._options();if(!this._ready(t))return;const e=this._begin(),s=performance.now(),o=await $(this.app.book,t,this._display(),e);if(this._end(e),e.cancelled){this.status.textContent=a("Stopped.");return}this.lastMs=performance.now()-s,this.results=o,this.order=new Uint32Array(o.count);for(let n=0;n<o.count;n++)this.order[n]=n;this.sort={key:null,dir:1},this.activeRow=-1;const r=g(o.count);this.status.textContent=o.overflow?a("The first {shown} cells found. There are more.",{shown:r}):a("{shown} cells found.",{count:o.count,shown:r}),this._renderResults()}_cellValue(t){const{book:e,grid:s}=this.app,{results:o}=this,r=o.sheetList[o.sheets[t]],n=o.rows[t],h=o.cols[t];if(this.look.value==="notes")return r.comments?.get(n*L+h)?.text??"";const i=r.kind(n,h)&E;return s.displayText(i,r.value(n,h),e.styles.get(r.style(n,h))).replace(/\u0001.?\u0001/g," ")}_cellFormula(t){const{book:e}=this.app,{results:s}=this,o=e.editText(s.sheetList[s.sheets[t]],s.rows[t],s.cols[t]);return o[0]==="="||o.startsWith("{=")?o:""}_sortBy(t){const{results:e}=this;if(!e)return;const s=this.sort.key===t?-this.sort.dir:1;this.sort={key:t,dir:s};const o={sheet:i=>e.sheetList[e.sheets[i]].name,cell:i=>e.cols[i]*B+e.rows[i],value:i=>this._cellValue(i),formula:i=>this._cellFormula(i)}[t],r=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),n=new Array(e.count);for(let i=0;i<e.count;i++)n[i]=o(i);const h=Array.from(this.order);h.sort((i,d)=>s*(typeof n[i]=="number"?n[i]-n[d]:r.compare(n[i],n[d]))),this.order=Uint32Array.from(h),this._renderResults()}_renderResults(){const{results:t}=this,e=(h,i)=>l("button",{type:"button",textContent:`${a(h)}${this.sort.key===i?this.sort.dir>0?" ▴":" ▾":""}`,on:{click:()=>this._sortBy(i)}}),s=l("div",{class:"bk-results-body",tabIndex:0}),o=l("div",{style:`height:${t.count*m}px`}),r=l("div");s.append(o,r);const n=()=>{const h=Math.floor(s.scrollTop/m),i=Math.min(t.count,h+Math.ceil(s.clientHeight/m)+2),d=[];for(let u=h;u<i;u++){const f=this.order[u],k=l("div",{class:`bk-results-row${u===this.activeRow?" active":""}`,style:`top:${u*m}px`,on:{click:()=>this._pick(u)}},l("span",{textContent:t.sheetList[t.sheets[f]].name}),l("span",{textContent:_(t.rows[f],t.cols[f])}),l("span",{textContent:this._cellValue(f)}),l("span",{textContent:this._cellFormula(f)}));d.push(k)}r.replaceChildren(...d)};this.drawResults=n,s.addEventListener("scroll",n,{passive:!0}),s.addEventListener("keydown",h=>{h.key!=="ArrowDown"&&h.key!=="ArrowUp"||(h.preventDefault(),this._pick(Math.max(0,Math.min(t.count-1,this.activeRow+(h.key==="ArrowDown"?1:-1)))))}),this.resultsHost.replaceChildren(l("div",{class:"bk-results-head"},e("Sheet","sheet"),e("Cell","cell"),e("Value","value"),e("Formula","formula")),s),this.resultsHost.hidden=t.count===0,n(),this.resultsBody=s}_pick(t){const{results:e}=this,s=this.order[t];this.activeRow=t,this._jump({sheet:e.sheetList[e.sheets[s]],row:e.rows[s],col:e.cols[s]});const o=this.resultsBody;t*m<o.scrollTop?o.scrollTop=t*m:(t+1)*m>o.scrollTop+o.clientHeight&&(o.scrollTop=(t+1)*m-o.clientHeight),this.drawResults()}async doReplace(){const t=this._options(!1);if(!this._ready(t))return;const{app:e}=this,{book:s}=e,{sheet:o}=s,{row:r,col:n}=e.grid.selection;if(await b(s,{...t,within:"sheet",look:"formulas"},{row:r,col:n},1,this._display(),{})!==null&&this._matchesHere(t,r,n))if(o.protection&&s.styles.get(o.style(r,n)).unlocked!==!0)this.status.textContent=a("This cell is locked.");else{const d=t.what===""?null:W(t.what,this.repl.value,t),u={invalid:0};if(s.transact("replace",f=>{H(s,f,r,n,d,this.replaceFormat,u)}),e.grid.invalidate(),u.invalid>0){this.status.textContent=a("There's a problem with this formula after the replacement, so the cell was left as it was.");return}}await this.doFind(1)}_matchesHere(t,e,s){const{book:o}=this.app,{sheet:r}=o;return O(o,{...t,look:"formulas"},this._display())(r,e,s,r.kind(e,s),r.value(e,s))}async doReplaceAll(){const t=this._options();if(!this._ready(t))return;const e=this._begin(),s=performance.now(),o=await N(this.app.book,t,this.repl.value,this.replaceFormat,this._display(),e);if(this._end(e),this.lastMs=performance.now()-s,o.cancelled){this.status.textContent=a("Stopped; nothing was replaced.");return}const r={count:o.count,shown:g(o.count),sheets:o.sheets},n=[o.count===0&&o.locked===0&&o.invalid===0?a("We couldn't find anything to replace."):o.sheets>1?a("All done. We made {shown} replacements on {sheets} sheets.",r):a("All done. We made {shown} replacements.",r)];o.locked>0&&n.push(a("{shown} locked cells on protected sheets were left as they were.",{count:o.locked,shown:g(o.locked)})),o.invalid>0&&n.push(a("{shown} cells were left as they were, as the replacement would break their formulas.",{count:o.invalid,shown:g(o.invalid)})),this.status.textContent=n.join(" "),this.app.grid.invalidate(),this.app.afterCommand(),this.what.focus()}}function tt(c,t){if(!p&&v){const e=c.grid.selection;return b(c.book,v,{row:e.row,col:e.col},t,(s,o,r)=>c.grid.displayText(s,o,r),{}).then(s=>s?(s.sheet&&s.sheet!==c.book.sheet&&c.switchSheet(c.book.sheets.indexOf(s.sheet)),c.controller.moveTo(s.row,s.col),s):(c.shell?.setStatus(a("We couldn't find what you were looking for.")),null))}return p?(M(c),p.doFind(t)):(U(c),null)}const A=new WeakSet;function M(c){p.app=c,!A.has(c)&&(A.add(c),c.signal?.addEventListener("abort",()=>{p?.app===c&&(p.cancel(),p.node.remove(),p=null)},{once:!0}))}function U(c,t=!1){p??=new V(c),M(c),p.setMode(t),p.focus();const e=p;return setTimeout(()=>{p===e&&document.activeElement!==e.what&&!e.node.contains(document.activeElement)&&e.focus()},0),p}export{tt as findAgain,U as openFind};
|
|
1
|
+
import{cellEditable as T}from"../core/protection.js";import{overlayRoot as L}from"../api/overlay.js";import{el as l,openFormatCells as B}from"../ui/dialogs.js";import{cellRef as _,MAX_COLS as E,MAX_ROWS as $}from"../core/address.js";import{KIND_MASK as W}from"../core/sheet.js";import{formatCount as k}from"../core/numfmt.js";import{findAll as O,findNext as v,makeReplacer as N,makeTest as H,regexProblem as F,replaceAll as P,replaceInCell as D}from"./find-engine.js";import{ensureBookCss as j}from"./book-css.js";import{svgNode as I}from"./format-tabs.js";import{t as r,tc as R}from"../i18n/index.js";const m=20,V=["fontName","fontSize","bold","italic","underline","strike","color","fill","pattern","borders","numFmt","hAlign","vAlign","wrap","indent","rotation","shrink","unlocked","hiddenFormula"];let p=null,b=null;const w=[];function M(c){const t=l("span",{class:"bk-fmt-chip",textContent:c?r("Preview*"):r("No Format Set")});return y(t,c),t}function y(c,t){c.textContent=t?r("Preview*"):r("No Format Set"),c.style.background=t?.fill??"",c.style.color=t?.color??"",c.style.fontWeight=t?.bold?"700":"",c.style.fontStyle=t?.italic?"italic":"",c.style.textDecoration=t?.underline?"underline":""}function U(c){const t={};for(const e of V)c[e]!==void 0&&c[e]!==null&&c[e]!==!1&&c[e]!==0&&c[e]!=="General"&&(t[e]=c[e]);return t}class X{constructor(t){this.app=t,this.findFormat=null,this.replaceFormat=null,this.ctrl=null,this.results=null,this.order=null,this.activeRow=-1,this.sort={key:null,dir:1},this._build()}_build(){j();const t=(i,d)=>{const u=l("select",{class:"dlg-input","aria-label":r(i)});for(const[f,g]of d)u.append(l("option",{value:g,textContent:r(f)}));return u},e=(i,d,u=!1)=>l("button",{class:`dlg-btn${u?" primary":""}`,type:"button",textContent:r(i),on:{click:d}}),o=l("button",{type:"button",class:"bk-find-history",title:r("Recent searches"),"aria-label":r("Recent searches"),on:{click:i=>this.app.ribbon.openMenu(i.currentTarget,{items:w.length?w.map(d=>[d,()=>{this.what.value=d,this.what.focus()},{raw:!0}]):[["No recent searches",()=>{}]]})}},I('<svg width="9" height="6" viewBox="0 0 9 6" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M1 1l3.5 3.5L8 1"/></svg>'));this.what=l("input",{class:"dlg-input","aria-label":r("Find what"),spellcheck:!1}),this.repl=l("input",{class:"dlg-input","aria-label":r("Replace with"),spellcheck:!1}),this.within=t("Within",[["Sheet","sheet"],["Workbook","workbook"]]),this.searchBy=t("Search",[["By Rows","rows"],["By Columns","cols"]]),this.look=t("Look in",[["Formulas","formulas"],["Values","values"],["Notes","notes"]]),this.matchCase=l("input",{type:"checkbox","aria-label":r("Match case")}),this.whole=l("input",{type:"checkbox","aria-label":r("Match entire cell contents")}),this.regex=l("input",{type:"checkbox","aria-label":r("Match using regular expressions")}),this.status=l("div",{class:"dlg-status",role:"status"}),this.progress=l("div",{class:"bk-progress",hidden:!0},l("div")),this.findChip=M(null),this.replaceChip=M(null);const s=i=>e("Format…",d=>this._formatMenu(i,d.currentTarget)),a=(...i)=>l("span",{class:"dlg-row bk-find-fmt",hidden:!0},...i);this.fmtFind=a(this.findChip,s("find")),this.fmtReplace=a(this.replaceChip,s("replace")),this.replaceRow=[l("span",{textContent:r("Replace with:")}),l("div",{class:"dlg-row"},this.repl,this.fmtReplace)],this.modeFind=l("button",{type:"button",role:"tab",class:"dlg-tab",textContent:r("Find"),on:{click:()=>this.setMode(!1)}}),this.modeReplace=l("button",{type:"button",role:"tab",class:"dlg-tab",textContent:r("Replace"),on:{click:()=>this.setMode(!0)}}),this.opts=l("div",{class:"bk-find-opts",hidden:!0},l("span",{textContent:r("Within:")}),this.within,l("label",{class:"dlg-row dlg-check"},this.matchCase,` ${r("Match case")}`),l("span",{textContent:r("Search:")}),this.searchBy,l("label",{class:"dlg-row dlg-check"},this.whole,` ${r("Match entire cell contents")}`),l("span",{textContent:r("Look in:")}),this.look,l("label",{class:"dlg-row dlg-check"},this.regex,` ${r("Match using regular expressions")}`)),this.btnReplaceAll=e("Replace All",()=>this.doReplaceAll()),this.btnReplace=e("Replace",()=>this.doReplace()),this.resultsHost=l("div",{class:"bk-results",hidden:!0});const n=l("h2",{class:"bk-panel-title",textContent:r("Find & Replace")});this.node=l("div",{class:"bk-panel xl-dlg",role:"dialog","aria-label":r("Find & Replace")},n,l("div",{class:"xl-tabbed"},l("div",{class:"dlg-tabs",role:"tablist"},this.modeFind,this.modeReplace),l("div",{class:"xl-box bk-find-box"},l("div",{class:"bk-find-grid"},l("span",{textContent:r("Find what:")}),l("div",{class:"dlg-row"},l("span",{class:"bk-find-field"},this.what,o),this.fmtFind),...this.replaceRow),this.opts,this.progress,this.resultsHost,l("div",{class:"bk-find-low"},this.status,e("Options",()=>this.toggleOptions())))),l("div",{class:"bk-find-foot"},this.btnReplaceAll,this.btnReplace,e("Find All",()=>this.doFindAll()),e(R("find","Previous"),()=>this.doFind(-1)),e(R("find","Next"),()=>this.doFind(1),!0),e("Close",()=>this.close()))),this.node.addEventListener("keydown",i=>{i.stopPropagation(),i.key==="Escape"?(i.preventDefault(),this.ctrl?this.cancel():this.close()):i.key==="Enter"&&i.target.tagName!=="BUTTON"&&(i.preventDefault(),this.doFind(i.shiftKey?-1:1))}),n.addEventListener("pointerdown",i=>{i.preventDefault(),n.setPointerCapture(i.pointerId);const d=this.node.getBoundingClientRect(),u=i.clientX-d.left,f=i.clientY-d.top,g=C=>{this.node.style.left=`${Math.max(0,Math.min(window.innerWidth-80,C.clientX-u))}px`,this.node.style.top=`${Math.max(0,Math.min(window.innerHeight-40,C.clientY-f))}px`},x=()=>{n.removeEventListener("pointermove",g),n.removeEventListener("pointerup",x)};n.addEventListener("pointermove",g),n.addEventListener("pointerup",x)}),this.node.style.right="24px",this.node.style.top="120px",L().append(this.node);const h=this.node.getBoundingClientRect();this.node.style.left=`${h.left}px`,this.node.style.right="auto"}toggleOptions(){const t=this.opts.hidden||!!(this.findFormat||this.replaceFormat);this.opts.hidden=!t,this.fmtFind.hidden=!t,this.fmtReplace.hidden=!t}setMode(t){this.withReplace=t,this.modeFind.setAttribute("aria-selected",String(!t)),this.modeReplace.setAttribute("aria-selected",String(t));for(const e of this.replaceRow)e.hidden=!t;this.btnReplaceAll.hidden=!t,this.btnReplace.hidden=!t,t&&(this.look.value="formulas"),this.look.querySelector('option[value="values"]').disabled=t,this.look.querySelector('option[value="notes"]').disabled=t}focus(){this.what.focus(),this.what.select()}close(){this.cancel(),(this.what.value!==""||this.findFormat)&&(b=this._options(!1)),this.node.remove(),p=null,this.app.controller.pickCell=null,this.app.controller.focusGrid()}cancel(){this.ctrl&&(this.ctrl.cancelled=!0)}_formatMenu(t,e){const{app:o}=this,s=a=>{t==="find"?(this.findFormat=a,y(this.findChip,a)):(this.replaceFormat=a,y(this.replaceChip,a))};o.ribbon.openMenu(e,{items:[["Format…",()=>B(o,"Number",{onPick:a=>s(Object.keys(a).length?a:null)})],["Choose Format from Cell…",()=>{this.status.textContent=r("Click the cell whose format you want."),o.controller.pickCell=(a,n)=>{const{book:h}=o;s(U(h.styles.get(h.sheet.style(a,n)))),this.status.textContent=""}}],["Clear Format",()=>s(null)]]})}_options(t=!0){const{app:e}=this,o=e.grid.selection,s=o.ranges.length===1&&o.ranges[0].r0===o.ranges[0].r1&&o.ranges[0].c0===o.ranges[0].c1,a=e.book.sheet.mergeAt(o.row,o.col),n=s||a&&o.ranges.length===1;return{what:this.what.value,matchCase:this.matchCase.checked,whole:this.whole.checked,regex:this.regex.checked,look:this.look.value,format:this.findFormat,byColumns:this.searchBy.value==="cols",within:this.within.value,ranges:t&&!n?o.ranges:null}}_display(){const{grid:t}=this.app;return(e,o,s)=>t.displayText(e,o,s)}_ready(t){if(t.what===""&&t.format===null)return this.status.textContent=r("Enter what to find, or choose a format."),this.what.focus(),!1;const e=t.regex?F(t.what):null;if(e!==null)return this.status.textContent=r("This regular expression isn't valid: {problem}",{problem:e}),this.what.focus(),!1;if(t.what!==""){const o=w.indexOf(t.what);o>=0&&w.splice(o,1),w.unshift(t.what),w.length=Math.min(w.length,12)}return!0}_begin(){this.cancel();const t={cancelled:!1};this.ctrl=t;const e=this.progress,o=performance.now();return t.onProgress=()=>{if(performance.now()-o>150){e.hidden=!1;const s=e.firstChild;s.style.width=`${((performance.now()-o)/40%100).toFixed(0)}%`,this.status.textContent=r("Searching… Press Esc to stop.")}},t}_end(t){this.ctrl===t&&(this.ctrl=null),this.progress.hidden=!0}_jump(t){const{app:e}=this,{book:o}=e;t.sheet!==o.sheet&&(o.selectedSheets&&!o.selectedSheets.has(t.sheet)&&(o.selectedSheets=null),e.switchSheet(o.sheets.indexOf(t.sheet)));const s=e.grid.selection;s.ranges.some(n=>(n.r0!==n.r1||n.c0!==n.c1)&&t.row>=n.r0&&t.row<=n.r1&&t.col>=n.c0&&t.col<=n.c1)?(e.grid.setSelection({ranges:s.ranges,row:t.row,col:t.col}),e.grid.ensureVisible(t.row,t.col)):e.controller.moveTo(t.row,t.col)}async doFind(t){const e=this._options();if(!this._ready(e))return null;const o=this._begin(),s=performance.now(),a=this.app.grid.selection,n=await v(this.app.book,e,{row:a.row,col:a.col},t,this._display(),o);return this._end(o),o.cancelled?(this.status.textContent=r("Stopped."),null):(this.lastMs=performance.now()-s,n?(this._jump(n),this.status.textContent=`${n.sheet===this.app.book.sheet?"":`${n.sheet.name}!`}${_(n.row,n.col)}`,n):(this.status.textContent=r("We couldn't find what you were looking for."),null))}async doFindAll(){const t=this._options();if(!this._ready(t))return;const e=this._begin(),o=performance.now(),s=await O(this.app.book,t,this._display(),e);if(this._end(e),e.cancelled){this.status.textContent=r("Stopped.");return}this.lastMs=performance.now()-o,this.results=s,this.order=new Uint32Array(s.count);for(let n=0;n<s.count;n++)this.order[n]=n;this.sort={key:null,dir:1},this.activeRow=-1;const a=k(s.count);this.status.textContent=s.overflow?r("The first {shown} cells found. There are more.",{shown:a}):r("{shown} cells found.",{count:s.count,shown:a}),this._renderResults()}_cellValue(t){const{book:e,grid:o}=this.app,{results:s}=this,a=s.sheetList[s.sheets[t]],n=s.rows[t],h=s.cols[t];if(this.look.value==="notes")return a.comments?.get(n*E+h)?.text??"";const i=a.kind(n,h)&W;return o.displayText(i,a.value(n,h),e.styles.get(a.style(n,h))).replace(/\u0001.?\u0001/g," ")}_cellFormula(t){const{book:e}=this.app,{results:o}=this,s=e.editText(o.sheetList[o.sheets[t]],o.rows[t],o.cols[t]);return s[0]==="="||s.startsWith("{=")?s:""}_sortBy(t){const{results:e}=this;if(!e)return;const o=this.sort.key===t?-this.sort.dir:1;this.sort={key:t,dir:o};const s={sheet:i=>e.sheetList[e.sheets[i]].name,cell:i=>e.cols[i]*$+e.rows[i],value:i=>this._cellValue(i),formula:i=>this._cellFormula(i)}[t],a=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),n=new Array(e.count);for(let i=0;i<e.count;i++)n[i]=s(i);const h=Array.from(this.order);h.sort((i,d)=>o*(typeof n[i]=="number"?n[i]-n[d]:a.compare(n[i],n[d]))),this.order=Uint32Array.from(h),this._renderResults()}_renderResults(){const{results:t}=this,e=(h,i)=>l("button",{type:"button",textContent:`${r(h)}${this.sort.key===i?this.sort.dir>0?" ▴":" ▾":""}`,on:{click:()=>this._sortBy(i)}}),o=l("div",{class:"bk-results-body",tabIndex:0}),s=l("div",{style:`height:${t.count*m}px`}),a=l("div");o.append(s,a);const n=()=>{const h=Math.floor(o.scrollTop/m),i=Math.min(t.count,h+Math.ceil(o.clientHeight/m)+2),d=[];for(let u=h;u<i;u++){const f=this.order[u],g=l("div",{class:`bk-results-row${u===this.activeRow?" active":""}`,style:`top:${u*m}px`,on:{click:()=>this._pick(u)}},l("span",{textContent:t.sheetList[t.sheets[f]].name}),l("span",{textContent:_(t.rows[f],t.cols[f])}),l("span",{textContent:this._cellValue(f)}),l("span",{textContent:this._cellFormula(f)}));d.push(g)}a.replaceChildren(...d)};this.drawResults=n,o.addEventListener("scroll",n,{passive:!0}),o.addEventListener("keydown",h=>{h.key!=="ArrowDown"&&h.key!=="ArrowUp"||(h.preventDefault(),this._pick(Math.max(0,Math.min(t.count-1,this.activeRow+(h.key==="ArrowDown"?1:-1)))))}),this.resultsHost.replaceChildren(l("div",{class:"bk-results-head"},e("Sheet","sheet"),e("Cell","cell"),e("Value","value"),e("Formula","formula")),o),this.resultsHost.hidden=t.count===0,n(),this.resultsBody=o}_pick(t){const{results:e}=this,o=this.order[t];this.activeRow=t,this._jump({sheet:e.sheetList[e.sheets[o]],row:e.rows[o],col:e.cols[o]});const s=this.resultsBody;t*m<s.scrollTop?s.scrollTop=t*m:(t+1)*m>s.scrollTop+s.clientHeight&&(s.scrollTop=(t+1)*m-s.clientHeight),this.drawResults()}async doReplace(){const t=this._options(!1);if(!this._ready(t))return;const{app:e}=this,{book:o}=e,{sheet:s}=o,{row:a,col:n}=e.grid.selection;if(await v(o,{...t,within:"sheet",look:"formulas"},{row:a,col:n},1,this._display(),{})!==null&&this._matchesHere(t,a,n))if(s.protection&&!T(o,s,a,n))this.status.textContent=r("This cell is locked.");else{const d=t.what===""?null:N(t.what,this.repl.value,t),u={invalid:0};if(o.transact("replace",f=>{D(o,f,a,n,d,this.replaceFormat,u)}),e.grid.invalidate(),u.invalid>0){this.status.textContent=r("There's a problem with this formula after the replacement, so the cell was left as it was.");return}}await this.doFind(1)}_matchesHere(t,e,o){const{book:s}=this.app,{sheet:a}=s;return H(s,{...t,look:"formulas"},this._display())(a,e,o,a.kind(e,o),a.value(e,o))}async doReplaceAll(){const t=this._options();if(!this._ready(t))return;const e=this._begin(),o=performance.now(),s=await P(this.app.book,t,this.repl.value,this.replaceFormat,this._display(),e);if(this._end(e),this.lastMs=performance.now()-o,s.cancelled){this.status.textContent=r("Stopped; nothing was replaced.");return}const a={count:s.count,shown:k(s.count),sheets:s.sheets},n=[s.count===0&&s.locked===0&&s.invalid===0?r("We couldn't find anything to replace."):s.sheets>1?r("All done. We made {shown} replacements on {sheets} sheets.",a):r("All done. We made {shown} replacements.",a)];s.locked>0&&n.push(r("{shown} locked cells on protected sheets were left as they were.",{count:s.locked,shown:k(s.locked)})),s.invalid>0&&n.push(r("{shown} cells were left as they were, as the replacement would break their formulas.",{count:s.invalid,shown:k(s.invalid)})),this.status.textContent=n.join(" "),this.app.grid.invalidate(),this.app.afterCommand(),this.what.focus()}}function ot(c,t){if(!p&&b){const e=b.regex?F(b.what):null;if(e!==null)return c.shell?.setStatus(r("This regular expression isn't valid: {problem}",{problem:e})),null;const o=c.grid.selection;return v(c.book,b,{row:o.row,col:o.col},t,(s,a,n)=>c.grid.displayText(s,a,n),{}).then(s=>s?(s.sheet&&s.sheet!==c.book.sheet&&c.switchSheet(c.book.sheets.indexOf(s.sheet)),c.controller.moveTo(s.row,s.col),s):(c.shell?.setStatus(r("We couldn't find what you were looking for.")),null))}return p?(A(c),p.doFind(t)):(K(c),null)}const S=new WeakSet;function A(c){p.app=c,!S.has(c)&&(S.add(c),c.signal?.addEventListener("abort",()=>{p?.app===c&&(p.cancel(),p.node.remove(),p=null)},{once:!0}))}function K(c,t=!1){p??=new X(c),A(c),p.setMode(t),p.focus();const e=p;return setTimeout(()=>{p===e&&document.activeElement!==e.what&&!e.node.contains(document.activeElement)&&e.focus()},0),p}export{ot as findAgain,K as openFind};
|