@8sheets/data-grid 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/api/theme-core.js +2 -0
- package/calc/adjust.js +1 -1
- package/calc/compile.js +1 -1
- package/calc/engine.js +1 -1
- package/calc/functions/array.js +1 -1
- package/calc/functions/date.js +1 -1
- package/calc/functions/dbcs.js +1 -0
- package/calc/functions/financial.js +1 -1
- package/calc/functions/helpers.js +1 -1
- package/calc/functions/index.js +7 -1
- package/calc/functions/info.js +1 -1
- package/calc/functions/logical.js +1 -1
- package/calc/functions/lookup.js +1 -1
- package/calc/functions/math.js +1 -1
- package/calc/functions/stat.js +1 -1
- package/calc/functions/text.js +1 -1
- package/calc/parser.js +3 -3
- package/calc/values.js +1 -1
- package/calcx/culture/custom.js +1 -0
- package/calcx/culture/format-locale.js +1 -1
- package/calcx/culture/separators.js +1 -0
- package/calcx/functions/text.js +1 -1
- package/calcx/lang/convert.js +1 -0
- package/cells/axis-ops.js +1 -1
- package/cells/block.js +1 -0
- package/cells/book-css.js +2 -2
- package/cells/cell-defaults.js +1 -1
- package/cells/cf-engine.js +1 -1
- package/cells/consolidate-links.js +1 -1
- package/cells/find-engine.js +2 -2
- package/cells/format-panes.js +3 -3
- package/cells/format-tabs.js +5 -5
- package/cells/name-box.js +1 -1
- package/cells/outline-column.js +1 -1
- package/cells/panes.js +1 -1
- package/cells/selection-modes.js +1 -1
- package/cells/shift-check.js +1 -0
- package/cells/table-rows.js +1 -0
- package/cells/text-layout.js +9 -8
- package/cells/ui-kit.js +15 -0
- package/cells/view-options.js +1 -1
- package/celltypes/diagonal.js +1 -1
- package/celltypes/dropdowns.js +2 -2
- package/core/address.js +1 -1
- package/core/autofill.js +1 -0
- package/core/axis-styles.js +1 -0
- package/core/axis.js +1 -1
- package/core/cond-format.js +1 -1
- package/core/culture.js +1 -0
- package/core/default-names.js +1 -1
- package/core/formula-refs.js +1 -1
- package/core/input.js +1 -1
- package/core/merge.js +1 -0
- package/core/numfmt.js +1 -1
- package/core/region-input.js +1 -0
- package/core/row-fit.js +1 -0
- package/core/sheet.js +1 -1
- package/core/structure.js +1 -0
- package/core/styles.js +1 -1
- package/core/tables.js +2 -2
- package/core/whatif.js +1 -1
- package/core/workbook.js +1 -1
- package/datasheets/data-core.js +1 -1
- package/datasheets/gantt-paint.js +1 -1
- package/datasheets/path-binding.js +2 -2
- package/datasheets/rules.js +1 -1
- package/datasheets/view.js +2 -2
- package/i18n/dom.js +1 -1
- package/i18n/en/cells.js +1 -1
- package/i18n/en/common.js +1 -1
- package/i18n/en/format.js +1 -1
- package/i18n/en/shell.js +2 -1
- package/i18n/pl/cells.js +1 -1
- package/i18n/pl/common.js +1 -1
- package/i18n/pl/format.js +1 -1
- package/i18n/pl/shell.js +2 -1
- package/io/csv.js +8 -8
- package/io/plan.js +1 -1
- package/io/text-split.js +3 -3
- package/io/xlsx-write.js +2 -2
- package/objects/chart-model.js +1 -1
- package/package.json +1 -1
- package/pivot/engine.js +1 -1
- package/print/paginate.js +1 -1
- package/print/render-page.js +3 -3
- package/table-view/api.js +1 -1
- package/table-view/cell-editor.js +2 -1
- package/table-view/chart.js +1 -0
- package/table-view/column-drag.js +1 -1
- package/table-view/context-menu.js +1 -0
- package/table-view/editors.js +1 -0
- package/table-view/events.js +1 -1
- package/table-view/files.js +1 -1
- package/table-view/fill-handle.js +1 -0
- package/table-view/filter-builder.js +1 -0
- package/table-view/find.js +1 -0
- package/table-view/grid-keys.js +2 -2
- package/table-view/labels-de.js +1 -0
- package/table-view/labels-es.js +1 -0
- package/table-view/labels-fr.js +1 -0
- package/table-view/labels-ja.js +1 -0
- package/table-view/labels.js +1 -1
- package/table-view/model.js +1 -1
- package/table-view/mount.js +1 -1
- package/table-view/panel.js +1 -1
- package/table-view/pivot-spec.js +1 -0
- package/table-view/pivot.js +1 -1
- package/table-view/public.d.ts +277 -28
- package/table-view/reader.worker.js +1 -1
- package/table-view/remote.js +1 -1
- package/table-view/row-drag.js +1 -0
- package/table-view/sparkline.js +1 -0
- package/table-view/state-check.js +1 -0
- package/table-view/table-css.js +380 -0
- package/table-view/version.js +1 -1
- package/ui/dialogs.js +3 -3
- package/ui/icons.js +1 -1
- package/ui/menu-base.js +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{CHUNK_BITS as v,CHUNK_MASK as A,CHUNK_SIZE as q,FORMULA as ln,STR as sn}from"./sheet.js";import{FormulaStore as D}from"./formula-store.js";import{cellRef as B,MAX_COLS as w,MAX_ROWS as k,parseCellRef as L,parseRangeRef as X,rangeRef as H}from"./address.js";import{translateFormula as on}from"./formula-refs.js";import{adjustFormula as T,adjustRange as O}from"../calc/adjust.js";import{clonePageSetup as en,shiftPageSetup as an}from"../print/page-setup.js";import{shiftSparse as cn}from"./sparse.js";import{shiftRuleFormulas as un}from"../cells/cf-file.js";import{noteStructure as fn}from"./changes.js";import{shiftHeaderColors as mn}from"../cells/header-colors.js";function V(t){return{kinds:new Uint8Array(q),values:new Float64Array(q),styles:t.styles===null?null:new Uint16Array(q)}}function W(t,n,r){if(!t||n===0)return;const s=/outlineLevel="\d+"/.exec(t.get(n-1)??"");if(s)for(let o=n;o<n+r;o++)t.set(o,s[0])}function Z(t,n,r,s,o,c){let l=s,e=r,u=c;for(;l>0;){const a=u>>>v,i=u&A,m=Math.min(l,q-i);let y=o[a];y===void 0&&(y=V(t),o[a]=y);const d=e-n;y.kinds.set(t.kinds.subarray(d,d+m),i),y.values.set(t.values.subarray(d,d+m),i),t.styles!==null&&(y.styles===null&&(y.styles=new Uint16Array(q)),y.styles.set(t.styles.subarray(d,d+m),i)),l-=m,e+=m,u+=m}}function G(t,n,r){const s=n>>>v,o=t.slice(0,s),c=t[s];c!==void 0&&(n&A)>0&&Z(c,s<<v,s<<v,n&A,o,s<<v);const l=r<0?n-r:n;for(let e=s;e<t.length;e++){const u=t[e];if(u===void 0)continue;const a=e<<v,i=Math.max(a,l),m=a+q;if(i>=m)continue;const y=i+r;if(y>=k)continue;const d=Math.min(m-i,k-y);Z(u,a,i,d,o,y)}return o}function dn(t,n,r){const s=[];for(let o=0;o<t.length;o++){const c=t[o];c!==void 0&&(o<n?s[o]=c:r>0?o+r<w&&(s[o+r]=c):o>=n-r&&(s[o+r]=c))}return s}function gn(t,n,r,s){const o=r-1,c=Math.min(s,(n?k:w)-r);if(c<=0)return;if(n){const u=c*t.columns.filter(Boolean).length<=4194304;for(let i=0;u&&i<t.columns.length;i++){if(t.columns[i]===void 0)continue;const m=t.cellStyle(o,i);if(m!==0)for(let y=0;y<c;y++)t.setStyle(r+y,i,m)}const a=t.rowStyles?.get(o);if(a!==void 0)for(let i=0;i<c;i++)t.rowStyles.set(r+i,a);return}const l=t.columns[o];if(l!==void 0&&l.some(u=>u?.styles)){for(let u=0;u<c;u++){const a=[];l.forEach((i,m)=>{if(i===void 0||i.styles===null)return;const y=V(i);y.styles.set(i.styles),a[m]=y}),t.columns[r+u]=a}r+c-1>t.maxCol&&(t.maxCol=r+c-1)}const e=t.colStyles?.get(o);if(e!==void 0)for(let u=0;u<c;u++)t.colStyles.set(r+u,e)}function N(t,n,r){if(t===null)return null;const s=new Map;for(const[o,c]of t)o<n?s.set(o,c):(r>0||o>=n-r)&&s.set(o+r,c);return s}const U=(t,n,r)=>r.axis==="row"?t<r.at?[t,n]:r.n>0?t+r.n<k?[t+r.n,n]:null:t>=r.at-r.n?[t+r.n,n]:null:n<r.at?[t,n]:r.n>0?n+r.n<w?[t,n+r.n]:null:n>=r.at-r.n?[t,n+r.n]:null;function J(t,n,r){if(t.f!==void 0)return t.f;if(t.sf!==void 0){const s=Math.floor(t.base/w);return on(t.sf,n-s,r-(t.base-s*w))}return null}const P=(t,n)=>(t.f??t.sf)?.toUpperCase().includes(n)===!0;function Q(t,n){for(const r of t.descriptors())if(P(r,n))return!0;return!1}function _(t,n){const r=X(t),s=r&&O(r,n);return s?H(s):t}function Y(t,n,r,s,o){if(t.t==="dataTable"){if(!s)return t;const l={...t,ref:_(t.ref,r),tpl:void 0};return t.r1&&(l.r1=_(t.r1,r)),t.r2&&(l.r2=_(t.r2,r)),l}const c={f:T(n,r,s,o)};return t.typed&&(c.typed=!0),t.ca&&(c.ca=t.ca),t.cm&&(c.cm=t.cm),t.t==="array"&&(c.t="array",c.ref=s&&t.ref?_(t.ref,r):t.ref),c}function Un(t,n,r){t.collab?.structure(n,r);const{at:s,n:o}=r,c=r.axis==="row",l=$(t,n),e=fn(n,r);if(c){const d=[];n.columns.forEach((p,R)=>{d[R]=G(p,s,o)}),n.columns=d,n.rows=n.rows.shifted(s,o),n.rowStyles=N(n.rowStyles,s,o),n.rowExtras=N(n.rowExtras,s,o),o>0&&W(n.rowExtras,s,o),n.maxRow=n.maxRow>=s?Math.max(s-1,n.maxRow+o):n.maxRow,n.maxRow>=k&&(n.maxRow=k-1),n.frozenRows>s&&(n.frozenRows=Math.max(s,n.frozenRows+o))}else n.columns=dn(n.columns,s,o),n.cols=n.cols.shifted(s,o),n.colStyles=N(n.colStyles,s,o),n.colExtras=N(n.colExtras,s,o),o>0&&W(n.colExtras,s,o),n.colsChanged=!0,n.maxCol=n.maxCol>=s?Math.max(s-1,n.maxCol+o):n.maxCol,n.maxCol>=w&&(n.maxCol=w-1),n.frozenCols>s&&(n.frozenCols=Math.max(s,n.frozenCols+o));if(o>0&&s>0&&!r.noFormat&&gn(n,c,s,o),n.merges=n.merges.map(d=>O(d,r)).filter(d=>d!==null&&(d.r0!==d.r1||d.c0!==d.c1)),n.mergeIndex=null,n.spills){const d=new Map;for(const[p,R]of n.spills){const f=Math.floor(p/w),x=U(f,p-f*w,r),g=O(R,r);x&&g&&d.set(x[0]*w+x[1],{...R,...g})}n.spills=d}if(n.valueMeta){const d=new Map;for(const[p,R]of n.valueMeta){const f=Math.floor(p/w),x=U(f,p-f*w,r);x&&d.set(x[0]*w+x[1],R)}n.valueMeta=d}const u=n.name.toUpperCase();for(const d of t.sheets){const p=d===n;if(!p&&!Q(d.formulas,u))continue;const R=new D;d.formulas.forEachCell((f,x,g)=>{const C=p?U(f,x,r):[f,x];if(C===null)return;if(!p&&!P(g,u)){R.put(C[0],C[1],g);return}const S=J(g,f,x);if(S===null||!p&&!S.toUpperCase().includes(u)){R.put(C[0],C[1],g);return}const M=Y(g,S,r,p,n.name);if(M.t==="array"&&M.ref&&p){const z=d.spills?.get(C[0]*w+C[1]);z&&(M.ref=H(z))}R.put(C[0],C[1],M)}),d.formulas=R}const a=tn(t,n,r),i=t.engine;if(i){for(const d of i.names.values())d.text=T(d.text,r,!1,n.name);i.names.size>0&&(t.namesChanged=!0),i.nameTemplates.clear(),i.rebuild()}n.structureOps=[...n.structureOps??[],r],n.pageSetup&&(an(n.pageSetup,r),n.pageSetupChanged=!0),n.viewChanged=!0,n.revision++,t.collab?.structureDone(n);const m=(d,p)=>()=>m(d(),p()),y=m(a,b(t,n,l));return e===null?y:m(y,e)}const E=(t,n)=>{if(n.span){const[r,s]=n.span;if(!(n.axis==="row"?t.c0>=r&&t.c1<=s:t.r0>=r&&t.r1<=s))return t}return O(t,n)};function j(t,n){return t.split(/\s+/).map(X).filter(Boolean).map(r=>E(r,n)).filter(Boolean).map(H).join(" ")}function F(t,n,r){if(r.span){const[s,o]=r.span,c=r.axis==="row"?n:t;if(c<s||c>o)return[t,n]}return U(t,n,r)}function h(t,n){if(!t)return t;const r=E(t,n);if(r===null)return null;let{columns:s}=t;if(n.axis==="col"&&s?.size>0){s=new Map;for(const[c,l]of t.columns){const e=F(t.r0,c,n);e&&s.set(e[1],l)}}let{buttons:o}=t;if(n.axis==="col"&&o?.size>0){o=new Map;for(const[c,l]of t.buttons){const e=F(t.r0,c,n);e&&o.set(e[1],l)}}return{...t,...r,columns:s,buttons:o,sortState:nn(t.sortState,n)}}function nn(t,n){if(!t)return t??null;const r=E(t,n);if(r===null)return null;const s=[];for(const o of t.conditions){const c=E(o,n);c!==null&&s.push({...o,...c})}return s.length>0?{...t,...r,conditions:s}:null}const I=t=>({sheets:t.sheets.map(n=>[n,{cf:n.cf,cellStates:n.cellStates,headerColors:n.headerColors,validations:n.validations,hyperlinks:n.hyperlinks,ignoredErrors:n.ignoredErrors,comments:n.comments,sparklines:n.sparklines,sparkRules:n.sparkRules,autoFilter:n.autoFilter,advancedFilter:n.advancedFilter,outlineColumn:n.outlineColumn,outlineVersion:(n.outlineVersion??0)+1,sortState:n.sortState,filteredRows:n.filteredRows,scenarios:n.scenarios,threads:n.threads}]),tables:t.engine?[...t.engine.tables.values()].map(n=>[n,{r0:n.r0,c0:n.c0,r1:n.r1,c1:n.c1,columns:n.columns,filter:n.filter,totals:n.totals,dirty:n.dirty,columnsChanged:n.columnsChanged}]):[]}),rn=t=>{for(const[n,r]of t.sheets)Object.assign(n,r),n.cfEval?.invalidate();for(const[n,r]of t.tables)Object.assign(n,r)};function tn(t,n,r){const s=I(t),o=n.name;for(const l of t.sheets){const e=l===n,u=a=>typeof a=="string"&&a!==""?T(a,r,e,o):a;if(l.cf?.length>0&&(l.cf=l.cf.map(({_ranges:a,...i})=>({...i,sqref:e?j(i.sqref,r):i.sqref,rules:i.rules.map(m=>un(m,u))})).filter(a=>a.sqref!==""),l.cfChanged=!0,l.cfEval?.invalidate()),e&&l.headerColors&&!r.span&&(l.headerColors=mn(l.headerColors,r)),e&&l.cellStates?.length>0){const a=l.cellStates.map(i=>({...i,ranges:i.ranges.map(m=>E(m,r)).filter(Boolean)})).filter(i=>i.ranges.length>0);l.cellStates=a.length>0?a:null}l.validations?.length>0&&(l.validations=l.validations.map(({_ranges:a,...i})=>({...i,sqref:e?j(i.sqref,r):i.sqref,formula1:u(i.formula1),formula2:u(i.formula2)})).filter(a=>a.sqref!==""),l.validationsChanged=!0),e&&l.ignoredErrors?.length>0&&(l.ignoredErrors=l.ignoredErrors.map(a=>({...a,sqref:j(a.sqref,r)})).filter(a=>a.sqref!==""),l.ignoredErrorsChanged=!0),l.hyperlinks?.length>0&&(l.hyperlinks=l.hyperlinks.map(({_ranges:a,...i})=>{const m=e?j(i.ref,r):i.ref;return{...i,ref:m,...i.location?{location:u(i.location)}:{}}}).filter(a=>a.ref!==""),l.hyperlinksChanged=!0),l.sparkRules?.length>0&&(l.sparkRules=l.sparkRules.map(a=>({...a,sqref:e?j(a.sqref,r):a.sqref,formula:u(a.formula)})).filter(a=>a.sqref!=="")),l.sparklines?.length>0&&(l.sparklines=l.sparklines.map(a=>({...a,items:a.items.map(i=>{const m=L(i.cell),y=e&&m?F(m.row,m.col,r):m?[m.row,m.col]:null;return y?{...i,cell:B(y[0],y[1]),source:u(i.source)}:null}).filter(Boolean)})).filter(a=>a.items.length>0),l.sparklinesChanged=!0)}if(n.comments?.size>0){const l=new Map;for(const[e,u]of n.comments){const a=Math.floor(e/w),i=F(a,e-a*w,r);i&&l.set(i[0]*w+i[1],{...u,ref:B(i[0],i[1])})}n.comments=l,n.commentsChanged=!0}if(n.scenarios?.items.length>0&&(n.scenarios={...n.scenarios,items:n.scenarios.items.map(l=>({...l,cells:l.cells.map(e=>{const u=L(e.r),a=u&&F(u.row,u.col,r);return a?{...e,r:B(a[0],a[1])}:null}).filter(Boolean)}))},n.scenariosChanged=!0),n.threads?.length>0&&(n.threads=n.threads.map(l=>{const e=L(l.ref),u=e&&F(e.row,e.col,r);return u?{...l,ref:B(u[0],u[1])}:null}).filter(Boolean),n.threadsChanged=!0),n.outlineColumn){const l=n.outlineColumn;if(r.axis==="col"&&!r.span){const e=U(0,l.col,r);n.outlineColumn=e?{...l,col:e[1]}:null}else if(r.axis==="row"&&!r.span&&l.checks){const e={};for(const u of Object.keys(l.checks)){const a=U(Number(u),0,r);a&&(e[a[0]]=l.checks[u])}n.outlineColumn={...l,checks:e}}}if(n.outlineVersion=(n.outlineVersion??0)+1,n.sortState&&(n.sortState=nn(n.sortState,r),n.filterChanged=!0),n.autoFilter&&(n.autoFilter=h(n.autoFilter,r),n.filterChanged=!0),n.advancedFilter){const l=n.advancedFilter,e=l.listSheet===n?E(l,r):l;n.advancedFilter=e===null?null:{...l,r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1,criteria:l.criteria&&l.criteriaSheet===n?E(l.criteria,r):l.criteria,extract:l.extract?E(l.extract,r):null},n.filterChanged=!0}if(n.filteredRows&&r.axis==="row"&&!r.span){const l=new Set;for(const e of n.filteredRows){const u=U(e,0,r);u&&l.add(u[0])}n.filteredRows=l}if(t.engine)for(const l of[...t.engine.tables.values()]){if(l.sheet!==n)continue;const e=E(l,r);if(e===null)continue;const u=!r.span||r.span[0]<=l.r0&&r.span[1]>=l.r1;r.axis==="col"&&u&&e.c1-e.c0!==l.c1-l.c0&&Cn(t,l,r),Object.assign(l,{r0:e.r0,c0:e.c0,r1:e.r1,c1:e.c1}),l.filter=h(l.filter,r),l.dirty=!0}const c=l=>()=>{const e=I(t);return rn(l),c(e)};return c(s)}function On(t){const n=r=>()=>{const s=I(t);return rn(r),n(s)};return n(I(t))}function xn(t,n){return b(t,n,$(t,n))}function yn(t,n,r,s){if(t===void 0&&n===void 0)return;const o=t===void 0?[]:t.slice();for(let c=r>>>v;c<=s>>>v;c++){const l=t?.[c],e=n?.[c];if(l===void 0&&e===void 0)continue;const u=c<<v,a=Math.max(r,u)-u,i=Math.min(s,u+A)-u+1,m=l===void 0?V({styles:null}):{kinds:l.kinds.slice(),values:l.values.slice(),styles:l.styles?l.styles.slice():null};e===void 0?(m.kinds.fill(0,a,i),m.values.fill(0,a,i),m.styles!==null&&m.styles.fill(0,a,i)):(m.kinds.set(e.kinds.subarray(a,i),a),m.values.set(e.values.subarray(a,i),a),e.styles!==null?(m.styles===null&&(m.styles=new Uint16Array(q)),m.styles.set(e.styles.subarray(a,i),a)):m.styles!==null&&m.styles.fill(0,a,i)),o[c]=m}return o}function wn(t){if(t===void 0)return-1;for(let n=t.length-1;n>=0;n--){const r=t[n];if(r!==void 0){for(let s=A;s>=0;s--)if(r.kinds[s]!==0||r.styles!==null&&r.styles[s]!==0)return(n<<v)+s}}return-1}function An(t,n,r){t.collab?.structure(n,r);const{at:s,n:o}=r,[c,l]=r.span,e=r.axis==="row",u=xn(t,n),a=n.columns.slice();if(e)for(let f=c;f<=Math.min(l,n.columns.length-1);f++)n.columns[f]!==void 0&&(a[f]=G(n.columns[f],s,o),o>0&&(n.maxRow=Math.min(k-1,Math.max(n.maxRow,wn(a[f])))));else{const f=n.columns.length-1,x=o>0?Math.min(f+o,w-1):f;for(let g=s;g<=x;g++){const C=g-o,S=o>0&&g<s+o?void 0:n.columns[C],M=yn(n.columns[g],S,c,l);M!==void 0&&(a[g]=M)}o>0&&(n.maxCol=Math.min(w-1,Math.max(n.maxCol,Math.min(n.maxCol+o,x))))}if(n.columns=a,o>0&&s>0&&!r.noFormat){const f=Math.min(o,(e?k:w)-s),x=Math.min(l,e?n.maxCol:n.maxRow);if(f>0&&f*(x-c+1)<=1<<22)for(let g=c;g<=x;g++){const C=e?n.cellStyle(s-1,g):n.cellStyle(g,s-1);if(C!==0)for(let S=0;S<f;S++)e?n.setStyle(s+S,g,C):n.setStyle(g,s+S,C)}}const i=f=>e?f.c0>=c&&f.c1<=l:f.r0>=c&&f.r1<=l;if(n.merges=n.merges.map(f=>i(f)?O(f,r):f).filter(f=>f!==null&&(f.r0!==f.r1||f.c0!==f.c1)),n.mergeIndex=null,n.spills){const f=new Map;for(const[x,g]of n.spills){const C=Math.floor(x/w),S=F(C,x-C*w,r),M=i(g)?O(g,r):g;S&&M&&f.set(S[0]*w+S[1],{...g,...M})}n.spills=f}if(n.valueMeta){const f=new Map;for(const[x,g]of n.valueMeta){const C=Math.floor(x/w),S=F(C,x-C*w,r);S&&f.set(S[0]*w+S[1],g)}n.valueMeta=f}const m=n.name.toUpperCase();for(const f of t.sheets){const x=f===n;if(!x&&!Q(f.formulas,m))continue;const g=new D;f.formulas.forEachCell((C,S,M)=>{const z=x?F(C,S,r):[C,S];if(z===null)return;const K=x||P(M,m)?J(M,C,S):null;K===null||!x&&!K.toUpperCase().includes(m)?g.put(z[0],z[1],M):g.put(z[0],z[1],Y(M,K,r,x,n.name))}),f.formulas=g}const y=tn(t,n,r),d=cn(n,r),p=t.engine;if(p){for(const f of p.names.values())f.text=T(f.text,r,!1,n.name);p.names.size>0&&(t.namesChanged=!0),p.nameTemplates.clear(),p.rebuild()}n.viewChanged=!0,n.revision++,t.collab?.structureDone(n);const R=(f,x,g)=>()=>R(f(n),x(n),g(n));return R(d,y,u)}function Cn(t,n,r){const s=r.at-n.c0,o=n.columns.slice(),c=n.totals?.slice()??null;if(r.n>0){const l=new Set(o.map(u=>u.toLowerCase())),e=[];for(let u=0,a=1;u<r.n;u++){for(;l.has(`column${a}`);)a++;l.add(`column${a}`),e.push(`Column${a}`)}o.splice(s,0,...e),c?.splice(s,0,...e.map(()=>null)),n.headerRows>0&&e.forEach((u,a)=>n.sheet.setCell(n.r0,r.at+a,sn,t.strings.add(u)))}else{const l=Math.max(s,0),e=Math.min(-r.n-Math.max(0,n.c0-r.at),o.length-l);o.splice(l,e),c?.splice(l,e)}n.columns=o,n.totals=c,n.columnsChanged=!0}function $(t,n){const r=t.engine;return{columns:n.columns,rows:n.rows,cols:n.cols,rowStyles:n.rowStyles,colStyles:n.colStyles,rowExtras:n.rowExtras,colExtras:n.colExtras,valueMeta:n.valueMeta,merges:n.merges,spills:n.spills,maxRow:n.maxRow,maxCol:n.maxCol,frozenRows:n.frozenRows,frozenCols:n.frozenCols,colsChanged:n.colsChanged,structureOps:n.structureOps,pageSetup:n.pageSetup?en(n.pageSetup):null,formulas:t.sheets.map(s=>[s,s.formulas]),names:r?[...r.names].map(([s,o])=>[s,{...o}]):null}}function b(t,n,r){return()=>{const s=$(t,n);n.columns=r.columns,n.rows=r.rows,n.cols=r.cols,n.rowStyles=r.rowStyles,n.colStyles=r.colStyles,n.rowExtras=r.rowExtras,n.colExtras=r.colExtras,n.valueMeta=r.valueMeta,n.merges=r.merges,n.mergeIndex=null,n.spills=r.spills,n.maxRow=r.maxRow,n.maxCol=r.maxCol,n.frozenRows=r.frozenRows,n.frozenCols=r.frozenCols,n.colsChanged=r.colsChanged,n.structureOps=r.structureOps,r.pageSetup&&(n.pageSetup=r.pageSetup);for(const[c,l]of r.formulas)c.formulas=l;const o=t.engine;return o&&(o.names=new Map(r.names),o.nameTemplates.clear(),o.rebuild()),n.revision++,b(t,n,s)}}export{ln as FORMULA,I as captureFeatures,On as featuresUndo,rn as restoreFeatures,An as shiftBand,tn as shiftFeatures,Un as shiftStructure,xn as structureUndo};
|
package/core/styles.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const d='"Aptos Narrow","Calibri","Carlito","Arial Narrow","Helvetica Neue",Arial,sans-serif',u="Aptos Narrow",m=12;function c(){return{fontName:u,fontSize:12,bold:!1,italic:!1,underline:0,strike:!1,color:null,fill:null,borders:null,numFmt:"General",hAlign:null,vAlign:null,wrap:!1,indent:0,rotation:0,shrink:!1}}const g=["pattern","gradient","quotePrefix","vertAlign","namedStyle","unlocked","hiddenFormula","readingOrder","justifyLastLine"];function x(f){return JSON.stringify(f,(t,i)=>t[0]==="_"?void 0:i)}class b{constructor(){this.list=[c()],this.index=null,this.sourceCount=0,this.deriveCache=new Map,this.hasButtons=!1,this.hasExt=!1}get(t){return this.list[t]??this.list[0]}explicitDefault(){if(this.list[this.defaultCellId]!==this.list[0]){if(this.list.length>=65535)throw new Error("Too many cell formats");this.defaultCellId=this.list.length,this.list.push(this.list[0])}return this.defaultCellId}load(t){this.list=t.length?t:[c()],this.sourceCount=t.length,this.index=null,this.hasExt=!1,this.hasButtons=!1,this.deriveCache.clear()}intern(t){if(this.index===null){this.index=new Map;for(let n=this.list.length-1;n>=0;n--)this.index.set(x(this.list[n]),n)}const i=x(t);let l=this.index.get(i);if(l===void 0){if(l=this.list.length,l>=65535)throw new Error("Too many cell formats");this.list.push(t),this.index.set(i,l)}return l}derive(t,i,l=JSON.stringify(i)){let n=this.deriveCache.get(l);n===void 0&&(n=new Map,this.deriveCache.set(l,n));let h=n.get(t);if(h===void 0){const a=this.get(t),s={...a,...i};for(const e of Object.keys(s))e[0]==="_"&&delete s[e];if(i.ext!==void 0){const e={...a.ext??{},...i.ext??{}};for(const r of Object.keys(e))e[r]===null&&delete e[r];Object.keys(e).length>0?(s.ext=e,e.buttons!==void 0&&(this.hasButtons=!0),this.hasExt=!0):delete s.ext}if(a.themeRefs||i.themeRefs){const e={...a.themeRefs};for(const[r,o]of Object.entries(i.themeRefs??{}))o!==void 0&&(e[r]=o);for(const[r,o]of[["fill","fill"],["color","color"],["fontName","font"],["pattern","patternFg"]])r in i&&!i.themeRefs?.[o]&&delete e[o];Object.keys(e).length?s.themeRefs=e:delete s.themeRefs}for(const e of g)(s[e]===null||s[e]===void 0||s[e]===!1)&&delete s[e];h=this.intern(s),n.set(t,h)}return h}}function k(f,t){const i=f.fontName===u?d:`"${f.fontName}",${d}`;return`${f.italic?"italic ":""}${f.bold?"bold ":""}${t}px ${i}`}export{u as DEFAULT_FONT,m as DEFAULT_SIZE,d as FONT_FALLBACK,b as StyleTable,k as cssFont,c as defaultStyle};
|
package/core/tables.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{patchTableColumns as
|
|
2
|
-
<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="${e}" name="${
|
|
1
|
+
import{formulaEntryLimit as H}from"../calc/parser.js";import{patchTableColumns as q,totalsChildXml as B}from"../slicers/table-file.js";import{allUndo as J,cowTx as Q,rectsTouch as A}from"../cells/block.js";import{checkBandShift as V,MSG_OFF as k}from"../cells/shift-check.js";import{unmergeCells as ee}from"./merge.js";import{shiftBand as te}from"./structure.js";import{colName as re,MAX_COLS as ne,MAX_ROWS as se,rangeRef as L,sheetPrefix as le}from"./address.js";import{columnStem as M,freeColumnName as oe,newColumnName as ae,nextName as ce,tableStem as ie,totalLabel as ue}from"./default-names.js";import{FORMULA as D,KIND_MASK as _,STR as v}from"./sheet.js";import{translateFormula as fe}from"./formula-refs.js";import{autoFilterXml as me,sortStateXml as de}from"../cells/filter-file.js";import{PRESET_DXFS as pe,PRESET_STYLES as K}from"./table-presets.js";import{resolveColor as he}from"../io/xlsx-styles.js";import{elementTableColors as we}from"../slicers/custom-styles.js";import{undoGroup as be}from"../cells/undo-group.js";import{escapeMarkup as F,xmlAttr as I}from"../io/xml-escape.js";const Ce=["FFFFFF","000000","E8E8E8","0E2841","156082","E97132","196B24","0F9ED5","A02B93","4EA72E"],P=new Set;function qe(t){P.add(t)}function ge(t,e){const r=K[t];if(!r)return null;const s=e&&e.length>=10?e:Ce,n=c=>typeof c=="string"?`#${c}`:he({a:{theme:String(c[0]),tint:c[1]?String(c[1]):void 0}},s),a={},o={};for(const[c,l,i]of r){const u=pe[l],f={};u.bold&&(f.bold=!0),u.italic&&(f.italic=!0),u.c&&(f.color=n(u.c)),u.f&&(f.fill=n(u.f));for(const m of["l","r","t","b","v","h"])u[m]&&(f.borders??={},f.borders[m]={style:u[m][0],color:n(u[m][1])});a[c]=f,i&&(o[c]=i)}return{el:a,sizes:o}}const Z=new WeakMap,$e={};function Re(t,e){if(t&&K[t]&&t.startsWith("TableStyle")){const r=e&&e.length>=10?e:$e;let s=Z.get(r);s||Z.set(r,s=new Map);let n=s.get(t);if(!n){const{el:a,sizes:o}=ge(t,e),c=l=>o[l]??1;n=we(a,[c("firstRowStripe"),c("secondRowStripe")],[c("firstColumnStripe"),c("secondColumnStripe")]),s.set(t,n)}return n}for(const r of P){const s=r(t,e);if(s)return s}return null}function Je(t,e){const r=t.r0+t.headerRows,s=t.sheet?.rows;if(!s||s.hiddenSizes===null||s.hiddenSizes.size===0)return e-r;let n=t._bandRows;if(!n||n.version!==s.version||n.top!==r||n.r1!==t.r1||n.rows!==s){const c=[];for(const l of s.hiddenSizes.keys())l>=r&&l<=t.r1&&c.push(l);c.sort((l,i)=>l-i),n={version:s.version,top:r,r1:t.r1,rows:s,list:c},t._bandRows=n}let a=0,o=n.list.length;for(;a<o;){const c=a+o>>1;n.list[c]<e?a=c+1:o=c}return e-r-a}function Se(t){const e=t.engine;return ce(ie(),r=>e.tables.has(r.toUpperCase()))}function Qe(t,e,r,s,n="TableStyleMedium2",a=[]){const o=t.engine,c=[];let l={...r};const i={...l,r0:l.r0-1,r1:l.r0-1},u=S(t,e),f=!s&&l.r0>0&&!O(e,i.r0,l.c0,l.c1)&&!u.some(d=>A(d,i))&&!e.merges.some(d=>A(d,i))&&!a.some(d=>d.anchor?.sheet===e&&d.renderedRange&&A(d.renderedRange,i)),m=!s&&!f;let h=null;return t.transact("table",d=>{if(e.protection)return;if(m){const p=l.r1+1>=se?k:V(t,e,{...l,r1:l.r0},"down",1,a);if(p)throw new Te(p)}const w=[];if(e.merges.some(p=>A(p,l))&&w.push(ee(e,l)),m?(w.push(te(t,e,{axis:"row",at:l.r0,n:1,span:[l.c0,l.c1]})),d=Q(e),l.r1++):f&&l.r0--,!s)for(let p=l.c0;p<=l.c1;p++)t.setInput(d,l.r0,p,`${M()}${p-l.c0+1}`);const b=new Set;for(let p=l.c0;p<=l.c1;p++){let $=t.editText(e,l.r0,p).trim()||`${M()}${p-l.c0+1}`,g=$;for(let R=2;b.has(g.toLowerCase());R++)g=`${$}${R}`;b.add(g.toLowerCase()),c.push(g),(g!==$||(e.kind(l.r0,p)&_)!==v)&&($=g,d.saveCell(l.r0,p),e.setCell(l.r0,p,v,t.strings.add(g)))}h={name:Se(t),sheet:e,...l,headerRows:1,totalsRows:0,columns:c,styleName:n,showRowStripes:!0,showColumnStripes:!1,showFirstColumn:!1,showLastColumn:!1,filter:{r0:l.r0,c0:l.c0,r1:l.r1,c1:l.c1,columns:new Map},isNew:!0,dirty:!0},o.tables.set(h.name.toUpperCase(),h);const C=p=>()=>(p?o.tables.set(h.name.toUpperCase(),h):o.tables.delete(h.name.toUpperCase()),o.rebuild(),C(!p));return J([...w,C(!1)])}),h}class Te extends Error{}function O(t,e,r,s){for(let n=r;n<=s;n++)if(t.kind(e,n)!==0)return!0;return!1}function S(t,e){const r=[];if(t.engine)for(const s of t.engine.tables.values())s.sheet===e&&r.push(s);return r}function Ve(t,e,r,s){for(const n of S(t,e)){const a=r===n.r1+1-0&&n.totalsRows===0&&s>=n.c0&&s<=n.c1,o=s===n.c1+1&&r>=n.r0&&r<=n.r1;if(a)return n.r1=r,n.filter&&(n.filter.r1=r),n.dirty=!0,r-1>=n.r0+n.headerRows&&t.transact("table-row",c=>{for(let l=n.c0;l<=n.c1;l++)l===s||(e.kind(r-1,l)&D)===0||e.kind(r,l)!==0||t.setInput(c,r,l,`=${fe(t.editText(e,r-1,l).slice(1),1,0)}`,{overLimitAsText:!0})}),t.engine.rebuild(),n;if(o){n.c1=s;const c=t.editText(e,n.r0,s).trim()||ae(new Set(n.columns.map(l=>l.toLowerCase())),n.columns);return n.columns.push(c),n.filter&&(n.filter.c1=s),e.kind(n.r0,s)===0&&e.setCell(n.r0,s,v,t.strings.add(c)),n.dirty=!0,n.columnsChanged=!0,t.engine.rebuild(),n}}return null}function ke(t,e,r){for(const s of S(t,e)){if(r.r0!==s.r1+1||s.totalsRows!==0||r.c0<s.c0||r.c0>s.c1)continue;const n=r.r1;if(S(t,e).some(o=>o!==s&&o.r0<=n&&o.r1>=r.r0&&o.c0<=s.c1&&o.c1>=s.c0))return null;const a={r1:s.r1,filter:s.filter?{...s.filter}:null};return t.transact("table-expand",()=>{const o=i=>{s.r1=i.r1,s.filter=i.filter?{...i.filter}:null,s.dirty=!0,t.engine.rebuild()},c={r1:n,filter:s.filter?{...s.filter,r1:n}:null};o(c);const l=(i,u)=>()=>(o(i),l(u,i));return l(a,c)}),s}return null}function et(t,e,r,s,n,a){if(!n.startsWith("="))return!1;for(const o of S(t,e)){if(s<o.c0||s>o.c1||r<=o.r0||r>o.r1-o.totalsRows)continue;const c=o.r0+o.headerRows,l=o.r1-o.totalsRows;for(let i=c;i<=l;i++)if(i!==r&&e.kind(i,s)!==0)return!1;return l===c?!1:(t.transact("calculated-column",i=>{for(let u=c;u<=l;u++)u!==r&&t.setInput(i,u,s,`=${a(n.slice(1),u-r,0)}`,{overLimitAsText:!0})}),!0)}return!1}const j=(t,e)=>{const r=t.totals?.[e];return r?r.label!==void 0?` totalsRowLabel="${I(r.label)}"`:` totalsRowFunction="${r.fn}"`:""},W=t=>`<tableStyleInfo name="${I(t.styleName??"TableStyleMedium2")}" showFirstColumn="${t.showFirstColumn?1:0}" showLastColumn="${t.showLastColumn?1:0}" showRowStripes="${t.showRowStripes===!1?0:1}" showColumnStripes="${t.showColumnStripes?1:0}"/>`,xe=t=>L({r0:t.r0,c0:t.c0,r1:t.r1-t.totalsRows,c1:t.c1}),Y=t=>t.filter&&t.headerRows>0?me({...t.filter,r0:t.r0,c0:t.c0,r1:t.r1-t.totalsRows,c1:t.c1},!1)+de(t.filter.sortState):"",G=t=>`${t.headerRows===0?' headerRowCount="0"':""}${t.totalsRows?` totalsRowCount="${t.totalsRows}"`:' totalsRowShown="0"'}`;function tt(t,e){const r=t.columns.map((n,a)=>{const o=B(t,a),c=`<tableColumn id="${t.columnIds?.[a]??a+1}" name="${I(n)}"${j(t,a)}`;return o?`${c}>${o}</tableColumn>`:`${c}/>`}).join(""),s=Y(t);return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
2
|
+
<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="${e}" name="${F(t.name)}" displayName="${F(t.name)}" ref="${L(t)}"${G(t)}>${s}<tableColumns count="${t.columns.length}">${r}</tableColumns>${W(t)}</table>`}function rt(t){return{name:t.name,ref:L(t),filterRef:t.filter&&t.headerRows>0?xe(t):null,filterXml:Y(t),counts:G(t),styleInfo:W(t),totals:t.totals?t.columns.map((e,r)=>j(t,r)):null,totalsChild:t.totals?t.columns.map((e,r)=>B(t,r)):null}}function nt(t,e){let r=t.replace(/<table\b[^>]*>/,s=>s.replace(/\bname="[^"]*"/,`name="${F(e.name)}"`).replace(/\bdisplayName="[^"]*"/,`displayName="${F(e.name)}"`).replace(/\bref="[^"]*"/,`ref="${e.ref}"`).replace(/\s(?:headerRowCount|totalsRowCount|totalsRowShown)="[^"]*"/g,"").replace(/\s*(\/?)>$/,`${e.counts}$1>`));return r=r.replace(/<autoFilter\b[^>]*\/>|<autoFilter\b[\s\S]*?<\/autoFilter>/,"").replace(/<sortState\b[^>]*\/>|<sortState\b[\s\S]*?<\/sortState>/,""),e.filterXml&&(r=r.replace("<tableColumns",`${e.filterXml}<tableColumns`)),/<tableStyleInfo\b/.test(r)?r=r.replace(/<tableStyleInfo\b[^>]*\/>/,e.styleInfo):r=r.replace("</tableColumns>",`</tableColumns>${e.styleInfo}`),e.totals&&(r=q(r,e)),r}const ye=/[[\]#']/g,U=t=>t.replace(ye,"'$&"),ve=/^[A-Za-z_\\][A-Za-z0-9_.\\]*$/;function z(t,e){const r=[];for(const s of t.sheets){const n=new Map;for(const[a,o]of s.formulas){const c=o.f??o.sf;if(typeof c!="string")continue;const l=o.f===void 0&&o.base!==void 0;let i=l?n.get(o):void 0;if(i===void 0){const u=e(c,s,Math.floor((l?o.base:a)/ne));i=u===c?null:o.f!==void 0?{...o,f:u,tpl:void 0}:{...o,sf:u,tpl:void 0},l&&n.set(o,i)}i!==null&&r.push([s.formulas,a,o,i])}}for(const[s,n]of t.engine.names){const a=e(n.text,null,0,s);a!==n.text&&r.push([t.engine.names,s,n,{...n,text:a}])}for(const s of t.engine.tables.values())s.totals?.forEach((n,a)=>{if(n?.fn!=="custom"||!n.formula)return;const o=e(n.formula,s.sheet,s.r1);o!==n.formula&&r.push([{set:(c,l)=>{s.totals[c]=l,s.dirty=!0}},a,n,{...n,formula:o}])});return t.formulasEdited=!0,r.some(s=>s[0]===t.engine.names)&&(t.namesChanged=!0),E(r,3),r}const E=(t,e)=>{for(const r of t)r[0].set(r[1],r[e])};function T(t,e,r,s,{rebuild:n=!1}={}){const a=t.engine;t.transact(r,o=>{const c={...e},l=s(o),i={...e};e.dirty=!0,n&&a.rebuild();const u=(f,m,h)=>()=>(Object.assign(e,f),e.dirty=!0,h?.(),n&&a.rebuild(),u(m,f,h));return u(c,i,l)})}function st(t,e,r,s){T(t,e,"table-option",()=>{e[r]=s})}function lt(t,e,r){r&&e.headerRows===0||T(t,e,"table-filter",()=>{e.filter=r?{r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1,columns:new Map}:null})}function ot(t,e,r){const s=t.engine;if(!ve.test(r)||/^[A-Za-z]{1,3}[0-9]+$/.test(r)||/^[Rr][Cc]?$|^[Cc]$/.test(r))return"That isn't a valid table name.";const n=r.toUpperCase();if(n===e.name.toUpperCase()&&r===e.name)return null;if(s.tables.has(n)&&s.tables.get(n)!==e)return"Another table already uses that name.";if(s.names.has(n))return"A defined name already uses that name.";const a=e.name;return t.transact("table-name",()=>{const o=new RegExp(`(^|[^A-Za-z0-9_.\\\\])${a.replace(/[.\\]/g,"\\$&")}(?=\\[)`,"gi"),c=z(t,f=>f.replace(o,`$1${r}`)),l=(f,m,h)=>{s.tables.delete(f.toUpperCase()),e.name=m,s.tables.set(m.toUpperCase(),e),e.dirty=!0,E(c,h),s.rebuild()};l(a,r,3);const i=()=>(l(a,r,3),u),u=()=>(l(r,a,2),i);return u}),null}const Ee={average:101,countNums:102,count:103,max:104,min:105,stdDev:107,sum:109,var:110};function Ae(t,e,r){if(!r)return null;if(r.label!==void 0)return r.label;if(r.fn==="custom")return r.formula?`=${r.formula}`:null;const s=Ee[r.fn];return s?`=SUBTOTAL(${s},${t.name}[${U(t.columns[e])}])`:null}function at(t,e,r){const{sheet:s}=e;if(r===e.totalsRows>0)return null;if(r){const a=e.r1+1;if(O(s,a,e.c0,e.c1))return"Clear the row under the table to add a total row.";const o=e.columns.map((l,i)=>e.totals?.[i]??null);if(!o.some(Boolean)&&(o[0]={label:ue()},o.length>1)){let l=!1;for(let i=e.r0+e.headerRows;i<=e.r1&&!l;i++)l=(s.kind(i,e.c1)&_)===1;o[o.length-1]={fn:l?"sum":"count"}}const c=o.map((l,i)=>Ae(e,i,l));for(let l=0;l<c.length;l++){if(o[l]?.label!==void 0||!c[l])continue;const i=H(c[l].slice(1));if(i)return i}return T(t,e,"table-totals",l=>{e.totals=o,c.forEach((i,u)=>{o[u]?.label!==void 0?t.setRichInput(l,a,e.c0+u,i,null):i&&t.setInput(l,a,e.c0+u,i)}),e.totalsRows=1,e.r1=a,e.columnsChanged=e.source!==!0},{rebuild:!0}),null}const n=e.r1;return T(t,e,"table-totals",a=>{for(let o=e.c0;o<=e.c1;o++)t.setInput(a,n,o,"");e.totalsRows=0,e.r1=n-1},{rebuild:!0}),null}function ct(t,e,r){if(r===e.headerRows>0)return null;const{sheet:s}=e;return r?e.r0===0||O(s,e.r0-1,e.c0,e.c1)?"Clear the row above the table to show its headers.":(T(t,e,"table-header",n=>{e.r0-=1,e.headerRows=1,e.columns.forEach((a,o)=>t.setRichInput(n,e.r0,e.c0+o,a,null)),e.filter={r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1,columns:new Map}},{rebuild:!0}),null):(T(t,e,"table-header",n=>{for(let a=e.c0;a<=e.c1;a++)t.setInput(n,e.r0,a,"");e.r0+=1,e.headerRows=0,e.filter=null},{rebuild:!0}),null)}function it(t,e,r){const{sheet:s}=e;if(r.r0!==e.r0)return"The header row must stay in the same row.";if(r.c0!==e.c0)return"The table must keep its first column.";if(r.r1<r.r0+e.headerRows+e.totalsRows)return"The table needs at least one data row.";for(const n of S(t,s))if(n!==e&&n.r0<=r.r1&&n.r1>=r.r0&&n.c0<=r.c1&&n.c1>=r.c0)return"A table can't overlap another table.";return T(t,e,"table-resize",()=>{const n=r.c1-r.c0+1,a=e.columns.slice(0,n);for(let o=a.length;o<n;o++){const c=e.c0+o;let l=e.headerRows?t.editText(s,e.r0,c).trim():"";l||(l=`${M()}${o+1}`),a.push(l)}e.columns=a,e.r1=r.r1,e.c1=r.c1,e.filter&&(e.filter={r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1,columns:new Map}),e.columnsChanged=!0},{rebuild:!0}),null}function Fe(t,e,r){const{sheet:s}=e,n=e.r1-e.r0+1,a=e.c1-e.c0+1,o=new Map,c=(i,u,f,m)=>{const h=(i-e.r0)*a+(u-e.c0);let d=o.get(h);d||o.set(h,d={}),d[f]=m};for(const i of r.areas(e,e.r0,e.r1,e.c0,e.c1)){const u=i.borders;for(let f=Math.max(i.r0,e.r0);f<=Math.min(i.r1,e.r1);f++)for(let m=Math.max(i.c0,e.c0);m<=Math.min(i.c1,e.c1);m++)u.t&&f===i.r0&&c(f,m,"t",u.t),u.b&&f===i.r1&&c(f,m,"b",u.b),u.l&&m===i.c0&&c(f,m,"l",u.l),u.r&&m===i.c1&&c(f,m,"r",u.r),u.h&&f<i.r1&&c(f,m,"b",u.h),u.v&&m<i.c1&&c(f,m,"r",u.v)}const l=new Map;t.transact("format",i=>{for(let u=0;u<n;u++){const f=e.r0+u;for(let m=0;m<a;m++){const h=e.c0+m,d=r.format(e,f,h),w=o.get(u*a+m),b=s.style(f,h),C=t.styles.get(b),p={};if(d.fill&&!C.fill&&(p.fill=d.fill),d.color&&!C.color&&(p.color=d.color),d.bold&&!C.bold&&(p.bold=!0),d.italic&&!C.italic&&(p.italic=!0),w){const x=C.borders??{},X={l:x.l??null,r:x.r??null,t:x.t??null,b:x.b??null};let N=!1;for(const y of["l","r","t","b"])w[y]&&!x[y]&&(X[y]={style:w[y].style,color:w[y].color},N=!0);N&&(p.borders=X)}const $=JSON.stringify(p);if($==="{}")continue;const g=`${b}|${$}`;let R=l.get(g);R===void 0&&l.set(g,R=t.styles.derive(b,p,$)),R!==b&&(i.saveCell(f,h),s.setStyle(f,h,R))}}})}function ut(t,e){be(t,"Convert to Range",()=>Le(t,e))}function Le(t,e){const r=t.engine,{sheet:s}=e,n=Re(e.styleName,t.theme),a=t.activeSheet;t.activeSheet=t.sheets.indexOf(s),n?.format&&Fe(t,e,n),t.activeSheet=a;const o=e.name.toUpperCase(),c=new RegExp(`(^|[^A-Za-z0-9_.\\\\])${e.name.replace(/[.\\]/g,"\\$&")}(\\[(?:[^\\[\\]']|'.|\\[(?:[^\\[\\]']|'.)*\\])*\\])`,"gi");t.transact("table-convert",()=>{const l=z(t,(m,h,d)=>m.replace(c,(w,b,C)=>{const p=r.tableSpecToA1(e,C,d);return p===null?w:`${b}${h===s?"":le(s.name)}${p}`})),i=e.source===!0&&e.part?{part:e.part,sheetIndex:t.sheets.indexOf(s)}:null,u=()=>{r.tables.delete(o),i&&(t.removedTables??=[]).push(i),E(l,3),r.rebuild()},f=()=>(r.tables.set(o,e),i&&(t.removedTables=t.removedTables.filter(m=>m!==i)),E(l,2),r.rebuild(),()=>(u(),f));return u(),f})}function Me(t,e,r,s){const n=t.toLowerCase(),a=`${e.toLowerCase()}[`;let o="",c=0;for(let l=n.indexOf(a);l>=0;l=n.indexOf(a,l+1)){const i=l+a.length-1;let u=0,f=i;for(;f<t.length;f++){const d=t[f];if(d==="'")f++;else if(d==="[")u++;else if(d==="]"&&--u===0)break}const m=t.slice(i,f+1),h=m.split(`[${r}]`).join(`[${s}]`);h!==m&&(o+=t.slice(c,i)+h,c=f+1)}return c===0?t:o+t.slice(c)}function _e(t,e,r,s){const n=e.columns[r],a=U(n),o=U(s),c=z(t,f=>f.includes("[")?Me(f,e.name,a,o):f),l=(f,m)=>{e.columns=e.columns.map((h,d)=>d===r?f:h),e.columnsChanged=!0,e.dirty=!0,E(c,m),t.engine?.rebuild()};l(s,3);const i=()=>(l(s,3),u),u=()=>(l(n,2),i);return u}function ft(t,e,r){let s=null;const{sheet:n}=e;for(const a of S(t,n))if(!(a.headerRows===0||a.dataSheet))for(let o=0;o<r.count;o++){if(r.rows[o]!==a.r0||r.cols[o]<a.c0||r.cols[o]>a.c1)continue;const c=r.cols[o],l=c-a.c0,i=n.kind(a.r0,c);let u=i===0?"":String(t.engine.read(n,a.r0,c)??"").trim();const f=new Set(a.columns.filter((w,b)=>b!==l).map(w=>w.toLowerCase()));if(u==="")u=oe(f);else if(f.has(u.toLowerCase())){const w=u;let b=2;for(;f.has(`${w}${b}`.toLowerCase());)b++;u=`${w}${b}`}if(((i&_)!==v||(i&D)!==0||t.strings.get(n.value(a.r0,c))!==u)&&(e.saveCell(a.r0,c),n.setFormula(a.r0,c,null),n.setCell(a.r0,c,v,t.strings.add(u))),a.columns[l]===u)continue;const m=_e(t,a,l,u),h=s,d=(w,b)=>b?()=>d(w(),b()):w;s=d(m,h)}return s}const mt=[...Array.from({length:21},(t,e)=>`TableStyleLight${e+1}`),...Array.from({length:28},(t,e)=>`TableStyleMedium${e+1}`),...Array.from({length:11},(t,e)=>`TableStyleDark${e+1}`)];export{Ee as SUBTOTAL_CODE,mt as TABLE_STYLE_NAMES,Te as TableCreationError,Je as bandRow,re as colName,ut as convertTableToRange,Qe as createTable,et as fillCalculatedColumn,ke as growTableOver,Ve as maybeExpandTable,Se as nextTableName,nt as patchTableXml,ge as presetElements,ot as renameTable,_e as renameTableColumn,it as resizeTable,z as rewriteFormulas,qe as setCustomTableResolver,lt as setTableFilterButton,ct as setTableHeaderRow,st as setTableOption,at as setTableTotals,U as structuredColumn,ft as syncTableHeaders,Re as tableColors,rt as tablePatch,tt as tableXml,S as tablesOf,Ae as totalInput};
|
package/core/whatif.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FORMULA as H,KIND_MASK as K,NUM as b,STR as
|
|
1
|
+
import{FORMULA as H,KIND_MASK as K,NUM as b,STR as $}from"./sheet.js";import{cellRef as I,MAX_COLS as W,parseRangeRef as F,rangeRef as X}from"./address.js";async function Z(t,n,r,e,a,{maxIter:o=200,tolerance:l=.001}={}){const u=t.engine,g=async d=>{t.transact("goal-seek",S=>{S.saveCell(e.row,e.col),n.setCell(e.row,e.col,b,d)}),await u.whenIdle();const x=u.read(n,r.row,r.col);return typeof x=="number"?x-a:NaN},s=()=>t.undoStack.length,c=s(),f=n.value(e.row,e.col);let p=f,i=await g(p),v=f===0?1:f*1.01,M=await g(v),E={x:p,f:i},L=null,h=null;for(let d=0;d<o&&((Math.abs(M)<Math.abs(E.f)||Number.isNaN(E.f))&&(E={x:v,f:M}),!(Math.abs(M)<=l));d++){i*M<0&&(L=i<0?p:v,h=i<0?v:p);let x=M===i?v*1.5+1:v-M*(v-p)/(M-i);if(L!==null&&(!Number.isFinite(x)||x<Math.min(L,h)||x>Math.max(L,h))&&(x=(L+h)/2),!Number.isFinite(x))break;p=v,i=M,v=x,M=await g(v)}for(;s()>c;)t.undoStack.pop();t.transact("goal-seek",d=>{d.saveCell(e.row,e.col),n.setCell(e.row,e.col,b,f)});const m=t.undoStack.pop();return t.transact("goal-seek",d=>{d.saveCell(e.row,e.col),n.setCell(e.row,e.col,b,E.x)}),await u.whenIdle(),{value:E.x,found:Math.abs(E.f)<=l,result:u.read(n,r.row,r.col)}}const P=t=>{if(t===void 0)return 0;const n=t.indexOf('outlineLevel="');return n<0?0:t.charCodeAt(n+14)-48},U=(t,n)=>t.rowExtras===null?0:P(t.rowExtras.get(n));function j(t,n,r){t.rowExtras||(t.rowExtras=new Map);const e=(t.rowExtras.get(n)??"").replace(/\s*outlineLevel="\d+"/,"").trim(),a=r>0?`${e} outlineLevel="${r}"`.trim():e;a?t.rowExtras.set(n,a):t.rowExtras.delete(n)}const _=(t,n)=>t.colExtras===null?0:P(t.colExtras.get(n));function z(t,n,r){t.colExtras||(t.colExtras=new Map);const e=(t.colExtras.get(n)??"").replace(/\s*outlineLevel="\d+"/,"").trim(),a=r>0?`${e} outlineLevel="${r}"`.trim():e;a?t.colExtras.set(n,a):t.colExtras.delete(n)}function C(t,n,r,e,a){for(let o=r;o<=e;o++)n==="row"?j(t,o,Math.max(0,Math.min(7,U(t,o)+a))):z(t,o,Math.max(0,Math.min(7,_(t,o)+a)));t.outlineVersion=(t.outlineVersion??0)+1,n==="col"&&(t.colsChanged=!0),t.revision++}function tt(t,n){let r=0;const e=n==="row"?t.rowExtras:t.colExtras;if(e)for(const a of e.values()){const o=/outlineLevel="(\d+)"/.exec(a);o&&(r=Math.max(r,Number(o[1])))}return r}function nt(t,n,r){return n==="row"?U(t,r):_(t,r)}function rt(t,n,r){const e=n==="row"?t.rowExtras:t.colExtras,a=n==="row"?t.rows:t.cols;if(e){for(const[o,l]of e){const u=/outlineLevel="(\d+)"/.exec(l);u&&a.setHidden(o,Number(u[1])>=r)}n==="col"&&(t.colsChanged=!0),t.revision++}}function et(t,n,r,e,a,o){const l=[],u={1:"Average",2:"Count",3:"Count",4:"Max",5:"Min",6:"Product",7:"StdDev",8:"StdDevp",9:"Total",10:"Var",11:"Varp"}[a],g=c=>(n.kind(c,e)&K)===$?t.strings.get(n.value(c,e)):String(n.value(c,e));let s=r.r0+1;for(let c=r.r0+1;c<=r.r1+1;c++)(c>r.r1||g(c)!==g(s))&&(l.push({afterRow:c-1,from:s,to:c-1,title:`${g(s)} ${u}`}),s=c);return{groups:l,functionNum:a,sumCols:o,groupCol:e,grandTitle:`Grand ${u}`}}function ot(t,n,r,e,a){const o={r0:r.r0+1,c0:r.c0+1,r1:r.r1,c1:r.c1},l=e&&a,u={t:"dataTable",ref:X(o),dt2D:l?"1":"0",dtr:e?"1":"0",r1:I((e??a).row,(e??a).col)};l&&(u.r2=I(a.row,a.col));const g=t.engine,s={sheet:n,row:o.r0,col:o.c0,info:u};t.transact("data-table",c=>{for(let i=o.r0;i<=o.r1;i++)for(let v=o.c0;v<=o.c1;v++)c.saveCell(i,v),n.setFormula(i,v,null),n.setCell(i,v,b,0);n.setFormula(o.r0,o.c0,u),n.setCell(o.r0,o.c0,H|b,0),t.formulasEdited=!0,g.dataTables.push(s),g.tablesDirty=!0;const f=()=>(g.dataTables=g.dataTables.filter(i=>i!==s),p),p=()=>(g.dataTables.push(s),g.tablesDirty=!0,f);return f})}const q=(t,n,r,e)=>{const a=n.kind(r,e)&K;return a===0?"":a===$?t.strings.get(n.value(r,e)):String(n.value(r,e))};function at(t,n,r,e){const a=[],o=new Set;for(const l of r.split(/[\s,;]+/)){const u=F(l.replace(/\$/g,""));if(u)for(let g=u.r0;g<=u.r1&&a.length<32;g++)for(let s=u.c0;s<=u.c1&&a.length<32;s++){const c=I(g,s);if(o.has(c))continue;o.add(c);const f=e?.cells.find(p=>p.r===c);a.push({r:c,val:f?f.val:q(t,n,g,s)})}}return a}function ct(t,n,r){t.transact("scenario",e=>{for(const{r:a,val:o}of r.cells){const l=F(a);l&&t.setInput(e,l.r0,l.c0,o,{overLimitAsText:!0})}})}function st(t,n,r,e){const a=t.engine,o=[["Scenario Summary","Current Values",...r.map(s=>s.name)]],l=[];for(const s of r)for(const c of s.cells)l.includes(c.r)||l.push(c.r);const u=s=>{const c=F(s);return{row:c.r0,col:c.c0}};o.push(["Changing Cells:"]);for(const s of l){const{row:c,col:f}=u(s);o.push([s,q(t,n,c,f),...r.map(p=>p.cells.find(i=>i.r===s)?.val??"")])}if(e.length>0){o.push(["Result Cells:"]);const s=r.map(c=>a.evaluateWith(n,c.cells.map(f=>({...u(f.r),text:f.val})),()=>e.map(({row:f,col:p})=>a.read(n,f,p))));e.forEach(({row:c,col:f},p)=>{o.push([I(c,f),String(a.read(n,c,f)??""),...s.map(i=>String(i[p]??""))])})}const g=t.addSheet();return t.transact("scenario-summary",s=>{o.forEach((c,f)=>c.forEach((p,i)=>{p!==""&&t.setInput(s,f,i,String(p),{overLimitAsText:!0})}))}),g}const w=t=>t.filter(n=>typeof n=="number"),R=t=>t.reduce((n,r)=>n+r,0),B=t=>R(t)/t.length,O=(t,n)=>{const r=B(t);return R(t.map(e=>(e-r)**2))/n},J={Sum:t=>R(w(t)),Count:t=>t.filter(n=>n!==null&&n!=="").length,Average:t=>w(t).length?B(w(t)):null,Max:t=>w(t).length?Math.max(...w(t)):0,Min:t=>w(t).length?Math.min(...w(t)):0,Product:t=>w(t).length?w(t).reduce((n,r)=>n*r,1):0,"Count Numbers":t=>w(t).length,StdDev:t=>w(t).length>1?Math.sqrt(O(w(t),w(t).length-1)):null,StdDevp:t=>w(t).length?Math.sqrt(O(w(t),w(t).length)):null,Var:t=>w(t).length>1?O(w(t),w(t).length-1):null,Varp:t=>w(t).length?O(w(t),w(t).length):null};function lt(t,n,r,e,a,{topRow:o=!1,leftCol:l=!1}={}){const u=t.engine,g=J[a],s=[],c=[],f=new Map,p=new Map,i=new Map,v=(h,m,d)=>{const x=String(d).toLowerCase();let S=h.get(x);return S===void 0&&(S=m.length,h.set(x,S),m.push(d)),S};for(const{sheet:h,range:m,read:d}of e){const x=d??((y,T)=>u.read(h,y,T)),S=m.r0+(o?1:0),N=m.c0+(l?1:0);for(let y=S;y<=m.r1;y++){const T=l?x(y,m.c0):y-S;if(l&&(T===null||T===""))continue;const k=v(f,s,T);for(let D=N;D<=m.c1;D++){const A=o?x(m.r0,D):D-N;if(o&&(A===null||A===""))continue;const G=v(p,c,A),V=k*16384+G;i.has(V)||i.set(V,[]),i.get(V).push(x(y,D))}}}const M=r.row+(o?1:0),E=r.col+(l?1:0),L=(h,m,d,x)=>{h.saveCell(m,d),n.setFormula(m,d,null),typeof x=="number"?n.setCell(m,d,b,x):n.setCell(m,d,$,t.strings.add(String(x)))};return t.transact("consolidate",h=>{o&&c.forEach((m,d)=>L(h,r.row,E+d,m)),l&&s.forEach((m,d)=>L(h,M+d,r.col,m));for(const[m,d]of i){const x=Math.floor(m/16384),S=m-x*16384,N=g(d);N!==null&&L(h,M+x,E+S,N)}}),{rows:s.length,cols:c.length}}export{J as CONSOLIDATE_FUNCTIONS,W as MAX_COLS,C as changeOutline,lt as consolidate,ot as createDataTable,Z as goalSeek,tt as maxOutlineLevel,nt as outlineLevel,st as scenarioSummary,at as scenarioValues,rt as showOutlineLevel,ct as showScenario,et as subtotalPlan};
|
package/core/workbook.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expandBareTables as K}from"../slicers/structured.js";import{syncTableHeaders as j}from"./tables.js";import{BOOL as F,CHUNK_BITS as I,CHUNK_MASK as J,EMPTY as _,ERR as E,ERRORS as W,FORMULA as k,DIRTY as N,EVALUATING as z,KIND_MASK as Z,NUM as P,Sheet as A,SPILL as Y,STR as R}from"./sheet.js";import{cellRef as X,MAX_COLS as w,MAX_ROWS as B,quoteSheetName as Q,rangeRef as ee,renameSheetInFormula as D,sheetReferencePattern as te}from"./address.js";import{translateFormula as se}from"./formula-refs.js";import{sheetStem as q}from"./default-names.js";import{StringTable as ne}from"./strings.js";import{StyleTable as ie}from"./styles.js";import{parseInput as G}from"./input.js";import{noteChanges as H}from"./changes.js";import{overrideRuns as le}from"../cells/rich-runs.js";import{sheetRenameHooks as re}from"./sparse.js";import{expandStructured as oe,toDisplayFormula as V,toFileFormula as ae}from"../calc/parser.js";const he=200,ce=new Set(["entry","clear","format","borders","fill"]);class ue{constructor(){this.ids=new Int32Array(1024),this.list=[]}set(t,e){if(t>=this.ids.length){let l=this.ids.length*2;for(;l<=t;)l*=2;const n=new Int32Array(l);n.set(this.ids),this.ids=n}const s=this.list.length;(s===0||this.list[s-1]!==e)&&this.list.push(e),this.ids[t]=this.list.length}get(t){const e=t<this.ids.length?this.ids[t]:0;return e===0?void 0:this.list[e-1]}}class b{constructor(){this.capacity=1024,this.count=0,this.rows=new Uint32Array(this.capacity),this.cols=new Uint16Array(this.capacity),this.kinds=new Uint8Array(this.capacity),this.styles=new Uint16Array(this.capacity),this.values=new Float64Array(this.capacity),this.formulas=null,this.vms=null}_grow(){const t=this.capacity*2,e=(s,l)=>{const n=new s(t);return n.set(l),n};this.rows=e(Uint32Array,this.rows),this.cols=e(Uint16Array,this.cols),this.kinds=e(Uint8Array,this.kinds),this.styles=e(Uint16Array,this.styles),this.values=e(Float64Array,this.values),this.capacity=t}push(t,e,s){this.count===this.capacity&&this._grow();const l=this.count++,n=t.kind(e,s)&~(N|z);if(this.rows[l]=e,this.cols[l]=s,this.kinds[l]=n,this.styles[l]=t.cellStyle(e,s),this.values[l]=t.value(e,s),n&k&&(this.formulas===null&&(this.formulas=new ue),this.formulas.set(l,t.formula(e,s))),t.valueMeta!==null){const i=t.valueMeta.get(e*w+s);i!==void 0&&(this.vms??=new Map).set(l,i)}}}class Re{constructor(){this.sheets=[new A(`${q()}1`)],this.activeSheet=0,this.strings=new ne,this.styles=new ie,this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.source=null,this.formulasEdited=!1,this.edits=0,this._dirty=!1,this.engine=null,this.selectedSheets=null}get sheet(){return this.sheets[this.activeSheet]}get dirty(){return this._dirty}set dirty(t){t&&this.edits++,this._dirty=!!t}onChange(t){this.listeners.add(t)}_emit(t){this.dirty=!0;for(const e of this.listeners)e(t)}addSheet(t){const e=q();let s=1,l=t??`${e}${s}`;const n=o=>this.sheets.some(r=>r.name.toLowerCase()===o.toLowerCase());for(;n(l);)l=`${e}${++s}`;const i=new A(l);return this.sheets.push(i),this.activeSheet=this.sheets.length-1,this.engine?.sheetsChanged(),this._emit("sheets"),i}deleteSheet(t){if(this.sheets.filter(s=>!s.hidden).length<=1)return!1;this._shrink3D(t);const[e]=this.sheets.splice(t,1);if(this.selectedSheets?.delete(e),this._forgetSheet(e,t),this.engine)for(const[s,l]of this.engine.tables)l.sheet===e&&this.engine.tables.delete(s);for(this._reindexNames(s=>s===t?-1:s>t?s-1:s),this.activeSheet>=this.sheets.length&&(this.activeSheet=this.sheets.length-1);this.sheets[this.activeSheet].hidden;)this.activeSheet=(this.activeSheet+1)%this.sheets.length;return this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),!0}_forgetSheet(t,e){const s=n=>n.sheet===t||n.sheet===void 0&&n.sheetIndex===e||(n.extra?.parts??[]).some(s),l=n=>{n.sheetIndex>e&&n.sheetIndex--;for(const i of n.extra?.parts??[])l(i)};for(const n of[this.undoStack,this.redoStack]){const i=n.filter(o=>!s(o));i.forEach(l),n.splice(0,n.length,...i)}}moveSheet(t,e){if(t===e)return;const s=this.sheet,[l]=this.sheets.splice(t,1);this.sheets.splice(e,0,l),this.activeSheet=this.sheets.indexOf(s);const n=o=>o===t?e:t<e?o>t&&o<=e?o-1:o:o>=e&&o<t?o+1:o,i=o=>{o.sheetIndex=n(o.sheetIndex);for(const r of o.extra?.parts??[])i(r)};for(const o of this.undoStack)i(o);for(const o of this.redoStack)i(o);this.structureEdited=!0,this._reindexNames(n),this.engine?.orderChanged(),this._emit("sheets")}_copyScopedNames(t,e,s){const{engine:l}=this;if(!l||l.names.size===0)return;const n=`${t}!`;let i=!1;for(const[o,r]of[...l.names])o.startsWith(n)&&(l.names.set(`${t+1}!${o.slice(n.length)}`,{...r,text:D(r.text,e.name,s.name)}),i=!0);i&&(this.namesChanged=!0)}_reindexNames(t){const{engine:e}=this;if(!e||e.names.size===0)return;const s=[];let l=!1;for(const[n,i]of e.names){const o=n.indexOf("!"),r=o<0?0:t(Number(n.slice(0,o)));o>=0&&r!==Number(n.slice(0,o))&&(l=!0),o<0?s.push([n,i]):r>=0&&s.push([`${r}!${n.slice(o+1)}`,i])}if(l){e.names.clear();for(const[n,i]of s)e.names.set(n,i);e.nameTemplates.clear(),this.namesChanged=!0,e.rebuild()}}duplicateSheet(t){const e=this.sheets[t];let l=`${e.name} (2)`,n=2;for(;this.sheets.some(a=>a.name.toLowerCase()===l.toLowerCase());)l=`${e.name} (${++n})`;const i=new A(l);e.columns.forEach((a,u)=>{const m=[];a.forEach((h,y)=>{m[y]={kinds:h.kinds.slice(),values:h.values.slice(),styles:h.styles?h.styles.slice():null}}),i.columns[u]=m}),i.maxRow=e.maxRow,i.maxCol=e.maxCol,i.rows=e.rows.shifted(0,0),i.cols=e.cols.shifted(0,0);const o=new Map;e.formulas.forEachCell((a,u,m)=>{let h=o.get(m);h===void 0&&(h={...m,tpl:void 0},o.set(m,h)),i.setFormula(a,u,h)}),i.merges=e.merges.map(a=>({...a})),i.rowStyles=e.rowStyles?new Map(e.rowStyles):null,i.colStyles=e.colStyles?new Map(e.colStyles):null,i.frozenRows=e.frozenRows,i.frozenCols=e.frozenCols,i.showGridlines=e.showGridlines,i.cellTypes=e.cellTypes?new Map(e.cellTypes):null,i.sparkRules=e.sparkRules,i.cellDropdowns=e.cellDropdowns?new Map(e.cellDropdowns):null,i.cellTags=e.cellTags?new Map(e.cellTags):null,i.cellButtons=e.cellButtons?new Map(e.cellButtons):null,i.cellStates=e.cellStates?e.cellStates.slice():null,i.autoMerges=e.autoMerges?e.autoMerges.map(a=>({...a})):null,i.background=e.background,i.outlineColumn=e.outlineColumn?{...e.outlineColumn}:null,i.frozenTrailingRows=e.frozenTrailingRows,i.frozenTrailingCols=e.frozenTrailingCols,i.hideZeros=e.hideZeros,i.hideHeadings=e.hideHeadings,i.isChartSheet=e.isChartSheet,i.hideOutline=e.hideOutline,i.gridColorId=e.gridColorId,i.areaOffset=e.areaOffset,i.selectionPolicy=e.selectionPolicy,i.selectionUnit=e.selectionUnit,i.gridlineAxes=e.gridlineAxes,i.gridColor=e.gridColor,i.tabStyles=e.tabStyles;const r=x;return i.cf=r(e.cf),i.validations=r(e.validations),i.comments=r(e.comments),i.threads=r(e.threads),i.hyperlinks=e.hyperlinks?e.hyperlinks.map(a=>({...r({...a,_ranges:void 0})})):e.hyperlinks,i.autoFilter=r(e.autoFilter),i.filteredRows=e.filteredRows?new Set(e.filteredRows):e.filteredRows,i.pageSetup=r(e.pageSetup),i.tabColor=e.tabColor,i.protection=r(e.protection),i.rtl=e.rtl,i.zoom=e.zoom,i.valueMeta=e.valueMeta?new Map(e.valueMeta):null,i.colsChanged=!0,i.viewChanged=!0,this.sheets.splice(t+1,0,i),this.activeSheet=t+1,this._reindexNames(a=>a>t?a+1:a),this._copyScopedNames(t,e,i),this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),i}sheetNameProblem(t,e){const s=e.trim().slice(0,31);return!s||/[\\/?*[\]:]/.test(s)||/^'|'$/.test(s)?"rules":s.toLowerCase()==="history"?"reserved":this.sheets.some((l,n)=>n!==t&&l.name.toLowerCase()===s.toLowerCase())?"taken":null}renameSheet(t,e){const s=e.trim().slice(0,31);if(this.sheetNameProblem(t,e)!==null)return!1;const l=this.sheets[t].name;this.sheets[t].name=s,this._renameInFormulas(l,s);for(const n of re)n(this,l,s);return this.engine?.sheetsChanged(),this._emit("sheets"),!0}_shrink3D(t){const e=this.sheets[t].name.toLowerCase(),s=r=>this.sheets.findIndex(a=>a.name.toLowerCase()===r.toLowerCase()),l=r=>r[0]==="'"?r.slice(1,-1).replace(/''/g,"'"):r,n=/((?:'(?:[^']|'')+'|[A-Za-z_\u00C0-\uFFFF][\w.\u00C0-\uFFFF]*)):((?:'(?:[^']|'')+'|[A-Za-z_\u00C0-\uFFFF][\w.\u00C0-\uFFFF]*))!/g,i=r=>r.replace(n,(a,u,m,h)=>{if(r[h-1]==="]")return a;const y=l(u),p=l(m);if(y.toLowerCase()!==e&&p.toLowerCase()!==e)return a;let c=s(y),S=s(p);if(c<0||S<0||(c>S&&([c,S]=[S,c]),c===t&&c++,S===t&&S--,c>S))return a;const f=g=>Q(this.sheets[g].name);return c===S?`${f(c)}!`:`${f(c)}:${f(S)}!`}),o=r=>r.includes(":")&&r.includes("!")?r.split(/("(?:[^"]|"")*")/).map((a,u)=>u%2?a:i(a)).join(""):r;for(const r of this.sheets){const a=new Map;r.formulas.forEachCell((u,m,h)=>{let y=a.get(h);if(y===void 0){const p=h.f??h.sf,c=typeof p=="string"?o(p):p;y=c===p?null:h.f!==void 0?{...h,f:c,tpl:void 0}:{...h,sf:c,tpl:void 0},a.set(h,y)}y!==null&&r.setFormula(u,m,y)})}for(const r of this.engine?.names.values()??[])typeof r.text=="string"&&(r.text=o(r.text));this.engine?.templates.clear()}_renameInFormulas(t,e){const s=te(t);let l=!1;for(const n of this.sheets){const i=new Map;n.formulas.forEachCell((o,r,a)=>{let u=i.get(a);if(u===void 0){const m=a.f??a.sf;if(m===void 0||!s.test(m))s.lastIndex=0,u=null;else{s.lastIndex=0;const h=D(m,t,e);u=a.f!==void 0?{...a,f:h,tpl:void 0}:{...a,sf:h,tpl:void 0}}i.set(a,u)}u!==null&&(n.setFormula(o,r,u),l=!0)})}l&&(this.formulasEdited=!0,this.engine?.templates.clear(),this.engine?.rebuild())}editText(t,e,s){const l=t.kind(e,s);if(this.engine?.dataTables.length){const o=this.engine.dataTableAt(t,e,s);if(o){const{info:r}=o,a=r.dt2D==="1",u=r.dtr==="1";return`{=TABLE(${a||u?r.r1:""},${a?r.r2:u?"":r.r1})}`}}if(l&Y&&this.engine){const o=this.engine.spillMaster(t,e,s);if(o)return this.editText(t,o.row,o.col)}if(l&k){const o=t.formula(e,s);if(o&&o.f!==void 0){const r="="+V(o.f);return o.t==="array"&&!o.cm?`{${r}}`:r}if(o&&o.sf!==void 0){const r=Math.floor(o.base/w),a=o.base-r*w;return"="+V(se(o.sf,e-r,s-a))}}const n=l&Z;if(n===_)return"";const i=t.value(e,s);if(n===E&&t.valueMeta!==null&&!(l&k)){const o=this.richImages?.get(t.valueMeta.get(e*w+s));if(o!==void 0)return o.alt??"";const r=this.richValues?.indexOfVm(t.valueMeta.get(e*w+s))??-1,a=r>=0?this.richValues.view(r):null;if(a!==null)return a.text}return n===R?this.styles.get(t.style(e,s)).quotePrefix?`'${this.strings.get(i)}`:this.strings.get(i):n===F?i?"TRUE":"FALSE":n===E?W[i]??"#N/A":String(i)}transact(t,e){if(this.guard&&!this.guard(t))return;const s=this.selectedSheets,l=s!==null&&s.size>1&&ce.has(t)?this._runGroup(t,e,s):this._runOn(this.sheet,t,e);l!==null&&this._pushUndo(l)}transactOn(t,e,s){const l=this._runOn(t,e,s);l!==null&&this._pushUndo(l)}_runOn(t,e,s){const l=new b,n={sheet:t,log:l,saveCell:(u,m)=>l.push(t,u,m)},i=s(n)??null;e!=="entry"&&this.engine?.presentationChanged(),t.changes!==null&&l.count>0&&H(this,t,l),l.vms!==null&&fe(t,l);const o=l.count>0&&this.engine?.tables.size>0?j(this,n,l):null,r=(u,m)=>h=>r(u(h),m(h)),a=i&&o?r(i,o):i??o;return l.count===0&&a===null?null:(t.revision++,this.engine?.cellsChanged(t,l.rows,l.cols,l.count),{sheetIndex:t===this.sheet?this.activeSheet:this.sheets.indexOf(t),sheet:t,log:l,label:e,extra:a})}_runGroup(t,e,s){const l=[];for(const n of this.sheets){if(!s.has(n)||n.protection&&n!==this.sheet)continue;const i=this._runOn(n,t,e);i!==null&&l.push(i)}return l.length===0?null:{sheetIndex:this.activeSheet,sheet:this.sheet,log:new b,label:t,extra:T(this,l)}}runSlice(t,e,s){const l=this._runOn(t,e,s);return l!==null&&this._emit("cells"),l}pushFolded(t,e,s){t.length!==0&&this._pushUndo({sheetIndex:this.sheets.indexOf(s),sheet:s,log:new b,label:e,extra:T(this,t)})}rollbackSlices(t){for(let e=t.length-1;e>=0;e--)this._restore(t[e]);this._emit("cells")}_pushUndo(t){this.allowUndo===!1?this.undoStack.length=0:(this.undoStack.push(t),this.undoStack.length>(this.historyLimit??he)&&this.undoStack.shift()),this.redoStack.length=0,this._emit("cells")}_restore(t){const e=t.sheet??this.sheets[t.sheetIndex],{log:s}=t,l=new b;for(let o=s.count-1;o>=0;o--){const r=s.rows[o],a=s.cols[o];l.push(e,r,a),e.setCell(r,a,s.kinds[o],s.values[o]),e.setStyle(r,a,s.styles[o]),e.setFormula(r,a,s.kinds[o]&k?s.formulas.get(o):null)}if(s.vms!==null){e.valueMeta=new Map(e.valueMeta??[]);for(const[o,r]of s.vms)e.valueMeta.set(s.rows[o]*w+s.cols[o],r)}let n=null;t.extra&&(n=t.extra(e)),this.engine?.presentationChanged(),e.changes!==null&&s.count>0&&H(this,e,l),e.revision++,this.engine?.cellsChanged(e,s.rows,s.cols,s.count);const i=this.sheets.indexOf(e);return i>=0&&(this.activeSheet=i),{sheetIndex:i>=0?i:t.sheetIndex,sheet:e,log:l,label:t.label,extra:n}}undo(){const t=this.undoStack.pop();return t?(this.redoStack.push(this._restore(t)),this._emit("cells"),!0):!1}redo(){const t=this.redoStack.pop();return t?(this.undoStack.push(this._restore(t)),this._emit("cells"),!0):!1}setInput(t,e,s,l){const{sheet:n}=t;this.recorder?.push(`sheet.setValue(${JSON.stringify(X(e,s))}, ${JSON.stringify(l)});`),t.saveCell(e,s),n.setFormula(e,s,null);const i=n.cellStyle(e,s),r=l!==""&&this.styles.get(n.style(e,s)).numFmt==="@"?{kind:R,text:l[0]==="'"?l.slice(1):l}:G(l),a=l[0]==="'"&&l.length>1;switch((a||i!==0&&this.styles.get(i).quotePrefix)&&n.setStyle(e,s,this.styles.derive(i,{quotePrefix:a})),r.kind){case _:n.setCell(e,s,_,0);break;case P:n.setCell(e,s,P,r.value),r.format&&(n.cellStyle(e,s)===0||this.styles.get(n.cellStyle(e,s)).numFmt==="General")&&n.setStyle(e,s,this.styles.derive(n.cellStyle(e,s),{numFmt:r.format}));break;case F:n.setCell(e,s,F,r.value);break;case k:n.setCell(e,s,k|_,0),n.setFormula(e,s,{f:ae(this._expandTableRefs(K(r.formula,this.engine?.tables),n,e,s),this.engine?.names??null),typed:this.dynamicArrays!==!1}),this.formulasEdited=!0;break;default:n.setCell(e,s,R,this.strings.add(r.text))}}setRichInput(t,e,s,l,n){const{sheet:i}=t;t.saveCell(e,s),i.setFormula(e,s,null),i.setCell(e,s,R,this.strings.addRich(l,n))}_expandTableRefs(t,e,s,l){const n=this.engine;return!n||n.tables.size===0?t:oe(t,()=>{for(const i of n.tables.values())if(i.sheet===e&&s>=i.r0&&s<=i.r1&&l>=i.c0&&l<=i.c1)return i;return null})}clearRange(t,e="contents",{visibleOnly:s=!1}={}){this.sheet.dataRanges?.cleared(t)||this.transact("clear",l=>{const{sheet:n}=l,i=[];if(e!=="contents")for(const{r0:r,c0:a,r1:u,c1:m}of t){const h=r===0&&u===B-1,y=a===0&&m===w-1,p=(c,S,f,g)=>{for(const[C,v]of[...S])C<f||C>g||(i.push([c,C,v]),S.delete(C))};h&&n.colStyles!==null&&p("col",n.colStyles,a,m),y&&n.rowStyles!==null&&p("row",n.rowStyles,r,u)}const o=s&&n.filteredRows?.size>0?n.filteredRows:null;for(const{r0:r,c0:a,r1:u,c1:m}of t){const h=Math.min(m,n.maxCol),y=Math.min(u,n.maxRow);for(let p=a;p<=h;p++)if(n.columns[p]!==void 0)for(let c=r;c<=y;c++){if(n._chunk(c,p)===void 0){c|=1023;continue}if(o!==null&&o.has(c))continue;const f=n.kind(c,p)!==0,g=n.cellStyle(c,p)!==0;if(e==="formats"){if(!g)continue;l.saveCell(c,p),n.setStyle(c,p,0);continue}!f&&!(e==="all"&&g)||(l.saveCell(c,p),n.setCell(c,p,_,0),n.setFormula(c,p,null),e==="all"&&n.setStyle(c,p,0))}}return i.length>0?O([],i):void 0})}applyStyle(t,e){const s=JSON.stringify(e);if(this.recorder)for(const l of t)this.recorder.push(`sheet.setFormat(${JSON.stringify(ee(l))}, ${s});`);this.transact("format",l=>{const{sheet:n}=l;this.strings.rich!==null&&le(this,l,t,e);const i=[],o=new Set,r=[];for(const{r0:a,c0:u,r1:m,c1:h}of t){const y=a===0&&m===B-1,p=u===0&&h===w-1;if(y){n.colStyles===null&&(n.colStyles=new Map);for(let f=u;f<=h;f++){const g=n.colStyles.get(f);r.push(["col",f,g]),n.colStyles.set(f,this.styles.derive(g??0,e,s))}if(p&&n.rowStyles!==null)for(const[f,g]of n.rowStyles)r.push(["row",f,g]),n.rowStyles.set(f,this.styles.derive(g,e,s))}else if(p){n.rowStyles===null&&(n.rowStyles=new Map);for(let f=a;f<=m;f++){const g=n.rowStyles.get(f);r.push(["row",f,g]),n.rowStyles.set(f,this.styles.derive(g??0,e,s))}}const c=y?n.maxRow:m,S=p?n.maxCol:h;for(let f=u;f<=S;f++)for(let g=a>>>I;g<=c>>>I;g++){const C=g<<I,v=Math.max(a,C),L=Math.min(c,C+J);if(v>L)continue;const $=n._ensure(v,f),U=f*2048+g;o.has(U)||(o.add(U),i.push(f,g,$.styles===null?null:$.styles.slice()));for(let M=v;M<=L;M++)n.setStyle(M,f,this.styles.derive(n.style(M,f),e,s))}}return O(i,r)})}}function T(d,t){const e=()=>{const s=[];for(let l=t.length-1;l>=0;l--)s.push(d._restore(t[l]));return T(d,s)};return e.parts=t,e}function fe(d,t){let e=null;for(const s of t.vms.keys()){const l=t.rows[s],n=t.cols[s];(d.kind(l,n)&~(N|z))===t.kinds[s]&&d.value(l,n)===t.values[s]||(e??=new Map(d.valueMeta),e.delete(l*w+n))}e!==null&&(d.valueMeta=e.size>0?e:null)}function x(d){if(d===null||typeof d!="object")return d;if(Array.isArray(d))return d.map(x);if(d instanceof Map)return new Map([...d].map(([e,s])=>[e,x(s)]));if(d instanceof Set)return new Set([...d].map(x));if(ArrayBuffer.isView(d))return d.slice();const t={};for(const[e,s]of Object.entries(d))!e.startsWith("_")&&typeof s!="function"&&(t[e]=x(s));return t}function O(d,t){return e=>{const s=[];for(let n=0;n<d.length;n+=3){const i=d[n],o=d[n+1],r=e.columns[i]?.[o];r!==void 0&&(s.push(i,o,r.styles),r.styles=d[n+2])}const l=[];for(const[n,i,o]of t){const r=n==="col"?"colStyles":"rowStyles",a=e[r]??=new Map;l.push([n,i,a.get(i)]),o===void 0?a.delete(i):a.set(i,o)}return O(s,l)}}export{b as CellLog,ce as GROUP_LABELS,Re as Workbook,T as foldEntries,G as parseInput,O as swapStyles};
|
|
1
|
+
import{expandBareTables as ue}from"../slicers/structured.js";import{syncTableHeaders as fe,tablesOf as de}from"./tables.js";import{BOOL as D,CHUNK_BITS as z,CHUNK_MASK as K,EMPTY as T,ERR as U,ERRORS as me,FORMULA as F,DIRTY as W,EVALUATING as J,KIND_MASK as Z,NUM as P,Sheet as B,SPILL as pe,STR as A}from"./sheet.js";import{cellRef as ge,isValidName as ye,MAX_COLS as b,MAX_ROWS as Y,quoteSheetName as X,rangeRef as Se,renameSheetInFormula as Q,sheetReferencePattern as ee}from"./address.js";import{translateFormula as we}from"./formula-refs.js";import{sheetStem as te}from"./default-names.js";import{StringTable as Ce}from"./strings.js";import{formatAxis as se,formatSheetColumns as ve}from"./axis-styles.js";import{autoRowHeight as ke}from"./row-fit.js";import{StyleTable as xe}from"./styles.js";import{cellEntryText as ne,parseInput as ie}from"./input.js";import{noteChanges as oe}from"./changes.js";import{overrideRuns as _e}from"../cells/rich-runs.js";import{sheetRenameHooks as be}from"./sparse.js";import{shiftRuleFormulas as re}from"../cells/cf-file.js";import{expandStructured as Re,formulaEntryLimit as Me,FormulaSyntaxError as L,tokenize as Fe,toDisplayFormula as le,toFileFormula as Ae}from"../calc/parser.js";const Ie=200,Ee=new Set(["entry","clear","format","borders","fill"]);class Te{constructor(){this.ids=new Int32Array(1024),this.list=[]}set(t,e){if(t>=this.ids.length){let i=this.ids.length*2;for(;i<=t;)i*=2;const r=new Int32Array(i);r.set(this.ids),this.ids=r}const n=this.list.length;(n===0||this.list[n-1]!==e)&&this.list.push(e),this.ids[t]=this.list.length}get(t){const e=t<this.ids.length?this.ids[t]:0;return e===0?void 0:this.list[e-1]}}class ${constructor(){this.capacity=1024,this.count=0,this.rows=new Uint32Array(this.capacity),this.cols=new Uint16Array(this.capacity),this.kinds=new Uint8Array(this.capacity),this.styles=new Uint16Array(this.capacity),this.values=new Float64Array(this.capacity),this.formulas=null,this.vms=null}_grow(){const t=this.capacity*2,e=(n,i)=>{const r=new n(t);return r.set(i),r};this.rows=e(Uint32Array,this.rows),this.cols=e(Uint16Array,this.cols),this.kinds=e(Uint8Array,this.kinds),this.styles=e(Uint16Array,this.styles),this.values=e(Float64Array,this.values),this.capacity=t}push(t,e,n){this.count===this.capacity&&this._grow();const i=this.count++,r=t.kind(e,n)&~(W|J);if(this.rows[i]=e,this.cols[i]=n,this.kinds[i]=r,this.styles[i]=t.cellStyle(e,n),this.values[i]=t.value(e,n),r&F&&(this.formulas===null&&(this.formulas=new Te),this.formulas.set(i,t.formula(e,n))),t.valueMeta!==null){const s=t.valueMeta.get(e*b+n);s!==void 0&&(this.vms??=new Map).set(i,s)}}}class Ye{constructor(){this.sheets=[new B(`${te()}1`)],this.activeSheet=0,this.strings=new Ce,this.styles=new xe,this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.source=null,this.formulasEdited=!1,this.edits=0,this._dirty=!1,this.engine=null,this.selectedSheets=null}get sheet(){return this.sheets[this.activeSheet]}get dirty(){return this._dirty}set dirty(t){t&&this.edits++,this._dirty=!!t}onChange(t){this.listeners.add(t)}_emit(t){this.dirty=!0;for(const e of this.listeners)e(t)}addSheet(t){const e=te();let n=1,i=t??`${e}${n}`;const r=o=>this.sheets.some(l=>l.name.toLowerCase()===o.toLowerCase());for(;r(i);)i=`${e}${++n}`;const s=new B(i);return this.sheets.push(s),this.activeSheet=this.sheets.length-1,this.engine?.sheetsChanged(),this._emit("sheets"),s}deleteSheet(t){return this.sheets.filter(e=>!e.hidden).length<=1?!1:(this._shrink3D(t),this._refErrorsFor(t),this._removeSheet(t))}_removeSheet(t){if(this.sheets.length<=1)return!1;const[e]=this.sheets.splice(t,1);if(this.selectedSheets?.delete(e),this._forgetSheet(e,t),this.engine)for(const[i,r]of this.engine.tables)r.sheet===e&&this.engine.tables.delete(i);this._reindexNames(i=>i===t?-1:i>t?i-1:i),this.activeSheet>=this.sheets.length&&(this.activeSheet=this.sheets.length-1);const n=this.activeSheet;for(;this.sheets[this.activeSheet].hidden&&(this.activeSheet=(this.activeSheet+1)%this.sheets.length,this.activeSheet!==n););return this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),!0}_forgetSheet(t,e){const n=r=>r.sheet===t||r.sheet===void 0&&r.sheetIndex===e||(r.extra?.parts??[]).some(n),i=r=>{r.sheetIndex>e&&r.sheetIndex--;for(const s of r.extra?.parts??[])i(s)};for(const r of[this.undoStack,this.redoStack]){const s=r.filter(o=>!n(o));s.forEach(i),r.splice(0,r.length,...s)}}moveSheet(t,e){if(t===e)return;const n=this.sheet,[i]=this.sheets.splice(t,1);this.sheets.splice(e,0,i),this.activeSheet=this.sheets.indexOf(n);const r=o=>o===t?e:t<e?o>t&&o<=e?o-1:o:o>=e&&o<t?o+1:o,s=o=>{o.sheetIndex=r(o.sheetIndex);for(const l of o.extra?.parts??[])s(l)};for(const o of this.undoStack)s(o);for(const o of this.redoStack)s(o);this.structureEdited=!0,this._reindexNames(r),this.engine?.orderChanged(),this._emit("sheets")}_copyTables(t,e){const n=new Map,i=new Set;for(const r of de(this,t)){const{sheet:s,part:o,id:l,source:a,sheetIndex:c,...h}=r;let u=this.engine.tables.size+n.size+2,p,f;do{const d=String(u++),g=r.name.slice(0,255-d.length);p=g+d,ye(p)||(p=g.slice(0,254-d.length)+"_"+d),f=p.toUpperCase()}while(i.has(f)||this.engine.tables.has(f)||this.engine.names.has(f));i.add(f),n.set(r.name.toUpperCase(),{...I(h),name:p,sheet:e,isNew:!0,dirty:!0})}return n}_copyScopedNames(t,e,n,i){const{engine:r}=this;if(!r||r.names.size===0)return;const s=`${t}!`;let o=!1;for(const[l,a]of[...r.names])l.startsWith(s)&&(r.names.set(`${t+1}!${l.slice(s.length)}`,{...a,text:i(Q(a.text,e.name,n.name))}),o=!0);o&&(this.namesChanged=!0)}_reindexNames(t){const{engine:e}=this;if(!e||e.names.size===0)return;const n=[];let i=!1;for(const[r,s]of e.names){const o=r.indexOf("!"),l=o<0?0:t(Number(r.slice(0,o)));o>=0&&l!==Number(r.slice(0,o))&&(i=!0),o<0?n.push([r,s]):l>=0&&n.push([`${l}!${r.slice(o+1)}`,s])}if(i){e.names.clear();for(const[r,s]of n)e.names.set(r,s);e.nameTemplates.clear(),this.namesChanged=!0,e.rebuild()}}duplicateSheet(t){const e=this.sheets[t];let i=`${e.name} (2)`,r=2;for(;this.sheets.some(h=>h.name.toLowerCase()===i.toLowerCase());)i=`${e.name} (${++r})`;const s=new B(i),o=this._copyTables(e,s),l=h=>ze(h,o,e.name,s.name);for(const h of o.values())for(const u of h.totals??[])u?.formula&&(u.formula=l(u.formula));e.columns.forEach((h,u)=>{const p=[];h.forEach((f,d)=>{p[d]={kinds:f.kinds.slice(),values:f.values.slice(),styles:f.styles?f.styles.slice():null}}),s.columns[u]=p}),s.maxRow=e.maxRow,s.maxCol=e.maxCol,s.rows=e.rows.shifted(0,0),s.cols=e.cols.shifted(0,0);const a=new Map;e.formulas.forEachCell((h,u,p)=>{let f=a.get(p);f===void 0&&(f={...p,tpl:void 0},p.f!==void 0&&(f.f=l(p.f)),p.sf!==void 0&&(f.sf=l(p.sf)),a.set(p,f)),s.setFormula(h,u,f)}),s.merges=e.merges.map(h=>({...h})),s.rowStyles=e.rowStyles?new Map(e.rowStyles):null,s.colStyles=e.colStyles?new Map(e.colStyles):null,s.frozenRows=e.frozenRows,s.frozenCols=e.frozenCols,s.showGridlines=e.showGridlines,s.cellTypes=e.cellTypes?new Map(e.cellTypes):null,s.sparkRules=e.sparkRules,s.cellDropdowns=e.cellDropdowns?new Map(e.cellDropdowns):null,s.cellTags=e.cellTags?new Map(e.cellTags):null,s.cellButtons=e.cellButtons?new Map(e.cellButtons):null,s.cellStates=e.cellStates?e.cellStates.slice():null,s.autoMerges=e.autoMerges?e.autoMerges.map(h=>({...h})):null,s.background=e.background,s.outlineColumn=e.outlineColumn?{...e.outlineColumn}:null,s.frozenTrailingRows=e.frozenTrailingRows,s.frozenTrailingCols=e.frozenTrailingCols,s.hideZeros=e.hideZeros,s.hideHeadings=e.hideHeadings,s.isChartSheet=e.isChartSheet,s.hideOutline=e.hideOutline,s.gridColorId=e.gridColorId,s.areaOffset=e.areaOffset,s.selectionPolicy=e.selectionPolicy,s.selectionUnit=e.selectionUnit,s.gridlineAxes=e.gridlineAxes,s.gridColor=e.gridColor,s.tabStyles=e.tabStyles;const c=I;if(s.cf=c(e.cf),s.validations=c(e.validations),o.size){for(const h of s.cf??[])h.rules=h.rules.map(u=>re(u,l));for(const h of s.validations??[])h.formula1&&(h.formula1=l(h.formula1)),h.formula2&&(h.formula2=l(h.formula2))}s.comments=c(e.comments),s.threads=c(e.threads),s.hyperlinks=e.hyperlinks?e.hyperlinks.map(h=>({...c({...h,_ranges:void 0})})):e.hyperlinks,s.autoFilter=c(e.autoFilter),s.filteredRows=e.filteredRows?new Set(e.filteredRows):e.filteredRows,s.pageSetup=c(e.pageSetup),s.tabColor=e.tabColor,s.protection=c(e.protection),s.rtl=e.rtl,s.zoom=e.zoom,s.valueMeta=e.valueMeta?new Map(e.valueMeta):null,s.colsChanged=!0,s.viewChanged=!0,this.sheets.splice(t+1,0,s);for(const h of o.values())this.engine.tables.set(h.name.toUpperCase(),h);return this.activeSheet=t+1,this._reindexNames(h=>h>t?h+1:h),this._copyScopedNames(t,e,s,l),this.structureEdited=!0,this.engine?.sheetsChanged(),this.engine?.rebuild(),this._emit("sheets"),s}sheetNameProblem(t,e){const n=e.trim().slice(0,31);return!n||/[\\/?*[\]:]/.test(n)||/^'|'$/.test(n)?"rules":n.toLowerCase()==="history"?"reserved":this.sheets.some((i,r)=>r!==t&&i.name.toLowerCase()===n.toLowerCase())?"taken":null}renameSheet(t,e){const n=e.trim().slice(0,31);if(this.sheetNameProblem(t,e)!==null)return!1;const i=this.sheets[t].name;this.sheets[t].name=n,this.engine?.sheetsChanged(),this._renameInFormulas(i,n);for(const r of be)r(this,i,n);return this._emit("sheets"),!0}_shrink3D(t){const e=this.sheets[t].name.toLowerCase(),n=l=>this.sheets.findIndex(a=>a.name.toLowerCase()===l.toLowerCase()),i=l=>l[0]==="'"?l.slice(1,-1).replace(/''/g,"'"):l,r=/((?:'(?:[^']|'')+'|[A-Za-z_\u00C0-\uFFFF][\w.\u00C0-\uFFFF]*)):((?:'(?:[^']|'')+'|[A-Za-z_\u00C0-\uFFFF][\w.\u00C0-\uFFFF]*))!/g,s=l=>l.replace(r,(a,c,h,u)=>{if(l[u-1]==="]")return a;const p=i(c),f=i(h);if(p.toLowerCase()!==e&&f.toLowerCase()!==e)return a;let d=n(p),g=n(f);if(d<0||g<0||(d>g&&([d,g]=[g,d]),d===t&&d++,g===t&&g--,d>g))return a;const y=w=>X(this.sheets[w].name);return d===g?`${y(d)}!`:`${y(d)}:${y(g)}!`}),o=l=>l.includes(":")&&l.includes("!")?l.split(/("(?:[^"]|"")*")/).map((a,c)=>c%2?a:s(a)).join(""):l;for(const l of this.sheets){const a=new Map;l.formulas.forEachCell((c,h,u)=>{let p=a.get(u);if(p===void 0){const f=u.f??u.sf,d=typeof f=="string"?o(f):f;p=d===f?null:u.f!==void 0?{...u,f:d,tpl:void 0}:{...u,sf:d,tpl:void 0},a.set(u,p)}p!==null&&l.setFormula(c,h,p)})}for(const l of this.engine?.names.values()??[])typeof l.text=="string"&&(l.text=o(l.text));this.engine?.templates.clear()}_refErrorsFor(t){const e=ee(this.sheets[t].name),n=s=>s.split(/("(?:[^"]|"")*")/).map((o,l)=>l%2?o:o.replace(e,"#REF!")).join(""),i=s=>typeof s=="string"&&s!==""?n(s):s,r=this.sheets[t];for(const s of this.sheets){if(s===r)continue;s.cf?.length>0&&(s.cf=s.cf.map(l=>({...l,rules:l.rules.map(a=>re(a,i))})),s.cfChanged=!0,s.cfEval?.invalidate()),s.validations?.length>0&&(s.validations=s.validations.map(l=>({...l,formula1:i(l.formula1),formula2:i(l.formula2)})),s.validationsChanged=!0);const o=new Map;s.formulas.forEachCell((l,a,c)=>{let h=o.get(c);if(h===void 0){const u=c.f??c.sf,p=typeof u=="string"?n(u):u;h=p===u?null:c.f!==void 0?{...c,f:p,tpl:void 0}:{...c,sf:p,tpl:void 0},o.set(c,h)}h!==null&&(s.setFormula(l,a,h),this.formulasEdited=!0)})}for(const s of this.engine?.names.values()??[])typeof s.text=="string"&&(s.text=n(s.text));this.engine?.templates.clear()}_renameInFormulas(t,e){const n=ee(t);let i=!1;for(const r of this.sheets){const s=new Map;r.formulas.forEachCell((o,l,a)=>{let c=s.get(a);if(c===void 0){const h=a.f??a.sf;if(h===void 0||!n.test(h))n.lastIndex=0,c=null;else{n.lastIndex=0;const u=Q(h,t,e);c=a.f!==void 0?{...a,f:u,tpl:void 0}:{...a,sf:u,tpl:void 0}}s.set(a,c)}c!==null&&(r.setFormula(o,l,c),i=!0)})}i&&(this.formulasEdited=!0,this.engine?.templates.clear(),this.engine?.rebuild())}editText(t,e,n){const i=t.kind(e,n);if(this.engine?.dataTables.length){const o=this.engine.dataTableAt(t,e,n);if(o){const{info:l}=o,a=l.dt2D==="1",c=l.dtr==="1";return`{=TABLE(${a||c?l.r1:""},${a?l.r2:c?"":l.r1})}`}}if(i&pe&&this.engine){const o=this.engine.spillMaster(t,e,n);if(o)return this.editText(t,o.row,o.col)}if(i&F){const o=t.formula(e,n),l=o&&!o.typed&&o.t!=="array"&&o.tpl?.rangeResult?"=@":"=";if(o&&o.f!==void 0){const a=l+le(o.f);return o.t==="array"&&!o.cm?`{${a}}`:a}if(o&&o.sf!==void 0){const a=Math.floor(o.base/b),c=o.base-a*b;return l+le(we(o.sf,e-a,n-c))}}const r=i&Z;if(r===T)return"";const s=t.value(e,n);if(r===U&&t.valueMeta!==null&&!(i&F)){const o=this.richImages?.get(t.valueMeta.get(e*b+n));if(o!==void 0)return o.alt??"";const l=this.richValues?.indexOfVm(t.valueMeta.get(e*b+n))??-1,a=l>=0?this.richValues.view(l):null;if(a!==null)return a.text}return r===A?this.styles.get(t.style(e,n)).quotePrefix?`'${this.strings.get(s)}`:this.strings.get(s):r===D?s?"TRUE":"FALSE":r===U?me[s]??"#N/A":String(s)}transact(t,e,n=null){if(this.guard&&!this.guard(t))return;const i=this.selectedSheets;!n&&i?.size>1&&Ee.has(t)&&(n=this.sheets.filter(s=>i.has(s)&&(!s.protection||s===this.sheet)));const r=n?this._runGroup(t,e,n):this._runOn(this.sheet,t,e);r!==null&&this._pushUndo(r)}transactOn(t,e,n){const i=this._runOn(t,e,n);i!==null&&this._pushUndo(i)}_runOn(t,e,n){const i=new $,r={sheet:t,log:i,saveCell:(f,d)=>i.push(t,f,d)},{maxRow:s,maxCol:o}=t,l=this.recorder?.length,a=this.formulasEdited;let c;try{c=n(r)??null}catch(f){throw f instanceof L&&(ae(t,i),t.maxRow=s,t.maxCol=o,this.formulasEdited=a,l!==void 0&&(this.recorder.length=l),this.engine?.cellsChanged(t,i.rows,i.cols,i.count)),f}e!=="entry"&&this.engine?.presentationChanged(),t.changes!==null&&i.count>0&&oe(this,t,i),i.vms!==null&&Oe(t,i);const h=i.count>0&&this.engine?.tables.size>0?fe(this,r,i):null,u=(f,d)=>g=>u(f(g),d(g)),p=c&&h?u(c,h):c??h;return i.count===0&&p===null?null:(t.revision++,this.engine?.cellsChanged(t,i.rows,i.cols,i.count),{sheetIndex:t===this.sheet?this.activeSheet:this.sheets.indexOf(t),sheet:t,log:i,label:e,extra:p})}_runGroup(t,e,n){const i=[],r=this.activeSheet,s=this.recorder?.length,o=this.formulasEdited,l=[];try{for(const a of n){const{maxRow:c,maxCol:h}=a,u=this._runOn(a,t,e);u!==null&&(i.push(u),l.push([a,c,h]))}}catch(a){if(a instanceof L){this.rollbackSlices(i);for(const[c,h,u]of l)c.maxRow=h,c.maxCol=u;this.activeSheet=r,this.formulasEdited=o,s!==void 0&&(this.recorder.length=s)}throw a}return i.length===0?null:{sheetIndex:this.activeSheet,sheet:this.sheet,log:new $,label:t,extra:H(this,i)}}runSlice(t,e,n){const i=this._runOn(t,e,n);return i!==null&&this._emit("cells"),i}pushFolded(t,e,n){t.length!==0&&this._pushUndo({sheetIndex:this.sheets.indexOf(n),sheet:n,log:new $,label:e,extra:H(this,t)})}rollbackSlices(t){for(let e=t.length-1;e>=0;e--)this._restore(t[e]);this._emit("cells")}_pushUndo(t){this.allowUndo===!1?this.undoStack.length=0:(this.undoStack.push(t),this.undoStack.length>(this.historyLimit??Ie)&&this.undoStack.shift()),this.redoStack.length=0,this._emit("cells")}_restore(t){const e=t.sheet??this.sheets[t.sheetIndex],{log:n}=t,i=new $;if(ae(e,n,i),n.vms!==null){e.valueMeta=new Map(e.valueMeta??[]);for(const[o,l]of n.vms)e.valueMeta.set(n.rows[o]*b+n.cols[o],l)}let r=null;t.extra&&(r=t.extra(e)),this.engine?.presentationChanged(),e.changes!==null&&n.count>0&&oe(this,e,i),e.revision++,this.engine?.cellsChanged(e,n.rows,n.cols,n.count);const s=this.sheets.indexOf(e);return s>=0&&(this.activeSheet=s),{sheetIndex:s>=0?s:t.sheetIndex,sheet:e,log:i,label:t.label,extra:r}}undo(){const t=this.undoStack.pop();return t?(this.redoStack.push(this._restore(t)),this._emit("cells"),!0):!1}redo(){const t=this.redoStack.pop();return t?(this.undoStack.push(this._restore(t)),this._emit("cells"),!0):!1}setInput(t,e,n,i,{overLimitAsText:r=!1}={}){const{sheet:s}=t,o=s.style(e,n),l=i!==""&&this.styles.get(o).numFmt==="@";let a=l?{kind:A,text:i[0]==="'"?i.slice(1):i}:ie(i);if(a.kind===F){const h=Me(a.formula);if(h){if(!r)throw new L(h);a={kind:A,text:i}}}if(this.recorder){const h=a.kind===A&&i.startsWith("=")&&!l?`'${i}`:i;this.recorder.push(`sheet.setValue(${JSON.stringify(ge(e,n))}, ${JSON.stringify(h)});`)}t.saveCell(e,n),s.setFormula(e,n,null);const c=i[0]==="'"&&i.length>1;switch((c||this.styles.get(o).quotePrefix)&&s.setStyle(e,n,this.styles.derive(o,{quotePrefix:c})),a.kind){case T:s.setCell(e,n,T,0);break;case P:s.setCell(e,n,P,a.value),a.format&&this.styles.get(o).numFmt==="General"&&s.setStyle(e,n,this.styles.derive(s.style(e,n),{numFmt:a.format}));break;case D:s.setCell(e,n,D,a.value);break;case U:s.setCell(e,n,U,a.value);break;case F:s.setCell(e,n,F|T,0),s.setFormula(e,n,{f:Ae(this._expandTableRefs(ue(a.formula,this.engine?.tables),s,e,n),this.engine?.names??null),typed:this.dynamicArrays!==!1}),this.formulasEdited=!0;break;default:s.setCell(e,n,A,this.strings.add(ne(a.text)))}}setRichInput(t,e,n,i,r){const{sheet:s}=t;t.saveCell(e,n),s.setFormula(e,n,null);const o=ne(i);s.setCell(e,n,A,this.strings.addRich(o,o===i?r:r?.filter(l=>l.at<o.length)))}_expandTableRefs(t,e,n,i){const r=this.engine;return!r||r.tables.size===0?t:Re(t,()=>{for(const s of r.tables.values())if(s.sheet===e&&n>=s.r0&&n<=s.r1&&i>=s.c0&&i<=s.c1)return s;return null})}clearRange(t,e="contents",{visibleOnly:n=!1}={}){this.sheet.dataRanges?.cleared(t)||this.transact("clear",i=>{const{sheet:r}=i,s=[];if(e!=="contents")for(const{r0:l,c0:a,r1:c,c1:h}of t){const u=l===0&&c===Y-1,p=a===0&&h===b-1,f=(d,g,y,w)=>{for(const[C,x]of[...g])C<y||C>w||(s.push([d,C,x]),g.delete(C))};u&&r.colStyles!==null&&f("col",r.colStyles,a,h),p&&r.rowStyles!==null&&f("row",r.rowStyles,l,c)}const o=n&&r.filteredRows?.size>0?r.filteredRows:null;for(const{r0:l,c0:a,r1:c,c1:h}of t){const u=Math.min(h,r.maxCol),p=Math.min(c,r.maxRow);for(let f=a;f<=u;f++)if(r.columns[f]!==void 0)for(let d=l;d<=p;d++){if(r._chunk(d,f)===void 0){d|=1023;continue}if(o!==null&&o.has(d))continue;const y=r.kind(d,f)!==0,w=r.cellStyle(d,f)!==0;if(e==="formats"){if(!w)continue;i.saveCell(d,f),r.setStyle(d,f,0);continue}!y&&!(e==="all"&&w)||(i.saveCell(d,f),r.setCell(d,f,T,0),r.setFormula(d,f,null),e==="all"&&r.setStyle(d,f,0))}}return s.length>0?V([],s):void 0})}applyStyle(t,e,{measureRow:n,numberFit:i}={}){const r=JSON.stringify(e);if(this.recorder)for(const s of t)this.recorder.push(`sheet.setFormat(${JSON.stringify(Se(s))}, ${r});`);this.transact("format",s=>{const{sheet:o}=s;this.strings.rich!==null&&_e(this,s,t,e);const l=[],a=new Set,c=[],h=[],u=(g,y,w)=>{const C=g*2048+y;a.has(C)||(a.add(C),l.push(g,y,w.styles===null?null:w.styles.slice()))},p=(g,y,w)=>{w===0&&(o.rowStyles?.has(g)||o.colStyles?.has(y))&&(w=this.styles.explicitDefault()),o.setStyle(g,y,w)};for(const{r0:g,c0:y,r1:w,c1:C}of t){const x=g===0&&w===Y-1,v=y===0&&C===b-1,k=x||v,R=k?Math.min(w,o.maxRow):w,he=k?Math.min(C,o.maxCol):C;for(let S=y;S<=he&&g<=R;S++){const _=o.columns[S];if(!(k&&!_))for(let M=g>>>z;M<=R>>>z;M++){const q=M<<z,G=Math.max(g,q),ce=Math.min(R,q+K),N=k?_[M]:o._ensure(G,S);if(!(k&&!N?.styles)){u(S,M,N);for(let E=G;E<=ce;E++)(!k||N.styles[E&K])&&p(E,S,this.styles.derive(o.style(E,S),e,r))}}}const O=S=>this.styles.derive(S,e,r),j=(S,_,M)=>{u(_,S>>>z,o._ensure(S,_)),o.setStyle(S,_,M||this.styles.explicitDefault())};if(v&&x){ve(o,O,c);for(const[S,_]of o.rowStyles??[])c.push(["row",S,_]),o.rowStyles.set(S,O(_))}else if(x)for(let S=y;S<=C;S++)se(o,"col",S,O,c,j);else if(v)for(let S=g;S<=w;S++)se(o,"row",S,O,c,j)}const f=(g,y,w)=>{const C=o[g];w!==C.sizeOf(y)&&(h.push([g,y,C.isCustom(y)?C.sizeOf(y):null,C.isAuto(y)]),C.setSize(y,w,!0),g==="cols"&&(o.colsChanged=!0))},d=e.fontSize!==void 0||e.wrap!==void 0||e.rotation!==void 0||["justify","distributed"].includes(e.hAlign)||["justify","distributed"].includes(e.vAlign);for(const{r0:g,r1:y,c0:w,c1:C}of t){const x=Math.min(y,o.maxRow);if(d&&x-g<=2e3)for(let v=g;v<=x;v++)f("rows",v,ke(o,this,v,n));if(i)for(const v of i.cols){if(v<w||v>C||!o.columns[v]||o.cols.isCustom(v)&&!o.cols.isAuto(v))continue;let k=o.cols.sizeOf(v);for(const R of i.rows)R>=g&&R<=x&&(o.kind(R,v)&Z)===P&&(k=Math.max(k,i.measure(o,R,v)));f("cols",v,k)}}return V(l,c,h)})}}function ae(m,t,e){for(let n=t.count-1;n>=0;n--){const i=t.rows[n],r=t.cols[n];e?.push(m,i,r),m.setCell(i,r,t.kinds[n],t.values[n]),m.setStyle(i,r,t.styles[n]),m.setFormula(i,r,t.kinds[n]&F?t.formulas.get(n):null)}}function H(m,t){const e=()=>{const n=[];for(let i=t.length-1;i>=0;i--)n.push(m._restore(t[i]));return H(m,n)};return e.parts=t,e}function Oe(m,t){let e=null;for(const n of t.vms.keys()){const i=t.rows[n],r=t.cols[n];(m.kind(i,r)&~(W|J))===t.kinds[n]&&m.value(i,r)===t.values[n]||(e??=new Map(m.valueMeta),e.delete(i*b+r))}e!==null&&(m.valueMeta=e.size>0?e:null)}function ze(m,t,e,n){if(!t.size||typeof m!="string")return m;let i;try{i=Fe(m)}catch(o){if(o instanceof L)return m;throw o}let r="",s=0;for(let o=0;o<i.length;o++){const l=i[o],a=l.t==="name"?m.slice(l.s,l.e):l.t==="table"?l.v.name:null;if(!a)continue;const c=t.get(a.toUpperCase());if(!c)continue;let h=o-1;for(;i[h]?.t==="ws";)h--;const u=i[h];if(u?.t==="sheet"){const{book:p,sheet:f,sheet2:d}=u.v;if(p!==null||d!==null)continue;if(f.toUpperCase()===e.toUpperCase())r+=m.slice(s,u.s)+X(n)+"!",s=u.e;else if(f.toUpperCase()!==n.toUpperCase())continue}r+=m.slice(s,l.s)+c.name,s=l.s+a.length}return s?r+m.slice(s):m}function I(m){if(m===null||typeof m!="object")return m;if(Array.isArray(m))return m.map(I);if(m instanceof Map)return new Map([...m].map(([e,n])=>[e,I(n)]));if(m instanceof Set)return new Set([...m].map(I));if(ArrayBuffer.isView(m))return m.slice();const t={};for(const[e,n]of Object.entries(m))!e.startsWith("_")&&typeof n!="function"&&(t[e]=I(n));return t}function V(m,t,e=[]){return n=>{const i=[];for(let o=0;o<m.length;o+=3){const l=m[o],a=m[o+1],c=n.columns[l]?.[a];c!==void 0&&(i.push(l,a,c.styles),c.styles=m[o+2])}const r=[];for(let o=t.length-1;o>=0;o--){const[l,a,c]=t[o];if(l==="columns"){r.push([l,a,n.colStyles]),n.colStyles=c,n.colsChanged=!0;continue}l==="col"&&(n.colsChanged=!0);const h=l==="col"?"colStyles":"rowStyles",u=n[h]??=new Map;r.push([l,a,u.get(a)]),c===void 0?u.delete(a):u.set(a,c)}const s=[];for(let o=e.length-1;o>=0;o--){const[l,a,c,h]=e[o],u=n[l];s.push([l,a,u.isCustom(a)?u.sizeOf(a):null,u.isAuto(a)]),u.setSize(a,c,h),l==="cols"&&(n.colsChanged=!0)}return V(i,r,s)}}export{$ as CellLog,Ee as GROUP_LABELS,Ye as Workbook,H as foldEntries,ie as parseInput,V as swapStyles};
|
package/datasheets/data-core.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BOOL as E,EMPTY as b,ERR as D,ERRORS as P,KIND_MASK as T,NUM as k,STR as N}from"../core/sheet.js";import{partsToSerial as H}from"../core/numfmt.js";import{StringTable as L}from"../core/strings.js";import{ERR_BY_CODE as $,ERR_BY_INDEX as V,numberToText as z,textToNumber as j,XlError as x}from"../calc/values.js";import{parseInput as q}from"../core/input.js";import{rankStrings as B}from"./sort.js";import{computeWindow as K}from"./window.js";import{checkValidator as Y,flattenRecord as X,parseSource as W,readField as J,readRemote as Q,sendChanges as I}from"./remote.js";import{t as _}from"../i18n/index.js";const Z=["number","date","boolean","string","any"],tt=new Set(["number","date","boolean"]),u={UNCHANGED:0,INSERTED:1,UPDATED:2,PURGED:3},et=256;class m extends Error{}class O{constructor(t,e,i){if(this.table=t,this.index=i,this.name=e.name,this.caption=e.caption??e.name,this.type=e.type??"any",!Z.includes(this.type))throw new m(`Unknown field type: ${this.type}`);this.format=e.format??(this.type==="date"?"yyyy-mm-dd":"General"),this.readOnly=e.readOnly===!0,this.defaultValue=e.defaultValue??null,this.width=e.width??null,this.hidden=e.hidden===!0,this.formula=e.formula??null,this.lookup=e.lookup??null,this.rollup=e.rollup??null,this.window=e.window??null,this.required=e.required===!0,this.showNullAs=e.showNullAs??null,this.validator=e.validator??null,this.trigger=e.trigger??null,this.computed=this.formula!==null||this.lookup!==null||this.rollup!==null||this.window!==null,this.stale=this.computed,this.deps=[],this.rangeDep=!1,this.compiled=null,this.revision=0,this.rankCache=null,this.styles=null,this.kinds=null,this.data=this.type==="string"?new Int32Array(t.capacity).fill(-1):new Float64Array(t.capacity).fill(NaN)}get isString(){return this.type==="string"}get isNumeric(){return tt.has(this.type)||this.type==="any"&&this.kinds===null}_grow(t){const e=this.data,i=this.isString?new Int32Array(t).fill(-1):new Float64Array(t).fill(NaN);if(i.set(e),this.data=i,this.kinds!==null){const n=new Uint8Array(t);n.set(this.kinds),this.kinds=n}if(this.styles!==null){const n=new Uint16Array(t);n.set(this.styles),this.styles=n}}kind(t){if(this.isString)return this.data[t]<0?b:N;if(this.kinds!==null)return this.kinds[t];const e=this.data[t];return e!==e?b:this.type==="boolean"?E:k}raw(t){return this.data[t]}get(t){switch(this.stale&&this.table.ensure(this),this.kind(t)){case k:return this.data[t];case N:return this.table.manager.strings.get(this.data[t]);case E:return this.data[t]!==0;case D:return V[this.data[t]]??null;default:return null}}put(t,e){const{strings:i}=this.table.manager;if(this.isString){this.data[t]=e===null?-1:i.add(String(e));return}if(this.kinds===null){if(typeof e=="number"){this.data[t]=e;return}if(e===null){this.data[t]=NaN;return}if(this.type==="boolean"){this.data[t]=e?1:0;return}this.kinds=new Uint8Array(this.data.length);const n=this.table.rowCount,{data:s,kinds:r}=this;for(let o=0;o<n;o++)r[o]=s[o]!==s[o]?b:k}e===null?(this.kinds[t]=b,this.data[t]=0):typeof e=="number"?(this.kinds[t]=k,this.data[t]=e):typeof e=="string"?(this.kinds[t]=N,this.data[t]=i.add(e)):typeof e=="boolean"?(this.kinds[t]=E,this.data[t]=e?1:0):e instanceof x?(this.kinds[t]=D,this.data[t]=e.index):(this.kinds[t]=b,this.data[t]=0)}coerce(t){if(t==null)return null;if(t==="")return this.type==="string"?"":null;switch(t instanceof Date&&(t=H(t.getUTCFullYear(),t.getUTCMonth()+1,t.getUTCDate())+t.getTime()%864e5/864e5),this.type){case"string":return typeof t=="string"?t:typeof t=="number"?z(t):typeof t=="boolean"?t?"TRUE":"FALSE":t instanceof x?t.code:String(t);case"number":case"date":{if(typeof t=="number")return t;if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){const e=q(t);if(e.kind===k)return e.value;const i=j(t);if(i!=null&&!Number.isNaN(i))return i}throw new m(_(this.type==="date"?`"{value}" isn't a date, which the {field} field needs.`:`"{value}" isn't a number, which the {field} field needs.`,{value:t,field:this.caption}))}case"boolean":if(typeof t=="boolean")return t;if(t===1||t===0)return t===1;if(typeof t=="string"){const e=t.trim().toLowerCase();if(e==="true"||e==="yes")return!0;if(e==="false"||e==="no")return!1}throw new m(_(`"{value}" isn't TRUE or FALSE, which the {field} field needs.`,{value:t,field:this.caption}));default:return t}}ranks(){const{strings:t}=this.table.manager;if(this.rankCache!==null&&this.rankCache.revision===this.revision&&this.rankCache.size===t.size)return this.rankCache;const e=this.table.rowCount,i=new Uint8Array(t.size),{data:n,kinds:s}=this,r=[];if(this.isString)for(let l=0;l<e;l++){const a=n[l];a>=0&&i[a]===0&&(i[a]=1,r.push(a))}else if(s!==null){for(let l=0;l<e;l++)if(s[l]===N){const a=n[l];i[a]===0&&(i[a]=1,r.push(a))}}const{rank:o,count:h}=B(t,r,t.size);return this.rankCache={rank:o,count:h,revision:this.revision,size:t.size},this.rankCache}}class it{constructor(t,e){if(this.manager=t,this.from=t.table(e.from),this.to=t.table(e.to),this.fromField=e.fromField,this.toField=e.toField??e.to_field??this.to.key,this.name=e.name,this.inverse=e.inverse??null,!this.from.column(this.fromField))throw new m(_("No field {field} in {table}",{field:this.fromField,table:this.from.name}));if(!this.toField||!this.to.column(this.toField))throw new m(_("No key field in {table}",{table:this.to.name}));this._parents=null,this._children=null,this._stamp=-1}_currentStamp(){return this.from.structureRevision*4096+this.to.structureRevision}_check(){const t=this._currentStamp();t!==this._stamp&&(this._stamp=t,this._parents=null,this._children=null)}parents(){if(this._check(),this._parents!==null)return this._parents;const t=this.from.column(this.fromField),e=this.to.column(this.toField);this.from.ensure(t),this.to.ensure(e);const i=this.from.rowCount,n=new Int32Array(this.from.capacity).fill(-1);if(t.isString===e.isString&&t.kinds===null&&e.kinds===null){const s=st(e,this.to),{data:r}=t,o=t.isString?-1:NaN;for(let h=0;h<i;h++){const l=r[h];l===o||l!==l||(n[h]=s(l))}}else{const s=new Map;for(let r=this.to.rowCount-1;r>=0;r--)this.to.alive[r]&&s.set(String(e.get(r)),r);for(let r=0;r<i;r++){const o=t.get(r);o!==null&&(n[r]=s.get(String(o))??-1)}}return this._parents=n,n}children(){if(this._check(),this._children!==null)return this._children;const t=this.parents(),e=this.from.rowCount,i=this.to.rowCount,n=new Int32Array(i+2),{alive:s}=this.from;for(let o=0;o<e;o++){const h=t[o];h>=0&&s[o]&&n[h+2]++}for(let o=0;o<i;o++)n[o+2]+=n[o+1];const r=new Int32Array(n[i+1]);for(let o=0;o<e;o++){const h=t[o];h>=0&&s[o]&&(r[n[h+1]++]=o)}return this._children={starts:n,rows:r},this._children}childRows(t){const{starts:e,rows:i}=this.children();return i.subarray(e[t],e[t+1])}}function st(c,t){const{data:e}=c,i=t.rowCount;let n=1/0,s=-1/0,r=!0;for(let h=0;h<i;h++){const l=e[h];l!==l||!t.alive[h]||(l<n&&(n=l),l>s&&(s=l),l!==Math.floor(l)&&(r=!1))}if(r&&s-n<i*4+1024){const h=new Int32Array(s-n+1>0?s-n+1:0).fill(-1);for(let l=i-1;l>=0;l--){const a=e[l];a===a&&t.alive[l]&&(!c.isString||a>=0)&&(h[a-n]=l)}return l=>l>=n&&l<=s&&l===Math.floor(l)?h[l-n]:-1}const o=new Map;for(let h=i-1;h>=0;h--){const l=e[h];l===l&&t.alive[h]&&o.set(l,h)}return h=>o.get(h)??-1}function mt(c,t="children",e="level"){const i=[],n=[];for(let s=c.length-1;s>=0;s--)n.push([c[s],0]);for(;n.length>0;){const[s,r]=n.pop(),{[t]:o,...h}=s;if(i.push({...h,[e]:r}),Array.isArray(o))for(let l=o.length-1;l>=0;l--)n.push([o[l],r+1])}return i}const nt={SUM:"sum",COUNT:"count",COUNTA:"count",AVERAGE:"average",AVG:"average",MIN:"min",MAX:"max"};class M{constructor(t,e,i={}){this.manager=t,this.name=e,this.capacity=Math.max(et,i.capacity??0),this.rowCount=0,this.columns=[],this.byName=new Map,this.alive=new Uint8Array(this.capacity),this.state=new Uint8Array(this.capacity),this.deletedCount=0,this.originals=new Map,this.listeners=new Set,this.revision=0,this.structureRevision=0,this.key=i.key??null,this.tracking=i.tracking!==!1,this.provider=i.provider??null,this.batchDepth=0,this.batchChanged=!1,this.indexes=new Map,this.views=new Map,this.windowDefs=i.windows??{},this.schema=i.schema??null,this.remote=i.remote??null,this.autoSync=i.autoSync===!0,this.batchSync=i.batch===!0,this.rowErrors=new Map,this.fetched=!1,this.fetching=null,this.triggers=[],this.options=i;for(const n of i.fields??[])this.addField(n);i.indexes&&this.createIndexes(i.indexes),i.data&&this.load(i.data)}createIndexes(t){for(const e of t)this.column(e)&&this.indexes.set(e,null)}dropIndexes(t){for(const e of t)this.indexes.delete(e)}clearIndexes(){this.indexes.clear()}getIndexes(){return[...this.indexes.keys()]}searchRows(t,e){const i=this.column(e);if(!i)return[];if(this.ensure(i),this.indexes.has(e)){let r=this.indexes.get(e);if(r===null){r=new Map;const o=this.rowCount;for(let h=0;h<o;h++){if(this.alive[h]===0)continue;const l=i.get(h);if(l===null)continue;const a=r.get(l);a===void 0?r.set(l,[h]):a.push(h)}this.indexes.set(e,r)}return r.get(t)??[]}const n=[],s=this.rowCount;for(let r=0;r<s;r++)this.alive[r]===1&&i.get(r)===t&&n.push(r);return n}search(t,e){return this.searchRows(t,e).map(i=>this.record(i))}_dropIndexOf(t){this.indexes.has(t.name)&&this.indexes.set(t.name,null)}_dropAllIndexes(){for(const t of this.indexes.keys())this.indexes.set(t,null)}ensureOrderColumn(){let t=this.byName.get("__order");if(!t){t=this.addHelper({name:"__order",type:"number",hidden:!0});for(let e=0;e<this.rowCount;e++)t.data[e]=e}return t}column(t){const e=this.byName.get(t);if(e!==void 0)return e;if(typeof t=="string"&&t.includes("."))return this._pathColumn(t)}get fields(){return this.columns.filter(t=>t!==null&&!t.hidden)}addField(t){if(this.byName.has(t.name))throw new m(_("The field {field} already exists in {table}.",{field:t.name,table:this.name}));const e=new O(this,t,this.columns.length);return this.columns.push(e),this.byName.set(e.name,e),e.formula!==null&&this.manager.formulas.bind(e),e.trigger&&this.triggers.push(e),this.computedOrder=null,this.revision++,this._emit({type:"schema"}),e}removeField(t){const e=this.byName.get(t);if(e){this.byName.delete(t),this.columns[e.index]=null,this.computedOrder=null,this.revision++;for(const i of this.columns)i&&i.computed&&(i.stale=!0);this._emit({type:"schema"})}}setFormula(t,e){const i=this.byName.get(t);if(!i)throw new m(`No field ${t} in ${this.name}`);i.formula=e,i.computed=!0,i.stale=!0,this.manager.formulas.bind(i),this.computedOrder=null,this._markDependentsStale(i),this.revision++,this._emit({type:"reload"})}_pathColumn(t){const e=t.indexOf("."),i=t.slice(0,e),n=t.slice(e+1),s=this.manager.relationshipFrom(this,i);if(!s)return;const r=s.to.column(n);if(r)return this.addHelper({name:t,type:r.type==="string"?"string":r.type,format:r.format,caption:r.caption,readOnly:!0,hidden:!0,lookup:{relation:s,field:n}})}addHelper(t){const e=new O(this,t,this.columns.length);return this.columns.push(e),this.byName.set(e.name,e),this.computedOrder=null,e}rollupColumn(t,e){const i=`${t}(${e})`,n=this.byName.get(i);if(n)return n;const s=e.indexOf(".");if(s<0)return;const r=this.manager.relationshipTo(this,e.slice(0,s)),o=nt[t];if(!r||!o)return;const h=e.slice(s+1);if(r.from.column(h))return this.addHelper({name:i,type:"number",readOnly:!0,hidden:!0,rollup:{relation:r,field:h,agg:o}})}ensure(t){t.stale&&(t.stale=!1,t.window!==null?K(t):t.formula!==null?this.manager.formulas.computeAll(t):t.lookup!==null?this._computeLookup(t):t.rollup!==null&&this._computeRollup(t),t.revision++)}ensureAll(){for(const t of this.columns)t!==null&&t.stale&&this.ensure(t)}_computeLookup(t){const{relation:e,field:i}=t.lookup,n=e.parents(),s=e.to.column(i);e.to.ensure(s);const r=this.rowCount,{data:o}=t,h=s.data;if(t.isString&&s.isString)for(let l=0;l<r;l++){const a=n[l];o[l]=a<0?-1:h[a]}else if(!t.isString&&!s.isString&&s.kinds===null){t.kinds=null;for(let l=0;l<r;l++){const a=n[l];o[l]=a<0?NaN:h[a]}}else for(let l=0;l<r;l++){const a=n[l];t.put(l,a<0?null:s.get(a))}}_computeRollup(t){const{relation:e,field:i,agg:n}=t.rollup,s=e.from.column(i);e.from.ensure(s);const{starts:r,rows:o}=e.children(),h=this.rowCount,{data:l}=t,a=s.data,p=s.isNumeric;for(let f=0;f<h;f++){const d=r[f],w=r[f+1];let y=0,g=0,v=1/0,R=-1/0;for(let A=d;A<w;A++){const U=o[A];if(!p){s.kind(U)!==b&&g++;continue}const C=a[U];C===C&&(y+=C,g++,C<v&&(v=C),C>R&&(R=C))}switch(n){case"sum":l[f]=y;break;case"count":l[f]=g;break;case"average":l[f]=g>0?y/g:NaN;break;case"min":l[f]=g>0?v:NaN;break;default:l[f]=g>0?R:NaN}}}_order(){if(this.computedOrder)return this.computedOrder;const t=[],e=new Set,i=n=>{if(!e.has(n)){e.add(n);for(const s of n.deps){const r=this.column(s);r&&r.computed&&i(r)}t.push(n)}};for(const n of this.columns)n&&n.computed&&i(n);return this.computedOrder=t,t}_reserve(t){if(t<=this.capacity)return;let e=this.capacity;for(;e<t;)e*=2;for(const n of this.columns)n!==null&&n._grow(e);const i=n=>{const s=new Uint8Array(e);return s.set(n),s};this.alive=i(this.alive),this.state=i(this.state),this.capacity=e}get liveCount(){return this.rowCount-this.deletedCount}load(t){this.schema&&(t=W(t,this.schema)),Array.isArray(t)&&t.length>0&&this.schema?.spread&&(t=t.map(r=>X(r)));const e=Array.isArray(t)?t:null;if(e!==null&&this.columns.length===0&&e.length>0&&this._inferFields(e),e===null)return this._loadColumns(t);const i=e.length;this._reserve(i);const n=this.columns.filter(r=>r!==null&&!r.computed),s=i>0&&Array.isArray(e[0]);for(const r of n)r.rankCache=null,r.kinds=null,r.data.fill(r.isString?-1:NaN,0,this.capacity);this.rowCount=i;for(let r=0;r<n.length;r++){const o=n[r];for(let h=0;h<i;h++){const l=s?e[h][r]:J(e[h],o.name);l!=null&&o.put(h,o.coerce(l))}}return this._afterLoad(i),i}_loadColumns(t){let e=0;for(const i of Object.values(t))e=Math.max(e,i.length);this._reserve(e),this.rowCount=e;for(const[i,n]of Object.entries(t)){let s=this.byName.get(i);if(!s){const r=n.length>0?n[0]:null;s=this.addField({name:i,type:ArrayBuffer.isView(n)||typeof r=="number"?"number":typeof r=="boolean"?"boolean":"string"}),this._reserve(e)}if(s.rankCache=null,ArrayBuffer.isView(n)&&!s.isString)s.kinds=null,s.data.set(n),n.length<this.capacity&&s.data.fill(NaN,n.length);else if(s.isString&&n instanceof Int32Array)s.data.set(n);else for(let r=0;r<n.length;r++){const o=n[r];o!=null&&s.put(r,s.coerce(o))}}return this._afterLoad(e),e}_afterLoad(t){this._dropAllIndexes(),this.rowErrors.clear(),this.alive.fill(1,0,t),this.alive.fill(0,t),this.state.fill(0),this.originals.clear(),this.deletedCount=0,this.revision++,this.structureRevision++,this._markAllComputedStale(),this.manager._tableChanged(this),this._emit({type:"reload"})}_inferFields(t){const e=t[0];if(Array.isArray(e)){e.forEach((s,r)=>this.addField({name:`Field${r+1}`,type:S(t,r)}));return}const i=new Set,n=Math.min(t.length,200);for(let s=0;s<n;s++)for(const r of Object.keys(t[s]))i.add(r);for(const s of i)this.addField({name:s,type:S(t,s)})}loadSheet(t,e,i,{header:n=!0}={}){const s=[],{strings:r}=t;for(let a=i.c0;a<=i.c1;a++){const f=(e.kind(i.r0,a)&T)===N?r.get(e.value(i.r0,a)):"";s.push(n&&f?f:`Field${a-i.c0+1}`)}const o=n?i.r0+1:i.r0,h=Math.max(0,i.r1-o+1),l=(a,p)=>{const f=e.kind(a,p)&T,d=e.value(a,p);return f===k?d:f===N?r.get(d):f===E?d!==0:f===D?$.get(P[d])??null:null};return s.forEach((a,p)=>{if(this.byName.has(a))return;const f=[];for(let g=o;g<=Math.min(o+199,o+h-1);g++)f.push([l(g,i.c0+p)]);const d=t.styles?.get(e.style(o,i.c0+p)),w=d&&/[ymd]/i.test(String(d.numFmt??"").replace(/"[^"]*"/g,"")),y=S(f,0);this.addField({name:a,type:y==="number"&&w?"date":y,format:d?.numFmt!=="General"?d?.numFmt:void 0})}),this._reserve(h),this.rowCount=h,s.forEach((a,p)=>{const f=this.byName.get(a),d=i.c0+p;f.rankCache=null;for(let w=0;w<h;w++){const y=l(o+w,d);f.put(w,y instanceof x?null:f.coerce(y))}}),this._afterLoad(h),h}addRow(t={},{track:e=!0}={}){const i=this.rowCount;this._reserve(i+1),this.rowCount=i+1,this.alive[i]=1,this.state[i]=e&&this.tracking?u.INSERTED:u.UNCHANGED;for(const s of this.columns){if(s===null||s.computed)continue;let r=t[s.name]!==void 0?t[s.name]:s.defaultValue;typeof r=="string"&&r[0]==="="&&t[s.name]===void 0&&(r=this.manager.formulas.evaluateOnce(this,i,r)),s.put(i,r==null?null:s.coerce(r)),s.rankCache=null}const n=this.byName.get("__order");return n&&(n.data[i]=t.__order??this._nextOrder(n.data)),this._dropAllIndexes(),this._runTriggers(i,!0),this._rowsChanged(i),this._emit({type:"rows",row:i,added:!0}),i}_nextOrder(t){let e=-1;for(let i=0;i<this.rowCount;i++)t[i]>e&&(e=t[i]);return e+1}_runTriggers(t,e){for(const i of this.triggers){if(!e&&i.trigger.when!=="newAndUpdate")continue;const n=this.manager.formulas.evaluateOnce(this,t,i.trigger.formula);i.put(t,n instanceof x?null:i.coerce(n)),i.revision++}}removeRow(t){return this.alive[t]?(this.alive[t]=0,this.deletedCount++,this._dropAllIndexes(),this._rowsChanged(t),this._emit({type:"rows",row:t,removed:!0}),this._autoPush(),!0):!1}restoreRow(t){return this.alive[t]?!1:(this.alive[t]=1,this.deletedCount--,this.state[t]===u.PURGED&&(this.state[t]=u.UNCHANGED),this._rowsChanged(t),this._emit({type:"rows",row:t,added:!0}),!0)}_rowsChanged(t){this.revision++,this.structureRevision++;for(const e of this._order())this._recomputeRowOrAll(e,t);this.manager._tableChanged(this)}_recomputeRowOrAll(t,e){t.stale||(t.formula!==null&&!t.rangeDep&&e<this.rowCount?this.manager.formulas.computeRow(t,e):t.stale=!0)}_markAllComputedStale(){for(const t of this.columns)t!==null&&t.computed&&(t.stale=!0)}_markDependentsStale(t){for(const e of this._order())e!==t&&e.deps.includes(t.name)&&(e.stale=!0,this._markDependentsStale(e))}get(t,e){const i=this.column(e);if(!i)throw new m(`No field ${e} in ${this.name}`);return i.get(t)}set(t,e,i){const n=typeof e=="string"?this.column(e):e;if(!n)throw new m(`No field ${e} in ${this.name}`);if(n.computed)throw new m(_("The {field} field is calculated, so it can't be edited.",{field:n.caption}));if(n.readOnly)throw new m(_("The {field} field is read-only.",{field:n.caption}));const s=n.coerce(i),r=n.get(t);if(G(r,s))return!1;if(n.validator!==null){const o=Y(n,s,t);if(o)throw new m(o)}if(n.required&&(s===null||s===""))throw new m(_("The {field} field can't be blank.",{field:n.caption}));return this.tracking&&this.state[t]!==u.INSERTED&&this._track(t,n,r,s),n.put(t,s),n.revision++,this._dropIndexOf(n),this.triggers.length>0&&this._runTriggers(t,!1),this._afterEdit(t,n),this._autoPush(),!0}_track(t,e,i,n){let s=this.originals.get(t);s===void 0&&(s=new Map,this.originals.set(t,s)),s.has(e.index)?G(s.get(e.index),n)&&s.delete(e.index):s.set(e.index,i),s.size===0?(this.originals.delete(t),this.state[t]=u.UNCHANGED):this.state[t]=u.UPDATED}_afterEdit(t,e){this.revision++;const i=new Set([e.name]);let n=this.manager.isKeyField(this,e.name);for(const s of this._order())s.deps.some(r=>i.has(r))&&(i.add(s.name),s.rangeDep||s.formula===null?s.stale=!0:s.stale||this.manager.formulas.computeRow(s,t),this.manager.isKeyField(this,s.name)&&(n=!0));n&&this.structureRevision++,this.manager._fieldChanged(this,i),this._emit({type:"cell",row:t,col:e})}batch(t){this.batchDepth++;try{return t()}finally{this.batchDepth--,this.batchDepth===0&&this.batchChanged&&(this.batchChanged=!1,this._emit({type:"reload"}))}}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(t){if(this.batchDepth>0){this.batchChanged=!0;return}for(const e of this.listeners)e(t)}getChanges(){const t=[],e=[],i=[],n=this.rowCount,{state:s,alive:r}=this;for(let o=0;o<n;o++)if(s[o]!==u.PURGED){if(s[o]===u.INSERTED)r[o]&&t.push(Object.defineProperty(this.record(o),"__row",{value:o,enumerable:!1}));else if(!r[o])i.push({row:o,record:this.originalRecord(o)});else if(s[o]===u.UPDATED){const h=this.originals.get(o),l={},a={};for(const[p,f]of h){const d=this.columns[p];l[d.name]=d.get(o),a[d.name]=f}e.push({row:o,record:this.record(o),changes:l,original:a})}}return{inserted:t,updated:e,deleted:i}}get hasChanges(){if(this.originals.size>0)return!0;const{state:t,alive:e}=this;for(let i=0;i<this.rowCount;i++)if(t[i]===u.INSERTED?e[i]===1:t[i]!==u.PURGED&&e[i]===0)return!0;return!1}originalValue(t,e){return this.originals.get(t)?.get(e.index)}isCellEdited(t,e){return this.originals.get(t)?.has(e.index)===!0}record(t){const e={};for(const i of this.columns)i!==null&&!i.hidden&&(e[i.name]=i.get(t));return e}originalRecord(t){const e=this.record(t),i=this.originals.get(t);if(i)for(const[n,s]of i)e[this.columns[n].name]=s;return e}acceptChanges(){this.originals.clear();const t=this.rowCount,{state:e,alive:i}=this;for(let n=0;n<t;n++)e[n]=i[n]?u.UNCHANGED:u.PURGED;this.revision++,this._emit({type:"cells"})}rejectChanges(){this.batch(()=>{for(const[s,r]of this.originals)for(const[o,h]of r){const l=this.columns[o];l.put(s,h),l.revision++}this.originals.clear();const t=this.rowCount,{state:e,alive:i}=this;let n=0;for(let s=0;s<t;s++)e[s]===u.INSERTED?(i[s]=0,e[s]=u.PURGED):e[s]!==u.PURGED&&(i[s]=1,e[s]=u.UNCHANGED),i[s]===0&&n++;this.deletedCount=n,this.structureRevision++,this.revision++,this._markAllComputedStale(),this.manager._tableChanged(this),this.batchChanged=!0})}revertRow(t){const e=this.originals.get(t);if(e){for(const[i,n]of e){const s=this.columns[i];s.put(t,n),s.revision++,this._afterEdit(t,s)}this.originals.delete(t),this.state[t]=u.UNCHANGED}if(this.state[t]===u.INSERTED){this.state[t]=u.PURGED,this.removeRow(t);return}this.alive[t]||this.restoreRow(t),this._emit({type:"cell",row:t})}connect(t){this.remote=t,this.provider=null}fetch(t=!1){return this.fetched&&!t?Promise.resolve(this):this.fetching?this.fetching:!this.remote&&this.options.data===void 0&&!t?(this.fetched=!0,Promise.resolve(this)):this.remote?(this.fetching=Q(this.remote,this.schema).then(e=>(this.load(e),this.fetched=!0,this.fetching=null,this),e=>{throw this.fetching=null,e}),this.fetching):Promise.resolve(this)}pull(){return this.fetch(!0)}_autoPush(){!this.autoSync||!this.remote||this.batchDepth>0||this._pushing||(this._pushing=!0,queueMicrotask(()=>{this._pushing=!1,this.submitChanges().catch(()=>{})}))}async submitChanges(){if(!this.remote)throw new m(_("{table} has no data source to write to.",{table:this.name}));const t=this.getChanges(),e=await I(this,t);return this.rowErrors=e.errors,e.errors.size===0?this.acceptChanges():this._acceptExcept(e.errors),this._emit({type:"cells"}),e.counts}push(){return this.submitChanges()}cancelChanges(){this.rejectChanges()}_acceptExcept(t){const e=this.rowCount,{state:i,alive:n}=this;for(let s=0;s<e;s++)t.has(s)||(this.originals.delete(s),i[s]=n[s]?u.UNCHANGED:u.PURGED);this.revision++}async saveRow(t){if(!this.remote){this.originals.delete(t),this.state[t]=this.alive[t]?u.UNCHANGED:u.PURGED,this._emit({type:"cells"});return}const e=this.getChanges(),i={inserted:e.inserted.filter(s=>s.__row===t),updated:e.updated.filter(s=>s.row===t),deleted:e.deleted.filter(s=>s.row===t)},n=await I(this,i);n.errors.has(t)?this.rowErrors.set(t,n.errors.get(t)):(this.rowErrors.delete(t),this.originals.delete(t),this.state[t]=this.alive[t]?u.UNCHANGED:u.PURGED),this._emit({type:"cells"})}resetRow(t){this.rowErrors.delete(t),this.revertRow(t)}missingRequired(t){const e=[];for(const i of this.columns)i!==null&&i.required&&(i.kind(t)===b||i.get(t)==="")&&e.push(i.caption);return e}}const G=(c,t)=>c===t?!0:c===null||t===null||typeof c=="string"&&typeof t=="string"?!1:typeof c=="boolean"&&typeof t=="number"?(c?1:0)===t:typeof c=="number"&&typeof t=="boolean"?(t?1:0)===c:!1;function S(c,t){let e=null;const i=Math.min(c.length,500);for(let n=0;n<i;n++){const s=c[n][t];if(s==null||s==="")continue;const r=s instanceof Date?"date":typeof s=="number"?"number":typeof s=="boolean"?"boolean":typeof s=="string"?"string":"any";if(e===null)e=r;else if(e!==r)if(e==="date"&&r==="number"||e==="number"&&r==="date")e="number";else return"any"}return e??"string"}let F=null;function pt(c){F=c}class gt{constructor(t=null){this.book=t,this.strings=t?.strings??new L,this.tables=new Map,this.relationships=[],this._formulas=null}get formulas(){if(this._formulas===null){if(F===null)throw new Error("Formula support is not loaded. Import datasheets/data.js first.");this._formulas=new F(this)}return this._formulas}addTable(t,e={}){if(this.tables.has(t))throw new m(`The table ${t} already exists.`);const i=new M(this,t,e);return this.tables.set(t,i),i}table(t){if(t instanceof M)return t;const e=this.tables.get(t);if(!e)throw new m(`No table named ${t}.`);return e}removeTable(t){const e=this.table(t);this.tables.delete(e.name),this.relationships=this.relationships.filter(i=>i.from!==e&&i.to!==e)}addRelationship(t){const e=new it(this,t);return this.relationships.push(e),e}removeRelationship(t){this.relationships=this.relationships.filter(e=>e!==t)}relationshipFrom(t,e){return this.relationships.find(i=>i.from===t&&i.name===e)??null}relationshipTo(t,e){return this.relationships.find(i=>i.to===t&&i.inverse===e)??null}relationshipBetween(t,e){return this.relationships.find(i=>i.from===t&&i.to===e||i.from===e&&i.to===t)??null}isKeyField(t,e){return this.relationships.length===0?!1:this.relationships.some(i=>i.from===t&&i.fromField===e||i.to===t&&i.toField===e)}_tableChanged(t){for(const e of this.tables.values()){let i=!1;for(const n of e.columns)n!==null&&(n.lookup&&(n.lookup.relation.to===t||n.lookup.relation.from===t)||n.rollup&&(n.rollup.relation.from===t||n.rollup.relation.to===t))&&(n.stale||(n.stale=!0,i=!0,e._markDependentsStale(n)));i&&e!==t&&e._emit({type:"reload",derived:!0})}}_fieldChanged(t,e){if(this.relationships.length!==0)for(const i of this.tables.values()){let n=!1;for(const s of i.columns){if(s===null)continue;(s.window&&s.window.table===t&&s.deps.some(o=>e.has(o))||s.lookup&&s.lookup.relation.to===t&&e.has(s.lookup.field)||s.rollup&&s.rollup.relation.from===t&&e.has(s.rollup.field)||s.lookup&&s.lookup.relation.from===t&&e.has(s.lookup.relation.fromField)||s.rollup&&s.rollup.relation.from===t&&e.has(s.rollup.relation.fromField))&&!s.stale&&(s.stale=!0,n=!0,i._markDependentsStale(s))}n&&i!==t&&i._emit({type:"reload",derived:!0})}}}export{O as DataColumn,m as DataError,gt as DataManager,M as DataTable,Z as FIELD_TYPES,u as ROW,it as Relationship,mt as flattenTree,pt as installFormulas,st as keyIndex};
|
|
1
|
+
import{BOOL as E,EMPTY as b,ERR as D,ERRORS as P,KIND_MASK as T,NUM as k,STR as N}from"../core/sheet.js";import{partsToSerial as H}from"../core/numfmt.js";import{StringTable as L}from"../core/strings.js";import{ERR_BY_CODE as $,ERR_BY_INDEX as V,numberToText as z,textToNumber as j,XlError as x}from"../calc/values.js";import{parseInput as q}from"../core/input.js";import{rankStrings as B}from"./sort.js";import{computeWindow as K}from"./window.js";import{checkValidator as Y,flattenRecord as X,parseSource as W,readField as J,readRemote as Q,sendChanges as I}from"./remote.js";import{t as _}from"../i18n/index.js";const Z=["number","date","boolean","string","any"],tt=new Set(["number","date","boolean"]),u={UNCHANGED:0,INSERTED:1,UPDATED:2,PURGED:3},et=256;class m extends Error{}class O{constructor(t,e,i){if(this.table=t,this.index=i,this.name=e.name,this.caption=e.caption??e.name,this.type=e.type??"any",!Z.includes(this.type))throw new m(`Unknown field type: ${this.type}`);this.format=e.format??(this.type==="date"?"yyyy-mm-dd":"General"),this.readOnly=e.readOnly===!0,this.defaultValue=e.defaultValue??null,this.width=e.width??null,this.hidden=e.hidden===!0,this.formula=e.formula??null,this.lookup=e.lookup??null,this.rollup=e.rollup??null,this.window=e.window??null,this.required=e.required===!0,this.showNullAs=e.showNullAs??null,this.validator=e.validator??null,this.trigger=e.trigger??null,this.computed=this.formula!==null||this.lookup!==null||this.rollup!==null||this.window!==null,this.stale=this.computed,this.deps=[],this.rangeDep=!1,this.compiled=null,this.revision=0,this.rankCache=null,this.styles=null,this.kinds=null,this.data=this.type==="string"?new Int32Array(t.capacity).fill(-1):new Float64Array(t.capacity).fill(NaN)}get isString(){return this.type==="string"}get isNumeric(){return tt.has(this.type)||this.type==="any"&&this.kinds===null}_grow(t){const e=this.data,i=this.isString?new Int32Array(t).fill(-1):new Float64Array(t).fill(NaN);if(i.set(e),this.data=i,this.kinds!==null){const n=new Uint8Array(t);n.set(this.kinds),this.kinds=n}if(this.styles!==null){const n=new Uint16Array(t);n.set(this.styles),this.styles=n}}kind(t){if(this.isString)return this.data[t]<0?b:N;if(this.kinds!==null)return this.kinds[t];const e=this.data[t];return e!==e?b:this.type==="boolean"?E:k}raw(t){return this.data[t]}get(t){switch(this.stale&&this.table.ensure(this),this.kind(t)){case k:return this.data[t];case N:return this.table.manager.strings.get(this.data[t]);case E:return this.data[t]!==0;case D:return V[this.data[t]]??null;default:return null}}put(t,e){const{strings:i}=this.table.manager;if(this.isString){this.data[t]=e===null?-1:i.add(String(e));return}if(this.kinds===null){if(typeof e=="number"){this.data[t]=e;return}if(e===null){this.data[t]=NaN;return}if(this.type==="boolean"){this.data[t]=e?1:0;return}this.kinds=new Uint8Array(this.data.length);const n=this.table.rowCount,{data:s,kinds:r}=this;for(let o=0;o<n;o++)r[o]=s[o]!==s[o]?b:k}e===null?(this.kinds[t]=b,this.data[t]=0):typeof e=="number"?(this.kinds[t]=k,this.data[t]=e):typeof e=="string"?(this.kinds[t]=N,this.data[t]=i.add(e)):typeof e=="boolean"?(this.kinds[t]=E,this.data[t]=e?1:0):e instanceof x?(this.kinds[t]=D,this.data[t]=e.index):(this.kinds[t]=b,this.data[t]=0)}coerce(t){if(t==null)return null;if(t==="")return this.type==="string"?"":null;switch(t instanceof Date&&(t=H(t.getUTCFullYear(),t.getUTCMonth()+1,t.getUTCDate())+t.getTime()%864e5/864e5),this.type){case"string":return typeof t=="string"?t:typeof t=="number"?z(t):typeof t=="boolean"?t?"TRUE":"FALSE":t instanceof x?t.code:String(t);case"number":case"date":{if(typeof t=="number")return t;if(typeof t=="boolean")return t?1:0;if(typeof t=="string"){const e=q(t);if(e.kind===k)return e.value;const i=j(t);if(i!=null&&!Number.isNaN(i))return i}throw new m(_(this.type==="date"?`"{value}" isn't a date, which the {field} field needs.`:`"{value}" isn't a number, which the {field} field needs.`,{value:t,field:this.caption}))}case"boolean":if(typeof t=="boolean")return t;if(t===1||t===0)return t===1;if(typeof t=="string"){const e=t.trim().toLowerCase();if(e==="true"||e==="yes")return!0;if(e==="false"||e==="no")return!1}throw new m(_(`"{value}" isn't TRUE or FALSE, which the {field} field needs.`,{value:t,field:this.caption}));default:return t}}ranks(){const{strings:t}=this.table.manager;if(this.rankCache!==null&&this.rankCache.revision===this.revision&&this.rankCache.size===t.size)return this.rankCache;const e=this.table.rowCount,i=new Uint8Array(t.size),{data:n,kinds:s}=this,r=[];if(this.isString)for(let l=0;l<e;l++){const a=n[l];a>=0&&i[a]===0&&(i[a]=1,r.push(a))}else if(s!==null){for(let l=0;l<e;l++)if(s[l]===N){const a=n[l];i[a]===0&&(i[a]=1,r.push(a))}}const{rank:o,count:h}=B(t,r,t.size);return this.rankCache={rank:o,count:h,revision:this.revision,size:t.size},this.rankCache}}class it{constructor(t,e){if(this.manager=t,this.from=t.table(e.from),this.to=t.table(e.to),this.fromField=e.fromField,this.toField=e.toField??e.to_field??this.to.key,this.name=e.name,this.inverse=e.inverse??null,!this.from.column(this.fromField))throw new m(_("No field {field} in {table}",{field:this.fromField,table:this.from.name}));if(!this.toField||!this.to.column(this.toField))throw new m(_("No key field in {table}",{table:this.to.name}));this._parents=null,this._children=null,this._stamp=-1}_currentStamp(){return this.from.structureRevision*4096+this.to.structureRevision}_check(){const t=this._currentStamp();t!==this._stamp&&(this._stamp=t,this._parents=null,this._children=null)}parents(){if(this._check(),this._parents!==null)return this._parents;const t=this.from.column(this.fromField),e=this.to.column(this.toField);this.from.ensure(t),this.to.ensure(e);const i=this.from.rowCount,n=new Int32Array(this.from.capacity).fill(-1);if(t.isString===e.isString&&t.kinds===null&&e.kinds===null){const s=st(e,this.to),{data:r}=t,o=t.isString?-1:NaN;for(let h=0;h<i;h++){const l=r[h];l===o||l!==l||(n[h]=s(l))}}else{const s=new Map;for(let r=this.to.rowCount-1;r>=0;r--)this.to.alive[r]&&s.set(String(e.get(r)),r);for(let r=0;r<i;r++){const o=t.get(r);o!==null&&(n[r]=s.get(String(o))??-1)}}return this._parents=n,n}children(){if(this._check(),this._children!==null)return this._children;const t=this.parents(),e=this.from.rowCount,i=this.to.rowCount,n=new Int32Array(i+2),{alive:s}=this.from;for(let o=0;o<e;o++){const h=t[o];h>=0&&s[o]&&n[h+2]++}for(let o=0;o<i;o++)n[o+2]+=n[o+1];const r=new Int32Array(n[i+1]);for(let o=0;o<e;o++){const h=t[o];h>=0&&s[o]&&(r[n[h+1]++]=o)}return this._children={starts:n,rows:r},this._children}childRows(t){const{starts:e,rows:i}=this.children();return i.subarray(e[t],e[t+1])}}function st(c,t){const{data:e}=c,i=t.rowCount;let n=1/0,s=-1/0,r=!0;for(let h=0;h<i;h++){const l=e[h];l!==l||!t.alive[h]||(l<n&&(n=l),l>s&&(s=l),l!==Math.floor(l)&&(r=!1))}if(r&&s-n<i*4+1024){const h=new Int32Array(s-n+1>0?s-n+1:0).fill(-1);for(let l=i-1;l>=0;l--){const a=e[l];a===a&&t.alive[l]&&(!c.isString||a>=0)&&(h[a-n]=l)}return l=>l>=n&&l<=s&&l===Math.floor(l)?h[l-n]:-1}const o=new Map;for(let h=i-1;h>=0;h--){const l=e[h];l===l&&t.alive[h]&&o.set(l,h)}return h=>o.get(h)??-1}function mt(c,t="children",e="level"){const i=[],n=[];for(let s=c.length-1;s>=0;s--)n.push([c[s],0]);for(;n.length>0;){const[s,r]=n.pop(),{[t]:o,...h}=s;if(i.push({...h,[e]:r}),Array.isArray(o))for(let l=o.length-1;l>=0;l--)n.push([o[l],r+1])}return i}const nt={SUM:"sum",COUNT:"count",COUNTA:"count",AVERAGE:"average",AVG:"average",MIN:"min",MAX:"max"};class M{constructor(t,e,i={}){this.manager=t,this.name=e,this.capacity=Math.max(et,i.capacity??0),this.rowCount=0,this.columns=[],this.byName=new Map,this.alive=new Uint8Array(this.capacity),this.state=new Uint8Array(this.capacity),this.deletedCount=0,this.originals=new Map,this.listeners=new Set,this.revision=0,this.structureRevision=0,this.key=i.key??null,this.tracking=i.tracking!==!1,this.provider=i.provider??null,this.batchDepth=0,this.batchChanged=!1,this.indexes=new Map,this.views=new Map,this.windowDefs=i.windows??{},this.schema=i.schema??null,this.remote=i.remote??null,this.autoSync=i.autoSync===!0,this.batchSync=i.batch===!0,this.rowErrors=new Map,this.fetched=!1,this.fetching=null,this.triggers=[],this.options=i;for(const n of i.fields??[])this.addField(n);i.indexes&&this.createIndexes(i.indexes),i.data&&this.load(i.data)}createIndexes(t){for(const e of t)this.column(e)&&this.indexes.set(e,null)}dropIndexes(t){for(const e of t)this.indexes.delete(e)}clearIndexes(){this.indexes.clear()}getIndexes(){return[...this.indexes.keys()]}searchRows(t,e){const i=this.column(e);if(!i)return[];if(this.ensure(i),this.indexes.has(e)){let r=this.indexes.get(e);if(r===null){r=new Map;const o=this.rowCount;for(let h=0;h<o;h++){if(this.alive[h]===0)continue;const l=i.get(h);if(l===null)continue;const a=r.get(l);a===void 0?r.set(l,[h]):a.push(h)}this.indexes.set(e,r)}return r.get(t)??[]}const n=[],s=this.rowCount;for(let r=0;r<s;r++)this.alive[r]===1&&i.get(r)===t&&n.push(r);return n}search(t,e){return this.searchRows(t,e).map(i=>this.record(i))}_dropIndexOf(t){this.indexes.has(t.name)&&this.indexes.set(t.name,null)}_dropAllIndexes(){for(const t of this.indexes.keys())this.indexes.set(t,null)}ensureOrderColumn(){let t=this.byName.get("__order");if(!t){t=this.addHelper({name:"__order",type:"number",hidden:!0});for(let e=0;e<this.rowCount;e++)t.data[e]=e}return t}column(t){const e=this.byName.get(t);if(e!==void 0)return e;if(typeof t=="string"&&t.includes("."))return this._pathColumn(t)}get fields(){return this.columns.filter(t=>t!==null&&!t.hidden)}addField(t){if(this.byName.has(t.name))throw new m(_("The field {field} already exists in {table}.",{field:t.name,table:this.name}));const e=new O(this,t,this.columns.length);return this.columns.push(e),this.byName.set(e.name,e),e.formula!==null&&this.manager.formulas.bind(e),e.trigger&&this.triggers.push(e),this.computedOrder=null,this.revision++,this._emit({type:"schema"}),e}removeField(t){const e=this.byName.get(t);if(e){this.byName.delete(t),this.columns[e.index]=null,this.computedOrder=null,this.revision++;for(const i of this.columns)i&&i.computed&&(i.stale=!0);this._emit({type:"schema"})}}setFormula(t,e){const i=this.byName.get(t);if(!i)throw new m(`No field ${t} in ${this.name}`);i.formula=e,i.computed=!0,i.stale=!0,this.manager.formulas.bind(i),this.computedOrder=null,this._markDependentsStale(i),this.revision++,this._emit({type:"reload"})}_pathColumn(t){const e=t.indexOf("."),i=t.slice(0,e),n=t.slice(e+1),s=this.manager.relationshipFrom(this,i);if(!s)return;const r=s.to.column(n);if(r)return this.addHelper({name:t,type:r.type==="string"?"string":r.type,format:r.format,caption:r.caption,readOnly:!0,hidden:!0,lookup:{relation:s,field:n}})}addHelper(t){const e=new O(this,t,this.columns.length);return this.columns.push(e),this.byName.set(e.name,e),this.computedOrder=null,e}rollupColumn(t,e){const i=`${t}(${e})`,n=this.byName.get(i);if(n)return n;const s=e.indexOf(".");if(s<0)return;const r=this.manager.relationshipTo(this,e.slice(0,s)),o=nt[t];if(!r||!o)return;const h=e.slice(s+1);if(r.from.column(h))return this.addHelper({name:i,type:"number",readOnly:!0,hidden:!0,rollup:{relation:r,field:h,agg:o}})}ensure(t){t.stale&&(t.stale=!1,t.window!==null?K(t):t.formula!==null?this.manager.formulas.computeAll(t):t.lookup!==null?this._computeLookup(t):t.rollup!==null&&this._computeRollup(t),t.revision++)}ensureAll(){for(const t of this.columns)t!==null&&t.stale&&this.ensure(t)}_computeLookup(t){const{relation:e,field:i}=t.lookup,n=e.parents(),s=e.to.column(i);e.to.ensure(s);const r=this.rowCount,{data:o}=t,h=s.data;if(t.isString&&s.isString)for(let l=0;l<r;l++){const a=n[l];o[l]=a<0?-1:h[a]}else if(!t.isString&&!s.isString&&s.kinds===null){t.kinds=null;for(let l=0;l<r;l++){const a=n[l];o[l]=a<0?NaN:h[a]}}else for(let l=0;l<r;l++){const a=n[l];t.put(l,a<0?null:s.get(a))}}_computeRollup(t){const{relation:e,field:i,agg:n}=t.rollup,s=e.from.column(i);e.from.ensure(s);const{starts:r,rows:o}=e.children(),h=this.rowCount,{data:l}=t,a=s.data,p=s.isNumeric;for(let f=0;f<h;f++){const d=r[f],w=r[f+1];let y=0,g=0,v=1/0,R=-1/0;for(let A=d;A<w;A++){const U=o[A];if(!p){s.kind(U)!==b&&g++;continue}const C=a[U];C===C&&(y+=C,g++,C<v&&(v=C),C>R&&(R=C))}switch(n){case"sum":l[f]=y;break;case"count":l[f]=g;break;case"average":l[f]=g>0?y/g:NaN;break;case"min":l[f]=g>0?v:NaN;break;default:l[f]=g>0?R:NaN}}}_order(){if(this.computedOrder)return this.computedOrder;const t=[],e=new Set,i=n=>{if(!e.has(n)){e.add(n);for(const s of n.deps){const r=this.column(s);r&&r.computed&&i(r)}t.push(n)}};for(const n of this.columns)n&&n.computed&&i(n);return this.computedOrder=t,t}_reserve(t){if(t<=this.capacity)return;let e=this.capacity;for(;e<t;)e*=2;for(const n of this.columns)n!==null&&n._grow(e);const i=n=>{const s=new Uint8Array(e);return s.set(n),s};this.alive=i(this.alive),this.state=i(this.state),this.capacity=e}get liveCount(){return this.rowCount-this.deletedCount}load(t){this.schema&&(t=W(t,this.schema)),Array.isArray(t)&&t.length>0&&this.schema?.spread&&(t=t.map(r=>X(r)));const e=Array.isArray(t)?t:null;if(e!==null&&this.columns.length===0&&e.length>0&&this._inferFields(e),e===null)return this._loadColumns(t);const i=e.length;this._reserve(i);const n=this.columns.filter(r=>r!==null&&!r.computed),s=i>0&&Array.isArray(e[0]);for(const r of n)r.rankCache=null,r.kinds=null,r.data.fill(r.isString?-1:NaN,0,this.capacity);this.rowCount=i;for(let r=0;r<n.length;r++){const o=n[r];for(let h=0;h<i;h++){const l=s?e[h][r]:J(e[h],o.name);l!=null&&o.put(h,o.coerce(l))}}return this._afterLoad(i),i}_loadColumns(t){let e=0;for(const i of Object.values(t))e=Math.max(e,i.length);this._reserve(e),this.rowCount=e;for(const[i,n]of Object.entries(t)){let s=this.byName.get(i);if(!s){const r=n.length>0?n[0]:null;s=this.addField({name:i,type:ArrayBuffer.isView(n)||typeof r=="number"?"number":typeof r=="boolean"?"boolean":"string"}),this._reserve(e)}if(s.rankCache=null,ArrayBuffer.isView(n)&&!s.isString)s.kinds=null,s.data.set(n),n.length<this.capacity&&s.data.fill(NaN,n.length);else if(s.isString&&n instanceof Int32Array)s.data.set(n);else for(let r=0;r<n.length;r++){const o=n[r];o!=null&&s.put(r,s.coerce(o))}}return this._afterLoad(e),e}_afterLoad(t){this._dropAllIndexes(),this.rowErrors.clear(),this.alive.fill(1,0,t),this.alive.fill(0,t),this.state.fill(0),this.originals.clear(),this.deletedCount=0,this.revision++,this.structureRevision++,this._markAllComputedStale(),this.manager._tableChanged(this),this._emit({type:"reload"})}_inferFields(t){const e=t[0];if(Array.isArray(e)){e.forEach((s,r)=>this.addField({name:`Field${r+1}`,type:S(t,r)}));return}const i=new Set,n=Math.min(t.length,200);for(let s=0;s<n;s++)for(const r of Object.keys(t[s]))i.add(r);for(const s of i)this.addField({name:s,type:S(t,s)})}loadSheet(t,e,i,{header:n=!0}={}){const s=[],{strings:r}=t;for(let a=i.c0;a<=i.c1;a++){const f=(e.kind(i.r0,a)&T)===N?r.get(e.value(i.r0,a)):"";s.push(n&&f?f:`Field${a-i.c0+1}`)}const o=n?i.r0+1:i.r0,h=Math.max(0,i.r1-o+1),l=(a,p)=>{const f=e.kind(a,p)&T,d=e.value(a,p);return f===k?d:f===N?r.get(d):f===E?d!==0:f===D?$.get(P[d])??null:null};return s.forEach((a,p)=>{if(this.byName.has(a))return;const f=[];for(let g=o;g<=Math.min(o+199,o+h-1);g++)f.push([l(g,i.c0+p)]);const d=t.styles?.get(e.style(o,i.c0+p)),w=d&&/[ymd]/i.test(String(d.numFmt??"").replace(/"[^"]*"/g,"")),y=S(f,0);this.addField({name:a,type:y==="number"&&w?"date":y,format:d?.numFmt!=="General"?d?.numFmt:void 0})}),this._reserve(h),this.rowCount=h,s.forEach((a,p)=>{const f=this.byName.get(a),d=i.c0+p;f.rankCache=null;for(let w=0;w<h;w++){const y=l(o+w,d);f.put(w,y instanceof x?null:f.coerce(y))}}),this._afterLoad(h),h}addRow(t={},{track:e=!0}={}){const i=this.rowCount;this._reserve(i+1),this.rowCount=i+1,this.alive[i]=1,this.state[i]=e&&this.tracking?u.INSERTED:u.UNCHANGED;for(const s of this.columns){if(s===null||s.computed)continue;let r=t[s.name]!==void 0?t[s.name]:s.defaultValue;typeof r=="string"&&r[0]==="="&&t[s.name]===void 0&&(r=this.manager.formulas.evaluateOnce(this,i,r)),s.put(i,r==null?null:s.coerce(r)),s.rankCache=null}const n=this.byName.get("__order");return n&&(n.data[i]=t.__order??this._nextOrder(n.data)),this._dropAllIndexes(),this._runTriggers(i,!0),this._rowsChanged(i),this._emit({type:"rows",row:i,added:!0}),i}_nextOrder(t){let e=-1;for(let i=0;i<this.rowCount;i++)t[i]>e&&(e=t[i]);return e+1}_runTriggers(t,e){for(const i of this.triggers){if(!e&&i.trigger.when!=="newAndUpdate")continue;const n=this.manager.formulas.evaluateOnce(this,t,i.trigger.formula);i.put(t,n instanceof x?null:i.coerce(n)),i.revision++}}removeRow(t){return this.alive[t]?(this.alive[t]=0,this.deletedCount++,this._dropAllIndexes(),this._rowsChanged(t),this._emit({type:"rows",row:t,removed:!0}),this._autoPush(),!0):!1}restoreRow(t){return this.alive[t]?!1:(this.alive[t]=1,this.deletedCount--,this.state[t]===u.PURGED&&(this.state[t]=u.UNCHANGED),this._rowsChanged(t),this._emit({type:"rows",row:t,added:!0}),!0)}_rowsChanged(t){this.revision++,this.structureRevision++;for(const e of this._order())this._recomputeRowOrAll(e,t);this.manager._tableChanged(this)}_recomputeRowOrAll(t,e){t.stale||(t.formula!==null&&!t.rangeDep&&e<this.rowCount?this.manager.formulas.computeRow(t,e):t.stale=!0)}_markAllComputedStale(){for(const t of this.columns)t!==null&&t.computed&&(t.stale=!0)}_markDependentsStale(t){for(const e of this._order())e!==t&&e.deps.includes(t.name)&&(e.stale=!0,this._markDependentsStale(e))}get(t,e){const i=this.column(e);if(!i)throw new m(`No field ${e} in ${this.name}`);return i.get(t)}set(t,e,i,{host:n=!1}={}){const s=typeof e=="string"?this.column(e):e;if(!s)throw new m(`No field ${e} in ${this.name}`);if(s.computed)throw new m(_("The {field} field is calculated, so it can't be edited.",{field:s.caption}));if(s.readOnly&&!n)throw new m(_("The {field} field is read-only.",{field:s.caption}));const r=s.coerce(i),o=s.get(t);if(G(o,r))return!1;if(s.validator!==null){const h=Y(s,r,t);if(h)throw new m(h)}if(s.required&&(r===null||r===""))throw new m(_("The {field} field can't be blank.",{field:s.caption}));return this.tracking&&this.state[t]!==u.INSERTED&&this._track(t,s,o,r),s.put(t,r),s.revision++,this._dropIndexOf(s),this.triggers.length>0&&this._runTriggers(t,!1),this._afterEdit(t,s),this._autoPush(),!0}_track(t,e,i,n){let s=this.originals.get(t);s===void 0&&(s=new Map,this.originals.set(t,s)),s.has(e.index)?G(s.get(e.index),n)&&s.delete(e.index):s.set(e.index,i),s.size===0?(this.originals.delete(t),this.state[t]=u.UNCHANGED):this.state[t]=u.UPDATED}_afterEdit(t,e){this.revision++;const i=new Set([e.name]);let n=this.manager.isKeyField(this,e.name);for(const s of this._order())s.deps.some(r=>i.has(r))&&(i.add(s.name),s.rangeDep||s.formula===null?s.stale=!0:s.stale||this.manager.formulas.computeRow(s,t),this.manager.isKeyField(this,s.name)&&(n=!0));n&&this.structureRevision++,this.manager._fieldChanged(this,i),this._emit({type:"cell",row:t,col:e})}batch(t){this.batchDepth++;try{return t()}finally{this.batchDepth--,this.batchDepth===0&&this.batchChanged&&(this.batchChanged=!1,this._emit({type:"reload"}))}}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}_emit(t){if(this.batchDepth>0){this.batchChanged=!0;return}for(const e of this.listeners)e(t)}getChanges(){const t=[],e=[],i=[],n=this.rowCount,{state:s,alive:r}=this;for(let o=0;o<n;o++)if(s[o]!==u.PURGED){if(s[o]===u.INSERTED)r[o]&&t.push(Object.defineProperty(this.record(o),"__row",{value:o,enumerable:!1}));else if(!r[o])i.push({row:o,record:this.originalRecord(o)});else if(s[o]===u.UPDATED){const h=this.originals.get(o),l={},a={};for(const[p,f]of h){const d=this.columns[p];l[d.name]=d.get(o),a[d.name]=f}e.push({row:o,record:this.record(o),changes:l,original:a})}}return{inserted:t,updated:e,deleted:i}}get hasChanges(){if(this.originals.size>0)return!0;const{state:t,alive:e}=this;for(let i=0;i<this.rowCount;i++)if(t[i]===u.INSERTED?e[i]===1:t[i]!==u.PURGED&&e[i]===0)return!0;return!1}originalValue(t,e){return this.originals.get(t)?.get(e.index)}isCellEdited(t,e){return this.originals.get(t)?.has(e.index)===!0}record(t){const e={};for(const i of this.columns)i!==null&&!i.hidden&&(e[i.name]=i.get(t));return e}originalRecord(t){const e=this.record(t),i=this.originals.get(t);if(i)for(const[n,s]of i)e[this.columns[n].name]=s;return e}acceptChanges(){this.originals.clear();const t=this.rowCount,{state:e,alive:i}=this;for(let n=0;n<t;n++)e[n]=i[n]?u.UNCHANGED:u.PURGED;this.revision++,this._emit({type:"cells"})}rejectChanges(){this.batch(()=>{for(const[s,r]of this.originals)for(const[o,h]of r){const l=this.columns[o];l.put(s,h),l.revision++}this.originals.clear();const t=this.rowCount,{state:e,alive:i}=this;let n=0;for(let s=0;s<t;s++)e[s]===u.INSERTED?(i[s]=0,e[s]=u.PURGED):e[s]!==u.PURGED&&(i[s]=1,e[s]=u.UNCHANGED),i[s]===0&&n++;this.deletedCount=n,this.structureRevision++,this.revision++,this._markAllComputedStale(),this.manager._tableChanged(this),this.batchChanged=!0})}revertRow(t){const e=this.originals.get(t);if(e){for(const[i,n]of e){const s=this.columns[i];s.put(t,n),s.revision++,this._afterEdit(t,s)}this.originals.delete(t),this.state[t]=u.UNCHANGED}if(this.state[t]===u.INSERTED){this.state[t]=u.PURGED,this.removeRow(t);return}this.alive[t]||this.restoreRow(t),this._emit({type:"cell",row:t})}connect(t){this.remote=t,this.provider=null}fetch(t=!1){return this.fetched&&!t?Promise.resolve(this):this.fetching?this.fetching:!this.remote&&this.options.data===void 0&&!t?(this.fetched=!0,Promise.resolve(this)):this.remote?(this.fetching=Q(this.remote,this.schema).then(e=>(this.load(e),this.fetched=!0,this.fetching=null,this),e=>{throw this.fetching=null,e}),this.fetching):Promise.resolve(this)}pull(){return this.fetch(!0)}_autoPush(){!this.autoSync||!this.remote||this.batchDepth>0||this._pushing||(this._pushing=!0,queueMicrotask(()=>{this._pushing=!1,this.submitChanges().catch(()=>{})}))}async submitChanges(){if(!this.remote)throw new m(_("{table} has no data source to write to.",{table:this.name}));const t=this.getChanges(),e=await I(this,t);return this.rowErrors=e.errors,e.errors.size===0?this.acceptChanges():this._acceptExcept(e.errors),this._emit({type:"cells"}),e.counts}push(){return this.submitChanges()}cancelChanges(){this.rejectChanges()}_acceptExcept(t){const e=this.rowCount,{state:i,alive:n}=this;for(let s=0;s<e;s++)t.has(s)||(this.originals.delete(s),i[s]=n[s]?u.UNCHANGED:u.PURGED);this.revision++}async saveRow(t){if(!this.remote){this.originals.delete(t),this.state[t]=this.alive[t]?u.UNCHANGED:u.PURGED,this._emit({type:"cells"});return}const e=this.getChanges(),i={inserted:e.inserted.filter(s=>s.__row===t),updated:e.updated.filter(s=>s.row===t),deleted:e.deleted.filter(s=>s.row===t)},n=await I(this,i);n.errors.has(t)?this.rowErrors.set(t,n.errors.get(t)):(this.rowErrors.delete(t),this.originals.delete(t),this.state[t]=this.alive[t]?u.UNCHANGED:u.PURGED),this._emit({type:"cells"})}resetRow(t){this.rowErrors.delete(t),this.revertRow(t)}missingRequired(t){const e=[];for(const i of this.columns)i!==null&&i.required&&(i.kind(t)===b||i.get(t)==="")&&e.push(i.caption);return e}}const G=(c,t)=>c===t?!0:c===null||t===null||typeof c=="string"&&typeof t=="string"?!1:typeof c=="boolean"&&typeof t=="number"?(c?1:0)===t:typeof c=="number"&&typeof t=="boolean"?(t?1:0)===c:!1;function S(c,t){let e=null;const i=Math.min(c.length,500);for(let n=0;n<i;n++){const s=c[n][t];if(s==null||s==="")continue;const r=s instanceof Date?"date":typeof s=="number"?"number":typeof s=="boolean"?"boolean":typeof s=="string"?"string":"any";if(e===null)e=r;else if(e!==r)if(e==="date"&&r==="number"||e==="number"&&r==="date")e="number";else return"any"}return e??"string"}let F=null;function pt(c){F=c}class gt{constructor(t=null){this.book=t,this.strings=t?.strings??new L,this.tables=new Map,this.relationships=[],this._formulas=null}get formulas(){if(this._formulas===null){if(F===null)throw new Error("Formula support is not loaded. Import datasheets/data.js first.");this._formulas=new F(this)}return this._formulas}addTable(t,e={}){if(this.tables.has(t))throw new m(`The table ${t} already exists.`);const i=new M(this,t,e);return this.tables.set(t,i),i}table(t){if(t instanceof M)return t;const e=this.tables.get(t);if(!e)throw new m(`No table named ${t}.`);return e}removeTable(t){const e=this.table(t);this.tables.delete(e.name),this.relationships=this.relationships.filter(i=>i.from!==e&&i.to!==e)}addRelationship(t){const e=new it(this,t);return this.relationships.push(e),e}removeRelationship(t){this.relationships=this.relationships.filter(e=>e!==t)}relationshipFrom(t,e){return this.relationships.find(i=>i.from===t&&i.name===e)??null}relationshipTo(t,e){return this.relationships.find(i=>i.to===t&&i.inverse===e)??null}relationshipBetween(t,e){return this.relationships.find(i=>i.from===t&&i.to===e||i.from===e&&i.to===t)??null}isKeyField(t,e){return this.relationships.length===0?!1:this.relationships.some(i=>i.from===t&&i.fromField===e||i.to===t&&i.toField===e)}_tableChanged(t){for(const e of this.tables.values()){let i=!1;for(const n of e.columns)n!==null&&(n.lookup&&(n.lookup.relation.to===t||n.lookup.relation.from===t)||n.rollup&&(n.rollup.relation.from===t||n.rollup.relation.to===t))&&(n.stale||(n.stale=!0,i=!0,e._markDependentsStale(n)));i&&e!==t&&e._emit({type:"reload",derived:!0})}}_fieldChanged(t,e){if(this.relationships.length!==0)for(const i of this.tables.values()){let n=!1;for(const s of i.columns){if(s===null)continue;(s.window&&s.window.table===t&&s.deps.some(o=>e.has(o))||s.lookup&&s.lookup.relation.to===t&&e.has(s.lookup.field)||s.rollup&&s.rollup.relation.from===t&&e.has(s.rollup.field)||s.lookup&&s.lookup.relation.from===t&&e.has(s.lookup.relation.fromField)||s.rollup&&s.rollup.relation.from===t&&e.has(s.rollup.relation.fromField))&&!s.stale&&(s.stale=!0,n=!0,i._markDependentsStale(s))}n&&i!==t&&i._emit({type:"reload",derived:!0})}}}export{O as DataColumn,m as DataError,gt as DataManager,M as DataTable,Z as FIELD_TYPES,u as ROW,it as Relationship,mt as flattenTree,pt as installFormulas,st as keyIndex};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{STR as on}from"../core/sheet.js";import{getFormatter as ln}from"../core/numfmt.js";import{formulaHelper as mn}from"./view.js";const B={bar:"#4a90d9",barDone:"#22598f",critical:"#d64545",criticalDone:"#932626",summary:"#404040",milestone:"#2b2b2b",baseline:"#a8a8a8",deadline:"#c42b1c",link:"#6b6b6b",linkCritical:"#c42b1c",today:"#107c41",tier:"#f3f3f3",tierLine:"#d0d0d0",tierInk:"#3b3b3b",label:"#3b3b3b"};function cn(n,i){if(i)return i._panes();const e=n.toScreen(0,0);return[{x:n.hx,y:n.hy,w:n.cssW-n.hx,h:n.cssH-n.hy,originX:n.hx-e.x,originY:n.hy-e.y,frozenC:!1,frozenR:!1,print:!0}]}function tn(n,i,e,l,o,t){const f=Math.min(t,l/2,o/2);n.beginPath(),n.moveTo(i+f,e),n.lineTo(i+l-f,e),n.quadraticCurveTo(i+l,e,i+l,e+f),n.lineTo(i+l,e+o-f),n.quadraticCurveTo(i+l,e+o,i+l-f,e+o),n.lineTo(i+f,e+o),n.quadraticCurveTo(i,e+o,i,e+o-f),n.lineTo(i,e+f),n.quadraticCurveTo(i,e,i+f,e),n.closePath()}function rn(n,i,e,l,o,t,f,r){if(!t||t==="solid")return;n.save(),n.beginPath(),n.rect(i,e,l,o),n.clip(),n.strokeStyle=f,n.fillStyle=f,n.lineWidth=Math.max(1,r*.75);const a=5*r;if(t==="dots")for(let s=i;s<i+l;s+=a)for(let m=e;m<e+o;m+=a)n.fillRect(s,m,Math.max(1,r),Math.max(1,r));else{n.beginPath();for(let s=-o;s<l;s+=a)n.moveTo(i+s,e+o),n.lineTo(i+s+o,e);n.stroke()}n.restore()}function dn(n,i,e,l){let t=n.taskbarStyles[e]??null;const f=n.taskbarRules;for(let r=0;r<f.length;r++){const a=f[r];if(a.type&&a.type!==e)continue;let s=!0;if(a.formula){let m=l[r];m===void 0&&(m=mn(n.table,a.formula),l[r]=m);const S=m.get(i);s=S===!0||typeof S=="number"&&S!==0}s&&(t=t===null?a.style:{...t,...a.style})}return t}function an(n,i,e,l,o,t,f,r){if(!i)return;const a=l+o/2,s=o*.75,m=r?1:-1;n.fillStyle=t,n.beginPath(),i==="diamond"?(n.moveTo(e,a-s),n.lineTo(e+s,a),n.lineTo(e,a+s),n.lineTo(e-s,a)):i==="triangle"?(n.moveTo(e,a-s),n.lineTo(e+m*s,a),n.lineTo(e,a+s)):i==="circle"?n.arc(e,a,s*.8,0,Math.PI*2):n.rect(e-f*1.5,l-f,3*f,o+2*f),n.closePath(),n.fill()}function Mn(n,i,e,l=null){const o=e.schedule;if(!o)return;const{dpr:t}=i,{zoom:f}=i;for(const r of cn(i,l)){n.save(),n.beginPath(),n.rect(r.x*t,r.y*t,r.w*t,r.h*t),n.clip();const a=y=>(r.x+(y-r.originX)*f)*t,s=y=>(r.y+(y-r.originY)*f)*t,m=f*t,{rows:S,cols:k}=e,w=r.originX,u=r.originX+r.w/f,g=r.originY,D=r.originY+r.h/f,h=k.offsetOf(e.timelineStart);if(u>h){const y=r.frozenR?0:Math.max(S.indexAt(g),e.frozenRows),c=r.frozenR?e.frozenRows-1:S.indexAt(D),b=Math.max(g,S.offsetOf(e.frozenRows));(!r.frozenR||r.print)&&fn(n,e,a,s,m,w,u,b,D,r),(!r.frozenR||r.print)&&un(n,e,o,a,s,m,w,u,b,D,y,c),y===0&&!r.print&&(r.frozenR||e.frozenRows===0)&&sn(n,e,a,s,m,w,u),r.print&&g<S.sizeOf(0)&&sn(n,e,a,s,m,w,u),(c>=e.bodyStart||r.frozenR)&&yn(n,e,o,a,s,m,Math.max(y,1),Math.min(c,e.bodyStart+e.view.count-1),w,u),e.nonWorking.mode==="front"&&!r.frozenR&&fn(n,e,a,s,m,w,u,b,D,r,!0),r.frozenR||bn(n,e,o,a,s,m,g,D),e.progressLine.visible&&!r.frozenR&&pn(n,e,o,a,s,m,Math.max(y,1),Math.min(c,e.bodyStart+e.view.count-1))}n.restore()}}function sn(n,i,e,l,o,t,f){const{scale:r,cols:a,colors:s}=i,m=a.offsetOf(i.timelineStart),S=r.tickWidth,k=i.rows.sizeOf(0),w=l(0),u=Math.max(m,t),g=s?.tier??B.tier,D=s?.tierInk??B.tierInk,h=s?.tierLine??B.tierLine;n.fillStyle=g,n.fillRect(e(u),w,(f-u)*o,k*o),n.textBaseline="middle";const y=Math.round(10.5*o);n.font=`${y}px -apple-system, "Helvetica Neue", Arial, sans-serif`;const c=Math.max(0,Math.floor((t-m)/S)),b=Math.min(r.count-1,Math.floor((f-m)/S)),C=r.tiers,O=k/Math.max(1,C.length),T=Math.max(1,Math.round(o*.75));C.forEach((v,W)=>{const P=W*O,{marks:F}=v;let I=0,d=F.length-1;for(;I<d;){const z=I+d+1>>>1;F[z].tick<=c?I=z:d=z-1}n.textAlign=v.bottom?"center":"left";for(let z=I;z<F.length;z++){const A=F[z];if(A.tick>b)break;const Z=z+1<F.length?F[z+1].tick:r.count,q=m+A.tick*S,R=m+Z*S;n.fillStyle=h,n.fillRect(Math.round(e(q)),l(P),T,O*o),n.fillStyle=D,v.bottom?n.fillText(A.label,e((q+R)/2),l(P+O/2)):(n.save(),n.beginPath(),n.rect(e(q),l(P),(R-q)*o,O*o),n.clip(),n.fillText(A.label,e(Math.max(q,t)+4),l(P+O/2)),n.restore())}n.fillStyle=h,n.fillRect(e(u),l(P+O)-T,(f-u)*o,T)})}function fn(n,i,e,l,o,t,f,r,a,s,m=!1){const{scale:S,cols:k,calendar:w,nonWorking:u}=i;if(s.frozenR||u.mode==="none"||u.mode==="front"!==m)return;const{unit:g}=S.bottomTier;if(g!=="day"&&g!=="hour"&&g!=="minute")return;const D=k.offsetOf(i.timelineStart),h=S.tickWidth,y=Math.max(0,Math.floor((t-D)/h)),c=Math.min(S.count-1,Math.floor((f-D)/h));n.fillStyle=u.color;const b=n.globalCompositeOperation;!m&&n.fillRect&&!s.print&&(n.globalCompositeOperation="multiply");for(let C=y;C<=c;C++){const O=S.ticks[C];(g==="day"?w.isWorkDay(O):w.isWorkTime(O+1e-6))||(n.fillRect(e(D+C*h),l(r),h*o,(a-r)*o),u.pattern&&u.pattern!=="solid"&&(n.globalCompositeOperation=b,rn(n,e(D+C*h),l(r),h*o,(a-r)*o,u.pattern,"#b8b8b8",o),!m&&!s.print&&(n.globalCompositeOperation="multiply"),n.fillStyle=u.color))}n.globalCompositeOperation=b}function un(n,i,e,l,o,t,f,r,a,s,m,S){const{scale:k,cols:w,gridlines:u,rows:g}=i,D=Math.max(1,Math.round(t*.75));if(u.interval>0){const h=w.offsetOf(i.timelineStart),y=k.tickWidth,c=Math.max(0,Math.floor((f-h)/y)),b=Math.min(k.count-1,Math.floor((r-h)/y));n.fillStyle=u.intervalColor;for(let C=c-c%u.interval;C<=b;C+=u.interval)n.fillRect(l(h+C*y),o(a),D,(s-a)*t)}if(u.rowInterval>0){n.fillStyle=u.rowColor;const h=Math.max(i.bodyStart,m);for(let y=h-(h-i.bodyStart)%u.rowInterval;y<=S;y+=u.rowInterval)n.fillRect(l(f),o(g.offsetOf(y)),(r-f)*t,D)}}function Y(n,i,e,l,o,t,f){n.strokeStyle=o,n.lineWidth=Math.max(1,t),n.setLineDash(f.map(r=>r*t)),n.beginPath(),n.moveTo(i,e),n.lineTo(i,l),n.stroke(),n.setLineDash([])}function bn(n,i,e,l,o,t,f,r){const{gridlines:a}=i,s=o(f),m=o(r);i.showToday&&a.current!==!1&&Y(n,l(i.xOfDate(i.today)),s,m,B.today,t,[4,3]),a.status&&i.statusDate!==null&&Y(n,l(i.xOfDate(i.statusDate)),s,m,"#7a4fb5",t,[2,2]),a.projectStart&&Y(n,l(i.xOfDate(e.projectStart)),s,m,"#2f6fb3",t,[6,3]),a.projectFinish&&Y(n,l(i.xOfDate(e.projectFinish)),s,m,"#2f6fb3",t,[6,3])}function pn(n,i,e,l,o,t,f,r){const{progressLine:a,rows:s,table:m,fields:S}=i,k=a.reference==="current"?i.today:i.statusDate??i.today,w=i.xOfDate(k),u=m.column(S.progress)?.data,g=[];for(let c=f;c<=r;c++){const b=i.recordAtRow(c);if(b<0||b>=e.rows||e.isSummary[b]===1||e.momentStart[b]===1/0)continue;const C=i.xOfDate(e.momentStart[b]),O=i.xOfDate(e.momentFinish[b]),T=u?u[b]:0,v=T===T?T:0,W=v>=1&&e.momentFinish[b]<=k||v<=0&&e.momentStart[b]>=k;g.push({x:W?w:C+(O-C)*v,y:s.offsetOf(c)+s.sizeOf(c)/2,row:c})}n.strokeStyle=a.color,n.fillStyle=a.color,n.lineWidth=Math.max(1,t*(a.width??1)),n.beginPath();let D=!1,h=null;const y=(c,b)=>{D?n.lineTo(l(c),o(b)):(n.moveTo(l(c),o(b)),D=!0)};for(const c of g){if(a.returnToAnchor){const b=c.y-s.sizeOf(c.row)/2;y(w,b),a.path==="square"&&y(c.x,b),y(c.x,c.y),a.path==="square"&&y(c.x,b+s.sizeOf(c.row)),y(w,b+s.sizeOf(c.row))}else h&&a.path==="square"&&y(h.x,c.y),y(c.x,c.y);h=c}n.stroke();for(const c of g)n.beginPath(),n.arc(l(c.x),o(c.y),2.2*t,0,Math.PI*2),n.fill();g.length>0&&a.showDate!==!1&&(n.font=`${Math.round(10*t)}px -apple-system, "Helvetica Neue", Arial, sans-serif`,n.textAlign="center",n.textBaseline="bottom",n.fillText(ln("d-mmm").number(Math.floor(k)),l(w),o(g[0].y-s.sizeOf(g[0].row)/2)))}const V=(n,i,e,l)=>{if(!e)return"";const o=n.table.column(e);if(!o)return String(e);const t=o.get(i);if(t==null)return"";if(typeof t=="number"){const f=l??o.format;return f&&f!=="General"?ln(f).number(t):String(t)}return typeof t=="object"?t.code:String(t)};function yn(n,i,e,l,o,t,f,r,a,s){const{table:m,view:S,fields:k,rows:w,layoutOptions:u,colors:g}=i,D=m.column(k.progress)?.data,h=m.column(k.name),y=m.column(k.resource),c=i.showBaseline?m.column(k.deadline)?.data:null,b=i.showBaseline?m.column(k.baselineStart)?.data:null,C=i.showBaseline?m.column(k.baselineFinish)?.data:null,O=Math.round(11*t);n.font=`${O}px -apple-system, "Helvetica Neue", Arial, sans-serif`,n.textBaseline="middle",n.textAlign="left";const T=i.bodyStart+S.count-1;i.showLinks&&u.linkMode!=="noLinks"&&Tn(n,i,e,l,o,t,f,Math.min(r,T));const v=[],W=u.roundToDays,P=g?.bar??B.bar,F=g?.barDone??B.barDone;for(let I=f;I<=r&&I<=T;I++){const d=i.recordAtRow(I);if(d<0||d>=e.rows||e.momentStart[d]===1/0)continue;const z=w.offsetOf(I),A=w.sizeOf(I),Z=W?Math.floor(e.momentStart[d]):e.momentStart[d],q=W?Math.ceil(e.momentFinish[d]):e.momentFinish[d],R=i.xOfDate(Z),H=i.xOfDate(q);if(H<a-300||R>s+40)continue;const E=e.isSummary[d]===1,j=!E&&e.duration[d]===0,$=i.showCritical&&e.critical[d]===1,K=m.column(k.manual)?.data[d]===1,p=dn(i,d,E?"summary":j?"milestone":K?"manual":$?"critical":"task",v),_=u.barHeight??A-8-(b?2:0),U=z+(A-_)/2-(b?1:0);if(b&&b[d]===b[d]&&!E){const L=i.xOfDate(b[d]),M=i.xOfDate(C[d]+(m.column(k.baselineFinish)&&e.calOf(d).fullDays?1:0));n.fillStyle=i.taskbarStyles.baseline?.fill??B.baseline,n.fillRect(l(L),o(z+A-4),Math.max(2,(M-L)*t),Math.max(2,2*t))}if(E){const L=p?.fill??($?B.criticalDone:g?.summary??B.summary);n.fillStyle=L;const M=U+1,N=Math.max(3,_*.45);n.fillRect(l(R),o(M),Math.max(2,(H-R)*t),N*t);const J=Math.min(5,Math.max(2,(H-R)/2)),G=N+3;n.beginPath(),n.moveTo(l(R),o(M)),n.lineTo(l(R+J),o(M)),n.lineTo(l(R),o(M+G)),n.closePath(),n.moveTo(l(H),o(M)),n.lineTo(l(H-J),o(M)),n.lineTo(l(H),o(M+G)),n.closePath(),n.fill()}else if(j){const L=z+A/2,M=Math.min(A/2-2,6);n.fillStyle=p?.fill??($?B.critical:B.milestone),n.beginPath(),n.moveTo(l(R),o(L-M)),n.lineTo(l(R+M),o(L)),n.lineTo(l(R),o(L+M)),n.lineTo(l(R-M),o(L)),n.closePath(),n.fill()}else{const L=Math.max(3/t,H-R),M=l(R),N=o(U),J=L*t,G=_*t,x=p?.fill??($?B.critical:K?"#7fa8d1":P);n.fillStyle=x,tn(n,M,N,J,G,2*t),n.fill(),p?.pattern&&rn(n,M,N,J,G,p.pattern,p.patternColor??"#ffffff",t),K&&!p&&(n.strokeStyle=F,n.lineWidth=Math.max(1,t*.75),n.strokeRect(M,N,J,G));const en=D?D[d]:0;en>0&&(n.fillStyle=p?.progressFill??($?B.criticalDone:F),tn(n,M,N,L*Math.min(1,en)*t,G,2*t),n.fill()),p?.startShape&&an(n,p.startShape,M,N,G,p.shapeColor??x,t,!1),p?.endShape&&an(n,p.endShape,M+J,N,G,p.shapeColor??x,t,!0)}if(c&&c[d]===c[d]){const L=i.xOfDate(c[d]+1),M=e.momentFinish[d]>c[d]+1;n.strokeStyle=B.deadline,n.lineWidth=Math.max(1,(M?2:1)*t),n.beginPath(),n.moveTo(l(L),o(z+2)),n.lineTo(l(L),o(z+A-2)),n.stroke(),n.fillStyle=B.deadline,n.beginPath(),n.moveTo(l(L-3),o(z+2)),n.lineTo(l(L+3),o(z+2)),n.lineTo(l(L),o(z+6)),n.closePath(),n.fill()}n.textBaseline="middle";const nn=p?.textColor??B.label,X=j?9:4;if(p&&(p.textRight!==void 0||p.textLeft!==void 0||p.textInside!==void 0||p.textTop!==void 0||p.textBottom!==void 0))n.fillStyle=nn,n.textAlign="left",p.textRight&&n.fillText(V(i,d,p.textRight,u.barDateFormat),l(H+X),o(z+A/2)),p.textInside&&(n.save(),n.beginPath(),n.rect(l(R),o(U),(H-R)*t,_*t),n.clip(),n.fillStyle=p.insideColor??"#ffffff",n.fillText(V(i,d,p.textInside,u.barDateFormat),l(R+3),o(z+A/2)),n.restore()),n.textAlign="right",p.textLeft&&n.fillText(V(i,d,p.textLeft,u.barDateFormat),l(R-X),o(z+A/2)),n.textAlign="center",p.textTop&&(n.textBaseline="bottom",n.fillText(V(i,d,p.textTop,u.barDateFormat),l((R+H)/2),o(U))),p.textBottom&&(n.textBaseline="top",n.fillText(V(i,d,p.textBottom,u.barDateFormat),l((R+H)/2),o(U+_))),n.textAlign="left",n.textBaseline="middle";else if(i.showLabels){const M=(y&&y.kind(d)===on?y.get(d):null)??((E||j)&&h.kind(d)===on?h.get(d):"");M&&(n.fillStyle=nn,n.fillText(M,l(H+X),o(z+A/2)))}}}function Tn(n,i,e,l,o,t,f,r){const{rows:a,layoutOptions:s}=i,m=i.linkIndex(),{outStart:S,outList:k,inStart:w,inList:u,from:g,to:D,type:h}=m,y=new Set;n.lineWidth=Math.max(1,t);const c=s.linkMode==="toEnd",b=O=>{const T=i.rowOfRecord(O);return T<0?null:a.offsetOf(T)+a.sizeOf(T)/2},C=O=>{if(y.has(O))return;y.add(O);const T=g[O],v=D[O],W=b(T),P=b(v);if(W===null||P===null)return;const F=h[O],I=i.xOfDate(F===0||F===2?e.momentFinish[T]:e.momentStart[T]),d=i.xOfDate(F===0||F===1?e.momentStart[v]:e.momentFinish[v]),A=i.showCritical&&e.critical[T]===1&&e.critical[v]===1&&e.isSummary[T]===0&&e.isSummary[v]===0?B.linkCritical:B.link;n.strokeStyle=A,n.fillStyle=A;const q=F===0||F===1?1:-1,R=F===0||F===2?1:-1,H=7;n.beginPath(),n.moveTo(l(I),o(W));const E=I+R*H,j=d-q*H,$=W+(P>W?1:-1)*(a.defaultSize/2);if(!c&&F===0&&d>=I+2){const K=(P>W?-1:1)*Math.min(4,a.defaultSize/2-2),Q=d+3;n.lineTo(l(Q),o(W)),n.lineTo(l(Q),o(P+K-(P>W?3:-3))),n.stroke();const p=P+K,_=P>W?1:-1;n.beginPath(),n.moveTo(l(Q),o(p)),n.lineTo(l(Q-3),o(p-_*4)),n.lineTo(l(Q+3),o(p-_*4)),n.closePath(),n.fill();return}q===1&&j>=E||q===-1&&j<=E?(n.lineTo(l(j),o(W)),n.lineTo(l(j),o(P))):(n.lineTo(l(E),o(W)),n.lineTo(l(E),o($)),n.lineTo(l(j),o($)),n.lineTo(l(j),o(P))),n.lineTo(l(d-q*3),o(P)),n.stroke(),n.beginPath(),n.moveTo(l(d),o(P)),n.lineTo(l(d-q*4),o(P-3)),n.lineTo(l(d-q*4),o(P+3)),n.closePath(),n.fill()};for(let O=f;O<=r;O++){const T=i.recordAtRow(O);if(!(T<0||T>=e.rows)){for(let v=w[T];v<w[T+1];v++)C(u[v]);for(let v=S[T];v<S[T+1];v++)C(k[v])}}}export{B as BAR_COLORS,dn as barStyleOf,Mn as paintGantt,cn as viewAreas};
|
|
1
|
+
import{STR as on}from"../core/sheet.js";import{getFormatter as ln}from"../core/numfmt.js";import{formulaHelper as mn}from"./view.js";const B={bar:"#4a90d9",barDone:"#22598f",critical:"#d64545",criticalDone:"#932626",summary:"#404040",milestone:"#2b2b2b",baseline:"#a8a8a8",deadline:"#c42b1c",link:"#6b6b6b",linkCritical:"#c42b1c",today:"#107c41",tier:"#f3f3f3",tierLine:"#d0d0d0",tierInk:"#3b3b3b",label:"#3b3b3b"};function cn(n,i){if(i)return i._panes();const e=n.toScreen(0,0);return[{x:n.hx,y:n.hy,w:n.cssW-n.hx,h:n.cssH-n.hy,originX:n.hx-e.x,originY:n.hy-e.y,frozenC:!1,frozenR:!1,print:!0}]}function tn(n,i,e,o,l,a){const s=Math.min(a,o/2,l/2);n.beginPath(),n.moveTo(i+s,e),n.lineTo(i+o-s,e),n.quadraticCurveTo(i+o,e,i+o,e+s),n.lineTo(i+o,e+l-s),n.quadraticCurveTo(i+o,e+l,i+o-s,e+l),n.lineTo(i+s,e+l),n.quadraticCurveTo(i,e+l,i,e+l-s),n.lineTo(i,e+s),n.quadraticCurveTo(i,e,i+s,e),n.closePath()}function an(n,i,e,o,l,a,s,u){if(!a||a==="solid")return;n.save(),n.beginPath(),n.rect(i,e,o,l),n.clip(),n.strokeStyle=s,n.fillStyle=s,n.lineWidth=Math.max(1,u*.75);const t=5*u;if(a==="dots")for(let r=i;r<i+o;r+=t)for(let f=e;f<e+l;f+=t)n.fillRect(r,f,Math.max(1,u),Math.max(1,u));else{n.beginPath();for(let r=-l;r<o;r+=t)n.moveTo(i+r,e+l),n.lineTo(i+r+l,e);n.stroke()}n.restore()}function dn(n,i,e,o){let a=n.taskbarStyles[e]??null;const s=n.taskbarRules;for(let u=0;u<s.length;u++){const t=s[u];if(t.type&&t.type!==e)continue;let r=!0;if(t.formula){let f=o[u];f===void 0&&(f=mn(n.table,t.formula),o[u]=f);const S=f.get(i);r=S===!0||typeof S=="number"&&S!==0}r&&(a=a===null?t.style:{...a,...t.style})}return a}function rn(n,i,e,o,l,a,s,u){if(!i)return;const t=o+l/2,r=l*.75,f=u?1:-1;n.fillStyle=a,n.beginPath(),i==="diamond"?(n.moveTo(e,t-r),n.lineTo(e+r,t),n.lineTo(e,t+r),n.lineTo(e-r,t)):i==="triangle"?(n.moveTo(e,t-r),n.lineTo(e+f*r,t),n.lineTo(e,t+r)):i==="circle"?n.arc(e,t,r*.8,0,Math.PI*2):n.rect(e-s*1.5,o-s,3*s,l+2*s),n.closePath(),n.fill()}function Mn(n,i,e,o=null){const l=e.schedule;if(!l)return;const{dpr:a}=i,{zoom:s}=i,u=o?.displayCols.scale??1;for(const t of cn(i,o)){n.save(),n.beginPath(),n.rect(t.x*a,t.y*a,t.w*a,t.h*a),n.clip();const r=m=>(t.x+(m*u-t.originX)*s)*a,f=m=>(t.y+(m-t.originY)*s)*a,S=s*a,{rows:h,cols:C}=e,d=t.originX/u,T=(t.originX+t.w/s)/u,w=t.originY,y=t.originY+t.h/s,g=C.offsetOf(e.timelineStart);if(T>g){const m=t.frozenR?0:Math.max(h.indexAt(w),e.frozenRows),b=t.frozenR?e.frozenRows-1:h.indexAt(y),M=Math.max(w,h.offsetOf(e.frozenRows));(!t.frozenR||t.print)&&fn(n,e,r,f,S,d,T,M,y,t),(!t.frozenR||t.print)&&un(n,e,l,r,f,S,d,T,M,y,m,b),m===0&&!t.print&&(t.frozenR||e.frozenRows===0)&&sn(n,e,r,f,S,d,T),t.print&&w<h.sizeOf(0)&&sn(n,e,r,f,S,d,T),(b>=e.bodyStart||t.frozenR)&&yn(n,e,l,r,f,S,Math.max(m,1),Math.min(b,e.bodyStart+e.view.count-1),d,T),e.nonWorking.mode==="front"&&!t.frozenR&&fn(n,e,r,f,S,d,T,M,y,t,!0),t.frozenR||bn(n,e,l,r,f,S,w,y),e.progressLine.visible&&!t.frozenR&&pn(n,e,l,r,f,S,Math.max(m,1),Math.min(b,e.bodyStart+e.view.count-1))}n.restore()}}function sn(n,i,e,o,l,a,s){const{scale:u,cols:t,colors:r}=i,f=t.offsetOf(i.timelineStart),S=u.tickWidth,h=i.rows.sizeOf(0),C=o(0),d=Math.max(f,a),T=r?.tier??B.tier,w=r?.tierInk??B.tierInk,y=r?.tierLine??B.tierLine;n.fillStyle=T,n.fillRect(e(d),C,e(s)-e(d),h*l),n.textBaseline="middle";const g=Math.round(10.5*l);n.font=`${g}px -apple-system, "Helvetica Neue", Arial, sans-serif`;const m=Math.max(0,Math.floor((a-f)/S)),b=Math.min(u.count-1,Math.floor((s-f)/S)),M=u.tiers,R=h/Math.max(1,M.length),k=Math.max(1,Math.round(l*.75));M.forEach((v,W)=>{const P=W*R,{marks:F}=v;let I=0,c=F.length-1;for(;I<c;){const z=I+c+1>>>1;F[z].tick<=m?I=z:c=z-1}n.textAlign=v.bottom?"center":"left";for(let z=I;z<F.length;z++){const L=F[z];if(L.tick>b)break;const Z=z+1<F.length?F[z+1].tick:u.count,q=f+L.tick*S,D=f+Z*S;n.fillStyle=y,n.fillRect(Math.round(e(q)),o(P),k,R*l),n.fillStyle=w,v.bottom?n.fillText(L.label,e((q+D)/2),o(P+R/2)):(n.save(),n.beginPath(),n.rect(e(q),o(P),e(D)-e(q),R*l),n.clip(),n.fillText(L.label,e(Math.max(q,a)+4),o(P+R/2)),n.restore())}n.fillStyle=y,n.fillRect(e(d),o(P+R)-k,e(s)-e(d),k)})}function fn(n,i,e,o,l,a,s,u,t,r,f=!1){const{scale:S,cols:h,calendar:C,nonWorking:d}=i;if(r.frozenR||d.mode==="none"||d.mode==="front"!==f)return;const{unit:T}=S.bottomTier;if(T!=="day"&&T!=="hour"&&T!=="minute")return;const w=h.offsetOf(i.timelineStart),y=S.tickWidth,g=Math.max(0,Math.floor((a-w)/y)),m=Math.min(S.count-1,Math.floor((s-w)/y));n.fillStyle=d.color;const b=n.globalCompositeOperation;!f&&n.fillRect&&!r.print&&(n.globalCompositeOperation="multiply");for(let M=g;M<=m;M++){const R=S.ticks[M];(T==="day"?C.isWorkDay(R):C.isWorkTime(R+1e-6))||(n.fillRect(e(w+M*y),o(u),e(w+(M+1)*y)-e(w+M*y),(t-u)*l),d.pattern&&d.pattern!=="solid"&&(n.globalCompositeOperation=b,an(n,e(w+M*y),o(u),e(w+(M+1)*y)-e(w+M*y),(t-u)*l,d.pattern,"#b8b8b8",l),!f&&!r.print&&(n.globalCompositeOperation="multiply"),n.fillStyle=d.color))}n.globalCompositeOperation=b}function un(n,i,e,o,l,a,s,u,t,r,f,S){const{scale:h,cols:C,gridlines:d,rows:T}=i,w=Math.max(1,Math.round(a*.75));if(d.interval>0){const y=C.offsetOf(i.timelineStart),g=h.tickWidth,m=Math.max(0,Math.floor((s-y)/g)),b=Math.min(h.count-1,Math.floor((u-y)/g));n.fillStyle=d.intervalColor;for(let M=m-m%d.interval;M<=b;M+=d.interval)n.fillRect(o(y+M*g),l(t),w,(r-t)*a)}if(d.rowInterval>0){n.fillStyle=d.rowColor;const y=Math.max(i.bodyStart,f);for(let g=y-(y-i.bodyStart)%d.rowInterval;g<=S;g+=d.rowInterval)n.fillRect(o(s),l(T.offsetOf(g)),o(u)-o(s),w)}}function Y(n,i,e,o,l,a,s){n.strokeStyle=l,n.lineWidth=Math.max(1,a),n.setLineDash(s.map(u=>u*a)),n.beginPath(),n.moveTo(i,e),n.lineTo(i,o),n.stroke(),n.setLineDash([])}function bn(n,i,e,o,l,a,s,u){const{gridlines:t}=i,r=l(s),f=l(u);i.showToday&&t.current!==!1&&Y(n,o(i.xOfDate(i.today)),r,f,B.today,a,[4,3]),t.status&&i.statusDate!==null&&Y(n,o(i.xOfDate(i.statusDate)),r,f,"#7a4fb5",a,[2,2]),t.projectStart&&Y(n,o(i.xOfDate(e.projectStart)),r,f,"#2f6fb3",a,[6,3]),t.projectFinish&&Y(n,o(i.xOfDate(e.projectFinish)),r,f,"#2f6fb3",a,[6,3])}function pn(n,i,e,o,l,a,s,u){const{progressLine:t,rows:r,table:f,fields:S}=i,h=t.reference==="current"?i.today:i.statusDate??i.today,C=i.xOfDate(h),d=f.column(S.progress)?.data,T=[];for(let m=s;m<=u;m++){const b=i.recordAtRow(m);if(b<0||b>=e.rows||e.isSummary[b]===1||e.momentStart[b]===1/0)continue;const M=i.xOfDate(e.momentStart[b]),R=i.xOfDate(e.momentFinish[b]),k=d?d[b]:0,v=k===k?k:0,W=v>=1&&e.momentFinish[b]<=h||v<=0&&e.momentStart[b]>=h;T.push({x:W?C:M+(R-M)*v,y:r.offsetOf(m)+r.sizeOf(m)/2,row:m})}n.strokeStyle=t.color,n.fillStyle=t.color,n.lineWidth=Math.max(1,a*(t.width??1)),n.beginPath();let w=!1,y=null;const g=(m,b)=>{w?n.lineTo(o(m),l(b)):(n.moveTo(o(m),l(b)),w=!0)};for(const m of T){if(t.returnToAnchor){const b=m.y-r.sizeOf(m.row)/2;g(C,b),t.path==="square"&&g(m.x,b),g(m.x,m.y),t.path==="square"&&g(m.x,b+r.sizeOf(m.row)),g(C,b+r.sizeOf(m.row))}else y&&t.path==="square"&&g(y.x,m.y),g(m.x,m.y);y=m}n.stroke();for(const m of T)n.beginPath(),n.arc(o(m.x),l(m.y),2.2*a,0,Math.PI*2),n.fill();T.length>0&&t.showDate!==!1&&(n.font=`${Math.round(10*a)}px -apple-system, "Helvetica Neue", Arial, sans-serif`,n.textAlign="center",n.textBaseline="bottom",n.fillText(ln("d-mmm").number(Math.floor(h)),o(C),l(T[0].y-r.sizeOf(T[0].row)/2)))}const V=(n,i,e,o)=>{if(!e)return"";const l=n.table.column(e);if(!l)return String(e);const a=l.get(i);if(a==null)return"";if(typeof a=="number"){const s=o??l.format;return s&&s!=="General"?ln(s).number(a):String(a)}return typeof a=="object"?a.code:String(a)};function yn(n,i,e,o,l,a,s,u,t,r){const{table:f,view:S,fields:h,rows:C,layoutOptions:d,colors:T}=i,w=f.column(h.progress)?.data,y=f.column(h.name),g=f.column(h.resource),m=i.showBaseline?f.column(h.deadline)?.data:null,b=i.showBaseline?f.column(h.baselineStart)?.data:null,M=i.showBaseline?f.column(h.baselineFinish)?.data:null,R=Math.round(11*a);n.font=`${R}px -apple-system, "Helvetica Neue", Arial, sans-serif`,n.textBaseline="middle",n.textAlign="left";const k=i.bodyStart+S.count-1;i.showLinks&&d.linkMode!=="noLinks"&&Sn(n,i,e,o,l,a,s,Math.min(u,k));const v=[],W=d.roundToDays,P=T?.bar??B.bar,F=T?.barDone??B.barDone;for(let I=s;I<=u&&I<=k;I++){const c=i.recordAtRow(I);if(c<0||c>=e.rows||e.momentStart[c]===1/0)continue;const z=C.offsetOf(I),L=C.sizeOf(I),Z=W?Math.floor(e.momentStart[c]):e.momentStart[c],q=W?Math.ceil(e.momentFinish[c]):e.momentFinish[c],D=i.xOfDate(Z),H=i.xOfDate(q);if(H<t-300||D>r+40)continue;const E=e.isSummary[c]===1,j=!E&&e.duration[c]===0,$=i.showCritical&&e.critical[c]===1,K=f.column(h.manual)?.data[c]===1,p=dn(i,c,E?"summary":j?"milestone":K?"manual":$?"critical":"task",v),_=d.barHeight??L-8-(b?2:0),U=z+(L-_)/2-(b?1:0);if(b&&b[c]===b[c]&&!E){const A=i.xOfDate(b[c]),O=i.xOfDate(M[c]+(f.column(h.baselineFinish)&&e.calOf(c).fullDays?1:0));n.fillStyle=i.taskbarStyles.baseline?.fill??B.baseline,n.fillRect(o(A),l(z+L-4),Math.max(2,o(O)-o(A)),Math.max(2,2*a))}if(E){const A=p?.fill??($?B.criticalDone:T?.summary??B.summary);n.fillStyle=A;const O=U+1,N=Math.max(3,_*.45);n.fillRect(o(D),l(O),Math.max(2,o(H)-o(D)),N*a);const J=Math.min(5,Math.max(2,(H-D)/2)),G=N+3;n.beginPath(),n.moveTo(o(D),l(O)),n.lineTo(o(D+J),l(O)),n.lineTo(o(D),l(O+G)),n.closePath(),n.moveTo(o(H),l(O)),n.lineTo(o(H-J),l(O)),n.lineTo(o(H),l(O+G)),n.closePath(),n.fill()}else if(j){const A=z+L/2,O=Math.min(L/2-2,6);n.fillStyle=p?.fill??($?B.critical:B.milestone),n.beginPath(),n.moveTo(o(D),l(A-O)),n.lineTo(o(D+O),l(A)),n.lineTo(o(D),l(A+O)),n.lineTo(o(D-O),l(A)),n.closePath(),n.fill()}else{const A=Math.max(3/a,H-D),O=o(D),N=l(U),J=o(D+A)-O,G=_*a,x=p?.fill??($?B.critical:K?"#7fa8d1":P);n.fillStyle=x,tn(n,O,N,J,G,2*a),n.fill(),p?.pattern&&an(n,O,N,J,G,p.pattern,p.patternColor??"#ffffff",a),K&&!p&&(n.strokeStyle=F,n.lineWidth=Math.max(1,a*.75),n.strokeRect(O,N,J,G));const en=w?w[c]:0;en>0&&(n.fillStyle=p?.progressFill??($?B.criticalDone:F),tn(n,O,N,J*Math.min(1,en),G,2*a),n.fill()),p?.startShape&&rn(n,p.startShape,O,N,G,p.shapeColor??x,a,!1),p?.endShape&&rn(n,p.endShape,O+J,N,G,p.shapeColor??x,a,!0)}if(m&&m[c]===m[c]){const A=i.xOfDate(m[c]+1),O=e.momentFinish[c]>m[c]+1;n.strokeStyle=B.deadline,n.lineWidth=Math.max(1,(O?2:1)*a),n.beginPath(),n.moveTo(o(A),l(z+2)),n.lineTo(o(A),l(z+L-2)),n.stroke(),n.fillStyle=B.deadline,n.beginPath(),n.moveTo(o(A-3),l(z+2)),n.lineTo(o(A+3),l(z+2)),n.lineTo(o(A),l(z+6)),n.closePath(),n.fill()}n.textBaseline="middle";const nn=p?.textColor??B.label,X=j?9:4;if(p&&(p.textRight!==void 0||p.textLeft!==void 0||p.textInside!==void 0||p.textTop!==void 0||p.textBottom!==void 0))n.fillStyle=nn,n.textAlign="left",p.textRight&&n.fillText(V(i,c,p.textRight,d.barDateFormat),o(H+X),l(z+L/2)),p.textInside&&(n.save(),n.beginPath(),n.rect(o(D),l(U),o(H)-o(D),_*a),n.clip(),n.fillStyle=p.insideColor??"#ffffff",n.fillText(V(i,c,p.textInside,d.barDateFormat),o(D+3),l(z+L/2)),n.restore()),n.textAlign="right",p.textLeft&&n.fillText(V(i,c,p.textLeft,d.barDateFormat),o(D-X),l(z+L/2)),n.textAlign="center",p.textTop&&(n.textBaseline="bottom",n.fillText(V(i,c,p.textTop,d.barDateFormat),o((D+H)/2),l(U))),p.textBottom&&(n.textBaseline="top",n.fillText(V(i,c,p.textBottom,d.barDateFormat),o((D+H)/2),l(U+_))),n.textAlign="left",n.textBaseline="middle";else if(i.showLabels){const O=(g&&g.kind(c)===on?g.get(c):null)??((E||j)&&y.kind(c)===on?y.get(c):"");O&&(n.fillStyle=nn,n.fillText(O,o(H+X),l(z+L/2)))}}}function Sn(n,i,e,o,l,a,s,u){const{rows:t,layoutOptions:r}=i,f=i.linkIndex(),{outStart:S,outList:h,inStart:C,inList:d,from:T,to:w,type:y}=f,g=new Set;n.lineWidth=Math.max(1,a);const m=r.linkMode==="toEnd",b=R=>{const k=i.rowOfRecord(R);return k<0?null:t.offsetOf(k)+t.sizeOf(k)/2},M=R=>{if(g.has(R))return;g.add(R);const k=T[R],v=w[R],W=b(k),P=b(v);if(W===null||P===null)return;const F=y[R],I=i.xOfDate(F===0||F===2?e.momentFinish[k]:e.momentStart[k]),c=i.xOfDate(F===0||F===1?e.momentStart[v]:e.momentFinish[v]),L=i.showCritical&&e.critical[k]===1&&e.critical[v]===1&&e.isSummary[k]===0&&e.isSummary[v]===0?B.linkCritical:B.link;n.strokeStyle=L,n.fillStyle=L;const q=F===0||F===1?1:-1,D=F===0||F===2?1:-1,H=7;n.beginPath(),n.moveTo(o(I),l(W));const E=I+D*H,j=c-q*H,$=W+(P>W?1:-1)*(t.defaultSize/2);if(!m&&F===0&&c>=I+2){const K=(P>W?-1:1)*Math.min(4,t.defaultSize/2-2),Q=c+3;n.lineTo(o(Q),l(W)),n.lineTo(o(Q),l(P+K-(P>W?3:-3))),n.stroke();const p=P+K,_=P>W?1:-1;n.beginPath(),n.moveTo(o(Q),l(p)),n.lineTo(o(Q-3),l(p-_*4)),n.lineTo(o(Q+3),l(p-_*4)),n.closePath(),n.fill();return}q===1&&j>=E||q===-1&&j<=E?(n.lineTo(o(j),l(W)),n.lineTo(o(j),l(P))):(n.lineTo(o(E),l(W)),n.lineTo(o(E),l($)),n.lineTo(o(j),l($)),n.lineTo(o(j),l(P))),n.lineTo(o(c-q*3),l(P)),n.stroke(),n.beginPath(),n.moveTo(o(c),l(P)),n.lineTo(o(c-q*4),l(P-3)),n.lineTo(o(c-q*4),l(P+3)),n.closePath(),n.fill()};for(let R=s;R<=u;R++){const k=i.recordAtRow(R);if(!(k<0||k>=e.rows)){for(let v=C[k];v<C[k+1];v++)M(d[v]);for(let v=S[k];v<S[k+1];v++)M(h[v])}}}export{B as BAR_COLORS,dn as barStyleOf,Mn as paintGantt,cn as viewAreas};
|