@8sheets/data-grid 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +36 -0
- package/README.md +52 -2
- package/a11y/cell-alt-text.js +1 -0
- package/api/overlay.js +1 -0
- package/api/serialize.js +1 -0
- package/api/skins.js +1 -0
- package/api/style-refs.js +1 -0
- package/api/watermark-xml.js +2 -0
- package/calc/adjust.js +1 -0
- package/calc/cell-set.js +1 -0
- package/calc/compile.js +1 -0
- package/calc/engine.js +1 -0
- package/calc/fill-shape.js +2 -0
- package/calc/functions/array.js +1 -0
- package/calc/functions/database.js +1 -0
- package/calc/functions/date.js +1 -0
- package/calc/functions/engineering.js +1 -0
- package/calc/functions/financial.js +1 -0
- package/calc/functions/helpers.js +1 -0
- package/calc/functions/index.js +1 -0
- package/calc/functions/info.js +1 -0
- package/calc/functions/logical.js +1 -0
- package/calc/functions/lookup.js +1 -0
- package/calc/functions/math.js +1 -0
- package/calc/functions/registry.js +1 -0
- package/calc/functions/stat.js +1 -0
- package/calc/functions/text.js +1 -0
- package/calc/parser.js +3 -0
- package/calc/values.js +1 -0
- package/calcx/ai/client.js +1 -0
- package/calcx/ai/functions.js +15 -0
- package/calcx/ai/settings.js +1 -0
- package/calcx/async.js +1 -0
- package/calcx/culture/format-locale.js +1 -0
- package/calcx/culture/lcid.js +1 -0
- package/calcx/external-read.js +1 -0
- package/calcx/external-write.js +3 -0
- package/calcx/external.js +1 -0
- package/calcx/functions/dynamic.js +1 -0
- package/calcx/functions/ets.js +1 -0
- package/calcx/functions/index.js +1 -0
- package/calcx/functions/misc.js +1 -0
- package/calcx/functions/text.js +1 -0
- package/calcx/functions/xml.js +1 -0
- package/calcx/refresh.js +1 -0
- package/cells/auto-merge.js +1 -0
- package/cells/axis-limits.js +1 -0
- package/cells/axis-ops.js +1 -0
- package/cells/background-xml.js +1 -0
- package/cells/background.js +1 -0
- package/cells/book-css.js +206 -0
- package/cells/book-read.js +1 -0
- package/cells/book-view.js +1 -0
- package/cells/cell-defaults.js +1 -0
- package/cells/cell-extras.js +1 -0
- package/cells/cell-options-ui.js +1 -0
- package/cells/cell-styles-xml.js +1 -0
- package/cells/cf-engine.js +1 -0
- package/cells/cf-file.js +1 -0
- package/cells/cf-paint.js +1 -0
- package/cells/consolidate-links.js +1 -0
- package/cells/docprops-xml.js +2 -0
- package/cells/filter-file.js +1 -0
- package/cells/find-engine.js +2 -0
- package/cells/find.js +1 -0
- package/cells/format-code.js +1 -0
- package/cells/format-panes.js +3 -0
- package/cells/format-tabs.js +102 -0
- package/cells/goto.js +1 -0
- package/cells/header-colors.js +1 -0
- package/cells/mask.js +1 -0
- package/cells/menu-extras.js +1 -0
- package/cells/name-box.js +1 -0
- package/cells/note-xml.js +1 -0
- package/cells/options.js +1 -0
- package/cells/outline-column.js +1 -0
- package/cells/paint.js +1 -0
- package/cells/panes.js +1 -0
- package/cells/rich-data-xml.js +2 -0
- package/cells/rich-data.js +1 -0
- package/cells/rich-runs.js +2 -0
- package/cells/rich-values.js +1 -0
- package/cells/rich-xml.js +1 -0
- package/cells/rounded.js +1 -0
- package/cells/sections.js +2 -0
- package/cells/selection-modes.js +1 -0
- package/cells/style-xml.js +1 -0
- package/cells/text-layout.js +8 -0
- package/cells/undo-group.js +1 -0
- package/cells/validation-alert.js +2 -0
- package/cells/view-options.js +1 -0
- package/cells/view-xml.js +1 -0
- package/celltypes/barcode-tables.js +31 -0
- package/celltypes/barcode.js +2 -0
- package/celltypes/base.js +1 -0
- package/celltypes/cell-buttons.js +1 -0
- package/celltypes/cell-types.js +2 -0
- package/celltypes/data-object.js +1 -0
- package/celltypes/diagonal.js +1 -0
- package/celltypes/dropdowns-more.js +13 -0
- package/celltypes/dropdowns.js +42 -0
- package/celltypes/file-cell.js +2 -0
- package/celltypes/glyphs.js +1 -0
- package/celltypes/persist.js +2 -0
- package/celltypes/range-template.js +2 -0
- package/charts/chartex.js +3 -0
- package/charts/geo/geo-xml.js +1 -0
- package/charts/geo/map-state.js +1 -0
- package/charts/patterns.js +1 -0
- package/core/address.js +1 -0
- package/core/axis.js +1 -0
- package/core/base64.js +1 -0
- package/core/changes.js +1 -0
- package/core/color.js +1 -0
- package/core/cond-format.js +1 -0
- package/core/custom-views.js +1 -0
- package/core/default-names.js +1 -0
- package/core/formula-refs.js +1 -0
- package/core/formula-store.js +1 -0
- package/core/input.js +1 -0
- package/core/math.js +1 -0
- package/core/numfmt.js +1 -0
- package/core/online.js +1 -0
- package/core/protection.js +1 -0
- package/core/regexp.js +1 -0
- package/core/sheet-group.js +1 -0
- package/core/sheet.js +1 -0
- package/core/sparklines.js +1 -0
- package/core/sparse.js +1 -0
- package/core/strings.js +1 -0
- package/core/styles.js +1 -0
- package/core/table-presets.js +7 -0
- package/core/tables.js +2 -0
- package/core/tsv.js +4 -0
- package/core/whatif.js +1 -0
- package/core/workbook.js +1 -0
- package/datasheets/bind.js +1 -0
- package/datasheets/calendar.js +1 -0
- package/datasheets/cross.js +1 -0
- package/datasheets/data-core.js +1 -0
- package/datasheets/data.js +1 -0
- package/datasheets/formula.js +1 -0
- package/datasheets/gantt-paint.js +1 -0
- package/datasheets/gantt-resources.js +1 -0
- package/datasheets/gantt-shapes.js +1 -0
- package/datasheets/gantt.js +1 -0
- package/datasheets/manager.js +1 -0
- package/datasheets/path-binding.js +2 -0
- package/datasheets/persist-writer.js +2 -0
- package/datasheets/persist.js +1 -0
- package/datasheets/query-function.js +1 -0
- package/datasheets/remote.js +3 -0
- package/datasheets/report-entry.js +1 -0
- package/datasheets/report.js +1 -0
- package/datasheets/rules.js +1 -0
- package/datasheets/sort.js +1 -0
- package/datasheets/table-sheet.js +1 -0
- package/datasheets/view.js +3 -0
- package/datasheets/virtual-sheet.js +1 -0
- package/datasheets/window.js +1 -0
- package/extras/getdata/persist.js +2 -0
- package/extras/getdata/rows.js +1 -0
- package/extras/getdata/steps.js +1 -0
- package/i18n/dom.js +1 -0
- package/i18n/en/a11y.js +1 -0
- package/i18n/en/cells.js +1 -0
- package/i18n/en/charts.js +1 -0
- package/i18n/en/common.js +1 -0
- package/i18n/en/datasheets.js +1 -0
- package/i18n/en/format.js +1 -0
- package/i18n/en/misc.js +1 -0
- package/i18n/en/pivot.js +1 -0
- package/i18n/en/proofing.js +1 -0
- package/i18n/en/ribbon.js +1 -0
- package/i18n/en/shapes.js +1 -0
- package/i18n/en/shell.js +1 -0
- package/i18n/en/touch.js +1 -0
- package/i18n/en.js +1 -0
- package/i18n/index.js +1 -0
- package/i18n/key-text.js +1 -0
- package/i18n/languages.js +1 -0
- package/i18n/pl/a11y.js +1 -0
- package/i18n/pl/cells.js +1 -0
- package/i18n/pl/charts.js +1 -0
- package/i18n/pl/common.js +1 -0
- package/i18n/pl/datasheets.js +1 -0
- package/i18n/pl/format.js +1 -0
- package/i18n/pl/misc.js +1 -0
- package/i18n/pl/pivot.js +1 -0
- package/i18n/pl/proofing.js +1 -0
- package/i18n/pl/ribbon.js +1 -0
- package/i18n/pl/shapes.js +1 -0
- package/i18n/pl/shell.js +1 -0
- package/i18n/pl/touch.js +1 -0
- package/i18n/pl.js +1 -0
- package/io/client.js +1 -0
- package/io/crc32.js +1 -0
- package/io/crypto/aes.js +1 -0
- package/io/crypto/agile.js +2 -0
- package/io/crypto/cfb-read.js +1 -0
- package/io/crypto/cfb-write.js +1 -0
- package/io/crypto/dataspaces.js +1 -0
- package/io/crypto/errors.js +1 -0
- package/io/crypto/hash.js +1 -0
- package/io/crypto/index.js +1 -0
- package/io/crypto/package-read.js +1 -0
- package/io/crypto/package-write.js +1 -0
- package/io/crypto/spool.js +1 -0
- package/io/crypto/standard.js +1 -0
- package/io/csv.js +8 -0
- package/io/export-blocks.js +1 -0
- package/io/foreign-parts.js +1 -0
- package/io/foreign-sheets.js +2 -0
- package/io/io.worker.js +1 -0
- package/io/package-paths.js +1 -0
- package/io/plan.js +1 -0
- package/io/text-split.js +3 -0
- package/io/xlsx-read.js +1 -0
- package/io/xlsx-styles.js +2 -0
- package/io/xlsx-tail.js +1 -0
- package/io/xlsx-write.js +2 -0
- package/io/xml-escape.js +1 -0
- package/io/xml-scan.js +1 -0
- package/io/zip-reader.js +1 -0
- package/io/zip-writer.js +1 -0
- package/objects/chart-model.js +1 -0
- package/objects/dml.js +5 -0
- package/objects/drawing-xml.js +1 -0
- package/objects/picture-url.js +1 -0
- package/package.json +57 -4
- package/pivot/engine.js +1 -0
- package/pivot/xml.js +2 -0
- package/print/page-setup.js +1 -0
- package/print/paginate.js +1 -0
- package/print/pdf.js +35 -0
- package/print/render-page.js +3 -0
- package/render/patterns.js +1 -0
- package/shapes/form-xml.js +1 -0
- package/shapes/watermark.js +1 -0
- package/slicers/custom-styles.js +1 -0
- package/slicers/date-filters.js +1 -0
- package/slicers/format.js +2 -0
- package/slicers/pivot-file.js +1 -0
- package/slicers/structured.js +1 -0
- package/slicers/table-file.js +1 -0
- package/slicers/write.js +1 -0
- package/sparklines/colors.js +1 -0
- package/sparklines/data.js +1 -0
- package/sparklines/descriptor.js +1 -0
- package/sparklines/excel-paint.js +1 -0
- package/sparklines/functions.js +1 -0
- package/sparklines/paint-core.js +1 -0
- package/sparklines/paint-measure.js +1 -0
- package/sparklines/paint-other.js +2 -0
- package/sparklines/paint-series.js +1 -0
- package/sparklines/paint.js +1 -0
- package/sparklines/print.js +1 -0
- package/sparklines/rule.js +1 -0
- package/table-view/api.js +1 -0
- package/table-view/cell-editor.js +1 -0
- package/table-view/cell-format.js +1 -0
- package/table-view/chrome.js +1 -0
- package/table-view/client.js +1 -0
- package/table-view/column-drag.js +1 -0
- package/table-view/column-input.js +1 -0
- package/table-view/column-window.js +1 -0
- package/table-view/events.js +1 -0
- package/table-view/files.js +1 -0
- package/table-view/grid-keys.js +2 -0
- package/table-view/index.d.ts +4 -0
- package/table-view/index.js +1 -0
- package/table-view/labels.js +1 -0
- package/table-view/model.js +1 -0
- package/table-view/mount.js +1 -0
- package/table-view/panel.js +1 -0
- package/table-view/pivot.js +1 -0
- package/table-view/public.d.ts +841 -0
- package/table-view/quick-filter.js +1 -0
- package/table-view/reader.worker.js +1 -0
- package/table-view/remote.js +1 -0
- package/table-view/row-cache.js +1 -0
- package/table-view/row-selection.js +1 -0
- package/table-view/table-css.js +1207 -0
- package/table-view/totals.js +1 -0
- package/table-view/version.js +1 -0
- package/table-view/worksheet-table.js +1 -0
- package/ui/dialogs.js +3 -0
- package/ui/dom.js +1 -0
- package/ui/icons.js +1 -0
- package/ui/menu-base.js +1 -0
- package/ui/protection-ui.js +1 -0
- package/ui/ui-scale.js +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{EMPTY as te,STR as ee}from"../core/sheet.js";import{serialToParts as ft,partsToSerial as z}from"../core/numfmt.js";import{MAX_COLS as se}from"../core/address.js";import{getPageSetup as ne}from"../print/page-setup.js";import{sortByF64 as ie,sortColumn as re}from"./sort.js";import{CALENDAR_PRESETS as ae,makeCalendar as Pt,WorkCalendar as oe}from"./calendar.js";import{enableResources as le,levelTasks as ce,resourceNamesOf as jt,syncAssignments as he}from"./gantt-resources.js";import{addPlanShapes as ue,SHAPE_MAX_TASKS as de}from"./gantt-shapes.js";import{ROW as fe}from"./data.js";import{STAGE as zt,TableView as me,todaySerial as Ht}from"./view.js";import{TableSheet as pe}from"./table-sheet.js";import{language as ye,t as mt}from"../i18n/index.js";const Kt=["FS","SS","FF","SF"],we=/^\s*(\d+)\s*(FS|SS|FF|SF)?\s*(?:([+-])\s*(\d+(?:\.\d+)?)\s*(d|w|day|days|wk|wks)?)?\s*$/i;function rt(p){const s=[];if(p==null||p==="")return s;for(const e of String(p).split(/[,;]/)){if(e.trim()==="")continue;const n=we.exec(e);if(!n)return null;let t=n[4]?Number(n[4]):0;n[3]==="-"&&(t=-t),n[5]&&/^w/i.test(n[5])&&(t*=5),s.push({id:Number(n[1]),type:(n[2]??"FS").toUpperCase(),lag:Math.round(t)})}return s}function pt(p){return p.map(s=>`${s.id}${s.type==="FS"&&s.lag===0?"":s.type}${s.lag>0?`+${s.lag}d`:s.lag<0?`${s.lag}d`:""}`).join(",")}const $t={id:"id",parent:"parent",name:"name",start:"start",finish:"finish",duration:"duration",progress:"progress",predecessors:"predecessors",constraint:"constraint",manual:"manual",deadline:"deadline",baselineStart:"baselineStart",baselineFinish:"baselineFinish",order:"order",slack:"slack",critical:"critical",wbs:"wbs",resource:"resource",successors:"successors",work:"work",calendar:"calendar",cost:"cost",fixedCost:"fixedCost",levelStart:"levelStart",levelFrom:"levelFrom",priority:"priority"};function Ee(p,s,e=[],n=[]){const t=p.addTable(s,{key:"id",fields:[{name:"id",caption:"ID",type:"number",width:44},{name:"wbs",caption:"WBS",type:"string",width:58,readOnly:!0},{name:"name",caption:"Task",type:"string",width:200},{name:"start",caption:"Start",type:"date",format:"d-mmm-yy",width:76},{name:"finish",caption:"Finish",type:"date",format:"d-mmm-yy",width:76},{name:"duration",caption:"Days",type:"number",format:"0",width:42},{name:"progress",caption:"% Done",type:"number",format:"0%",width:52},{name:"predecessors",caption:"Predecessors",type:"string",width:84},{name:"resource",caption:"Resource",type:"string",width:90},{name:"slack",caption:"Slack",type:"number",format:"0",width:42,readOnly:!0},{name:"critical",caption:"Critical",type:"boolean",width:50,readOnly:!0},{name:"successors",caption:"Successors",type:"string",width:84,readOnly:!0},{name:"work",caption:"Work",type:"number",format:"0.0",width:50,readOnly:!0},{name:"cost",caption:"Cost",type:"number",format:"#,##0.00",width:70,readOnly:!0},{name:"fixedCost",caption:"Fixed Cost",type:"number",format:"#,##0.00",width:70,hidden:!0},{name:"priority",caption:"Priority",type:"number",format:"0",width:56,hidden:!0},{name:"levelStart",caption:"Leveled Start",type:"date",format:"d-mmm-yy",hidden:!0},{name:"levelFrom",caption:"Start Before Leveling",type:"date",format:"d-mmm-yy",hidden:!0},{name:"calendar",caption:"Calendar",type:"string",hidden:!0},{name:"parent",caption:"Parent",type:"number",hidden:!0},{name:"order",caption:"Order",type:"number",hidden:!0},{name:"constraint",caption:"Start No Earlier Than",type:"date",format:"d-mmm-yy",hidden:!0},{name:"manual",caption:"Manual",type:"boolean",hidden:!0},{name:"deadline",caption:"Deadline",type:"date",format:"d-mmm-yy",hidden:!0},{name:"baselineStart",caption:"Baseline Start",type:"date",format:"d-mmm-yy",hidden:!0},{name:"baselineFinish",caption:"Baseline Finish",type:"date",format:"d-mmm-yy",hidden:!0},...n]});return e.length>0&&t.load(ge(e)),t}function ge(p,s={}){const e=s.childrenKey??"children",n=[];if(p.some(r=>Array.isArray(r[e]))){let r=p.reduce(function o(l,u){const g=typeof u.id=="number"?u.id:0;return Math.max(l,g,Array.isArray(u[e])?u[e].reduce(o,0):0)},0)+1;const a=(o,l)=>{for(const u of o){const{[e]:g,...d}=u,m=typeof d.id=="number"?d.id:r++;n.push({...d,id:m,parent:l??null}),Array.isArray(g)&&a(g,m)}};a(p,null)}else if(p.length>0&&p.every(r=>typeof r.level=="number")&&!p.some(r=>r.parent!==void 0)){const r=[];let a=p.reduce((o,l)=>Math.max(o,typeof l.id=="number"?l.id:0),0)+1;for(const o of p){const l=typeof o.id=="number"?o.id:a++;r.length=Math.min(r.length,o.level),n.push({...o,id:l,parent:r.length>0?r[r.length-1]:null}),r[o.level]=l}}else if(p.length>0&&p.every(r=>typeof r.path=="string")){const r=new Map;let a=1;for(const o of p)r.set(o.path,typeof o.id=="number"?o.id:a++);for(const o of p){const l=o.path.lastIndexOf(".");n.push({...o,id:r.get(o.path),parent:l>0?r.get(o.path.slice(0,l))??null:null})}}else n.push(...p);return n.forEach((r,a)=>{r.order===void 0&&(r.order=a+1)}),n}function Tt(p,s,e,{projectStart:n=null,calendars:t=null,durationUnit:r="d"}={}){const a=p.rowCount,o={...$t,...s},{alive:l}=p,u=i=>p.column(o[i]),g=u("id").data,d=u("parent").data,m=u("start").data,f=u("finish").data,T=u("duration").data,O=u("predecessors"),y=u("constraint")?.data??null,k=u("manual")?.data??null,S=u("levelStart")?.data??null,_=u("progress")?.data??null,U=u("calendar")??null;let Y=0,G=1/0;for(let i=0;i<a;i++){if(l[i]===0)continue;const h=g[i];h>Y&&(Y=h);const c=m[i];c===c&&c<G&&(G=c)}G===1/0&&(G=n??Ht());const Q=n??G,Z=Y<=a*4+1024?new Int32Array(Y+1).fill(-1):null,vt=Z===null?new Map:null;for(let i=a-1;i>=0;i--){if(l[i]===0)continue;const h=g[i];h===h&&(Z!==null?Z[h]=i:vt.set(h,i))}const Mt=i=>Z!==null?i<=Y&&i>=0&&i===Math.floor(i)?Z[i]:-1:vt.get(i)??-1,q=new Int32Array(a).fill(-1),A=new Uint8Array(a);for(let i=0;i<a;i++){if(l[i]===0)continue;const h=d[i];if(h===h){const c=Mt(h);c>=0&&c!==i&&(q[i]=c,A[c]=1)}}const L=!t||!U||t.size===0?()=>e:i=>{const h=U.get(i);return h===null?e:t.get(h)??e},At=new Map,{strings:Yt}=p.manager,H=[],tt=[],K=[],X=[],Ft=[],Gt=O.data;for(let i=0;i<a;i++){if(l[i]===0)continue;const h=Gt[i];if(h<0)continue;let c=At.get(h);if(c===void 0&&(c=rt(Yt.get(h)),At.set(h,c)),c===null){Ft.push(i);continue}for(const w of c){const b=Mt(w.id);b<0||b===i||(H.push(b),tt.push(i),K.push(Kt.indexOf(w.type)),X.push(w.lag))}}const gt=H.length,C=new Float64Array(a);for(let i=0;i<a;i++){if(l[i]===0||A[i]===1)continue;const h=L(i),c=T[i],w=h.unitsPer(r);if(c===c)C[i]=Math.max(0,Math.round(c*w));else if(m[i]===m[i]&&f[i]===f[i]){const b=h.fullDays?Math.floor(f[i])+1:f[i];C[i]=Math.max(0,h.unitsBetween(m[i],b))}else C[i]=Math.round(w)}const P=2*a,B=new Int32Array(P+1),at=i=>{B[i+1]++};for(let i=0;i<a;i++){if(l[i]===0)continue;at(2*i);const h=q[i];h>=0&&(at(2*h),at(2*i+1))}for(let i=0;i<gt;i++){const h=K[i];at(h===0||h===2?2*H[i]+1:2*H[i])}for(let i=0;i<P;i++)B[i+1]+=B[i];const kt=B[P],ot=new Int32Array(kt),bt=new Int32Array(kt),Qt=B.slice(),lt=(i,h,c)=>{const w=Qt[i]++;ot[w]=h,bt[w]=c};for(let i=0;i<a;i++){if(l[i]===0)continue;lt(2*i,2*i+1,0);const h=q[i];h>=0&&(lt(2*h,2*i,1),lt(2*i+1,2*h+1,2))}for(let i=0;i<gt;i++){const h=K[i];lt(h===0||h===2?2*H[i]+1:2*H[i],2*tt[i],3+i)}const et=-1/0,x=new Float64Array(P).fill(et),ct=new Int32Array(P);for(let i=0;i<kt;i++)ct[ot[i]]++;const Lt=new Uint8Array(a);for(let i=0;i<gt;i++)Lt[tt[i]]=1;const ht=i=>k!==null&&k[i]===1,st=new Uint8Array(a);for(let i=0;i<a;i++){if(l[i]===0)continue;const h=L(i);let c=et;if(A[i]===0){const w=m[i];if(ht(i)){const b=f?f[i]:NaN;w===w?c=h.nextWork(w):b===b&&(c=h.sub(h.fullDays?b+1:b,C[i]))}else Lt[i]===0&&(c=h.nextWork(w===w?w:Q))}if(y!==null){const w=y[i];w===w&&(c=Math.max(c,h.nextWork(w)))}if(S!==null&&A[i]===0&&!ht(i)){const w=S[i];w===w&&(c=Math.max(c,h.nextWork(w)))}c===et&&A[i]===0&&ht(i)&&(st[i]=1),x[2*i]=c}const E=new Int32Array(P);let It=0,R=0;for(let i=0;i<a;i++)l[i]!==0&&(ct[2*i]===0&&(E[R++]=2*i),ct[2*i+1]===0&&(E[R++]=2*i+1));const Ot=(i,h)=>h*i.unitsPer("d"),Zt=(i,h,c)=>{const w=x[i];if(w===et)return;const b=h>>1;if(st[b]===1)return;let v;if(c===0)if(A[b]===1)v=w;else{const M=L(b);v=C[b]===0?M.nextWork(w):M.add(w,C[b])}else if(c===1||c===2)v=w;else{if(ht(b)&&A[b]===0)return;const M=c-3,F=L(b),j=X[M]===0?w:F.add(w,Ot(F,X[M])),J=K[M];J===0||J===1||A[b]===1?v=F.nextWork(j):v=F.sub(j,C[b])}v>x[h]&&(x[h]=v)};for(;It<R;){const i=E[It++];for(let h=B[i];h<B[i+1];h++){const c=ot[h];Zt(i,c,bt[h]),--ct[c]===0&&(E[R++]=c)}}const Rt=[];let Dt=0;for(let i=0;i<a;i++)l[i]===1&&(Dt+=2);if(R<Dt){const i=new Uint8Array(P);for(let h=0;h<R;h++)i[E[h]]=1;for(let h=0;h<a;h++)if(l[h]!==0&&(i[2*h]===0||i[2*h+1]===0)){Rt.push(h),i[2*h]===0&&(E[R++]=2*h),i[2*h+1]===0&&(E[R++]=2*h+1);const c=m[h],w=L(h);x[2*h]=w.nextWork(c===c?c:Q),x[2*h+1]=w.add(x[2*h],C[h])}}for(let i=0;i<a;i++){if(l[i]===0||A[i]===1||st[i]===1)continue;const h=L(i);x[2*i]===et&&(x[2*i]=h.nextWork(Q));const c=C[i]===0?x[2*i]:h.add(x[2*i],C[i]);c>x[2*i+1]&&(x[2*i+1]=c)}const Wt=new Float64Array(a).fill(NaN),Et=new Float64Array(a).fill(NaN),D=new Float64Array(a).fill(1/0),I=new Float64Array(a).fill(-1/0),nt=new Float64Array(a),ut=new Float64Array(a),St=new Float64Array(a);let $=-1/0,it=1/0;for(let i=0;i<R;i++){const h=E[i];if((h&1)===0)continue;const c=h>>1;if(st[c]!==1)if(A[c]===0){const b=x[2*c],v=C[c]===0?b:L(c).add(b,C[c]);D[c]=b,I[c]=v;const M=C[c],F=_!==null&&_[c]===_[c]?_[c]:0;nt[c]=M,ut[c]=M*F,St[c]=F}else nt[c]>0&&(St[c]=ut[c]/nt[c]);if(I[c]>$&&($=I[c]),D[c]<it&&(it=D[c]),D[c]!==1/0){Wt[c]=D[c];const b=L(c).fullDays;Et[c]=b&&I[c]>D[c]?Math.ceil(I[c])-1:I[c]}const w=q[c];w>=0&&(D[c]<D[w]&&(D[w]=D[c]),I[c]>I[w]&&(I[w]=I[c]),nt[w]+=nt[c],ut[w]+=ut[c])}$===-1/0&&($=e.nextWork(Q),it=$);const W=new Float64Array(P).fill(1/0);for(let i=0;i<a;i++)l[i]===1&&(W[2*i+1]=$);for(let i=R-1;i>=0;i--){const h=E[i],c=h>>1;let w=W[h];for(let b=B[h];b<B[h+1];b++){const v=ot[b],M=bt[b];let F;if(M===0)F=A[c]===1||C[c]===0?W[v]:L(c).sub(W[v],C[c]);else if(M===1||M===2)F=W[v];else{const j=M-3,J=tt[j],Ut=L(J),Bt=K[j]===2||K[j]===3?W[2*J+1]:W[2*J];F=X[j]===0?Bt:Ut.add(Bt,-Ot(Ut,X[j]))}F<w&&(w=F)}W[h]=w}const Nt=new Float64Array(a).fill(NaN),dt=new Uint8Array(a);for(let i=0;i<a;i++){if(l[i]===0||A[i]===1||st[i]===1)continue;const h=L(i),c=I[i],w=Math.max(h.unitsBetween(c,W[2*i+1]),0),b=h.unitsPer("d");Nt[i]=w/b,(W[2*i+1]<=c+1e-9||w===0)&&(dt[i]=1)}for(let i=0;i<R;i++){const h=E[i];if((h&1)===0)continue;const c=h>>1,w=q[c];w>=0&&dt[c]===1&&(dt[w]=1)}return{rows:a,start:Wt,finish:Et,momentStart:D,momentFinish:I,duration:C,parentRow:q,isSummary:A,progress:St,slack:Nt,critical:dt,links:{from:H,to:tt,type:K,lag:X},inCycle:Rt,badLinks:Ft,projectStart:it===1/0?Q:it,projectFinish:$,calendar:e,calOf:L,durationUnit:r}}const qt=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ke=["S","M","T","W","T","F","S"],Xt=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],_t={months:qt,weekdays:Xt,shown:!1};let yt=null;function be(){const p=ye();if(yt?.lang!==p)if(p==="en")yt={..._t,shown:!0,lang:p};else{const s=new Intl.DateTimeFormat(p,{month:"short",timeZone:"UTC"}),e=new Intl.DateTimeFormat(p,{weekday:"short",timeZone:"UTC"});yt={lang:p,shown:!0,months:qt.map((n,t)=>s.format(Date.UTC(2021,t,1))),weekdays:Xt.map((n,t)=>e.format(Date.UTC(2021,0,3+t)))}}return yt}const V=[{name:"minutes",unit:"minute",tickWidth:24,tiers:[{unit:"day"},{unit:"hour"},{unit:"minute",count:15}]},{name:"hours",unit:"hour",tickWidth:24,tiers:[{unit:"week"},{unit:"day"},{unit:"hour"}]},{name:"shifts",unit:"hour",tickWidth:28,tiers:[{unit:"day"},{unit:"hour",count:6}]},{name:"day-wide",unit:"day",tickWidth:28,tiers:[{unit:"week"},{unit:"day"}]},{name:"day",unit:"day",tickWidth:18,tiers:[{unit:"month"},{unit:"day"}]},{name:"week",unit:"week",tickWidth:44,tiers:[{unit:"month"},{unit:"week"}]},{name:"month",unit:"month",tickWidth:54,tiers:[{unit:"year"},{unit:"month"}]},{name:"quarter",unit:"quarter",tickWidth:64,tiers:[{unit:"year"},{unit:"quarter"}]},{name:"half",unit:"half",tickWidth:64,tiers:[{unit:"year"},{unit:"half"}]},{name:"year",unit:"year",tickWidth:72,tiers:[{unit:"decade"},{unit:"year"}]}],Ct=p=>V.findIndex(s=>s.name===p);function xt(p,s,e=1,n=1){const t=Math.floor(p),r=ft(t);switch(s){case"minute":{const a=e/1440;return Math.floor(p/a+1e-6)*a}case"hour":{const a=e/24;return t+Math.floor((p-t)/a+1e-6)*a}case"day":return t;case"week":return t-(r.weekday-n+7)%7;case"month":return z(r.year,r.month,1);case"quarter":return z(r.year,Math.floor((r.month-1)/3)*3+1,1);case"half":return z(r.year,r.month<=6?1:7,1);case"year":return z(r.year,1,1);default:return z(Math.floor(r.year/10)*10,1,1)}}function wt(p,s,e=1){const n=s==="minute"||s==="hour"||s==="day"||s==="week"?null:ft(p);switch(s){case"minute":return p+e/1440;case"hour":return p+e/24;case"day":return p+e;case"week":return p+7*e;case"month":{const t=n.month-1+e;return z(n.year+Math.floor(t/12),t%12+1,1)}case"quarter":return wt(p,"month",3*e);case"half":return wt(p,"month",6*e);case"year":return z(n.year+e,1,1);default:return z(n.year+10*e,1,1)}}const N=(p,s,e)=>p.shown?mt(s,e):s.replace(/\{(\w+)\}/g,(n,t)=>String(e[t]));function Jt(p,s,e=_t){const n=ft(Math.floor(p)),t=Math.round((p-Math.floor(p))*1440),r=e.months[n.month-1];switch(s){case"minute":return String(t%60).padStart(2,"0");case"hour":return String(Math.floor(t/60));case"day":return String(n.day);case"week":return N(e,"{day} {month}",{day:n.day,month:r});case"month":return r;case"quarter":return N(e,"Q{n}",{n:Math.floor((n.month-1)/3)+1});case"half":return N(e,"H{n}",{n:n.month<=6?1:2});case"year":return String(n.year);default:return N(e,"{decade}s",{decade:Math.floor(n.year/10)*10})}}function Se(p,s,e=_t){const n=ft(Math.floor(p)),t=e.months[n.month-1];switch(s){case"hour":return`${String(Math.round((p-Math.floor(p))*24)).padStart(2,"0")}:00`;case"day":return N(e,"{weekday} {day} {month}",{weekday:e.weekdays[(Math.floor(p)-1)%7],day:n.day,month:t});case"week":return N(e,"{month} {day}, {year}",{month:t,day:n.day,year:n.year});case"month":return N(e,"{month} {year}",{month:t,year:n.year});case"quarter":return N(e,"Q{n} {year}",{n:Math.floor((n.month-1)/3)+1,year:n.year});case"half":return N(e,"H{n} {year}",{n:n.month<=6?1:2,year:n.year});case"year":return String(n.year);default:return N(e,"{decade}s",{decade:Math.floor(n.year/10)*10})}}class Vt{constructor(s=Ct("day")){this.level=s,this.ticks=new Float64Array(0),this.tiers=[],this.tops=[],this.count=0,this.padBefore=3,this.padAfter=6,this.factor=1,this.customTiers=null,this.minDate=null,this.maxDate=null,this.autoFit="project",this.margin=null,this.weekStart=1}get spec(){return V[this.level]}get tierSpecs(){return this.customTiers??this.spec.tiers}get bottomTier(){const s=this.tierSpecs;return s[s.length-1]}get tickWidth(){return Math.max(4,Math.round((this.bottomTier.width??this.spec.tickWidth)*this.factor))}build(s,e,n=se-64){let t=s,r=e;this.minDate!==null&&(t=this.minDate),this.maxDate!==null&&(r=this.maxDate),this.autoFit==="none"&&this.ticks.length>0&&this.minDate===null&&this.builtFrom!==void 0&&(t=this.builtFrom,r=this.builtTo);const a=this.margin?.before??this.padBefore,o=this.margin?.after??this.padAfter;for(;;){const l=this.bottomTier,{unit:u}=l,g=l.count??1;let d=xt(t,u,g,this.weekStart);for(let f=0;f<a;f++)d=xt(d-1e-6,u,g,this.weekStart);const m=[];for(;(d<=r||m.length===0)&&(m.push(d),d=wt(d,u,g),!(m.length>n)););if(m.length>n&&this.level<V.length-1&&this.customTiers===null){this.level++;continue}for(let f=0;f<o&&m.length<=n;f++)m.push(d),d=wt(d,u,g);m.push(d),this.ticks=Float64Array.from(m),this.count=m.length-1,this.builtFrom=t,this.builtTo=r,this._buildTiers();return}}_buildTiers(){const s=this.tierSpecs,e=be();this.tiers=s.map((n,t)=>{const r=t===s.length-1,a=[];let o=NaN;for(let l=0;l<this.count;l++){const u=xt(this.ticks[l],n.unit,n.count??1,this.weekStart);u!==o&&(a.push({tick:l,label:n.label?n.label(this.ticks[l]):r?Jt(this.ticks[l],n.unit,e):Se(n.unit==="week"?this.ticks[l]:u,n.unit,e)}),o=u)}return{unit:n.unit,count:n.count??1,marks:a,bottom:r}}),this.tops=this.tiers.length>1?this.tiers[this.tiers.length-2].marks:[]}position(s){const{ticks:e,count:n}=this;if(n===0)return 0;if(s<=e[0])return(s-e[0])/(e[1]-e[0]);if(s>=e[n])return n+(s-e[n])/(e[n]-e[n-1]);let t=0,r=n;for(;r-t>1;){const a=t+r>>>1;e[a]<=s?t=a:r=a}return t+(s-e[t])/(e[t+1]-e[t])}dateAt(s){const{ticks:e,count:n}=this;if(n===0)return 0;const t=Math.max(0,Math.min(n-1,Math.floor(s))),r=e[t]+(s-t)*(e[t+1]-e[t]),{unit:a}=this.bottomTier;return a==="hour"||a==="minute"?Math.round(r*1440)/1440:Math.round(r)}label(s){return Jt(this.ticks[s],this.bottomTier.unit)}weekdayLetter(s){return ke[(Math.floor(this.ticks[s])-1)%7]}}const Te=2e4,_e=1200;class Ne extends pe{constructor(s,e,n,t={}){const r={...$t,...t.fields},a=t.columns??["id","wbs","name","start","finish","duration","progress","predecessors","resource"].filter(l=>n.column(r[l]??l)),o=t.view??new me(n,{columns:a,sort:[{field:r.order}],hierarchy:{key:r.id,parent:r.parent,column:r.name}});super(s,e,o,{banded:!1,rowHeight:20,allowAdd:!0,...t.sheet}),this.kindName="gantt",this.fields=r,this.calendar=Pt(t.calendar),this.calendars=new Map(Object.entries(t.calendars??{}).map(([l,u])=>[l,Pt(u)])),this.durationUnit=t.durationUnit??"d",this.scale=new Vt(t.scaleLevel??Ct("day")),Object.assign(this.scale,t.scale??{}),this.schedule=null,this.showCritical=t.showCritical!==!1,this.showBaseline=t.showBaseline!==!1,this.showLinks=t.showLinks!==!1,this.showLabels=t.showLabels!==!1,this.showToday=t.showToday!==!1,this.today=t.today??Ht(),this.statusDate=t.statusDate??null,this.taskbarRules=t.taskbarRules??[],this.taskbarStyles=t.taskbarStyles??{},this.layoutOptions={linkMode:"toTop",barHeight:null,roundToDays:!1,barDateFormat:null,...t.layout},this.gridlines={interval:0,intervalColor:"#e0e0e0",rowInterval:0,rowColor:"#e8e8e8",projectStart:!1,projectFinish:!1,status:!1,current:!0,...t.gridlines},this.nonWorking={color:"#f1f1f1",pattern:"solid",mode:"behind",...t.nonWorking},this.progressLine={visible:!1,reference:"status",path:"angled",returnToAnchor:!0,color:"#c42b1c",...t.progressLine},this.frozenLimit=t.frozenLimit??null,this.lastCycle=[],this.scheduleDirty=!0,this.reschedule({track:!1}),this.applyLayout(),t.resources&&le(this,t.resources)}shapeColumnCount(){return this.exporting&&this._exportBars()?this.view.columns.length+this.scale.count:this.view.columns.length}_useShapes(){return this.book.dataSheets?.objects?.takesExportObjects===!0&&this.options.barExport!=="cells"&&this.view.count<=de}addExportObjects(s){return!this.exporting||!this._useShapes()?null:ue(this,s)}supportsNewRow(){return this.options.allowAdd&&this.view.spec.filters.length===0&&!this.view.spec.search}clearSort(){this.viewOp("sort",s=>s.setSort([{field:this.fields.order}]))}_exportBars(){return this.view.count<=Te&&this.scale.count<=_e}applyLayout(s){if(this.scale===void 0){super.applyLayout(s);return}this.timelineStart=this.view.columns.length;const e=this.scale.tickWidth,t=Math.max(1,this.scale.tierSpecs.length)*16+2;this.rows.sizeOf(0)!==t&&this.rows.setSize(0,t),super.applyLayout(s);const r=this.timelineStart+this.scale.count;for(let u=this.timelineStart;u<r;u++)this.cols.sizeOf(u)!==e&&this.cols.setSize(u,e);if(this.lastTotal!==void 0&&this.lastTotal>r)for(let u=r;u<this.lastTotal;u++)this.cols.setSize(u,this.cols.defaultSize);this.lastTotal=r,this.maxCol=r-1,this._applyPrintArea(r);let a=0,o=0;const l=this.frozenLimit??640;for(let u=0;u<this.timelineStart;u++)a+=this.cols.sizeOf(u),a<=l&&(o=u+1);o!==this.frozenCols&&(this.frozenCols=o,this.viewChanged=!0)}setSplitter(s){this.frozenLimit=Math.max(0,s),this.applyLayout({keepCells:!0}),this.onRefresh?.()}_applyPrintArea(s){const e=ne(this),n={r0:0,c0:0,r1:Math.max(0,this.bodyStart+this.view.count-1),c1:s-1},t=this._printArea;(e.printAreas.length===0||t&&e.printAreas.length===1&&e.printAreas[0]===t)&&(t||(e.orientation="landscape",e.fitToPage=!0,e.fitToWidth=1,e.fitToHeight=0,e.titleRows={r0:0,r1:0}),e.printAreas=[n],this._printArea=n,this.pageSetupChanged=!0)}fillChunk(s,e,n){if(s<this.timelineStart||!this.exporting){super.fillChunk(s,e,n);return}n.kinds.fill(0),n.store.fill(0),n.hasStyles=!1;const t=s-this.timelineStart,r=e<<10,a=this.scale.ticks[t],o=this.scale.ticks[t+1],l=this.schedule;if(l===null)return;const u=this._useShapes(),g=Math.min(1024,this.maxRow+1-r);for(let d=0;d<g;d++){const m=r+d;if(m===0){n.kinds[d]=ee,n.values[d]=this.book.strings.add(this.scale.label(t)),n.store[d]=this._headerStyle(),n.hasStyles=!0;continue}if(u)continue;const f=this.recordAtRow(m);if(f<0||f>=l.rows)continue;const T=l.momentStart[f],O=l.momentFinish[f];T===1/0||!(T<o&&O>a)||(n.store[d]=this._barStyle(f),n.hasStyles=!0)}}_barStyle(s){const e=this.schedule;return e.isSummary[s]===1?this._style("bar-s",{fill:this.colors.summary}):this.showCritical&&e.critical[s]===1?this._style("bar-c",{fill:"#d64545"}):this._style("bar",{fill:this.colors.bar})}reschedule({track:s=!0}={}){const{table:e,fields:n}=this;e.ensureAll();const t=Tt(e,n,this.calendar,{calendars:this.calendars,durationUnit:this.durationUnit});this.schedule=t,this.lastCycle=t.inCycle;const r=e.column(n.start),a=e.column(n.finish),o=e.column(n.duration),l=e.column(n.progress),u=e.column(n.slack),g=e.column(n.critical),d=e.rowCount,m=s&&e.tracking,f=(y,k,S)=>{if(!y)return;const _=y.data[k];_===S||_!==_&&S!==S||(m&&e.state[k]!==fe.INSERTED&&e._track(k,y,_!==_?null:_,S!==S?null:S),y.data[k]=S,y.revision++)},{alive:T}=e,{durationUnit:O}=this;for(let y=0;y<d;y++){if(T[y]===0)continue;const k=t.calOf(y),S=k.unitsPer(O);if(f(r,y,t.start[y]),f(a,y,t.finish[y]),t.isSummary[y]===1){const _=t.momentStart[y],U=_!==1/0?k.unitsBetween(_,t.momentFinish[y])/S:NaN;f(o,y,U),l&&f(l,y,t.progress[y])}else f(o,y,Math.round(t.duration[y]/S*1e3)/1e3);u&&(u.data[y]=t.slack[y]),g&&(g.data[y]=t.critical[y])}return this._writeWbs(),this._writeSuccessors(),jt(this,t),this._layTimeline(),this.scheduleDirty=!1,t}_writeSuccessors(){const{table:s,fields:e,schedule:n}=this,t=s.column(e.successors);if(!t)return;const r=s.column(e.id).data,a=new Map,{from:o,to:l,type:u,lag:g}=n.links;for(let f=0;f<o.length;f++)a.has(o[f])||a.set(o[f],[]),a.get(o[f]).push({id:r[l[f]],type:Kt[u[f]],lag:g[f]});const{strings:d}=s.manager,{data:m}=t;for(let f=0;f<s.rowCount;f++){const T=a.get(f);m[f]=T?d.add(pt(T)):-1}t.revision++}_writeWbs(){const{table:s,fields:e,schedule:n}=this,t=s.column(e.wbs);if(!t)return;const r=s.column(e.order),a=s.rowCount,o=new Int32Array(s.liveCount);let l=0;for(let y=0;y<a;y++)s.alive[y]===1&&(o[l++]=y);r&&ie(o,l,r.data,!1);const u=new Int32Array(a+1),g=new Array(a);let d=0;const m=new Int32Array(a);for(let y=0;y<l;y++){const k=o[y],S=n.parentRow[k];m[k]=S>=0?++u[S]:++d}const{strings:f}=s.manager,T=[],O=t.data;for(let y=0;y<l;y++){let k=o[y];for(T.length=0;k>=0&&g[k]===void 0&&T.length<=a;)T.push(k),k=n.parentRow[k];let S=k>=0?g[k]??"":"";for(let _=T.length-1;_>=0;_--){const U=T[_];S=S===""?String(m[U]):`${S}.${m[U]}`,g[U]=S,O[U]=f.add(S)}}t.revision++}_layTimeline(){const s=this.schedule;if(!s)return;let e=s.projectStart,n=s.projectFinish;this.progressLine.visible&&this.statusDate!==null&&(e=Math.min(e,this.statusDate),n=Math.max(n,this.statusDate)),this.scale.build(e,n)}setScaleLevel(s){const e=typeof s=="string"?Ct(s):s,n=Math.max(0,Math.min(V.length-1,e));n===this.scale.level&&this.scale.factor===1&&this.scale.customTiers===null||(this.scale.level=n,this.scale.factor=1,this.scale.customTiers=null,this._relayTimeline())}setTiers(s){this.scale.customTiers=s,this._relayTimeline()}_relayTimeline(){this._layTimeline(),this.applyLayout(),this.onRefresh?.()}zoomIn(){this.setScaleLevel(this.scale.level-1)}zoomOut(){this.setScaleLevel(this.scale.level+1)}zoomTo(s){this.scale.factor=Math.max(.2,Math.min(8,s)),this._relayTimeline()}zoomToRange(s,e,n){for(let t=0;t<V.length;t++){const r=new Vt(t);if(r.padBefore=0,r.padAfter=0,r.build(s,e,2e3),r.level===t&&r.count*r.tickWidth<=n){this.scale.level=t,this.scale.factor=Math.min(3,n/Math.max(1,r.count*r.tickWidth)),this.scale.customTiers=null,this._relayTimeline();return}}this.setScaleLevel(V.length-1)}zoomToFit(s){const e=this.schedule;e&&this.zoomToRange(e.projectStart,e.projectFinish,s)}setRange({minDate:s=null,maxDate:e=null,autoFit:n="project",margin:t=null}={}){Object.assign(this.scale,{minDate:s,maxDate:e,autoFit:n,margin:t}),this._relayTimeline()}xOfDate(s){const e=this.scale.position(s);return this.cols.offsetOf(this.timelineStart)+e*this.scale.tickWidth}dateOfX(s){return this.scale.dateAt((s-this.cols.offsetOf(this.timelineStart))/this.scale.tickWidth)}newRecordValues(){const{table:s,fields:e}=this,n=s.column(e.id).data,t=s.column(e.order)?.data;let r=0,a=0;for(let l=0;l<s.rowCount;l++)n[l]>r&&(r=n[l]),t&&t[l]>a&&(a=t[l]);const o=this.schedule?.projectFinish??this.today;return{[e.id]:r+1,[e.order]:a+1,[e.duration]:1,[e.start]:o,[e.progress]:0}}_isBlankRecord(s){const{table:e,fields:n}=this;return e.column(n.name).kind(s)===te}_write(s,e,n,t){const r=this.recordAtRow(s),{fields:a,table:o}=this,l=this.schedule;if(r>=0&&r<l.rows&&l.isSummary[r]===1){const u=n.field;if(u===a.start||u===a.finish||u===a.duration||u===a.progress){this._reject(mt("Summary tasks take their dates and progress from their subtasks."));return}}if(n.field===a.predecessors&&t!==null&&rt(t)===null){this._reject(mt(`"{value}" isn't a list of predecessors. Use IDs with an optional type and lag, such as 3FS+2d, 5SS.`,{value:t}));return}if(n.field===a.progress&&typeof t=="number"&&t>1&&(t/=100),r>=0&&n.field===a.start&&t!==null){this._writing++;try{o.set(r,a.constraint,t)}finally{this._writing--}}else if(r>=0&&n.field===a.finish&&t!==null){const u=o.column(a.start).data[r];if(u===u){const g=l.calOf(r),d=g.fullDays?Math.floor(t)+1:t,m=Math.max(0,g.unitsBetween(u,d)/g.unitsPer(this.durationUnit));this._writing++;try{o.set(r,a.duration,m)}finally{this._writing--}}}if(r>=0&&n.field===a.resource&&this.assignmentTable){this._writing++;try{he(this,r,t)}finally{this._writing--}}super._write(s,e,n,t),n.field===a.predecessors&&this._checkCycle(r,t)}_checkCycle(s,e){const{table:n,fields:t}=this,r=Tt(n,t,this.calendar,{calendars:this.calendars,durationUnit:this.durationUnit});r.inCycle.length>0&&s>=0&&(this.lastCycle=r.inCycle,this._reject(mt(`The predecessors "{value}" would make a task depend on itself. The tasks in that loop keep their dates until it's fixed.`,{value:e})))}afterRecordWrite(){this.scheduleDirty=!0}flush(){if(this.scheduleDirty){this._writing++;try{this.reschedule()}finally{this._writing--}}super.flush()}editTask(s,e,n){const{table:t}=this,r={};for(const a of Object.keys(n))r[a]=t.get(e,a);this.book.transact(s,()=>(this._writeTask(e,n),this._taskClosure(e,r,n))),this.onRefresh?.()}_writeTask(s,e){const{table:n}=this;this._writing++;try{n.batch(()=>{for(const[t,r]of Object.entries(e))n.set(s,t,r)}),this.reschedule()}finally{this._writing--}this.view.refresh(),this.applyLayout(),this.notifyEngine()}_taskClosure(s,e,n){return()=>(this._writeTask(s,e),this.onRefresh?.(),this._taskClosure(s,n,e))}moveTask(s,e){const{table:n,fields:t}=this,r=n.column(t.start).data[s],a=this.schedule.calOf(s).nextWork(r+e);this.editTask("move task",s,{[t.constraint]:a,[t.start]:a})}setTaskFinish(s,e){const{table:n,fields:t}=this,r=this.schedule.calOf(s),a=n.column(t.start).data[s],o=r.fullDays?Math.floor(Math.max(e,a))+1:Math.max(e,a),l=r.unitsPer(this.durationUnit),u=Math.max(r.unitsBetween(a,o),(r.fullDays,1));this.editTask("resize task",s,{[t.duration]:Math.round(u/l*1e3)/1e3})}setTaskProgress(s,e){this.editTask("progress",s,{[this.fields.progress]:Math.max(0,Math.min(1,e))})}completeThrough(s,e){const n=this.schedule,{table:t,fields:r}=this,a=s??[...Array(t.rowCount).keys()].filter(d=>t.alive[d]===1&&n.isSummary[d]===0),o=a.map(d=>t.get(d,r.progress)),l=d=>{this._writing++;try{t.batch(()=>{a.forEach((m,f)=>t.set(m,r.progress,d[f]))}),this.reschedule()}finally{this._writing--}this.view.refresh(),this.applyLayout()},u=a.map(d=>{const m=n.calOf(d),f=n.duration[d];return f<=0?e>=n.momentStart[d]?1:0:Math.max(0,Math.min(1,m.unitsBetween(n.momentStart[d],e)/f))}),g=(d,m)=>()=>(l(d),this.onRefresh?.(),g(m,d));this.book.transact("complete through",()=>(l(u),g(o,u))),this.onRefresh?.()}setTaskMode(s,e){const{fields:n,table:t}=this;t.column(n.manual)&&this.editTask("schedule mode",s,{[n.manual]:e==="manual"})}link(s,e,n="FS",t=0){const{table:r,fields:a}=this,o=r.column(a.id).data[s],l=r.column(a.predecessors),u=rt(l.get(e))??[];if(u.some(d=>d.id===o))return!0;const g=pt([...u,{id:o,type:n,lag:t}]);return this._wouldCycle(e,g)?!1:(this.editTask("link tasks",e,{[a.predecessors]:g}),!0)}unlink(s,e){const{table:n,fields:t}=this,r=n.column(t.id).data[s],a=n.column(t.predecessors),o=rt(a.get(e))??[];this.editTask("unlink tasks",e,{[t.predecessors]:pt(o.filter(l=>l.id!==r))})}_wouldCycle(s,e){const{table:n,fields:t}=this,r=n.column(t.predecessors),a=r.data[s];r.data[s]=n.manager.strings.add(e);const o=Tt(n,t,this.calendar,{calendars:this.calendars,durationUnit:this.durationUnit});return r.data[s]=a,o.inCycle.length>0}addTask(s={},e=-1,n="task"){const{fields:t,table:r}=this,a=this.newRecordValues();if(n==="milestone"&&(a[t.duration]=0),e>=0){const l=r.column(t.order),u=r.column(t.parent).data[e];u===u&&(a[t.parent]=u);const g=l.data[e];let d=1/0;for(let m=0;m<r.rowCount;m++){const f=l.data[m];f>g&&f<d&&(d=f)}a[t.order]=d===1/0?g+1:(g+d)/2}let o=-1;return this.book.transact("add task",()=>{this._writing++;try{o=r.addRow({[t.name]:"New task",...a,...s}),this.view.invalidate(zt.FILTER),this.view.refresh(),this.reschedule()}finally{this._writing--}return this.view.refresh(),this._planRecordsClosure([o],!1)}),this.applyLayout(),this.notifyEngine(),this.onRefresh?.(),o}removeTasks(s){const e=this.schedule,{table:n}=this,t=new Set(s);for(let a=!0;a;){a=!1;for(let o=0;o<n.rowCount;o++)n.alive[o]===1&&!t.has(o)&&t.has(e.parentRow[o])&&(t.add(o),a=!0)}const r=[...t].filter(a=>n.alive[a]===1);return r.length===0?0:(this.book.transact("delete task",()=>(this._planApply(r,!0),this._planRecordsClosure(r,!0))),this.applyLayout(),this.notifyEngine(),this.onRefresh?.(),r.length)}_planApply(s,e){this._writing++;try{this.table.batch(()=>{for(const n of s)e?this.table.removeRow(n):this.table.restoreRow(n)}),this.view.invalidate(zt.FILTER),this.view.refresh(),this.reschedule()}finally{this._writing--}this.view.refresh()}_planRecordsClosure(s,e){return()=>(this._planApply(s,!e),this.applyLayout(),this.notifyEngine(),this.onRefresh?.(),this._planRecordsClosure(s,!e))}indent(s){const{fields:e,table:n}=this,t=this.view.rowOfRecord(s);if(t<=0)return!1;const r=this.view.treeLevel[s];for(let a=t-1;a>=0;a--){const o=this.view.recordAt(a);if(o<0)continue;const l=this.view.treeLevel[o];if(l===r)return this.editTask("indent",s,{[e.parent]:n.column(e.id).data[o]}),!0;if(l<r)return!1}return!1}outdent(s){const{fields:e,table:n}=this,t=this.schedule.parentRow[s];if(t<0)return!1;const r=n.column(e.parent).data[t],a=n.column(e.order),o=a.data[t];let l=1/0;for(let u=0;u<n.rowCount;u++){const g=a.data[u];g>o&&g<l&&(l=g)}return this.editTask("outdent",s,{[e.parent]:r===r?r:null,[e.order]:l===1/0?o+1:(o+l)/2}),!0}sortProject(s,e=!1,{keepOutline:n=!0,renumber:t=!1}={}){if(!t){this.viewOp("sort",f=>{f.setSort([{field:s,desc:e},{field:this.fields.order}]),n?f.spec.hierarchy||f.setHierarchy({key:this.fields.id,parent:this.fields.parent,column:this.fields.name}):f.setHierarchy(null)});return}const{table:r,fields:a}=this,o=new Int32Array(r.liveCount);let l=0;for(let f=0;f<r.rowCount;f++)r.alive[f]===1&&(o[l++]=f);const u=r.column(s);u&&re(r,o,l,u,e);const g=r.column(a.id),d=new Map;o.forEach((f,T)=>d.set(g.data[f],T+1));const m=f=>pt((rt(f)??[]).map(T=>({...T,id:d.get(T.id)??T.id})));this._writing++;try{r.batch(()=>{const f=r.column(a.predecessors),T=r.column(a.parent),O=this.assignmentTable;if(O){const y=O.column("taskId");for(let k=0;k<O.rowCount;k++){const S=y.data[k];d.has(S)&&(y.data[k]=d.get(S))}}for(let y=0;y<l;y++){const k=o[y],S=f.get(k);S&&r.set(k,a.predecessors,m(S));const _=T.data[k];_===_&&d.has(_)&&r.set(k,a.parent,d.get(_))}for(let y=0;y<l;y++){const k=o[y];r.set(k,a.id,y+1),r.set(k,a.order,y+1)}}),this.view.setSort([{field:a.order}]),this.reschedule()}finally{this._writing--}this._forgetSheetUndo(),this.view.refresh(),this.applyLayout(),this.onRefresh?.()}setBaseline(){const{table:s,fields:e}=this,n=[],t=s.rowCount,r=s.column(e.baselineStart),a=s.column(e.baselineFinish),o=s.column(e.start),l=s.column(e.finish);if(!r||!a)return;n.push(r.data.slice(0,t),a.data.slice(0,t));const u=(g,d)=>()=>{const m=r.data.slice(0,t),f=a.data.slice(0,t);return r.data.set(g),a.data.set(d),this.onRefresh?.(),u(m,f)};this.book.transact("baseline",()=>(r.data.set(o.data.subarray(0,t)),a.data.set(l.data.subarray(0,t)),u(n[0],n[1]))),this.onRefresh?.()}levelResources(){return this._leveling("level resources",()=>ce(this))}clearLeveling(){return this._leveling("clear leveling",()=>{const{table:s,fields:e}=this,n=s.column(e.levelStart).data,t=s.column(e.levelFrom).data,r=s.column(e.start).data;let a=0;for(let o=0;o<s.rowCount;o++)n[o]===n[o]&&(r[o]=t[o],n[o]=NaN,t[o]=NaN,a++);return a})}_leveling(s,e){const{table:n,fields:t}=this;for(const d of[t.levelStart,t.levelFrom])n.column(d)||n.addField({name:d,type:"date",hidden:!0});const r=[n.column(t.levelStart),n.column(t.levelFrom),n.column(t.start)],a=()=>{for(const d of r)d.revision++;this.reschedule(),this.view.refresh(),this.applyLayout(),this.notifyEngine(),this.onRefresh?.()},o=()=>r.map(d=>d.data.slice()),l=d=>()=>{const m=o();return r.forEach((f,T)=>f.data.set(d[T])),a(),l(m)},u=o();let g=0;return this.book.transact(s,()=>(g=e(),a(),l(u))),g}linkIndex(){const s=this.schedule;if(this._linkIndex?.schedule===s)return this._linkIndex;const{from:e,to:n,type:t}=s.links,r=s.rows,a=new Int32Array(r+1),o=new Int32Array(r+1);for(let m=0;m<e.length;m++)a[e[m]+1]++,o[n[m]+1]++;for(let m=0;m<r;m++)a[m+1]+=a[m],o[m+1]+=o[m];const l=new Int32Array(e.length),u=new Int32Array(e.length),g=a.slice(),d=o.slice();for(let m=0;m<e.length;m++)l[g[e[m]]++]=m,u[d[n[m]]++]=m;return this._linkIndex={schedule:s,outStart:a,outList:l,inStart:o,inList:u,from:e,to:n,type:t},this._linkIndex}resourceNamesChanged(){const s=this.resourceTable;if(!s)return;const e=[];for(let t=0;t<s.rowCount;t++)s.alive[t]===1&&e.push(s.get(t,"name"));const{fields:n}=this;this.view.spec.columns=this.view.spec.columns.map(t=>t.field===n.resource?{...t,validator:{type:"list",items:e,errorStyle:"warning",allowBlank:!0}}:t),this.view._columns=null,this.schedule&&(jt(this,this.schedule),this.invalidateCells(),this.onRefresh?.())}toJSON(){const s=this.scale;return{fields:this.fields,calendar:this.calendar.toJSON(),calendars:Object.fromEntries([...this.calendars].map(([e,n])=>[e,n.toJSON()])),durationUnit:this.durationUnit,scaleLevel:s.level,scale:{factor:s.factor,customTiers:s.customTiers?.map(({label:e,...n})=>n)??null,minDate:s.minDate,maxDate:s.maxDate,autoFit:s.autoFit,margin:s.margin},showCritical:this.showCritical,showBaseline:this.showBaseline,showLinks:this.showLinks,showLabels:this.showLabels,showToday:this.showToday,statusDate:this.statusDate,taskbarRules:this.taskbarRules,taskbarStyles:this.taskbarStyles,layout:this.layoutOptions,gridlines:this.gridlines,nonWorking:this.nonWorking,progressLine:this.progressLine,frozenLimit:this.frozenLimit,resourceTable:this.resourceTable?.name??null,assignmentTable:this.assignmentTable?.name??null}}}export{ae as CALENDAR_PRESETS,Ne as GanttSheet,Kt as LINK_TYPES,V as SCALE_LEVELS,Vt as TimeScale,oe as WorkCalendar,Tt as computeSchedule,Ee as createPlanTable,pt as formatLinks,Ct as levelOf,ge as normalizePlanRows,rt as parseLinks,be as shownDateNames,Se as topLabel,Jt as unitLabel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./query-function.js";import{Sheet as d}from"../core/sheet.js";import{DataManager as u}from"./data.js";import{TableView as o}from"./view.js";import{TableSheet as l}from"./table-sheet.js";import{createPlanTable as m,GanttSheet as c}from"./gantt.js";import{ReportTemplate as f}from"./report.js";import{TableBinding as g}from"./bind.js";import{CellPathBinding as p,RowsBinding as S}from"./path-binding.js";import{attachDataEntry as b}from"./report-entry.js";import{buildDataSheetPackage as _,dataSheetsFromJSON as w,dataSheetsToJSON as v,readDataSheetPackage as T}from"./persist.js";class E{constructor(e){this.book=e,this.manager=new u(e),e.dataSheets=this,this.sheets=[],this.bindings=[],this.reports=[],this.loaded=!1,this.onSheetAdded=null,this.savedSheets=null,this.loadNotes=[],this._hookInput(e)}_hookInput(e){if(e.setInputRouted)return;e.setInputRouted=!0;const t=e.setInput;e.setInput=function(i,r,n,h){const{sheet:a}=i;if(!(a.routeInput!==void 0&&a.routeInput(i,r,n,h)))return t.call(this,i,r,n,h)}}_uniqueName(e){const t=i=>this.book.sheets.some(r=>r.name.toLowerCase()===i.toLowerCase());let s=e;for(let i=2;t(s);i++)s=`${e}${i}`;return s}_insert(e,t=!0,s=null){const{book:i}=this;i.sheets.push(e),t&&(i.activeSheet=i.sheets.length-1),i.structureEdited=!0,i.engine?.sheetsChanged(),s?.(),i._emit("sheets")}_registerSheet(e){this.sheets.push(e),this.onSheetAdded?.(e)}_registerBinding(e){this.bindings.push(e),this.onSheetAdded?.(e.sheet)}isDataSheet(e){return e.isVirtual===!0}addTableFromSheetTable(e,t=null){const s=e,i=this.manager.addTable(t??`${s.name} Data`);return i.loadSheet(this.book,s.sheet,{r0:s.r0,c0:s.c0,r1:s.r1-s.totalsRows,c1:s.c1}),i}addTable(e,t){return this.manager.addTable(e,t)}addTableSheet(e,t,s={},i={}){const r=this.manager.table(t),n=s instanceof o?s:new o(r,s),h=new l(this.book,this._uniqueName(e),n,i);return this._insert(h,i.activate!==!1,()=>this._registerSheet(h)),h}addGanttSheet(e,t=null,s={}){const i=Array.isArray(t)?t:[],r=t&&!Array.isArray(t)?this.manager.table(t):m(this.manager,this._freeTable(`${e} Tasks`),i),n=new c(this.book,this._uniqueName(e),r,s);return this._insert(n,s.activate!==!1,()=>this._registerSheet(n)),n}_freeTable(e){let t=e;for(let s=2;this.manager.tables.has(t);s++)t=`${e} ${s}`;return t}addReportSheet(e,t={}){const s=new d(this._uniqueName(e));let i=null;return this._insert(s,t.activate!==!1,()=>{i=new f(this.manager,s,t),this.reports.push(i),this.onSheetAdded?.(s)}),i}bindPaths(e,t=null,s={}){const i=new p(this.book,e,t,s);return this._registerBinding(i),i}bindRows(e,t,s,i={}){const r=new S(this.book,e,t,s,i);return this._registerBinding(r),r}dataEntry(e){if(!e.output)throw new Error("Generate the report first.");return b(this.book,e,e.output)}toJSON(){return v(this)}fromJSON(e){return w(e,this),this}bindTable(e,t,s,i={}){const r=new g(this.book,e,t,s,i);return this._registerBinding(r),r}removeBinding(e){e.unbind(),this.bindings=this.bindings.filter(t=>t!==e)}_pruneDeleted(){const e=new Set(this.book.sheets);this.sheets=this.sheets.filter(t=>e.has(t)),this.bindings=this.bindings.filter(t=>e.has(t.sheet)),this.reports=this.reports.filter(t=>e.has(t.sheet))}prepareSave(){this._pruneDeleted();for(const e of this.sheets)e.prepareSave();this.savedSheets=this.sheets.slice()}async savePackage(){for(const t of this.sheets)t.savePlanned?.();const e=await _(this);return e.parts.length===0&&!this.loaded?null:e}finishSave(){for(const e of this.savedSheets??[])e.finishSave();this.savedSheets=null}async load(e){return T(e,this)}}export{E as DataSheets};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{FORMULA as k,STR as q}from"../core/sheet.js";import{cellRef as B,colName as F,MAX_COLS as m}from"../core/address.js";import{translateFormula as T}from"../core/formula-refs.js";import{createTable as R,resizeTable as U}from"../core/tables.js";import{hookSheet as $,rawCells as p,TableBinding as v,unhookSheet as E,valueOfWrite as N,writeRaw as O}from"./bind.js";import{DataError as S}from"./data.js";import{getPath as y,setPath as w}from"./remote.js";const g=(i,t)=>i*m+t;function _(i){const t=i.book.dataSheets;t&&(t.bindings=t.bindings.filter(e=>e!==i)),i.unbind()}function C(i,t){const e=i.usedRange(),{captions:s,rows:r}=i.exportRows();switch(t){case"json":return JSON.stringify(r,null,2);case"csv":{const o=n=>{const h=n==null?"":String(n);return/[",\n]/.test(h)?`"${h.replace(/"/g,'""')}"`:h};return[s.map(o).join(","),...r.map(n=>s.map(h=>o(n[h])).join(","))].join(`\r
|
|
2
|
+
`)}case"table":return _(i),R(i.book,i.sheet,e,!0);case"values":return _(i),e;default:throw new S(`Unknown export form: ${t}`)}}class M{constructor(t,e){this.book=t,this.sheet=e,this.quiet=0,this.options={},$(e),e.dataBindings.push(this)}redraw(){this.refresh()}unbind(){const t=this.sheet.dataBindings;t.splice(t.indexOf(this),1),E(this.sheet)}_notify(t,e){const s=this.book.engine;this.sheet.revision++,s&&s.deps.get(this.sheet)!==void 0&&t.length>0&&s.cellsChanged(this.sheet,Uint32Array.from(t),Uint16Array.from(e),t.length),this.options.onRefresh?.()}formulaWritten(t,e,s){if(this.quiet>0)return;const r=s.f??s.sf,{engine:o}=this.book;if(r===void 0||!o)return;let n;try{n=o.template(r,t,e).fn(t,e,this.sheet),n&&n.isCell&&(n=o.read(n.sheet,n.r0,n.c0))}catch{n=null}p.setFormula.call(this.sheet,t,e,null),this._store(t,e,n)}cellWritten(t,e,s,r){this.quiet>0||s&k||this._store(t,e,N(this.book.strings,s,r))}}class H extends M{constructor(t,e,s=null,r={}){super(t,e),this.source=s,this.options=r,this.paths=new Map,this.fieldOptions=new Map}bindCell(t,e,s){this.paths.set(g(t,e),s),this._renderCell(t,e,s),this._notify([t],[e])}clearCell(t,e){this.paths.delete(g(t,e))}clearAll(){this.paths.clear(),this.fieldOptions.clear()}pathAt(t,e){return this.paths.get(g(t,e))??null}contains(t,e){return this.paths.has(g(t,e))}setSource(t){this.source=t,this.refresh()}setRecord(t){this.source={...this.source,record:t},this.refresh()}_read(t){const e=this.source;if(e==null)return null;if(e.table){const r=typeof e.table=="string"?this.book.dataSheets?.manager.table(e.table)??null:e.table;return!r||e.record===void 0||e.record>=r.rowCount?null:r.get(e.record,t)}const s=y(e,t);return s===void 0?null:s}_renderCell(t,e){this.quiet++,O(this.sheet,this.book.strings,t,e,this._read(this.paths.get(g(t,e)))),this.quiet--}refresh(){const t=[],e=[];for(const s of this.paths.keys()){const r=Math.floor(s/m),o=s-r*m;this._renderCell(r,o),t.push(r),e.push(o)}this._notify(t,e)}_store(t,e,s){const r=this.paths.get(g(t,e)),o=this.source;if(!(r===void 0||o===null||o===void 0)){if(o.table){const n=typeof o.table=="string"?this.book.dataSheets?.manager.table(o.table):o.table;try{n.set(o.record,r,s)}catch(h){if(!(h instanceof S))throw h;this.options.onRejected?.(h.message),queueMicrotask(()=>this._renderCell(t,e))}return}w(o,r,s)}}autoGenerateLabels(t="left"){const e=t==="up"?-1:0,s=t==="left"?-1:0;this.book.transact("labels",r=>{for(const[o,n]of this.paths){const h=Math.floor(o/m),c=o-h*m;h+e<0||c+s<0||(r.sheet.kind(h+e,c+s)&7)===0&&!this.contains(h+e,c+s)&&this.book.setInput(r,h+e,c+s,A(n))}})}shift(t){const e=new Map;for(const[s,r]of this.paths){let o=Math.floor(s/m),n=s-o*m;t.axis==="row"&&o>=t.at&&(o+=t.n),t.axis==="col"&&n>=t.at&&(n+=t.n),o>=0&&n>=0&&e.set(g(o,n),r)}this.paths=e}toJSON(){const t=this.source;return{kind:"paths",sheet:this.sheet.name,paths:[...this.paths],fieldOptions:[...this.fieldOptions],source:t&&t.table?{table:typeof t.table=="string"?t.table:t.table.name,record:t.record}:{data:t}}}}const A=i=>{const e=String(i).split(".").pop().replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ");return e.charAt(0).toUpperCase()+e.slice(1)};class z extends M{constructor(t,e,s,r,o={}){if(super(t,e),this.anchor={row:s.row??s.r0,col:s.col??s.c0},this.array=r,this.options={header:!0,...o},this.columns=(o.columns??I(r)).map(n=>typeof n=="string"?{path:n}:n).filter(n=>!n.hidden),this.table=o.table??null,this.lastRows=0,this.styles=new Map,this.refresh(),o.asTable&&!this.table&&t.engine){const n=this.anchor;this.table=R(t,e,{r0:n.row,c0:n.col,r1:n.row+Math.max(1,r.length),c1:n.col+this.columns.length-1},!0)}}get headerRows(){return this.options.header?1:0}usedRange(){const{row:t,col:e}=this.anchor;return{r0:t,c0:e,r1:t+this.headerRows+Math.max(this.array.length,1)-1,c1:e+this.columns.length-1}}exportRows(){const t=this.columns.map(s=>s.caption??s.path),e=this.array.map(s=>{const r={};return this.columns.forEach((o,n)=>{r[t[n]]=o.path?y(s,o.path)??null:null}),r});return{captions:t,rows:e}}contains(t,e){const{row:s,col:r}=this.anchor;return e<r||e>=r+this.columns.length||t<s||this.columns[e-r].formula?!1:t<s+this.headerRows+this.array.length+1}_styleOf(t){if(!t||t==="General")return 0;let e=this.styles.get(t);return e===void 0&&(e=this.book.styles.derive(0,{numFmt:t}),this.styles.set(t,e)),e}refresh(){const{sheet:t,book:e,anchor:s,array:r,columns:o}=this,n=s.row+this.headerRows;this.quiet++,o.forEach((a,l)=>{const u=s.col+l;a.width&&t.cols.setSize(u,a.width),this.headerRows&&p.setCell.call(t,s.row,u,q,e.strings.add(a.caption??A(a.path??`Column${l+1}`)));const b=this._styleOf(a.format);if(a.formula){const d=String(a.formula).replace(/^=/,"");for(let f=0;f<r.length;f++)p.setCell.call(t,n+f,u,k,0),p.setFormula.call(t,n+f,u,{f:T(d,f,0),typed:!0}),b&&p.setStyle.call(t,n+f,u,b);return}for(let d=0;d<r.length;d++){const f=y(r[d],a.path);O(t,e.strings,n+d,u,f===void 0?null:f),b&&t.cellStyle(n+d,u)===0&&p.setStyle.call(t,n+d,u,b)}});for(let a=r.length;a<this.lastRows;a++)for(let l=0;l<o.length;l++)p.setCell.call(t,n+a,s.col+l,0,0),p.setFormula.call(t,n+a,s.col+l,null);const h=Math.max(r.length,this.lastRows);this.lastRows=r.length,this.quiet--;const c=[],x=[];if(o.forEach((a,l)=>{c.push(s.row,n+Math.max(0,h-1)),x.push(s.col+l,s.col+l)}),this._notify(c,x),this.table&&this.book.engine){const a=this.anchor,l={r0:a.row,c0:a.col,r1:a.row+Math.max(1,r.length),c1:a.col+o.length-1};this.table.r1!==l.r1&&U(this.book,this.table,l)}}_store(t,e,s){const{anchor:r,array:o}=this,n=this.columns[e-r.col],h=t-r.row-this.headerRows;if(h<0){typeof s=="string"&&(n.caption=s);return}if(h===o.length){if(s===null)return;const c={};w(c,n.path,s),o.push(c),this.lastRows=o.length,queueMicrotask(()=>this.refresh());return}o[h]&&w(o[h],n.path,s)}shiftRecords(t,e=!1){if(t.axis!=="row")return;const s=t.at-this.anchor.row-this.headerRows;if(s<0||s>this.array.length)return;const r=this.removedItems??(this.removedItems=[]);if(t.n>0){const o=e&&r.at(-1)?.length===t.n?r.pop():Array.from({length:t.n},()=>({}));this.array.splice(s,0,...o)}else r.push(this.array.splice(s,-t.n));this.refresh()}shift(t){t.axis==="row"&&t.at<=this.anchor.row&&(this.anchor.row+=t.n),t.axis==="col"&&t.at<=this.anchor.col&&(this.anchor.col+=t.n)}toJSON(){return{kind:"rows",sheet:this.sheet.name,anchor:this.anchor,columns:this.columns,options:{header:this.options.header},table:this.table?.name??null,data:this.array}}}function I(i){const t=new Set;for(const e of i.slice(0,100))if(e&&typeof e=="object")for(const s of Object.keys(e))t.add(s);return[...t].map(e=>({path:e}))}z.prototype.exportAs=function(t){return C(this,t)},v.prototype.exportAs=function(t){return C(this,t)};function j(i){return Array.isArray(i)?{type:"table",fields:j(i[0]??{}).fields}:i!==null&&typeof i=="object"&&!(i instanceof Date)?{type:"object",fields:Object.entries(i).map(([t,e])=>({name:t,...j(e)}))}:{type:"text"}}function J(i){if(i.type==="table")return[];if(i.type==="object"||i.fields){const t={};for(const e of i.fields??[])t[e.name]=J(e);return t}return null}export{H as CellPathBinding,z as RowsBinding,B as cellRef,F as colName,C as exportBinding,J as sampleOf,j as schemaOf};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const x="urn:8sheets:datasheets:2",u="customXml/ds8c",S="manifest",y="application/xml",b="http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",g="xl/datasheets/",w="https://8cells.app/relationships/datasheets",m=new TextEncoder,n=m.encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),X=a=>`${u}${a+1}.xml`,R=a=>a.startsWith(g),$=a=>a.startsWith(u)||R(a);function C(a,o,t=null){for(const e of a.entries.keys())$(e)&&o.add(e);for(const e of t?.replaced??[])o.add(e)}const h=a=>a.replace(/[.*+?^${}()|[\]\\/]/g,"\\$&");function D(a,o){let t=a.replace(/<Override\b[^>]*PartName="\/(?:xl\/datasheets\/|customXml\/ds8c)[^"]*"[^>]*\/>/g,"");for(const s of o?.replaced??[])t=t.replace(new RegExp(`<Override\\b[^>]*PartName="/${h(s)}"[^>]*/>`),"");const e=(o?.parts??[]).map(s=>`<Override PartName="/${s.file}" ContentType="${y}"/>`).join("");return t.replace("</Types>",`${e}</Types>`)}function L(a,o){let t=a.replace(new RegExp(`<Relationship\\b[^>]*Type="${h(w)}"[^>]*/>`,"g"),"").replace(/<Relationship\b[^>]*Target="\/?(?:\.\.\/)?customXml\/ds8c[^"]*"[^>]*\/>/g,"");for(const s of o?.replaced??[]){const r=s.replace(/^customXml\//,"");t=t.replace(new RegExp(`<Relationship\\b[^>]*Target="[^"]*customXml/${h(r)}"[^>]*/>`),"")}const e=(o?.parts??[]).map((s,r)=>`<Relationship Id="rId8cDs${r+1}" Type="${b}" Target="/${s.file}"/>`).join("");return t.replace("</Relationships>",`${e}</Relationships>`)}async function T(a,o){const t=new Uint8Array(262144);let e=0,s=0,r=0,i=0;const f=async()=>{e>0&&(await o(t.slice(0,e)),e=0)};for await(const p of a){let l=0;const d=p.length;if(i>0)if(i===1&&d>=2){const c=s<<16|p[0]<<8|p[1];l=2,t[e++]=n[c>>18],t[e++]=n[c>>12&63],t[e++]=n[c>>6&63],t[e++]=n[c&63],i=0}else if(i===2&&d>=1){const c=s<<16|r<<8|p[0];l=1,t[e++]=n[c>>18],t[e++]=n[c>>12&63],t[e++]=n[c>>6&63],t[e++]=n[c&63],i=0}else{i===1&&d===1&&(r=p[0],i=2);continue}for(;l+2<d;){e+4>t.length&&await f();const c=p[l]<<16|p[l+1]<<8|p[l+2];t[e]=n[c>>18],t[e+1]=n[c>>12&63],t[e+2]=n[c>>6&63],t[e+3]=n[c&63],e+=4,l+=3}l<d&&(s=p[l],i=1,l+1<d&&(r=p[l+1],i=2)),e+8>t.length&&await f()}i===1?(t[e++]=n[s>>2],t[e++]=n[(s&3)<<4],t[e++]=61,t[e++]=61):i===2&&(t[e++]=n[s>>2],t[e++]=n[(s&3)<<4|r>>4],t[e++]=n[(r&15)<<2],t[e++]=61),await f()}async function*E(a){const o=a.stream().getReader();for(;;){const{done:t,value:e}=await o.read();if(t)return;yield e}}async function N(a,o,t){for(const e of o?.parts??[]){t?.add(e.file);const s=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
2
|
+
<d xmlns="${x}" n="${e.name}" b="${e.bytes}">`;await a.add(e.file,async r=>{await r(m.encode(s)),await T(E(e.blob),r),await r(m.encode("</d>"))},{large:e.blob.size>2952790016})}}export{y as CUSTOM_XML_TYPE,S as MANIFEST_NAME,x as NS,X as partFileName,D as patchDataSheetContentTypes,L as patchDataSheetWorkbookRels,C as skipOldDataSheetParts,N as writeDataSheetParts};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{decodeBytes as Y}from"../core/strings.js";import{MANIFEST_NAME as L,NS as q,partFileName as K}from"./persist-writer.js";import{ROW as J}from"./data.js";import{TableView as Q}from"./view.js";import{TableSheet as Z}from"./table-sheet.js";import{GanttSheet as z,WorkCalendar as j}from"./gantt.js";import{ReportTemplate as ee}from"./report.js";import{TableBinding as te}from"./bind.js";import{CellPathBinding as ne,RowsBinding as oe}from"./path-binding.js";import{t as se}from"../i18n/index.js";const M=2,U=new TextEncoder,O=1<<18,A=()=>new Promise(e=>setTimeout(e,0)),$=e=>e!==null&&!e.lookup&&!e.rollup&&!e.window&&!e.name.startsWith("__formula:")&&!e.name.startsWith("__cross:");function F(e){const i={name:e.name,type:e.type};return e.caption!==e.name&&(i.caption=e.caption),e.format!=="General"&&!(e.type==="date"&&e.format==="yyyy-mm-dd")&&(i.format=e.format),e.readOnly&&(i.readOnly=!0),e.width!==null&&(i.width=e.width),e.hidden&&(i.hidden=!0),e.formula!==null&&(i.formula=e.formula),e.defaultValue!==null&&(i.defaultValue=e.defaultValue),e.required&&(i.required=!0),e.showNullAs!==null&&(i.showNullAs=e.showNullAs),e.validator!==null&&!e.validator.fn&&(i.validator=e.validator),e.trigger&&(i.trigger=e.trigger),i}function ie(e){const i=e.rowCount,{state:t,alive:r}=e;let o=!1;for(let l=0;l<i;l++)if(t[l]===J.PURGED&&r[l]===0){o=!0;break}if(!o)return null;const a=new Int32Array(i);let n=0;for(let l=0;l<i;l++)a[l]=t[l]===J.PURGED&&r[l]===0?-1:n++;return{map:a,count:n}}function C(e,i,t){if(t===null)return e.subarray(0,i);const r=new e.constructor(t.count);for(let o=0;o<i;o++)t.map[o]>=0&&(r[t.map[o]]=e[o]);return r}async function ae(e,i,t){const r=e.rowCount,o=ie(e),a=o?o.count:r,{strings:n}=e.manager,l=`t${i}/`,s=(d,h)=>(t.push({name:`${l}${d}`,blob:new Blob([h]),bytes:h.byteLength}),d),c=new Map,f=[],u=d=>{let h=c.get(d);return h===void 0&&(h=f.length,c.set(d,h),f.push(n.get(d))),h},m=[],g=[];let p=0;for(const d of e.columns){if(!$(d)||(m.push(F(d)),d.computed))continue;const h={field:d.name};if(d.isString){const b=C(d.data,r,o),y=new Int32Array(b.length);for(let w=0;w<b.length;w++){const D=b[w];y[w]=D<0?-1:u(D),++p%O===0&&await A()}h.encoding="i32",h.part=s(`c${d.index}.bin`,y)}else if(d.kinds!==null){const b=C(d.kinds,r,o),y=Float64Array.from(C(d.data,r,o));for(let w=0;w<y.length;w++)b[w]===2&&(y[w]=u(y[w])),++p%O===0&&await A();h.encoding="mixed",h.part=s(`c${d.index}.bin`,y),h.kinds=s(`c${d.index}.kinds`,b)}else h.encoding="f64",h.part=s(`c${d.index}.bin`,C(d.data,r,o));d.styles!==null&&(h.styles=s(`c${d.index}.styles`,C(d.styles,r,o))),g.push(h)}const S=[],k=new Float64Array(f.length+1);let x=0,v=[],N=0;const R=()=>{N!==0&&(S.push(U.encode(v.join(""))),v=[],N=0)};for(let d=0;d<f.length;d++){const h=re(f[d]);k[d]=x,x+=h,v.push(f[d]),N+=f[d].length,N>1<<20&&(R(),await A())}R(),k[f.length]=x,t.push({name:`${l}strings.bin`,blob:new Blob(S),bytes:x}),s("strings.idx",k);const G=C(e.alive,r,o),I=C(e.state,r,o);s("alive.bin",G),s("state.bin",I);const B=[];for(const[d,h]of e.originals){const b=o?o.map[d]:d;b<0||B.push([b,[...h].map(([y,w])=>[e.columns[y].name,_(w)])])}return{name:e.name,key:e.key,tracking:e.tracking,rowCount:a,dir:l,indexes:e.getIndexes(),windows:e.windowDefs,schema:e.schema,remote:E(e.remote),autoSync:e.autoSync,batch:e.batchSync,stringCount:f.length,fields:m,columns:g,originals:B,map:o}}function E(e){if(!e||typeof e!="object")return null;const i={};for(const[t,r]of Object.entries(e))typeof r!="function"&&(i[t]=r);return Object.keys(i).length>0?i:null}const _=e=>e!==null&&typeof e=="object"?{error:e.code}:e;function re(e){let i=e.length;for(let t=0;t<e.length;t++){const r=e.charCodeAt(t);if(r>=128)if(r<2048)i++;else if(r>=55296&&r<=56319){const o=e.charCodeAt(t+1);o>=56320&&o<=57343?(i+=2,t++):i+=2}else i+=2}return i}function T(e,i){const t=e.toJSON(),r=i.map;return r&&(t.pinnedRows=t.pinnedRows.map(o=>r.map[o]).filter(o=>o>=0),t.treeCollapsed=t.treeCollapsed.map(o=>r.map[o]).filter(o=>o>=0)),t}function le(e){return e.toJSON()}function W(e,i){let t=0;const r=new Map,{columns:o}=e;for(let a=0;a<o.length;a++){const n=o[a];if(n===void 0)continue;const l=n.length;for(let s=0;s<l;s++){const c=n[s];if(c===void 0)continue;const{kinds:f,values:u}=c;for(let m=0;m<f.length;m++){const g=f[m]&7;if(g===0)continue;let p;if(g===2){const k=u[m];if(p=r.get(k),p===void 0){p=7;const x=i.get(k);for(let v=0;v<x.length;v++)p=Math.imul(p,31)+x.charCodeAt(v)|0;r.set(k,p)}}else p=Math.round(u[m]*1e3)|0;const S=Math.imul((s<<10)+m+1,2654435761)^Math.imul(a+1,2246822507);t=t+Math.imul(p^S,625341585)|0}}}return t}function ce(e,i,t){return{sheet:e.name,kind:e.kindName,table:e.table.name,view:T(e.view,i(e.table)),options:e.options,gantt:e.kindName==="gantt"?e.toJSON():void 0,cells:W(e,t)}}function V(e,i){const{manager:t,sheets:r,bindings:o,reports:a,book:n}=e,l=s=>i.find(c=>c.name===s.name);return{format:"8sheets-datasheets",version:M,tables:i.map(({map:s,...c})=>c),relationships:t.relationships.map(s=>({from:s.from.name,fromField:s.fromField,to:s.to.name,toField:s.toField,name:s.name,inverse:s.inverse})),views:[...t.tables.values()].flatMap(s=>[...s.views.values()].map(c=>({table:s.name,name:c.name,view:T(c,l(s))}))),sheets:r.map(s=>ce(s,l,n.strings)),bindings:o.map(s=>s.toJSON?s.toJSON():{kind:"view",sheet:s.sheet.name,range:s.range,table:s.table.name,view:T(s.view,l(s.table)),options:{header:s.options.header,grow:s.options.grow,editable:s.options.editable,sticky:s.options.sticky}}),reports:a.map(le)}}async function Se(e){const{manager:i,sheets:t,bindings:r,reports:o}=e,a=e.sourceParts??[];if(!(i.tables.size>0||t.length>0||o.length>0||r.length>0))return{parts:[],replaced:a};const l=[],s=[];let c=0;for(const u of i.tables.values())s.push(await ae(u,c++,l));const f=U.encode(JSON.stringify(V(e,s)));return l.push({name:L,blob:new Blob([f]),bytes:f.length}),l.forEach((u,m)=>{u.file=K(m)}),{parts:l,replaced:a}}const fe=(()=>{const e=new Int8Array(256).fill(-1),i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(let t=0;t<64;t++)e[i.charCodeAt(t)]=t;return e})();async function ue(e,i){const t=(await e.stream(i)).getReader(),{value:r}=await t.read();if(t.cancel().catch(()=>{}),!r)return null;const o=new TextDecoder().decode(r.subarray(0,400));if(!o.includes(q))return null;const a=/\bn="([^"]*)"/.exec(o)?.[1],n=Number(/\bb="(\d+)"/.exec(o)?.[1]??0);return a===void 0?null:{name:a,bytes:n,file:i}}async function H(e,i,t){const r=(await e.stream(i)).getReader(),o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let a=0,n=!1,l=0,s=0;for(;;){const{done:c,value:f}=await r.read();if(c)break;let u=0;if(!n){let m=0;for(;u<f.length;u++)if(f[u]===62&&(m++,m===2)){u++,n=!0;break}if(!n)continue}for(;u<f.length;u++){const m=fe[f[u]];m<0||(l=l<<6|m,s++,s===4&&(a+3<=o.length?(o[a]=l>>16,o[a+1]=l>>8&255,o[a+2]=l&255):(a<o.length&&(o[a]=l>>16),a+1<o.length&&(o[a+1]=l>>8&255)),a+=3,l=0,s=0))}}s===2&&a<o.length&&(o[a]=l>>4),s===3&&(a<o.length&&(o[a]=l>>10),a+1<o.length&&(o[a+1]=l>>2&255))}async function de(e,i,t){const r=i.addTable(t.name,{key:t.key,tracking:t.tracking,capacity:t.rowCount,fields:t.fields,windows:t.windows,schema:t.schema,remote:t.remote,autoSync:t.autoSync,batch:t.batch,indexes:t.indexes}),{dir:o}=t,a=new Float64Array(t.stringCount+1);await e(`${o}strings.idx`,a);const n=new Uint8Array(a[t.stringCount]);await e(`${o}strings.bin`,n);const l=new Int32Array(t.stringCount);for(let c=0;c<t.stringCount;c++)l[c]=i.strings.add(Y(n,a[c],a[c+1])),(c+1)%O===0&&await A();r.rowCount=t.rowCount;for(const c of t.columns){const f=r.byName.get(c.field);if(f){if(c.encoding==="i32"){const u=new Int32Array(t.rowCount);await e(`${o}${c.part}`,u);const{data:m}=f;for(let g=0;g<t.rowCount;g++){const p=u[g];m[g]=p<0?-1:l[p]}}else if(c.encoding==="mixed"){await e(`${o}${c.part}`,new Float64Array(f.data.buffer,0,t.rowCount)),f.kinds=new Uint8Array(r.capacity),await e(`${o}${c.kinds}`,new Uint8Array(f.kinds.buffer,0,t.rowCount));for(let u=0;u<t.rowCount;u++)f.kinds[u]===2&&(f.data[u]=l[f.data[u]])}else await e(`${o}${c.part}`,new Float64Array(f.data.buffer,0,t.rowCount));c.styles&&(f.styles=new Uint16Array(r.capacity),await e(`${o}${c.styles}`,new Uint16Array(f.styles.buffer,0,t.rowCount))),await A()}}await e(`${o}alive.bin`,new Uint8Array(r.alive.buffer,0,t.rowCount)),await e(`${o}state.bin`,new Uint8Array(r.state.buffer,0,t.rowCount));let s=0;for(let c=0;c<t.rowCount;c++)r.alive[c]===0&&s++;r.deletedCount=s;for(const[c,f]of t.originals)r.originals.set(c,new Map(f.map(([u,m])=>[r.byName.get(u)?.index,m]).filter(([u])=>u!==void 0)));return r.revision++,r.structureRevision++,r._markAllComputedStale(),r}function P(e,i){const t=new Q(e,i);return t.applySavedState(i),t}async function Ne(e,i){const t=new Map,r=[];for(const c of e.entries.keys()){if(!c.startsWith("customXml/")||c.includes("/_rels/")||!c.endsWith(".xml")||/itemProps/i.test(c))continue;const f=await ue(e,c);f&&(t.set(f.name,f),r.push(c))}const o=t.get(L);if(!o)return!1;const a=new Uint8Array(o.bytes);await H(e,o.file,a);const n=JSON.parse(new TextDecoder().decode(a));if(n.format!=="8sheets-datasheets"||n.version>M)return!1;i.sourceParts=me(e,r);const l=async(c,f)=>{const u=t.get(c);u&&await H(e,u.file,f)},{manager:s}=i;for(const c of n.tables)await de(l,s,c);return X(n,i),i.loaded=!0,!0}function me(e,i){const t=[];for(const r of i){t.push(r);const o=r.slice(10),a=`customXml/_rels/${o}.rels`;if(e.has(a)){t.push(a);const n=/(\d+)\.xml$/.exec(o)?.[1];n&&e.has(`customXml/itemProps${n}.xml`)&&t.push(`customXml/itemProps${n}.xml`)}}return t}function he(e,i,t){return{view:i,fields:e.fields,calendar:new j(e.calendar),calendars:e.calendars,durationUnit:e.durationUnit,scaleLevel:e.scaleLevel,scale:e.scale,showCritical:e.showCritical,showBaseline:e.showBaseline,showLinks:e.showLinks,showLabels:e.showLabels,showToday:e.showToday,statusDate:e.statusDate,taskbarRules:e.taskbarRules,taskbarStyles:e.taskbarStyles,layout:e.layout,gridlines:e.gridlines,nonWorking:e.nonWorking,progressLine:e.progressLine,frozenLimit:e.frozenLimit,sheet:t}}function X(e,i){const{book:t,manager:r}=i;for(const n of e.relationships)r.addRelationship(n);for(const n of e.views??[]){const l=r.table(n.table);l.views.set(n.name,P(l,n.view))}const o=n=>t.sheets.find(l=>l.name===n),a=[];for(const n of e.sheets){const l=o(n.sheet);if(!l)continue;if(n.cells!==void 0&&!l.isVirtual&&W(l,t.strings)!==n.cells){a.push(n.sheet);continue}const s=r.table(n.table),c=P(s,n.view);let f;n.kind==="gantt"?(f=new z(t,n.sheet,s,he(n.gantt,c,n.options)),n.gantt.resourceTable&&(f.resourceTable=r.tables.get(n.gantt.resourceTable)??null,f.assignmentTable=r.tables.get(n.gantt.assignmentTable)??null,f.resourceNamesChanged())):f=new Z(t,n.sheet,c,n.options),f.adoptFrom(l),t.sheets[t.sheets.indexOf(l)]=f,i._registerSheet(f)}a.length>0&&i.loadNotes.push(se("{sheets} changed outside this app, so they stay plain sheets. The data tables are still there.",{sheets:a.join(", "),count:a.length}));for(const n of e.bindings){const l=o(n.sheet);if(l)if(n.kind==="paths"){const s=new ne(t,l,n.source?.table?n.source:n.source?.data??null);s.paths=new Map(n.paths),s.fieldOptions=new Map(n.fieldOptions??[]),s.refresh(),i._registerBinding(s)}else if(n.kind==="rows")i._registerBinding(new oe(t,l,n.anchor,n.data,{columns:n.columns,...n.options,table:n.table?t.engine?.tables.get(n.table.toUpperCase())??null:null}));else{const s=P(r.table(n.table),n.view);i._registerBinding(new te(t,l,n.range,s,n.options))}}for(const n of e.reports){const l=o(n.sheet);if(!l)continue;const s=new ee(r,l,{table:n.table,name:n.name,titleRows:n.titleRows,pageSetup:n.pageSetup,mode:n.mode,pagination:n.pagination,layout:n.layout,dataEntry:n.dataEntry,charts:n.charts,pictures:n.pictures,states:n.states,showHiddenRows:n.showHiddenRows,showHiddenCols:n.showHiddenCols});for(const c of n.bindings)s.setBinding(c.row,c.col,c);for(const c of n.params)s.addParam(c.name,c);s.filters=n.filters,s.output=n.output?o(n.output)??null:null,i.reports.push(s)}t.engine?.sheetsChanged(),t.engine?.rebuild()}function Oe(e){const{manager:i,book:t}=e,r=[...i.tables.values()].map(a=>{const n=[],l=a.columns.filter(s=>$(s)&&!s.computed);for(let s=0;s<a.rowCount;s++){if(a.alive[s]===0)continue;const c={};for(const f of l){const u=f.get(s);u!==null&&(c[f.name]=_(u))}n.push(c)}return{name:a.name,key:a.key,tracking:a.tracking,windows:a.windowDefs,schema:a.schema,remote:E(a.remote),autoSync:a.autoSync,batch:a.batchSync,indexes:a.getIndexes(),fields:a.columns.filter($).map(F),rows:n}}),o=V(e,r.map(a=>({name:a.name,map:null})));o.tables=r;for(const a of o.sheets)delete a.cells;return o}function $e(e,i){const{book:t,manager:r}=i;for(const o of e.tables){const{rows:a,...n}=o;r.addTable(o.name,n).load(a)}for(const o of e.sheets)t.sheets.some(a=>a.name===o.sheet)||t.addSheet(o.sheet);for(const o of e.reports??[])t.sheets.some(a=>a.name===o.sheet)||t.addSheet(o.sheet);X(e,i)}export{Se as buildDataSheetPackage,$e as dataSheetsFromJSON,Oe as dataSheetsToJSON,he as ganttOptions,W as hashSheetCells,Ne as readDataSheetPackage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{raw as p}from"../calc/functions/registry.js";import{Arr as E,ERR as a,Ref as R,str as h}from"../calc/values.js";import{formulaHelper as g}from"./view.js";import{sortColumn as y}from"./sort.js";const A=l=>l??"";function C(l,n){const i=/^(.+?)(?:#(\d+)|\/(.+)|\?([^=]+)=(.*))?$/.exec(n),e=l?.tables.get(i?.[1]);if(!e)return null;if(i[2]!==void 0){const t=Number(i[2]);let d=-1;for(let u=0;u<e.rowCount;u++)if(e.alive[u]===1&&++d===t)return{table:e,rows:[u]};return{table:e,rows:[]}}const r=(t,d)=>{const u=[];e.ensure(t);for(let f=0;f<e.rowCount;f++)e.alive[f]===1&&String(t.get(f))===d&&u.push(f);return u};if(i[3]!==void 0){const t=e.column(e.key);return t?{table:e,rows:r(t,i[3])}:null}if(i[4]!==void 0){const t=e.column(i[4]);return t?{table:e,rows:r(t,i[5])}:null}const o=[];for(let t=0;t<e.rowCount;t++)e.alive[t]===1&&o.push(t);return{table:e,rows:o}}function S(l,n,i){if(n===void 0||n==="")return i.fields.map(r=>r.name);if(n instanceof R){const r=[];for(let o=n.r0;o<=n.r1;o++)for(let t=n.c0;t<=n.c1;t++)r.push(String(l.engine?.read?.(n.sheet,o,t)??""));return r.map(o=>o.trim()).filter(Boolean)}if(n instanceof E)return n.data.map(r=>String(r).trim()).filter(Boolean);const e=h(n).trim();return e===""?i.fields.map(r=>r.name):e.split(",").map(r=>r.trim())}p("QUERY",1,4,(l,n)=>{const i=C(l.book.dataSheets?.manager,h(n[0]));if(!i)return a.VALUE;const{table:e}=i,r=S(l,n[1],e).map(s=>e.column(s));if(r.some(s=>!s))return a.REF;for(const s of r)e.ensure(s);let o=Int32Array.from(i.rows);const t=n[2],d=t===!0;if(typeof t=="string"&&t!==""){const s=g(e,t);o=o.filter(c=>{const m=s.get(c);return m===!0||typeof m=="number"&&m!==0})}const u=n[3]===void 0?"":h(n[3]).trim();if(u!==""){const[s,c]=u.split(/\s+/),m=e.column(s);if(!m)return a.REF;e.ensure(m),y(e,o,o.length,m,/^desc/i.test(c??""))}const f=d?Math.min(1,o.length):o.length;if(f===0)return a.NA;const w=new Array(f*r.length);for(let s=0;s<f;s++)for(let c=0;c<r.length;c++)w[s*r.length+c]=A(r[c].get(o[s]));return new E(f,r.length,w)},{volatile:!0}),p("CALCULATE",1,2,(l,n)=>n[0]),p("REMOVEFILTERS",0,255,()=>0);
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{unescapeXml as T}from"../io/xml-scan.js";import{t as j}from"../i18n/index.js";import{mayReach as P,OFFLINE_MESSAGE as R,onlineAllowed as k}from"../core/online.js";function F(t,n){if(t===null||typeof t!="object")return;const r=t[n];if(r!==void 0)return r;if(n.includes("."))return A(t,n)}function A(t,n){let r=t;for(const e of String(n).split(".")){if(r==null)return;r=r[e]}return r}function J(t,n,r){const e=String(n).split(".");let o=t;for(let s=0;s<e.length-1;s++){const a=e[s];(o[a]===null||typeof o[a]!="object")&&(o[a]=/^\d+$/.test(e[s+1])?[]:{}),o=o[a]}o[e[e.length-1]]=r}function q(t,n="",r={}){for(const[e,o]of Object.entries(t)){const s=n?`${n}.${e}`:e;o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)?q(o,s,r):r[s]=o}return r}function _(t,n=","){const r=[];let e=[],o="",s=!1;for(let u=0;u<t.length;u++){const c=t[u];s?c==='"'?t[u+1]==='"'?(o+='"',u++):s=!1:o+=c:c==='"'?s=!0:c===n?(e.push(o),o=""):c===`
|
|
2
|
+
`||c==="\r"?(c==="\r"&&t[u+1]===`
|
|
3
|
+
`&&u++,e.push(o),o="",r.push(e),e=[]):o+=c}if((o!==""||e.length>0)&&(e.push(o),r.push(e)),r.length===0)return[];const[a,...i]=r;return i.map(u=>{const c={};return a.forEach((d,g)=>{c[d]=E(u[g])}),c})}function E(t){if(t===void 0||t==="")return null;if(/^[+-]?(\d+([.]\d*)?|[.]\d+)([eE][+-]?\d+)?$/.test(t)&&!/^0\d/.test(t))return Number(t);const n=t.toUpperCase();return n==="TRUE"?!0:n==="FALSE"?!1:t}function C(t,n){const r=[],e=n??L(t);if(!e)return r;const o=new RegExp(`<${e}\\b([^>]*?)(?:/>|>([\\s\\S]*?)</${e}>)`,"g"),s=/<([A-Za-z_][\w.-]*)\b[^>]*?(?:\/>|>([\s\S]*?)<\/\1>)/g,a=/([A-Za-z_][\w.-]*)="([^"]*)"/g;for(const i of t.matchAll(o)){const u={};for(const c of(i[1]??"").matchAll(a))u[c[1]]=E(T(c[2]));for(const c of(i[2]??"").matchAll(s))u[c[1]]=E(T(c[2]??""));r.push(u)}return r}function L(t){const n=new Map;let r=0;for(const s of t.matchAll(/<(\/?)([A-Za-z_][\w.-]*)\b[^>]*?(\/?)>/g)){if(s[1]){r--;continue}r===1&&n.set(s[2],(n.get(s[2])??0)+1),s[3]||r++}let e=null,o=0;for(const[s,a]of n)a>o&&(e=s,o=a);return e}function z(t,n){const r=n.type??"json";let e=t;if(typeof e=="string"){if(r==="csv")return _(e,n.delimiter);if(r==="xml")return C(e,n.recordName);e=JSON.parse(e)}if(n.dataPath&&(e=A(e,n.dataPath)),r==="columnJson"&&e&&!Array.isArray(e)){const o=Object.keys(e),s=o.reduce((i,u)=>Math.max(i,e[u].length),0),a=new Array(s);for(let i=0;i<s;i++){const u={};for(const c of o)u[c]=e[c][i];a[i]=u}return a}return e??[]}function S(t,n){const r=n.min??n.value,e=n.max;switch(n.operator){case"between":return t>=r&&t<=e;case"notBetween":return t<r||t>e;case"equal":return t===r;case"notEqual":return t!==r;case"greaterThan":return t>r;case"lessThan":return t<r;case"greaterThanOrEqual":return t>=r;case"lessThanOrEqual":return t<=r;default:return!(n.min!==void 0&&t<n.min||n.max!==void 0&&t>n.max)}}function I(t,n,r=-1){const e=t.validator;if(n==null)return e.allowBlank===!1?j("The {field} field can't be blank.",{field:t.caption}):null;if(e.errorStyle==="warning"||e.errorStyle==="information")return null;const o=()=>e.message??j("That isn't a valid value for the {field} field.",{field:t.caption});switch(e.type){case"list":return(e.items??[]).some(s=>String(s).toLowerCase()===String(n).toLowerCase())?null:o();case"whole":return typeof n=="number"&&Number.isInteger(n)&&S(n,e)?null:o();case"number":case"decimal":case"date":return typeof n=="number"&&S(n,e)?null:o();case"time":return typeof n!="number"?o():S(n-Math.floor(n),e)?null:o();case"textLength":return S(String(n).length,e)?null:o();case"custom":{if(e.fn)return e.fn(n)?null:o();if(!e.formula||r<0)return null;const s=typeof n=="string"?`"${n.replace(/"/g,'""')}"`:String(n),a=String(e.formula).split(`[@${t.name}]`).join(s),i=t.table.manager.formulas.evaluateOnce(t.table,r,a);return i===!0||typeof i=="number"&&i!==0?null:o()}default:return null}}const h=t=>typeof t=="string"?{url:t}:t;async function m(t,{url:n,method:r,body:e,query:o}={}){const s=new URL(n??t.url,globalThis.location?.href??"http://localhost/");for(const[c,d]of Object.entries({...t.query??{},...o??{}}))s.searchParams.set(c,d);const a={method:r??t.method??"GET",headers:{Accept:"application/json",...t.headers??{}}};if(e!==void 0&&(a.headers["Content-Type"]=a.headers["Content-Type"]??"application/json",a.body=typeof e=="string"?e:JSON.stringify(e)),!P(s.href))throw new Error(j(R));k()||(a.redirect="error");const i=await fetch(s,a);if(!i.ok)throw new Error(`${i.status} ${i.statusText}`);if(i.status===204)return null;const u=i.headers.get("content-type")??"";return/json/.test(u)?i.json():i.text()}const $=(t,n)=>typeof t=="string"&&(n?.type??"json")==="json"?JSON.parse(t):t;async function Z(t,n){const r=t.read??t;if(typeof r=="function")return r();const e=h(r),o=e.protocol??t.protocol??"json";if(o==="graphql"){const a=$(await m(e,{method:"POST",body:{query:e.query_??e.graphql,variables:e.variables}}),n),i=a.data??a;return n?.dataPath?i:Object.values(i)[0]??[]}const s=$(await m(e,{body:e.body}),n);return o==="odata"&&!n?.dataPath?s?.d?.results??s?.d??s?.value??s:o==="odata4"&&!n?.dataPath?s?.value??s:s}const O=(t,n,r)=>r==="odata"||r==="odata4"?`${t.url}(${typeof n=="string"?`'${n}'`:n})`:`${String(t.url).replace(/\/$/,"")}/${encodeURIComponent(n)}`;async function B(t,n){const r=t.remote,{inserted:e,updated:o,deleted:s}=n,a=new Map,i={inserted:e.length,updated:o.length,deleted:s.length};if(typeof r=="object"&&r.create===void 0&&r.update===void 0&&r.delete===void 0&&r.remove===void 0&&r.batch===void 0)return{errors:a,counts:i};const{key:u}=t,c=r.protocol??h(r.read??{})?.protocol??"json";if(typeof r.batch=="function"||r.batch&&t.batchSync){const l=[...e.map(f=>({op:"insert",data:f})),...o.map(f=>({op:"update",data:f.record,original:f.original})),...s.map(f=>({op:"delete",data:f.record}))];if(l.length===0)return{errors:a,counts:i};try{typeof r.batch=="function"?await r.batch(l):await m(h(r.batch),{method:"POST",body:l})}catch(f){for(const p of e)a.set(p.__row,f.message);for(const p of o)a.set(p.row,f.message);for(const p of s)a.set(p.row,f.message)}return{errors:a,counts:i}}const d=async(l,f)=>{try{await f()}catch(p){a.set(l,p.message)}},g=(l,f)=>r[l]??(f?r[f]:void 0),y=g("create"),w=g("update"),b=g("delete","remove");if(typeof y=="function"){if(e.length>0)try{await y(e)}catch(l){for(const f of e)a.set(f.__row,l.message)}}else if(y)for(const l of e)await d(l.__row,()=>m(h(y),{method:"POST",body:l}));if(typeof w=="function"){if(o.length>0)try{await w(o)}catch(l){for(const f of o)a.set(f.row,l.message)}}else if(w){const l=h(w);for(const f of o)await d(f.row,()=>m(l,{url:O(l,u?f.record[u]:f.row,c),method:l.method??(c==="json"?"PUT":"PATCH"),body:c==="json"?f.record:f.changes}))}if(typeof b=="function"){if(s.length>0)try{await b(s)}catch(l){for(const f of s)a.set(f.row,l.message)}}else if(b){const l=h(b);for(const f of s)await d(f.row,()=>m(l,{url:O(l,u?f.record[u]:f.row,c),method:"DELETE"}))}return{errors:a,counts:i}}export{I as checkValidator,q as flattenRecord,A as getPath,z as parseSource,F as readField,Z as readRemote,B as sendChanges,J as setPath};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Sheet as p}from"../core/sheet.js";import{DataError as g,ROW as h}from"./data.js";import{valueOfWrite as m}from"./bind.js";import{t as b}from"../i18n/index.js";const d=p.prototype.setCell;class y{constructor(t,e,s){this.book=t,this.template=e,this.out=s,this.onRejected=null,this.onRefresh=null,this.writing=!1,this._hook()}get settings(){return this.template.dataEntry??{}}_hook(){const t=this,{out:e}=this;e.reportEntry||(e.reportEntry=this,e.setCell=function(r,n,l,i){if(this.reportWriting||t.writing){d.call(this,r,n,l,i);return}t._written(r,n,l,i)})}cellInfo(t,e){const s=this.out.reportMap;if(!s||t>=s.rowRec.length)return null;const r=s.colTpl[e],n=s.overlay?.get(t)??s.rowTpl[t],l=this.template.binding(n,r);if(!l||l.type!=="list"||l.editable===!1)return null;const i=this.template.manager.table(l.table),o=s.contexts[s.rowCtx[t]];let a=s.rowRec[t];if(a<0&&(a=o?.table===i&&o.rows.length>0?o.rows[0]:-1),a<0)return null;const c=i.column(l.field);return!c||c.computed||c.readOnly?null:{table:i,rec:a,field:l.field,column:c,binding:l}}_written(t,e,s,r){const n=this.cellInfo(t,e);if(n===null){this.onRejected?.(b("Only list cells of a report take entries."));return}this.updateCellValue(t,e,m(this.book.strings,s,r),n)}updateCellValue(t,e,s,r=null){const n=r??this.cellInfo(t,e);if(n===null)return!1;const{table:l,rec:i,field:o,column:a}=n;if(a.get(i)===s)return!0;if(!this.template.fire("dataChanging",{row:t,col:e,record:i,field:o,value:s,table:l}))return!1;try{l.set(i,o,s)}catch(u){if(!(u instanceof g))throw u;return this.onRejected?.(u.message),!1}this.writing=!0;const c=a.kind(i);return d.call(this.out,t,e,c,a.raw(i)),this.writing=!1,this.out.revision++,this.template.fire("dataChanged",{row:t,col:e,record:i,field:o,value:s,table:l}),!0}isDirty(t,e){const s=this.cellInfo(t,e);if(s===null)return!1;const{table:r,rec:n,column:l}=s;return r.state[n]===h.INSERTED||r.isCellEdited(n,l)}_regenerate(){const t=this.template.generate(this.book,{target:this.out});return this.onRefresh?.(),t}tables(){const t=new Set;for(const e of this.template.bindings.values())e.type==="list"&&e.editable!==!1&&t.add(this.template.manager.table(e.table));return[...t]}_bindingOfRow(t){const e=this.out.reportMap,s=e.overlay?.get(t)??e.rowTpl[t];for(const r of e.colTpl){const n=this.template.binding(s,r);if(n&&n.type==="list")return n}return null}addRecordAt(t){const e=this.out.reportMap,s=this._bindingOfRow(t)??[...this.template.bindings.values()].find(i=>i.type==="list");if(!s)return-1;const r=this.template.manager.table(s.table),n={};for(let i=e.contexts[e.rowCtx[t]];i;i=i.parent){const o=i.node?.binding;if(o&&o.type==="group"&&i.table===r&&!o.by&&!o.size&&!o.bins&&!o.formula&&i.rows.length>0){const a=r.column(o.field);a&&!a.computed&&(n[o.field]=a.get(i.rows[0]))}}for(const[i,o]of Object.entries(this.settings.defaults??{}))n[i]===void 0&&(n[i]=typeof o=="string"&&/^=\s*UUID\(\s*\)$/i.test(o)?w():o);const l=r.addRow(n);return this._regenerate(),l}deleteRecordAt(t){const e=this.out.reportMap,s=this._bindingOfRow(t);if(!s)return!1;let r=e.rowRec[t];const n=this.template.manager.table(s.table);if(r<0){const l=e.contexts[e.rowCtx[t]];r=l?.table===n&&l.rows.length===1?l.rows[0]:-1}return r<0?!1:(n.removeRow(r),this._regenerate(),!0)}getChanges(){const t={inserted:[],updated:[],deleted:[]};for(const e of this.tables()){const s=e.getChanges(),r=n=>n.map(l=>({table:e.name,...l}));t.inserted.push(...r(s.inserted)),t.updated.push(...r(s.updated)),t.deleted.push(...r(s.deleted))}return t}async submit(){const t=this.getChanges();if(!this.template.fire("submitting",{changes:t}))return null;const{skipEmpty:e}=this.settings,s=[];let r=0;for(const n of this.tables()){if(e)for(let o=0;o<n.rowCount;o++)n.state[o]===h.INSERTED&&n.alive[o]===1&&n.columns.every(a=>a===null||a.computed||a.hidden||a.kind(o)===0)&&n.removeRow(o);const l=n.getChanges(),i=l.inserted.length+l.updated.length+l.deleted.length;if(n.remote){await n.submitChanges();for(const[o,a]of n.rowErrors)s.push({table:n.name,row:o,message:a});r+=i-n.rowErrors.size}else n.acceptChanges(),r+=i}return this.template.fire("submitted",{succeeded:r,failed:s}),this._regenerate(),{succeeded:r,failed:s}}cancel(){for(const t of this.tables())t.rejectChanges();this._regenerate()}}function w(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`id-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function x(f,t,e=t.output){return e.reportEntry??new y(f,t,e)}export{y as ReportEntry,x as attachDataEntry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{BOOL as ft,EMPTY as $,ERR as Z,FORMULA as J,KIND_MASK as ut,NUM as B,SPILL as pt,STR as E}from"../core/sheet.js";import{cellRef as N,colName as H,colIndex as wt,MAX_COLS as P,MAX_ROWS as L,parseRangeRef as Y,rangeRef as dt,sheetPrefix as gt}from"../core/address.js";import{rangesOf as mt}from"../core/cond-format.js";import{translateFormula as yt}from"../core/formula-refs.js";import{getPageSetup as _t}from"../print/page-setup.js";import{paginate as V}from"../print/paginate.js";import{getFormatter as j}from"../core/numfmt.js";import{ERR as Ct,XlError as bt}from"../calc/values.js";import{aggregate as Q,formulaHelper as q,groupKeys as tt,TableView as et}from"./view.js";import{sortByF64 as kt}from"./sort.js";import{Axis as st}from"../core/axis.js";import{t as A}from"../i18n/index.js";const Rt=["group","list","summary","param","static","chart"],M=(g,t)=>g*P+t,U=new Int32Array(0),G=-2,St=8e3;class O{constructor(t,s,e,l=null,a=void 0){this.parent=t,this.table=s,this.rows=e,this.node=l,this.value=a,this.first=-1,this.last=-1,this.resolved=null}}class T extends Error{}class ht{constructor(t,s,e={}){this.manager=t,this.sheet=s,this.bindings=new Map,this.params=new Map,this.filters=[],this.titleRows=e.titleRows??null,this.pageSetup=e.pageSetup??null,this.defaultTable=e.table??null,this.name=e.name??s.name,this.output=null,this.mode=e.mode??"design",this.pagination=e.pagination??null,this.layout=e.layout??null,this.dataEntry=e.dataEntry??null,this.charts=e.charts??[],this.pictures=e.pictures??[],this.states=e.states??null,this.measure=e.measure??null,this.showHiddenRows=e.showHiddenRows===!0,this.showHiddenCols=e.showHiddenCols===!0,this.listeners=new Map,s.report=this}setBinding(t,s,e){const l=e.type;if(!Rt.includes(l))throw new T(`Unknown binding type: ${l}`);const a={table:this.defaultTable,expand:l==="group"||l==="list"?"vertical":"none",agg:"sum",sort:l==="group"?"asc":null,...e,row:t,col:s};return this.bindings.set(M(t,s),a),a}binding(t,s){return this.bindings.get(M(t,s))??null}removeBinding(t,s){this.bindings.delete(M(t,s))}static markerText(t){switch(t.type){case"group":return`[${t.field}]`;case"list":return`=[${t.field}]`;case"summary":return`${t.agg??"sum"}[${t.field}]`;case"chart":return`chart[${t.chartType??"line"}]`;default:return`{${t.param}}`}}writeMarkers(t){t.sheet===this.sheet&&t.transact("report binding",s=>{for(const e of this.bindings.values())e.type!=="static"&&(s.saveCell(e.row,e.col),this.sheet.setFormula(e.row,e.col,null),this.sheet.setCell(e.row,e.col,E,t.strings.add(ht.markerText(e))))})}addParam(t,s={}){this.params.set(t,{name:t,caption:s.caption??t,type:s.type??"string",value:s.value??null,options:s.options??null})}setParam(t,s){const e=this.params.get(t);if(!e)throw new T(A("No parameter named {name}.",{name:t}));e.value=s}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>this.listeners.get(t).delete(s)}fire(t,s){let e=!0;for(const l of this.listeners.get(t)??[])l(s)===!1&&(e=!1);return e}addFilter(t){this.filters.push(t)}generate(t,{target:s=null,name:e=null,params:l=null,measure:a=null}={}){if(l)for(const[o,n]of Object.entries(l))this.setParam(o,n);a&&(this.measure=a),this.fire("stage",{stage:"start"});const f=new xt(this,t).run(s,e);return this.fire("stage",{stage:"done",result:f}),f}async generateAsync(t,s){return await new Promise(e=>setTimeout(e,0)),this.generate(t,s)}toJSON(){return{name:this.name,sheet:this.sheet.name,table:this.defaultTable,bindings:[...this.bindings.values()].map(t=>({...t})),params:[...this.params.values()],filters:this.filters,titleRows:this.titleRows,pageSetup:this.pageSetup,output:this.output?.name??null,mode:this.mode,pagination:this.pagination,layout:this.layout,dataEntry:this.dataEntry,charts:this.charts,pictures:this.pictures,states:this.states,showHiddenRows:this.showHiddenRows,showHiddenCols:this.showHiddenCols}}}const nt=(g,t)=>`${g.name}|${t.formula??t.field}|${t.by??""}|${t.size??""}|${t.bins?JSON.stringify(t.bins):""}`,vt=g=>{let t=0;for(let s=g.parent;s!==null;s=s.parent)t++;return t};class rt{constructor(t,s,e,l){this.binding=t,this.a=s,this.b=e,this.parent=l,this.children=[],this.members=[]}}class xt{constructor(t,s){this.t=t,this.book=s,this.manager=t.manager,this.sheet=t.sheet,this.roots=new Map,this.keyCache=new Map,this.helperViews=new Map,this.cellInfo=new Map,this.groupMerges=[],this.collapses=[],this.overlay=null,this.breaks=[],this.formulas=[],this.memberColumns=new Map,this.rowCap=1024,this.rowTpl=new Int32Array(this.rowCap),this.rowCtx=new Int32Array(this.rowCap),this.rowRec=new Int32Array(this.rowCap),this.rowCount=0,this.contexts=[],this.colOut=[]}_table(t){if(!t)throw new T(A("A binding needs a table."));return this.manager.table(t)}_templateExtent(){const{sheet:t}=this;let s=t.maxRow,e=t.maxCol;for(const l of this.t.bindings.values())l.row>s&&(s=l.row),l.col>e&&(e=l.col);for(const l of t.merges)l.r1>s&&(s=l.r1),l.c1>e&&(e=l.c1);return{maxRow:s,maxCol:e}}_buildTree(t,s){const e=t==="vertical",l=i=>e?i.row:i.col,a=i=>e?i.col:i.row,f=[...this.t.bindings.values()].filter(i=>(i.type==="group"||i.type==="list")&&i.expand===t);f.sort((i,u)=>a(i)-a(u)||l(i)-l(u));const o=new rt(null,0,e?s.maxRow:s.maxCol,null),n=new Map,c=i=>{if(i.span>1)return l(i)+i.span-1;const u=this.sheet.mergeAt(i.row,i.col);return u?e?u.r1:u.c1:l(i)},r=i=>{if(i.parent==="none")return o;if(i.parent){const p=n.get(M(i.parent.row,i.parent.col));if(p)return p}let u=o;for(const p of n.values())a(p.binding)>=a(i)||l(i)<p.a||l(i)>p.b||p.a>=u.a&&(u===o||a(p.binding)>=a(u.binding))&&(u=p);return u};for(const i of f){const u=r(i);if(i.type==="list"&&u!==o&&u.binding.type==="list"&&l(u.binding)===l(i)&&u.binding.table===i.table){u.members.push(i);continue}if(i.type==="list"){const w=u.children.find(m=>m.binding.type==="list"&&l(m.binding)===l(i)&&m.binding.table===i.table);if(w){w.members.push(i);continue}}const p=new rt(i,l(i),c(i),u);u.children.push(p),n.set(M(i.row,i.col),p)}const h=i=>{i.children.sort((u,p)=>u.a-p.a);for(const u of i.children)h(u),i!==o&&u.b>i.b&&(i.b=u.b),i!==o&&u.a<i.a&&(i.a=u.a);for(let u=1;u<i.children.length;u++)if(i.children[u].a<=i.children[u-1].b){const p=i.children[u].binding,w=i.children[u-1].binding;throw new T(A("The cells {first} and {second} expand over the same rows but neither is the other's parent.",{first:N(p.row,p.col),second:N(w.row,w.col)}))}};return h(o),o}_rootRows(t){let s=this.roots.get(t);if(s!==void 0)return s;const e=this.t.filters.filter(a=>this.manager.table(a.table??this.t.defaultTable)===t).map(a=>this._resolveFilter(a)),l=new et(t,{columns:[],filters:e});return s=l.filtered.slice(0,l.filteredCount),l.dispose(),this.roots.set(t,s),s}_resolveFilter(t){const s={...t};if(t.param&&(s.value=this._param(t.param)),t.param2&&(s.value2=this._param(t.param2)),t.valuesParam){const e=this._param(t.valuesParam);s.values=Array.isArray(e)?e:[e],s.op=s.op??"in"}return s}_param(t){const s=this.t.params.get(t);if(!s)throw new T(A("No parameter named {name}.",{name:t}));return s.value}_filterActive(t){if(t.param&&(this._param(t.param)===null||this._param(t.param)===""))return!1;if(t.valuesParam){const s=this._param(t.valuesParam);if(s===null||s===""||Array.isArray(s)&&s.length===0)return!1}return!0}_rowsIn(t,s){if(t===null)return this._rootRows(s);if(t.table===s)return t.rows;t.resolved===null&&(t.resolved=new Map);let e=t.resolved.get(s);return e!==void 0||(e=this._crossRows(t,s),t.resolved.set(s,e)),e}_crossRows(t,s){for(let e=t;e!==null;e=e.parent){if(e.table===s)return e.rows;if(e.table===null)continue;const l=e.node?.binding.link;if(l)return this._joinRows(e,s,l.from,l.to);const a=this.manager.relationshipBetween(e.table,s);if(!a)continue;const f=this._rootMask(s);if(a.to===e.table){const{starts:r,rows:h}=a.children();let i=0;for(let w=0;w<e.rows.length;w++)i+=r[e.rows[w]+1]-r[e.rows[w]];const u=new Int32Array(i);let p=0;for(let w=0;w<e.rows.length;w++){const m=e.rows[w];for(let C=r[m];C<r[m+1];C++)(f===null||f[h[C]]===1)&&(u[p++]=h[C])}return p===i?u:u.slice(0,p)}const o=a.parents(),n=new Uint8Array(s.rowCount),c=[];for(let r=0;r<e.rows.length;r++){const h=o[e.rows[r]];h>=0&&n[h]===0&&(f===null||f[h]===1)&&(n[h]=1,c.push(h))}return Int32Array.from(c)}return this._rootRows(s)}_rootMask(t){if(!this.t.filters.some(e=>this.manager.table(e.table??this.t.defaultTable)===t))return null;const s=new Uint8Array(t.rowCount);for(const e of this._rootRows(t))s[e]=1;return s}_joinRows(t,s,e,l){const a=new Set,f=t.table.column(e);for(let r=0;r<t.rows.length;r++)a.add(String(f.get(t.rows[r])));const o=s.column(l),n=this._rootRows(s),c=[];for(let r=0;r<n.length;r++)a.has(String(o.get(n[r])))&&c.push(n[r]);return Int32Array.from(c)}_helperView(t){let s=this.helperViews.get(t);return s===void 0&&(s=new et(t,{columns:[]}),this.helperViews.set(t,s)),s}_prepareRows(t,s,e,l=null){let a=t;const f=(s.filters??[]).filter(o=>this._filterActive(o)).map(o=>this._resolveFilter(o));if(f.length>0||s.filter){const o=this._helperView(e),n=new Uint8Array(e.rowCount);for(let h=0;h<a.length;h++)n[a[h]]=1;for(const h of f)o._applyCondition(h,n,e.rowCount);s.filter&&this._applyFilterTree(s.filter,n,e,o,l);const c=new Int32Array(a.length);let r=0;for(let h=0;h<a.length;h++)n[a[h]]===1&&(c[r++]=a[h]);a=c.subarray(0,r)}if(s.sortFormula)a=a===t?t.slice():a,this._helperView(e)._sortColumn(a,a.length,q(e,s.sortFormula),s.sort==="desc");else if(s.sort||s.sortBy){const o=e.column(s.sortBy??s.field);o&&(a=a===t?t.slice():a,this._helperView(e)._sortColumn(a,a.length,o,s.sort==="desc"))}return a}_applyFilterTree(t,s,e,l,a){const f=e.rowCount;if(t.and){for(const n of t.and)this._applyFilterTree(n,s,e,l,a);return}if(t.or){const n=new Uint8Array(f);for(const c of t.or){const r=s.slice();this._applyFilterTree(c,r,e,l,a);for(let h=0;h<f;h++)n[h]|=r[h]}s.set(n);return}if(t.param!==void 0&&!this._filterActive(t))return;const o=this._resolveFilter(t);if(t.cell){const n=this.t.binding(t.cell.row,t.cell.col);for(let c=a;c!=null;c=c.parent)if(c.node?.binding===n&&c.rows.length>0){o.value=c.table.column(n.field).get(c.rows[0]);break}}if(t.join){const n=this._table(t.join.table),c=n.column(t.join.field),r=a?this._rowsIn(a,n):this._rootRows(n),h=new Set;for(let i=0;i<r.length;i++)h.add(c.get(r[i]));o.op="in",o.values=[...h]}l._applyCondition(o,s,f)}_partition(t,s,e,l=null){const a=this._prepareRows(t,{...s,sort:null,sortBy:null,sortFormula:null},e,l),f=nt(e,s);let o=this.keyCache.get(f);if(o===void 0){if(o=tt(e,s),o===null)throw new T(A("No field {field} in {table}.",{field:s.field,table:e.name}));this.keyCache.set(f,o)}const n=a===t?t.slice():a;s.sort&&Tt(n,o,s.sort==="desc");const c=[],r=s.sort?null:new Map;let h=0;const i=n.length;if(s.sort)for(;h<i;){const u=o[n[h]];let p=h+1;if(u===u)for(;p<i&&o[n[p]]===u;)p++;else for(;p<i&&o[n[p]]!==o[n[p]];)p++;c.push(n.subarray(h,p)),h=p}else{for(;h<i;h++){const u=o[n[h]],p=u!==u?"blank":u,w=r.get(p);w?w.push(n[h]):r.set(p,[n[h]])}for(const u of r.values())c.push(Int32Array.from(u))}return this._orderGroups(c,s,e)}_orderGroups(t,s,e){if(s.sortList){const l=s.formula?q(e,s.formula):e.column(s.field),a=new Map(s.sortList.map((o,n)=>[String(o).toLowerCase(),n])),f=o=>a.get(String(l.get(o[0])).toLowerCase())??1/0;return t.map((o,n)=>[o,f(o),n]).sort((o,n)=>o[1]-n[1]||o[2]-n[2]).map(o=>o[0])}if(s.sortCell){const l=this.t.binding(s.sortCell.row,s.sortCell.col),a=l&&l.field?e.column(l.field):null;if(a){const f=s.sort==="desc"?-1:1,o=n=>Q(a,l.agg??"sum",n,0,n.length);return t.map(n=>[n,o(n)]).sort((n,c)=>f*(n[1]-c[1])).map(n=>n[0])}}return t}_paginateRows(){const{t}=this,s=t.pagination,e=new Set,l=new Set;for(const n of t.bindings.values())n.pageBefore&&e.add(n.row),n.pageAfter&&l.add(n.row);if(e.size>0||l.size>0)for(let n=0;n<this.rowCount;n++){const c=this.rowTpl[n];e.has(c)&&n>0&&this.breaks.push(n),l.has(c)&&this.breaks.push(n+1)}const a=s?.endRows??null,f=t.titleRows?t.titleRows.r1-t.titleRows.r0+1:0;let o=s?.rowsPerPage>0?s.rowsPerPage:0;if(a&&o===0){const n=V(this.book,this.sheet).box.h,c=a.r1-a.r0+1;o=Math.max(1,Math.floor(n/this.sheet.rows.defaultSize)-f-c)}if(a)this._repeatEndRows(a,o,f);else if(o>0)for(const n of this._rowPageStarts(this.rowCount,o,f,new Set(this.breaks)))this.breaks.push(n);this.pageStartSet=new Set(this.breaks)}_rowPageStarts(t,s,e,l){const a=[];for(const i of this.contexts)i.node?.binding?.keepTogether&&i.first!==void 0&&i.last>i.first&&a.push(i);a.sort((i,u)=>i.first-u.first);const f=[];let o=0,n=e+s,c=0;const r=[...l].sort((i,u)=>i-u);let h=0;for(;o+n<t;){let i=o+n;for(;h<r.length&&r[h]<=o;)h++;for(h<r.length&&r[h]<i&&(i=r[h]);c<a.length&&a[c].last<i;)c++;c<a.length&&a[c].first<i&&a[c].first>o&&a[c].last>=i&&(i=a[c].first),f.push(i),o=i,n=s}return f}_repeatEndRows(t,s,e){const l=this.rowCount,{rowTpl:a,rowCtx:f,rowRec:o}=this,n=[],c=[];for(let d=0;d<l;d++)(a[d]>=t.r0&&a[d]<=t.r1?c:n).push(d);if(c.length===0||n.length===0)return;const r=new Int32Array(l).fill(-1);n.forEach((d,_)=>{r[d]=_});const h=new Set;for(const d of this.breaks){let _=d;for(;_<l&&r[_]<0;)_++;_<l&&h.add(r[_])}const i=this.contexts.map(d=>[d.first,d.last]);for(const d of this.contexts){if(d.first===void 0||d.first<0)continue;let _=d.first;for(;_<l&&r[_]<0;)_++;let v=d.last;for(;v>0&&r[v]<0;)v--;d.first=_<l?r[_]:0,d.last=v>=0&&r[v]>=0?r[v]:d.first}const u=s>0?this._rowPageStarts(n.length,s,e,h):[...h].sort((d,_)=>d-_);i.forEach(([d,_],v)=>{this.contexts[v].first=d,this.contexts[v].last=_});const p=n.length+c.length*(u.length+1),w=new Int32Array(p),m=new Int32Array(p),C=new Int32Array(p),k=new Int32Array(l).fill(-1),R=[];let S=0,y=0;const x=()=>{c.forEach(d=>{w[S]=a[d],m[S]=f[d],C[S]=o[d],k[d]<0&&(k[d]=S),S++})};n.forEach((d,_)=>{y<u.length&&u[y]===_&&(x(),R.push(S),y++),w[S]=a[d],m[S]=f[d],C[S]=o[d],k[d]=S,S++}),x(),this.rowTpl=w,this.rowCtx=m,this.rowRec=C,this.rowCount=p,this.rowCap=p,this.breaks=R;const b=d=>d>=0&&d<l&&k[d]>=0?k[d]:d;for(const d of this.contexts)d.first!==void 0&&(d.first=b(d.first)),d.last!==void 0&&(d.last=b(d.last));for(const d of this.collapses)d.row=b(d.row),d.from=b(d.from),d.to=b(d.to);for(const d of this.groupMerges)d.r0=b(d.r0),d.r1=b(d.r1);this.overlay&&(this.overlay=new Map([...this.overlay].map(([d,_])=>[b(d),_])))}_paginateCols(){const{t}=this,s=t.pagination;this.colBreaks=[];const e=new Set,l=new Set;for(const p of t.bindings.values())p.colPageBefore&&e.add(p.col),p.colPageAfter&&l.add(p.col);const a=s?.endCols??null,f=p=>a&&p.tpl>=a.c0&&p.tpl<=a.c1,o=a?this.colOut.filter(f):[],n=a?this.colOut.filter(p=>!f(p)):this.colOut,c=s?.colsPerPage>0?s.colsPerPage:0,r=[],h=s?.titleCols?s.titleCols.c1-s.titleCols.c0+1:0;let i=0,u=h+c;n.forEach((p,w)=>{w>0&&(c>0&&i>=u||e.has(p.tpl)||l.has(n[w-1].tpl))&&(r.push(...o),this.colBreaks.push(r.length),i=0,u=c),r.push(p),i++}),r.push(...o),this.colOut=r}_pushRow(t,s,e){if(this.rowCount===this.rowCap){const a=this.rowCap*2,f=o=>{const n=new Int32Array(a);return n.set(o),n};this.rowTpl=f(this.rowTpl),this.rowCtx=f(this.rowCtx),this.rowRec=f(this.rowRec),this.rowCap=a}if(this.rowCount>=L)throw new T(A("The report needs more than {count} rows. Add a filter.",{count:L}));const l=this.rowCount++;return this.rowTpl[l]=t,this.rowCtx[l]=s,this.rowRec[l]=e,l}_newContext(t){return this.contexts.push(t),t.index=this.contexts.length-1,t}_emitBand(t,s,e,l,a){let f=e;const o=t.children;let n=0;for(;f<=l;){for(;n<o.length&&o[n].b<f;)n++;const c=n<o.length&&o[n].a===f?o[n]:null;if(c!==null){const r=this._expandNode(c,s);f=c.b+1+(r??0)}else this._pushRow(f,s.index,a),f++}}_expandNode(t,s){const e=t.binding,l=this._table(e.table),a=this._rowsIn(s,l),f=c=>e.fillTo>1?(e.fillTo-c%e.fillTo)%e.fillTo:0;if(e.type==="group"){let c=this._partition(a,e,l,s);e.spillMode==="none"&&(c=c.slice(0,1));const r=e.merge===!0||this.sheet.mergeAt(e.row,e.col)!==null,h=c.length;for(let i=0;i<h;i++){const u=this._newContext(new O(s,l,c[i],t));u.ordinal=i+1,u.first=this.rowCount,this._emitBand(t,u,t.a,t.b,-1),u.last=this.rowCount-1,r&&u.last>u.first&&this.groupMerges.push({binding:e,r0:u.first,r1:u.last}),e.collapse&&u.last>u.first&&this.collapses.push({binding:e,row:u.first,from:u.first+1,to:u.last,depth:vt(u),collapsed:e.initial==="collapsed"}),e.pageBreak&&i<h-1&&this.breaks.push(this.rowCount)}for(let i=f(h);i>0;i--){const u=this._newContext(new O(s,l,U,t));u.first=this.rowCount,this._emitBand(t,u,t.a,t.b,G),u.last=this.rowCount-1}return 0}let o=this._prepareRows(a,e,l,s);e.spillMode==="none"&&(o=o.subarray(0,1));const n=e.pageEvery??0;if(t.a===t.b&&t.children.length===0){const c=this._newContext(new O(s,l,o,t));if(c.first=this.rowCount,e.spillMode==="overwrite"){const r=o.length;for(let h=0;h<r;h++){const i=this._pushRow(t.a+h,c.index,o[h]);this.overlay===null&&(this.overlay=new Map),this.overlay.set(i,t.a)}return c.last=this.rowCount-1,Math.max(0,r-1)}for(let r=0;r<o.length;r++)this._pushRow(t.a,c.index,o[r]),n>0&&(r+1)%n===0&&r+1<o.length&&this.breaks.push(this.rowCount);for(let r=f(o.length);r>0;r--)this._pushRow(t.a,c.index,G);return c.last=this.rowCount-1,0}for(let c=0;c<o.length;c++){const r=o.subarray(c,c+1),h=this._newContext(new O(s,l,r,t));h.ordinal=c+1,h.first=this.rowCount,this._emitBand(t,h,t.a,t.b,o[c]),h.last=this.rowCount-1,n>0&&(c+1)%n===0&&c+1<o.length&&this.breaks.push(this.rowCount)}return 0}_expandColumns(t,s,e,l){let a=e,f=0;const o=t.children;for(;a<=l;){for(;f<o.length&&o[f].b<a;)f++;const n=f<o.length&&o[f].a===a?o[f]:null;if(n!==null)this._expandColumnNode(n,s),a=n.b+1;else{if(this.colOut.length>=P)throw new T(A("The report needs more than {count} columns. Add a filter.",{count:P}));this.colOut.push({tpl:a,ctx:s}),a++}}}_expandColumnNode(t,s){const e=t.binding,l=this._table(e.table),a=this._colRows(s,l);let f=e.type==="group"?this._partition(a,e,l):Array.from(this._prepareRows(a,e,l),n=>Int32Array.of(n));e.spillMode==="none"&&(f=f.slice(0,1));const o=e.fillTo>1?(e.fillTo-f.length%e.fillTo)%e.fillTo:0;for(let n=0;n<o;n++)f.push(U);for(const n of f){const c=new O(s,l,n,t);c.first=this.colOut.length,this._expandColumns(t,c,t.a,t.b),c.last=this.colOut.length-1}}_colRows(t,s){return t===null||t.table===null?this._rootRows(s):this._rowsIn(t,s)}run(t,s){const{book:e,t:l}=this,a=this._templateExtent();this.extent=a;const f=this._buildTree("vertical",a),o=this._buildTree("horizontal",a),n=this._newContext(new O(null,null,U,null));n.first=0,this._emitBand(f,n,0,a.maxRow,-1),n.last=this.rowCount-1;const c=new O(null,null,U,null);this._expandColumns(o,c,0,a.maxCol),this._paginateRows(),this._paginateCols();const r=t??e.addSheet(s??`${l.name} Report`);this.outSheet=r,r.reportWriting=!0;const h=r.formulas.size>0;this._clear(r),this._writeGeometry(r),this._writeCells(r),this._writeMerges(r),this._writeSheetRules(r),this._writePageSetup(r),this._writeFormulas(r),this._applyAutoFit(r),l.layout&&this._applyLayoutSetting(r),this._saveMap(r),h&&e.engine?.rebuild(),r.reportWriting=!1,r.revision++,l.output=r;for(const i of this.helperViews.values())i.dispose();return{sheet:r,rows:this.rowCount,cols:this.colOut.length,pages:Et(e,r)}}_clear(t){t.columns=[],t.formulas=new Map,t.maxRow=-1,t.maxCol=-1,t.merges=[],t.mergeIndex=null,t.spills=null,t.rowStyles=null,t.colStyles=null,t.pageSetup=void 0,t.cf=void 0,t.cfEval=void 0,t.validations=void 0,t.sparklines=void 0,t.rows=new st(L,this.sheet.rows.defaultSize),t.cols=new st(P,this.sheet.cols.defaultSize),t.colsChanged=!0,t.viewChanged=!0}_writeGeometry(t){const{sheet:s}=this,{colOut:e,rowTpl:l,rowCount:a}=this;if(s.cols.sizes!==null)for(let o=0;o<e.length;o++){const n=s.cols.sizeOf(e[o].tpl);s.cols.isHidden(e[o].tpl)||(n!==t.cols.defaultSize||t.cols.isCustom(o))&&t.cols.setSize(o,n)}if(s.rows.sizes!==null)for(let o=0;o<a;o++){const n=l[o];s.rows.isCustom(n)&&!s.rows.isHidden(n)&&t.rows.setSize(o,s.rows.sizeOf(n))}if(!this.t.showHiddenRows&&s.rows.hiddenSizes?.size>0)for(let o=0;o<a;o++)s.rows.isHidden(l[o])&&t.rows.setHidden(o,!0);!this.t.showHiddenCols&&s.cols.hiddenSizes?.size>0&&e.forEach((o,n)=>{s.cols.isHidden(o.tpl)&&t.cols.setHidden(n,!0)}),s.colStyles&&(t.colStyles=new Map,e.forEach((o,n)=>{const c=s.colStyles.get(o.tpl);c!==void 0&&t.colStyles.set(n,c)}))}_writeCells(t){const{colOut:s,rowCount:e,rowTpl:l,rowCtx:a,rowRec:f,sheet:o,contexts:n}=this,{strings:c}=this.book,{bindings:r}=this.t,{overlay:h}=this,i=o.formulas.size>0,u=new Map;s.forEach((w,m)=>{u.has(w.tpl)||u.set(w.tpl,m)});const p=(w,m)=>{const C=M(w,m),k=r.get(C)??null,R=k!==null&&k.type==="static"?null:k,S=o.kind(w,m),y={binding:R,options:k!==null&&k.type==="static"?k:null,kind:S&~pt,value:o.value(w,m),style:o.cellStyle(w,m),table:R&&R.table?this._table(R.table):null,col:null,formula:S&J?o.formula(w,m):null,merged:o.mergeAt(w,m)};if(R&&R.type!=="param"&&R.type!=="chart"){if(y.col=R.formula?q(y.table,R.formula):y.table?.column(R.field)??null,!y.col&&!(R.type==="summary"&&R.agg==="countAll"))throw new T(A("No field {field} in {table}.",{field:R.field,table:R.table}));y.col&&y.table.ensure(y.col),R.collapse&&(y.style=this.book.styles.derive(y.style,{indent:1,hAlign:"left"})),R.format?y.style=this.book.styles.derive(y.style,{numFmt:R.format}):y.col&&y.col.format!=="General"&&(y.style===0||this.book.styles.get(y.style).numFmt==="General")&&(y.style=this.book.styles.derive(y.style,{numFmt:y.col.format}))}return y};for(let w=0;w<s.length;w++){const{tpl:m,ctx:C}=s[w];let k=-1;const R=[],S=u.get(m)===w;for(let y=0;y<e;y++){let x=l[y];if(h!==null){const _=h.get(y);_!==void 0&&r.get(M(_,m))?.type==="list"&&(x=_)}let b=R[x];b===void 0&&(b=p(x,m),R[x]=b);const d=b.binding;if(d===null){const _=b.options;if(_!==null){if(_.pin)continue;const v=_.autoExpand??"both";if((v==="none"||v==="horizontal")&&b.seen||(v==="none"||v==="vertical")&&!S)continue;b.seen=!0}if(b.formula){i&&this.formulas.push({or:y,oc:w,tr:x,tc:m,info:b.formula,ctx:n[a[y]],colCtx:C,style:b.style});continue}b.kind!==$&&t.setCell(y,w,b.kind,b.value),b.style!==0&&t.setStyle(y,w,b.style);continue}switch(b.style!==0&&t.setStyle(y,w,b.style),d.type){case"param":lt(t,y,w,this._param(d.param),c);break;case"list":{const _=d.expand==="horizontal"?this._recordAcross(C,b.table):this._recordFor(n[a[y]],f[y],b.table);_>=0&&it(t,y,w,b.col,_);break}case"group":{const _=this._groupContext(n[a[y]],C,d);if(_===null)break;if(_.index!==void 0&&!d.repeat){if(_.index===k&&!(d.repeatOnPage&&this.pageStartSet.has(y)))break;k=_.index}this._writeGroupValue(t,y,w,d,b,_);break}case"chart":this._writeChartCell(t,y,w,d,n[a[y]]);break;default:{if(f[y]===G)break;const _=this._summaryRows(n[a[y]],C,b.table,d,f[y]),v=b.col?Q(b.col,d.agg??"sum",_,0,_.length):d.agg==="countAll"?_.length:NaN;v===v&&t.setCell(y,w,B,v)}}}}}_writeChartCell(t,s,e,l,a){if(!l.source)return;const o=(this.tplRows??(this.tplRows=this._rowsByTemplate())).get(l.source.row),n=this.colOut.findIndex(u=>u.tpl===l.source.col);if(!o||n<0)return;const c=ot(o,a.first,a.last);if(c.length===0)return;const r=c[0][0],h=c[c.length-1][1];t.sparklines||(t.sparklines=[],t.sparklinesChanged=!0),this.sparkGroups||(this.sparkGroups=new Map);let i=this.sparkGroups.get(l);i||(i={type:l.chartType??"line",markers:!1,high:!1,low:!1,first:!1,last:!1,negative:l.chartType==="winloss",lineWeight:1,seriesColor:l.color??"#2f6fb3",negativeColor:"#c42b1c",markerColor:"#107c41",items:[]},this.sparkGroups.set(l,i),t.sparklines.push(i)),i.items.push({source:`${gt(t.name)}${H(n)}${r+1}:${H(n)}${h+1}`,cell:N(s,e)})}_rowsByTemplate(){const t=new Map;for(let s=0;s<this.rowCount;s++){const e=this.rowTpl[s];let l=t.get(e);l===void 0&&(l=[],t.set(e,l)),l.push(s)}return t}_writeSheetRules(t){const{sheet:s,colOut:e}=this,l=this.tplRows??(this.tplRows=this._rowsByTemplate()),a=new Map;e.forEach((o,n)=>{a.has(o.tpl)||a.set(o.tpl,[]),a.get(o.tpl).push(n)});const f=o=>{const n=[];for(const c of mt(o)){const r=[];for(let i=c.r0;i<=c.r1&&i<=this.extent.maxRow;i++)for(const u of l.get(i)??[])r.push(u);r.sort((i,u)=>i-u);const h=[];for(let i=c.c0;i<=c.c1&&i<=this.extent.maxCol;i++)for(const u of a.get(i)??[])h.push(u);h.sort((i,u)=>i-u);for(const[i,u]of at(r))for(const[p,w]of at(h))n.push(dt({r0:i,c0:p,r1:u,c1:w}))}return n.join(" ")};s.cf&&s.cf.length>0&&(t.cf=s.cf.map(({_ranges:o,...n})=>({...n,sqref:f(n.sqref)})).filter(o=>o.sqref),t.cfChanged=!0),s.validations&&s.validations.length>0&&(t.validations=s.validations.map(({_ranges:o,...n})=>({...n,sqref:f(n.sqref)})).filter(o=>o.sqref),t.validationsChanged=!0);for(const o of this.t.bindings.values()){if(o.type!=="static"||!o.pin)continue;const n=s.kind(o.row,o.col),c=o.pin==="column"?l.get(o.row)?.[0]??o.row:o.row,r=o.pin==="row"?a.get(o.col)?.[0]??o.col:o.col;(n&7)!==$&&t.setCell(c,r,n&7,s.value(o.row,o.col));const h=s.cellStyle(o.row,o.col);h&&t.setStyle(c,r,h)}}_applyAutoFit(t){const s=[...this.t.bindings.values()].filter(i=>i.autoFit);if(s.length===0)return;const e=this.t.measure??(i=>i.length*6.4),{colOut:l,rowTpl:a,rowCount:f,sheet:o}=this,{strings:n,styles:c}=this.book,r=(i,u)=>{const p=t.kind(i,u)&7;if(p===0)return"";if(p===E)return n.get(t.value(i,u));if(p===B){const w=c.get(t.style(i,u)).numFmt;return w&&w!=="General"?j(w).number(t.value(i,u)):String(t.value(i,u))}return"TRUE"},h=Math.min(f,1e5);for(const i of s)if(i.autoFit==="column")l.forEach((u,p)=>{if(u.tpl!==i.col)return;let w=o.cols.sizeOf(i.col);for(let m=0;m<h;m++)a[m]===i.row&&(w=Math.max(w,e(r(m,p))+8));w!==t.cols.sizeOf(p)&&t.cols.setSize(p,Math.ceil(w))});else{const u=l.findIndex(m=>m.tpl===i.col);if(u<0)continue;const p=Math.max(10,t.cols.sizeOf(u)-6),w=t.rows.defaultSize;for(let m=0;m<h;m++){if(a[m]!==i.row)continue;const C=Math.ceil(e(r(m,u))/p),k=Math.max(o.rows.sizeOf(i.row),C*w);k!==t.rows.sizeOf(m)&&t.rows.setSize(m,k)}}}_applyLayoutSetting(t){const{type:s,count:e,repeat:l=0}=this.t.layout;if(!(e>l))return;const a=[],f=t.maxRow,o=t.maxCol;for(let c=0;c<=f;c++)for(let r=0;r<=o;r++){const h=t.kind(c,r)&15,i=t.cellStyle(c,r);(h!==0||i!==0)&&a.push(c,r,h,t.value(c,r),i)}const n=e-l;t.columns=[],t.maxRow=-1,t.maxCol=-1;for(let c=0;c<a.length;c+=5){const[r,h,i,u,p]=[a[c],a[c+1],a[c+2],a[c+3],a[c+4]],w=(m,C)=>{i!==0&&t.setCell(m,C,i,u),p!==0&&t.setStyle(m,C,p)};if(s==="row"){const m=o+1;if(r<l){const C=Math.max(1,Math.ceil((f+1-l)/n));for(let k=0;k<C;k++)w(r,h+k*m)}else{const C=Math.floor((r-l)/n);w(l+(r-l)%n,h+C*m)}}else{const m=f+1;if(h<l){const C=Math.max(1,Math.ceil((o+1-l)/n));for(let k=0;k<C;k++)w(r+k*m,h)}else{const C=Math.floor((h-l)/n);w(r+C*m,l+(h-l)%n)}}}}_saveMap(t){const{rowTpl:s,rowRec:e,rowCtx:l,rowCount:a,colOut:f,contexts:o,collapses:n}=this,c=new Map;f.forEach((h,i)=>{c.has(h.tpl)||c.set(h.tpl,i)});const r=n.map(h=>({...h,col:c.get(h.binding.col)??0}));t.reportMap={template:this.t,rowTpl:s.subarray(0,a),rowRec:e.subarray(0,a),rowCtx:l.subarray(0,a),contexts:o,colTpl:f.map(h=>h.tpl),collapses:r,overlay:this.overlay,book:this.book,layout:this.t.layout??null},r.some(h=>h.collapsed)&&ct(t)}_groupContext(t,s,e){for(let l=t;l!==null;l=l.parent)if(l.node?.binding===e)return l;for(let l=s;l!==null;l=l.parent)if(l.node?.binding===e)return l;return null}_writeGroupValue(t,s,e,l,a,f){const o=f.rows.length>0?f.rows[0]:-1;if(o<0)return;const n=a.col.get(o);if(l.bins){const c=l.bins.find(r=>typeof n=="number"&&(r.min===void 0||n>=r.min)&&(r.max===void 0||n<r.max));t.setCell(s,e,E,this.book.strings.add(c?.name??"(other)"))}else if(typeof n=="number"&&l.by&&l.by!=="value")t.setCell(s,e,E,this.book.strings.add(Ot(n,l.by)));else if(typeof n=="number"&&l.size>0){const c=Math.floor(n/l.size)*l.size;t.setCell(s,e,E,this.book.strings.add(`${c} to ${c+l.size}`))}else it(t,s,e,a.col,o)}_recordAcross(t,s){for(let e=t;e!==null&&e.node!==null;e=e.parent)if(e.table===s)return e.rows.length>0?e.rows[0]:-1;return-1}_recordFor(t,s,e){if(s===G)return-1;if(s>=0&&(t.table===e||t.table===null))return s;for(let a=t;a!==null;a=a.parent)if(a.table===e&&a.rows.length>0)return s>=0&&a===t?s:a.rows[0];const l=this._rowsIn(t,e);return l.length>0?l[0]:-1}_summaryRows(t,s,e,l,a){let f=t.table===e&&a>=0?Int32Array.of(a):this._rowsIn(t.table===null?null:t,e);for(let o=s;o!==null&&o.node!==null;o=o.parent){const n=o.node.binding;if(o.table!==e)continue;const c=nt(e,n);let r=this.keyCache.get(c);r===void 0&&(r=tt(e,n),this.keyCache.set(c,r));const h=r[o.rows[0]],i=new Int32Array(f.length);let u=0;for(let p=0;p<f.length;p++){const w=r[f[p]];(w===h||w!==w&&h!==h)&&(i[u++]=f[p])}f=i.subarray(0,u)}return l.filters?.length&&(f=this._prepareRows(f,{...l,sort:null,sortBy:null},e)),f}_writeMerges(t){const{sheet:s,rowTpl:e,rowCtx:l,rowCount:a,colOut:f,groupMerges:o}=this,n=new Map;f.forEach((r,h)=>{n.has(r.tpl)||n.set(r.tpl,[]),n.get(r.tpl).push(h)});const c=new Set;for(const r of o){const{binding:h,r0:i,r1:u}=r,p=s.mergeAt(h.row,h.col),w=p?p.c0:h.col,m=p?p.c1:h.col;p&&c.add(p);const C=[];let k=i;if(h.repeatOnPage)for(let R=i+1;R<=u;R++)this.pageStartSet.has(R)&&(C.push([k,R-1]),k=R);C.push([k,u]);for(const R of n.get(w)??[]){const S=R+(m-w);for(const[y,x]of C)(x>y||S>R)&&t.addMerge({r0:y,c0:R,r1:x,c1:S})}}for(const r of s.merges){if(c.has(r)||this.t.bindings.has(M(r.r0,r.c0))){const i=this.t.bindings.get(M(r.r0,r.c0));if(i&&(i.type==="group"||i.type==="list")&&i.expand==="vertical")continue}if(c.has(r))continue;const h=r.r1-r.r0;for(let i=0;i<a;i++){if(e[i]!==r.r0||i+h>=a)continue;let u=!0;for(let p=1;p<=h;p++)(e[i+p]!==r.r0+p||l[i+p]!==l[i])&&(u=!1);if(u)for(const p of n.get(r.c0)??[]){const w=p+(r.c1-r.c0);w<f.length&&t.addMerge({r0:i,c0:p,r1:i+h,c1:w})}}}}_writePageSetup(t){const{t:s,rowTpl:e,rowCount:l}=this,a=_t(t),f=this.sheet.pageSetup;if(f)for(const n of["orientation","paperSize","paperWidth","paperHeight","scale","fitToPage","fitToWidth","fitToHeight","horizontalCentered","verticalCentered","header","footer","headings","gridLines","margins"])f[n]!==void 0&&(a[n]=f[n]);s.pageSetup&&Object.assign(a,s.pageSetup);const o=s.pagination;if(o?.order&&(a.pageOrder=o.order),a.rowBreaks=[...new Set(this.breaks)].filter(n=>n>0&&n<l).sort((n,c)=>n-c),a.colBreaks=[...new Set(this.colBreaks)].filter(n=>n>0&&n<this.colOut.length).sort((n,c)=>n-c),o?.titleCols){let n=-1,c=-1;this.colOut.forEach((r,h)=>{r.tpl>=o.titleCols.c0&&r.tpl<=o.titleCols.c1&&(n<0||h===c+1)&&(n<0&&(n=h),c=h)}),n>=0&&(a.titleCols={c0:n,c1:c})}if(s.titleRows){let n=-1,c=-1;for(let r=0;r<l;r++){const h=e[r];if(h>=s.titleRows.r0&&h<=s.titleRows.r1)n<0&&(n=r),c=r;else if(n>=0)break}n>=0&&(a.titleRows={r0:n,r1:c})}t.pageSetupChanged=!0}_writeFormulas(t){if(this.formulas.length===0)return;const{rowTpl:s,rowCount:e,colOut:l}=this,a=new Map;for(let r=0;r<e;r++){const h=s[r];let i=a.get(h);i===void 0&&(i=[],a.set(h,i)),i.push(r)}const f=new Map;l.forEach((r,h)=>{f.has(r.tpl)||f.set(r.tpl,[]),f.get(r.tpl).push(h)});const o=new Uint32Array(this.formulas.length),n=new Uint16Array(this.formulas.length);this.formulas.forEach((r,h)=>{const{or:i,oc:u,tr:p,tc:w,info:m,ctx:C,style:k}=r,R=m.f??yt(m.sf,p-Math.floor(m.base/P),w-m.base%P),S=this._reportFunctions(R,i,C),y=Mt(S,(x,b,d,_)=>{const v=a.get(b),z=f.get(_);if(!v||!z)return null;const W=b===p?[[i,i]]:ot(v,C.first,C.last);if(W.length===0)return"#REF!";let I,F;return _===w?(I=u,F=u):(I=z[0],F=z[z.length-1]),W.map(([D,K])=>{const X=`${d}${H(I)}${x}${D+1}`;return D===K&&I===F?X:`${X}:${d}${H(F)}${x}${K+1}`}).join(",")});if(y.length>St){t.setCell(i,u,Z,Ct.REF.index),k!==0&&t.setStyle(i,u,k),o[h]=i,n[h]=u;return}t.setCell(i,u,J|$,0),t.setFormula(i,u,{f:y,typed:!0}),k!==0&&t.setStyle(i,u,k),o[h]=i,n[h]=u}),this.book.engine?.cellsChanged(t,o,n,o.length),this.book.formulasEdited=!0;const c=this.book.engine;c&&this.formulas.forEach(r=>{if(this.t.bindings.get(M(r.tr,r.tc))?.preserveFormula!==!1)return;const i=c.read(t,r.or,r.oc);t.setFormula(r.or,r.oc,null),t.setCell(r.or,r.oc,$,0),lt(t,r.or,r.oc,i,this.book.strings)})}_reportFunctions(t,s,e){if(!/RPT_/i.test(t))return t;const l=n=>this._measureCell(f(n),s,e),a=n=>{const c=n.trim();for(const r of this.t.bindings.values())if(r.alias===c)return N(r.row,r.col);return c},f=a,o=n=>n==null?'""':String(n);return t.replace(/RPT_RANK\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=l(c);return r?o(1+r.values.filter(h=>h>r.current).length):'""'}).replace(/RPT_PROPORTION\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=l(c),h=r?r.values.reduce((i,u)=>i+u,0):0;return r&&h!==0?o(r.current/h):'""'}).replace(/RPT_CUMULATIVE\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=l(c);return r?o(r.values.slice(0,r.at+1).reduce((h,i)=>h+i,0)):'""'}).replace(/RPT_(MOM|YOY)\(\s*([^()]+?)\s*\)/gi,(n,c,r)=>{const h=l(r);if(!h)return'""';const i=c.toUpperCase()==="MOM"?1:{month:12,quarter:4,year:1,week:52}[h.by]??12,u=h.values[h.at-i];return u===void 0||u===0?'""':o((h.current-u)/u)}).replace(/RPT_VALUE\(\s*([^()]+?)\s*\)/gi,(n,c)=>a(c)).replace(/RPT_PARAM\(\s*"([^"]+)"\s*\)/gi,(n,c)=>{const r=this._param(c);return typeof r=="number"?String(r):`"${String(r??"").replace(/"/g,'""')}"`}).replace(/RPT_INDEX\(\s*([^()]+?)\s*\)/gi,(n,c)=>{const r=Y(a(c).replace(/\$/g,"")),h=r?this.t.binding(r.r0,r.c0):null;for(let i=e;i!==null;i=i.parent)if(i.node?.binding===h)return String(i.ordinal??1);return"1"}).replace(/RPT_PAGES\(\s*(TRUE)?\s*\)/gi,(n,c)=>{const r=this._pageStarts();if(!c)return String(r.length);const h=this._topContext(e);return String(r.filter(i=>i>=h.first&&i<=h.last).length||1)}).replace(/RPT_PAGE\(\s*(TRUE)?\s*\)/gi,(n,c)=>{const r=this._pageStarts();let h=0;for(let p=0;p<r.length;p++)r[p]<=s&&(h=p);if(!c)return String(h+1);const i=this._topContext(e);let u=0;for(;u<h&&r[u]<i.first;)u++;return String(h-u+1)})}_topContext(t){let s=t;for(let e=t;e!=null&&e.node;e=e.parent)s=e;return s}_measureCell(t,s,e){const l=Y(t.replace(/\$/g,""));if(!l)return null;const a=this.outSheet,f=this.colOut.findIndex(p=>p.tpl===l.c0);if(f<0)return null;let o=e;for(;o&&!o.node&&o.parent;)o=o.parent;const n=o?.node?.binding?.type==="list"?o:o?.parent??o,c=n?.first??0,r=n?.last??this.rowCount-1,h=[];let i=-1,u=1/0;for(let p=c;p<=r;p++){if(this.rowTpl[p]!==l.r0||(a.kind(p,f)&ut)!==B)continue;const m=Math.abs(p-s);(p<=s||i<0)&&m<u&&(u=m,i=h.length),h.push(a.value(p,f))}return i<0||h.length===0?null:{values:h,at:i,current:h[i],by:o?.node?.binding?.by??null}}_pageStarts(){if(this.pageStarts)return this.pageStarts;const t=V(this.book,this.outSheet),s=[];for(let e=0;e<t.pageCount;e++)s.push(t.page(e).r0);return this.pageStarts=s,s}}function ot(g,t,s){const e=[];let l=0,a=g.length;if(t>=0)for(;l<a;){const f=l+a>>>1;g[f]<t?l=f+1:a=f}for(let f=l;f<g.length;f++){const o=g[f];if(t>=0&&o>s)break;const n=e[e.length-1];n&&n[1]===o-1?n[1]=o:e.push([o,o])}return e}function Mt(g,t){let s="",e=0;const l=g.length,a=/(\$?)([A-Za-z]{1,3})(\$?)(\d+)(?::(\$?)([A-Za-z]{1,3})(\$?)(\d+))?/y;for(;e<l;){const f=g[e];if(f==='"'){let c=e+1;for(;c<l;)if(g[c]==='"')if(g[c+1]==='"')c+=2;else break;else c++;s+=g.slice(e,c+1),e=c+1;continue}if(f==="'"){const c=g.indexOf("'!",e+1);if(c>=0){const r=/^\$?[A-Za-z]{1,3}\$?\d+(:\$?[A-Za-z]{1,3}\$?\d+)?/.exec(g.slice(c+2)),h=c+2+(r?r[0].length:0);s+=g.slice(e,h),e=h;continue}}a.lastIndex=e;const o=e>0?g[e-1]:"",n=/[A-Za-z0-9_.!$]/.test(o)?null:a.exec(g);if(n){const c=g[e+n[0].length]??"";if(!/[A-Za-z0-9_.(!]/.test(c)){const r=(i,u,p,w)=>t(p,Number(w)-1,i,wt(u.toUpperCase())),h=r(n[1],n[2],n[3],n[4]);if(n[6]===void 0)s+=h??n[0];else{const i=r(n[5],n[6],n[7],n[8]);s+=h===null||i===null?n[0]:`${h.split(/[:,]/)[0]}:${i.split(/[:,]/).pop()}`}e+=n[0].length;continue}}s+=f,e++}return s}function Tt(g,t,s){const e=new Float64Array(g.length);for(let f=0;f<g.length;f++)e[f]=t[g[f]];const l=new Int32Array(g.length);for(let f=0;f<g.length;f++)l[f]=f;kt(l,g.length,e,s);const a=new Int32Array(g.length);for(let f=0;f<g.length;f++)a[f]=g[l[f]];g.set(a)}const At=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Ot(g,t){const e=j("yyyy-mm").number(Math.floor(g)),l=Number(e.slice(0,4)),a=Number(e.slice(5,7));switch(t){case"year":return String(l);case"quarter":return`Q${Math.floor((a-1)/3)+1} ${l}`;case"month":return`${At[a-1]} ${l}`;default:return j("yyyy-mm-dd").number(Math.floor(g))}}function it(g,t,s,e,l){const a=e.kind(l);a!==$&&g.setCell(t,s,a,e.raw(l))}function lt(g,t,s,e,l){e==null||e===""||(typeof e=="number"?g.setCell(t,s,B,e):typeof e=="boolean"?g.setCell(t,s,ft,e?1:0):e instanceof bt?g.setCell(t,s,Z,e.index):g.setCell(t,s,E,l.add(Array.isArray(e)?e.join(", "):String(e))))}function at(g){const t=[];for(const s of g){const e=t[t.length-1];e&&(e[1]===s||e[1]===s-1)?e[1]=s:t.push([s,s])}return t}function ct(g){const t=g.reportMap;if(t){for(const s of t.collapses)for(let e=s.from;e<=s.to;e++)g.rows.setHidden(e,!1);for(const s of t.collapses)if(s.collapsed)for(let e=s.from;e<=s.to;e++)g.rows.setHidden(e,!0);g.revision++}}function jt(g,t,s,e=void 0,l=!1){const a=g.reportMap;if(!a)return!1;const f=a.collapses.find(n=>n.row===t&&(s===void 0||n.col===s));if(!f)return!1;const o=e===void 0?!f.collapsed:e==="collapsed"||e===!0;if(f.collapsed=o,l)for(const n of a.collapses)n.from>=f.from&&n.to<=f.to&&(n.collapsed=o);return ct(g),!0}function Et(g,t,s={}){return V(g,t,s).pageCount}export{Rt as BINDING_TYPES,T as ReportError,ht as ReportTemplate,ct as applyCollapses,Et as reportPages,jt as toggleCollapse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{formulaHelper as w}from"./view.js";import{colName as k}from"../core/address.js";import{tableColors as $}from"../core/tables.js";import{ROW as S}from"./data.js";import{tint as s}from"../core/color.js";const m={headerFill:"#107c41",headerInk:"#ffffff",band:"#f1f8f4",group:["#d9ead3","#e8f3e4","#f1f8ee","#f7fbf5"],footer:"#f2f2f2",total:"#e4e4e4",pinned:"#fff7dc",rule:"#8fbfa3",tier:"#f3f3f3",tierInk:"#3b3b3b",tierLine:"#d0d0d0",bar:"#4a90d9",barDone:"#22598f",summary:"#404040"};function c(e){return{...m,headerFill:e,band:s(e,.93),group:[s(e,.75),s(e,.85),s(e,.9),s(e,.95)],rule:s(e,.45),bar:s(e,.15),barDone:s(e,-.35)}}const E={green:m,blue:c("#2f6fb3"),orange:c("#c56a00"),red:c("#b23a3a"),purple:c("#7a4fb5"),teal:c("#1f8a8a"),gray:{...c("#5f6368"),bar:"#7c7f85",barDone:"#3c4043"},plain:{...m,headerFill:"#f3f3f3",headerInk:"#242424",band:"#fafafa",group:["#ececec","#f2f2f2","#f6f6f6","#fafafa"],rule:"#c8c8c8"}};function V(e,t){if(!e)return m;if(E[e])return E[e];const r=$(e,t);if(!r)return m;const a=r.headerFill??r.rule??"#404040";return{...c(a),headerFill:r.headerFill??"#ffffff",headerInk:r.headerFill?r.headerInk??"#ffffff":"#000000",band:r.band??m.band}}const y=e=>{const t={};for(const r of["fill","color","bold","italic","underline","strike","numFmt","hAlign","vAlign","indent","wrap","fontSize","fontName","borders"])e[r]!==void 0&&(t[r]=e[r]);return t};class D{constructor(t){this.sheet=t,this.table=t.table,this.list=[],this.overlays={};for(const r of t.view.spec.rules){const a=y(r.style??{});if(r.state==="hover"||r.state==="selected"){this.overlays[r.state]=a.fill??"#107c41";continue}const u={rule:r,patch:a,key:JSON.stringify(a),fields:r.fields?new Set(r.fields):null,helper:null};r.formula&&(u.helper=w(this.table,r.formula)),this.list.push(u)}}get active(){return this.list.length>0}apply(t,r,a,u){let o=t;const{table:n}=this,{styles:i}=this.sheet.book;for(const l of this.list){if(l.fields!==null&&!l.fields.has(a.field))continue;let f;if(l.helper!==null){const d=l.helper.get(r);f=d===!0||typeof d=="number"&&d!==0}else switch(l.rule.state){case"dirty":f=n.state[r]===S.UPDATED&&(n.isCellEdited(r,a.col)||l.fields===null);break;case"inserted":f=n.state[r]===S.INSERTED;break;case"pinned":f=u;break;case"readOnly":f=a.readOnly;break;case"required":f=a.col.required===!0&&a.col.kind(r)===0;break;default:f=!1}f&&(o=i.derive(o,l.patch,l.key))}return o}}const q={greaterThan:"greaterThan",lessThan:"lessThan",greaterThanOrEqual:"greaterThanOrEqual",lessThanOrEqual:"lessThanOrEqual",equal:"equal",notEqual:"notEqual",between:"between",notBetween:"notBetween"},v=e=>typeof e=="number"?String(e):`"${String(e).replace(/"/g,'""')}"`;function R(e,t,r,a){let u=null;t.style&&(e.dxfs||(e.dxfs=[]),e.dxfs.push(y(t.style)),u=e.dxfs.length-1);const o={priority:r,dxfId:u,stopIfTrue:t.stopIfTrue===!0};switch(t.type){case"cellValue":return{...o,type:"cellIs",operator:q[t.operator]??"equal",formulas:[t.value,t.value2].filter(n=>n!==void 0).map(v)};case"text":{const n=t.operator??"contains",i=String(t.value??""),l=v(i);return n==="beginsWith"?{...o,type:"beginsWith",operator:"beginsWith",text:i,formulas:[`LEFT(${a},${i.length})=${l}`]}:n==="endsWith"?{...o,type:"endsWith",operator:"endsWith",text:i,formulas:[`RIGHT(${a},${i.length})=${l}`]}:n==="notContains"?{...o,type:"notContainsText",operator:"notContains",text:i,formulas:[`ISERROR(SEARCH(${l},${a}))`]}:{...o,type:"containsText",operator:"containsText",text:i,formulas:[`NOT(ISERROR(SEARCH(${l},${a})))`]}}case"date":return{...o,type:"timePeriod",timePeriod:t.period??"today",formulas:[]};case"top":case"bottom":return{...o,type:"top10",rank:t.rank??10,percent:t.percent===!0,bottom:t.type==="bottom"};case"average":return{...o,type:"aboveAverage",aboveAverage:t.above!==!1,equalAverage:t.equal===!0};case"duplicate":return{...o,type:"duplicateValues"};case"unique":return{...o,type:"uniqueValues"};case"blank":return{...o,type:"containsBlanks",formulas:[`LEN(TRIM(${a}))=0`]};case"notBlank":return{...o,type:"notContainsBlanks",formulas:[`LEN(TRIM(${a}))>0`]};case"errors":return{...o,type:"containsErrors",formulas:[`ISERROR(${a})`]};case"formula":return{...o,type:"expression",formulas:[String(t.formula).replace(/^=/,"")]};case"dataBar":return{...o,type:"dataBar",dataBar:{cfvo:[{type:"min"},{type:"max"}],color:T(t.color??"#638EC6"),showValue:t.showValue!==!1}};case"colorScale":{const n=t.colors??["#F8696B","#FFEB84","#63BE7B"],i=n.length===2?[{type:"min"},{type:"max"}]:[{type:"min"},{type:"percentile",val:"50"},{type:"max"}];return{...o,type:"colorScale",colorScale:{cfvo:i,colors:n.map(T)}}}case"iconSet":{const n=t.name??"3TrafficLights1",i=Number(n[0])||3,l=[];for(let f=0;f<i;f++)l.push({type:"percent",val:String(Math.round(f*100/i))});return{...o,type:"iconSet",iconSet:{name:n,cfvo:l,reverse:t.reverse===!0,showValue:t.showValue!==!1}}}default:return null}}const T=e=>({rgb:`FF${e.slice(1).toUpperCase()}`});function B(e,t){const r={sqref:t,allowBlank:e.allowBlank!==!1,showErrorMessage:!0,showInputMessage:!!e.prompt,promptTitle:e.promptTitle,prompt:e.prompt,errorStyle:e.errorStyle??"stop",errorTitle:e.errorTitle,error:e.message};switch(e.type){case"list":return{...r,type:"list",formula1:e.formula??`"${(e.items??[]).join(",")}"`,showDropDown:!0};case"number":case"decimal":case"whole":case"date":case"time":case"textLength":{const a=e.type==="number"?e.whole?"whole":"decimal":e.type;if(e.operator){const u=e.operator==="between"||e.operator==="notBetween";return{...r,type:a,operator:e.operator,formula1:String(e.min??e.value??0),...u?{formula2:String(e.max??0)}:{}}}return e.min!==void 0&&e.max!==void 0?{...r,type:a,operator:"between",formula1:String(e.min),formula2:String(e.max)}:e.min!==void 0?{...r,type:a,operator:"greaterThanOrEqual",formula1:String(e.min)}:e.max!==void 0?{...r,type:a,operator:"lessThanOrEqual",formula1:String(e.max)}:null}case"custom":return e.formula?{...r,type:"custom",formula1:String(e.formula).replace(/^=/,"")}:null;default:return null}}function M(e){const{view:t,book:r}=e,a=e.bodyStart+1,u=Math.max(a,e.bodyStart+t.count),o=[],n=[];let i=1;t.columns.forEach((d,x)=>{const p=k(x),b=`${p}${a}:${p}${u}`;for(const h of d.conditionalFormats??[]){const g=R(r,h,i++,`${p}${a}`);g&&o.push({sqref:b,rules:[g]})}if(d.validator){const h=B(d.validator,b);h&&n.push(h)}});const l=e.cf&&e.cf.length>0;(o.length>0||l)&&(e.cf=o,e.cfChanged=!0,e.cfEval=void 0);const f=e.validations&&e.validations.length>0;(n.length>0||f)&&(e.validations=n,e.validationsChanged=!0)}export{D as StyleRules,E as THEMES,M as applyColumnRules,y as stylePatch,V as themeColors};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{compareText as B}from"../calc/values.js";const C=2048,k=C-1;function K(f,t,c){const o=new Uint32Array(C),a=new Uint32Array(C),w=new Uint32Array(1024);for(let i=0;i<t;i++){const n=c[i];o[n&k]++,a[n>>>11&k]++,w[n>>>22]++}let s=f,r=c,A=new Int32Array(t),u=new Uint32Array(t);const l=(i,n,h)=>{let U=0,e=!1;for(let y=0;y<=h;y++){const S=i[y];S===t&&(e=!0),i[y]=U,U+=S}if(e)return;for(let y=0;y<t;y++){const S=r[y],v=i[S>>>n&h]++;A[v]=s[y],u[v]=S}const g=s;s=A,A=g;const p=r;r=u,u=p};l(o,0,k),l(a,11,k),l(w,22,1023),s!==f&&f.set(s.subarray(0,t))}const M=new Float64Array(1),N=new Uint32Array(M.buffer);function O(f,t,c,o=!1){const a=new Uint32Array(t),w=new Uint32Array(t),s=new Uint32Array(C*6),r=o?4294967295:0;for(let e=0;e<t;e++){const g=c[f[e]];let p,y;g!==g?(p=4294967295,y=4294967295):(M[0]=g+0,p=N[1],y=N[0],p>>>31?(p=~p>>>0,y=~y>>>0):p=(p|2147483648)>>>0,p=(p^r)>>>0,y=(y^r)>>>0,p===4294967295&&y===4294967295&&(y=4294967294)),a[e]=p,w[e]=y,s[y&k]++,s[C+(y>>>11&k)]++,s[C*2+(y>>>22)]++,s[C*3+(p&k)]++,s[C*4+(p>>>11&k)]++,s[C*5+(p>>>22)]++}let A=f,u=a,l=w,i=new Int32Array(t),n=new Uint32Array(t),h=new Uint32Array(t);const U=(e,g,p,y)=>{const S=e*C;let v=0,F=!1;for(let I=0;I<=y;I++){const L=s[S+I];L===t&&(F=!0),s[S+I]=v,v+=L}if(F)return;const T=g?u:l;for(let I=0;I<t;I++){const L=s[S+(T[I]>>>p&y)]++;i[L]=A[I],n[L]=u[I],h[L]=l[I]}let x=A;A=i,i=x,x=u,u=n,n=x,x=l,l=h,h=x};U(0,!1,0,k),U(1,!1,11,k),U(2,!1,22,1023),U(3,!0,0,k),U(4,!0,11,k),U(5,!0,22,1023),A!==f&&f.set(A.subarray(0,t))}function $(f,t,c,o,a,w=!1){const s=new Uint32Array(t),r=a-1;for(let A=0;A<t;A++){const u=c[f[A]];s[A]=u<0?4294967295:w?r-o[u]:o[u]}K(f,t,s)}const R=' !"#$%&()*,./:;?@[\\]^_`{|}~+<=>',b=new Uint16Array(128);{let f=1;for(let t=0;t<128;t++){const c=t>=48&&t<=57,o=t>=65&&t<=90||t>=97&&t<=122;!c&&!o&&!R.includes(String.fromCharCode(t))&&(b[t]=f++)}for(const t of R)b[t.charCodeAt(0)]=f++;for(let t=48;t<=57;t++)b[t]=f++;for(let t=97;t<=122;t++)b[t]=f,b[t-32]=f,f++}const j=/^[\x00-\x7f]*$/,D=2e4,_=f=>{const t=f.toLowerCase(),c=j.test(t)?t:t.normalize("NFD").replace(/\p{M}/gu,"");return/['-]/.test(c)?`${c.replace(/['-]/g,"")}${c}`:c};function z(f,t,c){const o=[0,f.length,0],a=(w,s)=>{const r=t[w]+s;return r<t[w+1]?c[r]:0};for(;o.length>0;){const w=o.pop(),s=o.pop(),r=o.pop(),A=s-r;if(A<2)continue;if(A<12){for(let g=r+1;g<s;g++){const p=f[g];let y=g;for(;y>r&&E(p,f[y-1],t,c,w);)f[y]=f[y-1],y--;f[y]=p}continue}const u=a(f[r],w),l=a(f[r+(A>>1)],w),i=a(f[s-1],w),n=u<l?l<i?l:u<i?i:u:u<i?u:l<i?i:l;let h=r,U=s-1,e=r;for(;e<=U;){const g=a(f[e],w);if(g<n){const p=f[h];f[h]=f[e],f[e]=p,h++,e++}else if(g>n){const p=f[U];f[U]=f[e],f[e]=p,U--}else e++}o.push(r,h,w),o.push(U+1,s,w),n!==0&&o.push(h,U+1,w+1)}}function E(f,t,c,o,a){let w=c[f]+a,s=c[t]+a;const r=c[f+1],A=c[t+1];for(;w<r&&s<A;){const u=o[w++]-o[s++];if(u!==0)return u<0}return r-w<A-s}function H(f,t,c){const o=t.length,a=new Int32Array(c).fill(-1);if(o===0)return{rank:a,count:0};if(o<=D){const n=new Array(o);for(let e=0;e<o;e++)n[e]=e;const h=new Array(o);for(let e=0;e<o;e++)h[e]=f.get(t[e]);n.sort((e,g)=>B(h[e],h[g]));let U=-1;for(let e=0;e<o;e++)(e===0||B(h[n[e-1]],h[n[e]])!==0)&&U++,a[t[n[e]]]=U;return{rank:a,count:U+1}}const w=new Array(o);let s=0;for(let n=0;n<o;n++){const h=_(f.get(t[n]));w[n]=h,s+=h.length}const r=new Uint32Array(o+1),A=new Uint16Array(s);let u=0;for(let n=0;n<o;n++){r[n]=u;const h=w[n];for(let U=0;U<h.length;U++){const e=h.charCodeAt(U);A[u++]=e<128?b[e]:e+128}}r[o]=u;const l=new Int32Array(o);for(let n=0;n<o;n++)l[n]=n;z(l,r,A);let i=-1;for(let n=0;n<o;n++){const h=l[n];(n===0||!Y(A,r,l[n-1],h))&&i++,a[t[h]]=i}return{rank:a,count:i+1}}function Y(f,t,c,o){const a=t[c+1]-t[c];if(a!==t[o+1]-t[o])return!1;const w=t[c],s=t[o];for(let r=0;r<a;r++)if(f[w+r]!==f[s+r])return!1;return!0}function W(f,t,c,o,a=!1){if(f.ensure(o),o.isString){const{rank:l,count:i}=o.ranks();$(t,c,o.data,l,i,a);return}if(o.kinds===null){O(t,c,o.data,a);return}const{rank:w}=o.ranks(),{kinds:s,data:r}=o,A=new Float64Array(f.rowCount);for(let l=0;l<c;l++){const i=t[l];A[i]=s[i]===1?r[i]:NaN}O(t,c,A,a);const u=new Uint32Array(c);for(let l=0;l<c;l++){const i=t[l],n=s[i];n===0?u[l]=4294967295:n===1?u[l]=a?2147483647:0:n===2?u[l]=a?1879048191-w[r[i]]:1+w[r[i]]:n===3?u[l]=a?2-r[i]:1879048192+r[i]:u[l]=a?1:2147483632}K(t,c,u)}export{H as rankStrings,O as sortByF64,$ as sortByRank,K as sortByU32,W as sortColumn};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createTable as lt}from"../core/tables.js";import{BOOL as S,CHUNK_BITS as ht,CHUNK_MASK as at,CHUNK_SIZE as ct,EMPTY as K,ERR as ut,FORMULA as ft,KIND_MASK as L,NUM as R,STR as g}from"../core/sheet.js";import{MAX_ROWS as dt}from"../core/address.js";import{ERR_BY_INDEX as pt,XlError as N}from"../calc/values.js";import{VirtualSheet as wt}from"./virtual-sheet.js";import{DataError as yt,ROW as mt}from"./data.js";import{applyColumnRules as gt,stylePatch as F,StyleRules as bt,themeColors as V}from"./rules.js";import{formulaHelper as Rt}from"./view.js";import{cellRef as P}from"../core/address.js";import{t as z}from"../i18n/index.js";const zt=["pin","status","save","reset","remove"],vt={number:76,date:84,boolean:56,string:120,any:96};class ${constructor(t){this.sheet=t,this.cache=new Map,this.groupCache=new Map}get size(){return this.cache.size>0||this.groupCache.size>0?2147483647:0}get(t){if(this.cache.size===0&&this.groupCache.size===0)return;const e=Math.floor(t/16384),s=t-e*16384,i=this.sheet.describeRow(e);if(i?.kind==="group")return this.groupCache.size>0?this.groupCache.get(`${i.level}|${s}`):void 0;if(i?.kind==="record"||i?.kind==="pinned")return this.cache.get(s)}has(t){return this.get(t)!==void 0}[Symbol.iterator](){return[][Symbol.iterator]()}entries(){return[][Symbol.iterator]()}keys(){return[][Symbol.iterator]()}values(){return[][Symbol.iterator]()}forEach(){}set(){return this}delete(){return!1}}class B extends wt{constructor(t,e,s,i={}){super(e),this.book=t,this.view=s,this.table=s.table,this.kindName="table",this.options={banded:!0,allowAdd:!0,allowRemove:!0,rowHeight:18,...i},this.exporting=!1,this.bodyStart=1,this.showNew=this.options.allowAdd,this.freeRows=0,this.headerRowCount=1,this.headerRow=0,this.rules=null,this.colors=V(this.options.theme,t.theme),this.styleCache=new Map,this.styleGen=0,this.columnStyle=[],this.onRejected=null,this.onRefresh=null,this._flushQueued=!1,this._pendingEmpty=new Set,this._writing=0,this.rows.setDefaultSize(this.options.rowHeight),this._unsubscribe=s.onChange(n=>this._viewChanged(n)),this.applyLayout()}setTheme(t){this.options.theme=t,this.colors=V(t,this.book.theme),this.styleCache.clear(),this.columnStyle=[],this.invalidateCells(),this.onRefresh?.()}dispose(){this._unsubscribe()}get viewColumnCount(){return this.view.columns.length}get lastRow(){return this.bodyStart+this.view.count+(this.showNew&&!this.exporting?1:0)-1}applyLayout({keepCells:t=!1}={}){const{view:e}=this,s=e.pinned.length,i=e.spec.options.freeHeader;this.freeRows=i?.rows??0;const n=e.columns.reduce((l,h)=>Math.max(l,h.captionPath?.length??1),1);this.headerRowCount=n,this.headerRow=this.freeRows+n-1,this.bodyStart=this.freeRows+n+s,this.showNew=this.supportsNewRow();const r=this.bodyStart,o=e.pinnedColumnCount;(r!==this.frozenRows||o!==this.frozenCols)&&(this.frozenRows=r,this.frozenCols=o,this.viewChanged=!0),this._applyColumnWidths(),this._applyHeaderLayout(),this.setShape(this.shapeColumnCount(),Math.min(this.lastRow,dt-1)),this.columnStyle=[],this.rules=e.spec.rules.length>0?new bt(this):null,this._applyCellTypes(),gt(this),this.cfEval?.invalidate(),this._syncEngineTable(),t||this.invalidateCells()}_applyHeaderLayout(){const{view:t,freeRows:e,headerRowCount:s}=this,i=[];if(s>1){const l=t.columns,h=u=>{const f=u.captionPath??[u.caption];return Array.from({length:s},(p,w)=>f[Math.min(w,f.length-1)])},a=l.map(h);for(let u=0;u<s;u++)for(let f=0;f<l.length;){let p=f;for(;p+1<l.length&&a[p+1][u]===a[f][u]&&a[p+1].slice(0,u).join("")===a[f].slice(0,u).join("");)p++;let w=u;for(;w+1<s&&p===f&&a[f][w+1]===a[f][u];)w++;(p>f||w>u)&&i.push({r0:e+u,c0:f,r1:e+w,c1:p}),f=p+1}}JSON.stringify(this.merges)!==JSON.stringify(i)&&(this.merges=i,this.mergeIndex=null);let r=0;for(const l of t.columns){const h=String(l.caption??"").length;l.headerFit==="vertical"?r=Math.max(r,h*7+26):l.headerFit==="stack"&&(r=Math.max(r,h*14+22))}const o=t.spec.options.headerHeight??(r>0?r:0);o>0&&this.rows.sizeOf(this.headerRow)!==o&&this.rows.setSize(this.headerRow,o)}_applyCellTypes(){const t=B.makeCellType,e=t?this.view.columns.map((i,n)=>[n,i.cellType]).filter(([,i])=>i):[],s=[];if(t&&this.view.spec.groups.forEach((i,n)=>{for(const[r,o]of Object.entries(i.cellTypes??{})){const l=this.view.columns.findIndex(h=>h.field===r);l>=0&&s.push([`${n}|${l}`,o])}}),e.length===0&&s.length===0){this.cellTypes instanceof $&&(this.cellTypes=null);return}this.cellTypes instanceof $||(this.cellTypes=new $(this)),this.cellTypes.cache.clear(),this.cellTypes.groupCache.clear();for(const[i,n]of e){const r=t(n.type,n);r&&this.cellTypes.cache.set(i,r)}for(const[i,n]of s){const r=t(n.type,n);r&&this.cellTypes.groupCache.set(i,r)}}_syncEngineTable(){const t=this.book.engine;if(!t||this.kindName===void 0)return;const e=this.table.name.replace(/[^A-Za-z0-9_.]/g,"_").toUpperCase();let s=this.engineTable;if(!s){if(t.tables.has(e))return;s={name:this.table.name.replace(/[^A-Za-z0-9_.]/g,"_"),sheet:this,headerRows:1,totalsRows:0,columns:[],styleName:null,showRowStripes:!1,dataSheet:!0},this.engineTable=s,t.tables.set(e,s)}s.r0=this.headerRow,s.c0=0,s.c1=Math.max(0,this.view.columns.length-1),s.r1=Math.max(this.headerRow+1,this.bodyStart+this.view.count-1),s.columns=this.view.columns.map(i=>({name:i.field})),s.columnNames=s.columns.map(i=>i.name)}supportsNewRow(){const{spec:t}=this.view;return this.options.allowAdd&&t.groups.length===0&&!t.hierarchy&&t.totals.length===0}shapeColumnCount(){return this.view.columns.length}_applyColumnWidths(){const{view:t}=this;let e=null;t.columns.forEach((s,i)=>{if(typeof s.width=="string"&&s.width.endsWith("*")){(e??=[]).push({col:i,weight:Number(s.width.slice(0,-1))||1});return}s.special==="actions"&&this.cols.isHidden(i)&&!this.hidActions&&this.cols.setHidden(i,!1);const n=s.width??Math.max(vt[s.col.type]??96,Math.min(200,s.caption.length*8+26));this.cols.sizeOf(i)!==n&&this.cols.setSize(i,n)}),this.starColumns=e,this.starRoom=-1,this.colsChanged=!0}defaultPrintAreas(){if(this.view.columns[0]?.special!=="actions")return[];const t=this.bodyStart+this.view.count-1;return[{r0:0,c0:1,r1:Math.max(t,this.headerRow),c1:Math.max(1,this.view.columns.length-1)}]}toWorksheetTable(t=null){const{book:e,view:s}=this,i=t??this._freeSheetName(`${this.name} Table`),n=e.addSheet(i),r=s.columns.filter(a=>!a.special);r.forEach((a,u)=>{n.setCell(0,u,g,e.strings.add(a.caption));const f=this.cols.sizeOf(s.columns.indexOf(a));f>0&&n.cols.setSize(u,f)});let o=1;const l=r.map(a=>a.format&&a.format!=="General"?e.styles.derive(0,{numFmt:a.format}):0);for(let a=0;a<s.count;a++){const u=s.map[a];u<0||(r.forEach((f,p)=>{f.col.table.ensure(f.col);const w=f.col.get(u);w==null||w===""||(typeof w=="number"?n.setCell(o,p,R,w):typeof w=="boolean"?n.setCell(o,p,S,w?1:0):n.setCell(o,p,g,e.strings.add(String(w))),l[p]!==0&&n.setStyle(o,p,l[p]))}),o++)}e.engine?.sheetsChanged?.();const h=lt(e,n,{r0:0,c0:0,r1:Math.max(1,o-1),c1:Math.max(0,r.length-1)},!0);return{sheet:n,table:h}}_freeSheetName(t){const e=i=>this.book.sheets.some(n=>n.name.toLowerCase()===i.toLowerCase());let s=t;for(let i=2;e(s);i++)s=`${t} ${i}`;return s}fitStarColumns(t){const e=this.starColumns;if(e===null||this.starRoom===t)return!1;this.starRoom=t;const s=new Set(e.map(o=>o.col));let i=0,n=0;this.view.columns.forEach((o,l)=>{s.has(l)||(i+=this.cols.sizeOf(l))});for(const o of e)n+=o.weight;const r=Math.max(0,t-i);for(const o of e)this.cols.setSize(o.col,Math.max(40,Math.floor(r*o.weight/n)));return this.colsChanged=!0,!0}captureWidths(){const{view:t}=this,e=t.columns;let s=!1;const i=t.spec.columns.map(n=>{const r=e.findIndex(l=>l.def===n);if(r<0)return n;const o=this.cols.sizeOf(r);return n.width===o||typeof n.width=="string"?n:(s=!0,{...n,width:o})});s&&(t.spec.columns=i,t._columns=null)}_style(t,e){let s=this.styleCache.get(t);return s===void 0&&(s=this.book.styles.derive(0,e),this.styleCache.set(t,s)),s}_styleOf(t){let e=this.columnStyle[t];if(e!==void 0)return e;const s=this.view.columns[t],i={numFmt:s.format??"General"};s.align&&(i.hAlign=s.align);const n=`p|${i.numFmt}|${s.align??""}`,r=i.numFmt==="General"&&!s.align?0:this._style(n,i);s.style&&Object.assign(i,F(s.style));const o=s.style?`${n}|${JSON.stringify(s.style)}`:n,l=s.style?this._style(`p|${o}`,i):r,h=this.options.banded&&!i.fill?this._style(`b|${o}`,{...i,fill:this.colors.band}):l,a=this._style(`n|${o}`,{...i,fill:this.colors.pinned});return e={plain:l,band:h,pinned:a,fmt:i,plainKey:o},this.columnStyle[t]=e,e}_headerStyle(){return this._style("header",{bold:!0,fill:this.colors.headerFill,color:this.colors.headerInk,vAlign:"center"})}_groupStyle(t,e){const s=this.colors.group[Math.min(t,this.colors.group.length-1)];if(e===0)return this._style(`g0|${t}`,{bold:!0,fill:s,indent:t+1});const{fmt:i,plainKey:n}=this._styleOf(e);return this._style(`g|${t}|${n}`,{...i,bold:!0,fill:s})}_footerStyle(t,e){const s=t<0?this.colors.total:this.colors.footer,i={t:{style:t<0?"double":"thin",color:"#6f6f6f"}};if(e===0)return this._style(`f0|${t<0?"t":t}`,{bold:!0,fill:s,indent:Math.max(0,t+1),borders:i});const{fmt:n,plainKey:r}=this._styleOf(e);return this._style(`f|${t<0?"t":"g"}|${r}`,{...n,bold:!0,fill:s,borders:i})}_indentStyle(t,e,s){const{fmt:i,plainKey:n}=this._styleOf(s);return this._style(`i|${t}|${e?1:0}|${n}`,{...i,indent:t,...e?{fill:this.colors.band}:{}})}describeRow(t){if(t<this.freeRows)return{kind:"free"};if(t<=this.headerRow)return{kind:"header",buttons:t===this.headerRow};if(t<this.bodyStart)return{kind:"pinned",record:this.view.pinned[t-this.headerRow-1],level:0};const e=t-this.bodyStart;return e>=this.view.count?e===this.view.count&&this.showNew&&!this.exporting?{kind:"new"}:null:{viewRow:e,...this.view.rowInfo(e)}}recordAtRow(t){return t<=this.headerRow?-1:t<this.bodyStart?this.view.pinned[t-this.headerRow-1]:this.view.recordAt(t-this.bodyStart)}rowOfRecord(t){const e=this.view.pinned.indexOf(t);if(e>=0)return this.headerRow+1+e;const s=this.view.rowOfRecord(t);return s<0?-1:s+this.bodyStart}fillChunk(t,e,s){const{view:i,table:n}=this,{kinds:r,values:o,store:l}=s;r.fill(0),l.fill(0),s.hasStyles=!0;const h=i.columns[t];if(h===void 0)return;const a=h.col;a.stale&&n.ensure(a);const u=e<<ht,{bodyStart:f,headerRow:p,freeRows:w,headerRowCount:G}=this,{map:D,count:J}=i,{plain:Q,band:X,pinned:Z}=this._styleOf(t),k=(h.display?Rt(n,h.display):null)??a,{data:O,isString:Y,styles:A}=k,E=k.kinds,q=k.type==="boolean",C=i.spec.hierarchy,H=C?i.treeLevel:null,tt=C?Math.max(0,C.column?i.columnIndex(C.column):0):-1,x=C?i.rollups.get(h.field):void 0,T=this.options.banded,et=f>p+1,j=this.rules!==null&&this.rules.active?this.rules:null,v=h.showNullAs?this.book.strings.add(h.showNullAs):-1,st=h.showEmptyAs?this.book.strings.add(""):-1,it=h.showEmptyAs?this.book.strings.add(h.showEmptyAs):-1,nt=h.special==="rowNumber",ot=h.special!==void 0,M=i.spec.groups,I=i.spec.groupLayout==="tabular"?M.findIndex(c=>c.field===h.field):-1,W=i.spec.groupLayout==="condensed"&&t===0&&M.length>0?M.length:0,rt=Math.min(ct,this.maxRow+1-u);for(let c=0;c<rt;c++){const m=u+c;let y,b;if(m<=p){if(m<w){this._fillFreeCell(s,c,m,t);continue}const d=m-w,_=h.captionPath??[h.caption],U=_[Math.min(d,_.length-1)];(G===1||!this.mergeAt(m,t)||this.mergeAt(m,t).r0===m&&this.mergeAt(m,t).c0===t)&&U!==""&&(r[c]=g,o[c]=this.book.strings.add(String(U))),l[c]=this._headerStyleOf(h);continue}if(et&&m<f)y=i.pinned[m-p-1],b=Z;else{const d=m-f;if(d>=J)continue;const _=D[d];if(_<0){this._fillGroupCell(s,c,_,t,h);continue}if(y=_,b=T&&(d&1)===1?X:Q,t===tt&&H!==null?b=this._indentStyle(H[y]+1,T&&(d&1)===1,t):W>0&&(b=this._indentStyle(W,T&&(d&1)===1,t)),nt){r[c]=R,o[c]=i.recordNumberAt(d),l[c]=b;continue}}if(ot){l[c]=b;continue}if(A!==null&&A[y]!==0&&(b=A[y]),j!==null&&(b=j.apply(b,y,h,m<f)),l[c]=b,h.summaryOnly){if(i.spec.groupLayout==="tabular"&&i.showsGroupValue(y,h.sliceLevel)){const d=i.summaryOfRecord(y,h);d!==void 0&&d===d&&(r[c]=R,o[c]=d)}continue}if(!(I>=0&&!i.showsGroupValue(y,I))){if(x!==void 0&&x.touched[y]===1){const d=x.values[y];d===d&&(r[c]=R,o[c]=d);continue}if(Y){const d=O[y];d>=0?(r[c]=g,o[c]=d===st?it:d):v>=0&&(r[c]=g,o[c]=v)}else if(E!==null)r[c]=E[y],o[c]=O[y],E[y]===K&&v>=0&&(r[c]=g,o[c]=v);else{const d=O[y];d===d?(r[c]=q?S:R,o[c]=d):v>=0&&(r[c]=g,o[c]=v)}}}}_fillFreeCell(t,e,s,i){const r=this.view.spec.options.freeHeader?.cells?.[P(s,i)];if(!r)return;const o=r.value;typeof o=="number"?(t.kinds[e]=R,t.values[e]=o):typeof o=="boolean"?(t.kinds[e]=S,t.values[e]=o?1:0):o!=null&&o!==""&&(t.kinds[e]=g,t.values[e]=this.book.strings.add(String(o))),r.style&&(t.store[e]=this._style(`free|${JSON.stringify(r.style)}`,F(r.style)))}_headerStyleOf(t){const e=t.headerFit,s=t.headerStyle;if(!s&&(!e||e==="normal"))return this._headerStyle();const i=e==="vertical"?90:e==="stack"?255:0,n=`header|${e}|${s?JSON.stringify(s):""}`;return this._style(n,{bold:!0,fill:this.colors.headerFill,color:this.colors.headerInk,vAlign:"center",rotation:i,hAlign:i?"center":void 0,...s?F(s):{}})}_fillGroupCell(t,e,s,i,n){const{view:r}=this,o=-s-1,l=o>>>1,h=(o&1)===1,a=r.nodeLevel[l];if(t.store[e]=h?this._footerStyle(a,i):this._groupStyle(a,i),i===0){t.kinds[e]=g;const f=h?a<0?"Total":`${r.groupCaption(l)} total`:r.groupCaption(l);t.values[e]=this.book.strings.add(f);return}const u=r.summaryFor(l,n.field);u!==void 0&&u===u&&(t.kinds[e]=R,t.values[e]=u)}routeCell(t,e,s,i){if(s&ft)return;const n=this.view.columns[e];if(n===void 0)return;if(t<this.freeRows){this._writeFree(t,e,s,i);return}if(t<=this.headerRow){t===this.headerRow&&(s&L)===g&&this._rename(n,this.book.strings.get(i));return}const r=s&L;let o;switch(r){case R:o=i;break;case g:o=this.book.strings.get(i);break;case S:o=i!==0;break;case ut:o=pt[i]??null;break;default:o=null}this._write(t,e,n,o)}routeFormula(t,e,s){const i=this.view.columns[e];if(i===void 0||t<=this.headerRow)return;const n=s.f??s.sf;if(n===void 0)return;const r=this.recordAtRow(t);let o;try{n.includes("[")&&r>=0?o=this.table.manager.formulas.evaluateOnce(this.table,r,n):this.book.engine?(o=this.book.engine.template(n,t,e).fn(t,e,this),o&&o.isCell&&(o=this.book.engine.read(o.sheet,o.r0,o.c0))):o=null}catch(l){o=l instanceof N?l:null}if(o instanceof N&&i.col.type!=="any"){this._reject(z("The formula gives {error}, which the {field} field can't store.",{error:o.code,field:i.caption}));return}this._write(t,e,i,o)}routeInput(t,e,s,i){const n=this.view.columns[s];if(n===void 0||e<=this.headerRow)return!1;if(i[0]==="="&&i.includes("[")){const o=this.recordAtRow(e);if(o<0)return!1;t.saveCell(e,s);const l=this.table.manager.formulas.evaluateOnce(this.table,o,i);return l instanceof N&&n.col.type!=="any"?this._reject(z("The formula gives {error}, which the {field} field can't store.",{error:l.code,field:n.caption})):this._write(e,s,n,l),!0}if(n.col.type!=="string"||i[0]==="=")return!1;t.saveCell(e,s);const r=i[0]==="'"?i.slice(1):i;return this._write(e,s,n,r===""?null:r),!0}_writeFree(t,e,s,i){const n=this.view.spec.options,r=s&L,o=P(t,e),l={...n.freeHeader.cells??{}},h=r===R?i:r===g?this.book.strings.get(i):r===S?i!==0:null;h===null?delete l[o]:l[o]={...l[o]??{},value:h},n.freeHeader={...n.freeHeader,cells:l},this.patchCached(t,e,r,i)}_write(t,e,s,i){let n=this.recordAtRow(t);if(n<0){if(t<this.bodyStart)return;const o=t-this.bodyStart;if(o<this.view.count||!this.options.allowAdd||i===null||(n=this._appendForWrite(o),n<0))return}if(s.readOnly){this._reject(z(s.col.computed?"The {field} field is calculated, so it can't be edited.":"The {field} field is read-only, so it can't be edited.",{field:s.caption}));return}this._writing++;try{this.table.set(n,s.col,i)}catch(o){if(!(o instanceof yt))throw o;this._reject(o.message);return}finally{this._writing--}const r=s.col.kind(n);this.patchCached(t,e,r,s.col.raw(n)),i===null&&this.table.state[n]===mt.INSERTED&&this._pendingEmpty.add(n),this.scheduleFlush(),this.afterRecordWrite?.(n,s.field)}_appendForWrite(t){let e=-1;this._writing++;try{for(let s=this.view.count;s<=t;s++)e=this.table.addRow(this.newRecordValues?.()??{})}finally{this._writing--}return e}_rename(t,e){this.view.setColumn(t.field,{caption:e})}_reject(t){this.lastRejection=t,this.scheduleFlush(),this.onRejected?.(t)}routeStyle(t,e,s){const i=this.view.columns[e];if(i===void 0||t<=this.headerRow)return;const n=this.recordAtRow(t);if(n<0||i.special)return;const r=i.col,{plain:o,band:l,pinned:h}=this._styleOf(e),a=s===o||s===l||s===h;if(r.styles===null){if(a||s===0)return;r.styles=new Uint16Array(r.table.capacity)}r.styles[n]=a?0:s,this.formatEdited=!0,this.patchStyleCached(t,e,s===0?o:s),this.scheduleFlush()}patchStyleCached(t,e,s){const i=this.residentChunk(t,e);i!==null&&(i.hasStyles=!0,i.store[t&at]=s)}scheduleFlush(){this._flushQueued||(this._flushQueued=!0,queueMicrotask(()=>this.flush()))}flush(){if(this._flushQueued=!1,this._pendingEmpty.size>0){const t=[...this._pendingEmpty];this._pendingEmpty.clear(),this._writing++;try{for(const e of t)this.table.alive[e]===1&&this._isBlankRecord(e)&&this.table.removeRow(e)}finally{this._writing--}}this.view.refresh(),this.applyLayout(),this.notifyEngine(),this.onRefresh?.()}_isBlankRecord(t){for(const e of this.table.columns)if(!(e===null||e.computed||e.hidden)&&e.kind(t)!==K&&e.get(t)!==e.defaultValue)return!1;return!0}notifyEngine(){const t=this.book.engine;if(!t||t.deps.get(this)===void 0)return;const e=this.view.columns.length,s=new Uint32Array(e*2),i=new Uint16Array(e*2);for(let n=0;n<e;n++)s[n*2]=0,s[n*2+1]=Math.max(0,this.maxRow),i[n*2]=n,i[n*2+1]=n;t.cellsChanged(this,s,i,e*2)}_viewChanged(t){t.type==="layout"||t.type==="columns"?(this.applyLayout({keepCells:this._writing>0}),this._writing===0&&(this._forgetSheetUndo(),this.notifyEngine(),this.onRefresh?.())):this._writing===0&&this.scheduleFlush()}_forgetSheetUndo(){const{book:t}=this,e=t.sheets.indexOf(this),s=i=>i.sheetIndex!==e;t.undoStack=t.undoStack.filter(s),t.redoStack=t.redoStack.filter(s)}_restoreClosure(t){return()=>{const e=this.view.snapshot();this._writing++;try{this.view.restore(t)}finally{this._writing--}return this.applyLayout(),this.notifyEngine(),this.onRefresh?.(),this._restoreClosure(e)}}viewOp(t,e){this.captureWidths();const s=this.view.snapshot();this.book.transact(t,()=>{this._writing++;try{e(this.view)}finally{this._writing--}return this._restoreClosure(s)}),this.applyLayout(),this.notifyEngine(),this.onRefresh?.()}sortBy(t,e=!1,{add:s=!1}={}){this.viewOp("sort",i=>{const n=s?i.spec.sort.filter(r=>r.field!==t):[];i.setSort([...n,{field:t,desc:e}])})}clearSort(){this.viewOp("sort",t=>t.setSort([]))}filterBy(t,e){this.viewOp("filter",s=>s.setFilter(t,e))}clearFilters(){this.viewOp("filter",t=>t.setFilters([]))}groupBy(t){this.viewOp("group",e=>e.setGroups(t))}toggleRow(t){const e=t-this.bodyStart;let s=!1;return this.viewOp("outline",i=>{s=i.toggleRow(e)}),s}showLevel(t){this.viewOp("outline",e=>e.showLevel(t))}pinRow(t){const e=this.recordAtRow(t);e>=0&&this.viewOp("pin",s=>s.pinRecord(e))}unpinRow(t){const e=this.recordAtRow(t);e>=0&&this.viewOp("pin",s=>s.unpinRecord(e))}pinColumn(t,e=!0){this.viewOp("pin",s=>s.setColumn(t,{pinned:e}))}hideColumn(t){this.viewOp("hide",e=>e.setColumn(t,{hidden:!0}))}addColumn(t){this.viewOp("add column",e=>e.addColumn(t))}addRecord(t={},e={}){let s=-1;const i=e.atRow!==void 0?this._groupValuesAt(e.atRow):{};return this.book.transact("add row",()=>{this._writing++;try{s=this.table.addRow({...i,...this.newRecordValues?.()??{},...t});const n=e.before??(e.atRow!==void 0?this.recordAtRow(e.atRow):-1);n>=0&&!this.view.spec.groups.length&&this.view.moveRecords([s],n)}finally{this._writing--}return this._recordsClosure([s],!1)}),this.applyLayout(),this.notifyEngine(),this.onRefresh?.(),s}_groupValuesAt(t){const{view:e}=this,s=this.describeRow(t);if(!s||e.spec.groups.length===0)return{};const i={};let n=-1;if(s.kind==="group"||s.kind==="footer")n=s.node;else if(s.kind==="record")for(let r=t-this.bodyStart-1;r>=0;r--){const o=e.map[r];if(o<0&&(-o-1&1)===0){n=-o-1>>>1;break}}for(let r=n;r>0;r=e.nodeParent[r]){const o=e.spec.groups[e.nodeLevel[r]];if(o.by||o.size||o.bins||o.formula)continue;const l=this.table.column(o.field);l&&!l.computed&&(i[o.field]=l.get(e.perm[e.nodeStart[r]]))}return i}moveRecordsTo(t,e){const s=this.recordAtRow(e),i=this.table.ensureOrderColumn(),n=t.map(o=>i.data[o]),r=(o,l)=>()=>{const h=o.map(a=>i.data[a]);return o.forEach((a,u)=>{i.data[a]=l[u]}),this._writing++,this.view.invalidate(4),this.view.refresh(),this._writing--,this.applyLayout(),this.notifyEngine(),this.onRefresh?.(),r(o,h)};this.book.transact("move rows",()=>{this._writing++;try{this.view.moveRecords(t,s)}finally{this._writing--}return r(t,n)}),this.applyLayout(),this.notifyEngine(),this.onRefresh?.()}runRowAction(t,e){const s=this.rowOfRecord(e);switch(t){case"pin":this.view.isPinned(e)?this.viewOp("pin",i=>i.unpinRecord(e)):this.viewOp("pin",i=>i.pinRecord(e));return;case"remove":this.removeRecords([e]);return;case"save":this.table.saveRow(e).then(()=>this.onRefresh?.(),i=>this.onRejected?.(i.message));return;case"reset":this._writing++;try{this.table.resetRow(e)}finally{this._writing--}this._forgetSheetUndo(),this.view.refresh(),this.applyLayout(),this.notifyEngine(),this.onRefresh?.();return;default:this.view.spec.options.rowActions?.find(n=>typeof n=="object"&&n.name===t)?.run?.(e,this,s)}}removeRecords(t){const e=t.filter(s=>this.table.alive[s]===1);return e.length===0?0:(this.captureWidths(),this.book.transact("delete row",()=>(this._applyRecords(e,!0),this._recordsClosure(e,!0))),this.applyLayout(),this.notifyEngine(),this.onRefresh?.(),e.length)}_applyRecords(t,e){this._writing++;try{t.length===1?e?this.table.removeRow(t[0]):this.table.restoreRow(t[0]):this.table.batch(()=>{for(const s of t)e?this.table.removeRow(s):this.table.restoreRow(s)})}finally{this._writing--}}_recordsClosure(t,e){return()=>(this._applyRecords(t,!e),this.applyLayout(),this.notifyEngine(),this.onRefresh?.(),this._recordsClosure(t,!e))}recordsInRanges(t){const e=new Set;for(const{r0:s,r1:i}of t){const n=Math.min(i,this.bodyStart+this.view.count-1);for(let r=Math.max(s,1);r<=n;r++){const o=this.recordAtRow(r);o>=0&&e.add(o)}}return[...e]}acceptChanges(){this._writing++;try{this.table.acceptChanges()}finally{this._writing--}this.applyLayout(),this.onRefresh?.()}rejectChanges(){this._writing++;try{this.table.rejectChanges()}finally{this._writing--}this._forgetSheetUndo(),this.view.refresh(),this.applyLayout(),this.notifyEngine(),this.onRefresh?.()}structureOp(t){if(t.axis==="row"){if(t.n>0){const e=[],s=this.recordAtRow(t.at),i=this._groupValuesAt(t.at);this.book.transact("add row",()=>{this._writing++;try{this.table.batch(()=>{for(let n=0;n<t.n;n++)e.push(this.table.addRow({...i,...this.newRecordValues?.()??{}}))}),s>=0&&!this.view.spec.groups.length&&this.view.moveRecords(e,s)}finally{this._writing--}return this._recordsClosure(e,!1)}),this.applyLayout(),this.onRefresh?.()}else this.removeRecords(this.recordsInRanges([{r0:t.at,r1:t.at-t.n-1}]));return!0}if(t.n<0){const e=[];for(let s=t.at;s<t.at-t.n;s++){const i=this.view.columns[s];i&&e.push(i.field)}this.viewOp("hide",s=>{for(const i of e)s.setColumn(i,{hidden:!0})})}return!0}prepareSave(){this.captureWidths(),this.exporting=!0,this.view.columns[0]?.special==="actions"&&!this.cols.isHidden(0)&&(this.cols.setHidden(0,!0),this.colsChanged=!0,this.hidActions=!0),this.table.ensureAll(),this.view.refresh(),this.applyLayout();const{columns:t,blockCount:e}=this;for(let s=0;s<t.length;s++){const i=t[s];for(let n=0;n<e;n++)i[n]}}savePlanned(){this.hidActions&&(this.cols.setHidden(0,!1),this.hidActions=!1)}finishSave(){this.savePlanned(),this.exporting=!1,this.applyLayout()}}export{zt as ROW_ACTIONS,B as TableSheet};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{crossColumnsOf as B,fillGenerated as K,sliceColumnsOf as W}from"./cross.js";import{BOOL as H,EMPTY as k,ERR as Y,NUM as F,STR as R}from"../core/sheet.js";import{formatGeneral as X,getFormatter as V,partsToSerial as E,serialToParts as x}from"../core/numfmt.js";import{colName as J,MAX_ROWS as U}from"../core/address.js";import{sortByF64 as G,sortByU32 as j,sortColumn as Q}from"./sort.js";import{DataTable as O,keyIndex as Z}from"./data-core.js";import{XlError as tt}from"../calc/values.js";const C={NONE:0,FLATTEN:1,GROUP:2,SORT:3,FILTER:4},et=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wt=["sum","count","countAll","average","min","max","product","stdev","stdevp","var","varp","median","distinct"],vt={sum:"Sum",count:"Count",countAll:"Rows",average:"Average",min:"Min",max:"Max",product:"Product",stdev:"StdDev",stdevp:"StdDevP",var:"Var",varp:"VarP",median:"Median",distinct:"Distinct"},bt={equal:"filter|Equals",notEqual:"Does not equal",gt:"Greater than",gte:"Greater than or equal to",lt:"Less than",lte:"Less than or equal to",between:"Between",notBetween:"Not between",contains:"Contains",notContains:"Does not contain",beginsWith:"Begins with",endsWith:"Ends with",blank:"Is blank",notBlank:"Is not blank",top:"Top N",bottom:"Bottom N",aboveAverage:"Above average",belowAverage:"Below average",today:"Today",yesterday:"Yesterday",tomorrow:"Tomorrow",thisWeek:"This week",thisMonth:"This month",lastMonth:"Last month",thisYear:"This year",lastYear:"Last year"};function P(b,t,e,s,n){if(t==="countAll")return n-s;if(b.stale&&b.table.ensure(b),t==="count"||t==="distinct"){if(t==="count"){let y=0;if(b.isString){const{data:d}=b;for(let g=s;g<n;g++)d[e[g]]>=0&&y++}else if(b.kinds!==null){const{kinds:d}=b;for(let g=s;g<n;g++)d[e[g]]!==k&&y++}else{const{data:d}=b;for(let g=s;g<n;g++){const w=d[e[g]];w===w&&y++}}return y}const p=new Set;for(let y=s;y<n;y++){const d=e[y];b.kind(d)!==k&&p.add(b.raw(d))}return p.size}if(b.isString)return NaN;const{data:r,kinds:l}=b;let a=0,o=0,h=1/0,i=-1/0,u=1,c=0,f=0;const m=t==="stdev"||t==="stdevp"||t==="var"||t==="varp";if(t==="median"){const p=new Float64Array(n-s);let y=0;for(let g=s;g<n;g++){const w=e[g];if(l!==null&&l[w]!==F)continue;const _=r[w];_===_&&(p[y++]=_)}if(y===0)return NaN;const d=p.subarray(0,y).sort();return y%2===1?d[y>>1]:(d[(y>>1)-1]+d[y>>1])/2}for(let p=s;p<n;p++){const y=e[p];if(l!==null&&l[y]!==F)continue;const d=r[y];if(d===d&&(o++,a+=d,d<h&&(h=d),d>i&&(i=d),t==="product"&&(u*=d),m)){const g=d-f;f+=g/o,c+=g*(d-f)}}if(o===0)return NaN;switch(t){case"sum":return a;case"average":return a/o;case"min":return h;case"max":return i;case"product":return u;case"var":return o>1?c/(o-1):NaN;case"varp":return c/o;case"stdev":return o>1?Math.sqrt(c/(o-1)):NaN;case"stdevp":return Math.sqrt(c/o);default:return NaN}}const st=/\bCALCULATE\s*\(\s*(SUM|COUNT|COUNTA|AVERAGE|AVG|MIN|MAX|PRODUCT|STDEV|STDEVP|VAR|VARP|MEDIAN)\s*\(\s*\[@?\[?([^[\]@]+)\]?\]\s*\)\s*(?:,\s*REMOVEFILTERS\s*\(\s*(?:"([^"]*)"|\[@?([^\]]*)\])?\s*\))?\s*\)/gi,nt=/\b(SUM|COUNT|COUNTA|AVERAGE|AVG|MIN|MAX|PRODUCT|STDEV|STDEVP|VAR|VARP|MEDIAN)\s*\(\s*\[@?\[?([^[\]@]+)\]?\]\s*\)/gi,rt={SUM:"sum",COUNT:"count",COUNTA:"count",AVERAGE:"average",AVG:"average",MIN:"min",MAX:"max",PRODUCT:"product",STDEV:"stdev",STDEVP:"stdevp",VAR:"var",VARP:"varp",MEDIAN:"median"};function it(b,t){const e=Math.floor(t),s=x(e);switch(b){case"today":return[e,e+1];case"yesterday":return[e-1,e];case"tomorrow":return[e+1,e+2];case"thisWeek":return[e-s.weekday,e-s.weekday+7];case"thisMonth":return[E(s.year,s.month,1),s.month===12?E(s.year+1,1,1):E(s.year,s.month+1,1)];case"lastMonth":return[s.month===1?E(s.year-1,12,1):E(s.year,s.month-1,1),E(s.year,s.month,1)];case"thisYear":return[E(s.year,1,1),E(s.year+1,1,1)];case"lastYear":return[E(s.year-1,1,1),E(s.year,1,1)];default:return null}}const ot=()=>{const b=new Date;return E(b.getFullYear(),b.getMonth()+1,b.getDate())};function lt(b,t){const e=t.formula?M(b,t.formula):b.column(t.field);if(!e)return null;b.ensure(e);const s=b.rowCount,n=new Float64Array(s),{data:r,kinds:l}=e;if(e.isString){const{rank:a}=e.ranks();for(let o=0;o<s;o++){const h=r[o];n[o]=h<0?NaN:a[h]}return n}if(l!==null){const{rank:a}=e.ranks();for(let o=0;o<s;o++)switch(l[o]){case F:n[o]=r[o];break;case R:n[o]=1e300+a[r[o]]*1e290;break;case H:n[o]=15e307+r[o]*1e300;break;case Y:n[o]=17e307;break;default:n[o]=NaN}return n}if(t.by&&t.by!=="value"){const a=new Map;for(let o=0;o<s;o++){const h=r[o];if(h!==h){n[o]=NaN;continue}const i=Math.floor(h);let u=a.get(i);if(u===void 0){const c=x(i);switch(t.by){case"year":u=c.year;break;case"quarter":u=c.year*4+Math.floor((c.month-1)/3);break;case"month":u=c.year*12+c.month-1;break;case"week":u=Math.floor((i-1)/7);break;default:u=i}a.set(i,u)}n[o]=u}return n}if(t.size>0){for(let a=0;a<s;a++){const o=r[a];n[a]=o!==o?NaN:Math.floor(o/t.size)}return n}if(t.bins){const{bins:a}=t;for(let o=0;o<s;o++){const h=r[o];let i=NaN;if(h===h)for(let u=0;u<a.length;u++){const c=a[u];if((c.min===void 0||h>=c.min)&&(c.max===void 0||h<c.max)){i=u;break}}n[o]=i}return n}return n.set(r.subarray(0,s)),n}function M(b,t){const e=`__formula:${t}`;let s=b.byName.get(e);return s||(s=b.addHelper({name:e,formula:t,type:"any",hidden:!0,readOnly:!0}),b.manager.formulas.bind(s)),b.ensure(s),s}const D={type:"number",caption:"",computed:!0,stale:!1,isString:!1,kinds:null,data:new Float64Array(0),styles:null,table:null,validator:null,required:!1,kind:()=>k,raw:()=>0,get:()=>null},$=b=>typeof b=="string"?{field:b}:{...b};class at{constructor(t,e={}){this.table=t,this.spec={columns:(e.columns??t.fields.map(s=>s.name)).map($),sort:e.sort??[],filters:e.filters??[],groups:e.groups??[],hierarchy:e.hierarchy??null,pinnedRows:e.pinnedRows??[],totals:e.totals??[],search:e.search??"",rules:e.rules??[],groupLayout:e.groupLayout??"outline",options:e.options??{}},this.name=e.name??null,this.listeners=new Set,this.hooks=null,this.dirty=C.FILTER,this.needsFilter=!1,this.revision=0,this.count=0,this.map=new Int32Array(0),this.filtered=new Int32Array(0),this.filteredCount=0,this.perm=new Int32Array(0),this.inverse=null,this.truncated=!1,this.nodeCount=0,this.nodeStart=new Int32Array(0),this.nodeEnd=new Int32Array(0),this.nodeLevel=new Int8Array(0),this.nodeChild=new Int32Array(0),this.nodeChildEnd=new Int32Array(0),this.nodeParent=new Int32Array(0),this.nodeCollapsed=new Uint8Array(0),this.levelStart=[],this.summaryValues=new Map,this.summariesStale=!1,this.collapsedPaths=new Set,this.collapseFromLevel=1/0,this.treeLevel=null,this.treeHasKids=null,this.treeCollapsed=new Set,this.treeParent=null,this.rollups=new Map,this.pinned=new Int32Array(0),this._columns=null,this._unsubscribe=t.onChange(s=>this._tableChanged(s)),this.refresh()}dispose(){if(this._unsubscribe(),this._crossSources)for(const t of this._crossSources.values())t()}fetch(t=!1){return this.table.fetch(t).then(()=>this)}length(){return this.spec.columns.length}visibleLength(){return this.columns.length}on(t,e){return this.hooks===null&&(this.hooks=new Map),this.hooks.has(t)||this.hooks.set(t,new Set),this.hooks.get(t).add(e),()=>this.hooks.get(t).delete(e)}_fire(t,e){const s=this.hooks?.get(t);if(!s)return!0;let n=!0;for(const r of s)r(e)===!1&&(n=!1);return n}addStyleRule(t,e){this.spec.rules=[...this.spec.rules.filter(s=>s.name!==t),{name:t,...e}],this._rulesChanged()}removeStyleRule(t){this.spec.rules=this.spec.rules.filter(e=>e.name!==t),this._rulesChanged()}clearStyleRules(){this.spec.rules=[],this._rulesChanged()}getStyleRule(t){return t===void 0?this.spec.rules:this.spec.rules.find(e=>e.name===t)}_rulesChanged(){this.revision++,this._emit({type:"columns"})}moveRecords(t,e=-1){const s=this.table.ensureOrderColumn().data,n=new Set(t),r=this.spec.hierarchy?this.perm.subarray(0,this.filteredCount):this.map.subarray(0,this.count).filter(h=>h>=0);let l=1/0,a=-1/0;if(e>=0){l=s[e];for(const h of r)if(!n.has(h)){if(h===e)break;a=s[h]}}else for(const h of r)!n.has(h)&&s[h]>a&&(a=s[h]);a===-1/0&&(a=l===1/0?0:l-t.length-1),l===1/0&&(l=a+t.length+1);const o=(l-a)/(t.length+1);t.forEach((h,i)=>{s[h]=a+o*(i+1)}),this.invalidate(C.FILTER),this.refresh()}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(t){for(const e of this.listeners)e(t)}get columns(){if(this._columns!==null)return this._columns;const t=[];for(const r of this.spec.columns){if(r.hidden)continue;if(r.special){t.push({def:r,col:D,field:r.field??r.special,special:r.special,caption:r.caption??(r.special==="rowNumber"?"#":""),format:"General",width:r.width??(r.special==="rowNumber"?44:72),pinned:r.pinned===!0,readOnly:!0,align:r.align??null,allowSort:!1,allowFilter:!1});continue}if(r.cross){t.push(...B(this,r,M));continue}const l=this.table.column(r.field);l&&t.push({def:r,col:l,field:r.field,caption:r.caption??l.caption,format:r.format??l.format,width:r.width??l.width??null,pinned:r.pinned===!0,readOnly:r.readOnly===!0||l.readOnly||l.computed,align:r.align??null,allowSort:r.allowSort!==!1,allowFilter:r.allowFilter!==!1,showNullAs:r.showNullAs??l.showNullAs,showEmptyAs:r.showEmptyAs??null,display:r.display??null,style:r.style??null,headerStyle:r.headerStyle??null,headerFit:r.headerFit??"normal",captionPath:r.captionPath??null,cellType:r.cellType??null,validator:r.validator??l.validator,conditionalFormats:r.conditionalFormats??null,sparkline:r.sparkline??null})}this.spec.groups.some(r=>r.summaries?.some(l=>l.slice||l.own))&&t.push(...W(this,M));const e=t.filter(r=>r.pinned),s=e.length>0?[...e,...t.filter(r=>!r.pinned)]:t,n=s.findIndex(r=>r.special==="actions");if(n>0&&s.unshift(...s.splice(n,1)),this._columns=s,this._generated=s.filter(r=>r.fill),this._generated.length>0){const r=this._sourceStamp();(r!==this._crossStamp||this._generated.some(l=>!this._filled?.has(l.col)))&&(K(this,this._generated),this._crossStamp=r,this._filled=new Set(this._generated.map(l=>l.col)))}return this._columns}_useCrossSource(t){t!==this.table&&(this._crossSources||(this._crossSources=new Map),this._crossSources.has(t)||this._crossSources.set(t,t.onChange(()=>this._sourceChanged())))}_sourceStamp(){let t=`${this.table.revision}`;if(this._crossSources)for(const e of this._crossSources.keys())t+=`|${e.revision}`;return t}_syncGenerated(){if(!this._generated||this._generated.length===0||this._sourceStamp()===this._crossStamp)return!1;const e=this._generated.map(n=>n.field).join(`
|
|
2
|
+
`);this._columns=null;const s=this.columns;return this.summariesStale=!0,e!==s.filter(n=>n.fill).map(n=>n.field).join(`
|
|
3
|
+
`)}_sourceChanged(){this._syncGenerated()?this._columnsChanged():this._emit({type:"cells"})}get pinnedColumnCount(){return this.columns.reduce((t,e)=>t+(e.pinned?1:0),0)}columnIndex(t){return this.columns.findIndex(e=>e.field===t)}addColumn(t){const e=$(t);e.formula&&(this.table.byName.has(e.field)||this.table.addField({name:e.field,caption:e.caption,formula:e.formula,type:e.type??"any",format:e.format,readOnly:!0}),delete e.formula,delete e.type),this.spec.columns=[...this.spec.columns,e],this._columnsChanged()}removeColumn(t){this.spec.columns=this.spec.columns.filter(e=>e.field!==t),this._columnsChanged()}setColumn(t,e){this.spec.columns=this.spec.columns.map(s=>s.field===t?{...s,...e}:s),this._columnsChanged()}moveColumn(t,e){const s=[...this.spec.columns],n=s.findIndex(l=>l.field===t);if(n<0)return;const[r]=s.splice(n,1);s.splice(Math.max(0,Math.min(s.length,e)),0,r),this.spec.columns=s,this._columnsChanged()}_columnsChanged(){this._columns=null,this.revision++,this._emit({type:"columns"})}setSort(t){this._fire("beforeSort",{sort:t})&&(this.spec.sort=t??[],this.invalidate(C.SORT),this.refresh(),this._fire("afterSort",{sort:this.spec.sort}))}setFilter(t,e){if(!this._fire("beforeFilter",{field:t,condition:e}))return;const s=this.spec.filters.filter(n=>n.field!==t);this.spec.filters=e?[...s,{...e,field:t}]:s,this.invalidate(C.FILTER),this.refresh(),this._fire("afterFilter",{field:t,condition:e})}setFilters(t){this.spec.filters=t??[],this.invalidate(C.FILTER),this.refresh()}setSearch(t){this.spec.search=t??"",this.invalidate(C.FILTER),this.refresh()}setGroups(t){this.spec.groups=t??[],this._columns=null,this.invalidate(C.SORT),this.refresh()}setTotals(t){this.spec.totals=t??[],this.invalidate(C.GROUP),this.refresh()}setHierarchy(t){this.spec.hierarchy=t??null,this.invalidate(C.FILTER),this.refresh()}pinRecord(t){this.spec.pinnedRows.includes(t)||(this.spec.pinnedRows=[...this.spec.pinnedRows,t]),this.invalidate(C.FLATTEN),this.refresh()}unpinRecord(t){this.spec.pinnedRows=this.spec.pinnedRows.filter(e=>e!==t),this.invalidate(C.FLATTEN),this.refresh()}isPinned(t){return this.spec.pinnedRows.includes(t)}invalidate(t){t>this.dirty&&(this.dirty=t)}snapshot(){return{spec:{...this.spec},collapsedPaths:new Set(this.collapsedPaths),collapseFromLevel:this.collapseFromLevel,treeCollapsed:new Set(this.treeCollapsed)}}restore(t){this.spec={...t.spec},this.collapsedPaths=new Set(t.collapsedPaths),this.collapseFromLevel=t.collapseFromLevel,this.treeCollapsed=new Set(t.treeCollapsed),this._columns=null,this.invalidate(C.FILTER),this.refresh()}toJSON(){const{spec:t}=this;return{name:this.name,columns:t.columns,sort:t.sort,filters:t.filters.filter(e=>!e.fn),groups:t.groups.map(e=>({...e,summaries:e.summaries?.filter(s=>!s.fn)})),hierarchy:t.hierarchy,pinnedRows:t.pinnedRows,totals:t.totals,search:t.search,rules:t.rules,groupLayout:t.groupLayout,options:t.options,collapsedPaths:[...this.collapsedPaths],collapseFromLevel:this.collapseFromLevel===1/0?null:this.collapseFromLevel,treeCollapsed:[...this.treeCollapsed]}}applySavedState(t){this.collapsedPaths=new Set(t.collapsedPaths??[]),this.collapseFromLevel=t.collapseFromLevel??1/0,this.treeCollapsed=new Set(t.treeCollapsed??[]),this.invalidate(C.FILTER),this.refresh()}_tableChanged(t){if(this._generated?.length>0&&t.type!=="schema"&&this._syncGenerated()){this._columnsChanged();return}switch(t.type){case"cell":this.summariesStale=!0,this.revision++,this._emit({type:"cell",row:t.row,col:t.col});return;case"cells":this.revision++,this._emit({type:"cells"});return;case"rows":{if(this.spec.groups.length===0&&!this.spec.hierarchy&&this.spec.totals.length===0&&this.dirty===C.NONE){this.needsFilter=!0,t.added?this._appendToMap(t.row):this._removeFromMap(t.row),this.revision++,this._emit({type:"layout"});return}this.invalidate(C.FILTER),this.refresh();return}case"schema":this._columns=null,this.invalidate(C.FILTER),this.refresh();return;default:this.invalidate(C.FILTER),this.refresh()}}_appendToMap(t){if(!(this.count>=U-2)){if(this.count===this.map.length){const e=new Int32Array(Math.max(1024,this.map.length*2));e.set(this.map),this.map=e}this.map[this.count++]=t,this.inverse!==null&&(this.inverse=null)}}_removeFromMap(t){const e=this.map.subarray(0,this.count).indexOf(t);e>=0&&(this.map.copyWithin(e,e+1,this.count),this.count--),this.inverse=null,this.spec.pinnedRows.includes(t)&&(this.spec.pinnedRows=this.spec.pinnedRows.filter(s=>s!==t),this.pinned=Int32Array.from(this.spec.pinnedRows))}refresh(){this._columns===null&&this.columns;const t=this.needsFilter&&this.dirty>C.NONE?C.FILTER:this.dirty;if(t===C.NONE){this.summariesStale&&this._computeSummaries();return}t>=C.FILTER&&this._filter(),t>=C.SORT&&this._sort(),t>=C.GROUP&&this._group(),this._flatten(),this.dirty=C.NONE,this.needsFilter=!1,this.revision++,this._emit({type:"layout"})}_filter(){const t=this.table;t.ensureAll();const e=t.rowCount,s=new Uint8Array(e),{alive:n}=t;s.set(n.subarray(0,e));for(const o of this.spec.filters)this._applyCondition(o,s,e);this.spec.search&&this._applySearch(this.spec.search,s,e),this.spec.hierarchy&&this._buildTreeLinks(s,e);let r=0;for(let o=0;o<e;o++)r+=s[o];const l=new Int32Array(r);let a=0;for(let o=0;o<e;o++)s[o]!==0&&(l[a++]=o);this.filtered=l,this.filteredCount=r}_applyCondition(t,e,s){if(t.fn){for(let l=0;l<s;l++)e[l]!==0&&!t.fn(l,this.table)&&(e[l]=0);return}if(t.formula){const l=M(this.table,t.formula);for(let a=0;a<s;a++){if(e[a]===0)continue;const o=l.get(a);o===!0||typeof o=="number"&&o!==0||(e[a]=0)}return}const n=this.table.column(t.field);if(!n)return;this.table.ensure(n);const{op:r}=t;if(r==="in"||r==="notIn"){this._applyIn(n,t,e,s);return}if(r==="blank"||r==="notBlank"){const l=r==="blank";for(let a=0;a<s;a++)e[a]!==0&&(n.kind(a)===k||n.isString&&n.get(a)==="")!==l&&(e[a]=0);return}if(r==="contains"||r==="notContains"||r==="beginsWith"||r==="endsWith"){this._applyText(n,r,String(t.value??"").toLowerCase(),e,s);return}if(n.isString){this._applyStringCompare(n,t,e,s);return}if(n.kinds!==null){this._applyMixedCompare(n,t,e,s);return}this._applyNumeric(n,t,e,s)}_applyIn(t,e,s,n){const r=e.op==="in",l=new Set,a=new Set;let o=!1;for(const u of e.values??[])u===null||u===""?o=!0:typeof u=="number"?l.add(u):typeof u=="boolean"?l.add(u?1:0):a.add(String(u).toLowerCase());const{strings:h}=this.table.manager,{data:i}=t;if(t.isString||t.kinds!==null){const u=new Int8Array(h.size),c=f=>{let m=u[f];return m===0&&(m=a.has(h.get(f).toLowerCase())?1:-1,u[f]=m),m>0};for(let f=0;f<n;f++){if(s[f]===0)continue;const m=t.kind(f);let p;m===k?p=o:m===R?p=c(i[f]):p=l.has(i[f]),p!==r&&(s[f]=0)}return}for(let u=0;u<n;u++){if(s[u]===0)continue;const c=i[u];(c!==c?o:l.has(c))!==r&&(s[u]=0)}}_applyText(t,e,s,n,r){const{strings:l}=this.table.manager,a=e==="beginsWith"?h=>h.startsWith(s):e==="endsWith"?h=>h.endsWith(s):h=>h.includes(s),o=e==="notContains";if(t.isString){const h=new Int8Array(l.size),{data:i}=t;for(let u=0;u<r;u++){if(n[u]===0)continue;const c=i[u];if(c<0){o||(n[u]=0);continue}let f=h[c];f===0&&(f=a(l.get(c).toLowerCase())?1:-1,h[c]=f),f>0===o&&(n[u]=0)}return}for(let h=0;h<r;h++){if(n[h]===0)continue;const i=t.get(h);(i!==null&&a((typeof i=="number"?T(i):String(i)).toLowerCase()))===o&&(n[h]=0)}}_applyStringCompare(t,e,s,n){const{rank:r}=t.ranks(),{strings:l}=this.table.manager,{data:a}=t,o=String(e.value??"").toLowerCase();if(e.op==="equal"||e.op==="notEqual"){const c=e.op==="equal",f=new Int8Array(l.size);for(let m=0;m<n;m++){if(s[m]===0)continue;const p=a[m];let y=!1;if(p>=0){let d=f[p];d===0&&(d=l.get(p).toLowerCase()===o?1:-1,f[p]=d),y=d>0}else y=o==="";y!==c&&(s[m]=0)}return}const h=c=>{const f=String(c??"").toLowerCase();let m=-1;const p=new Int8Array(l.size);for(let y=0;y<n;y++){const d=a[y];d<0||p[d]||(p[d]=1,l.get(d).toLowerCase()<=f&&r[d]>m&&(m=r[d]))}return m+.5},i=h(e.value),u=e.value2!==void 0?h(e.value2):i;for(let c=0;c<n;c++){if(s[c]===0)continue;const f=a[c];if(f<0){s[c]=0;continue}const m=r[f];let p;switch(e.op){case"gt":p=m>i;break;case"gte":p=m>i-1;break;case"lt":p=m<i-1;break;case"lte":p=m<i;break;case"between":p=m>i-1&&m<u;break;case"notBetween":p=!(m>i-1&&m<u);break;default:p=!0}p||(s[c]=0)}}_applyMixedCompare(t,e,s,n){const r=e.value;for(let l=0;l<n;l++){if(s[l]===0)continue;const a=t.get(l);let o;if(e.op==="equal"||e.op==="notEqual"){const h=a===r||typeof a=="string"&&typeof r=="string"&&a.toLowerCase()===r.toLowerCase();o=e.op==="equal"?h:!h}else typeof a!="number"?o=!1:o=ut(e.op,a,Number(r),Number(e.value2));o||(s[l]=0)}}_applyNumeric(t,e,s,n){const{data:r}=t,{op:l}=e,a=it(l,e.now??ot());if(a!==null){const[i,u]=a;for(let c=0;c<n;c++){if(s[c]===0)continue;const f=r[c];f>=i&&f<u||(s[c]=0)}return}if(l==="top"||l==="bottom"){const i=new Float64Array(n);let u=0;for(let p=0;p<n;p++){if(s[p]===0)continue;const y=r[p];y===y&&(i[u++]=y)}const c=i.subarray(0,u).sort(),f=Math.max(0,Math.min(u,e.percent?Math.floor(u*Number(e.value)/100):Number(e.value)));if(f===0){s.fill(0);return}const m=l==="top"?c[u-f]:c[f-1];for(let p=0;p<n;p++){if(s[p]===0)continue;const y=r[p];(l==="top"?y>=m:y<=m)||(s[p]=0)}return}if(l==="aboveAverage"||l==="belowAverage"){let i=0,u=0;for(let f=0;f<n;f++){if(s[f]===0)continue;const m=r[f];m===m&&(i+=m,u++)}const c=u>0?i/u:0;for(let f=0;f<n;f++){if(s[f]===0)continue;const m=r[f];(l==="aboveAverage"?m>c:m<c)||(s[f]=0)}return}const o=q(e.value),h=q(e.value2);switch(l){case"gt":for(let i=0;i<n;i++)r[i]>o||(s[i]=0);return;case"gte":for(let i=0;i<n;i++)r[i]>=o||(s[i]=0);return;case"lt":for(let i=0;i<n;i++)r[i]<o||(s[i]=0);return;case"lte":for(let i=0;i<n;i++)r[i]<=o||(s[i]=0);return;case"equal":for(let i=0;i<n;i++)r[i]!==o&&(s[i]=0);return;case"notEqual":for(let i=0;i<n;i++)r[i]===o&&(s[i]=0);return;case"between":for(let i=0;i<n;i++)r[i]>=o&&r[i]<=h||(s[i]=0);return;case"notBetween":for(let i=0;i<n;i++)r[i]>=o&&r[i]<=h&&(s[i]=0);return;default:}}_applySearch(t,e,s){const n=t.toLowerCase(),{strings:r}=this.table.manager,l=ht(n),a=this.columns.map(i=>i.col).filter(i=>l||i.isString||i.kinds!==null),o=new Int8Array(r.size),h=i=>{let u=o[i];return u===0&&(u=r.get(i).toLowerCase().includes(n)?1:-1,o[i]=u),u>0};for(let i=0;i<s;i++){if(e[i]===0)continue;let u=!1;for(let c=0;c<a.length&&!u;c++){const f=a[c],m=f.kind(i);if(f!==D){if(m===R)u=h(f.data[i]);else if(m===F){const p=T(f.data[i]);u=(p.includes("E")?p.toLowerCase():p).includes(n)}}}u||(e[i]=0)}}_sortColumn(t,e,s,n){Q(this.table,t,e,s,n)}_groupKeys(t){return lt(this.table,this.spec.groups[t])}_sort(){const t=this.filteredCount,e=this.perm.length===t?this.perm:new Int32Array(t);e.set(this.filtered.subarray(0,t)),this.perm=e;const{sort:s,groups:n,hierarchy:r}=this.spec,l=this.table.byName.get("__order");l&&G(e,t,l.data,!1);for(let a=s.length-1;a>=0;a--){const o=this.table.column(s[a].field);o&&this._sortColumn(e,t,o,s[a].desc===!0)}if(this._keys=[],!r)for(let a=n.length-1;a>=0;a--){const o=this._groupKeys(a);o!==null&&(this._keys[a]=o,G(e,t,o,n[a].desc===!0))}}_group(){const{groups:t,hierarchy:e}=this.spec,s=this.filteredCount;if(e||t.length===0&&this.spec.totals.length===0){this.nodeCount=0,this.summaryValues.clear(),e&&this._computeRollups();return}(this._keys===void 0||this._keys.length===0&&t.length>0)&&this._sort();const n=t.length;let r=16,l=new Int32Array(r),a=new Int32Array(r),o=new Int32Array(r),h=new Int8Array(r),i=new Int32Array(r),u=new Int32Array(r);const c=()=>{const d=(g,w)=>{const _=new g(r*2);return _.set(w),_};l=d(Int32Array,l),a=d(Int32Array,a),o=d(Int32Array,o),h=d(Int8Array,h),i=d(Int32Array,i),u=d(Int32Array,u),r*=2};l[0]=0,a[0]=s,h[0]=-1,o[0]=-1;let f=1,m=0,p=1;this.levelStart=[];const{perm:y}=this;for(let d=0;d<n;d++){const g=this._keys[d];this.levelStart[d]=f;for(let w=m;w<p;w++){if(i[w]=f,g){let _=l[w];const A=a[w];for(;_<A;){const v=g[y[_]];let S=_+1;if(v===v)for(;S<A&&g[y[S]]===v;)S++;else for(;S<A&&g[y[S]]!==g[y[S]];)S++;f===r&&c(),l[f]=_,a[f]=S,o[f]=w,h[f]=d,f++,_=S}}u[w]=f}m=p,p=f}for(let d=m;d<p;d++)i[d]=0,u[d]=0;this.nodeCount=f,this.nodeStart=l,this.nodeEnd=a,this.nodeParent=o,this.nodeLevel=h,this.nodeChild=i,this.nodeChildEnd=u,this._applyCollapse(),this._computeSummaries()}_nodePath(t){const e=[];for(let s=t;s>0;s=this.nodeParent[s]){const n=this.spec.groups[this.nodeLevel[s]],r=this.groupKeyValue(s,n);e.push(r===null?"":String(r).toLowerCase())}return e.reverse().join("")}groupKeyValue(t,e=this.spec.groups[this.nodeLevel[t]]){const s=e.formula?M(this.table,e.formula):this.table.column(e.field),n=this.perm[this.nodeStart[t]],r=s.get(n);if(typeof r=="number"){if(e.by&&e.by!=="value")return this._keys[this.nodeLevel[t]][n];if(e.size>0)return Math.floor(r/e.size)*e.size;if(e.bins)return e.bins[this._keys[this.nodeLevel[t]][n]]?.name??"(other)"}return r instanceof tt?r.code:r}_applyCollapse(){const t=new Uint8Array(this.nodeCount),e=this.collapsedPaths.size>0,s=this.collapseFromLevel;if(e||s!==1/0)for(let n=1;n<this.nodeCount;n++){let r=this.nodeLevel[n]>=s;e&&this.collapsedPaths.has(this._nodePath(n))&&(r=!r),t[n]=r?1:0}this.nodeCollapsed=t}_computeSummaries(){if(this.summariesStale=!1,this.summaryValues.clear(),this.spec.hierarchy){this._computeRollups();return}if(this.nodeCount===0)return;const{groups:t,totals:e}=this.spec,s=this._generated??[],n=(l,a)=>{const o=s.filter(i=>i.sliceLevel===void 0?!0:i.sliceLevel===l).map(i=>({field:i.field,agg:i.summaryAgg??"sum"})),h=(a??[]).filter(i=>!i.slice&&!i.own);return o.length>0?[...h,...o]:h},r=(l,a,o,h)=>{if(!a||a.length===0)return;const i=a.length,u=new Float64Array((h-o)*i),{perm:c,nodeStart:f,nodeEnd:m}=this;a.forEach((p,y)=>{const d=p.field?this.table.column(p.field):null;if(p.where&&d){const g=M(this.table,p.where),w=new Int32Array(c.length);for(let _=o;_<h;_++){let A=0;for(let v=f[_];v<m[_];v++){const S=g.get(c[v]);(S===!0||typeof S=="number"&&S!==0)&&(w[A++]=c[v])}u[(_-o)*i+y]=P(d,p.agg??"sum",w,0,A)}}else if(p.formula){const g=this._summaryFormula(p.formula);for(let w=o;w<h;w++)u[(w-o)*i+y]=g(c,f[w],m[w],w)}else if(p.fn)for(let g=o;g<h;g++)u[(g-o)*i+y]=p.fn(c.subarray(f[g],m[g]),this.table);else if(d)for(let g=o;g<h;g++)u[(g-o)*i+y]=P(d,p.agg??"sum",c,f[g],m[g]);else u.fill(NaN)}),this.summaryValues.set(l,{values:u,per:i,list:a,first:o})};r(-1,e?.length>0?n(-1,e):e,0,1);for(let l=0;l<t.length;l++){const a=this.levelStart[l],o=l+1<t.length?this.levelStart[l+1]:this.nodeCount;r(l,n(l,t[l].summaries),a,o)}}_summaryFormula(t){const e=[],s=(i,u,c)=>(e.push({agg:rt[i.toUpperCase()],col:this.table.column(u.trim()),scope:c}),`$${J(e.length-1)}$1`),n=String(t).replace(/^=/,"").replace(st,(i,u,c,f,m)=>{if(!/REMOVEFILTERS/i.test(i))return s(u,c,null);const p=f??m,y=p?this.spec.groups.findIndex(d=>d.field===p.trim()):0;return s(u,c,{up:Math.max(0,y)})}).replace(nt,(i,u,c)=>s(u,c,null)),r=this.table.manager.formulas._engineFor(),l=r.template(n,0,0),a=e.map(()=>({kinds:new Uint8Array(1024),values:new Float64Array(1024),styles:null})),o=this.table.manager.formulas._sheet(this.table),h=(i,u)=>{let c=i;for(;c>0&&this.nodeLevel[c]>=u;)c=this.nodeParent[c];return c};return(i,u,c,f=0)=>{o.columns.length=0,e.forEach((p,y)=>{let d=u,g=c;if(p.scope){const _=h(f,p.scope.up);d=this.nodeStart[_],g=this.nodeEnd[_]}const w=p.col?P(p.col,p.agg,i,d,g):NaN;a[y].kinds[0]=w===w?F:k,a[y].values[0]=w,o.columns[y]=[a[y]]});let m;try{m=l.fn(0,0,o),m&&m.isCell&&(m=r.read(m.sheet,m.r0,m.c0))}catch{m=NaN}return o.columns.length=0,typeof m=="number"?m:NaN}}summaryFor(t,e){const s=this.nodeLevel[t],n=this.summaryValues.get(s);if(!n)return;const r=n.list.findIndex(l=>l.field===e||l.column===e);if(!(r<0))return n.values[(t-n.first)*n.per+r]}_buildTreeLinks(t,e){const s=this.spec.hierarchy,n=this.table,r=new Int32Array(e).fill(-1);if(s.level){const l=n.column(s.level);n.ensure(l);const{data:a}=l,o=[];for(let h=0;h<e;h++){if(!n.alive[h])continue;const i=a[h]===a[h]?a[h]:0;o.length=Math.min(o.length,i),r[h]=o.length>0?o[o.length-1]:-1,o[i]=h}}else{const l=n.column(s.key??n.key),a=n.column(s.parent);if(n.ensure(l),n.ensure(a),l.isString===a.isString&&l.kinds===null&&a.kinds===null){const o=Z(l,n),{data:h}=a;for(let i=0;i<e;i++){const u=h[i];u===u&&u!==-1&&(r[i]=o(u))}}else{const o=new Map;for(let h=e-1;h>=0;h--)n.alive[h]&&o.set(String(l.get(h)),h);for(let h=0;h<e;h++){const i=a.get(h);i!==null&&(r[h]=o.get(String(i))??-1)}}}if(this.treeParent=r,this.spec.filters.length>0||this.spec.search){for(let l=0;l<e;l++)if(t[l]!==0)for(let a=r[l];a>=0&&t[a]===0;a=r[a])t[a]=1}}_flattenTree(t,e){const s=this.filteredCount,n=this.table.rowCount,r=this.treeParent,{perm:l}=this,a=new Int32Array(n).fill(-1),o=new Int32Array(n).fill(-1),h=new Uint16Array(n),i=new Uint8Array(n),u=new Uint8Array(n);for(let w=0;w<s;w++)u[l[w]]=1;const c=[];for(let w=s-1;w>=0;w--){const _=l[w],A=r[_];A>=0&&u[A]===1&&A!==_?(o[_]=a[A],a[A]=_,i[A]=1):c.push(_)}const f=new Uint8Array(n),m=this.treeCollapsed;let p=0;const y=new Int32Array(Math.max(16,s+1));let d=0;const g=w=>{for(y[d++]=w;d>0;){const _=y[--d];if(f[_]===1)continue;f[_]=1,(!e||e[_]===0)&&(p<t.length&&(t[p]=_),p++);const A=h[_];if(a[_]>=0&&!m.has(_)){let v=a[_];const S=d;let L=0;for(;v>=0;)h[v]=A+1,y[d++]=v,L++,v=o[v];for(let I=S,N=S+L-1;I<N;I++,N--){const z=y[I];y[I]=y[N],y[N]=z}}}};for(let w=c.length-1;w>=0;w--)g(c[w]);if(!m.size)for(let w=0;w<s;w++)f[l[w]]===0&&g(l[w]);return this.treeLevel=h,this.treeHasKids=i,p}_computeRollups(){this.rollups.clear();const t=this.spec.hierarchy?.rollups;if(!t||t.length===0||!this.treeParent)return;const e=this.filteredCount,{perm:s,treeParent:n}=this,r=this.table.rowCount,l=new Int32Array(r).fill(-1),a=i=>{const u=[];let c=i;for(;c>=0&&l[c]<0&&u.length<r;)u.push(c),l[c]=0,c=n[c];let f=c>=0?l[c]+1:0;for(let m=u.length-1;m>=0;m--)l[u[m]]=f++};for(let i=0;i<e;i++)a(s[i]);const o=s.slice(0,e),h=new Uint32Array(e);for(let i=0;i<e;i++)h[i]=l[o[i]];j(o,e,h);for(const i of t){const u=this.table.column(i.field);if(!u)continue;this.table.ensure(u);const c=i.agg??"sum",f=new Float64Array(r).fill(NaN),m=new Float64Array(r),p=new Uint8Array(r);for(let y=0;y<e;y++){const d=o[y],g=u.isString?u.data[d]>=0?1:NaN:u.kinds!==null&&u.kinds[d]!==F?NaN:u.data[d];g===g&&(f[d]=c==="count"?1:g,m[d]=1)}for(let y=e-1;y>=0;y--){const d=o[y],g=n[d];if(g<0||l[g]<0||m[d]===0)continue;p[g]===0&&(p[g]=1,f[g]=NaN,m[g]=0);const w=f[d],_=f[g];c==="min"?f[g]=_!==_||w<_?w:_:c==="max"?f[g]=_!==_||w>_?w:_:f[g]=(_!==_?0:_)+w,m[g]+=m[d]}if(c==="average")for(let y=0;y<e;y++){const d=o[y];p[d]===1&&m[d]>0&&(f[d]/=m[d])}this.rollups.set(i.field,{values:f,touched:p})}}_flatten(){const t=this.spec.pinnedRows.filter(v=>v<this.table.rowCount&&this.table.alive[v]===1);this.pinned=Int32Array.from(t);let e=null;if(t.length>0){e=new Uint8Array(this.table.rowCount);for(const v of t)e[v]=1}const s=U-2-t.length;if(this.spec.hierarchy){const v=this.map.length>=this.filteredCount?this.map:new Int32Array(this.filteredCount);this.count=this._flattenTree(v,e),this.map=v,this.truncated=this.count>s,this.truncated&&(this.count=s),this.inverse=null;return}const n=this.spec.groups,r=this.filteredCount,{perm:l}=this;if(n.length===0&&this.spec.totals.length===0){const v=Math.min(r,s),S=this.map.length>=v?this.map:new Int32Array(v);if(e===null)S.set(l.subarray(0,v)),this.count=v;else{let L=0;for(let I=0;I<r&&L<v;I++){const N=l[I];e[N]===0&&(S[L++]=N)}this.count=L}this.map=S,this.truncated=r>s,this.inverse=null;return}this.groupStartOf=null,this.groupStartNode=null;const a=n.map(v=>v.footer===!0),o=this.spec.totals.length>0;let h=r+(o?1:0);for(let v=1;v<this.nodeCount;v++)h+=a[this.nodeLevel[v]]?2:1;const i=Math.min(h,s),u=this.map.length>=i?this.map:new Int32Array(i);let c=0;const f=n.length-1,{nodeChild:m,nodeChildEnd:p,nodeLevel:y,nodeCollapsed:d,nodeStart:g,nodeEnd:w}=this,_=this.spec.groupLayout==="tabular",A=v=>{if(c>=i)return;const S=y[v];if((!_||d[v]===1)&&(u[c++]=-(1+v*2)),d[v]!==1){if(S===f){const L=g[v],I=w[v];if(_&&this._markGroupStart(L,S,v),e===null){const N=Math.min(I-L,i-c);u.set(l.subarray(L,L+N),c),c+=N}else for(let N=L;N<I&&c<i;N++)e[l[N]]===0&&(u[c++]=l[N])}else for(let L=m[v];L<p[v];L++)A(L);a[S]&&c<i&&(u[c++]=-(2+v*2))}};if(n.length===0){const v=Math.min(r,i-1);if(e===null)u.set(l.subarray(0,v),0),c=v;else for(let S=0;S<r&&c<i-1;S++)e[l[S]]===0&&(u[c++]=l[S])}else for(let v=m[0];v<p[0];v++)A(v);o&&c<i&&(u[c++]=-2),this.count=c,this.map=u,this.truncated=h>s,this.inverse=null}_markGroupStart(t,e,s){const n=this.perm[t];this.groupStartOf||(this.groupStartOf=new Map),this.groupStartNode||(this.groupStartNode=new Map),this.groupStartNode.set(n,s);let r=e;for(let l=e-1;l>=0;l--){const a=this._keys[l],o=t>0?this.perm[t-1]:-1;if(o>=0&&(a[o]===a[n]||a[o]!==a[o]&&a[n]!==a[n]))break;r=l}this.groupStartOf.set(n,r)}showsGroupValue(t,e){const s=this.groupStartOf?.get(t);return s!==void 0&&s<=e}summaryOfRecord(t,e){let s=this.groupStartNode?.get(t);if(s!==void 0){for(;s>0&&this.nodeLevel[s]>e.sliceLevel;)s=this.nodeParent[s];return this.summariesStale&&this._computeSummaries(),this.summaryFor(s,e.field)}}recordNumberAt(t){if(this.spec.groups.length===0)return t+1;if(this._numbersOf!==this.map){const e=new Int32Array(this.count);let s=0;for(let n=0;n<this.count;n++)this.map[n]>=0&&(e[n]=++s);this._numbers=e,this._numbersOf=this.map}return this._numbers[t]}rowInfo(t){if(t<0||t>=this.count)return null;const e=this.map[t];if(e>=0){const r=this.treeLevel?this.treeLevel[e]:0;return{kind:"record",record:e,level:r,hasChildren:this.treeHasKids?this.treeHasKids[e]===1:!1,collapsed:this.treeCollapsed.has(e)}}const s=-e-1,n=s>>>1;return{kind:s&1?"footer":"group",node:n,level:this.nodeLevel[n],collapsed:this.nodeCollapsed[n]===1}}recordAt(t){const e=this.map[t];return t>=0&&t<this.count&&e>=0?e:-1}rowOfRecord(t){if(this.inverse===null){const e=new Int32Array(this.table.rowCount).fill(-1);for(let s=0;s<this.count;s++){const n=this.map[s];n>=0&&(e[n]=s)}this.inverse=e}return t<this.inverse.length?this.inverse[t]:-1}groupCaption(t){const e=this.nodeLevel[t],s=this.spec.groups[e],n=this.table.column(s.field),r=this.nodeEnd[t]-this.nodeStart[t],l=s.caption??n?.caption??s.field,a=this.groupKeyValue(t,s);return this.spec.groupLayout==="condensed"?`${this._groupValueText(a,s,n)} (${r})`:`${l}: ${this._groupValueText(a,s,n)} (${r})`}_groupValueText(t,e,s){if(t==null)return"(blank)";if(typeof t=="number"){switch(e.by){case"year":return String(t);case"quarter":return`Q${t%4+1} ${Math.floor(t/4)}`;case"month":return`${et[t%12]} ${Math.floor(t/12)}`;case"week":{const n=x(t*7+1);return`Week of ${n.year}-${String(n.month).padStart(2,"0")}-${String(n.day).padStart(2,"0")}`}default:}return e.size>0?`${T(t)} to ${T(t+e.size)}`:s&&s.format!=="General"?V(s.format).number(t):T(t)}return typeof t=="boolean"?t?"TRUE":"FALSE":String(t)}toggleRow(t){const e=this.rowInfo(t);return e?e.kind==="group"?(this._setNode(e.node,!e.collapsed),this._relayout(),!0):e.kind==="record"&&e.hasChildren?(e.collapsed?this.treeCollapsed.delete(e.record):this.treeCollapsed.add(e.record),this._relayout(),!0):!1:!1}_setNode(t,e){this.nodeCollapsed[t]=e?1:0;const s=this._nodePath(t),n=this.nodeLevel[t]>=this.collapseFromLevel;e===n?this.collapsedPaths.delete(s):this.collapsedPaths.add(s)}showLevel(t){if(this.collapsedPaths.clear(),this.collapseFromLevel=t,this.treeCollapsed.clear(),this.spec.hierarchy&&t!==1/0){const e=this.treeLevelsAll(),s=this.table.rowCount;for(let n=0;n<s;n++)e[n]>=t&&this.treeHasKids[n]===1&&this.treeCollapsed.add(n)}this.nodeCount>0&&this._applyCollapse(),this._relayout()}treeLevelsAll(){const t=this.table.rowCount,e=new Uint16Array(t),s=this.treeParent,n=new Uint8Array(t),r=[];for(let l=0;l<t;l++){let a=l;for(r.length=0;a>=0&&n[a]===0&&r.length<=t;)r.push(a),n[a]=1,a=s[a];let o=a>=0?e[a]+1:0;for(let h=r.length-1;h>=0;h--)e[r[h]]=o++}return e}expandAll(){this.showLevel(1/0)}collapseAll(){this.showLevel(0)}_relayout(){this.invalidate(C.FLATTEN),this.refresh()}distinctValues(t,{limit:e=5e3}={}){const s=this.table.column(t);if(!s)return{values:[],total:0};this.table.ensure(s);const n=this.table.rowCount,r=new Uint8Array(n);r.set(this.table.alive.subarray(0,n));for(const h of this.spec.filters)h.field!==t&&this._applyCondition(h,r,n);const l=new Map;for(let h=0;h<n;h++){if(r[h]===0)continue;const i=s.kind(h),u=i===k?null:i===R||s.isString?`s${s.data[h]}`:s.data[h];l.set(u,(l.get(u)??0)+1)}const{strings:a}=this.table.manager,o=[];for(const[h,i]of l)if(h===null)o.push({value:null,text:"(Blanks)",count:i});else if(typeof h=="string"){const u=a.get(Number(h.slice(1)));o.push({value:u,text:u,count:i})}else{const u=s.format!=="General"?V(s.format).number(h):T(h);o.push({value:s.type==="boolean"?h!==0:h,text:s.type==="boolean"?h?"TRUE":"FALSE":u,count:i})}return o.sort((h,i)=>h.value===null?1:i.value===null?-1:typeof h.value=="number"&&typeof i.value=="number"?h.value-i.value:String(h.text).localeCompare(String(i.text))),{values:o.slice(0,e),total:o.length}}}function T(b){return X(b)}function ht(b){const t=new Set("0123456789eE");for(const e of[-1.5,1e20,1e-20,1/0,-1/0,NaN])for(const s of T(e))t.add(s);for(const e of b)if(!t.has(e))return!1;return!0}function q(b){return typeof b=="number"?b:typeof b=="boolean"?b?1:0:b==null||b===""?NaN:Number(b)}function ut(b,t,e,s){switch(b){case"gt":return t>e;case"gte":return t>=e;case"lt":return t<e;case"lte":return t<=e;case"between":return t>=e&&t<=s;case"notBetween":return!(t>=e&&t<=s);default:return!0}}O.prototype.addView=function(t,e,s={}){const n=new at(this,{name:t,columns:e,...s});return this.views.set(t,n),n},O.prototype.getView=function(t){return this.views.get(t)??null},O.prototype.removeView=function(t){this.views.get(t)?.dispose(),this.views.delete(t)};export{vt as AGG_LABEL,bt as FILTER_OPS,C as STAGE,wt as SUMMARY_AGGS,at as TableView,P as aggregate,M as formulaHelper,lt as groupKeys,ot as todaySerial};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{CHUNK_BITS as l,CHUNK_MASK as d,CHUNK_SIZE as r,Sheet as f}from"../core/sheet.js";const a=4096;class c{constructor(s){this.sheet=s,this.kinds=new Uint8Array(r),this.values=new Float64Array(r),this.store=new Uint16Array(r),this.hasStyles=!1,this.col=0,this.n=0}get styles(){return this.hasStyles?this.store:null}set styles(s){const t=this.hasStyles?this.store:null,e=this.n<<l,i=new Uint16Array(r);s!==null&&i.set(s),this.store=i,this.hasStyles=s!==null;for(let n=0;n<r;n++)(t===null?0:t[n])!==i[n]&&this.sheet.routeStyle(e+n,this.col,i[n])}}class k{constructor(s,t){this.sheet=s,this.col=t}get(s,t){if(typeof t=="string"){const e=t.charCodeAt(0);if(e>=48&&e<=57){const i=s[t];return i!==void 0?i:this.sheet._materialize(this.col,+t,s)}if(t==="length")return this.sheet.blockCount}return Reflect.get(s,t)}has(s,t){if(typeof t=="string"){const e=t.charCodeAt(0);if(e>=48&&e<=57)return+t<this.sheet.blockCount}return Reflect.has(s,t)}set(){return!0}}class C extends f{constructor(s){super(s),this.isVirtual=!0,this.blockCount=0,this.targets=[],this.pool=[],this.residents=[],this.residentHead=0,this.residentLimit=a}setShape(s,t){if(this.blockCount=t<0?0:(t>>>l)+1,this.maxRow=t,this.maxCol=s-1,s!==this.columns.length){this.invalidateCells(),this.targets=[];const e=[];for(let i=0;i<s;i++){const n=[];this.targets[i]=n,e[i]=new Proxy(n,new k(this,i))}this.columns=e,this.residentLimit=Math.max(a,s*2)}}_materialize(s,t,e){if(t>=this.blockCount)return;const i=this.pool.pop()??new c(this);return i.col=s,i.n=t,i.hasStyles=!1,this.fillChunk(s,t,i),e[t]=i,this.residents.push(i),this.residents.length-this.residentHead>this.residentLimit&&this._evict(),i}_evict(){const s=this.residentLimit>>2;for(let t=0;t<s;t++){const e=this.residents[this.residentHead];this.residents[this.residentHead++]=null;const i=this.targets[e.col];i!==void 0&&i[e.n]===e&&(i[e.n]=void 0,this.pool.push(e))}this.residentHead>16384&&(this.residents=this.residents.slice(this.residentHead),this.residentHead=0)}invalidateCells(){for(let s=this.residentHead;s<this.residents.length;s++){const t=this.residents[s],e=this.targets[t.col];e!==void 0&&e[t.n]===t&&(e[t.n]=void 0),this.pool.push(t)}this.residents=[],this.residentHead=0,this.revision++}residentChunk(s,t){const e=this.targets[t];return e===void 0?null:e[s>>>l]??null}fillChunk(){throw new Error("fillChunk is abstract")}routeCell(){}routeStyle(){}routeFormula(){}_ensure(s,t){const e=this.columns[t],i=e===void 0?void 0:e[s>>>l];return i!==void 0?i:(this.scratch===void 0&&(this.scratch=new c({routeStyle(){}})),this.scratch)}setCell(s,t,e,i){this.routeCell(s,t,e,i)}setStyle(s,t,e){this.routeStyle(s,t,e)}setFormula(s,t,e){e&&this.routeFormula(s,t,e)}patchCached(s,t,e,i,n){const h=this.residentChunk(s,t);if(h===null)return;const o=s&d;h.kinds[o]=e,h.values[o]=i,n!==void 0&&(!h.hasStyles&&n!==0&&(h.store.fill(0),h.hasStyles=!0),h.hasStyles&&(h.store[o]=n))}adoptFrom(s){for(const t of["uid","hidden","sourceIndex","sourceId","pageSetup","tabColor","zoom","cf","validations","hyperlinks","protection","comments","sparklines","rowExtras","colExtras","showGridlines"])s[t]!==void 0&&(this[t]=s[t])}}export{c as VirtualChunk,C as VirtualSheet};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sortColumn as $,sortByU32 as G}from"./sort.js";const K=new Set(["ROW_NUMBER","RANK","DENSE_RANK","PERCENT_RANK","CUME_DIST","NTILE"]),W=new Set(["LAG","LEAD"]),P=new Set(["FIRST_VALUE","LAST_VALUE","NTH_VALUE"]),B=new Set(["SUM","AVERAGE","AVG","MIN","MAX","COUNT","COUNTA"]);function k(e){const n=[];let t=0,a=!1,f=0;for(let r=0;r<e.length;r++){const d=e[r];a?d==='"'&&(e[r+1]==='"'?r++:a=!1):d==='"'?a=!0:d==="("||d==="["?t++:d===")"||d==="]"?t--:d===","&&t===0&&(n.push(e.slice(f,r).trim()),f=r+1)}const u=e.slice(f).trim();return(u!==""||n.length>0)&&n.push(u),n}const V=e=>{const n=/^([A-Za-z_][A-Za-z_0-9]*)\s*\(([\s\S]*)\)$/.exec(e.trim());return n?{name:n[1].toUpperCase(),args:k(n[2])}:null},I=e=>{const n=/^\[@?\[?([^[\]]+?)\]?\]$/.exec(e.trim());return n?n[1].trim():null},L=e=>/^".*"$/.test(e)?e.slice(1,-1).replace(/""/g,'"'):null,b=e=>e===void 0||e===""||/^null$/i.test(e)||/^unbounded$/i.test(L(e)??e)?null:Number(e);function H(e,n){const t=k(e),a=V(t[0]??"");if(!a)throw new Error("A window needs a function.");const f={fn:a.name,args:a.args,partition:[],order:[],frame:null,exclude:null},u=r=>{r.partition&&(f.partition=r.partition),r.order&&(f.order=r.order),r.frame&&(f.frame=r.frame),r.exclude&&(f.exclude=r.exclude)};for(const r of t.slice(1)){const d=L(r);if(d!==null){const l=n.windowDefs[d];if(!l)throw new Error(`No window named ${d}.`);u(l);continue}const c=V(r);if(!c)throw new Error(`Can't read ${r} in a window.`);switch(c.name){case"PARTITIONBY":f.partition=c.args.map(I);break;case"ORDERBY":{f.order=[];for(let l=0;l<c.args.length;l++){const y=I(c.args[l]);if(y===null)continue;const g=L(c.args[l+1]??"");f.order.push({field:y,desc:g!==null&&/^desc/i.test(g)})}break}case"ROWS":case"RANGE":case"GROUPS":f.frame={type:c.name.toLowerCase(),from:b(c.args[0]),to:b(c.args[1])};break;case"EXCLUDE":f.exclude=(L(c.args[0]??"")??c.args[0]??"").toLowerCase();break;default:throw new Error(`${c.name} doesn't belong in a window.`)}}if(!K.has(f.fn)&&!W.has(f.fn)&&!P.has(f.fn)&&!B.has(f.fn))throw new Error(`${f.fn} can't run over a window.`);return f}function X(e,n,t){let a="",f=0;const u=/\bWINDOW\s*\(/gi;for(;;){u.lastIndex=f;const r=u.exec(e);if(!r){a+=e.slice(f);break}let d=1,c=r.index+r[0].length,l=!1;for(;c<e.length&&d>0;c++){const m=e[c];l?m==='"'&&(l=!1):m==='"'?l=!0:m==="("?d++:m===")"&&d--}const y=e.slice(r.index+r[0].length,c-1),g=`__window:${y}`;let w=n.byName.get(g);if(!w){let m;try{m=H(y,n)}catch{a+=`${e.slice(f,r.index)}#NAME?`,f=c;continue}w=n.addHelper({name:g,type:"any",hidden:!0,readOnly:!0,window:{...m,table:n}}),w.deps=D(m),w.rangeDep=!0,n.byName.set(`__w${w.index}`,w)}t(w),a+=`${e.slice(f,r.index)}[@__w${w.index}]`,f=c}return a}function D(e){const n=new Set;for(const t of e.args){const a=I(t);a&&n.add(a)}for(const t of e.partition)t&&n.add(t);for(const t of e.order)n.add(t.field);return[...n]}function Y(e){const n=e.window,{table:t}=n,a=t.rowCount;for(const i of D(n)){const h=t.column(i);h&&t.ensure(h)}const f=new Int32Array(t.liveCount);let u=0;for(let i=0;i<a;i++)t.alive[i]===1&&(f[u++]=i);const r=f.subarray(0,u);for(let i=n.order.length-1;i>=0;i--){const h=t.column(n.order[i].field);h&&$(t,r,u,h,n.order[i].desc)}const d=n.partition.map(i=>F(t,t.column(i)));for(let i=d.length-1;i>=0;i--){const h=new Uint32Array(u),p=d[i];for(let A=0;A<u;A++)h[A]=p[r[A]];G(r,u,h)}const c=n.order.map(i=>F(t,t.column(i.field))),l=z(t,n.args[0]),y=new Float64Array(t.capacity).fill(NaN);let g=null;const w=(i,h)=>{h<0||l===null||(l.isNumeric?y[i]=l.data[h]:(g===null&&(g=new Map),g.set(i,l.get(h))))};let m=0;for(;m<u;){let i=m+1;for(;i<u&&d.every(h=>h[r[m]]===h[r[i]]);)i++;j(n,r,m,i,c,l,y,w,t),m=i}if(e.kinds=null,e.data.fill(NaN),e.data.set(y.subarray(0,Math.min(y.length,e.data.length))),g!==null)for(const[i,h]of g)e.put(i,h)}function F(e,n){const t=e.rowCount,a=new Uint32Array(t);if(!n)return a;if(e.ensure(n),n.isString){const{rank:u}=n.ranks();for(let r=0;r<t;r++){const d=n.data[r];a[r]=d<0?4294967295:u[d]}return a}const f=new Map;for(let u=0;u<t;u++){const r=n.kinds===null?n.data[u]:n.get(u),d=r!==r||r===null?null:r;let c=f.get(d);c===void 0&&(c=f.size,f.set(d,c)),a[u]=c}return a}function z(e,n){if(!n)return null;const t=I(n);return t===null?null:e.column(t)??null}function j(e,n,t,a,f,u,r,d,c){const l=a-t,y=(o,N)=>f.every(s=>s[n[o]]===s[n[N]]);switch(e.fn){case"ROW_NUMBER":for(let o=t;o<a;o++)r[n[o]]=o-t+1;return;case"RANK":case"DENSE_RANK":case"PERCENT_RANK":case"CUME_DIST":{let o=1,N=1,s=t;for(;s<a;){let E=s+1;for(;E<a&&y(s,E);)E++;for(let T=s;T<E;T++){const S=n[T];e.fn==="RANK"?r[S]=o:e.fn==="DENSE_RANK"?r[S]=N:e.fn==="PERCENT_RANK"?r[S]=l>1?(o-1)/(l-1):0:r[S]=(E-t)/l}o+=E-s,N++,s=E}return}case"NTILE":{const o=Math.max(1,Number(e.args[0])||1),N=Math.floor(l/o),s=l%o;let E=t;for(let T=0;T<o&&E<a;T++){const S=N+(T<s?1:0);for(let O=0;O<S;O++)r[n[E++]]=T+1}return}case"LAG":case"LEAD":{const o=(e.args[1]!==void 0?Number(e.args[1]):1)*(e.fn==="LAG"?-1:1),N=e.args[2]!==void 0?Number(e.args[2]):NaN;for(let s=t;s<a;s++){const E=s+o;E>=t&&E<a?d(n[s],n[E]):r[n[s]]=N}return}default:}const g=f.length>0,w=e.frame??(g?{type:"range",from:null,to:0}:{type:"rows",from:null,to:null}),m=new Float64Array(l+1),i=new Float64Array(l+1),h=u&&u.isNumeric;for(let o=0;o<l;o++){const N=n[t+o],s=h?u.data[N]:NaN;m[o+1]=m[o]+(s===s?s:0),i[o+1]=i[o]+(u===null?1:h?s===s?1:0:u.kind(N)!==0?1:0)}const p=new Int32Array(l),A=new Int32Array(l),_=new Int32Array(l);let R=0;for(let o=0;o<l;){let N=o+1;if(g)for(;N<l&&y(t+o,t+N);)N++;for(let s=o;s<N;s++)p[s]=o,A[s]=N,_[s]=R;R++,o=N}const C=new Int32Array(R+1);for(let o=l-1;o>=0;o--)C[_[o]]=o;C[R]=l;const x=g?c.column(e.order[0].field):null,U=g&&e.order[0].desc,M=o=>x&&x.isNumeric?x.data[n[t+o]]:o;for(let o=0;o<l;o++){let N,s;if(w.type==="rows")N=w.from===null?0:Math.max(0,o+w.from),s=w.to===null?l:Math.min(l,o+w.to+1);else if(w.type==="groups"){const E=_[o];N=w.from===null?0:C[Math.max(0,E+w.from)],s=w.to===null?l:C[Math.min(R,E+w.to+1)]}else if(w.from===0&&w.to===0)N=p[o],s=A[o];else{const E=M(o),T=U?-1:1;if(N=0,w.from!==null){const S=E+T*w.from;for(N=o;N>0&&(U?M(N-1)<=S:M(N-1)>=S);)N--;N=p[N]}if(s=l,w.to!==null){const S=E+T*w.to;for(s=o+1;s<l&&(U?M(s)>=S:M(s)<=S);)s++;s=A[s-1]}}s<N&&(s=N),r[n[t+o]]=q(e,N,s,o,p[o],A[o],n,t,u,m,i,d)}}function q(e,n,t,a,f,u,r,d,c,l,y,g){const w=[],m=(A,_)=>{_>A&&w.push([A,_])};switch(e.exclude){case"current":case"current row":m(n,Math.min(a,t)),m(Math.max(a+1,n),t);break;case"group":m(n,Math.min(f,t)),m(Math.max(u,n),t);break;case"ties":m(n,Math.min(f,t)),a>=n&&a<t&&m(a,a+1),m(Math.max(u,n),t);break;default:m(n,t)}const i=e.fn;if(i==="FIRST_VALUE"||i==="LAST_VALUE"||i==="NTH_VALUE"){const A=i==="NTH_VALUE"?Number(e.args[1]):i==="FIRST_VALUE"?1:1/0;let _=0,R=-1;for(const[C,x]of w)for(let U=C;U<x&&_<A;U++)_++,R=U;return R<0||i==="NTH_VALUE"&&_<A?NaN:(g(r[d+a],r[d+R]),c&&c.isNumeric?c.data[r[d+R]]:NaN)}let h=0,p=0;for(const[A,_]of w)h+=l[_]-l[A],p+=y[_]-y[A];switch(i){case"SUM":return h;case"COUNT":case"COUNTA":return p;case"AVERAGE":case"AVG":return p>0?h/p:NaN;default:{if(!c||!c.isNumeric)return NaN;let A=NaN;const{data:_}=c;for(const[R,C]of w)for(let x=R;x<C;x++){const U=_[r[d+x]];U===U&&(A!==A||(i==="MIN"?U<A:U>A))&&(A=U)}return A}}}export{Y as computeWindow,X as extractWindowCalls,H as parseWindow};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{CUSTOM_XML_CONTENT_TYPE as E,CUSTOM_XML_REL as S,customXmlNames as b}from"../../celltypes/persist.js";import{escapeRegExp as d}from"../../core/regexp.js";import{children as _,parseTree as P,unescapeOoxml as A}from"../../io/xml-scan.js";import{xmlText as O}from"../../io/xml-escape.js";import{STEP_OPS as R,COLUMN_TYPES as N,FILTER_OPS as I,MAX_DELIMITER as M}from"./steps.js";const h="urn:8sheets:getdata:1",i="customXml/",p="queries8c.xml",$="rId8cGetData",j=4*1024*1024,X=256,q=256,y=16384,v=1024,L=8192,U=new Set(["csv","json","xml","web","table","range","workbook"]),D=new Set(["auto","csv","json","xml","html"]),C=new Set(["utf-8","windows-1250","windows-1252","iso-8859-2","utf-16le"]),Q=new Set([",",";"," ","|"]),l=(e,t=v)=>typeof e=="string"&&e.length<=t?e:null;function k(e){const t=l(e,L);if(!t)return null;let n;try{n=new URL(t)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password?null:n.href}function Y(e){if(e===null||typeof e!="object"||!U.has(e.type))return null;const t={type:e.type},n=l(e.fileName);if(n&&(t.fileName=n),e.type==="web"){if(t.url=k(e.url),!t.url)return null;t.format=D.has(e.format)?e.format:"auto"}if(e.type==="table"&&(t.table=l(e.table),!t.table)||e.type==="range"&&(t.sheet=l(e.sheet),t.ref=l(e.ref),!t.sheet||!t.ref)||e.type==="workbook"&&(t.sheet=l(e.sheet),!t.sheet))return null;(Q.has(e.delimiter)||typeof e.delimiter=="string"&&e.delimiter.length===1&&!/["\r\n]/.test(e.delimiter))&&(t.delimiter=e.delimiter),e.detectTypes===!1&&(t.detectTypes=!1),Number.isInteger(e.tableIndex)&&e.tableIndex>=0&&(t.tableIndex=e.tableIndex),C.has(e.encoding)&&(t.encoding=e.encoding);const o=l(e.recordsPath);o&&(t.recordsPath=o);const s=l(e.recordPath);return s&&(t.recordPath=s),e.ndjson===!0&&(t.ndjson=!0),t}function F(e){if(e===null||typeof e!="object"||!R.includes(e.op))return null;const{op:t}=e;switch(t){case"promoteHeaders":return{op:t};case"chooseColumns":{if(!Array.isArray(e.names)||e.names.length>y)return null;const n=e.names.map(o=>l(o));return n.includes(null)?null:{op:t,names:n}}case"splitColumn":{const n=l(e.column),o=typeof e.delimiter=="string"&&e.delimiter.length>=1&&e.delimiter.length<=M?e.delimiter:null,s=Number.isInteger(e.parts)&&e.parts>=1&&e.parts<=100?e.parts:null;return n!==null&&o!==null&&s!==null?{op:t,column:n,delimiter:o,parts:s}:null}case"rename":{const n=l(e.from),o=l(e.to);return n!==null&&o?{op:t,from:n,to:o}:null}case"changeType":{const n=l(e.column);return n!==null&&Object.hasOwn(N,e.to)?{op:t,column:n,to:e.to}:null}case"filterRows":{const n=l(e.column);return n===null||!Object.hasOwn(I,e.test)?null:{op:t,column:n,test:e.test,value:l(e.value)??""}}case"removeDuplicates":{if(e.columns===null||e.columns===void 0)return{op:t,columns:null};if(!Array.isArray(e.columns)||e.columns.length>y)return null;const n=e.columns.map(o=>l(o));return n.includes(null)?null:{op:t,columns:n}}case"sort":{const n=l(e.column);return n!==null?{op:t,column:n,desc:e.desc===!0}:null}default:return null}}function g(e){if(e===null||typeof e!="object")return null;const t=l(e.id,64),n=l(e.name,255),o=Y(e.source);if(!t||!n||!o||!Array.isArray(e.steps)||e.steps.length>q)return null;const s=e.steps.map(F);if(s.includes(null))return null;const u={id:t,name:n,source:o,steps:s},c=l(e.table);return c&&(u.table=c),e.connectionOnly===!0&&!c&&(u.connectionOnly=!0),u}function B(e){if(!e?.length)return null;const t=e.map(n=>{const o=g(n);return o?`<query>${O(JSON.stringify(o))}</query>`:""}).join("");return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
2
|
+
<queries xmlns="${h}" version="1">${t}</queries>`}function G(e){let t;try{t=P(new TextEncoder().encode(e))}catch{return{queries:[],rejected:1}}const n=[];let o=0;const s=new Set;for(const u of _(t,"query").slice(0,X)){let c=null;try{c=JSON.parse(A(u.t))}catch{}const r=g(c);r&&!s.has(r.id)?(s.add(r.id),n.push(r)):o++}return{queries:n,rejected:o}}function J(e){const t=B(e);return t===null?null:{path:`${i}${p}`,xml:t,override:{partName:`/${i}${p}`,contentType:E},relationship:{id:$,type:S,target:`/${i}${p}`}}}const z=e=>{const t=J(e.getDataQueries);return t?[t]:[]};async function x(e){const t=[];for(const n of b(e,j)){const o=await e.text(n);o.includes(h)&&t.push({name:n,text:o})}return t}async function w(e){const t=[];let n=0;for(const o of await x(e)){const s=G(o.text);t.push(...s.queries),n+=s.rejected}return{queries:t,rejected:n}}async function ee(e,t,n,o){let s=t,u=n;const c=r=>{s=s.replace(new RegExp(`<Override\\b[^>]*PartName="/${d(r)}"[^>]*/>`,"g"),"")};for(const{name:r}of await x(e)){o.add(r),c(r);const a=r.slice(i.length);u=u.replace(new RegExp(`<Relationship\\b[^>]*Target="[^"]*${d(i+a)}"[^>]*/>`,"g"),"");const f=`${i}_rels/${a}.rels`;if(e.has(f)){o.add(f);for(const T of(await e.text(f)).matchAll(/Target="([^"]+)"/g)){const m=`${i}${T[1].split("/").pop()}`;e.has(m)&&(o.add(m),c(m))}}}return{types:s,rels:u}}export{h as QUERIES_NS,k as cleanUrl,ee as dropQueryParts,z as getDataPackage,G as parseQueries,J as queriesPart,B as queriesXml,w as readQueries,x as readQueryParts,g as sanitizeQuery};
|