@8sheets/data-grid 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +36 -0
- package/README.md +52 -2
- package/a11y/cell-alt-text.js +1 -0
- package/api/overlay.js +1 -0
- package/api/serialize.js +1 -0
- package/api/skins.js +1 -0
- package/api/style-refs.js +1 -0
- package/api/watermark-xml.js +2 -0
- package/calc/adjust.js +1 -0
- package/calc/cell-set.js +1 -0
- package/calc/compile.js +1 -0
- package/calc/engine.js +1 -0
- package/calc/fill-shape.js +2 -0
- package/calc/functions/array.js +1 -0
- package/calc/functions/database.js +1 -0
- package/calc/functions/date.js +1 -0
- package/calc/functions/engineering.js +1 -0
- package/calc/functions/financial.js +1 -0
- package/calc/functions/helpers.js +1 -0
- package/calc/functions/index.js +1 -0
- package/calc/functions/info.js +1 -0
- package/calc/functions/logical.js +1 -0
- package/calc/functions/lookup.js +1 -0
- package/calc/functions/math.js +1 -0
- package/calc/functions/registry.js +1 -0
- package/calc/functions/stat.js +1 -0
- package/calc/functions/text.js +1 -0
- package/calc/parser.js +3 -0
- package/calc/values.js +1 -0
- package/calcx/ai/client.js +1 -0
- package/calcx/ai/functions.js +15 -0
- package/calcx/ai/settings.js +1 -0
- package/calcx/async.js +1 -0
- package/calcx/culture/format-locale.js +1 -0
- package/calcx/culture/lcid.js +1 -0
- package/calcx/external-read.js +1 -0
- package/calcx/external-write.js +3 -0
- package/calcx/external.js +1 -0
- package/calcx/functions/dynamic.js +1 -0
- package/calcx/functions/ets.js +1 -0
- package/calcx/functions/index.js +1 -0
- package/calcx/functions/misc.js +1 -0
- package/calcx/functions/text.js +1 -0
- package/calcx/functions/xml.js +1 -0
- package/calcx/refresh.js +1 -0
- package/cells/auto-merge.js +1 -0
- package/cells/axis-limits.js +1 -0
- package/cells/axis-ops.js +1 -0
- package/cells/background-xml.js +1 -0
- package/cells/background.js +1 -0
- package/cells/book-css.js +206 -0
- package/cells/book-read.js +1 -0
- package/cells/book-view.js +1 -0
- package/cells/cell-defaults.js +1 -0
- package/cells/cell-extras.js +1 -0
- package/cells/cell-options-ui.js +1 -0
- package/cells/cell-styles-xml.js +1 -0
- package/cells/cf-engine.js +1 -0
- package/cells/cf-file.js +1 -0
- package/cells/cf-paint.js +1 -0
- package/cells/consolidate-links.js +1 -0
- package/cells/docprops-xml.js +2 -0
- package/cells/filter-file.js +1 -0
- package/cells/find-engine.js +2 -0
- package/cells/find.js +1 -0
- package/cells/format-code.js +1 -0
- package/cells/format-panes.js +3 -0
- package/cells/format-tabs.js +102 -0
- package/cells/goto.js +1 -0
- package/cells/header-colors.js +1 -0
- package/cells/mask.js +1 -0
- package/cells/menu-extras.js +1 -0
- package/cells/name-box.js +1 -0
- package/cells/note-xml.js +1 -0
- package/cells/options.js +1 -0
- package/cells/outline-column.js +1 -0
- package/cells/paint.js +1 -0
- package/cells/panes.js +1 -0
- package/cells/rich-data-xml.js +2 -0
- package/cells/rich-data.js +1 -0
- package/cells/rich-runs.js +2 -0
- package/cells/rich-values.js +1 -0
- package/cells/rich-xml.js +1 -0
- package/cells/rounded.js +1 -0
- package/cells/sections.js +2 -0
- package/cells/selection-modes.js +1 -0
- package/cells/style-xml.js +1 -0
- package/cells/text-layout.js +8 -0
- package/cells/undo-group.js +1 -0
- package/cells/validation-alert.js +2 -0
- package/cells/view-options.js +1 -0
- package/cells/view-xml.js +1 -0
- package/celltypes/barcode-tables.js +31 -0
- package/celltypes/barcode.js +2 -0
- package/celltypes/base.js +1 -0
- package/celltypes/cell-buttons.js +1 -0
- package/celltypes/cell-types.js +2 -0
- package/celltypes/data-object.js +1 -0
- package/celltypes/diagonal.js +1 -0
- package/celltypes/dropdowns-more.js +13 -0
- package/celltypes/dropdowns.js +42 -0
- package/celltypes/file-cell.js +2 -0
- package/celltypes/glyphs.js +1 -0
- package/celltypes/persist.js +2 -0
- package/celltypes/range-template.js +2 -0
- package/charts/chartex.js +3 -0
- package/charts/geo/geo-xml.js +1 -0
- package/charts/geo/map-state.js +1 -0
- package/charts/patterns.js +1 -0
- package/core/address.js +1 -0
- package/core/axis.js +1 -0
- package/core/base64.js +1 -0
- package/core/changes.js +1 -0
- package/core/color.js +1 -0
- package/core/cond-format.js +1 -0
- package/core/custom-views.js +1 -0
- package/core/default-names.js +1 -0
- package/core/formula-refs.js +1 -0
- package/core/formula-store.js +1 -0
- package/core/input.js +1 -0
- package/core/math.js +1 -0
- package/core/numfmt.js +1 -0
- package/core/online.js +1 -0
- package/core/protection.js +1 -0
- package/core/regexp.js +1 -0
- package/core/sheet-group.js +1 -0
- package/core/sheet.js +1 -0
- package/core/sparklines.js +1 -0
- package/core/sparse.js +1 -0
- package/core/strings.js +1 -0
- package/core/styles.js +1 -0
- package/core/table-presets.js +7 -0
- package/core/tables.js +2 -0
- package/core/tsv.js +4 -0
- package/core/whatif.js +1 -0
- package/core/workbook.js +1 -0
- package/datasheets/bind.js +1 -0
- package/datasheets/calendar.js +1 -0
- package/datasheets/cross.js +1 -0
- package/datasheets/data-core.js +1 -0
- package/datasheets/data.js +1 -0
- package/datasheets/formula.js +1 -0
- package/datasheets/gantt-paint.js +1 -0
- package/datasheets/gantt-resources.js +1 -0
- package/datasheets/gantt-shapes.js +1 -0
- package/datasheets/gantt.js +1 -0
- package/datasheets/manager.js +1 -0
- package/datasheets/path-binding.js +2 -0
- package/datasheets/persist-writer.js +2 -0
- package/datasheets/persist.js +1 -0
- package/datasheets/query-function.js +1 -0
- package/datasheets/remote.js +3 -0
- package/datasheets/report-entry.js +1 -0
- package/datasheets/report.js +1 -0
- package/datasheets/rules.js +1 -0
- package/datasheets/sort.js +1 -0
- package/datasheets/table-sheet.js +1 -0
- package/datasheets/view.js +3 -0
- package/datasheets/virtual-sheet.js +1 -0
- package/datasheets/window.js +1 -0
- package/extras/getdata/persist.js +2 -0
- package/extras/getdata/rows.js +1 -0
- package/extras/getdata/steps.js +1 -0
- package/i18n/dom.js +1 -0
- package/i18n/en/a11y.js +1 -0
- package/i18n/en/cells.js +1 -0
- package/i18n/en/charts.js +1 -0
- package/i18n/en/common.js +1 -0
- package/i18n/en/datasheets.js +1 -0
- package/i18n/en/format.js +1 -0
- package/i18n/en/misc.js +1 -0
- package/i18n/en/pivot.js +1 -0
- package/i18n/en/proofing.js +1 -0
- package/i18n/en/ribbon.js +1 -0
- package/i18n/en/shapes.js +1 -0
- package/i18n/en/shell.js +1 -0
- package/i18n/en/touch.js +1 -0
- package/i18n/en.js +1 -0
- package/i18n/index.js +1 -0
- package/i18n/key-text.js +1 -0
- package/i18n/languages.js +1 -0
- package/i18n/pl/a11y.js +1 -0
- package/i18n/pl/cells.js +1 -0
- package/i18n/pl/charts.js +1 -0
- package/i18n/pl/common.js +1 -0
- package/i18n/pl/datasheets.js +1 -0
- package/i18n/pl/format.js +1 -0
- package/i18n/pl/misc.js +1 -0
- package/i18n/pl/pivot.js +1 -0
- package/i18n/pl/proofing.js +1 -0
- package/i18n/pl/ribbon.js +1 -0
- package/i18n/pl/shapes.js +1 -0
- package/i18n/pl/shell.js +1 -0
- package/i18n/pl/touch.js +1 -0
- package/i18n/pl.js +1 -0
- package/io/client.js +1 -0
- package/io/crc32.js +1 -0
- package/io/crypto/aes.js +1 -0
- package/io/crypto/agile.js +2 -0
- package/io/crypto/cfb-read.js +1 -0
- package/io/crypto/cfb-write.js +1 -0
- package/io/crypto/dataspaces.js +1 -0
- package/io/crypto/errors.js +1 -0
- package/io/crypto/hash.js +1 -0
- package/io/crypto/index.js +1 -0
- package/io/crypto/package-read.js +1 -0
- package/io/crypto/package-write.js +1 -0
- package/io/crypto/spool.js +1 -0
- package/io/crypto/standard.js +1 -0
- package/io/csv.js +8 -0
- package/io/export-blocks.js +1 -0
- package/io/foreign-parts.js +1 -0
- package/io/foreign-sheets.js +2 -0
- package/io/io.worker.js +1 -0
- package/io/package-paths.js +1 -0
- package/io/plan.js +1 -0
- package/io/text-split.js +3 -0
- package/io/xlsx-read.js +1 -0
- package/io/xlsx-styles.js +2 -0
- package/io/xlsx-tail.js +1 -0
- package/io/xlsx-write.js +2 -0
- package/io/xml-escape.js +1 -0
- package/io/xml-scan.js +1 -0
- package/io/zip-reader.js +1 -0
- package/io/zip-writer.js +1 -0
- package/objects/chart-model.js +1 -0
- package/objects/dml.js +5 -0
- package/objects/drawing-xml.js +1 -0
- package/objects/picture-url.js +1 -0
- package/package.json +57 -4
- package/pivot/engine.js +1 -0
- package/pivot/xml.js +2 -0
- package/print/page-setup.js +1 -0
- package/print/paginate.js +1 -0
- package/print/pdf.js +35 -0
- package/print/render-page.js +3 -0
- package/render/patterns.js +1 -0
- package/shapes/form-xml.js +1 -0
- package/shapes/watermark.js +1 -0
- package/slicers/custom-styles.js +1 -0
- package/slicers/date-filters.js +1 -0
- package/slicers/format.js +2 -0
- package/slicers/pivot-file.js +1 -0
- package/slicers/structured.js +1 -0
- package/slicers/table-file.js +1 -0
- package/slicers/write.js +1 -0
- package/sparklines/colors.js +1 -0
- package/sparklines/data.js +1 -0
- package/sparklines/descriptor.js +1 -0
- package/sparklines/excel-paint.js +1 -0
- package/sparklines/functions.js +1 -0
- package/sparklines/paint-core.js +1 -0
- package/sparklines/paint-measure.js +1 -0
- package/sparklines/paint-other.js +2 -0
- package/sparklines/paint-series.js +1 -0
- package/sparklines/paint.js +1 -0
- package/sparklines/print.js +1 -0
- package/sparklines/rule.js +1 -0
- package/table-view/api.js +1 -0
- package/table-view/cell-editor.js +1 -0
- package/table-view/cell-format.js +1 -0
- package/table-view/chrome.js +1 -0
- package/table-view/client.js +1 -0
- package/table-view/column-drag.js +1 -0
- package/table-view/column-input.js +1 -0
- package/table-view/column-window.js +1 -0
- package/table-view/events.js +1 -0
- package/table-view/files.js +1 -0
- package/table-view/grid-keys.js +2 -0
- package/table-view/index.d.ts +4 -0
- package/table-view/index.js +1 -0
- package/table-view/labels.js +1 -0
- package/table-view/model.js +1 -0
- package/table-view/mount.js +1 -0
- package/table-view/panel.js +1 -0
- package/table-view/pivot.js +1 -0
- package/table-view/public.d.ts +841 -0
- package/table-view/quick-filter.js +1 -0
- package/table-view/reader.worker.js +1 -0
- package/table-view/remote.js +1 -0
- package/table-view/row-cache.js +1 -0
- package/table-view/row-selection.js +1 -0
- package/table-view/table-css.js +1207 -0
- package/table-view/totals.js +1 -0
- package/table-view/version.js +1 -0
- package/table-view/worksheet-table.js +1 -0
- package/ui/dialogs.js +3 -0
- package/ui/dom.js +1 -0
- package/ui/icons.js +1 -0
- package/ui/menu-base.js +1 -0
- package/ui/protection-ui.js +1 -0
- package/ui/ui-scale.js +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{luminance as at}from"./colors.js";import{col as q,dot as Z,drawText as A,drawTextUp as mt,env as s,fillBox as st,frameArrow as tt,frameBox as y,frameOf as X,frameTick as O,frameX as D,frameY as Y,inset as C,lineWidth as F,pathBox as ut,pathSector as w,round as E,scaleTicks as lt,tint as _}from"./paint-core.js";import{clamp as J}from"../core/math.js";const G=Math.PI*2;function d(n,t,p,h,c,b=1){const i=C(b);return X(n+i,t+i,p-i*2,h-i*2,c)}const $=n=>n.len>0&&n.thick>0;function ht(n,t,p,h,c,b,i){const e=d(p,h,c,b,i);if(!$(e))return;const l=(t.size??.7)*e.thick,u=E((e.thick-l)/2),r=u+(s.snap?Math.max(1,Math.round(l)):l),k=Math.min(1,Math.abs(t.v))*e.len,a=t.c??(t.v<0?s.pal.negative:s.pal.series);if(t.v>0?y(n,e,0,k,u,r,a):t.v<0&&y(n,e,e.len-k,e.len,u,r,a),!t.noaxis){const M=F();y(n,e,0,M,0,e.thick,s.pal.mutedInk),y(n,e,e.len-M,e.len,0,e.thick,s.pal.mutedInk)}if(Math.abs(t.v)>1){const M=Math.min(l/2,4*s.s),f=(u+r)/2;t.v>0?tt(n,e,e.len-M,f,1,M,s.pal.surface):tt(n,e,M,f,-1,M,s.pal.surface)}}const Pt=(n,t,p,h,c,b)=>ht(n,t,p,h,c,b,!1),Tt=(n,t,p,h,c,b)=>ht(n,t,p,h,c,b,!0);function Wt(n,t,p,h,c,b){const i=d(p,h,c,b,t.vert);if(!$(i))return;const e=t.over?Math.max(t.x,t.m,t.t):t.x,l=i.len/e,u=t.c??s.pal.second,r=(t.size??1)*i.thick,k=(i.thick-r)/2,a=k+r;y(n,i,0,t.x*l,k,a,t.xc??_(u,.7)),t.g>0&&y(n,i,0,Math.min(t.g,t.x)*l,k,a,t.gc??_(u,.4)),t.b>0&&y(n,i,0,Math.min(t.b,t.x)*l,k,a,t.bc??_(u,.15));const M=r/4,f=J(t.m,0,e);if(t.f>0&&y(n,i,0,Math.min(t.f,e)*l,k+r*.42,a-r*.42,t.fc??s.pal.marker),y(n,i,0,f*l,k+M+M/2,a-M-M/2,t.mc??s.pal.series),lt(n,i,0,e,t.u,a-Math.max(2*s.s,r*.15),a,s.pal.mutedInk),t.t>=0&&t.t<=e&&O(n,i,t.t*l,k+r*.15,a-r*.15,t.tc??s.ink,F(1.5)),t.m>e){const I=Math.min(M,4*s.s);tt(n,i,i.len-I,(k+a)/2,1,I,s.pal.surface)}}function ct(n,t,p,h,c){const b=Math.min(9,t.thick/s.s*.7),i=h?t.len-C(2):C(2);t.vertical?A(n,p,D(t,i,t.thick/2),Y(t,i,t.thick/2),{size:b,base:h?"top":"bottom",color:c,maxW:t.thick}):A(n,p,D(t,i,t.thick/2),Y(t,i,t.thick/2),{size:b,align:h?"right":"left",color:c,maxW:t.len/2})}function St(n,t,p,h,c,b){const i=d(p,h,c,b,t.vert);if(!$(i))return;const e=i.len/(t.hi-t.lo),l=M=>(J(M,t.lo,t.hi)-t.lo)*e,u=i.thick*.2,r=i.thick*.8,k=t.v>=t.r,a=k?t.c??s.pal.positive:t.n??s.pal.negative;if(y(n,i,l(t.r),l(t.v),u,r,a),lt(n,i,t.lo,t.hi,t.u,0,Math.max(2*s.s,i.thick*.12),s.pal.mutedInk),O(n,i,l(t.r),0,i.thick,s.pal.mutedInk),t.mk!==void 0&&O(n,i,l(t.mk),u/2,i.thick-u/2,s.ink,F(1.5)),t.v>t.hi||t.v<t.lo){const M=Math.min(i.thick*.3,4*s.s),f=t.v>t.hi?i.len-M:M;tt(n,i,f,i.thick/2,t.v>t.hi?1:-1,M,s.pal.surface)}t.l!==void 0&&ct(n,i,t.l,!k,s.ink)}function zt(n,t,p,h,c,b){const i=d(p,h,c,b,t.vert);if(!$(i))return;const e=Math.max(1.5,Math.min(i.thick*.3,3.5*s.s)),l=e+C(),u=X(i.x,i.y,i.w,i.h,t.vert),r=i.len-l*2;if(r<=0)return;const k=r/(t.hi-t.lo),a=T=>l+(J(T,t.lo,t.hi)-t.lo)*k,M=i.thick/2,f=t.v>=t.r,I=f?t.c??s.pal.positive:t.n??s.pal.negative,m=F();if(y(n,u,a(t.r),a(t.v),M-m/2,M+m/2,I),O(n,i,a(t.r),0,i.thick,s.pal.mutedInk),t.u>0&<(n,X(i.vertical?i.x:i.x+l,i.vertical?i.y+l:i.y,i.vertical?i.w:r,i.vertical?r:i.h,t.vert),t.lo,t.hi,t.u,0,Math.max(2*s.s,i.thick*.12),s.pal.mutedInk),t.v>t.hi||t.v<t.lo){const T=e*1.4;tt(n,i,a(t.v),M,t.v>t.hi?1:-1,T,t.hc??s.ink)}else Z(n,D(i,a(t.v),M),Y(i,a(t.v),M),e,t.hc??s.ink);t.l!==void 0&&ct(n,i,t.l,!f,s.ink)}function It(n,t,p,h,c,b){const i=C(),e=t.vert?X(p,h+i,c,b-i*2,!0):X(p+i,h,c-i*2,b,!1);if(!$(e))return;const l=e.len/(t.hi-t.lo||1),u=(t.f-t.lo)*l,r=(t.t-t.lo)*l,a=t.t>=t.f?t.c??s.pal.positive:t.n??s.pal.negative,M=t.total?t.tc??s.pal.series:t.end?a:_(a,.35),f=E(e.thick*.15),I=E(e.thick*.85);y(n,e,u,r,f,I,M);const m=s.pal.mutedInk;t.pv&&O(n,e,u,0,f,m),t.nx&&O(n,e,r,I,e.thick,m),t.l!==void 0&&t.l!==""&&(e.vertical?A(n,t.l,D(e,0,e.thick/2),e.y+e.h,{size:Math.min(9,e.thick/s.s*.5),base:"bottom",maxW:e.thick}):A(n,t.l,p+C(2),h+b/2,{size:Math.min(9,b/s.s*.6),align:"left",maxW:e.len/2}))}function yt(n,t,p,h,c,b){const i=C(),e=t.vert?X(p,h+i,c,b-i*2,!0):X(p+i,h,c-i*2,b,!1);if(!$(e))return;const l=(t.size??.7)*e.thick,u=E((e.thick-l)/2),r=u+(s.snap?Math.max(1,Math.round(l)):l),k=t.hl?s.pal.negative:t.c??s.pal.second;y(n,e,t.f*e.len,t.t*e.len,u,r,k);const a=F();if(t.t1!==void 0&&O(n,e,J(t.t1,0,1)*e.len,0,e.thick,t.c1??s.pal.positive,a),t.t2!==void 0&&O(n,e,J(t.t2,0,1)*e.len,0,e.thick,t.c2??s.pal.negative,a),t.l!==void 0){const M=t.t<.6,f=M?t.t*e.len+C(2):t.f*e.len-C(2),I=Math.min(9,e.thick/s.s*.7);e.vertical?A(n,t.l,D(e,f,e.thick/2),Y(e,f,e.thick/2),{size:I,base:M?"bottom":"top",color:t.lc,maxW:e.thick}):A(n,t.l,D(e,f,e.thick/2),Y(e,f,e.thick/2),{size:I,align:M?"left":"right",color:t.lc,maxW:e.len*.4})}}const pt=[["#c00000","#ff7575"],["#548235","#92d36e"],["#2f5597","#7fa8ec"],["#bf9000","#ffd24d"]];function Bt(n,t,p,h,c,b){const i=d(p,h,c,b,t.vert);if(!$(i))return;const e=i.len/t.x,l=t.c??s.pal.second,u=t.v.length,r=F();let k=0;for(let a=0;a<u;a++){const M=k*e;k+=t.v[a];const f=Math.min(k,t.x)*e;if(f<=M)continue;const I=t.cs?.[a],m=I??_(l,u>1?a/u*.75:0),T=t.hl!==void 0&&t.hl!==a+1?_(m,.55):t.hl===a+1&&!I?s.pal.series:m;y(n,i,M,f,0,i.thick,T);const g=t.l?.[a];if(g){const W=at(T.slice(0,7))>.55?"#000000":"#ffffff",H=t.ts??10,R=(M+f)/2,B=f-M-r*2;t.tv!==void 0!==i.vertical?mt(n,g,D(i,R,i.thick/2),Y(i,R,i.thick/2),{size:H,color:W,maxW:i.vertical?B:i.thick,maxH:i.vertical?i.thick:B}):A(n,g,D(i,R,i.thick/2),Y(i,R,i.thick/2),{size:H,color:W,maxW:i.vertical?i.thick:B,maxH:i.vertical?B:i.thick})}f<i.len&&a<u-1&&y(n,i,f-r,f,0,i.thick,s.pal.surface)}for(let a=0;a<4;a++){const M=t.t?.[a];M==null||M<0||M>t.x||O(n,i,M*e,0,i.thick,pt[a][s.pal.surface==="#ffffff"?0:1],F(1.5))}}function At(n,t,p,h,c,b){const i=Math.max(1,1.2*s.s),e=d(p,h,c,b,t.vert,1+i/s.s);if(!$(e))return;const l=t.hi-t.lo||1,u=e.len/l,r=S=>J((S-t.lo)*u,0,e.len),[k,a,M,f,I]=t.q,m=e.thick/2,T=t.c??s.pal.muted,g=s.pal.mutedInk,W=F();if(t.band&&y(n,e,r(t.band[0]),r(t.band[1]),0,e.thick,_(s.pal.positive,.65)),t.st){const S=e.thick*.14;y(n,e,r(k),r(I),m-S,m+S,_(T,.25))}else y(n,e,r(k),r(a),m-W/2,m+W/2,g),y(n,e,r(f),r(I),m-W/2,m+W/2,g),O(n,e,r(k),e.thick*.3,e.thick*.7,g,W),O(n,e,r(I),e.thick*.3,e.thick*.7,g,W);const H=E(e.thick*.12),R=E(e.thick*.88);y(n,e,r(a),r(f),H,R,T),O(n,e,r(M),H,R,s.ink,F(1.25)),t.hatch&&(O(n,e,r(t.hatch[0]),e.thick*.32,e.thick*.68,g,W),O(n,e,r(t.hatch[1]),e.thick*.32,e.thick*.68,g,W));const B=(S,L)=>{S<t.lo||S>t.hi||(t.st?O(n,e,r(S),e.thick*.2,e.thick*.8,L,W):Z(n,D(e,r(S),m),Y(e,r(S),m),i,L))};for(const S of t.out??[])B(S,g);for(const S of t.ext??[])B(S,s.pal.negative);t.avg!==void 0&&Z(n,D(e,r(t.avg),m),Y(e,r(t.avg),m),i,s.pal.negative)}const kt=[{z:8},{z:11,b:1},{z:7},{z:7}],K=(n,t,p)=>{const h=n.fn?.[t]??kt[t];return{size:Math.min(h.z,p),bold:h.b,italic:h.i,family:h.f}};function Mt(n,t,p,h,c,b){const i=C(),e=t.l,l=((t.a0??-90)-90)*(Math.PI/180),u=((t.a1??90)-90)*(Math.PI/180),r=u-l,k=b/s.s,a=e?Math.min(Math.ceil(K(t,0,k*.16).size*s.s)+i,b*.25):0,M=Math.max(Math.sin(l),Math.sin(u),r>=Math.PI&&l<=Math.PI/2&&u>=Math.PI/2?1:0),f=Math.max(-Math.sin(l),-Math.sin(u),l<=-Math.PI/2&&u>=-Math.PI/2?1:0,0),I=b-i*2-a,m=Math.min((c-i*2)/2,I/Math.max(.5,Math.max(M,0)+f));if(m<=0)return;const T=E(p+c/2),g=E(h+i+f*m),W=m*(t.ir??.62),H=o=>(J(o,t.lo,t.hi)-t.lo)/(t.hi-t.lo),R=o=>l+H(o)*r,B=(o,v,z)=>{n.fillStyle=q(z),n.beginPath(),w(n,T,g,m,W,R(o),R(v)),n.fill()};B(t.lo,t.hi,s.pal.muted);for(const[o,v,z]of t.bands??[])B(o,v,z??s.pal.second);if(t.bands===void 0)B(t.lo,t.v,s.pal.series);else{const o=R(t.v);n.strokeStyle=q(s.ink),n.lineWidth=F(1.5),n.beginPath(),n.moveTo(T+Math.cos(o)*Math.max(W*.75,m*.15),g+Math.sin(o)*Math.max(W*.75,m*.15)),n.lineTo(T+Math.cos(o)*m,g+Math.sin(o)*m),n.stroke()}const S=R(t.t);if(n.strokeStyle=q(s.pal.negative),n.lineWidth=F(1.25),n.beginPath(),n.moveTo(T+Math.cos(S)*W,g+Math.sin(S)*W),n.lineTo(T+Math.cos(S)*m,g+Math.sin(S)*m),n.stroke(),!e)return;const[L,Q,nt,et]=e;A(n,Q,T,g-(f>.5?m*.12:0),{...K(t,1,k*.3),base:f>.5?"bottom":"middle",maxW:W*1.9||m});const V=K(t,2,k*.14),x=W>0?m-W:m*.5,P=(o,v)=>A(n,v,T+Math.cos(o)*(W+(m-W)/2),g+Math.sin(o)*(W+(m-W)/2)+V.size*s.s*.8,{...V,maxW:x*1.6});P(l,nt),P(u,et),A(n,L,T,h+b-i,{...K(t,0,k*.16),base:"bottom",maxW:c-i*2})}function ft(n,t,p,h,c,b,i){const e=C(),l=(i?c:b)/s.s,u=t.l,r=u?Math.ceil(Math.min(8,l*.22)*s.s)+e:0,k=i?X(p+e,h+e+r,c-e*2,b-e*2-r*2,!0):X(p+e,h+e+r,c-e*2,b-e*2-r*2,!1);if(!$(k))return;const a=k.len/(t.hi-t.lo),M=H=>(J(H,t.lo,t.hi)-t.lo)*a;y(n,k,0,k.len,0,k.thick,s.pal.muted);for(const[H,R,B]of t.bands??[])y(n,k,M(H),M(R),0,k.thick,B??s.pal.second);const f=k.thick*(t.bands?.3:0);if(y(n,k,0,M(t.v),f,k.thick-f,t.bands?s.ink:s.pal.series),O(n,k,M(t.t),0,k.thick,s.pal.negative,F(1.5)),!u)return;const[I,m,T,g]=u,W={...K(t,2,r/s.s)};if(i){const H=p+c/2;A(n,g,H,h+e,{...W,base:"top",maxW:c}),A(n,T,H,h+b-e,{...W,base:"bottom",maxW:c}),A(n,m,H,k.y+k.h-M(t.v),{...K(t,1,l*.22),maxW:c})}else A(n,T,p+e,h+e,{...W,align:"left",base:"top",maxW:c/3}),A(n,g,p+c-e,h+e,{...W,align:"right",base:"top",maxW:c/3}),A(n,m,p+c/2,h+e,{...K(t,1,r/s.s),base:"top",maxW:c/3}),A(n,I,p+c/2,h+b-e,{...K(t,0,r/s.s),base:"bottom",maxW:c})}function qt(n,t,p,h,c,b){t.ty===1?ft(n,t,p,h,c,b,!0):t.ty===2?ft(n,t,p,h,c,b,!1):Mt(n,t,p,h,c,b)}const j=-Math.PI/2;function ot(n,t,p,h,c,b,i,e,l){if(n.fillStyle=q(e),n.beginPath(),n.arc(t,p,h,0,G),n.arc(t,p,c,G,0,!0),n.fill(),!(b<=0)){if(b>=1){n.fillStyle=q(i),n.beginPath(),n.arc(t,p,h,0,G),n.arc(t,p,c,G,0,!0),n.fill();return}if(l){n.strokeStyle=q(i),n.lineWidth=h-c,n.lineCap="round",n.beginPath(),n.arc(t,p,(h+c)/2,j,j+b*G),n.stroke();return}n.fillStyle=q(i),n.beginPath(),w(n,t,p,h,c,j,j+b*G),n.fill()}}const rt=n=>`${Math.round(n*100)}%`;function Ht(n,t,p,h,c,b){const i=t.m??0,{v:e}=t;if(typeof e!="number")throw new TypeError("progress value");const l=t.c??s.pal.series,u=t.n??s.pal.muted,r=!t.hide,k=C(),a=p+k,M=h+k,f=c-k*2,I=b-k*2;if(f<=0||I<=0)return;const m=E(p+c/2),T=E(h+b/2),g=Math.min(f,I)/2,W=a+f*e,H=Math.min(9,I/s.s*.6),R=()=>{if(!r)return;const P=W-a>f*.5,o=P?at(l.slice(0,7))>.5?"#000000":"#ffffff":s.ink;A(n,rt(e),P?W-C(3):W+C(3),T,{size:H,align:P?"right":"left",color:o,maxH:I,maxW:f})},B=P=>{r&&A(n,rt(e),m,T,{size:g/s.s*P,maxW:g*1.8,maxH:g*1.4})},S=Math.min(I,Math.max(4*s.s,Math.min(I,12*s.s))),L=E(T-S/2),Q=(P,o,v)=>{n.fillStyle=q(v),n.beginPath(),n.roundRect(P,L,o,S,S/2),n.fill()},nt=(P,o)=>{n.beginPath(),n.roundRect(P,L,o,S,S/2),n.clip()},et=(P,o,v,z)=>{n.strokeStyle=q(v),n.lineWidth=F(),n.beginPath();for(let U=P-S;U<o;U+=z)n.moveTo(U,L+S),n.lineTo(U+S,L);n.stroke()},V=10,x=Math.round(e*V);switch(i){case 1:Q(a,f,u),e>0&&(Q(a,Math.max(S,f*e),l),n.save(),nt(a,Math.max(S,f*e)),et(a,a+Math.max(S,f*e),_(l,.45),Math.max(3*s.s,4)),n.restore());return;case 2:{const P=Math.max(1,E(s.s)),o=(f-P*(V-1))/V;for(let v=0;v<2;v++){n.fillStyle=q(v===0?u:l),n.beginPath();for(let z=0;z<V;z++)z<x==(v===1)&&ut(n,a+z*(o+P),L,a+z*(o+P)+o,L+S);n.fill()}return}case 3:ot(n,m,T,g,g*.68,e,l,u,!1),B(.62);return;case 4:{const P=Math.min(f/2,I*.92),o=h+b-k,v=P*.66;n.fillStyle=q(u),n.beginPath(),w(n,m,o,P,v,Math.PI,G),n.fill(),e>0&&(n.fillStyle=q(l),n.beginPath(),w(n,m,o,P,v,Math.PI,Math.PI+e*Math.PI),n.fill()),r&&A(n,rt(e),m,o,{size:P/s.s*.42,base:"bottom",maxW:v*1.8});return}case 5:n.save(),nt(a,f),e<1&&et(W,a+f,u,Math.max(3*s.s,4)),st(n,a,L,W,L+S,l),n.restore();return;case 6:{const P=Math.min(I/2-F(),f/(V*2.6));if(P<=0)return;const o=f/V;n.lineWidth=F(),n.strokeStyle=q(l);for(let v=0;v<V;v++){const z=a+(v+.5)*o;v<x?Z(n,z,T,P,l):(n.beginPath(),n.arc(z,T,P,0,G),n.stroke())}return}case 7:{const P=Math.max(.75,Math.min(S/4,1.2*s.s)),o=Math.max(P*3.5,3);for(let v=W+o;v<a+f;v+=o)Z(n,v,T,P,u);Q(a,Math.max(S,f*e),l),R();return}case 8:{const P=Math.min(I,f/(V*1.25));if(P<=0)return;const o=s.snap?Math.max(3,Math.floor(P)):P,v=f/V,z=F(),U=E(T-o/2);for(let it=0;it<V;it++){const N=E(a+(v-o)/2+it*v);it<x?(st(n,N,U,N+o,U+o,l),n.strokeStyle=q(at(l.slice(0,7))>.5?"#000000":"#ffffff"),n.lineWidth=z,n.beginPath(),n.moveTo(N+o*.2,U+o*.52),n.lineTo(N+o*.42,U+o*.74),n.lineTo(N+o*.8,U+o*.26),n.stroke()):(st(n,N,U,N+o,U+o,u),st(n,N+z,U+z,N+o-z,U+o-z,s.pal.surface))}return}case 9:{const o=Math.PI/2+.35,v=G-.35*2;n.fillStyle=q(u),n.beginPath(),w(n,m,T,g,g*.72,o,o+v),n.fill(),e>0&&(n.fillStyle=q(l),n.beginPath(),w(n,m,T,g,g*.72,o,o+v*e),n.fill()),B(.62);return}case 10:ot(n,m,T,g,g*.48,e,l,u,!1),B(.5);return;case 11:{ot(n,m,T,g*.74,g*.66,e,l,u,!1),n.lineWidth=F();for(let o=0;o<2;o++){n.strokeStyle=q(o===0?u:l),n.beginPath();for(let v=0;v<24;v++){if(v<Math.round(e*24)!=(o===1))continue;const z=j+v/24*G;n.moveTo(m+Math.cos(z)*g*.82,T+Math.sin(z)*g*.82),n.lineTo(m+Math.cos(z)*g,T+Math.sin(z)*g)}n.stroke()}B(.54);return}case 12:{for(let v=0;v<2;v++){n.fillStyle=q(v===0?u:l),n.beginPath();for(let z=0;z<24;z++)z<Math.round(e*24)==(v===1)&&w(n,m,T,g,g*.74,j+z/24*G+.05,j+(z+1)/24*G-.05);n.fill()}B(.6);return}case 13:{const o=Math.max(.6,g*.055);for(let v=0;v<30;v++){const z=j+v/30*G;Z(n,m+Math.cos(z)*(g-o),T+Math.sin(z)*(g-o),o,v<Math.round(e*30)?l:u)}B(.62);return}case 14:{const P=Math.max(1.5,g*.15),o=g-P;ot(n,m,T,o+P*.3,o-P*.3,e,l,u,!1);const v=j+e*G;Z(n,m+Math.cos(v)*o,T+Math.sin(v)*o,P,l),B(.56);return}default:Q(a,f,u),e>0&&Q(a,Math.max(S,f*e),l),R()}}export{At as paintBoxPlot,Wt as paintBullet,It as paintCascade,qt as paintGauge,Pt as paintHBar,zt as paintLollipop,yt as paintPareto,Ht as paintProgress,Bt as paintStacked,Tt as paintVBar,St as paintVariance};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{luminance as K,mixColors as Q}from"./colors.js";import{imageSourceAllowed as G}from"./descriptor.js";import{col as Z,drawText as q,env as p,fillBox as P,fontText as tt,inset as F,lineWidth as x,pathBox as nt,round as W,tint as N}from"./paint-core.js";const M=16;function et(n){if(n._groups!==void 0)return n._groups;let t=1/0,s=-1/0;for(const o of n.d)o===null||o===0||(o<t&&(t=o),o>s&&(s=o));const a=Array.from({length:M+1},()=>[]);for(let o=0;o<n.d.length;o++){const c=n.d[o];c===null||c===0?a[M].push(o):a[s>t?Math.min(M-1,Math.floor((c-t)/(s-t)*M)):M-1].push(o)}return n._groups=a,a}function ot(n){const{pal:t}=p;if(n._paletteOf===t)return n._palette;const s=n.st&&n.st.length>=2?n.st:[n.c1??N(t.positive,.75),n.c2??N(t.positive,.4),n.c3??t.positive],a=new Array(M);for(let o=0;o<M;o++){const c=o/(M-1)*(s.length-1),i=Math.min(s.length-2,Math.floor(c));a[o]=Q(s[i],s[i+1],c-i)}return n._palette=a,n._paletteOf=t,a}function U(n,t,s,a,o,c,i){const r=F(),u=Math.min((o-r*2)/i,(c-r*2)/7);if(u<=0)return;const m=p.snap&&u>=1?Math.floor(u):u,v=p.snap?m>=4?1:0:m*.12,w=W(s+(o-m*i)/2),k=W(a+(c-m*7)/2),d=et(t),e=ot(t),f=(l,h)=>{if(l.length!==0){n.fillStyle=Z(h),n.beginPath();for(let g=0;g<l.length;g++){const y=l[g]+t.wd,I=w+Math.floor(y/7)*m,b=k+y%7*m;nt(n,I,b,I+m-v,b+m-v)}n.fill()}};f(d[M],t.c0??p.pal.muted);for(let l=0;l<M;l++)f(d[l],e[l])}const gt=(n,t,s,a,o,c)=>U(n,t,s,a,o,c,6),ht=(n,t,s,a,o,c)=>U(n,t,s,a,o,c,54);function dt(n,t,s,a,o,c){const i=t._totals??(t._totals=[t.w.reduce((e,f)=>e+f,0),t.h.reduce((e,f)=>e+f,0)]);if(i[0]<=0||i[1]<=0)return;const r=o/i[0],u=c/i[1],m=t._xs??(t._xs=V(t.w)),v=t._ys??(t._ys=V(t.h)),w=x(.75);for(const e of t.cells){const f=s+m[e.c]*r,l=a+v[e.r]*u,h=(m[e.c+(e.cs??1)]-m[e.c])*r,g=(v[e.r+(e.rs??1)]-v[e.r])*u;if(e.f&&P(n,f,l,f+h,l+g,e.f),e.bd){const[y,I,b,S]=e.bd,C=(A,O,E,_,z)=>{A&&P(n,O,E,_,z,A[1]??p.ink)};C(y,f,l,f+h,l+w),C(b,f,l+g-w,f+h,l+g),C(S,f,l,f+w,l+g),C(I,f+h-w,l,f+h,l+g)}}const k=Math.min(r,u)/p.s,d=Math.max(1,2*r);for(const e of t.cells){if(!e.t)continue;const f=s+m[e.c]*r,l=a+v[e.r]*u,h=(m[e.c+(e.cs??1)]-m[e.c])*r,g=(v[e.r+(e.rs??1)]-v[e.r])*u;if(it(n,e.t,f,l,h,g))continue;const y=(e.z??12)*k,I=e.a==="right"?"right":e.a==="center"?"center":"left",b=I==="right"?f+h-d:I==="center"?f+h/2:f+d,S=e.va==="top"?"top":e.va==="center"?"middle":"bottom",C=e.i??(e.f?K(e.f.slice(0,7))>.55?"#000000":"#ffffff":void 0),A={size:y,bold:e.b,italic:e.it,align:I,base:S,color:C},O=e.w?st(n,e.t,A,h-d*2):[e.t],E=y*p.s*1.2;let _=S==="top"?l:S==="middle"?l+g/2-(O.length-1)*E/2:l+g-Math.max(1,u)-(O.length-1)*E;for(const z of O){if(_<l-E||_>l+g+E)break;if(q(n,z,b,_,{...A,maxW:e.w?void 0:h})&&e.u){const L=n.measureText(z).width,$=I==="right"?b-L:I==="center"?b-L/2:b,j=S==="top"?_+y*p.s:S==="middle"?_+y*p.s/2:_;P(n,$,j,$+L,j+x(.75),C??p.ink)}_+=E}}}function st(n,t,s,a){n.font=tt(s);const o=[];for(const c of t.split(`
|
|
2
|
+
`)){let i="";for(const r of c.split(" ")){const u=i===""?r:`${i} ${r}`;i!==""&&n.measureText(u).width>a?(o.push(i),i=r):i=u}o.push(i)}return o}let B=null,H=0;function vt(n){B=n}const rt=/^(?:data:image\/|https:\/\/\S+\.(?:png|jpe?g|gif|webp|svg|avif)(?:[?#]\S*)?$)/i;function it(n,t,s,a,o,c){if(rt.test(t))return ft(n,{src:t,va:1,ha:1},s,a,o,c),!0;if(B===null||H>=3||!t.startsWith("@@8c"))return!1;H++;try{return B(n,t,s,a,o,c)}finally{H--}}function V(n){const t=[0];for(const s of n)t.push(t[t.length-1]+s);return t}const at=256,T=new Map,R=new Set;let D=0;const X=[];function yt(n){return R.add(n),()=>R.delete(n)}function Y(n,t){n.state=t,D--;for(const s of R)s();if(D===0)for(const s of X.splice(0))s()}function J(n){let t=T.get(n);return t!==void 0?(T.delete(n),T.set(n,t),t):typeof Image>"u"?null:(t={state:"loading",img:new Image},T.size>=at&&T.delete(T.keys().next().value),T.set(n,t),D++,t.img.crossOrigin="anonymous",t.img.referrerPolicy="no-referrer",t.img.decoding="async",t.img.onload=()=>Y(t,"ready"),t.img.onerror=()=>Y(t,"failed"),t.img.src=n,t)}const wt=()=>D===0?Promise.resolve():new Promise(n=>X.push(n));function ct(n,t,s){if(n.gray)return n.gray;const a=typeof OffscreenCanvas<"u"?new OffscreenCanvas(t,s):Object.assign(document.createElement("canvas"),{width:t,height:s}),o=a.getContext("2d");o.drawImage(n.img,0,0,t,s);const c=o.getImageData(0,0,t,s),{data:i}=c;for(let r=0;r<i.length;r+=4){const u=.2126*i[r]+.7152*i[r+1]+.0722*i[r+2];i[r]=u,i[r+1]=u,i[r+2]=u}return o.putImageData(c,0,0),n.gray=a,a}function It(n){G(n)&&J(n)}function lt(n,t,s,a,o,c){if(t.alt&&q(n,t.alt,s+o/2,a+c/2,{size:9,color:p.pal.mutedInk,maxW:o,maxH:c}))return;const i=x(.75),r=F(2);if(o<=r*2+i*2||c<=r*2+i*2)return;const u=p.pal.muted;P(n,s+r,a+r,s+o-r,a+r+i,u),P(n,s+r,a+c-r-i,s+o-r,a+c-r,u),P(n,s+r,a+r,s+r+i,a+c-r,u),P(n,s+o-r-i,a+r,s+o-r,a+c-r,u)}function ft(n,t,s,a,o,c){if(!G(t.src))throw new TypeError("image source");const i=J(t.src);if(i===null||i.state!=="ready"){(i===null||i.state==="failed"||!p.snap)&<(n,t,s,a,o,c);return}const{img:r}=i,u=t.clip??[],m=u[0]??0,v=u[1]??0,w=r.naturalWidth||300,k=r.naturalHeight||150,d=Math.min(u[2]??w-m,w-m),e=Math.min(u[3]??k-v,k-v);if(!(d>0&&e>0))return;let f=o,l=c;switch(t.sz){case 1:break;case 2:f=d*p.s,l=e*p.s;break;case 3:f=t.w!==void 0?t.w*p.s:t.h*p.s/e*d,l=t.h!==void 0?t.h*p.s:t.w*p.s/d*e;break;default:{const y=Math.min(o/d,c/e);f=d*y,l=e*y}}const h=s+(t.ha===0?0:t.ha===2?o-f:(o-f)/2),g=a+(t.va===0?0:t.va===2?c-l:(c-l)/2);n.drawImage(p.mono?ct(i,w,k):r,m,v,d,e,W(h),W(g),W(f),W(l))}export{yt as onSparklineImage,dt as paintBlock,ft as paintImage,gt as paintMonth,ht as paintYear,It as requestSparklineImage,vt as setNestedPainter,wt as whenSparklineImagesReady};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{col as A,dot as U,drawText as nt,env as M,extent as J,fillBox as E,inset as D,lineWidth as F,pathBox as x,pathSector as Y,round as R,tint as et}from"./paint-core.js";const j=Math.PI*2;function Z(n,t){const a=n.o??{};let[i,u]=n._extent??(n._extent=J(n.v));return t&&(i=Math.min(i,0),u=Math.max(u,0)),a.min!==void 0&&(i=a.min),a.max!==void 0&&(u=a.max),i===u&&(i-=1,u+=1),[i,u]}function K(n,t,a){const i=n.x?n.x[a-1]>0?n.x[t]/n.x[a-1]:.5:a>1?t/(a-1):.5;return n.o?.rtl?1-i:i}function N(n,t,a){const i=n.o,u=n.v[t];if(i===void 0||u===null)return null;const{pal:b}=M,[r,f]=n._extent??(n._extent=J(n.v));return i.high&&u===f?i.highcolor??b.positive:i.low&&u===r?i.lowcolor??b.negative:i.first&&t===ot(n)?i.firstcolor??b.marker:i.last&&t===it(n,a)?i.lastcolor??b.marker:i.negative&&u<0?i.negativecolor??b.negative:i.markers?i.markercolor??i.color??b.series:null}function ot(n){for(let t=0;t<n.v.length;t++)if(n.v[t]!==null)return t;return 0}function it(n,t){for(let a=t-1;a>=0;a--)if(n.v[a]!==null)return a;return 0}const $=n=>n!==void 0&&(n.markers||n.high||n.low||n.first||n.last||n.negative);function d(n,t,a,i,u,b,r,f){if(!t?.axis||b>0||r<0)return;const P=u+f-(0-b)/(r-b)*f;E(n,a,P,i,P+F(),t.axiscolor??M.pal.mutedInk)}function ct(n,t,a,i,u,b){const{v:r}=t,f=r.length,P=t.o??{},[_,S]=Z(t,!1),h=$(t.o),v=Math.max(1,1.5*M.s),s=h?Math.ceil(v)+1:D(),w=a+s,k=i+s,m=u-s*2,y=b-s*2;if(m<=0||y<=0)return;d(n,t.o,w,w+m,k,_,S,y);const p=T=>k+y-(T-_)/(S-_)*y;if(n.strokeStyle=A(P.color??M.pal.series),n.lineWidth=M.snap?Math.max(1,(P.weight??.75)*M.s):(P.weight??.75)*M.s,n.lineJoin="round",n.lineCap="round",n.beginPath(),f>m*2){let T=-1,o=0,e=0,c=!1;const g=()=>{if(T<0)return;const l=w+T;c?n.lineTo(l,p(o)):n.moveTo(l,p(o)),e!==o&&n.lineTo(l,p(e)),c=!0};for(let l=0;l<f;l++){if(r[l]===null)continue;const O=Math.floor(K(t,l,f)*m);O!==T?(g(),T=O,o=r[l],e=r[l]):(r[l]<o&&(o=r[l]),r[l]>e&&(e=r[l]))}g()}else{const T=P.empty==="connect";let o=!1;for(let e=0;e<f;e++){if(r[e]===null){T||(o=!1);continue}const c=w+K(t,e,f)*m,g=p(r[e]);o?n.lineTo(c,g):(!T&&(e===f-1||r[e+1]===null)&&n.rect(c-.5,g-.5,1,1),n.moveTo(c,g),o=!0)}}if(n.stroke(),h&&f*v*2<=m*4)for(let T=0;T<f;T++){const o=N(t,T,f);o!==null&&U(n,w+K(t,T,f)*m,p(r[T]),v,o)}}function st(n,t,a,i){return N(n,t,a)??i}function lt(n,t){const a=new Array(t).fill(null),i=n.length;for(let u=0;u<i;u++){if(n[u]===null)continue;const b=Math.min(t-1,Math.floor(u/i*t));(a[b]===null||Math.abs(n[u])>Math.abs(a[b]))&&(a[b]=n[u])}return a}function tt(n,t,a,i,u,b,r){const f=t.o??{},P=D(),_=a+P,S=u-P*2,h=i+P,v=b-P*2;if(S<=0||v<=0)return;const s=M.snap?1:M.s;let w=t.v,k=w.length,m=$(t.o),y=null,p=S/k;if(t.x){const B=t.x[k-1]||1;let z=B;for(let C=1;C<k;C++)t.x[C]>t.x[C-1]&&t.x[C]-t.x[C-1]<z&&(z=t.x[C]-t.x[C-1]);p=S*z/(B+z);const W=S-p;y=t.x.map(C=>C/B*W)}else p<s&&(w=lt(w,Math.max(1,Math.floor(S/s))),k=w.length,p=S/k,m=!1);const T=p>=3*s?Math.max(s,Math.round(p*.2)):0,o=M.snap?Math.max(1,Math.floor(p)-T):p-T;let e,c;r?(e=-1,c=1):[e,c]=Z(t,!f.excelAxis);const g=v/(c-e),l=h+c*g,O=f.color??M.pal.series,I=f.negative?f.negativecolor??M.pal.negative:O,G=r?Math.max(s,R(v*.04)):0,V=B=>{n.fillStyle=A(B),n.beginPath();for(let z=0;z<k;z++){const W=w[z];if(W===null||W===0||(m?st(t,z,k,W<0?I:O):W<0?I:O)!==B)continue;const Q=y?y[f.rtl?k-1-z:z]:(f.rtl?k-1-z:z)*p,L=M.snap?Math.round(_+Q+(p-o)/2):_+Q+(p-o)/2;if(r){const q=h+v/2;W>0?x(n,L,h,L+o,q-G):x(n,L,q+G,L+o,h+v)}else{const q=Math.max(e,Math.min(c,W)),X=h+(c-q)*g,H=Math.max(h,Math.min(h+v,l));q>=0?x(n,L,Math.min(X,H-s),L+o,H):x(n,L,H,L+o,Math.max(X,H+s))}}n.fill()};if(V(O),I!==O&&V(I),m){const B=new Set([O,I]);for(let z=0;z<k;z++){const W=N(t,z,k);W!==null&&!B.has(W)&&(B.add(W),V(W))}}r||d(n,t.o,_,_+S,h,e,c,v)}const ht=(n,t,a,i,u,b)=>tt(n,t,a,i,u,b,!1),ut=(n,t,a,i,u,b)=>tt(n,t,a,i,u,b,!0);function pt(n,t,a,i,u,b){const r=D(),f=a+r,P=i+r,_=u-r*2,S=b-r*2;if(_<=0||S<=0)return;const h=[];for(let e=0;e<t.v.length;e++)t.v[e]!==null&&h.push(e);if(h.length===0)return;let[v,s]=t._extent??(t._extent=J(t.v));v=t.lo??Math.min(v,0),s=t.hi??Math.max(s,0),v===s&&(s=v+1);const w=e=>P+S-(Math.max(v,Math.min(s,e))-v)/(s-v)*S,k=v>0?v:s<0?s:0,m=w(k),y=t.v.length,p=e=>f+(y>1?e/(y-1)*_:_/2),T=(e,c)=>{n.fillStyle=A(c),n.beginPath(),n.moveTo(p(h[0]),m);for(let g=0;g<h.length;g++){const l=h[g],O=t.v[l];if(g>0){const I=t.v[h[g-1]];if(I>k!=O>k&&I!==O){const G=(k-I)/(O-I);n.lineTo(p(h[g-1])+G*(p(l)-p(h[g-1])),m)}}n.lineTo(p(l),(e?O>=k:O<=k)?w(O):m)}n.lineTo(p(h[h.length-1]),m),n.closePath(),n.fill()};T(!0,t.c??M.pal.series),T(!1,t.n??M.pal.negative);const o=[t.l1,t.l2];for(let e=0;e<2;e++){if(o[e]===void 0||o[e]<v||o[e]>s)continue;const c=w(o[e]);E(n,f,c,f+_,c+F(),M.ink)}}function mt(n,t,a,i,u,b){const r=D(),f=Math.min(u,b)/2-r;if(f<=0)return;const P=R(a+u/2),_=R(i+b/2),S=-Math.PI/2,h=t.c??[];if(t.v===void 0){n.fillStyle=A(h[1]??M.pal.muted),n.beginPath(),n.arc(P,_,f,0,j),n.fill(),t.s>0&&(n.fillStyle=A(h[0]??M.pal.series),n.beginPath(),t.s>=1?n.arc(P,_,f,0,j):Y(n,P,_,f,0,S,S+t.s*j),n.fill());return}let v=0;for(const w of t.v)v+=w;let s=S;t.v.forEach((w,k)=>{const m=w/v*j,y=h.length>0?h:M.pal.chart,p=Math.floor(k/y.length),T=y[k%y.length];n.fillStyle=A(p===0?T:et(T,Math.min(.75,p*.3))),n.beginPath(),t.v.length===1?n.arc(P,_,f,0,j):Y(n,P,_,f,0,s,s+m),n.fill(),s+=m})}function at(n,t,a,i,u){n.fillStyle=A(u),n.beginPath(),x(n,t-i,a-i,t+i,a+i),n.fill()}function gt(n,t,a,i,u,b){const r=Math.max(1,1.5*M.s),f=Math.ceil(r)+1,P=a+f,_=i+f,S=u-f*2,h=b-f*2;if(S<=0||h<=0)return;if(t._x===void 0){const o=[...t.a?.x??[],...t.b?.x??[]],e=[...t.a?.y??[],...t.b?.y??[]];t._x=J(o),t._y=J(e)}let v=t.x0??t._x[0],s=t.x1??t._x[1],w=t.y0??t._y[0],k=t.y1??t._y[1];v===s&&(v-=1,s+=1),w===k&&(w-=1,k+=1);const m=o=>P+(o-v)/(s-v)*S,y=o=>_+h-(o-w)/(k-w)*h;t.z&&E(n,m(t.z[0]),y(t.z[3]),m(t.z[1]),y(t.z[2]),M.pal.muted);const p=F();t.h!==void 0&&t.h>=w&&t.h<=k&&E(n,P,y(t.h),P+S,y(t.h)+p,M.pal.mutedInk),t.v!==void 0&&t.v>=v&&t.v<=s&&E(n,m(t.v),_,m(t.v)+p,_+h,M.pal.mutedInk);const T=(o,e,c)=>{if(o===void 0)return;const g=o.x.length;if(t.lines&&g>1){n.strokeStyle=A(e),n.lineWidth=p,n.lineJoin="round",n.setLineDash(t.dash?[3*M.s,2*M.s]:[]),n.beginPath();for(let l=0;l<g;l++)l===0?n.moveTo(m(o.x[l]),y(o.y[l])):n.lineTo(m(o.x[l]),y(o.y[l]));n.stroke(),n.setLineDash([])}if(!t.nosym)for(let l=0;l<g;l++){const O=m(o.x[l]),I=y(o.y[l]);O<a||O>a+u||I<i||I>i+b||c(n,O,I,r,e)}};if(T(t.a,t.c1??M.pal.second,U),T(t.b,t.c2??M.pal.negative,at),t.tags&&t.a!==void 0&&t.a.y.length>0){const[o,e]=J(t.a.y),c=t.a.y.indexOf(e),g=t.a.y.indexOf(o);U(n,m(t.a.x[c]),y(e),r,M.pal.series),U(n,m(t.a.x[g]),y(o),r,M.pal.negative)}}const ft=(n,t)=>{const a=Math.sin(n*12.9898+t*78.233)*43758.5453;return a-Math.floor(a)};function Mt(n,t,a,i,u,b){const r=D(),f=a+r,P=i+r,_=u-r*2,S=b-r*2;if(_<=0||S<=0)return;const h=!!t.vert,v=h?S:_,s=h?_:S;let w=1;for(const e of t.n)e>w&&(w=e);const k=t.c??M.pal.series,m=F(),y=Math.max(.75,M.s*.9);n.fillStyle=A(k),n.beginPath();const p=(e,c,g)=>{h?x(n,f+c,P+S-e-m,f+g,P+S-e):x(n,f+e,P+c,f+e+m,P+g)},T=(e,c)=>{const g=h?f+c:f+e,l=h?P+S-e:P+c;n.moveTo(g+y,l),n.arc(g,l,y,0,j)},o=Math.max(1,Math.floor(s/(y*2+1)));for(let e=0;e<t.at.length;e++){const c=(t.at[e]+.5)/t.slots*v,g=t.n[e];switch(t.st){case 1:{const l=g/w*s/2;p(c,s/2-l,s/2+l);break}case 2:{const l=Math.min(g,o);for(let O=0;O<l;O++)T(c,s/2+(O%2===0?1:-1)*Math.ceil(O/2)*(y*2+1));break}case 3:for(let l=0;l<Math.min(g,64);l++)T(c,y+ft(t.at[e],l)*(s-y*2));break;case 5:{const l=Math.min(g,o);for(let O=0;O<l;O++)T(c,s-y-O*(y*2+1));break}case 6:p(c,s*.25,s*.75);break;default:p(c,0,s);break}}if(n.fill(),t.avg!==void 0){const e=t.avg*v;n.fillStyle=A(M.pal.negative),n.beginPath(),p(e,0,s),n.fill()}}function vt(n,t,a,i,u,b){const r=D(2),f=t.l!==void 0,P=t.ts??Math.min(9,Math.floor(b/M.s/3)),_=f?Math.ceil(P*M.s)+D():0,S=a+r,h=i+r,v=u-r*2,s=b-r*2-_;if(v<=0||s<=0)return;const w=t.n.length;let k=1;for(const o of t.n)o>k&&(k=o);const m=v/w,y=t.size??1,p=M.snap?Math.max(1,Math.round(m*y)):m*y;if((o=>{n.fillStyle=A(o),n.beginPath();for(let e=0;e<w;e++){if(t.n[e]===0)continue;const c=R(S+e*m+(m-p)/2);x(n,c,h+s-t.n[e]/k*s,c+p,h+s)}n.fill()})(t.c??M.pal.series),m>=4*(M.snap?1:M.s)){const o=t.ec??M.pal.muted,e=F(.5);n.fillStyle=A(o),n.beginPath();for(let c=0;c<w;c++){if(t.n[c]===0)continue;const g=R(S+c*m+(m-p)/2),l=R(h+s-t.n[c]/k*s);x(n,g,l,g+e,h+s),x(n,g+p-e,l,g+p,h+s),x(n,g,l,g+p,l+e)}n.fill()}if(f)for(let o=0;o<w;o++)nt(n,t.l[o],S+(o+.5)*m,i+b-r,{size:P,base:"bottom",color:t.lc,maxW:m})}export{pt as paintArea,ht as paintColumn,vt as paintHistogram,ct as paintLine,mt as paintPie,gt as paintScatter,Mt as paintSpread,ut as paintWinLoss};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{luminance as I,normalizeColor as P}from"./colors.js";import{isSparklineText as E,parseSparkDescriptor as b}from"./descriptor.js";import{env as v,setEnv as k}from"./paint-core.js";import{isBarcodeText as y,paintBarcodeValue as B}from"../celltypes/barcode.js";import{paintBlock as T,paintImage as w,paintMonth as A,paintYear as H,setNestedPainter as M}from"./paint-other.js";import{paintBoxPlot as R,paintBullet as D,paintCascade as L,paintGauge as V,paintHBar as N,paintLollipop as z,paintPareto as W,paintProgress as _,paintStacked as q,paintVariance as F,paintVBar as G}from"./paint-measure.js";import{paintArea as Y,paintColumn as j,paintHistogram as J,paintLine as K,paintPie as O,paintScatter as Q,paintSpread as U,paintWinLoss as X}from"./paint-series.js";const c=new Map([["line",K],["column",j],["winloss",X],["area",Y],["pie",O],["scatter",Q],["spread",U],["histogram",J],["hbar",N],["vbar",G],["bullet",D],["variance",F],["lollipop",z],["cascade",L],["pareto",W],["stacked",q],["boxplot",R],["gauge",V],["progress",_],["month",A],["year",H],["block",T],["image",w]]),Z=new Set(["block","image","gauge","stacked","scatter"]);function se(a,e){c.set(a,e)}const $=32768,x=64*1024*1024;let f=new Map,g=0;function ee(a){let e=f.get(a);return e!==void 0||(e=b(a),e!==null&&!c.has(e.k)&&(e=null),(f.size>=$||g>=x)&&(f=new Map,g=0),f.set(a,e),g+=a.length),e}const d=new Map;function S(a){let e=d.get(a);if(e===void 0){const n=P(a);e=n!==null&&I(n)>.55,d.set(a,e)}return e}function h(a,e,n,p,r,t,s,o){const i=ee(e);if(i===null)return!1;if(r<=0||t<=0)return!0;const l=o?.ink??"#000000";k(s,o?.snap!==!1,l,S(l),o?.mono===!0),a.save();try{(Z.has(i.k)||i.k.startsWith("x:"))&&(a.beginPath(),a.rect(n,p,r,t),a.clip()),c.get(i.k)(a,i,n,p,r,t)}catch(u){if(!(u instanceof TypeError))throw u;return f.set(e,null),!1}finally{a.restore()}return!0}M((a,e,n,p,r,t)=>{const{s,snap:o,ink:i,mono:l,pal:u}=v,C=u.surface!=="#ffffff";let m=!1;return y(e)?m=B(a,e,n,p,r,t,s):E(e)&&(m=h(a,e,n,p,r,t,s,{ink:i,snap:o,mono:l}),k(s,o,i,C,l)),m});function le(a,e,n,p,r,t,s,o){if(r<=0||t<=0)return;const i=o?.ink??"#000000";k(s,o?.snap!==!1,i,S(i),o?.mono===!0),a.save();try{c.get(e.k)(a,e,n,p,r,t)}finally{a.restore()}}function fe(a,e,n,{scale:p=1,ink:r="#000000",snap:t=!1,mono:s=!1}={}){return h(a,n,e.x,e.y,e.width,e.height,p,{ink:r,snap:t,mono:s})}import{isSparklineText as me,sparklineDataText as ke}from"./descriptor.js";import{onSparklineImage as de,requestSparklineImage as Se,whenSparklineImagesReady as he}from"./paint-other.js";export{me as isSparklineText,de as onSparklineImage,le as paintSparklineData,fe as paintSparklineInRect,h as paintSparklineValue,se as registerSparklinePainter,Se as requestSparklineImage,ke as sparklineDataText,he as whenSparklineImagesReady};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{prepareWatermarks as S}from"../shapes/watermark.js";import{CHUNK_MASK as g,FORMULA as P,KIND_MASK as A,SPILL as M,STR as R}from"../core/sheet.js";import{MAX_COLS as m}from"../core/address.js";import{rangesOf as x}from"../core/cond-format.js";import{isSparklineText as u,parseSparkDescriptor as L}from"./descriptor.js";import{requestSparklineImage as p,whenSparklineImagesReady as _}from"./paint.js";import{sparkRuleTextAt as C}from"./rule.js";const I=8e3,T=2e4,d=/^(?:data:image\/|https:\/\/\S+\.(?:png|jpe?g|gif|webp|svg|avif)(?:[?#]\S*)?$)/i;function c(i,t=0){const e=L(i);if(!(e===null||t>3)){if(e.k==="image")p(e.src);else if(e.k==="block"&&Array.isArray(e.cells))for(const r of e.cells)typeof r?.t=="string"&&(d.test(r.t)?p(r.t):u(r.t)&&c(r.t,t+1))}}function k(i,t,e,r){const o=t._chunk(e,r);if(o===void 0)return;const s=e&g,f=o.kinds[s];if((f&A)!==R||(f&(P|M))===0)return;const n=i.strings.get(o.values[s]);u(n)&&c(n)}function h(i,t){for(const r of t.formulas.keys()){const o=Math.floor(r/m);k(i,t,o,r-o*m)}for(const r of t.spills?.values()??[])for(let o=r.r0;o<=r.r1;o++)for(let s=r.c0;s<=r.c1;s++)k(i,t,o,s);let e=T;for(const r of t.sparkRules??[])if(/SPARK_(?:IMAGE|BLOCK)/i.test(r.formula))for(const o of x(r.sqref)){const s=Math.min(o.r1,t.maxRow),f=Math.min(o.c1,t.maxCol);for(let n=o.r0;n<=s;n++)for(let a=o.c0;a<=f&&e>0;a++,e--){const l=C(i,t,n,a);l!==null&&c(l)}}}async function U(i,t=I){for(const r of i.entries??[])h(i.book,r.sheet);await Promise.all((i.entries??[]).map(r=>Promise.all([S(r.sheet),r.sheet.beforePrint?.(),i.book.beforePrintSheet?.(r.sheet)])));let e;await Promise.race([_(),new Promise(r=>{e=setTimeout(r,t)})]),clearTimeout(e)}export{U as preparePicturesForPrint,h as requestSheetPictures};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{cellRef as N,rangeRef as X,renameSheetInFormula as j}from"../core/address.js";import{rangesOf as b}from"../core/cond-format.js";import{Arr as B,XlError as W}from"../calc/values.js";import{registerSection as w}from"../cells/sections.js";import{sheetRenameHooks as Z}from"../core/sparse.js";import{isSparklineText as D}from"./descriptor.js";import{invalidateSparklineScales as J}from"./excel-paint.js";import{paintSparklineValue as I}from"./paint.js";const K=4096,Q=8192,Y=4e4,T=/"(?:[^"]|"")*"|\bTHIS_CELL\b|\bRULE_RANGE\b|\bRULE_POSITION\b|\$CF_RANGE\$|@(?![A-Za-z_$(\[])/g,C=(n,e)=>`$${N(n,e).replace(/\d+$/,t=>`$${t}`)}`;function V(n,e){const t=N(e.r0,e.c0),r=C(e.r0,e.c0),l=`${r}:${C(e.r1,e.c1)}`,s=e.r1>e.r0||e.c1===e.c0;return n.replace(T,u=>u[0]==='"'?u:u==="RULE_RANGE"||u==="$CF_RANGE$"?l:u==="RULE_POSITION"?`${s?"ROWS":"COLUMNS"}(${r}:${t})`:t)}function ee(n,e,t,{showValue:r=!1,priority:l}={}){const s=String(t).replace(/^\s*=/,"").trim().replace(T,a=>a[0]==="@"?"THIS_CELL":a);if(s===""||s.length>Q)return null;const u=b(e);if(u.length===0)return null;try{n.engine?.validate(V(s,u[0]))}catch{return null}return Object.freeze({sqref:u.map(X).join(" "),formula:s,showValue:!!r,priority:Number.isFinite(l)?l:void 0})}const F=new WeakMap;let x=0;function E(n){let e=F.get(n);return e===void 0||e.rules!==n.sparkRules?(e={rules:n.sparkRules,generation:x,compiled:[...n.sparkRules??[]].sort((t,r)=>(t.priority??1/0)-(r.priority??1/0)).map(t=>({rule:t,ranges:b(t.sqref),expanded:new Map})),results:new Map},F.set(n,e)):e.generation!==x&&(e.generation=x,e.results.clear()),e}function me(){x++,J()}function U(n,e,t){for(const r of n.compiled)for(const l of r.ranges)if(e>=l.r0&&e<=l.r1&&t>=l.c0&&t<=l.c1)return{entry:r,range:l};return null}function ne(n,e,t){return!n.sparkRules||n.sparkRules.length===0?null:U(E(n),e,t)?.entry.rule??null}function Re(n,e,t){const r=ne(n,e,t);return r!==null&&!r.showValue&&!(r.priority!==void 0&&n.cfEval?.stoppedBefore?.(r.priority,e,t))}function q(n,e,t,r,l,s,u){const a=n.template(t,r,l),o=n.legacy;n.legacy=!0;try{let i=a.fn(s,u,e);return i&&i.sheet&&(i=n.refAuto(i,s,u)),i instanceof B&&([i]=i.data),typeof i=="string"&&D(i)?i:null}catch(i){if(i instanceof W)return null;throw i}finally{n.legacy=o}}function de(n,e,t,r=0,l=0){return n.engine?q(n.engine,e,String(t).replace(/^\s*=/,""),r,l,r,l):null}function $(n,e,t,r,l){const s=r*16384+l;let u=t.results.get(s);if(u!==void 0)return u;const a=U(t,r,l);if(a===null)return null;const{range:o,entry:i}=a;if(i.rule.priority!==void 0&&e.cfEval?.stoppedBefore?.(i.rule.priority,r,l))return t.results.set(s,null),null;let c=i.expanded.get(o);return c===void 0&&(c=V(i.rule.formula,o),i.expanded.set(o,c)),u=q(n,e,c,o.r0,o.c0,r,l),t.results.size>=Y&&t.results.clear(),t.results.set(s,u),u}function ke(n,e,t,r){return!n.engine||!e.sparkRules?null:$(n.engine,e,E(e),t,r)}function ge(n,e,t,r,l){const{sheet:s,book:u,theme:a}=e;if(!u.engine)return;const{ca:o,cb:i,ra:c,rb:h,s:S,xs:p,ys:m}=r,g=E(s),A=(f,R)=>u.styles.list[s.style(f,R)]?.color??a.cellInk,v=g.compiled.length>1||g.compiled[0]?.ranges.length>1?new Set:null;for(const{ranges:f}of g.compiled)for(const R of f){const y=Math.max(R.r0,c),P=Math.min(R.r1,h),z=Math.max(R.c0,o),G=Math.min(R.c1,i);for(let d=y;d<=P;d++)for(let k=z;k<=G;k++){if(l.length>0&&s.mergeAt(d,k)!==null)continue;if(v!==null){const M=d*16384+k;if(v.has(M))continue;v.add(M)}const O=p[k-o+1]-p[k-o],_=m[d-c+1]-m[d-c];if(O<=0||_<=0)continue;const L=$(u.engine,s,g,d,k);L!==null&&I(n,L,p[k-o],m[d-c],O,_,S,{ink:A(d,k)})}}for(const f of l){if(f.r1<c||f.r0>h||f.c1<o||f.c0>i)continue;const R=$(u.engine,s,g,f.r0,f.c0);if(R===null)continue;const y=e._rectInPane(f,t,S);I(n,R,y.x,y.y,y.w,y.h,S,{ink:A(f.r0,f.c0)})}}function ye(n,e,t,{r0:r,r1:l,c0:s,c1:u,xs:a,ys:o,ox:i,oy:c,mono:h}){if(!e.engine)return;const S=E(t);for(let p=r;p<=l;p++)for(let m=s;m<=u;m++){const g=$(e.engine,t,S,p,m);if(g===null)continue;const A=e.styles.list[t.style(p,m)]?.color??"#000000";I(n,g,i+a[m-s],c+o[p-r],a[m-s+1]-a[m-s],o[p-r+1]-o[p-r],1,{ink:A,snap:!1,mono:h})}}function Se(n,e,t){const r=l=>()=>{const s=e.sparkRules;return e.sparkRules=l,n.dirty=!0,r(s)};n.transact("sparkline rule",()=>r(t.length>0?t:null)())}const re=j;Z.push((n,e,t)=>{const r=l=>re(l,e,t);for(const l of n.sheets)l.sparkRules?.length>0&&(l.sparkRules=l.sparkRules.map(s=>Object.freeze({...s,formula:r(s.formula)}))),l.sparklines?.length>0&&(l.sparklines=l.sparklines.map(s=>({...s,dateRange:s.dateRange?r(s.dateRange):s.dateRange,items:s.items.map(u=>({...u,source:r(u.source)}))})),l.sparklinesChanged=!0);x++});function H(n,e){if(!Array.isArray(n))return null;const t=[];for(const r of n.slice(0,K)){if(typeof(r?.sqref??r?.ref)!="string"||typeof r?.formula!="string")continue;const l=ee(e,r.sqref??r.ref,r.formula,{showValue:r.showValue===!0,priority:Number(r.priority)});l!==null&&t.push(l)}return t.length>0?t:null}const te=n=>n.sparkRules&&n.sparkRules.length>0?n.sparkRules.map(e=>({sqref:e.sqref,formula:e.formula,showValue:e.showValue,priority:e.priority})):void 0;w("sparklineRules",{sheet:{save:te,load(n,e,t){n.sparkRules=[...n.sparkRules??[],...H(e,t)??[]],n.sparkRules.length===0&&(n.sparkRules=null)}}}),w("cfSparkRules",{sheet:{save:()=>{},load(n,e,t){const r=H(e,t);r!==null&&(n.sparkRules=[...n.sparkRules??[],...r])}}});export{de as evaluateSparklineFormula,me as invalidateSparkRules,H as loadSparkRules,ee as makeSparkRule,ge as paintSparkRules,ye as paintSparkRulesOnPage,re as renameSheetInText,te as saveSparkRules,Se as setSparkRules,ne as sparkRuleAt,Re as sparkRuleHidesValue,ke as sparkRuleTextAt};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{colIndex as D,rangeRef as O}from"../core/address.js";import{parseTsv as I}from"../core/tsv.js";import{canEdit as S}from"./cell-editor.js";import{defaultState as R,displayOrder as L,groupPath as j,sortWith as F,toggleCollapsed as N}from"./events.js";import{parseQuickFilter as $}from"./quick-filter.js";const T=["sum","average","min","max","count","distinct"],C=["sum","average","min","max","count"],k=["sum","average","min","max","count"],V=new Set(["hidden","pinned","width","format","total","rules"]),A={data:"setData()",fields:"setData() or setDataSource()",file:"openFile()",dataSource:"setDataSource()",editable:"enableEditing()",transferColumns:"setData()"},P=new Set(["chrome","language","title","scrolling","rowSelection","renderers","detailRenderer","allowEdit","sharing","storageKey"]),p=100,w=l=>typeof l=="string"||typeof l=="number"&&Number.isFinite(l),h=l=>l!==null&&typeof l=="object"&&!Array.isArray(l);class z{#s;constructor(e){this.#s=e}#t(){if(this.#s.closed)throw new Error("The grid was destroyed.");return this.#s}#e(){const e=this.#t();if(!e.result||!e.fields)throw new Error("No table loaded.");return e}#r(e){const r=this.#e().fields.find(s=>s.name===e);if(!r)throw new Error(`Unknown field "${e}".`);return r}#o(){const e=this.#e();return L(e.state,e.fields.map(t=>t.name))}async#l(e){const t=this.#e();if(!w(e))throw new TypeError("A record ID is a number or a string.");if(!t.remote)return t.client.call("rowOf",{id:e});for(const[r,s]of t.rows?.blocks??[]){const o=s.findIndex(a=>a.id===e);if(o>=0)return r*t.rows.blockSize+o}throw new Error("This record is not loaded. A remote source scrolls to loaded records only; use scrollToRow().")}#c(e){const t=this.#s,r=t.rows?.meta?.columns??[];for(const s of t.rows?.blocks?.values()??[]){const o=s.find(a=>a.id===e&&a.group===void 0);if(o)return m(o,r)}return null}#a(e){if(!h(e)||typeof e.op!="string")throw new TypeError("A filter is { field, op, value?, value2?, values? }.");if(this.#r(e.field),(e.op==="in"||e.op==="notIn")&&!Array.isArray(e.values))throw new TypeError(`An "${e.op}" filter lists its values.`);return structuredClone(e)}#n(e,t,r=()=>{}){if(!Array.isArray(e))throw new TypeError(`${t} is a list.`);return e.map(s=>{if(!h(s))throw new TypeError(`Each item of ${t} is an object with a field.`);return this.#r(s.field),r(s),structuredClone(s)})}on(e,t){return this.#t().events.on(e,t)}off(e,t){this.#s.events.off(e,t)}destroy(){this.#s.destroy()}async openFile(e,{delimiter:t,textColumns:r,chooseSource:s=!0}={}){const o=this.#t();if(!(e instanceof Blob))throw new TypeError("openFile takes a File.");const a={};t&&(a.delimiter=t),r&&(a.textColumns=r.map(n=>typeof n=="number"?n:D(String(n).toUpperCase()))),await o.openFile(e,a,s)}async setData(e,{fields:t,title:r,editable:s,storageKey:o}={}){const a=this.#t();if(e==null||typeof e!="object")throw new TypeError("setData takes records: objects, arrays or columns.");for(const[n,i]of Object.entries({fields:t,title:r,editable:s,storageKey:o}))i!==void 0&&(a.options[n]=i);delete a.options.dataSource,await a.openData(e)}async setDataSource(e,{fields:t,title:r,editable:s,storageKey:o}={}){const a=this.#t();if(typeof e?.query!="function")throw new TypeError("A data source has a query method.");for(const[n,i]of Object.entries({fields:t,title:r,editable:s,storageKey:o}))i!==void 0&&(a.options[n]=i);if(!a.options.fields?.length)throw new Error("A remote source needs fields.");a.options.dataSource=e,await a.openRemote()}getSources(){return(this.#t().sources??[]).map((e,t)=>({index:t,name:e.name,range:O(e.range),whole:!!e.whole,header:e.headerRows!==0}))}async setSource(e,{range:t,header:r=!0}={}){const s=this.#t();if(!s.sources?.length)throw new Error("Sources belong to an open file.");await s.applySource(e,t,r)}getSource(){const e=this.#t(),t=e.sourceKind(),r={kind:t,title:t==="none"?"":e.title.textContent,editable:!!e.editable,dirty:!!e.dirty};return e.file&&(r.fileName=e.file.name),t==="file"&&Object.assign(r,{index:e.sourceIndex,range:e.sourceRange,header:e.sourceHeader}),r}async refresh({purge:e=!1}={}){const t=this.#e();t.rows&&(e?t.rows.reset():t.rows.invalidate()),await t.refresh()}getState(){return this.#e().getState()}async setState(e){const t=this.#e();if(!h(e))throw new TypeError("setState takes a state object; getState() returns one.");await t.setState({...R(t.fields),...structuredClone(e)})}async updateState(e){const t=this.#e();if(!h(e))throw new TypeError("updateState takes some keys of a state.");await t.update(structuredClone(e))}async resetState(){const e=this.#e();e.quickText?.clear(),await e.setState(R(e.fields))}async setSearch(e){const t=this.#e();clearTimeout(t.searchTimer),await t.update({search:String(e??"")})}async setFilters(e){const t=this.#e();if(!Array.isArray(e))throw new TypeError("setFilters takes a list of filters.");const r=e.map(s=>this.#a(s));t.quickText?.clear(),await t.update({filters:r,collapsed:[]})}async addFilter(e){const t=this.#e();await t.update({filters:[...t.state.filters,this.#a(e)],collapsed:[]})}async clearFilters(e){const t=this.#e();e!=null&&this.#r(e),e==null?t.quickText?.clear():t.quickText?.delete(e),await t.update({filters:e==null?[]:t.state.filters.filter(r=>r.field!==e),collapsed:[]})}async setQuickFilter(e,t){const r=this.#e(),s=this.#r(e),o=$(e,t,s.type),a=r.state.filters.filter(n=>!(n.quick&&n.field===e));o&&a.push(o),r.quickText?.delete(e),await r.update({filters:a,collapsed:[]})}async getDistinctValues(e,{limit:t=500}={}){const r=this.#e();if(this.#r(e),r.remote)throw new Error("A remote source lists its values itself.");if(!Number.isInteger(t)||t<1)throw new RangeError("limit is a positive whole number.");const{values:s}=await r.client.call("distinct",{field:e});return s.slice(0,t).map(({value:o,text:a,count:n})=>({value:o,text:a,count:n}))}async setSort(e){await this.#e().update({sort:this.#n(e,"sort").map(({field:r,desc:s})=>({field:r,desc:s===!0}))})}async sortBy(e,{desc:t=!1,add:r=!1}={}){const s=this.#e();this.#r(e),await s.update({sort:F(s.state.sort,e,t,r)})}async clearSort(e){const t=this.#e();e!=null&&this.#r(e),await t.update({sort:e==null?[]:t.state.sort.filter(r=>r.field!==e)})}async setGroups(e){const t=this.#e(),r=this.#n(e,"groups").map(({field:s,desc:o})=>o===!0?{field:s,desc:o}:{field:s});await t.update({groups:r,collapsed:[]})}async groupBy(e,{desc:t}={}){const r=this.#e();this.#r(e);const s=t===!0?{field:e,desc:t}:{field:e};await r.update({groups:[...r.state.groups.filter(o=>o.field!==e),s],collapsed:[]})}async clearGroups(e){const t=this.#e();e!=null&&this.#r(e),await t.update({groups:e==null?[]:t.state.groups.filter(r=>r.field!==e),collapsed:[]})}async#i(e,t){const r=this.#e();if(!r.state.groups.length)throw new Error("The records are not grouped.");const s=j(e);await r.applyLayout({collapsed:N(r.state.collapsed,s,t,r.state.collapseLevel)})}expandGroup(e){return this.#i(e,!1)}collapseGroup(e){return this.#i(e,!0)}async expandAll(){await this.#e().applyLayout({collapsed:[],collapseLevel:void 0})}async collapseAll(){await this.#e().applyLayout({collapsed:[],collapseLevel:0})}async setSummary(e){const t=this.#e();if(e!=null&&(this.#r(e.field),!T.includes(e.agg)))throw new Error(`A summary is one of ${T.join(", ")}.`);await t.applyLayout({total:e?{field:e.field,agg:e.agg}:null})}async setTotalsRow(e){await this.#e().toggleTotals(e!==!1)}async setFilterRow(e){await this.#e().toggleFilterRow(e!==!1)}getFields(){return(this.#t().fields??[]).map(e=>({...e}))}getColumn(e){const t=this.#e().state.columns.find(r=>r.field===e);return t?structuredClone(t):null}async setColumns(e){const t=this.#e(),r=this.#n(e,"columns",s=>x(s));if(new Set(r.map(s=>s.field)).size!==r.length)throw new Error("Each field appears once in columns.");await t.applyLayout({columns:r})}async setColumn(e,t){const r=this.#e();if(this.#r(e),!h(t))throw new TypeError("setColumn takes some keys of a column: hidden, pinned, width, format, total, rules.");for(const n of Object.keys(t))if(!V.has(n))throw new Error(`Unknown column setting "${n}".`);x(t);const s=Object.keys(t),o=r.state.columns.some(n=>n.field===e),a=(o?r.state.columns:[...r.state.columns,{field:e}]).map(n=>{if(n.field!==e)return n;const i={...n,...structuredClone(t)};for(const u of s)t[u]==null&&u!=="total"&&delete i[u];return i});if(o&&s.length===1&&s[0]==="width")return r.setColumnWidth(e,t.width??void 0);await r.applyLayout({columns:a})}async moveColumn(e,t){const r=this.#e();this.#r(e),t!=null&&this.#r(t),await r.moveColumn(e,t??null)}async autosizeColumn(e){const t=this.#e();if(this.#r(e),!this.#o().includes(e))throw new Error(`Show column "${e}" first.`);return await t.showColumn(e,this.#o()),t.autosizeColumn(e)??null}async addCalculatedField(e,t){await this.#e().addCalculatedField(e,t,"api")}getSavedViews(){return[...this.#e().readViews()].map(([e,t])=>({name:e,state:t}))}saveView(e,t){const r=this.#e();if(e=String(e??"").trim(),!e)throw new Error("A saved view needs a name.");const s=r.readViews();s.set(e,t?structuredClone(t):r.getState()),r.writeViews(s)}async restoreView(e){const t=this.#e(),r=t.readViews().get(e);if(!r)throw new Error(`No saved view "${e}".`);await t.setState(r)}deleteView(e){const t=this.#e(),r=t.readViews(),s=r.delete(e);return s&&t.writeViews(r),s}async openPivot({rowField:e,columnField:t,valueField:r,agg:s="sum"}={}){const o=this.#e();if(this.#r(e),this.#r(r),t&&this.#r(t),!k.includes(s))throw new Error(`A pivot value is one of ${k.join(", ")}.`);await o.openPivot({rowField:e,columnField:t||"",valueField:r,agg:s})}async closePivot(){await this.#e().closePivot()}async getChartData(e){const t=this.#e();if(!t.base)throw new Error("Chart data belongs to a pivot. Call openPivot() first.");return this.#r(e),t.client.call("chart",{field:e})}getPage(){const e=this.#e(),t=e.result;return e.continuous?{mode:"continuous",index:0,count:1,size:null}:{mode:"pages",index:Math.floor(t.offset/e.limit),count:t.exact===!1?null:Math.max(1,Math.ceil(t.count/e.limit)),size:e.limit}}async setPage(e){const t=this.#e();if(t.continuous)throw new Error('Paging is off. Call setScrolling("pages") first, or scrollToRow().');if(!Number.isInteger(e)||e<0)throw new RangeError("A page index is a whole number from 0.");const r=t.result;if(r.exact!==!1&&e*t.limit>=Math.max(1,r.count))throw new RangeError(`Page ${e} is past the last page.`);t.offset=e*t.limit,t.content.scrollTop=0,await t.refresh(!1)}async setScrolling(e){await this.#t().setScrolling(e)}getViewport(){return this.#e().viewport()}async scrollToRow(e){const t=this.#e();if(!Number.isInteger(e)||e<0)throw new RangeError("A row index is a whole number from 0.");if(t.result.exact!==!1&&e>=t.result.count)throw new RangeError(`Row ${e} is past the last row.`);await t.showRow(e)}async scrollToRecord(e){const t=this.#e(),r=await this.#l(e);return r<0?!1:(await t.showRow(r),!0)}async scrollToColumn(e){const t=this.#e();this.#r(e);const r=this.#o();if(!r.includes(e))throw new Error(`Column "${e}" is hidden.`);await t.showColumn(e,r)}async focusCell(e,t){const r=this.#e();if(this.#r(t),!await this.scrollToRecord(e))return!1;await this.scrollToColumn(t);const s=r.grid?.positionOf(e,t);return s?(r.grid.focusAt(s.row,s.col),!0):!1}getFocusedCell(){return this.#t().grid?.focused()??null}getRange(){const e=this.#t(),{range:t,grid:r}=e;if(!t||!r||!e.result)return null;const s=r.positionOf(t.anchor.id,t.anchor.field),o=r.positionOf(t.focus.id,t.focus.field);if(!s||!o)return null;const[a,n]=[Math.min(s.row,o.row),Math.max(s.row,o.row)],[i,u]=[Math.min(s.col,o.col),Math.max(s.col,o.col)],d=r.records.slice(a,n+1);return{anchor:{...t.anchor},focus:{...t.focus},ids:d.map(c=>c.id),fields:e.result.columns.slice(i,u+1),values:d.map(c=>c.values.slice(i,u+1))}}async setRange({anchor:e,focus:t=e}={}){const r=this.#e();for(const n of[e,t]){if(!h(n)||!w(n.id))throw new TypeError("A range is { anchor: { id, field }, focus: { id, field } }.");this.#r(n.field)}const s=n=>{const i=r.grid?.positionOf(n.id,n.field);return i&&r.grid.cells[i.row][i.col]?i:null};if(!s(e)){if(!await this.scrollToRecord(e.id))throw new Error("The range starts at a record that is not in the view.");await this.scrollToColumn(e.field)}const o=s(e),a=r.grid?.positionOf(t.id,t.field);if(!o||!a)throw new Error("A range covers drawn records only. Choose records near each other, or scroll first.");r.grid.select(o,a,!1)}async copyRange(){const e=this.#e();if(!this.getRange())throw new Error("Select cells first.");const t=e.grid.copyText();return await navigator.clipboard.writeText(t),t}getSelection(){return this.#t().getSelection()}async setSelection(e){await this.#e().setSelection(e)}async selectRecords(e,t=!0){const r=this.#e();if(!r.selection)throw new Error("Row selection is off for this table.");if(!Array.isArray(e)||!e.every(w))throw new TypeError("selectRecords takes a list of record IDs.");for(const s of e)r.selection.toggle(s,t!==!1);await r.recountSelection(!0)}async selectAll(){await this.#e().selectAll()}async clearSelection(){await this.#e().clearSelection()}getSelectedIds(){return this.#e().getSelectedIds()}async openRecordDetails(e){const t=this.#e(),r=t.result.rows.find(s=>s.id===e&&s.group===void 0&&!s.loading);if(r)return t.details(r);if(!t.remote)return await t.client.call("record",{id:e}),t.details({id:e},await t.client.call("detail",{id:e}));if(t.remote.detail)return t.details({id:e},await t.remote.detail({id:e,state:t.getState(),signal:new AbortController().signal}));throw new Error("This record is not loaded, and the source has no detail method.")}async openDialog(e,{field:t}={}){const r=this.#t(),s=()=>{if(r.remote)throw new Error("This dialog needs local records.")},o=()=>{if(s(),!r.editable)throw new Error("This view is read-only.")};if(e==="source"){if(!r.sources?.length||r.base)throw new Error("Sources belong to an open file.");return r.chooseSource()}switch(this.#e(),e){case"filter":return t!=null&&this.#r(t),r.filterDialog(t);case"sort":return r.orderDialog(!1);case"group":return r.orderDialog(!0);case"summary":return r.summaryDialog();case"columns":return r.columnsDialog();case"views":return r.readViews(),r.viewsDialog();case"pivot":if(s(),r.base)throw new Error("Go back to the records first.");return r.pivotDialog();case"chart":if(!r.base)throw new Error("A chart belongs to a pivot. Call openPivot() first.");return r.chartDialog();case"export":if(r.remote&&!r.remote.exportResults)throw new Error("This source cannot export.");return r.exportDialog();case"share":if(r.remote&&!r.remote.exportResults)throw new Error("This source cannot export.");if(!r.options.sharing&&!navigator.canShare)throw new Error("Sharing needs a sharing option.");return r.shareDialog();case"calculatedField":return o(),r.formulaDialog();case"addRecord":return o(),r.addRecordDialog();case"conditionalFormatting":return this.#r(t),r.formatDialog(t);default:throw new Error(`Unknown dialog "${e}".`)}}closeDialog(){const e=this.#t();e.root.querySelector(".tv-menu")?.dispatchEvent(new Event("tv-close"));const t=[...e.root.querySelectorAll("dialog[open]")];for(const r of t)r.close();return t.length>0}async expandRecord(e){const t=this.#e();if(!t.options.detailRenderer)throw new Error("Expanding a record needs the detailRenderer option.");if(t.expanded?.id===e)return!0;if(!await this.scrollToRecord(e))return!1;const r=t.result,s=r.rows.findIndex(o=>o.id===e&&o.group===void 0&&!o.loading);return s<0?!1:(t.toggleDetail(r.rows[s],r.offset+s),!0)}collapseRecord(){const e=this.#t();return e.expanded?(e.expanded=null,e.renderRows(),!0):!1}getExpandedRecord(){return this.#t().expanded?.id??null}isEditable(){return!!this.#t().editable}async enableEditing(){await this.#e().enableEditing()}setCellValue(e,t,r){return this.updateRecords([{id:e,values:{[t]:r}}])}async updateRecords(e){const t=this.#e();if(!Array.isArray(e))throw new TypeError("updateRecords takes a list of { id, values }.");const r=[];for(const s of e){if(!h(s)||!w(s.id)||!h(s.values))throw new TypeError("Each update is { id, values: { field: value } }.");for(const[o,a]of Object.entries(s.values)){if(this.#r(o),t.remote&&t.editable&&!S(t,o))throw new Error("This field is read-only.");r.push({id:s.id,field:o,value:a})}}return r.length?t.change("edit",{cells:r},"api"):!1}async addRecords(e){const t=this.#e();if(!Array.isArray(e)||!e.every(h))throw new TypeError("addRecords takes a list of records: { field: value } objects.");for(const s of e)for(const o of Object.keys(s))this.#r(o);if(!e.length)return[];const r=await t.change("add",{records:structuredClone(e)},"api");return r===!1?null:r}async removeRecords(e){const t=this.#e();if(!Array.isArray(e)||!e.every(w))throw new TypeError("removeRecords takes a list of record IDs.");return e.length?t.change("remove",{ids:[...new Set(e)]},"api"):!1}async paste(e,{id:t,field:r,repeat:s=1}={}){const o=this.#e(),a=typeof e=="string"?I(e):Array.isArray(e)&&e.every(Array.isArray)?e.map(n=>n.map(i=>i==null?"":String(i))):null;if(!a?.length)throw new TypeError("paste takes tab-separated text or a list of rows.");if(t===void 0||r===void 0){const n=this.getRange();if(!n)throw new Error("Choose where to paste: pass { id, field }, or select a cell.");t=n.ids[0],r=n.fields[0]}if(this.#r(r),!Number.isSafeInteger(s)||s<1)throw new RangeError("repeat is a whole number from 1.");return o.change("paste",{id:t,field:r,lines:a,repeat:s},"api")}async fillDown(){const e=this.#e();if(e.remote)throw new Error("Fill down works on local records.");const t=this.getRange();if(!t||t.ids.length<2)throw new Error("Select cells across two or more records first.");return e.grid.fillDown("api")}async undo(){return this.canUndo()?this.#s.change("undo",{},"api"):!1}async redo(){return this.canRedo()?this.#s.change("redo",{},"api"):!1}canUndo(){const e=this.#t();return!e.remote&&!!e.result?.canUndo}canRedo(){const e=this.#t();return!e.remote&&!!e.result?.canRedo}async startEdit(e,t,{text:r}={}){const s=this.#e();if(this.#r(t),!S(s,t))throw new Error(s.editable?"This field is read-only.":"This view is read-only.");if(!await this.focusCell(e,t))return!1;const o=s.grid.positionOf(e,t);return!!o&&s.grid.edit(o,r==null?void 0:String(r))}async stopEdit({cancel:e=!1}={}){const t=this.#t().editor;return t?e?(t.cancel(),!0):t.commit():!1}getEditingCell(){const e=this.#t().editor;return e?{id:e.id,field:e.field}:null}exportResults(e,t){return this.#t().exportResults(e,t)}async download(e,t){await this.#t().downloadResults(e,t)}createShareLink(){return this.#e().createShare()}revokeShareLink(){return this.#t().revokeShare()}isLoading(){return!!this.#t().load}cancelLoad(){return this.#t().cancelLoad()}setChrome(e){this.#t().setChrome(e)}getChrome(){return structuredClone(this.#t().chrome)}setLanguage(e){this.#t().setLanguage(e)}getLanguage(){return this.#t().language}async setOptions(e){const t=this.#t();if(!h(e))throw new TypeError("setOptions takes some options.");for(const s of Object.keys(e)){if(A[s])throw new Error(`The ${s} option can't change after mount. Use ${A[s]}.`);if(!P.has(s)&&!/^on[A-Z]/.test(s))throw new Error(`Unknown option "${s}".`);if(/^on[A-Z]/.test(s)&&e[s]!=null&&typeof e[s]!="function")throw new TypeError(`${s} is a function.`)}let r=!1;for(const[s,o]of Object.entries(e))switch(s){case"chrome":t.setChrome(o??"auto");break;case"language":t.setLanguage(o);break;case"scrolling":await t.setScrolling(o??"continuous");break;case"rowSelection":t.setRowSelection(o??null);break;case"title":t.options.title=o,t.result&&!t.file&&!t.base&&(t.title.textContent=o||t.t("Table"));break;case"storageKey":t.options.storageKey=o,t.result&&!t.file&&!t.base&&(t.storageKey=o?"8sheets.table.v1|"+JSON.stringify([o,t.title.textContent,t.fields.map(a=>a.name)]):null),t.renderTools();break;case"detailRenderer":t.options.detailRenderer=o??void 0,t.expanded=null,r=!0;break;case"renderers":t.options.renderers=o??void 0,r=!0;break;default:o==null?delete t.options[s]:t.options[s]=o,(s==="allowEdit"||s==="sharing")&&t.renderHeader()}r&&t.result&&t.renderRows()}async getRecords({offset:e=0,limit:t=100}={}){const r=this.#e();if(!Number.isSafeInteger(e)||e<0)throw new RangeError("offset is a whole number from 0.");if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new RangeError("limit is a whole number from 1 to 10000.");if(!r.remote)return r.client.call("rows",{offset:e,limit:t});if(r.state.groups.length)throw new Error("A grouped remote result mixes group rows with records. Ungroup it, or query your server.");const s=r.getState(),o=new AbortController().signal,a=[];let n=null;for(let i=Math.floor(e/p)*p;i<e+t;i+=p){const u=[];let d=0;for(;;){const f=await r.remote.query({state:s,offset:i,limit:p,columnOffset:d,columnLimit:r.columnLimit,signal:o});if(u.push(f),d+=r.columnLimit,!Number.isSafeInteger(f.columnCount)||d>=f.columnCount)break}const c=u[0];if(Number.isSafeInteger(c.matches)?n=c.matches:Number.isSafeInteger(c.count)&&(n=c.count),c.rows.forEach((f,y)=>{const E=i+y;if(E<e||E>=e+t||f.group!==void 0)return;const g=m(f,c.columns);for(const b of u.slice(1)){const v=m(b.rows[y]??{values:[]},b.columns);Object.assign(g.values,v.values),Object.assign(g.raw,v.raw)}a.push(g)}),c.rows.length<p||c.offset!==i)break}return{total:n,records:a}}async getRecord(e){const t=this.#e();if(!w(e))throw new TypeError("A record ID is a number or a string.");if(!t.remote)return t.client.call("record",{id:e});const r=this.#c(e);if(r)return r;if(!t.remote.detail)throw new Error("This record is not loaded, and the source has no detail method.");const s=await t.remote.detail({id:e,state:t.getState(),signal:new AbortController().signal});return{id:e,values:Object.fromEntries(s.map(o=>[o.field,o.value])),raw:{}}}async getCell(e,t){this.#r(t);const r=await this.getRecord(e);if(!Object.hasOwn(r.values,t))throw new Error(`Field "${t}" is not available for this record.`);return{value:r.raw[t]??null,text:r.values[t]}}getCounts(){const e=this.#e().result;return{matches:Number.isSafeInteger(e.matches)?e.matches:null,sourceCount:Number.isSafeInteger(e.sourceCount)?e.sourceCount:null,count:e.count,exact:e.exact!==!1}}getTotals(){const e=this.#e(),t=e.state.total;return{summary:t?{field:t.field,agg:t.agg,text:e.result.summary??""}:null,totals:{...e.result.totals??{}}}}}function m(l,e){const t={},r={};return e.forEach((s,o)=>{t[s]=l.values?.[o]??"",r[s]=l.raw?.[o]??null}),{id:l.id,values:t,raw:r}}function x(l){if(l.width!=null&&(!Number.isFinite(l.width)||l.width<48||l.width>800))throw new RangeError("A column width is 48 to 800 pixels.");if(l.total!=null&&!C.includes(l.total))throw new Error(`A column total is one of ${C.join(", ")}.`);if(l.rules!=null&&!Array.isArray(l.rules))throw new TypeError("Column rules are a list.");if(l.format!=null&&typeof l.format!="string")throw new TypeError('A column format is a number format text, such as "#,##0.00".')}export{z as DataGridApi};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{el as y}from"./panel.js";import{cancellable as g}from"./events.js";function x(t,i){const o=t.fieldIndex?.get(i);return!!(t.editable&&(t.remote?o?.editable===!0:o?.editable))}function k(t,i,o,a,m,c){const r=t.result.columns[a];if(!x(t,r)||i.querySelector(".tv-cell-editor"))return!1;const u=o.raw?.[a],p=t.fieldIndex.get(r)?.type==="number"&&typeof u=="number"&&Number.isFinite(u)?String(u):o.values[a]??"";if(!t.emit("editStart",g({id:o.id,field:r,value:u??null,text:p})))return!1;t.editor?.cancel();const n=y("input",null,{className:"tv-cell-editor",value:m??p,spellcheck:!1,size:4});n.setAttribute("aria-label",(t.fieldIndex.get(r)?.caption||r)+" · "+t.t("Edit"));const v=[...i.childNodes];i.classList.add("tv-editing"),i.replaceChildren(n),n.focus(),m==null&&n.select();let s=!1;const b=t.editor={id:o.id,field:r,get busy(){return s},commit:()=>f(null),cancel:()=>{t.status.textContent="",d(!0)}},d=(e,l)=>{t.editor===b&&(t.editor=null,i.classList.remove("tv-editing"),i.isConnected&&i.replaceChildren(...v),t.emit("editEnd",{id:o.id,field:r,cancelled:e,value:e?u??null:l}))},f=async e=>{if(s)return!0;if(n.value===p)return d(!1,u??null),c?.focus(e),!0;s=!0;try{t.focusAfter={id:o.id,col:a,step:e};const l=n.value;return await t.change("edit",{revision:t.result.revision,cells:[{id:o.id,field:r,value:l}]})===!1?(t.focusAfter=null,s=!1,d(!0),c?.focus({row:0,col:0}),!1):(t.status.textContent="",d(!1,l),!0)}catch(l){return t.focusAfter=null,s=!1,n.setAttribute("aria-invalid","true"),t.status.textContent=t.t(l.message),t.emit("error",l),n.focus(),!1}};n.addEventListener("keydown",e=>{e.stopPropagation(),e.key==="Escape"?(e.preventDefault(),t.status.textContent="",d(!0),c?.focus({row:0,col:0})):e.key==="Enter"?(e.preventDefault(),f({row:e.shiftKey?-1:1,col:0})):e.key==="Tab"&&(e.preventDefault(),f({row:0,col:e.shiftKey?-1:1}))}),n.addEventListener("blur",()=>{!s&&i.contains(n)&&!t.closed&&setTimeout(()=>!s&&i.contains(n)&&f(null),0)});for(const e of["copy","cut","paste","pointerdown","dblclick"])n.addEventListener(e,l=>l.stopPropagation());return!0}export{x as canEdit,k as startCellEdit};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const k=["gt","gte","lt","lte","between","equal","notEqual","contains"],h=["good","bad","warn","info","strong"],p=["var(--tv-cf-low)","var(--tv-cf-mid)","var(--tv-cf-high)"];function y(o,t,r){const i=typeof t=="number"&&Number.isFinite(t);if(o.op==="contains")return String(o.value??"")!==""&&r.toLowerCase().includes(String(o.value).toLowerCase());if(o.op==="equal"||o.op==="notEqual"){const u=o.value,e=i&&u!==""&&u!=null&&Number.isFinite(Number(u))?t===Number(u):r.toLowerCase()===String(u??"").toLowerCase();return o.op==="equal"?e:!e}if(!i)return!1;const c=Number(o.value),n=Number(o.value2);if(!Number.isFinite(c))return!1;switch(o.op){case"gt":return t>c;case"gte":return t>=c;case"lt":return t<c;case"lte":return t<=c;case"between":return Number.isFinite(n)&&t>=Math.min(c,n)&&t<=Math.max(c,n);default:return!1}}const v=(o,t,r)=>`color-mix(in srgb, ${o} ${Math.round(r*100)}%, ${t})`;function x(o,t,r,i,c=!1){if(!o?.length)return null;let n=null;const u=typeof t=="number"&&Number.isFinite(t);for(const e of o)if(e){if(e.type==="value"){if(n?.ruled||!y(e,t,r??""))continue;n??={},n.ruled=!0;const s=h.includes(e.style)?e.style:e.background||e.color?null:"info";s==="strong"?n.weight=700:s&&(n.background=`var(--tv-cf-${s}-bg)`,n.color=`var(--tv-cf-${s}-ink)`),e.background&&(n.background=e.background),e.color&&(n.color=e.color);continue}if(!(!u||!i||!(i.max>=i.min))){if(e.type==="scale"){if(n?.ruled&&n.background)continue;const[s,b,f]=Array.isArray(e.colors)&&e.colors.length===3?e.colors:p,l=i.max-i.min,a=l>0?(t-i.min)/l:.5;(n??={}).background=a<.5?v(b,s,a*2):v(f,b,(a-.5)*2)}else if(e.type==="bar"){const s=Math.min(0,i.min),f=Math.max(0,i.max)-s||1,l=(0-s)/f*100,a=(t-s)/f*100,g=Math.min(l,a),m=Math.max(l,a),d=t<0?"var(--tv-cf-bar-negative)":e.color??"var(--tv-cf-bar)";(n??={}).backgroundImage=`linear-gradient(to ${c?"left":"right"}, transparent ${g}%, ${d} ${g}%, ${d} ${m}%, transparent ${m}%)`}}}return n}function $(o,t){t&&(t.background&&(o.style.backgroundColor=t.background),t.color&&(o.style.color=t.color),t.weight&&(o.style.fontWeight=t.weight),t.backgroundImage&&(o.classList.add("tv-cf-bar"),o.style.backgroundImage=t.backgroundImage))}function N(o,t){let r=1/0,i=-1/0;for(const c of o){const n=c.raw?.[t];typeof n!="number"||!Number.isFinite(n)||(n<r&&(r=n),n>i&&(i=n))}return r<=i?{min:r,max:i}:null}export{k as RULE_OPS,h as RULE_STYLES,x as cellFormat,$ as paintCell,N as rangeOf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SKINS as s}from"../api/skins.js";const c={panel:"bg",chrome:"base",ink:"ink","ink-soft":"muted","panel-line":"line",accent:"accent",hover:"tint","on-accent":"on-accent"};function h(e,t){const n=typeof t=="object"&&t?t:Object.hasOwn(s,t)?s[t]:null,o=n?n.base??"light":t;if(!["auto","light","dark"].includes(o))throw new Error("Unknown table theme.");e.style.colorScheme=o==="auto"?"light dark":o;for(const[l,a]of Object.entries(c)){const r=n?.tokens?.[l];r?e.style.setProperty("--tv-"+a,r):e.style.removeProperty("--tv-"+a)}}function m(){try{return localStorage.getItem("sheets.theme")||"auto"}catch{return"auto"}}function f(e){try{e==="auto"?localStorage.removeItem("sheets.theme"):(e==="light"||e==="dark")&&localStorage.setItem("sheets.theme",e)}catch{}}export{h as applyTableChrome,m as readTableChrome,f as saveTableChrome};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class h{constructor(){this.worker=new Worker(new URL("./reader.worker.js",import.meta.url),{type:"module"}),this.pending=new Map,this.sequence=0,this.worker.onmessage=({data:e})=>{const r=this.pending.get(e.requestId);if(r){if(e.progress)return r.onProgress?.(e.progress);this.pending.delete(e.requestId),e.error?r.reject(new Error(e.error)):r.resolve(e.value)}},this.worker.onerror=e=>this.close(new Error(e.message||"The table worker could not start."))}call(e,r={},o=[],n){return this.closed?Promise.reject(this.closed):new Promise((i,t)=>{const s=++this.sequence;this.pending.set(s,{resolve:i,reject:t,onProgress:n});try{this.worker.postMessage({...r,op:e,requestId:s},o)}catch(l){this.pending.delete(s),t(l)}})}close(e=new Error("Table view closed.")){this.closed=e,this.worker.terminate();for(const r of this.pending.values())r.reject(e);this.pending.clear()}}export{h as TableClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{el as g}from"./panel.js";const w=48,C=800,v=t=>Math.round(Math.max(w,Math.min(C,t)));function L(t,n){const i=n?n+"px":"";t.style.width=t.style.minWidth=t.style.maxWidth=i}function u(t,n){return[...t.content.querySelectorAll("thead tr:first-child th[data-field]")].find(i=>i.dataset.field===n)}function f(t,n){const i=u(t,n);if(!i)return[];const e=i.cellIndex,o=[i];for(const l of i.closest("table").rows){if(l===i.parentElement||l.cells.length<=e)continue;const r=l.cells[e];r.colSpan===1&&o.push(r)}return o}function M(t,n){const i=f(t,n);if(!i.length)return null;const e=document.createRange();let o=0;for(const l of i){const r=getComputedStyle(l),c=parseFloat(r.paddingLeft)+parseFloat(r.paddingRight)+2;let s=0;if(l.tagName==="TH")for(const d of l.children)s+=d.classList.contains("tv-resize")?0:d.offsetWidth+2;else e.selectNodeContents(l),s=e.getBoundingClientRect().width;o=Math.max(o,Math.ceil(s+c))}return v(o)}function W(t,n){const i=t.rtl??=getComputedStyle(t.root).direction==="rtl";n.tHead?.addEventListener("pointerdown",e=>{if(e.button!==0)return;const o=e.target.closest(".tv-resize");if(o)return b(t,o.closest("th").dataset.field,e,i);const l=e.target.closest(".tv-sort");l&&e.pointerType!=="touch"&&E(t,l.closest("th").dataset.field,e)}),n.tHead?.addEventListener("dblclick",e=>{const o=e.target.closest(".tv-resize");o&&(e.preventDefault(),t.perform(()=>t.autosizeColumn(o.closest("th").dataset.field)))})}function x(t,n){const i=o=>t(o),e=o=>{document.removeEventListener("pointermove",i),document.removeEventListener("pointerup",e),document.removeEventListener("pointercancel",e),n(o,o.type==="pointercancel")};document.addEventListener("pointermove",i),document.addEventListener("pointerup",e),document.addEventListener("pointercancel",e)}function y(){const t=n=>{n.stopPropagation(),n.preventDefault()};window.addEventListener("click",t,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",t,{capture:!0}),0)}function b(t,n,i,e){const o=u(t,n);if(!o)return;i.preventDefault();const l=o.getBoundingClientRect().width;let r=l;t.root.classList.add("tv-resizing"),x(c=>{r=v(l+(e?i.clientX-c.clientX:c.clientX-i.clientX)),t.liveWidths.set(n,r);for(const p of f(t,n))L(p,r);const s=u(t,n),d=s?.closest("table"),a=d?.querySelector("colgroup")?.children[s.cellIndex];a&&(d.style.width=parseFloat(d.style.width)+r-parseFloat(a.style.width)+"px",a.style.width=r+"px"),t.positionPinned?.()},(c,s)=>{if(t.root.classList.remove("tv-resizing"),t.liveWidths.delete(n),r!==l){if(s)return t.renderRows();y(),t.setColumnWidth(n,r)}})}function E(t,n,i){let e=null,o=null,l=null;const r=()=>t.root.getBoundingClientRect();x(c=>{if(!e){if(Math.abs(c.clientX-i.clientX)<6)return;const h=u(t,n);if(!h)return;e=g("div",h.querySelector(".tv-sort")?.textContent??n,{className:"tv-drag-ghost"}),o=g("div",null,{className:"tv-drop-marker"}),e.setAttribute("aria-hidden","true"),o.setAttribute("aria-hidden","true"),t.root.append(e,o),t.root.classList.add("tv-moving")}const s=r();e.style.left=c.clientX-s.left+8+"px",e.style.top=c.clientY-s.top+8+"px";const d=[...t.content.querySelectorAll("thead tr:first-child th[data-field]")];l=null;let a=d.length?d.at(-1).getBoundingClientRect().right:0;for(const h of d){const m=h.getBoundingClientRect();if(c.clientX<m.left+m.width/2){l=h.dataset.field,a=m.left;break}}const p=d[0]?.closest("thead").getBoundingClientRect();o.style.left=a-s.left-1+"px",o.style.top=(p?.top??0)-s.top+"px",o.style.height=Math.min(t.content.getBoundingClientRect().bottom,(p?.bottom??0)+400)-(p?.top??0)+"px"},(c,s)=>{e&&(e.remove(),o.remove(),t.root.classList.remove("tv-moving"),y(),!s&&l!==n&&t.perform(()=>t.moveColumn(n,l)))})}export{C as MAX_WIDTH,w as MIN_WIDTH,W as enableColumnDrag,M as fitWidth,L as sizeCell};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
async function x(n,o,h,A){if(!Array.isArray(n)||n.length<4096||!o?.length)return null;const b=e=>e.formula!=null||e.lookup!=null||e.rollup!=null||e.window!=null,i=o.filter(e=>!b(e)).map((e,l)=>({field:e,index:l}));if(!i.length||i.some(({field:e})=>!["string","number","boolean"].includes(e.type)||e.name.includes(".")))return null;const p=Object.create(null),m=Object.create(null),g=new Map;for(const{field:e}of i){const l=e.type==="string";p[e.name]=l?new Int32Array(n.length):new Float64Array(n.length),l&&(m[e.name]=[],g.set(e.name,new Map))}const M=Array.isArray(n[0]);let w=performance.now()+8;for(let e=0;e<n.length;e+=512){if(h())throw new Error("Table view closed.");A?.(e,n.length);const l=Math.min(n.length,e+512);for(const{field:a,index:k}of i){const y=M?k:a.name,c=p[a.name];if(a.type==="string"){const t=m[a.name],s=g.get(a.name);for(let r=e;r<l;r++){const u=n[r][y];if(u==null)c[r]=-1;else{if(typeof u!="string")return null;{let f=s.get(u);f===void 0&&(f=t.length,t.push(u),s.set(u,f)),c[r]=f}}}}else for(let t=e;t<l;t++){const s=n[t][y];if(s==null)c[t]=NaN;else{if(typeof s!==a.type)return null;c[t]=s}}}performance.now()>w&&(await v(),w=performance.now()+8)}return{columns:p,strings:m}}const v=()=>new Promise(n=>{const o=new MessageChannel;o.port1.onmessage=()=>{o.port1.close(),n()},o.port2.postMessage(null)});export{x as packRecords};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const M=240,v=80;function C(n,t){const e=n.state;return JSON.stringify([t.columns,e.columns.map(o=>[o.field,o.width,o.pinned,o.hidden,o.format]),!!e.filterRow,!!e.totalsRow,!!n.selection,!!n.options.detailRenderer,n.language,n.content.clientWidth])}function L(n,t){const e=n.measured;return t.columns.map(o=>n.columnWidth(o)??e.widths.get(o)??100)}function N(n,t){const e=t.columns.map((m,h)=>h),o=C(n,t),s=n.measured;if(!s||s.sig!==o||s.fields!==n.fields)return{slots:e,measure:o,left:n.content.scrollLeft};const i=L(n,t),d=s.lead+i.reduce((m,h)=>m+h,0),c=n.content.clientWidth,l={lead:s.lead,widths:i,total:d};if(d<=c+1)return{slots:e,fixed:l,range:null};const r=t.columns.findIndex(m=>!n.columnIndex.get(m)?.pinned),a=r<0?t.columns.length:r,u=x(n,i,a,s.lead,240),f=e.slice(0,a),g=(m,h)=>i.slice(m,h).reduce((R,W)=>R+W,0);u.first>a&&f.push({gap:g(a,u.first)});for(let m=u.first;m<=u.last;m++)f.push(m);return u.last<i.length-1&&f.push({gap:g(u.last+1,i.length)}),{slots:f,fixed:l,range:{...u,p:a}}}function x(n,t,e,o,s){const i=n.content.scrollLeft,d=n.content.clientWidth;let c=o;for(let f=0;f<e;f++)c+=t[f];const l=i+c-s,r=i+d+s;let a=-1,u=-1;for(let f=e;f<t.length;f++){const g=c+t[f];g>l&&c<r&&(a<0&&(a=f),u=f),c=g}return a<0&&(a=u=Math.min(e,t.length-1)),{first:Math.max(e,a),last:Math.max(e,u)}}function S(n){const t=n.colWindow;if(!t||!n.result)return!1;if(t.measure)return n.content.scrollLeft!==t.left;if(!t.range)return!1;const e=x(n,t.fixed.widths,t.range.p,t.fixed.lead,160);return e.first<t.range.first||e.last>t.range.last}const w=(n,t)=>{let e="";for(const o of n){const s=o.values?.[t];s!=null&&s.length>e.length&&(e=s)}return e};function A(n,t,e,o,s){const d=[...e.cells].map(l=>l.getBoundingClientRect().width),c=getComputedStyle(s);n.measured={sig:o,fields:n.fields,lead:d[0],widths:new Map(t.columns.map((l,r)=>[l,d[r+1]])),chars:new Map(t.columns.map((l,r)=>[l,w(t.rows,r).length])),font:c.font,pad:parseFloat(c.paddingLeft)+parseFloat(c.paddingRight)+2}}let p=null;function O(n,t,e){const o=n.measured;let s=0;for(const i of e.slots){if(typeof i!="number")continue;const d=t.columns[i];if(n.columnWidth(d)!=null)continue;const c=w(t.rows,i);if(c.length<=(o.chars.get(d)??0))continue;o.chars.set(d,c.length),p??=document.createElement("canvas").getContext("2d"),p.font=o.font;const l=Math.ceil(p.measureText(c).width+o.pad);l<=e.fixed.widths[i]||(s+=l-e.fixed.widths[i],e.fixed.widths[i]=l,o.widths.set(d,l))}e.fixed.total+=s}function y(n,t){const e=n.colWindow;if(!e?.fixed)return!1;const{widths:o,lead:s}=e.fixed,i=e.range?.p??0;let d=s;for(let r=0;r<t;r++)d+=o[r];let c=s;for(let r=0;r<i;r++)c+=o[r];const l=n.content;return d-l.scrollLeft<c?l.scrollLeft=d-c:d+o[t]-l.scrollLeft>l.clientWidth&&(l.scrollLeft=d+o[t]-l.clientWidth),!0}export{N as columnWindow,S as columnsStale,A as measureColumns,y as revealColumn,O as widenColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const d=["stateChange","change","selectionChange","rangeChange","cellClick","cellDoubleClick","rowClick","rowDoubleClick","editStart","editEnd","beforeEdit","beforeAdd","beforeRemove","beforePaste","sourceLoad","viewportChange","loadStart","loadProgress","loadEnd","error"],p=new Set(d),c=t=>"on"+t[0].toUpperCase()+t.slice(1);function g(t=()=>({})){const e=new Map,o=(n,r)=>{if(!p.has(n))throw new Error(`Unknown grid event "${n}".`);if(typeof r!="function")throw new TypeError("An event handler must be a function.")};return{on(n,r){return o(n,r),e.has(n)||e.set(n,new Set),e.get(n).add(r),()=>this.off(n,r)},off(n,r){e.get(n)?.delete(r)},has(n){return typeof t()?.[c(n)]=="function"||(e.get(n)?.size??0)>0},emit(n,r){const l=[t()?.[c(n)],...e.get(n)??[]];for(const s of l){if(typeof s!="function")continue;let i;try{i=s(r)}catch(a){console.error(a);continue}i===!1&&r?.preventDefault&&r.preventDefault()}return!r?.defaultPrevented},clear(){e.clear()}}}function h(t){let e=!1;return Object.defineProperties(t,{defaultPrevented:{get:()=>e},preventDefault:{value:()=>void(e=!0)}})}const w=t=>({columns:t.map(e=>({field:e.name})),search:"",sort:[],filters:[],groups:[],collapsed:[],total:null}),f=["columns","search","filters","sort","groups","collapsed","collapseLevel","total","totalsRow","filterRow"];function m(t){const e={};for(const o of f)e[o]=JSON.stringify(t?.[o]??null);return e}function b(t,e){return f.filter(o=>t?.[o]!==e[o])}function x(t){if(typeof t=="string")return t;if(!Array.isArray(t)||!t.length)throw new TypeError('A group is named by its values, e.g. ["East"].');return t.map(e=>e==null||e===""?"":String(e).toLowerCase()).join("")}const u=t=>t.split("").length-1;function S(t,e,o,n){const r=Number.isInteger(n)&&u(e)>=n,l=new Set(t??[]);return o===r?l.delete(e):l.add(e),[...l]}function C(t,e){const o=Number.isInteger(t.collapseLevel)&&u(e)>=t.collapseLevel;return(t.collapsed??[]).includes(e)!==o}function E(t,e){const o=new Set(e),n=(t.columns??[]).filter(r=>!r.hidden&&o.has(r.field));return[...n.filter(r=>r.pinned),...n.filter(r=>!r.pinned)].map(r=>r.field)}function v(t,e,o,n){const r={field:e,desc:o===!0};return n?t.some(l=>l.field===e)?t.map(l=>l.field===e?r:l):[...t,r]:[r]}export{d as GRID_EVENTS,f as STATE_KEYS,h as cancellable,b as changedKeys,g as createEmitter,w as defaultState,E as displayOrder,x as groupPath,C as isCollapsed,c as optionName,u as pathLevel,v as sortWith,m as stateSnapshot,S as toggleCollapsed};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Workbook as g}from"../core/workbook.js";import{BOOL as C,ERR as k,NUM as v,STR as b}from"../core/sheet.js";import{Engine as R}from"../calc/engine.js";import{readCsv as S,CsvWriter as B}from"../io/csv.js";import{buildBlock as T,newBlockBuffers as N}from"../io/export-blocks.js";import{buildPlan as O}from"../io/plan.js";import{writeXlsx as $}from"../io/xlsx-write.js";import{MAX_ROWS as z,MAX_COLS as I,colIndex as x}from"../core/address.js";import{display as P}from"./model.js";async function J(u,h={},i){if(/\.(?:csv|tsv|txt)$/i.test(u.name)){const e=new g;let n=0;const l={size:u.size,slice:(...a)=>u.slice(...a),stream:()=>u.stream().pipeThrough(new TransformStream({transform(a,d){n+=a.byteLength,d.enqueue(a)}}))};return await S(l,{onProgress:a=>i?.({records:Math.max(0,a-1),loaded:n,total:u.size}),delimiter:h.delimiter||(/\.tsv$/i.test(u.name)?" ":void 0),textColumns:new Set(h.textColumns),preserveIdentifiers:!0,addString:a=>e.strings.add(a),styleFor:a=>e.styles.derive(0,{numFmt:a}),onBatch:a=>e.sheet.applyBatch(a)}),{book:e,tables:[]}}const{IoClient:o}=await import("../io/client.js"),m=new o;try{const e=i?await X(u):null,n=await m.open(u,{onProgress:({cells:s})=>i?.({records:e?.columns?Math.floor(s/e.columns):null,loaded:s,total:e?.cells??null})}),{tables:l=[],names:a=[],fullCalcOnLoad:d,manualCalc:t}=m.meta;n.engine=new R(n),n.engine.manual=t,n.engine.setNames(a),n.engine.setTables(l.map(s=>({...s,sheet:n.sheets[s.sheetIndex]}))),n.engine.buildGraph({fullCalc:d}),t||await n.engine.whenIdle();const{openZip:r}=await import("../io/zip-reader.js"),c=await r(await m.packageOf(u));if([...c.entries.keys()].some(s=>s.startsWith("customXml/"))){const{DataSheets:s}=await import("../datasheets/manager.js"),p=new s(n);if(await p.load(c))for(const f of p.manager.tables.values())f.autoSync=!1,f.remote=null}return{book:n,tables:l}}finally{m.close()}}async function X(u){try{const{openZip:h}=await import("../io/zip-reader.js"),i=await h(u);let o=0,m=0,e=0;for(const n of i.entries.keys()){if(!/^xl\/worksheets\/[^/]+\.xml$/.test(n))continue;const l=(await i.stream(n)).pipeThrough(new TextDecoderStream).getReader();let a="";for(;a.length<4096&&!/<(?:\w+:)?sheetData/.test(a);){const{done:c,value:s}=await l.read();if(c)break;a+=s}l.cancel().catch(()=>{});const d=a.match(/<(?:\w+:)?dimension\s+ref="\$?([A-Z]+)\$?(\d+)(?::\$?([A-Z]+)\$?(\d+))?"/);if(!d)return null;const t=d[3]?x(d[3])-x(d[1])+1:1,r=d[4]?Number(d[4])-Number(d[2])+1:1;o+=t*r,t*r>e&&(e=t*r,m=t)}return o>1?{cells:o,columns:m}:null}catch{return null}}function q({book:u,tables:h}){const i=[];return u.sheets.forEach((o,m)=>{if(!(o.hidden||o.isChartSheet)){if(o.kindName==="table"){const e=o.view.spec,n=o.table.byName,l=t=>t.filter(r=>n.has(r.field)),a=l(e.columns).map(({field:t,caption:r,hidden:c,pinned:s,format:p})=>({field:t,caption:r,hidden:c,pinned:s,format:p})),d=a.some(t=>!t.hidden)?{columns:a,search:e.search,sort:l(e.sort),filters:l(e.filters),groups:l(e.groups).map(({field:t})=>({field:t})),total:l(e.totals)[0]??null,collapsed:[...o.view.collapsedPaths]}:null;i.push({name:o.name,sheet:m,native:!0,initialState:d,range:{r0:0,c0:0,r1:o.maxRow,c1:o.maxCol}});return}for(const e of h.filter(n=>n.sheetIndex===m))i.push({name:e.name,sheet:m,headers:e.columns,headerRows:e.headerRows,range:{r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1}});o.maxCol>=0&&o.maxRow>=0&&i.push({name:o.name,sheet:m,whole:!0,range:{r0:0,c0:0,r1:o.maxRow,c1:o.maxCol}})}}),i.sort((o,m)=>+!!o.whole-+!!m.whole)}async function G(u,h){const{view:i}=u;i.refresh();const o=i.columns,m=[],e={write:t=>{m.push(new Blob([t]))}};if(h==="csv"){const t=new B(e,",",{bom:!0});await t.batch(o.map((c,s)=>[0,s,c.caption]));let r=[];for(let c=0;c<i.filteredCount;c++)for(let s=0;s<o.length;s++){const p=o[s];r.push([c+1,s,P(p.col.get(i.perm[c]),p.format)]),r.length===2048&&(await t.batch(r),r=[])}return await t.batch(r),await t.finish(i.filteredCount),new Blob(m,{type:"text/csv;charset=utf-8"})}if(!["xlsx","pdf"].includes(h)||i.filteredCount>=z||o.length>I)throw new Error("The result exceeds the XLSX row limit or the format is unsupported.");const n=new g,l=n.sheet;if(l.name="Results",o.forEach((t,r)=>{l.setCell(0,r,b,n.strings.add(t.caption));const c=n.styles.derive(0,{numFmt:t.format});for(let s=0;s<i.filteredCount;s++){const p=i.perm[s],f=t.col.kind(p);if(!f)continue;const w=t.col.get(p),y=f===b?n.strings.add(w):f===C?Number(w):f===k?w.index:w;l.setCell(s+1,r,f,y),c&&f===v&&l.setStyle(s+1,r,c)}}),h==="pdf"){const{createPrintJob:t}=await import("../print/paginate.js"),{writeJobPdf:r}=await import("../print/render-page.js"),c=(await import("../print/page-setup.js")).getPageSetup(l);return c.fitToPage=!0,c.fitToWidth=1,c.fitToHeight=0,await r(t(n,{sheets:[0]}),e,{title:"Results"}),new Blob(m,{type:"application/pdf"})}const a=O(n,{strings:0,styles:0,sheets:0}),d=N();return await $(e,a,{block:(t,r)=>T(l,n.strings,r,d)}),new Blob(m,{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})}export{G as exportResults,J as openFile,q as sourcesOf};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{parseTsv as V,quoteTsv as W}from"../core/tsv.js";import{formatNumber as X}from"../core/numfmt.js";import{canEdit as Y,startCellEdit as Z}from"./cell-editor.js";import{cancellable as B}from"./events.js";const H=(o,s)=>o.row===s.row&&o.col===s.col;function U(o){const s=o?.closest?.("td"),r=s?.parentElement?.dataset.recordIndex;if(r==null)return null;const d=s.closest("table")?.columnAt?.[s.cellIndex];return d==null||d<0?null:{row:Number(r),col:d}}function et(o,s,r){if(!r.length||!r[0].length)return;let d={row:0,col:0},l=d;const L=new Set,J=t=>({row:Math.max(0,Math.min(r.length-1,t.row)),col:Math.max(0,Math.min(r[0].length-1,t.col))});function D(){return{top:Math.min(d.row,l.row),bottom:Math.max(d.row,l.row),left:Math.min(d.col,l.col),right:Math.max(d.col,l.col)}}function g(t,e,n,a=!1){if(n&&!e&&o.virtual&&(t.row<0||t.row>=r.length)&&i.length){const c=t.row<0?0:r.length-1,f=t.row-c,x=o.focusAfter;if(x?.view!=null)x.view+=f;else{const y=o.result;o.focusAfter={view:y.offset+y.rows.indexOf(i[c])+f,col:l.col}}o.content.scrollTop+=f*o.stride;return}const u=J(t);if(!r[u.row][u.col]&&!(e&&!n)){if(!n||!o.revealColumn)return;o.focusAfter={id:i[u.row].id,col:u.col,step:{row:0,col:0}},o.revealColumn(u.col);return}l=u,e||(d=l);for(const c of L)c.classList.remove("tv-selected");L.clear();const{top:m,bottom:E,left:v,right:h}=D();let w=0,C=0,I=-1;for(let c=m;c<=E;c++)for(let f=v;f<=h;f++){const x=r[c][f],y=i[c].raw?.[f];Number.isFinite(y)&&(w++,C+=y,I<0&&(I=f)),x&&(L.add(x),x.classList.add("tv-selected"))}const j=(E-m+1)*(h-v+1),F=o.result.columns;o.setRange({anchor:{id:i[d.row].id,field:F[d.col]},focus:{id:i[l.row].id,field:F[l.col]}});const{t:K}=o,G=o.result.columns[I],M=o.columnIndex?.get(G)?.format??o.fieldIndex?.get(G)?.format,q=c=>X(M&&M!=="General"?M:Number.isInteger(c)?"#,##0":"#,##0.########",c);let z=K("Selected cells")+" "+j;if(w&&(z+=" · "+K("Sum")+" "+q(C)+" · "+K("Average")+" "+q(C/w)),o.selectionSummary.textContent=j>1?z:"",n){const c=r[l.row][l.col];b!==c&&b?.removeAttribute("tabindex"),b=c,c.tabIndex=0,c.focus({preventScroll:a})}}let b=null;const A=r[0].findIndex(Boolean);if(A<0)return;d=l={row:0,col:A},b=r[0][A],b.tabIndex=0;const i=o.result.rows.filter(t=>t.group===void 0&&!t.loading),p=U;s.addEventListener("pointerdown",t=>{const e=p(t.target);e&&t.button===0&&g(e,t.shiftKey,!0)});function N(){const{top:t,bottom:e,left:n,right:a}=D(),u=[];for(let m=t;m<=e;m++)u.push(i[m].values.slice(n,a+1).map(W).join(" "));return u.join(`\r
|
|
2
|
+
`)}function S(t="user"){const{top:e,bottom:n,left:a,right:u}=D(),m=o.result.columns,E=i[e],v=[];for(let h=e+1;h<=n;h++)for(let w=a;w<=u;w++)v.push({id:i[h].id,field:m[w],value:E.raw[w]});return v.length?o.change("edit",{cells:v},t):Promise.resolve(!1)}function Q(t,e){const n=i.findIndex(u=>u.id===t),a=o.result.columns.indexOf(e);return n<0||a<0?null:{row:n,col:a}}const O={focus:t=>t&&g({row:l.row+t.row,col:l.col+t.col},!1,!0),focusAt:(t,e,n)=>g({row:t,col:e},!1,!0,n),select(t,e,n){g(t,!1,!1),(n||!H(t,e))&&g(e,!0,n,!0)},rectangle:D,focused(){const t=U(document.activeElement);return t&&i[t.row]?{id:i[t.row].id,field:o.result.columns[t.col]}:null},copyText:N,fillDown:S,positionOf:Q,edit:(t,e)=>k(t,e),records:i,cells:r},k=(t,e)=>!!r[t.row][t.col]&&Z(o,r[t.row][t.col],i[t.row],t.col,e,O),P=t=>t.closest?.("button, input, select, textarea, a, .tv-detail"),T=t=>{const e=t.closest?.("tr")?.dataset.recordIndex;return e==null?null:i[Number(e)]},R=(t,e,n)=>({id:t.id,field:o.result.columns[e.col],text:t.values[e.col]??"",value:t.raw?.[e.col]??null,event:n});return s.addEventListener("click",t=>{const e=P(t.target)?null:T(t.target);if(!e)return;const n=p(t.target);n&&o.emit("cellClick",R(e,n,t)),o.emit("rowClick",{id:e.id,field:n?o.result.columns[n.col]:null,event:t})}),s.addEventListener("dblclick",t=>{const e=P(t.target)?null:T(t.target);if(!e)return;const n=p(t.target);let a=!0;if(n&&(a=o.emit("cellDoubleClick",B(R(e,n,t)))),a=o.emit("rowDoubleClick",B({id:e.id,field:n?o.result.columns[n.col]:null,event:t}))&&a,!a){t.stopPropagation(),t.preventDefault();return}n&&Y(o,o.result.columns[n.col])&&k(n)&&t.stopPropagation()},!0),s.addEventListener("pointerover",t=>{const e=p(t.target);e&&t.buttons===1&&!H(e,l)&&g(e,!0,!1)}),s.addEventListener("copy",t=>{p(t.target)&&(t.clipboardData.setData("text/plain",N()),t.preventDefault())}),s.addEventListener("paste",t=>{if(!o.editable||!p(t.target))return;t.preventDefault();const e=V(t.clipboardData.getData("text/plain"));o.perform(()=>o.change("paste",{id:i[l.row].id,field:o.result.columns[l.col],lines:e,repeat:1}))}),s.addEventListener("keydown",t=>{if(!p(t.target))return;const e=t.ctrlKey||t.metaKey;if(e&&o.editable&&!o.remote&&["z","y","d"].includes(t.key.toLowerCase())){t.preventDefault(),t.key.toLowerCase()==="d"?o.perform(()=>S()):o.perform(()=>o.change(t.shiftKey||t.key.toLowerCase()==="y"?"redo":"undo"));return}const n={...l};switch(t.key){case"ArrowLeft":n.col--;break;case"ArrowRight":n.col++;break;case"ArrowUp":n.row--;break;case"ArrowDown":n.row++;break;case"Home":n.col=0,e&&(n.row=0);break;case"End":n.col=r[0].length-1,e&&(n.row=r.length-1);break;case" ":if(!o.selection||e)return;t.preventDefault(),o.toggleRecord(i[n.row]);return;case"Enter":case"F2":if(t.preventDefault(),!t.shiftKey&&k(n))return;o.perform(()=>o.details(i[n.row]));return;default:t.key.length===1&&!e&&!t.altKey&&k(n,t.key)&&t.preventDefault();return}t.preventDefault(),g(n,t.shiftKey,!0)}),O}export{U as cellPosition,et as enableGridKeys};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{remoteTableSource as m}from"./remote.js";import{VERSION as i}from"./version.js";async function a(t,e={}){return(await(await import("./mount.js")).mountTable(t,e)).api}export{i as VERSION,a as mountTable,m as remoteTableSource};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o={"Autosize column":"Dopasuj szerokość","Drag to resize, double-click to fit":"Przeciągnij, aby zmienić szerokość; kliknij dwukrotnie, aby dopasować",Dismiss:"Zamknij podpowiedź","Filter row":"Wiersz filtrów","Clear column filters":"Wyczyść filtry kolumn","Greater than or equal":"Większe lub równe","Less than or equal":"Mniejsze lub równe","Open a row with its arrow to see the order lines. One order opens at a time and scrolls with the records.":"Rozwiń wiersz strzałką, aby zobaczyć pozycje zamówienia. Naraz otwarte jest jedno zamówienie, które przewija się razem z rekordami.","Tick rows, or the header box for every match. Drag across cells and press Ctrl+C to copy them. Export offers the selected rows.":"Zaznacz wiersze lub pole w nagłówku, aby wybrać wszystkie pasujące. Przeciągnij po komórkach i naciśnij Ctrl+C, aby je skopiować. Eksport obejmie zaznaczone wiersze.",Quantity:"Ilość",Price:"Cena",Amount:"Kwota",Total:"Razem","Order lines":"Pozycje zamówienia","Order no.":"Zamówienie nr",Product:"Produkt","Expand details":"Rozwiń szczegóły","Collapse details":"Zwiń szczegóły","Conditional formatting":"Formatowanie warunkowe","Data bar":"Pasek danych","Colour scale":"Skala kolorów","Green fill":"Zielone tło","Red fill":"Czerwone tło","Amber fill":"Bursztynowe tło","Blue fill":"Niebieskie tło","Bold text":"Pogrubiony tekst",Custom:"Własny","No rules":"Brak reguł",Style:"Styl",Rule:"Reguła","Add rule":"Dodaj regułę","Clear rules":"Usuń reguły","Drag a header edge to resize it and double-click to fit, drag a header to move it. Bars, colour scales and the totals row cover every matching record.":"Przeciągnij krawędź nagłówka, aby zmienić szerokość, kliknij dwukrotnie, aby dopasować, przeciągnij nagłówek, aby przenieść kolumnę. Paski, skale kolorów i wiersz sum obejmują wszystkie pasujące rekordy.",Totals:"Sumy","No total":"Bez podsumowania","Select all matching records":"Zaznacz wszystkie pasujące rekordy","Select record":"Zaznacz rekord",selected:"zaznaczonych","All matching selected":"Zaznaczono wszystkie pasujące","All matching selected except":"Zaznaczono wszystkie pasujące oprócz","Clear selection":"Wyczyść zaznaczenie","All matching records":"Wszystkie pasujące rekordy","Selected records":"Zaznaczone rekordy",Records:"Rekordy","Select records to export first.":"Najpierw zaznacz rekordy do eksportu.","This source cannot export selected records.":"To źródło nie eksportuje zaznaczonych rekordów.","Row selection is off for this table.":"Zaznaczanie wierszy jest wyłączone w tej tabeli.","Wait for the records to load.":"Poczekaj na wczytanie rekordów.","Search “East”, open a column menu to sort, filter, group or pin, and select cells to see their sum.":"Wyszukaj „East”, otwórz menu kolumny, aby sortować, filtrować, grupować lub przypinać, i zaznacz komórki, aby zobaczyć ich sumę.","One million orders generated off the main thread. Type “>30” under Units or a name under Customer, sort or group: the work runs in a Worker.":"Milion zamówień wygenerowanych poza wątkiem głównym. Wpisz „>30” pod Units lub nazwę pod Customer, sortuj lub grupuj: obliczenia działają w Workerze.","Rows arrive in blocks of 100 from a simulated server with 150–400 ms latency and an unknown total. Scroll quickly, then sort or search.":"Wiersze przychodzą blokami po 100 z symulowanego serwera z opóźnieniem 150–400 ms i nieznaną liczbą rekordów. Przewiń szybko, potem posortuj lub wyszukaj.","An editable copy: double-click a cell or press Enter to edit, Ctrl+Z to undo. Units must be a whole number from 1 to 500.":"Edytowalna kopia: kliknij komórkę dwukrotnie lub naciśnij Enter, aby edytować, Ctrl+Z cofa. Units musi być liczbą całkowitą od 1 do 500.","The sales records as a pivot by region and product, with its chart. Choose Back to records to return.":"Sprzedaż jako tabela przestawna według regionu i produktu, z wykresem. Wybierz Wróć do rekordów, aby wrócić.","Choose East, West, North or South.":"Wybierz East, West, North lub South.","Units must be a whole number from 1 to 500.":"Units musi być liczbą całkowitą od 1 do 500.","Shift-click to sort by another column":"Shift + kliknięcie dodaje kolumnę do sortowania","Selected cells":"Zaznaczone komórki","System theme":"Motyw systemowy","Light theme":"Motyw jasny","Dark theme":"Motyw ciemny","Custom theme":"Motyw własny",Theme:"Motyw","Column menu":"Menu kolumny","Sort ascending":"Sortuj rosnąco","Sort descending":"Sortuj malejąco","Clear sort":"Usuń sortowanie","Hide column":"Ukryj kolumnę","is one of":"jest jednym z","Clear all":"Wyczyść wszystko",Unpin:"Odepnij",Ungroup:"Usuń grupowanie","The data changed. Reopen the record before editing.":"Dane się zmieniły. Otwórz rekord ponownie przed edycją.",Rows:"Wiersze",Chart:"Wykres",Pivot:"Tabela przestawna","Back to records":"Wróć do rekordów","Top 20 by absolute value":"Pierwsze 20 według wartości bezwzględnej","Choose different row and column fields.":"Wybierz różne pola dla wierszy i kolumn.","Pick values":"Wybierz wartości","No values":"Brak wartości","Back to workbook":"Wróć do arkusza","Read columns as text":"Wczytaj kolumny jako tekst",Delimiter:"Separator",Automatic:"Automatycznie","Reimport CSV":"Wczytaj CSV ponownie","Add record":"Dodaj rekord","Remove record":"Usuń rekord",Width:"Szerokość",Share:"Udostępnij","Share link":"Link do widoku","Copy link":"Kopiuj link","Revoke link":"Unieważnij link","Publish filtered copy":"Opublikuj przefiltrowaną kopię","Prepare file":"Przygotuj plik","This share link has expired or was revoked.":"Link wygasł lub został unieważniony.",Pages:"Strony",Scroll:"Przewijanie","Table view":"Widok tabeli","Open file":"Otwórz plik","Open workbook":"Otwórz arkusz","Sales example":"Przykład sprzedaży","Open a table":"Otwórz tabelę","Choose a CSV or Excel file to explore its records.":"Wybierz plik CSV lub Excel, aby przeglądać rekordy.","Search records":"Szukaj rekordów",Filter:"Filtr",Group:"Grupowanie",Columns:"Kolumny",Views:"Widoki",Export:"Eksport",Sort:"Sortowanie",Apply:"Zastosuj",Cancel:"Anuluj",Close:"Zamknij",Field:"Pole",Condition:"Warunek",Value:"Wartość",Contains:"Zawiera",Equals:"Równa się","Greater than":"Większe niż","Less than":"Mniejsze niż","Is blank":"Puste","Starts with":"Zaczyna się od","Not equal":"Różne od",Between:"Pomiędzy","Second value":"Druga wartość","Is not blank":"Niepuste",Ascending:"Rosnąco",Descending:"Malejąco",Remove:"Usuń","Reset view":"Resetuj widok",None:"Brak",Summary:"Podsumowanie",Sum:"Suma",Average:"Średnia",Minimum:"Minimum",Maximum:"Maksimum",Count:"Liczba",Distinct:"Unikatowe",Visible:"Widoczna",Pin:"Przypnij","Move up":"Przesuń wyżej","Move down":"Przesuń niżej","Save view":"Zapisz widok","View name":"Nazwa widoku",Restore:"Przywróć","Record details":"Szczegóły rekordu",Details:"Szczegóły",Previous:"Poprzednia",Next:"Następna",Page:"Strona",of:"z",records:"rekordów","Export results":"Eksportuj wyniki","No matching records":"Brak pasujących rekordów","Clear filters":"Wyczyść filtry","Loading…":"Wczytywanie…","A new version of 8sheets is ready.":"Nowa wersja 8sheets jest gotowa.",Reload:"Wczytaj ponownie",Later:"Później","Reload and lose your unsaved edits?":"Wczytać ponownie i utracić niezapisane zmiany?","8sheets was updated in another tab. Save your work, then reload to use the new version.":"Aplikacja 8sheets została zaktualizowana w innej karcie. Zapisz pracę, a potem wczytaj stronę ponownie, aby użyć nowej wersji.",Opening:"Otwieranie:","Preparing records":"Przygotowywanie rekordów","Loading records":"Wczytywanie rekordów","Building pivot":"Tworzenie tabeli przestawnej","Generating records":"Generowanie rekordów","Records read":"Wczytane rekordy","Cancelling…":"Anulowanie…","Loading cancelled.":"Wczytywanie anulowane.",Loaded:"Wczytano","No data":"Brak danych",Table:"Tabela",Source:"Źródło",Range:"Zakres","First row contains headers":"Nagłówki w pierwszym wierszu","Edit copy":"Edytuj kopię","Editing copy":"Edycja kopii","Save changes":"Zapisz zmiany",Undo:"Cofnij",Redo:"Ponów","Calculated field":"Pole obliczane",Formula:"Formuła",Name:"Nazwa",Add:"Dodaj","Group by":"Grupuj według","Sort by":"Sortuj według","Add group":"Dodaj grupę","Add sort":"Dodaj sortowanie",Order:"Kolejność","Use Tab to separate fields and a new line for each record.":"Rozdziel pola tabulatorem, a rekordy nową linią.","Paste rows":"Wklej wiersze","Starting field":"Pole początkowe","Changes live in this copy until exported.":"Zmiany pozostają w kopii do czasu eksportu.","Choose at least one visible column.":"Wybierz przynajmniej jedną widoczną kolumnę.","No saved views":"Brak zapisanych widoków","Rows per page":"Wierszy na stronę","Choose source":"Wybierz źródło",Format:"Format","Copy row":"Kopiuj wiersz",Copied:"Skopiowano",Download:"Pobierz","Local file":"Plik lokalny","View settings":"Ustawienia widoku","Saved views":"Zapisane widoki","Paste exceeds the available records or columns.":"Wklejane dane wykraczają poza dostępne rekordy lub kolumny.","Editing is disabled for this view.":"Edycja tego widoku jest wyłączona.","Save or discard your local edits before replacing this table. Continue?":"Zastąpienie tabeli odrzuci lokalne zmiany. Kontynuować?","Select a value":"Wybierz wartość","No table loaded":"Nie wczytano tabeli",Filters:"Filtry",Print:"Drukuj","Fill down":"Wypełnij w dół","Number of records":"Liczba rekordów","Original workbook":"Oryginalny skoroszyt",Edit:"Edytuj",Reset:"Resetuj",Saved:"Zapisano","Choose a range inside the source.":"Wybierz zakres w obrębie źródła.","Choose an unused column name and a formula.":"Wpisz nieużywaną nazwę kolumny oraz formułę.","This view is read-only.":"Widok tylko do odczytu.","This file contains no visible data.":"Plik nie zawiera widocznych danych.","This field is read-only.":"Pole tylko do odczytu.","Field unavailable.":"Pole jest niedostępne.","Record unavailable.":"Rekord jest niedostępny.","Invalid column.":"Nieprawidłowa kolumna.","This source is read-only.":"To źródło jest tylko do odczytu.","This field or record is read-only.":"To pole lub rekord jest tylko do odczytu.","Use the record editor for this source.":"W tym źródle zmieniaj dane w szczegółach rekordu.","The selection changed. Open Table view again.":"Zaznaczenie się zmieniło. Otwórz widok tabeli ponownie.","The result exceeds the XLSX row limit or the format is unsupported.":"Wynik przekracza limit wierszy XLSX albo ten format nie jest obsługiwany.","The pivot exceeds the worksheet dimensions.":"Tabela przestawna nie mieści się w arkuszu.","File sharing is unavailable on this device.":"Udostępnianie plików nie działa na tym urządzeniu.","Allow opening the workbook in a new tab.":"Zezwól na otwarcie arkusza w nowej karcie.","The example could not be opened.":"Nie udało się otworzyć przykładu.","Invalid snapshot address.":"Nieprawidłowy adres kopii.","Invalid table response.":"Nieprawidłowa odpowiedź źródła tabeli.","Table view closed.":"Widok tabeli został zamknięty."},r=o,i=a=>e=>a?.startsWith("pl")?o[e]??e:e;export{r as PL,i as translator};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{TableView as y,aggregate as g,STAGE as w}from"../datasheets/view.js";import{formatNumber as R}from"../core/numfmt.js";import{checkValidator as E}from"../datasheets/remote.js";import{columnExtras as C}from"./totals.js";function p(u,e){return u==null?"":typeof u=="number"?Number.isFinite(u)?R(e||"General",u):"":String(u)}class F{constructor(e,o=!1){this.table=e,this.editable=o,this.view=new y(e),this.undo=[],this.redo=[],this.total=null}get fields(){return this.table.fields.map(e=>({name:e.name,caption:e.caption,type:e.type,format:e.format,editable:this.editable&&!e.computed&&!e.readOnly}))}apply(e){const o=this.table.byName,r=e.columns.filter(i=>o.has(i.field));if(o.size&&!r.some(i=>!i.hidden))throw new Error("Choose at least one visible column.");const{view:s}=this,t=e.total&&o.has(e.total.field)?e.total:null,l=e.groups.filter(i=>o.has(i.field)).map(i=>({field:i.field,desc:i.desc===!0,summaries:t?[t]:[]}));s.restore({spec:{...s.spec,columns:r,groups:l,search:e.search,filters:e.filters.filter(i=>o.has(i.field)).map(i=>{const n=o.get(i.field);return!["equal","notEqual","gt","gte","lt","lte","between","notBetween"].includes(i.op)||!["date","boolean"].includes(n.type)?i:{...i,value:n.coerce(i.value),value2:i.op==="between"||i.op==="notBetween"?n.coerce(i.value2):void 0}}),sort:e.sort.filter(i=>o.has(i.field))},collapsedPaths:e.collapsed??[],collapseFromLevel:Number.isInteger(e.collapseLevel)&&e.collapseLevel>=0?e.collapseLevel:1/0,treeCollapsed:[]}),this.total=t,this.layout=r,this.totalsRow=e.totalsRow===!0}page(e,o,r=0,s=32){const{view:t,table:l,total:i}=this;t.refresh(),e=Math.min(Math.max(0,e),Math.max(0,Math.floor((t.count-1)/o)*o));const n=[],c=t.columns.length;r=Math.min(r,Math.max(0,Math.floor((c-1)/s)*s));const f=t.columns.slice(r,r+s);for(let d=e;d<Math.min(t.count,e+o);d++){const a=t.rowInfo(d);if(a.kind==="record"){const m=f.map(h=>h.col.get(a.record));n.push({id:a.record,raw:this.editable?m:m.map(h=>typeof h=="number"?h:null),values:f.map((h,b)=>p(m[b],h.format))})}else{const m=i?p(t.summaryFor(a.node,i.field),this.summaryFormat()):"";n.push({path:t._nodePath(a.node),group:t.groupCaption(a.node),index:d,collapsed:a.collapsed,level:a.level,summary:m})}}(this.summaryRevision!==t.revision||this.summaryTableRevision!==l.revision)&&(this.summary=i?g(l.column(i.field),i.agg,t.perm,0,t.filteredCount):null,this.summaryRevision=t.revision,this.summaryTableRevision=l.revision);const v=this.summary;return{rows:n,offset:e,columnOffset:r,columnCount:c,count:t.count,matches:t.filteredCount,sourceCount:l.liveCount,summary:p(v,this.summaryFormat()),columns:f.map(d=>d.field),collapsed:[...t.collapsedPaths],canUndo:this.undo.length>0,canRedo:this.redo.length>0,...C(this,f,this.layout,this.totalsRow)}}summaryFormat(){return this.total&&!["count","countAll","distinct"].includes(this.total.agg)?this.table.column(this.total.field).format:"General"}record(e){const o=this.table;if(!Number.isInteger(e)||e<0||e>=o.rowCount||!o.alive[e])throw new Error("Record unavailable.");const r={},s={};for(const t of o.fields){const l=t.get(e);s[t.name]=l==null||["number","string","boolean"].includes(typeof l)?l??null:l.code??String(l),r[t.name]=p(l,t.format)}return{id:e,values:r,raw:s}}records(e,o){const r=this.view;r.refresh();const s=r.filteredCount,t=[];for(let l=Math.max(0,e);l<Math.min(s,e+o);l++)t.push(this.record(r.perm[l]));return{total:s,records:t}}rowActions(e){const o=[];try{for(const r of e)o.push(this.rowAction(r))}catch(r){for(const s of o.reverse())this.rowAction(s);throw r}return o.length===1?o[0]:{kind:"batch",actions:o.reverse()}}rowAction(e){if(!this.editable)throw new Error("This view is read-only.");if(e.kind==="batch")return this.rowActions(e.actions);if(this.view.invalidate(w.FILTER),e.kind==="add"){const o=Object.create(null);for(const r of this.table.fields){if(r.computed)continue;const s=e.values[r.name];if(r.readOnly&&s!=null)throw new Error("This field is read-only.");const t=r.coerce(s??r.defaultValue);if(r.required&&(t==null||t===""))throw new Error(r.caption+" is required.");if(r.validator){const l=E(r,t,this.table.rowCount);if(l)throw new Error(l)}o[r.name]=t}return{kind:"remove",id:this.table.addRow(o)}}if(!Number.isSafeInteger(e.id)||e.id<0||e.id>=this.table.rowCount)throw new Error("Record unavailable.");if(e.kind==="restore")return this.table.restoreRow(e.id),{kind:"remove",id:e.id};if(!this.table.alive[e.id])throw new Error("Record unavailable.");return this.table.removeRow(e.id),{kind:"restore",id:e.id}}edit(e,o=!1){if(!this.editable)throw new Error("This view is read-only.");const r=[];try{for(const{id:s,field:t,value:l}of e){if(!Number.isInteger(s)||!this.table.alive[s])throw new Error("Record unavailable.");const i=this.table.column(t);if(!i||!o&&!this.view.columns.some(c=>c.field===t&&!c.readOnly))throw new Error("This field is read-only.");const n=i.get(s);this.table.set(s,t,l)&&r.push({id:s,field:t,value:n})}}catch(s){for(const t of r.reverse())this.table.set(t.id,t.field,t.value);throw s}return r.length&&this.view.invalidate(w.FILTER),r.reverse()}}export{F as Reader,p as display};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{parseTsv as yt}from"../core/tsv.js";import{cellPosition as xt,enableGridKeys as St}from"./grid-keys.js";import{packRecords as Ct}from"./column-input.js";import{applyTableChrome as kt,readTableChrome as Nt,saveTableChrome as Rt}from"./chrome.js";import{TableClient as lt}from"./client.js";import{BlockCache as At}from"./row-cache.js";import{enableColumnDrag as Tt,fitWidth as Et,sizeCell as G}from"./column-drag.js";import{RowSelection as at}from"./row-selection.js";import{cellFormat as rt,paintCell as ct,rangeOf as Lt}from"./cell-format.js";import{parseQuickFilter as Mt}from"./quick-filter.js";import{columnWindow as Ot,columnsStale as qt,measureColumns as Ft,revealColumn as ht,widenColumns as Dt}from"./column-window.js";import{translator as dt}from"./labels.js";import{button as q,el as c,icon as _,iconButton as j,labeled as v,menu as ut,modal as T,select as k}from"./panel.js";import{rangeRef as J,colIndex as ft,colName as It}from"../core/address.js";import{usualLanguage as pt}from"../i18n/index.js";import{formatNumber as Pt}from"../core/numfmt.js";import Kt from"./table-css.js";import{cancellable as Bt,changedKeys as zt,createEmitter as Wt,defaultState as Ht,stateSnapshot as Vt}from"./events.js";import{DataGridApi as jt}from"./api.js";const mt=[["contains","Contains"],["equal","Equals"],["notEqual","Not equal"],["beginsWith","Starts with"],["gt","Greater than"],["lt","Less than"],["gte","Greater than or equal"],["lte","Less than or equal"],["between","Between"],["blank","Is blank"],["notBlank","Is not blank"]],U=[["sum","Sum"],["average","Average"],["min","Minimum"],["max","Maximum"],["count","Count"],["distinct","Distinct"]],Y=Ht,W=()=>new DOMException("The load was cancelled.","AbortError"),Jt=150,Z=8,gt=H=>({...H,columns:H.columns.map(({width:t,rules:e,...s})=>({...s,ranged:!!e?.some(i=>i?.type==="bar"||i?.type==="scale")})),filterRow:void 0});async function ue(H,t={}){const e=new Ut(H,t);try{return t.file?await e.openFile(t.file):t.dataSource?await e.openRemote():t.data&&await e.openData(t.data),e}catch(s){throw e.destroy(),s}}class Ut{constructor(t,e){this.options={...e},delete this.options.data,this.events=Wt(()=>this.options),this.api=new jt(this),this.language=e.language||pt(),this.t=dt(this.language),this.root=c("section",null,{className:"tv-root",lang:this.language});for(const o of["copy","cut","paste"])this.root.addEventListener(o,l=>l.stopPropagation());this.setChrome(e.chrome??(e.standalone?Nt():"auto")),this.root.append(c("style",Kt)),t.replaceChildren(this.root),this.sequence=0,this.loadToken=0,this.liveWidths=new Map,this.selection=e.rowSelection?new at(e.rowSelection):null,this.selectionStatus=c("span",null,{className:"tv-selection-status"}),this.continuous=e.scrolling!=="pages",this.limit=50,this.offset=0,this.columnOffset=0,this.columnLimit=32,this.header=c("header",null,{className:"tv-head"});const s=c("div",null,{className:"tv-identity"}),i=c("span","8",{className:"tv-mark"});i.setAttribute("aria-hidden","true"),this.title=c("h1","Data Grid"),s.append(i,this.title),this.headActions=c("div",null,{className:"tv-actions"}),this.header.append(s,this.headActions),this.fileInput=c("input",null,{type:"file",accept:".csv,.tsv,.txt,.xlsx,.xlsm,.xltx",hidden:!0}),this.fileInput.onchange=()=>this.perform(async()=>{const o=this.fileInput.files[0];this.fileInput.value="",o&&(!this.dirty||confirm(this.t("Save or discard your local edits before replacing this table. Continue?")))&&await this.openFile(o)}),this.toolbar=c("div",null,{className:"tv-tools"}),this.chips=c("div",null,{className:"tv-chips"}),this.content=c("div",null,{className:"tv-data"}),this.content.addEventListener("scroll",()=>this.scrollWindow(),{passive:!0}),this.resize=new ResizeObserver(()=>{this.scrollWindow(),this.load?.node&&this.placeLoader(this.load.node)}),this.resize.observe(this.content),this.footer=c("footer",null,{className:"tv-foot"}),this.status=c("div",null,{className:"tv-status"}),this.status.setAttribute("role","status"),this.root.append(this.header,this.fileInput,this.toolbar,this.chips,this.content,this.footer,this.status),this.renderHeader(),this.empty()}perform(t){return Promise.resolve().then(t).catch(e=>{this.closed||e.name==="AbortError"||(this.status.textContent=this.t(e.message),this.emit("error",e))})}emit(t,e){return this.closed?!0:this.events.emit(t,e)}sourceKind(){return!this.result&&!this.fields?"none":this.base?"pivot":this.remote?"remote":this.file?"file":"data"}noteState(){const t=Vt(this.state),e=this.committed;if(this.committed=t,!e)return;const s=zt(e,t);s.length&&this.emit("stateChange",{state:this.getState(),changed:s})}noteViewport(){if(!this.result||this.closed||!this.events.has("viewportChange"))return;const t=this.viewport(),e=JSON.stringify(t);e!==this.viewportKey&&(this.viewportKey=e,this.emit("viewportChange",t))}viewport(){const t=this.result,e=this.content.scrollTop,s=this.content.clientHeight;let i,o;if(this.virtual)i=Math.min(t.count-1,Math.floor(e/this.stride)),o=Math.min(t.count-1,Math.floor((e+s)/this.stride));else{const l=this.content.getBoundingClientRect(),n=[...this.content.querySelectorAll("tbody tr[data-view]")].filter(a=>{const r=a.getBoundingClientRect();return r.bottom>l.top&&r.top<l.bottom});i=n.length?Number(n[0].dataset.view):t.offset,o=n.length?Number(n.at(-1).dataset.view):t.offset-1}return{firstRow:Math.max(0,i),lastRow:Math.max(-1,o),rowCount:t.count,exact:t.exact!==!1,scrollTop:e,scrollLeft:this.content.scrollLeft}}action(t,e,s,i=""){const o=q(this.t(e),()=>this.perform(s),i);return t.append(o),o}setChrome(t){kt(this.root,t),this.chrome=t}renderHeader(){const t=this.headActions;if(t.replaceChildren(),this.options.standalone){const e=[["auto",this.t("System theme")],["light",this.t("Light theme")],["dark",this.t("Dark theme")]];e.some(([i])=>i===this.chrome)||e.push(["custom",this.t("Custom theme")]);const s=k(e,e.some(([i])=>i===this.chrome)?this.chrome:"custom");s.setAttribute("aria-label",this.t("Theme")),s.onchange=()=>{s.value!=="custom"&&(this.setChrome(s.value),this.options.rememberChrome&&Rt(s.value))},t.append(s),this.sources?.length&&!this.base&&this.action(t,"Source",()=>this.chooseSource()),this.action(t,"Open file",()=>this.fileInput.click()),this.action(t,this.options.workbookLabel||"Open workbook",()=>this.options.onWorkbook?.(this.file))}this.result&&(this.options.allowEdit&&!this.remote&&!this.editable&&!this.base&&this.action(t,"Edit copy",()=>this.enableEditing()),this.editable&&!this.remote&&(this.action(t,"Undo",()=>this.change("undo")).disabled=!this.result.canUndo,this.action(t,"Redo",()=>this.change("redo")).disabled=!this.result.canRedo),(!this.remote||this.remote.exportResults)&&((this.options.sharing||navigator.canShare)&&this.action(t,"Share",()=>this.shareDialog()),this.action(t,"Export",()=>this.exportDialog(),"tv-primary")))}async enableEditing(){if(!this.editable){if(this.remote)throw new Error("This source is read-only.");if(this.base)throw new Error("A pivot is read-only. Go back to the records first.");if(!this.client||!this.fields)throw new Error("No table loaded.");if(!this.options.allowEdit&&this.options.editable!==!0)throw new Error("Editing is disabled for this view.");this.fields=await this.client.call("enableEdit"),this.editable=!0,this.renderHeader(),this.renderTools(),this.renderRows()}}async track(t,e,s,i){const o=this.load;o&&(o.superseded=!0,this.endLoad(o,"cancelled"));const l={task:t,label:e,cancel:i,cancelled:!1,started:performance.now(),emitted:0,last:null};l.progress=(a,r)=>this.loadProgress(l,a,r),this.load=l,this.content.setAttribute("aria-busy","true"),this.emit("loadStart",{task:t,label:e});const n=performance.now()-(this.loaderHidden??-1/0)<400?0:Jt;l.delay=n,l.timer=setTimeout(()=>this.showLoader(l),n);try{const a=await s(l);if(l.cancelled||l.superseded)throw W();return this.endLoad(l,"done"),a}catch(a){const r=l.cancelled||l.superseded||a?.name==="AbortError";throw this.endLoad(l,r?"cancelled":"failed",r?void 0:a),r?W():a}}loadProgress(t,e,s=!1){if(t.ended)return;t.last=e;const i=performance.now();if(!t.node&&i-t.started>=t.delay&&this.showLoader(t),!s&&i-t.emitted<100)return;t.emitted=i,t.node&&this.paintLoader(t);const{records:o=null,loaded:l=null,total:n=null}=e??{};this.emit("loadProgress",{task:t.task,records:o,loaded:l,total:n,fraction:n?Math.min(1,l/n):null})}endLoad(t,e,s){if(t.ended)return;t.ended=!0,clearTimeout(t.timer),this.load===t&&(this.load=null,this.content.setAttribute("aria-busy","false"));const i=!!t.node;i&&this.hideLoader(t,e==="done"),i&&!this.closed&&!t.superseded&&(this.status.textContent=e==="done"?this.t("Loaded")+" · "+(this.result?this.countText():t.label):e==="cancelled"?this.t("Loading cancelled."):""),this.emit("loadEnd",{task:t.task,label:t.label,status:e,...s&&{error:s},records:e==="done"&&Number.isSafeInteger(this.result?.matches)?this.result.matches:null,duration:Math.round(performance.now()-t.started)})}cancelLoad(){const t=this.load;return!t?.cancel||t.cancelled?!1:(t.cancelled=!0,t.node&&(t.node.querySelector(".tv-loader-title").textContent=this.t("Cancelling…"),t.node.querySelector(".tv-loader-cancel").disabled=!0),t.cancel(),!0)}showLoader(t){if(t.node||t.ended||this.load!==t||this.closed)return;clearTimeout(t.timer);const e=this.t,s=c("div",null,{className:"tv-loader"}),i=c("div",null,{className:"tv-loader-panel"}),o=(this.uid??="tv"+Math.random().toString(36).slice(2,8))+"-loading";i.setAttribute("role","group"),i.setAttribute("aria-labelledby",o);const l=c("span",null,{className:"tv-spinner"});l.setAttribute("aria-hidden","true");const n=c("p",t.label,{className:"tv-loader-title",id:o}),a=c("div",null,{className:"tv-loader-bar"});a.setAttribute("role","progressbar"),a.setAttribute("aria-labelledby",o),a.append(c("span"));const r=c("p","",{className:"tv-loader-detail"});if(i.append(l,n,a,r),t.cancel){const h=q(e("Cancel"),()=>this.cancelLoad(),"tv-loader-cancel");i.append(h)}s.append(i),s.addEventListener("keydown",h=>{h.key==="Escape"&&(h.stopPropagation(),this.cancelLoad())}),this.placeLoader(s),this.root.append(s),t.node=s,this.paintLoader(t),this.status.textContent=t.label+"…";const d=document.activeElement;this.root.contains(d)&&!d.closest("dialog")&&(t.focus=d,s.querySelector(".tv-loader-cancel")?.focus({preventScroll:!0}))}placeLoader(t){t.style.top=this.content.offsetTop+"px",t.style.height=this.content.offsetHeight+"px"}paintLoader(t){const e=t.node,{records:s=null,loaded:i=null,total:o=null}=t.last??{},l=e.querySelector(".tv-loader-bar"),n=o?Math.min(1,i/o):null;l.classList.toggle("tv-indeterminate",n==null),n==null?l.removeAttribute("aria-valuenow"):(l.setAttribute("aria-valuemin","0"),l.setAttribute("aria-valuemax","100"),l.setAttribute("aria-valuenow",String(Math.floor(n*100)))),l.firstChild.style.width=n==null?"":n*100+"%";const a=d=>d.toLocaleString(this.language),r=[];s!=null&&r.push(this.t("Records read")+": "+a(s)),n!=null&&r.push(Math.floor(n*100)+"%"),e.querySelector(".tv-loader-detail").textContent=r.join(" · ")}hideLoader(t,e){t.node.remove(),t.node=null,this.loaderHidden=e?performance.now():null;const s=t.focus;!s||this.root.querySelector("dialog[open]")||(s.isConnected?s.focus({preventScroll:!0}):(this.content.querySelector('td[tabindex="0"]')??this.toolbar.querySelector("input"))?.focus({preventScroll:!0}))}empty(){const t=c("div",null,{className:"tv-empty"});t.append(c("h2",this.t("Open a table")),c("p",this.t("Choose a CSV or Excel file to explore its records."))),this.action(t,"Open file",()=>this.fileInput.click(),"tv-primary"),this.options.example&&this.action(t,"Sales example",()=>this.options.example(this)),this.content.replaceChildren(t)}openFile(t,e={},s=!0){return this.track("file",this.t("Opening")+" "+t.name,i=>this.readFile(t,e,s,i),()=>this.dropPending())}dropPending(){++this.loadToken,this.pendingClient?.close(W()),this.pendingClient=null}async readFile(t,e,s,i){const o=new lt;this.pendingClient?.close(W()),this.pendingClient=o;const l=++this.loadToken;try{const n=await o.call("file",{file:t,csv:e},[],i.progress),a=await o.call("source",{index:0,editable:!1});if(this.closed||l!==this.loadToken)return o.close();this.client?.close(),this.client=o,this.pendingClient=null,this.leaveRemote(),this.file=t,this.csv=e,this.sources=n,this.sourceIndex=0,this.sourceRange=J(n[0].range),this.sourceHeader=n[0].headerRows!==0,this.base=null,this.dirty=!1,this.editable=!1,await this.activate(a,n[0].name,this.fileViewKey(0,J(n[0].range),n[0].headerRows!==0),n[0].initialState),s&&(n.filter(r=>!r.whole).length>1||n.every(r=>r.whole)&&n.length>1)&&this.chooseSource()}catch(n){throw this.client!==o&&o.close(),n}}leaveRemote(){this.remote=null,this.rows?.reset(),this.rows=null}openData(t){return this.track("data",this.t("Preparing records"),e=>this.readData(t,e),()=>this.dropPending())}async readData(t,e){const s=++this.loadToken,i=new lt;this.pendingClient?.close(W()),this.pendingClient=i;const o=this.options.editable===!0;let l,n;try{n=await Ct(t,this.options.fields,()=>this.closed||s!==this.loadToken,(d,h)=>e.progress({records:d,loaded:d,total:h})),n&&(t=n.columns);const a=Array.isArray(t)?t.length:Object.values(t).find(d=>d?.length!=null)?.length;e.progress({records:a??null,loaded:null,total:null},!0);const r=(n||this.options.transferColumns)&&!Array.isArray(t)?[...new Set(Object.values(t).filter(d=>ArrayBuffer.isView(d)&&d.buffer instanceof ArrayBuffer).map(d=>d.buffer))]:[];l=await i.call("data",{data:t,strings:n?.strings,fields:this.options.fields,editable:o},r)}catch(a){throw i.close(),a}if(this.closed||s!==this.loadToken)return i.close();this.client?.close(),this.client=i,this.pendingClient=null,this.leaveRemote(),this.editable=o,this.file=null,this.sources=null,this.base=null,this.dirty=!1,await this.activate(l,this.options.title||this.t("Table"),this.options.storageKey)}openRemote(){const t=new AbortController;return this.track("remote",this.t("Loading records"),async()=>{const e=++this.loadToken,s=this.options.dataSource,i=this.options.fields,o=Y(i),l=await s.query({state:o,offset:0,limit:100,columnOffset:0,columnLimit:this.columnLimit,signal:t.signal});this.closed||e!==this.loadToken||(this.pendingClient?.close(W()),this.pendingClient=null,this.leaveRemote(),this.client?.close(),this.client=null,this.file=null,this.sources=null,this.base=null,this.dirty=!1,this.remote=s,this.editable=!!(this.options.editable&&s.update),this.firstBlock={key:JSON.stringify([gt(o),0]),page:l},await this.activate(i,this.options.title||this.t("Table"),this.options.storageKey))},()=>{++this.loadToken,t.abort()})}fileViewKey(t,e,s){return[this.file.name,this.file.size,this.file.lastModified,t,e,s].join("|")}async activate(t,e,s,i){this.fields=t,this.title.textContent=e,this.storageKey=s?"8sheets.table.v1|"+JSON.stringify([s,e,t.map(o=>o.name)]):null,this.state=i??Y(t),this.columnOffset=0,this.offset=0,this.continuous&&(this.limit=this.windowSize()),this.result=null,this.selection?.clear(),this.selectedCount=0,this.expanded=null,this.setRange(null),this.committed=null,this.renderTools(),await this.refresh(),this.emit("sourceLoad",{kind:this.sourceKind(),title:e,fields:this.fields.map(o=>({...o}))})}chooseSource(){const t=this.t;T(this.root,t("Choose source"),t,(e,s)=>{const i=k(this.sources.map((a,r)=>[String(r),a.name+" · "+J(a.range)]),String(this.sourceIndex)),o=c("input"),l=c("input",null,{type:"checkbox",checked:!0}),n=()=>{const a=this.sources[Number(i.value)];o.value=J(a.range),o.disabled=!a.whole,l.disabled=!a.whole,l.checked=a.headerRows!==0};if(n(),i.onchange=n,e.append(v(t("Source"),i),v(t("Range"),o),v(t("First row contains headers"),l)),/\.(csv|tsv|txt)$/i.test(this.file.name)){const a=k([["",t("Automatic")],[",",","],[";",";"],[" ","Tab"],["|","|"]],this.csv.delimiter||""),r=c("input",null,{value:(this.csv.textColumns||[]).map(It).join(", "),placeholder:"A, C"});e.append(v(t("Delimiter"),a),v(t("Read columns as text"),r)),s("Reimport CSV",async()=>{const d=r.value.trim()?r.value.toUpperCase().split(/[,\s]+/).filter(Boolean):[];if(d.some(h=>!/^([A-Z]{1,3})$/.test(h)||ft(h)>=16384))throw new Error("Invalid column.");this.dirty&&!confirm(t("Save or discard your local edits before replacing this table. Continue?"))||await this.openFile(this.file,{delimiter:a.value,textColumns:d.map(ft)})})}s("Apply",()=>this.applySource(Number(i.value),o.value,l.checked),"primary")})}async applySource(t,e,s=!0){const i=this.sources?.[t];if(!i)throw new Error("Choose a source of the open file.");if(this.base)throw new Error("Go back to the records first.");e=i.whole&&e?e:J(i.range);const o={index:this.sourceIndex,range:this.sourceRange,header:this.sourceHeader};await this.track("source",this.t("Opening")+" "+i.name,async l=>{const n=await this.client.call("source",{index:t,range:i.whole?e:void 0,header:s!==!1,editable:this.editable});if(l.cancelled){const a=this.sources[o.index];await this.client.call("source",{index:o.index,range:a.whole?o.range:void 0,header:o.header,editable:this.editable}),await this.refresh();return}this.sourceIndex=t,this.sourceRange=e,this.sourceHeader=i.whole?s!==!1:i.headerRows!==0,await this.activate(n,i.name,this.fileViewKey(t,e,s!==!1),i.initialState)},()=>{})}async refresh(t=!0){const e=++this.sequence,s={offset:this.offset,limit:this.limit,columnOffset:this.columnOffset,columnLimit:this.columnLimit};let i;if(this.remote)try{i=await this.remoteWindow(t)}catch(o){if(e!==this.sequence||this.closed)return;throw o}else i=await this.client.call("page",{...s,state:t?this.state:null});if(!(this.closed||e!==this.sequence)){if(this.continuous&&i.count<=100&&i.rows.length<i.count&&this.limit<100)return this.limit=100,this.refresh(t);this.result=i,this.offset=i.offset,this.columnOffset=i.columnOffset??0,this.checkExpanded(),this.state.collapsed=i.collapsed??this.state.collapsed,this.status.textContent="",this.renderHeader(),this.renderRows(),this.renderChips(),this.recountSelection(),this.noteState(),this.noteViewport()}}async remoteWindow(t){const e=this.rows??=new At({fetch:(r,d,h)=>this.remote.query({state:e.state,offset:r,limit:d,columnOffset:e.columnOffset,columnLimit:this.columnLimit,signal:h}),onLoad:()=>{this.closed||!e.meta||(this.result&&!this.result.loading&&e.covers(this.offset,this.limit)?this.growRemote():this.perform(()=>this.refresh(!1)))},onError:r=>{e.error=r,!this.closed&&(this.status.textContent=this.t(r.message),this.emit("error",r))}}),s=this.getState(),i=JSON.stringify([gt(s),this.columnOffset]);if(i!==e.key&&(e.reset(i),e.state=s,this.firstBlock?.key===i&&e.accept(0,this.firstBlock.page),this.firstBlock=null,e.columnOffset=this.columnOffset,e.error=null),clearTimeout(this.settleTimer),!e.meta||t){if(await e.request(this.offset,this.limit),!e.meta)throw e.error??new Error("Invalid table response.")}else if(e.covers(this.offset,this.limit))e.request(this.offset,this.limit);else{const{offset:r,limit:d}=this;this.settleTimer=setTimeout(()=>e.request(r,d),90)}this.offset>=e.count&&(this.offset=Math.max(0,e.count-this.limit));const{rows:o,missing:l}=e.window(this.offset,this.limit),n=e.meta,a=s.groups.length>0;return{...n,rows:o,offset:this.offset,count:e.count,exact:e.exact,loading:l,matches:Number.isSafeInteger(n.matches)?n.matches:e.exact&&!a?e.count:void 0,loaded:e.known}}growRemote(){const t=this.rows,e=this.result;if(t.count===e.count&&t.exact===e.exact)return;const s=Math.min(34,8e6/Math.max(1,t.count));if(!this.virtual||s!==this.stride||t.count<e.offset+e.rows.length)return this.perform(()=>this.refresh(!1));const i=this.state.groups.length>0;this.result={...e,count:t.count,exact:t.exact,loaded:t.known,matches:Number.isSafeInteger(e.matches)?e.matches:t.exact&&!i?t.count:void 0};const o=this.content.querySelector("tbody tr.tv-spacer:last-child td"),l=this.expanded&&this.expanded.index>=e.offset+e.rows.length?this.expanded.height:0;o&&(o.style.height=Math.max(0,s*(t.count-e.offset)-e.rows.length*34+l)+"px"),this.footer.querySelector("strong").textContent=this.countText()}countText(t=this.result){const e=this.t,s=Number.isSafeInteger(t.matches)?String(t.matches):t.loaded+"+";return Number.isSafeInteger(t.sourceCount)?s+" "+e("of")+" "+t.sourceCount+" "+e("records"):s+" "+e("records")}getState(){return structuredClone(this.state)}windowSize(){const t=this.content.clientHeight;return t?Math.min(250,Math.max(20,Math.ceil(t/34)+2*Z)):50}async setState(t){const e=this.state;this.state=structuredClone(t),this.expanded=null,this.continuous&&this.limit!==100&&(this.limit=this.windowSize()),this.offset=0,this.content.scrollTop=0;try{await this.refresh(),this.renderTools()}catch(s){throw this.state=e,s}}update(t){const e={...this.state,...t};return(t.sort||t.groups)&&(e.groups=e.groups.map(s=>{const i=e.sort.find(o=>o.field===s.field);return i&&!!s.desc!=!!i.desc?{...s,desc:i.desc}:s})),this.setState(e)}async change(t,e={},s="user"){if(!this.result)throw new Error("No table loaded.");if(this.remote){if(!this.editable||!this.remote.update)throw new Error("This source is read-only.");if(t==="add"||t==="remove")throw new Error("A remote source adds and removes records on its server. Change them there and call refresh().");if(t==="undo"||t==="redo")throw new Error("Undo and redo are not available for a remote source.")}else if(!this.editable)throw new Error("This view is read-only.");const i=this.beforeChange(t,e,s);if(!i)return!1;if(e=i,this.remote){let l=e;if(t==="paste"){if(this.result.loading)throw new Error("Wait for the records to load.");const a=this.result.rows.filter(m=>m.id!==void 0),r=this.result.columns,d=a.findIndex(m=>m.id===e.id),h=r.indexOf(e.field);if(d<0||h<0||d+e.lines.length>a.length||e.lines.some(m=>h+m.length>r.length))throw new Error("Paste exceeds the available records or columns.");const f=Array.from({length:e.lines.length*(e.repeat??1)},(m,g)=>e.lines[g%e.lines.length]);if(d+f.length>a.length)throw new Error("Paste exceeds the available records or columns.");l={cells:f.flatMap((m,g)=>m.map((y,w)=>({id:a[d+g].id,field:r[h+w],value:y})))}}else if(t!=="edit")throw new Error("Use the record editor for this source.");const n=await this.remoteUpdate(l);return this.emit("change",{action:t,...l,revision:n?.revision??l.revision,source:s}),!0}const o=await this.client.call(t,e);return this.dirty=!0,await this.refresh(!1),t==="add"?(this.emit("change",{action:"add",records:e.records,ids:o,source:s}),o):(this.emit("change",{action:t,...e,source:s}),!0)}async remoteUpdate(t){try{return await this.remote.update({state:this.getState(),revision:t.revision??this.result.revision,cells:t.cells})}finally{this.rows?.invalidate(),await this.refresh()}}beforeChange(t,e,s){const i={edit:"beforeEdit",paste:"beforePaste",add:"beforeAdd",remove:"beforeRemove"}[t];if(!i||!this.events.has(i))return e;const o=Bt({...structuredClone(e),source:s});if(!this.emit(i,o))return null;const{source:l,...n}=o;return n}renderTools(){const t=this.t,e=this.toolbar,s=e.contains(document.activeElement)&&document.activeElement.tagName==="BUTTON"?document.activeElement.title||document.activeElement.textContent:null;queueMicrotask(()=>{s==null||e.contains(document.activeElement)||[...e.querySelectorAll("button")].find(o=>(o.title||o.textContent)===s)?.focus()}),e.replaceChildren();const i=c("input",null,{type:"search",placeholder:t("Search records"),value:this.state.search});i.setAttribute("aria-label",t("Search records")),i.oninput=()=>{clearTimeout(this.searchTimer),this.state.search=i.value,this.offset=0,this.content.scrollTop=0,this.searchTimer=setTimeout(()=>this.perform(()=>this.refresh()),120)},e.append(i);for(const[o,l]of[["Filter",()=>this.filterDialog()],["Sort",()=>this.orderDialog(!1)],["Group",()=>this.orderDialog(!0)],["Summary",()=>this.summaryDialog()],["Columns",()=>this.columnsDialog()]])this.action(e,o,l);for(const[o,l,n,a]of[["filterRow","Filter row","filter-row",()=>this.toggleFilterRow()],["totalsRow","Totals","sigma",()=>this.toggleTotals()]]){const r=this.action(e,l,a,"tv-toggle");r.replaceChildren(_(n),c("span",t(l),{className:"tv-label"})),r.setAttribute("aria-pressed",String(!!this.state[o])),r.title=t(l)}!this.remote&&this.result?.matches!==0&&!this.base&&this.action(e,"Pivot",()=>this.pivotDialog()),this.base&&(this.action(e,"Chart",()=>this.chartDialog()),this.action(e,"Back to records",()=>this.closePivot())),this.storageKey&&this.action(e,"Views",()=>this.viewsDialog()),this.editable&&!this.remote&&(this.action(e,"Calculated field",()=>this.formulaDialog()),this.action(e,"Add record",()=>this.addRecordDialog()))}renderChips(){const t=this.t;this.chips.replaceChildren();let e=0;for(const[s,i]of[["filters","Filter"],["sort","Sort"],["groups","Group"]])this.state[s].forEach((o,l)=>{const n=this.fields.find(m=>m.name===o.field),a=n?.caption||o.field,r=m=>typeof m=="number"&&n?.format?Pt(n.format,m):String(m),d=s==="filters"?o.op==="in"?t("is one of")+" "+(o.values??[]).map(r).join(", "):[t(mt.find(m=>m[0]===o.op)?.[1]??o.op).toLowerCase(),o.value,o.op==="between"?o.value2:null].filter(m=>m!=null&&m!=="").join(" "):s==="sort"?t(o.desc?"Descending":"Ascending").toLowerCase():"",h=c("span",null,{className:"tv-chip tv-chip-"+s});h.append(c("span",t(i),{className:"tv-chip-kind"}),c("span",(a+" "+d).trim()));const f=j("close",t("Remove")+" · "+t(i)+" "+a,()=>this.perform(()=>this.update({[s]:this.state[s].filter((m,g)=>l!==g),collapsed:[]})));h.append(f),this.chips.append(h),e++});e>1&&this.action(this.chips,"Clear all",()=>this.update({filters:[],sort:[],groups:[],collapsed:[]}),"tv-link")}fieldSelect(t,e=!1){const s=this.fields.map(i=>[i.name,i.caption||i.name]);return e&&s.unshift(["",this.t("None")]),k(s,t)}columnMenu(t,e){const s=this.t,i=this.state,o=i.sort.find(h=>h.field===t),l=i.groups.some(h=>h.field===t),n=i.columns.find(h=>h.field===t)?.pinned,a=h=>()=>this.perform(h),r=h=>a(()=>this.update({sort:[{field:t,desc:h},...i.sort.filter(f=>f.field!==t)]})),d=i.columns.filter(h=>!h.hidden).length;ut(this.root,e,[[s("Sort ascending"),r(!1),{icon:"up",checked:!!o&&!o.desc}],[s("Sort descending"),r(!0),{icon:"down",checked:!!o?.desc}],o?[s("Clear sort"),a(()=>this.update({sort:i.sort.filter(h=>h.field!==t)}))]:!1,null,[s("Filter")+"…",()=>this.filterDialog(t),{icon:"filter"}],[s(l?"Ungroup":"Group by"),a(()=>this.update({groups:l?i.groups.filter(h=>h.field!==t):[...i.groups,{field:t}],collapsed:[]})),{icon:"group"}],null,[s(n?"Unpin":"Pin"),a(()=>this.update({columns:i.columns.map(h=>h.field===t?{...h,pinned:!n}:h)})),{icon:"pin"}],[s("Hide column"),a(()=>this.update({columns:i.columns.map(h=>h.field===t?{...h,hidden:!0}:h)})),{icon:"hide",disabled:d<=1}],[s("Autosize column"),a(()=>this.autosizeColumn(t)),{icon:"fit"}],[s("Conditional formatting")+"…",()=>this.formatDialog(t),{icon:"palette"}]].filter(h=>h!==!1))}filterDialog(t){const e=this.t;T(this.root,e("Filter"),e,(s,i)=>{const o=this.fieldSelect(t),l=k(mt.map(([f,m])=>[f,e(m)])),n=c("input"),a=c("input"),r=v(e("Value"),n),d=v(e("Second value"),a),h=()=>{const f=this.fields.find(m=>m.name===o.value)?.type==="number";n.inputMode=a.inputMode=f?"decimal":"text",r.hidden=["blank","notBlank"].includes(l.value),d.hidden=l.value!=="between"};h(),l.onchange=h,o.addEventListener("change",h),s.append(v(e("Field"),o),v(e("Condition"),l),r,d),this.remote||this.action(s,"Pick values",async()=>{const f=o.value,{values:m}=await this.client.call("distinct",{field:f});T(this.root,e("Pick values")+" · "+f,e,(g,y)=>{const w=[],S=c("div",null,{className:"tv-values"});g.append(S);for(const O of m){const E=c("input",null,{type:"checkbox"});w.push([E,O.value]),S.append(v(O.text+" ("+O.count+")",E))}w.length||(S.textContent=e("No values")),y("Apply",async()=>{const O=w.filter(([E])=>E.checked).map(([,E])=>E);await this.update({filters:[...this.state.filters.filter(E=>E.field!==f),{field:f,op:"in",values:O}],collapsed:[]}),s.closest("dialog")?.close()})})},"tv-link"),i("Apply",()=>this.update({filters:[...this.state.filters,{field:o.value,op:l.value,value:n.value,value2:a.value}],collapsed:[]}))})}orderDialog(t){const e=this.t,s=t?"groups":"sort";T(this.root,e(t?"Group by":"Sort by"),e,(i,o)=>{const l=this.fieldSelect(),n=k([["asc",e("Ascending")],["desc",e("Descending")]]);i.append(v(e("Field"),l)),t||i.append(v(e("Order"),n)),o(t?"Add group":"Add sort",()=>this.update({[s]:[...this.state[s].filter(a=>a.field!==l.value),{field:l.value,desc:n.value==="desc"}],collapsed:[]}))})}summaryDialog(){const t=this.t;T(this.root,t("Summary"),t,(e,s)=>{const i=this.fieldSelect(this.state.total?.field??"",!0),o=k(U.map(([l,n])=>[l,t(n)]),this.state.total?.agg);e.append(v(t("Field"),i),v(t("Summary"),o)),s("Apply",()=>this.update({total:i.value?{field:i.value,agg:o.value}:null}))})}columnsDialog(){const t=this.t,e=structuredClone(this.state.columns);T(this.root,t("Columns"),t,(s,i)=>{const o=c("div");s.append(o);const l=()=>{o.replaceChildren(),e.forEach((n,a)=>{const r=c("div",null,{className:"tv-column"}),d=c("input",null,{type:"checkbox",checked:!n.hidden});d.onchange=()=>{n.hidden=!d.checked};const h=c("input",null,{type:"number",min:48,max:800,value:n.width??"",placeholder:"px"});h.setAttribute("aria-label",t("Width")+" "+n.field),h.onchange=()=>{n.width=h.value?Math.max(48,Math.min(800,Number(h.value))):void 0};const f=c("input",null,{value:n.format??this.fields.find(S=>S.name===n.field)?.format??"General"});f.title=t("Format"),f.setAttribute("aria-label",t("Format")+" "+n.field),f.onchange=()=>{n.format=f.value||"General"};const m=c("input",null,{type:"checkbox",checked:!!n.pinned});m.onchange=()=>{n.pinned=m.checked};const g=S=>{e.splice(a,1),e.splice(a+S,0,n),l()},y=q("↑",()=>g(-1)),w=q("↓",()=>g(1));y.disabled=a===0,w.disabled=a===e.length-1,y.setAttribute("aria-label",t("Move up")+" "+n.field),w.setAttribute("aria-label",t("Move down")+" "+n.field),r.append(v(n.field,d),v(t("Pin"),m),h,f,y,w),o.append(r)})};l(),i("Apply",()=>this.update({columns:e}))})}readViews(){if(!this.storageKey)throw new Error("Saved views need a storageKey option.");try{return new Map(JSON.parse(localStorage.getItem(this.storageKey)||"[]"))}catch{return new Map}}writeViews(t){localStorage.setItem(this.storageKey,JSON.stringify([...t]))}viewsDialog(){const t=this.t,e=this.readViews(),s=()=>this.writeViews(e);T(this.root,t("Saved views"),t,(i,o)=>{const l=c("div");i.append(l);for(const[a,r]of e){const d=c("div",null,{className:"tv-column"});d.append(c("strong",a),q(t("Restore"),()=>this.perform(async()=>{await this.setState(r),d.closest("dialog").close()})),q(t("Remove"),()=>{e.delete(a),s(),d.remove()})),l.append(d)}e.size||(l.textContent=t("No saved views"));const n=c("input");i.append(v(t("View name"),n)),o("Reset view",()=>this.setState(Y(this.fields))),o("Save view",()=>{if(!n.value.trim())throw new Error(t("View name"));e.set(n.value.trim(),this.getState()),s()},"primary")})}pivotDialog(){const t=this.t,e=this.state.columns.filter(s=>!s.hidden).map(s=>[s.field,s.field]);T(this.root,t("Pivot"),t,(s,i)=>{const o=k(e),l=k([["",t("None")],...e]),n=k(e),a=k(U.filter(([g])=>g!=="distinct").map(([g,y])=>[g,t(y)])),r=g=>e.some(([y])=>y===g),d=g=>this.fields.find(y=>y.name===g)?.type,h=this.state.groups.map(g=>g.field).find(r)??e.map(([g])=>g).find(g=>d(g)==="string");h&&(o.value=h);const f=this.state.total?.field,m=f&&r(f)&&d(f)==="number"?f:this.fields.find(g=>g.type==="number"&&r(g.name))?.name;m&&(n.value=m),this.state.total&&this.state.total.agg!=="distinct"&&(a.value=this.state.total.agg),s.append(v(t("Rows"),o),v(t("Columns"),l),v(t("Value"),n),v(t("Summary"),a)),i("Apply",()=>this.openPivot({rowField:o.value,columnField:l.value,valueField:n.value,agg:a.value}))})}async openPivot({rowField:t,columnField:e="",valueField:s,agg:i="sum"}){if(this.remote)throw new Error("A pivot needs local records.");if(this.base)throw new Error("Go back to the records first.");if(!this.client||!this.fields)throw new Error("No table loaded.");await this.track("pivot",this.t("Building pivot"),async o=>{const l=await this.client.call("pivot",{rowField:t,columnField:e||"",valueField:s,agg:i});if(o.cancelled)return this.client.call("records");this.base={title:this.title.textContent,state:this.getState(),key:this.storageKey,editable:this.editable},this.editable=!1,await this.activate(l,this.base.title+" · "+this.t("Pivot"),null)},()=>{})}async closePivot(){const t=this.base;t&&(this.base=null,this.editable=t.editable,this.fields=await this.client.call("records"),this.title.textContent=t.title,this.storageKey=t.key,this.committed=null,await this.setState(t.state),this.emit("sourceLoad",{kind:this.sourceKind(),title:t.title,fields:this.fields.map(e=>({...e}))}))}chartDialog(){const t=this.t;T(this.root,t("Chart"),t,e=>{const s=this.result.columns.filter(n=>this.fields.find(a=>a.name===n)?.type==="number").map(n=>[n,n]);if(!s.length){e.append(c("p",t("No data")));return}const i=k(s),o=c("figure",null,{className:"tv-chart"});e.append(v(t("Value"),i),o);const l=async()=>{const n=i.value,a=await this.client.call("chart",{field:n});if(i.value!==n)return;o.replaceChildren(c("figcaption",t("Top 20 by absolute value")+" · "+n));const r=Math.max(1,...a.map(d=>Math.abs(d.value)));for(const d of a){const h=c("div",null,{className:"tv-chart-track"}),f=c("span");f.style.width=100*Math.abs(d.value)/r+"%",h.append(f),o.append(c("span",d.label),h,c("output",d.text))}};i.onchange=()=>this.perform(l),this.perform(l)})}addRecordDialog(){const t=this.t;T(this.root,t("Add record"),t,(e,s)=>{const i=new Map;for(const o of this.fields.filter(l=>l.editable)){const l=o.type==="boolean"?k([["",""],["true","TRUE"],["false","FALSE"]]):c("input");e.append(v(o.caption||o.name,l)),i.set(o.name,l)}s("Add",()=>this.change("add",{records:[Object.fromEntries([...i].filter(([,o])=>o.value!=="").map(([o,l])=>[o,l.value]))]}))})}formulaDialog(){const t=this.t;T(this.root,t("Calculated field"),t,(e,s)=>{const i=c("input"),o=c("input",null,{placeholder:"=[@Units]*[@Price]"});e.append(v(t("Name"),i),v(t("Formula"),o)),s("Add",()=>this.addCalculatedField(i.value,o.value))})}async addCalculatedField(t,e,s="user"){if(t=String(t??"").trim(),e=String(e??"").trim(),this.remote)throw new Error("This source is read-only.");if(!this.editable)throw new Error("This view is read-only.");this.fields=await this.client.call("formula",{name:t,formula:e}),this.dirty=!0,await this.update({columns:[...this.state.columns,{field:t}]}),this.emit("change",{action:"formula",name:t,formula:e,source:s})}scrollWindow(){const t=this.result;if(!t||this.closed||(qt(this)&&!this.columnFrame&&(this.columnFrame=requestAnimationFrame(()=>{this.columnFrame=0,!this.closed&&this.result&&this.renderRows()})),this.viewportFrame||(this.viewportFrame=requestAnimationFrame(()=>{this.viewportFrame=0,this.noteViewport()})),!this.virtual))return;const e=this.content.clientHeight,s=Math.ceil(e/34),i=this.windowSize();let o=this.content.scrollTop;const l=this.expanded;l?.height&&o>(l.index+1)*this.stride&&(o=Math.max((l.index+1)*this.stride,o-l.height));const n=Math.floor(o/this.stride);if((n>=this.offset+2||this.offset===0)&&(n+s<=this.offset+this.limit-2||this.offset+this.limit>=t.count)&&this.limit>=i)return;const r=Math.min(Math.max(0,t.count-i),Math.max(0,n-Z));this.offset===r&&this.limit===i||(this.offset=r,this.limit=i,this.perform(()=>this.refresh(!1)))}renderRows(){const t=this.result,e=this.t;this.editor&&!this.editor.busy&&this.editor.cancel();const s=c("table");s.setAttribute("aria-label",this.title.textContent);const i=s.createTHead().insertRow(),o=c("th",null,{scope:"col",className:"tv-row-action"});o.append(c("span",e("Details"),{className:"tv-sr"})),this.selection?.mode==="multiple"&&o.prepend(this.selectAllBox()),i.append(o),this.indexedFields!==this.fields&&(this.fieldIndex=new Map(this.fields.map(u=>[u.name,u])),this.indexedFields=this.fields),this.indexedColumns!==this.state.columns&&(this.columnIndex=new Map(this.state.columns.map(u=>[u.field,u])),this.indexedColumns=this.state.columns);const l=this.fieldIndex,n=this.colWindow=Ot(this,t),a=u=>{const p=c(u,null,{className:"tv-gap"});return p.setAttribute("aria-hidden","true"),p};for(const u of n.slots){if(typeof u=="object"){i.append(a("th"));continue}const p=t.columns[u],b=c("th",null,{scope:"col"}),L=this.state.sort.find(z=>z.field===p),V=this.state.sort.indexOf(L);V===0&&b.setAttribute("aria-sort",L.desc?"descending":"ascending");const x=l.get(p)?.caption||p,R=q(x,z=>this.perform(()=>{const P={field:p,desc:L?!L.desc:!1},ot=this.state.sort,bt=L?ot.map(nt=>nt.field===p?P:nt):[...ot,P];return this.update({sort:z.shiftKey?bt:[P]})}));R.className="tv-sort",R.title=e("Shift-click to sort by another column"),L?(b.classList.add("tv-sorted"),R.append(_(L.desc?"down":"up")),this.state.sort.length>1&&R.append(c("sup",String(V+1),{className:"tv-sort-order"})),R.setAttribute("aria-label",x+", "+e(L.desc?"Descending":"Ascending"))):R.append(c("span",null,{className:"tv-sort-space"})),l.get(p)?.type==="number"&&b.classList.add("tv-number"),b.append(R),b.dataset.field=p,G(b,this.columnWidth(p));const C=j("chevron",e("Column menu")+" · "+x,()=>this.columnMenu(p,C),"tv-field-menu");C.setAttribute("aria-haspopup","menu"),C.setAttribute("aria-expanded","false");const A=c("span",null,{className:"tv-resize"});A.setAttribute("aria-hidden","true"),A.title=e("Drag to resize, double-click to fit"),b.append(C,A),i.append(b)}this.state.filterRow&&this.renderFilterRow(s);const r=t.columns.map(u=>this.columnWidth(u)),d=this.rtl??=getComputedStyle(this.root).direction==="rtl",h=t.columns.map((u,p)=>{const b=this.columnIndex.get(u)?.rules;return b?.length?{rules:b,range:t.stats?.[u]??Lt(t.rows,p)}:null}),f=s.createTBody();this.virtual=this.continuous&&t.count>100;const m=Math.min(34,8e6/Math.max(1,t.count)),g=this.virtual&&this.stride&&m!==this.stride?m/this.stride:1;this.stride=m,s.classList.toggle("tv-virtual",this.virtual);const y=u=>{if(u<=0)return;const p=f.insertRow();p.className="tv-spacer",p.setAttribute("aria-hidden","true");const b=p.insertCell();b.colSpan=t.columns.length+1,b.style.height=u+"px"},w=this.expanded,S=w&&w.index<t.offset?w.height:0,O=w&&w.index>=t.offset+t.rows.length?w.height:0;this.virtual&&y(t.offset*this.stride+S);let E=t.offset-1;const D=[];for(const u of t.rows){E++;const p=f.insertRow();if(p.dataset.view=E,u.loading){p.className="tv-loading",p.insertCell();for(const x of n.slots){const R=p.insertCell();typeof x=="number"&&R.append(c("span",null,{className:"tv-skeleton"}))}continue}if(u.group!==void 0){p.className="tv-group";const x=this.state.total?n.slots.indexOf(t.columns.indexOf(this.state.total.field)):-1,R=p.insertCell();R.colSpan=x>0?x+1:n.slots.length+1;const C=q(u.group,()=>this.perform(async()=>{if(this.remote){const A=new Set(this.state.collapsed);A.has(u.path)?A.delete(u.path):A.add(u.path),await this.update({collapsed:[...A]})}else{const A=await this.client.call("toggle",{index:u.index,offset:this.offset,limit:this.limit});this.state.collapsed=A.collapsed,await this.refresh(!1)}}));if(C.className="tv-group-toggle",C.prepend(_(u.collapsed?"chevron-right":"chevron")),C.style.marginInlineStart=u.level*16+"px",C.setAttribute("aria-expanded",String(!u.collapsed)),R.append(C),x>0){const A=p.insertCell();A.className="tv-number tv-group-total",A.textContent=u.summary,x<n.slots.length-1&&(p.insertCell().colSpan=n.slots.length-1-x)}else u.summary&&R.append(c("strong",u.summary,{className:"tv-group-total"}));continue}const b=q(null,()=>this.perform(()=>this.details(u)),"tv-icon-btn tv-open-btn");b.setAttribute("aria-label",e("Record details")+" "+(u.values[0]||u.id));const L=p.insertCell();if(L.className="tv-row-action",this.selection){const x=this.selectionBox(u);L.append(x),p.classList.toggle("tv-row-selected",x.checked)}this.options.detailRenderer&&L.append(this.expandButton(u,E)),L.append(b),p.dataset.recordIndex=D.length;const V=new Array(t.columns.length);for(const x of n.slots){if(typeof x=="object"){p.insertCell().className="tv-gap";continue}const R=u.values[x],C=p.insertCell();C.textContent=R,V[x]=C;const A=t.columns[x],z=this.options.renderers?.[A];if(typeof z=="function"){const P=z({id:u.id,field:A,text:R});P instanceof Node?C.replaceChildren(P):P!=null&&(C.textContent=String(P))}l.get(A)?.type==="number"&&(C.className="tv-number"),r[x]&&!n.fixed&&G(C,r[x]),h[x]&&ct(C,rt(h[x].rules,u.raw?.[x],R,h[x].range,d))}D.push(V),p.ondblclick=()=>this.perform(()=>this.details(u)),w?.id===u.id&&w.index===E&&this.renderDetail(f,t.columns.length+1)}if(this.virtual&&y(this.stride*(t.count-t.offset)-t.rows.length*34+O),this.state.totalsRow&&this.renderTotals(s,r),n.fixed){Dt(this,t,n);const u=c("colgroup"),p=b=>{const L=c("col");L.style.width=b+"px",u.append(L)};p(n.fixed.lead);for(const b of n.slots)p(typeof b=="object"?b.gap:n.fixed.widths[b]);s.prepend(u),s.style.tableLayout="fixed",s.style.width=n.fixed.total+"px"}const I=this.range,M=document.activeElement,F=this.content.contains(M)?xt(M):null,K=F?{id:this.grid?.records[F.row]?.id,col:F.col,step:{row:0,col:0},quiet:!0}:null;s.columnAt=[-1,...n.slots.map(u=>typeof u=="number"?u:-1)],this.grid=St(this,s,D);const N=this.focusAfter??K;this.focusAfter=null;const vt=this.content.scrollLeft,wt=this.content.scrollTop,X=this.content.contains(document.activeElement)?document.activeElement:null,tt=X?.dataset.focus,Q=X?.selectionStart;this.content.replaceChildren(s);const et=n.measure&&D.length?D[0].find(Boolean):null;et&&Ft(this,t,i,n.measure,et);const st=s.tHead.rows[1];if(st)for(const u of st.cells)u.style.top=i.offsetHeight+"px";if(N?.view!=null&&this.grid){const u=Math.max(0,Math.min(t.count-1,N.view)),p=t.rows[u-t.offset],b=p?this.grid.records.indexOf(p):-1;b>=0?this.grid.focusAt(b,N.col):!p&&(N.tries??0)<8&&(this.focusAfter={...N,view:u,tries:(N.tries??0)+1})}else if(N?.step&&this.grid){const u=this.grid.records.findIndex(p=>p.id===N.id);u>=0&&this.grid.focusAt(u+N.step.row,N.col+N.step.col,N.quiet)}if(I&&(!N||N===K)){const u=this.grid?.positionOf(I.anchor.id,I.anchor.field),p=this.grid?.positionOf(I.focus.id,I.focus.field);u&&p&&this.grid.cells[u.row][u.col]&&this.grid.cells[p.row][p.col]?this.grid.select(u,p,!!F):this.setRange(null)}const it=s.querySelector("tr.tv-detail");if(it&&w&&(w.height=it.offsetHeight),tt){const u=[...s.querySelectorAll("[data-focus]")].find(p=>p.dataset.focus===tt);u&&(u.focus({preventScroll:!0}),Q!=null&&u.setSelectionRange&&u.setSelectionRange(Q,Q))}const $=this.root.querySelector(".tv-menu");if($&&!$.anchor?.isConnected&&$.dispatchEvent(new Event("tv-close")),!t.rows.length){const u=c("div",null,{className:"tv-empty"});u.append(c("h2",e(t.sourceCount?"No matching records":"No data"))),t.sourceCount&&this.action(u,"Clear filters",()=>this.update({filters:[],search:""})),this.content.append(u)}this.content.scrollLeft=vt,this.content.scrollTop=wt*g,s.setAttribute("aria-busy",String(!!t.loading)),this.positionPinned(s),Tt(this,s),this.selectionSummary=c("output",null,{className:"tv-selection-summary"}),this.selectionSummary.setAttribute("aria-live","polite"),this.footer.replaceChildren(),this.footer.append(c("strong",this.countText(t)),this.selectionStatus),this.state.total&&this.footer.append(c("span",e(U.find(u=>u[0]===this.state.total.agg)?.[1]||"Summary")+" · "+this.state.total.field+" "+t.summary));const B=c("div",null,{className:"tv-actions"});if(t.count>100&&this.action(B,this.continuous?"Pages":"Scroll",()=>this.setScrolling(this.continuous?"pages":"continuous")),!this.virtual&&(t.offset>0||t.offset+this.limit<t.count)){const u=this.action(B,"Previous",()=>this.page(-1));u.disabled=!t.offset,B.append(c("span",e("Page")+" "+(Math.floor(t.offset/this.limit)+1)+" / "+(t.exact===!1?"?":Math.max(1,Math.ceil(t.count/this.limit)))));const p=this.action(B,"Next",()=>this.page(1));p.disabled=t.offset+this.limit>=t.count}if(t.columnCount>this.columnLimit)for(const[u,p]of[["←",-1],["→",1]]){const b=this.action(B,u,()=>(this.columnOffset+=p*this.columnLimit,this.refresh(!1)));b.setAttribute("aria-label",e("Columns")+" "+e(p<0?"Previous":"Next")),b.disabled=p<0?!this.columnOffset:this.columnOffset+this.columnLimit>=t.columnCount}this.footer.append(this.selectionSummary,B)}setScrolling(t){if(t!=="continuous"&&t!=="pages")throw new Error('Scrolling is "continuous" or "pages".');return this.options.scrolling=t,this.continuous===(t==="continuous")?Promise.resolve():(this.continuous=t==="continuous",this.limit=50,this.offset=0,this.content.scrollTop=0,this.result?this.refresh(!1):Promise.resolve())}setRange(t){const e=t?JSON.stringify([t.anchor,t.focus]):null;this.range=t,e!==this.rangeKey&&(this.rangeKey=e,this.events.has("rangeChange")&&this.emit("rangeChange",this.api.getRange()))}positionPinned(t=this.content.querySelector("table")){const e=this.result,s=t?.tHead?.rows[0];if(!s)return;let i=0;for(;i<e.columns.length&&this.columnIndex.get(e.columns[i])?.pinned;)i++;if(!i)return;const o=this.colWindow?.fixed,l=[];for(let r=0;r<i;r++)l.push(this.liveWidths.get(e.columns[r])??o?.widths[r]??s.cells[r+1].offsetWidth);const n=[...t.rows].filter(r=>!r.classList.contains("tv-group"));let a=0;for(let r=0;r<i;r++){for(const d of n){const h=d.cells[r+1];h&&h.colSpan===1&&(h.classList.add("tv-pinned"),h.style.insetInlineStart=a+"px")}a+=l[r]}}revealColumn(t){ht(this,t)&&this.renderRows()}columnWidth(t){return this.liveWidths.get(t)??this.state.columns.find(e=>e.field===t)?.width}setColumnWidth(t,e){this.state={...this.state,columns:this.state.columns.map(s=>s.field===t?{...s,width:e}:s)},this.renderRows(),this.noteState()}async showRow(t){const e=this.result;if(this.continuous){if(this.virtual){const a=this.remote?this.rows:null;if(a&&!a.exact&&t>=a.count-a.blockSize){if(await a.reach(t),a.error)throw a.error;if(a.exact&&t>=a.count)throw new RangeError(`Row ${t} is past the last row.`)}const r=a?a.count:e.count,d=this.windowSize(),h=Math.min(Math.max(0,r-d),Math.max(0,t-Z));(h!==this.offset||d!==this.limit||this.result.loading||r!==e.count)&&(this.offset=h,this.limit=d,await this.refresh(!1));const f=this.expanded;this.content.scrollTop=t*this.stride+(f&&f.index<t?f.height:0)}}else{const a=Math.floor(t/this.limit)*this.limit;a!==e.offset&&(this.offset=a,this.content.scrollTop=0,await this.refresh(!1))}const s=this.content.querySelector(`tbody tr[data-view="${t}"]`);if(!s)return;const i=this.content.getBoundingClientRect(),o=s.getBoundingClientRect(),l=this.content.querySelector("thead")?.getBoundingClientRect().height??0,n=this.content.querySelector("tfoot")?.getBoundingClientRect().height??0;o.top<i.top+l?this.content.scrollTop-=i.top+l-o.top:o.bottom>i.bottom-n&&(this.content.scrollTop+=o.bottom-(i.bottom-n))}async showColumn(t,e){const s=e.indexOf(t),i=Math.floor(s/this.columnLimit)*this.columnLimit;i!==this.columnOffset&&(this.columnOffset=i,await this.refresh(!1));const o=this.result.columns.indexOf(t);if(o<0)return;if(ht(this,o))return this.renderRows();const l=[...this.content.querySelectorAll("thead tr:first-child th[data-field]")].find(f=>f.dataset.field===t);if(!l||l.classList.contains("tv-pinned"))return;const n=this.content.getBoundingClientRect(),a=l.getBoundingClientRect();let r=0;for(const f of this.content.querySelectorAll("thead tr:first-child th.tv-pinned"))r=Math.max(r,f.getBoundingClientRect().right-n.left);const d=this.content.querySelector("thead tr:first-child th.tv-row-action")?.getBoundingClientRect().width??0,h=n.left+Math.max(r,d);a.left<h?this.content.scrollLeft-=h-a.left:a.right>n.right&&(this.content.scrollLeft+=a.right-n.right)}setLanguage(t){this.language=t||pt(),this.t=dt(this.language),this.root.lang=this.language,this.rtl=null,this.renderHeader(),this.renderTools(),this.result?(this.renderRows(),this.renderChips(),this.renderSelectionStatus()):this.empty()}setRowSelection(t){if(t!=null&&t!=="multiple"&&t!=="single")throw new Error('Row selection is "multiple", "single" or null.');this.options.rowSelection=t??void 0,this.selection=t?new at(t):null,this.selectedCount=0,this.selectionKey=null,this.result&&this.renderRows(),this.renderSelectionStatus(),this.selection&&this.paintSelection()}autosizeColumn(t){const e=Et(this,t);return e&&this.setColumnWidth(t,e),e}async moveColumn(t,e){const s=this.state.columns.filter(l=>l.field!==t),i=this.state.columns.find(l=>l.field===t);if(!i)return;const o=e?s.findIndex(l=>l.field===e):-1;s.splice(o<0?s.length:o,0,i),this.state={...this.state,columns:s},await this.refresh()}async applyLayout(t){const e=this.state;this.state={...this.state,...t};try{await this.refresh()}catch(s){throw this.state=e,s}this.renderTools()}renderFilterRow(t){const e=this.t,s=this.result,i=t.tHead.insertRow();i.className="tv-filter-row";const o=c("th",null,{className:"tv-row-action"});if(this.state.filters.some(n=>n.quick)){const n=j("close",e("Clear column filters"),()=>this.perform(()=>this.update({filters:this.state.filters.filter(a=>!a.quick),collapsed:[]})));n.dataset.focus="quick-clear",o.append(n)}i.append(o),this.quickText??=new Map;for(const n of this.colWindow.slots){if(typeof n=="object"){i.append(c("th",null,{className:"tv-gap"}));continue}const a=s.columns[n],r=this.fieldIndex.get(a),d=r?.caption||a,h=this.state.filters.find(g=>g.quick&&g.field===a),f=c("input",null,{type:"text",value:this.quickText.get(a)??h?.text??"",placeholder:r?.type==="number"||r?.type==="date"?"> < = ..":e("Contains"),autocomplete:"off",spellcheck:!1,size:4});f.setAttribute("aria-label",e("Filter")+" · "+d),f.dataset.focus="quick:"+a,r?.type==="number"&&(f.inputMode="text"),f.addEventListener("input",()=>{this.quickText.set(a,f.value),clearTimeout(this.quickTimer),this.quickTimer=setTimeout(()=>this.perform(()=>this.applyQuickFilters()),300)}),f.addEventListener("keydown",g=>{g.key==="Escape"&&f.value?(g.stopPropagation(),f.value="",f.dispatchEvent(new Event("input"))):g.key==="Enter"&&(clearTimeout(this.quickTimer),this.perform(()=>this.applyQuickFilters()))});const m=c("th");m.append(f),r?.type==="number"&&m.classList.add("tv-number"),G(m,this.columnWidth(a)),i.append(m)}}applyQuickFilters(){const t=this.quickText;if(!t?.size)return;let e=this.state.filters;for(const[s,i]of t){const o=this.fields.find(a=>a.name===s)?.type,l=Mt(s,i,o),n=e.findIndex(a=>a.quick&&a.field===s);n>=0&&(e=e.filter((a,r)=>r!==n)),l&&(e=[...e,l])}return t.clear(),JSON.stringify(e)===JSON.stringify(this.state.filters)?this.renderRows():this.update({filters:e,collapsed:[]})}toggleFilterRow(t=!this.state.filterRow){return t||this.quickText?.clear(),this.applyLayout({filterRow:t})}expandButton(t,e){const s=this.expanded?.id===t.id&&this.expanded.index===e,i=this.t(s?"Collapse details":"Expand details")+" "+(t.values[0]||t.id),o=j(s?"chevron":"chevron-right",i,()=>this.perform(()=>this.toggleDetail(t,e)),"tv-expand",!1);return o.setAttribute("aria-expanded",String(s)),o.dataset.focus="expand:"+t.id,s&&o.setAttribute("aria-controls",this.detailId()),o}rowsKey(){const{search:t,filters:e,sort:s,groups:i,collapsed:o,collapseLevel:l}=this.state,n=this.result;return JSON.stringify([t,e,s,i,o,l,n?.exact===!1?null:n?.count,n?.matches])}checkExpanded(){const t=this.expanded,e=this.result;if(!t)return;const s=t.index-e.offset,i=s>=0&&s<e.rows.length&&e.rows[s]?.id!==t.id&&!e.rows[s]?.loading;(t.key!==this.rowsKey()||i)&&(this.expanded=null)}detailId(){return(this.uid??="tv"+Math.random().toString(36).slice(2,8))+"-detail"}toggleDetail(t,e){if(this.expanded?.id===t.id)this.expanded=null;else{const s=this.result.columns,i={id:t.id,values:Object.fromEntries(s.map((n,a)=>[n,t.values[a]])),raw:Object.fromEntries(s.map((n,a)=>[n,t.raw?.[a]??null]))},o=this.options.detailRenderer(i),l=o instanceof Node?o:c("div",o==null?"":String(o));this.expanded={id:t.id,index:e,node:l,height:0,key:this.rowsKey()}}this.renderRows()}renderDetail(t,e){const s=t.insertRow();s.className="tv-detail";const i=s.insertCell();i.colSpan=e;const o=c("div",null,{className:"tv-detail-panel",id:this.detailId()});o.setAttribute("role","region"),o.setAttribute("aria-label",this.t("Record details")),o.append(this.expanded.node),i.append(o)}formatDialog(t){const e=this.t,s=this.fields.find(r=>r.name===t),i=s?.type==="number",o=structuredClone(this.state.columns.find(r=>r.field===t)?.rules??[]),l=[...i?[["bar",e("Data bar")],["scale",e("Colour scale")],["gt",e("Greater than")],["lt",e("Less than")],["between",e("Between")]]:[],["equal",e("Equals")],["contains",e("Contains")]],n=[["good",e("Green fill")],["bad",e("Red fill")],["warn",e("Amber fill")],["info",e("Blue fill")],["strong",e("Bold text")]],a=r=>r.type==="bar"?e("Data bar"):r.type==="scale"?e("Colour scale"):[l.find(([d])=>d===r.op)?.[1]??r.op,r.value,r.op==="between"?"– "+r.value2:""].join(" ").trim()+" · "+(n.find(([d])=>d===r.style)?.[1]??e("Custom"));T(this.root,e("Conditional formatting")+" · "+(s?.caption||t),e,(r,d)=>{const h=c("div",null,{className:"tv-rule-list"}),f=()=>{h.replaceChildren(),o.length||h.append(c("p",e("No rules"),{className:"tv-muted"})),o.forEach((M,F)=>{const K=c("div",null,{className:"tv-column"}),N=c("span",null,{className:"tv-swatch"});ct(N,rt([M],1,"",{min:0,max:2})),K.append(N,c("span",a(M))),K.append(j("close",e("Remove")+" · "+a(M),()=>{o.splice(F,1),f()})),h.append(K)})};f();const m=k(l),g=k(n),y=c("input",null,{inputMode:i?"decimal":"text"}),w=c("input",null,{inputMode:"decimal"}),S=v(e("Value"),y),O=v(e("Second value"),w),E=v(e("Style"),g),D=()=>{const M=m.value==="bar"||m.value==="scale";S.hidden=E.hidden=M,O.hidden=m.value!=="between"};m.onchange=D,D();const I=q(e("Add rule"),()=>{const M=m.value;if(M==="bar"||M==="scale")o.push({type:M});else{if(y.value.trim()==="")return y.focus();const F={type:"value",op:M,value:y.value.trim(),style:g.value};M==="between"&&(F.value2=w.value.trim()),o.push(F)}y.value=w.value="",f()});I.classList.add("tv-add-rule"),r.append(h,v(e("Rule"),m),S,O,E,I),d("Clear rules",()=>this.setColumnRules(t,[]),"danger"),d("Apply",()=>this.setColumnRules(t,o),"primary")})}setColumnRules(t,e){return this.applyLayout({columns:this.state.columns.map(s=>s.field===t?{...s,rules:e.length?e:void 0}:s)})}toggleTotals(t=!this.state.totalsRow){const e=i=>this.fields.find(o=>o.name===i)?.type==="number",s=t?this.state.columns.map(i=>i.total===void 0&&e(i.field)?{...i,total:"sum"}:i):this.state.columns;return this.applyLayout({totalsRow:t,columns:s})}setColumnTotal(t,e){return this.applyLayout({columns:this.state.columns.map(s=>s.field===t?{...s,total:e||null}:s)})}renderTotals(t,e){const s=this.t,i=this.result,o=t.createTFoot().insertRow();o.className="tv-totals";const l=c("th",null,{scope:"row",className:"tv-row-action"});l.append(_("sigma"),c("span",s("Totals"),{className:"tv-sr"})),o.append(l);for(const n of this.colWindow.slots){const a=o.insertCell();if(typeof n=="object"){a.className="tv-gap";continue}const r=i.columns[n],d=this.columnIndex.get(r),h=this.fieldIndex.get(r),f=d?.total,m=h?.caption||r,g=U.find(([S])=>S===f)?.[1],y=i.totals?.[r]??"",w=q(null,()=>ut(this.root,w,[[s("None"),()=>this.perform(()=>this.setColumnTotal(r,null)),{checked:!f,icon:f?void 0:"check"}],...U.filter(([S])=>S!=="distinct").map(([S,O])=>[s(O),()=>this.perform(()=>this.setColumnTotal(r,S)),{checked:f===S,icon:f===S?"check":void 0,disabled:S!=="count"&&h?.type!=="number"&&h?.type!=="date"}])]));w.className="tv-total",w.setAttribute("aria-haspopup","menu"),w.setAttribute("aria-label",m+" · "+(g?s(g)+" "+y:s("No total"))),g&&w.append(c("span",s(g),{className:"tv-total-kind"}),c("span",y,{className:"tv-total-value"})),h?.type==="number"&&a.classList.add("tv-number"),e[n]&&!this.colWindow.fixed&&G(a,e[n]),a.append(w)}}selectAllBox(){const t=c("input",null,{type:"checkbox",className:"tv-select-all"});return t.setAttribute("aria-label",this.t("Select all matching records")),t.dataset.focus="select-all",t.addEventListener("change",()=>t.checked?this.selectAll():this.clearSelection()),this.paintSelectAll(t),t}paintSelectAll(t=this.content.querySelector(".tv-select-all")){if(!t)return;const e=this.selection,s=this.result?.matches,i=Number.isFinite(this.selectedCount)&&Number.isFinite(s)&&this.selectedCount===s,o=e.all?e.ids.size===0||i:this.selectedCount>0&&i;t.checked=o,t.indeterminate=!o&&!e.empty}selectionBox(t){const e=c("input",null,{type:"checkbox",className:"tv-select",checked:this.selection.has(t.id)});return e.recordId=t.id,e.dataset.focus="select:"+t.id,e.setAttribute("aria-label",this.t("Select record")+" "+(t.values[0]||t.id)),e.addEventListener("change",()=>this.toggleRecord(t,e.checked)),e}toggleRecord(t,e){const s=this.selection;if(!s||t?.id===void 0)return;const i=s.has(t.id);e??=!i,e!==i&&(s.toggle(t.id,e),s.mode==="single"?this.selectedCount=e?1:0:Number.isFinite(this.selectedCount)&&(this.selectedCount+=e?1:-1),this.paintSelection())}paintSelection(){const t=this.selection;for(const e of this.content.querySelectorAll("input.tv-select"))e.checked=t.has(e.recordId),e.closest("tr")?.classList.toggle("tv-row-selected",e.checked);this.paintSelectAll(),this.renderSelectionStatus(),this.emit("selectionChange",{...t.toJSON(),count:this.selectedCount})}renderSelectionStatus(){const t=this.selectionStatus,e=this.selection;if(t.replaceChildren(),!e||e.empty)return;const s=Number.isFinite(this.selectedCount)?this.selectedCount+" "+this.t("selected"):e.all?e.ids.size?this.t("All matching selected except")+" "+e.ids.size:this.t("All matching selected"):e.ids.size+" "+this.t("selected");t.append(c("span",s)),this.action(t,"Clear selection",()=>this.clearSelection(),"tv-link")}async recountSelection(t=!1){const e=this.selection,s=this.result;if(!e||!s)return;const i=JSON.stringify([this.state.search,this.state.filters,s.matches,s.sourceCount]);if(!t&&(i===this.selectionKey||e.empty))return;this.selectionKey=i;let o;e.empty?o=0:this.remote?o=e.all?Number.isSafeInteger(s.matches)?Math.max(0,s.matches-e.ids.size):void 0:e.ids.size:e.all&&!e.ids.size&&Number.isSafeInteger(s.matches)?o=s.matches:o=await this.client.call("selectionCount",{selection:e.toJSON()}),!(this.closed||i!==this.selectionKey)&&(this.selectedCount=o,this.paintSelection())}selectAll(){if(this.selection)return this.selection.selectAll(),this.recountSelection(!0)}clearSelection(){if(this.selection)return this.selection.clear(),this.recountSelection(!0)}getSelection(){return this.selection?this.selection.toJSON():{all:!1,ids:[]}}setSelection(t){if(!this.selection)throw new Error("Row selection is off for this table.");return this.selection.set(t),this.recountSelection(!0)}async getSelectedIds(){const t=this.selection;if(!t||t.empty)return[];if(!this.remote)return this.client.call("selectedIds",{selection:t.toJSON()});if(t.all)throw new Error('A remote source resolves "all matching records" itself. Use getSelection().');return[...t.ids]}page(t){return this.offset+=t*this.limit,this.content.scrollTop=0,this.refresh(!1)}async details(t,e){const s=this.t,i=this.result.revision;let o=this.result.columns;if(e)o=e.map(l=>l.field),t={...t,values:e.map(l=>l.value)};else if(this.result.columnCount>o.length&&(!this.remote||this.remote.detail)){const l=this.remote?await this.remote.detail({id:t.id,state:this.getState(),signal:(this.abort=new AbortController).signal}):await this.client.call("detail",{id:t.id});o=l.map(n=>n.field),t={...t,values:l.map(n=>n.value)}}T(this.root,s("Record details"),s,(l,n)=>{const a=[];o.forEach((r,d)=>{const h=this.fields.find(f=>f.name===r);if(this.editable&&(this.remote?h?.editable===!0:h?.editable)){const f=c("input",null,{value:t.values[d]});l.append(v(h.caption||r,f)),a.push({field:r,input:f,old:t.values[d]})}else l.append(v(h?.caption||r,c("output",t.values[d])))}),this.editable&&!this.remote&&n("Remove record",()=>this.change("remove",{ids:[t.id]}),"danger"),this.editable&&!this.remote&&n("Paste rows",()=>this.pasteDialog(t)),n("Copy row",()=>navigator.clipboard.writeText(t.values.join(" "))),this.editable&&n("Save changes",()=>this.change("edit",{revision:i,cells:a.filter(r=>r.input.value!==r.old).map(r=>({id:t.id,field:r.field,value:r.input.value}))}),"primary")})}pasteDialog(t){const e=this.t;T(this.root,e("Paste rows"),e,(s,i)=>{const o=k(this.result.columns.map(a=>[a,a])),l=c("textarea",null,{rows:5}),n=c("input",null,{type:"number",min:1,value:1});s.append(v(e("Starting field"),o),v(e("Use Tab to separate fields and a new line for each record."),l),v(e("Number of records"),n)),i("Apply",async()=>{await this.change("paste",{id:t.id,field:o.value,lines:yt(l.value),repeat:Number(n.value)})})})}shareDialog(){const t=this.t,e=this.options.sharing;T(this.root,t("Share")+" · "+this.countText(),t,(s,i)=>{if(e)if(!this.lastShare&&this.storageKey&&(this.lastShare=JSON.parse(sessionStorage.getItem(this.storageKey+".share")||"null")),this.lastShare){const o=c("input",null,{value:this.lastShare.url,readOnly:!0});s.append(v(t("Share link"),o)),i("Copy link",()=>navigator.clipboard.writeText(o.value),"primary"),i("Revoke link",()=>this.revokeShare(),"danger")}else i("Publish filtered copy",async()=>{await this.createShare(),this.shareDialog()});navigator.canShare&&i("Prepare file",async()=>{const o=new File([await this.exportResults("xlsx")],"Results.xlsx",{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});if(!navigator.canShare({files:[o]}))throw new Error("File sharing is unavailable on this device.");T(this.root,t("Share"),t,(l,n)=>n("Share",()=>navigator.share({files:[o],title:this.title.textContent})))})})}async createShare(){const t=this.options.sharing;if(!t)throw new Error("Sharing needs a sharing option.");return this.lastShare=await t.create(await this.exportResults("xlsx")),this.storageKey&&sessionStorage.setItem(this.storageKey+".share",JSON.stringify(this.lastShare)),{...this.lastShare}}async revokeShare(){const t=this.options.sharing;if(!t)throw new Error("Sharing needs a sharing option.");return!this.lastShare&&this.storageKey&&(this.lastShare=JSON.parse(sessionStorage.getItem(this.storageKey+".share")||"null")),this.lastShare?(await t.revoke(this.lastShare.id),this.lastShare=null,this.storageKey&&sessionStorage.removeItem(this.storageKey+".share"),!0):!1}async downloadResults(t,{selected:e=!1,fileName:s}={}){const i=await this.exportResults(t,{selected:e}),o=URL.createObjectURL(i),l=e?this.selectedCount:this.result?.matches;return c("a",null,{href:o,download:s||this.title.textContent+(Number.isSafeInteger(l)?"-"+l:"")+"."+t}).click(),setTimeout(()=>URL.revokeObjectURL(o),3e4),i}async exportDialog(){clearTimeout(this.searchTimer),await this.refresh();const t=this.t;T(this.root,t("Export results")+" · "+this.countText(),t,(e,s)=>{const i=k((this.remote?.formats??["xlsx","csv","pdf"]).map(n=>[n,{xlsx:"Excel (.xlsx)",csv:"CSV (.csv)",pdf:"PDF (.pdf)"}[n]]));e.append(v(t("Format"),i));const o=this.selection,l=o&&!o.empty&&(!this.remote||this.remote.selectionExport)?k([["all",t("All matching records")+" ("+this.countText().split(" ")[0]+")"],["selected",t("Selected records")+(Number.isFinite(this.selectedCount)?" ("+this.selectedCount+")":"")]],"selected"):null;l&&e.append(v(t("Records"),l)),s("Download",()=>this.downloadResults(i.value,{selected:l?.value==="selected"}))})}async exportResults(t,{selected:e=!1}={}){if(!["xlsx","csv","pdf"].includes(t))throw new Error('Export as "xlsx", "csv" or "pdf".');if(!this.result)throw new Error("No table loaded.");const s=this.getState(),i=e&&this.selection&&!this.selection.empty?this.selection.toJSON():void 0;if(e&&!i)throw new Error("Select records to export first.");if(this.remote){if(!this.remote.exportResults)throw new Error("This source cannot export.");if(!(this.remote.formats??["xlsx","csv","pdf"]).includes(t))throw new Error(`This source cannot export ${t}.`);if(i&&!this.remote.selectionExport)throw new Error("This source cannot export selected records.");return this.remote.exportResults({state:s,format:t,signal:this.abort?.signal,...i&&{selection:i}})}return this.client.call("export",{format:t,state:s,selection:i})}destroy(){this.closed||(this.load&&(this.load.cancel?.(),this.endLoad(this.load,"cancelled")),this.closed=!0,this.events.clear(),cancelAnimationFrame(this.viewportFrame),this.root.querySelector(".tv-menu")?.dispatchEvent(new Event("tv-close")),this.resize.disconnect(),++this.sequence,clearTimeout(this.searchTimer),this.abort?.abort(),clearTimeout(this.settleTimer),this.rows?.reset(),this.pendingClient?.close(),this.client?.close(),this.root.remove())}}export{ue as mountTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function d(n,e,s={}){const r=document.createElement(n);return e!=null&&(r.textContent=e),Object.assign(r,s),r}function g(n,e,s=""){const r=d("button",n,{type:"button",className:s});return r.addEventListener("click",e),r}const E={chevron:"M4 6l4 4 4-4","chevron-right":"M6 4l4 4-4 4",close:"M4 4l8 8M12 4l-8 8",up:"M8 13V3M4 7l4-4 4 4",down:"M8 3v10M4 9l4 4 4-4",open:"M9 3h4v4M13 3L7.5 8.5M11 9.5V13H3V5h3.5",filter:"M2.5 3.5h11L9.5 8.5v4l-3-1.5V8.5z",group:"M3 4h10M5 8h8M5 12h8M3 8v4",pin:"M6 2.5h4M7 2.5v4L4.5 9h7L9 6.5v-4M8 9v4.5",hide:"M2 8s2.2-4 6-4 6 4 6 4-2.2 4-6 4-6-4-6-4zM3 13L13 3",fit:"M2 3v10M14 3v10M5 8h6M7 6L5 8l2 2M9 6l2 2-2 2",sigma:"M12 3H4l4.5 5L4 13h8",palette:"M3 13V9M6.5 13V5M10 13V7.5M13.5 13V3","filter-row":"M2 3.5h12M2 7.5h12M4 11.5h8",expand:"M6 4l4 4-4 4",check:"M3.5 8.5l3 3 6-7"},w=new Map;function x(n){let e=w.get(n);if(!e){const s="http://www.w3.org/2000/svg";e=document.createElementNS(s,"svg"),e.setAttribute("viewBox","0 0 16 16"),e.setAttribute("aria-hidden","true"),e.setAttribute("class","tv-icon");const r=document.createElementNS(s,"path");r.setAttribute("d",E[n]),e.append(r),w.set(n,e)}return e.cloneNode(!0)}function L(n,e,s,r="",o=!0){const i=g(null,s,("tv-icon-btn "+r).trim());return i.append(x(n)),i.setAttribute("aria-label",e),o&&(i.title=e),i}function A(n,e){const s=d("select");for(const[r,o]of n)s.add(new Option(o,r));return e!=null&&(s.value=e),s}function k(n,e){const s=d("label");return e.setAttribute("aria-label",n),s.append(d("span",n),e),e.type==="checkbox"&&s.classList.add("tv-check"),s}function C(n,e,s){const r=n.querySelector(".tv-menu");if(r&&(r.dispatchEvent(new Event("tv-close")),r.anchor===e))return null;const o=d("div",null,{className:"tv-menu"});o.anchor=e,o.setAttribute("role","menu");const i=[];for(const t of s){if(!t){o.append(d("div",null,{className:"tv-menu-sep",role:"separator"}));continue}const[l,u,c={}]=t,a=d("button",null,{type:"button",className:"tv-menu-item",tabIndex:-1,disabled:!!c.disabled});a.setAttribute("role",c.checked!=null?"menuitemcheckbox":"menuitem"),c.checked!=null&&a.setAttribute("aria-checked",String(!!c.checked));const b=c.icon?x(c.icon):d("span",null,{className:"tv-icon"});a.append(b,d("span",l)),a.addEventListener("click",()=>{f(!1),u()}),o.append(a),i.push(a)}const v=()=>{if(!e.isConnected)return f(!1);const t=n.getBoundingClientRect(),l=e.getBoundingClientRect(),u=(e.closest("th")??e).getBoundingClientRect();if(l.right<t.left||l.left>t.right||l.bottom<t.top||l.top>t.bottom)return f(!1);const c=o.offsetWidth;let a=u.left-t.left;a+c>t.width-8&&(a=l.right-t.left-c),o.style.left=Math.max(8,Math.min(a,t.width-c-8))+"px";const b=l.bottom-t.top+4,y=b+o.offsetHeight<=t.height-8;o.style.top=(y?b:Math.max(8,l.top-t.top-o.offsetHeight-4))+"px"},h=t=>{const l=i.filter(c=>!c.disabled);if(!l.length)return;const u=l.indexOf(document.activeElement);l[(u+t+l.length)%l.length].focus()},M=t=>{if(t.key==="ArrowDown")h(1);else if(t.key==="ArrowUp")h(-1);else if(t.key==="Home"||t.key==="End"){const l=i.filter(u=>!u.disabled);l[t.key==="Home"?0:l.length-1]?.focus()}else if(t.key==="Escape")f(!0);else if(t.key==="Tab")f(!1);else return;t.preventDefault(),t.stopPropagation()},m=t=>{!o.contains(t.target)&&!e.contains(t.target)&&f(!1)},f=t=>{o.remove(),e.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",m,!0),window.removeEventListener("resize",p),n.querySelector(".tv-data")?.removeEventListener("scroll",v),t&&e.isConnected&&e.focus()},p=()=>f(!1);return o.addEventListener("keydown",M),o.addEventListener("tv-close",p),n.append(o),e.setAttribute("aria-expanded","true"),v(),document.addEventListener("pointerdown",m,!0),window.addEventListener("resize",p),n.querySelector(".tv-data")?.addEventListener("scroll",v,{passive:!0}),i.find(t=>!t.disabled)?.focus(),o}function N(n,e,s,r){const o=document.activeElement,i=d("dialog",null,{className:"tv-dialog"}),v=d("header"),h=L("close",s("Close"),()=>i.close(),"tv-close");v.append(d("h2",e),h);const M=d("div",null,{className:"tv-form"}),m=d("div",null,{className:"tv-dialog-actions"}),f=d("p",null,{className:"tv-error"});f.setAttribute("role","alert"),i.setAttribute("aria-label",e),i.append(v,M,f,m),n.append(i);const p=[],t=(l,u,c="")=>{const a=g(s(l),async()=>{if(!a.disabled){a.disabled=!0;try{await u(),i.close()}catch(b){f.textContent=s(b.message)}finally{a.disabled=!1}}},c?"tv-"+c:"");return m.append(a),p.push([a,c]),a};return i.addEventListener("close",()=>{if(i.remove(),n.querySelector("dialog[open]")||o?.isConnected)return;[...n.querySelectorAll("button")].find(u=>u.textContent===o?.textContent&&u.getAttribute("aria-label")===o?.getAttribute("aria-label"))?.focus()},{once:!0}),r(M,t,i),p.length===1&&!p[0][1]&&p[0][0].classList.add("tv-primary"),p.length||m.remove(),i.showModal(),i}export{g as button,d as el,x as icon,L as iconButton,k as labeled,C as menu,N as modal,A as select};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{PivotCache as U,PivotTable as W}from"../pivot/engine.js";import{Workbook as X}from"../core/workbook.js";import{NUM as g,STR as E,BOOL as D,ERR as M}from"../core/sheet.js";import{MAX_COLS as j,MAX_ROWS as q}from"../core/address.js";import{display as z}from"./model.js";import{worksheetTable as H}from"./worksheet-table.js";function Z(_,{rowField:f,columnField:u,valueField:s,agg:k}){const{view:l,table:m}=_;l.refresh();const p=[...new Set([f,u,s].filter(Boolean))],y=p.indexOf(f),d=p.indexOf(u),v=p.indexOf(s);if(y<0||v<0||y===d)throw new Error("Choose different row and column fields.");const B=new Set(l.columns.map(t=>t.field)),G=p.map(t=>{if(!B.has(t))throw new Error("Field unavailable.");const e=m.column(t),r=l.filteredCount,o=new Float64Array(r),n=new Uint8Array(r);m.ensure(e);for(let a=0;a<r;a++){const T=l.perm[a];o[a]=e.raw(T),n[a]=e.kind(T)}return{name:t,nums:o,kinds:n,numFmt:e.format}}),L=U.fromColumns(G,l.filteredCount,m.manager.strings),C=new W(L,{rows:[y],cols:d<0?[]:[d],values:[{field:v,agg:k,name:s}],layout:"tabular"});C.update();const{cells:w,firstDataRow:c,rows:O,cols:b}=C.result.layout;if(O>q||b>j)throw new Error("The pivot exceeds the worksheet dimensions.");const i=new X,h=i.sheet,x=Array.from({length:b},(t,e)=>e===0?f:s),N=k==="count"?"General":m.column(s).format,A=i.styles.derive(0,{numFmt:N}),S=m.column(f).format,R=S&&S!=="General"?i.styles.derive(0,{numFmt:S}):0,P=u?m.column(u).format:null;for(let t=0;t<w.count;t++){const e=w.rows[t],r=w.cols[t],o=w.valueAt(t);if(e===c-1&&r>0&&(x[r]=o==null?s:typeof o=="number"?z(o,P):String(o)),e<c||o==null)continue;const n=typeof o=="number"?g:typeof o=="boolean"?D:typeof o=="string"?E:M;h.setCell(e-c+1,r,n,n===E?i.strings.add(o):n===M?o.index:Number(o)),r>0&&A?h.setStyle(e-c+1,r,A):r===0&&n===g&&R&&h.setStyle(e-c+1,r,R)}return H(i,h,{r0:0,c0:0,r1:O-c,c1:b-1},x)}export{Z as pivotTable};
|