@8sheets/data-grid 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +1 -1
  2. package/api/theme-core.js +2 -0
  3. package/calc/adjust.js +1 -1
  4. package/calc/compile.js +1 -1
  5. package/calc/engine.js +1 -1
  6. package/calc/functions/array.js +1 -1
  7. package/calc/functions/date.js +1 -1
  8. package/calc/functions/dbcs.js +1 -0
  9. package/calc/functions/financial.js +1 -1
  10. package/calc/functions/helpers.js +1 -1
  11. package/calc/functions/index.js +7 -1
  12. package/calc/functions/info.js +1 -1
  13. package/calc/functions/logical.js +1 -1
  14. package/calc/functions/lookup.js +1 -1
  15. package/calc/functions/math.js +1 -1
  16. package/calc/functions/stat.js +1 -1
  17. package/calc/functions/text.js +1 -1
  18. package/calc/parser.js +3 -3
  19. package/calc/values.js +1 -1
  20. package/calcx/culture/custom.js +1 -0
  21. package/calcx/culture/format-locale.js +1 -1
  22. package/calcx/culture/separators.js +1 -0
  23. package/calcx/functions/text.js +1 -1
  24. package/calcx/lang/convert.js +1 -0
  25. package/cells/axis-ops.js +1 -1
  26. package/cells/block.js +1 -0
  27. package/cells/book-css.js +2 -2
  28. package/cells/cell-defaults.js +1 -1
  29. package/cells/cf-engine.js +1 -1
  30. package/cells/consolidate-links.js +1 -1
  31. package/cells/find-engine.js +2 -2
  32. package/cells/format-panes.js +3 -3
  33. package/cells/format-tabs.js +5 -5
  34. package/cells/name-box.js +1 -1
  35. package/cells/outline-column.js +1 -1
  36. package/cells/panes.js +1 -1
  37. package/cells/selection-modes.js +1 -1
  38. package/cells/shift-check.js +1 -0
  39. package/cells/table-rows.js +1 -0
  40. package/cells/text-layout.js +9 -8
  41. package/cells/ui-kit.js +15 -0
  42. package/cells/view-options.js +1 -1
  43. package/celltypes/diagonal.js +1 -1
  44. package/celltypes/dropdowns.js +2 -2
  45. package/core/address.js +1 -1
  46. package/core/autofill.js +1 -0
  47. package/core/axis-styles.js +1 -0
  48. package/core/axis.js +1 -1
  49. package/core/cond-format.js +1 -1
  50. package/core/culture.js +1 -0
  51. package/core/default-names.js +1 -1
  52. package/core/formula-refs.js +1 -1
  53. package/core/input.js +1 -1
  54. package/core/merge.js +1 -0
  55. package/core/numfmt.js +1 -1
  56. package/core/region-input.js +1 -0
  57. package/core/row-fit.js +1 -0
  58. package/core/sheet.js +1 -1
  59. package/core/structure.js +1 -0
  60. package/core/styles.js +1 -1
  61. package/core/tables.js +2 -2
  62. package/core/whatif.js +1 -1
  63. package/core/workbook.js +1 -1
  64. package/datasheets/data-core.js +1 -1
  65. package/datasheets/gantt-paint.js +1 -1
  66. package/datasheets/path-binding.js +2 -2
  67. package/datasheets/rules.js +1 -1
  68. package/datasheets/view.js +2 -2
  69. package/i18n/dom.js +1 -1
  70. package/i18n/en/cells.js +1 -1
  71. package/i18n/en/common.js +1 -1
  72. package/i18n/en/format.js +1 -1
  73. package/i18n/en/shell.js +2 -1
  74. package/i18n/pl/cells.js +1 -1
  75. package/i18n/pl/common.js +1 -1
  76. package/i18n/pl/format.js +1 -1
  77. package/i18n/pl/shell.js +2 -1
  78. package/io/csv.js +8 -8
  79. package/io/plan.js +1 -1
  80. package/io/text-split.js +3 -3
  81. package/io/xlsx-write.js +2 -2
  82. package/objects/chart-model.js +1 -1
  83. package/package.json +1 -1
  84. package/pivot/engine.js +1 -1
  85. package/print/paginate.js +1 -1
  86. package/print/render-page.js +3 -3
  87. package/table-view/api.js +1 -1
  88. package/table-view/cell-editor.js +2 -1
  89. package/table-view/chart.js +1 -0
  90. package/table-view/column-drag.js +1 -1
  91. package/table-view/context-menu.js +1 -0
  92. package/table-view/editors.js +1 -0
  93. package/table-view/events.js +1 -1
  94. package/table-view/files.js +1 -1
  95. package/table-view/fill-handle.js +1 -0
  96. package/table-view/filter-builder.js +1 -0
  97. package/table-view/find.js +1 -0
  98. package/table-view/grid-keys.js +2 -2
  99. package/table-view/labels-de.js +1 -0
  100. package/table-view/labels-es.js +1 -0
  101. package/table-view/labels-fr.js +1 -0
  102. package/table-view/labels-ja.js +1 -0
  103. package/table-view/labels.js +1 -1
  104. package/table-view/model.js +1 -1
  105. package/table-view/mount.js +1 -1
  106. package/table-view/panel.js +1 -1
  107. package/table-view/pivot-spec.js +1 -0
  108. package/table-view/pivot.js +1 -1
  109. package/table-view/public.d.ts +277 -28
  110. package/table-view/reader.worker.js +1 -1
  111. package/table-view/remote.js +1 -1
  112. package/table-view/row-drag.js +1 -0
  113. package/table-view/sparkline.js +1 -0
  114. package/table-view/state-check.js +1 -0
  115. package/table-view/table-css.js +380 -0
  116. package/table-view/version.js +1 -1
  117. package/ui/dialogs.js +3 -3
  118. package/ui/icons.js +1 -1
  119. package/ui/menu-base.js +1 -1
@@ -1 +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};
1
+ import{parseTsv as ht}from"../core/tsv.js";import{cellPosition as Tt,enableGridKeys as Et}from"./grid-keys.js";import{packRecords as Lt}from"./column-input.js";import{applyTableChrome as Ft,readTableChrome as Dt,saveTableChrome as Ot}from"./chrome.js";import{TableClient as et}from"./client.js";import{BlockCache as It}from"./row-cache.js";import{enableColumnDrag as qt,fitWidth as Mt,sizeCell as $}from"./column-drag.js";import{RowSelection as dt}from"./row-selection.js";import{cellFormat as ut,paintCell as ft,rangeOf as Bt}from"./cell-format.js";import{parseQuickFilter as Pt}from"./quick-filter.js";import{columnWindow as Kt,columnsStale as Ht,measureColumns as zt,revealColumn as pt,widenColumns as Wt}from"./column-window.js";import{browserGridLanguage as Ut,loadLanguage as Vt,translator as mt}from"./labels.js";import{button as N,el as h,icon as z,iconButton as M,labeled as g,menu as gt,modal as R,select as k}from"./panel.js";import{rangeRef as J,colIndex as wt,colName as jt}from"../core/address.js";import{usualLanguage as Gt}from"../i18n/index.js";import{formatNumber as Q}from"../core/numfmt.js";import Jt from"./table-css.js";import{cancellable as vt,changedKeys as _t,createEmitter as $t,defaultState as Qt,displayOrder as Yt,stateSnapshot as Zt}from"./events.js";import{DataGridApi as Xt}from"./api.js";import{canEdit as te,toggleCell as ee}from"./cell-editor.js";import{checkChoice as yt,createEditor as bt,editorKind as xt}from"./editors.js";import{enableContextMenu as se}from"./context-menu.js";import{parseSeries as ie,sparklineNode as ne}from"./sparkline.js";import{enableRowDrag as oe,registerSurface as re,rowGrip as le}from"./row-drag.js";import{CHART_TYPES as ae,chartNode as ce,rangeSeries as he,svgFile as de}from"./chart.js";import{FILTER_LABELS as ue,filterBuilder as fe}from"./filter-builder.js";import{stateProblems as pe,stateSchema as me}from"./state-check.js";const ge=[["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"]],_=[["sum","Sum"],["average","Average"],["min","Minimum"],["max","Maximum"],["count","Count"],["distinct","Distinct"]],st=Qt,St={compact:28,normal:34,comfortable:40},we=["editor","options","group"],G=()=>new DOMException("The load was cancelled.","AbortError"),ve=150,it=8,Ct=F=>({...F,columns:F.columns.map(({width:t,rules:e,caption:s,...i})=>({...i,ranged:!!e?.some(n=>n?.type==="bar"||n?.type==="scale")})),filterRow:void 0});async function _e(F,t={}){await Vt(t.language||nt());const e=new ye(F,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 ye{constructor(t,e){this.options={...e},delete this.options.data,this.events=$t(()=>this.options),this.api=new Xt(this),this.language=e.language||nt(),this.t=mt(this.language),this.root=h("section",null,{className:"tv-root",lang:this.language}),this.setDensity(e.density??"normal");for(const n of["copy","cut","paste"])this.root.addEventListener(n,o=>o.stopPropagation());this.setChrome(e.chrome??(e.standalone?Dt():"auto")),this.root.append(h("style",Jt)),t.replaceChildren(this.root),this.sequence=0,this.loadToken=0,this.liveWidths=new Map,this.selection=e.rowSelection?new dt(e.rowSelection):null,this.selectionStatus=h("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=h("header",null,{className:"tv-head"});const s=h("div",null,{className:"tv-identity"}),i=h("span","8",{className:"tv-mark"});i.setAttribute("aria-hidden","true"),this.title=h("h1","Data Grid"),s.append(i,this.title),this.headActions=h("div",null,{className:"tv-actions"}),this.header.append(s,this.headActions),this.fileInput=h("input",null,{type:"file",accept:".csv,.tsv,.txt,.xlsx,.xlsm,.xltx",hidden:!0}),this.fileInput.onchange=()=>this.perform(async()=>{const n=this.fileInput.files[0];this.fileInput.value="",n&&(!this.dirty||confirm(this.t("Save or discard your local edits before replacing this table. Continue?")))&&await this.openFile(n)}),this.toolbar=h("div",null,{className:"tv-tools"}),this.chips=h("div",null,{className:"tv-chips"}),this.content=h("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=h("footer",null,{className:"tv-foot"}),this.status=h("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),re(this),this.content.addEventListener("keydown",n=>{!((n.ctrlKey||n.metaKey)&&!n.altKey&&n.key.toLowerCase()==="f")||this.remote||!this.result||n.target.closest("input, textarea, select, .tv-detail")||(n.preventDefault(),this.perform(()=>this.openFind()))}),this.renderHeader(),this.empty()}get fields(){return this._fields}set fields(t){const e=new Map((this.options.fields??[]).map(s=>[s?.name,s]));this._fields=t?.map(s=>{const i=e.get(s.name);if(!i||i===s)return s;const n={...s};for(const o of we)i[o]!=null&&n[o]==null&&(n[o]=Array.isArray(i[o])?i[o].map(String):i[o]);return n})}setDensity(t){if(!Object.hasOwn(St,t))throw new Error('Density is "compact", "normal" or "comfortable".');return this.density=t,this.rowHeight=St[t],this.root.dataset.density=t,this.root.style.setProperty("--tv-row-h",this.rowHeight+"px"),this.result?(this.continuous&&this.limit!==100&&(this.limit=this.windowSize()),this.measured=null,this.refresh(!1)):Promise.resolve()}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=Zt(this.state),e=this.committed;if(this.committed=t,!e)return;const s=_t(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,n;if(this.virtual)i=Math.min(t.count-1,Math.floor(e/this.stride)),n=Math.min(t.count-1,Math.floor((e+s)/this.stride));else{const o=this.content.getBoundingClientRect(),r=[...this.content.querySelectorAll("tbody tr[data-view]")].filter(l=>{const a=l.getBoundingClientRect();return a.bottom>o.top&&a.top<o.bottom});i=r.length?Number(r[0].dataset.view):t.offset,n=r.length?Number(r.at(-1).dataset.view):t.offset-1}return{firstRow:Math.max(0,i),lastRow:Math.max(-1,n),rowCount:t.count,exact:t.exact!==!1,scrollTop:e,scrollLeft:this.content.scrollLeft}}action(t,e,s,i=""){const n=N(this.t(e),()=>this.perform(s),i);return t.append(n),n}setChrome(t){Ft(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&&Ot(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 n=this.load;n&&(n.superseded=!0,this.endLoad(n,"cancelled"));const o={task:t,label:e,cancel:i,cancelled:!1,started:performance.now(),emitted:0,last:null};o.progress=(l,a)=>this.loadProgress(o,l,a),this.load=o,this.content.setAttribute("aria-busy","true"),this.emit("loadStart",{task:t,label:e});const r=performance.now()-(this.loaderHidden??-1/0)<400?0:ve;o.delay=r,o.timer=setTimeout(()=>this.showLoader(o),r);try{const l=await s(o);if(o.cancelled||o.superseded)throw G();return this.endLoad(o,"done"),l}catch(l){const a=o.cancelled||o.superseded||l?.name==="AbortError";throw this.endLoad(o,a?"cancelled":"failed",a?void 0:l),a?G():l}}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:n=null,loaded:o=null,total:r=null}=e??{};this.emit("loadProgress",{task:t.task,records:n,loaded:o,total:r,fraction:r?Math.min(1,o/r):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=h("div",null,{className:"tv-loader"}),i=h("div",null,{className:"tv-loader-panel"}),n=(this.uid??="tv"+Math.random().toString(36).slice(2,8))+"-loading";i.setAttribute("role","group"),i.setAttribute("aria-labelledby",n);const o=h("span",null,{className:"tv-spinner"});o.setAttribute("aria-hidden","true");const r=h("p",t.label,{className:"tv-loader-title",id:n}),l=h("div",null,{className:"tv-loader-bar"});l.setAttribute("role","progressbar"),l.setAttribute("aria-labelledby",n),l.append(h("span"));const a=h("p","",{className:"tv-loader-detail"});if(i.append(o,r,l,a),t.cancel){const d=N(e("Cancel"),()=>this.cancelLoad(),"tv-loader-cancel");i.append(d)}s.append(i),s.addEventListener("keydown",d=>{d.key==="Escape"&&(d.stopPropagation(),this.cancelLoad())}),this.placeLoader(s),this.root.append(s),t.node=s,this.paintLoader(t),this.status.textContent=t.label+"…";const c=document.activeElement;this.root.contains(c)&&!c.closest("dialog")&&(t.focus=c,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:n=null}=t.last??{},o=e.querySelector(".tv-loader-bar"),r=n?Math.min(1,i/n):null;o.classList.toggle("tv-indeterminate",r==null),r==null?o.removeAttribute("aria-valuenow"):(o.setAttribute("aria-valuemin","0"),o.setAttribute("aria-valuemax","100"),o.setAttribute("aria-valuenow",String(Math.floor(r*100)))),o.firstChild.style.width=r==null?"":r*100+"%";const l=c=>c.toLocaleString(this.language),a=[];s!=null&&a.push(this.t("Records read")+": "+l(s)),r!=null&&a.push(Math.floor(r*100)+"%"),e.querySelector(".tv-loader-detail").textContent=a.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=h("div",null,{className:"tv-empty"});t.append(h("h2",this.t("Open a table")),h("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(G()),this.pendingClient=null}async readFile(t,e,s,i){const n=new et;this.pendingClient?.close(G()),this.pendingClient=n;const o=++this.loadToken;try{const r=await n.call("file",{file:t,csv:e},[],i.progress),l=await n.call("source",{index:0,editable:!1});if(this.closed||o!==this.loadToken)return n.close();this.client?.close(),this.client=n,this.pendingClient=null,this.leaveRemote(),this.file=t,this.csv=e,this.sources=r,this.sourceIndex=0,this.sourceRange=J(r[0].range),this.sourceHeader=r[0].headerRows!==0,this.base=null,this.dirty=!1,this.editable=!1,await this.activate(l,r[0].name,this.fileViewKey(0,J(r[0].range),r[0].headerRows!==0),r[0].initialState),s&&(r.filter(a=>!a.whole).length>1||r.every(a=>a.whole)&&r.length>1)&&this.chooseSource()}catch(r){throw this.client!==n&&n.close(),r}}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 et;this.pendingClient?.close(G()),this.pendingClient=i;const n=this.options.editable===!0;let o,r;try{r=await Lt(t,this.options.fields,()=>this.closed||s!==this.loadToken,(c,d)=>e.progress({records:c,loaded:c,total:d})),r&&(t=r.columns);const l=Array.isArray(t)?t.length:Object.values(t).find(c=>c?.length!=null)?.length;e.progress({records:l??null,loaded:null,total:null},!0);const a=(r||this.options.transferColumns)&&!Array.isArray(t)?[...new Set(Object.values(t).filter(c=>ArrayBuffer.isView(c)&&c.buffer instanceof ArrayBuffer).map(c=>c.buffer))]:[];o=await i.call("data",{data:t,strings:r?.strings,fields:be(this.options.fields),editable:n},a)}catch(l){throw i.close(),l}if(this.closed||s!==this.loadToken)return i.close();this.client?.close(),this.client=i,this.pendingClient=null,this.leaveRemote(),this.editable=n,this.file=null,this.sources=null,this.base=null,this.dirty=!1,await this.activate(o,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,n=st(i),o=await s.query({state:n,offset:0,limit:100,columnOffset:0,columnLimit:this.columnLimit,signal:t.signal});this.closed||e!==this.loadToken||(this.pendingClient?.close(G()),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([Ct(n),0]),page:o},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(n=>n.name)]):null,this.state=i??st(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(n=>({...n}))})}chooseSource(){const t=this.t;R(this.root,t("Choose source"),t,(e,s)=>{const i=k(this.sources.map((l,a)=>[String(a),l.name+" · "+J(l.range)]),String(this.sourceIndex)),n=h("input"),o=h("input",null,{type:"checkbox",checked:!0}),r=()=>{const l=this.sources[Number(i.value)];n.value=J(l.range),n.disabled=!l.whole,o.disabled=!l.whole,o.checked=l.headerRows!==0};if(r(),i.onchange=r,e.append(g(t("Source"),i),g(t("Range"),n),g(t("First row contains headers"),o)),/\.(csv|tsv|txt)$/i.test(this.file.name)){const l=k([["",t("Automatic")],[",",","],[";",";"],[" ","Tab"],["|","|"]],this.csv.delimiter||""),a=h("input",null,{value:(this.csv.textColumns||[]).map(jt).join(", "),placeholder:"A, C"});e.append(g(t("Delimiter"),l),g(t("Read columns as text"),a)),s("Reimport CSV",async()=>{const c=a.value.trim()?a.value.toUpperCase().split(/[,\s]+/).filter(Boolean):[];if(c.some(d=>!/^([A-Z]{1,3})$/.test(d)||wt(d)>=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:l.value,textColumns:c.map(wt)})})}s("Apply",()=>this.applySource(Number(i.value),n.value,o.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 n={index:this.sourceIndex,range:this.sourceRange,header:this.sourceHeader};await this.track("source",this.t("Opening")+" "+i.name,async o=>{const r=await this.client.call("source",{index:t,range:i.whole?e:void 0,header:s!==!1,editable:this.editable});if(o.cancelled){const l=this.sources[n.index];await this.client.call("source",{index:n.index,range:l.whole?n.range:void 0,header:n.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(r,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(n){if(e!==this.sequence||this.closed)return;throw n}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 It({fetch:(a,c,d)=>this.remote.query({state:e.state,offset:a,limit:c,columnOffset:e.columnOffset,columnLimit:this.columnLimit,signal:d}),onLoad:()=>{this.closed||!e.meta||(this.result&&!this.result.loading&&e.covers(this.offset,this.limit)?this.growRemote():this.perform(()=>this.refresh(!1)))},onError:a=>{e.error=a,!this.closed&&(this.status.textContent=this.t(a.message),this.emit("error",a))}}),s=this.getState(),i=JSON.stringify([Ct(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:a,limit:c}=this;this.settleTimer=setTimeout(()=>e.request(a,c),90)}this.offset>=e.count&&(this.offset=Math.max(0,e.count-this.limit));const{rows:n,missing:o}=e.window(this.offset,this.limit),r=e.meta,l=s.groups.length>0;return{...r,rows:n,offset:this.offset,count:e.count,exact:e.exact,loading:o,matches:Number.isSafeInteger(r.matches)?r.matches:e.exact&&!l?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(this.rowHeight,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 n=this.content.querySelector("tbody tr.tv-spacer:last-child td"),o=this.detailHeight(e.offset+e.rows.length,1/0);n&&(n.style.height=Math.max(0,s*(t.count-e.offset)-e.rows.length*this.rowHeight+o)+"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/this.rowHeight)+2*it)):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(n=>n.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 o=e;if(t==="paste"){if(this.result.loading)throw new Error("Wait for the records to load.");const l=this.result.rows.filter(p=>p.id!==void 0),a=this.result.columns,c=l.findIndex(p=>p.id===e.id),d=a.indexOf(e.field);if(c<0||d<0||c+e.lines.length>l.length||e.lines.some(p=>d+p.length>a.length))throw new Error("Paste exceeds the available records or columns.");const f=Array.from({length:e.lines.length*(e.repeat??1)},(p,v)=>e.lines[v%e.lines.length]);if(c+f.length>l.length)throw new Error("Paste exceeds the available records or columns.");o={cells:f.flatMap((p,v)=>p.map((x,w)=>({id:l[c+v].id,field:a[d+w],value:x})))}}else if(t!=="edit")throw new Error("Use the record editor for this source.");const r=await this.remoteUpdate(o);return this.emit("change",{action:t,...o,revision:r?.revision??o.revision,source:s}),!0}const n=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:n,source:s}),n):(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 n=vt({...structuredClone(e),source:s});if(!this.emit(i,n))return null;const{source:o,...r}=n;return r}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(n=>(n.title||n.textContent)===s)?.focus()}),e.replaceChildren();const i=h("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[n,o]of[["Filter",()=>this.filterDialog()],["Sort",()=>this.orderDialog(!1)],["Group",()=>this.orderDialog(!0)],["Summary",()=>this.summaryDialog()],["Columns",()=>this.columnsDialog()]])this.action(e,n,o);for(const[n,o,r,l]of[["filterRow","Filter row","filter-row",()=>this.toggleFilterRow()],["totalsRow","Totals","sigma",()=>this.toggleTotals()]]){const a=this.action(e,o,l,"tv-toggle");a.replaceChildren(z(r),h("span",t(o),{className:"tv-label"})),a.setAttribute("aria-pressed",String(!!this.state[n])),a.title=t(o)}if((!this.remote||this.remote.pivot)&&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.remote&&this.result){const n=this.action(e,"Find",()=>this.openFind());n.replaceChildren(z("search"),h("span",t("Find"),{className:"tv-label"})),n.title=t("Find in cells")}if(this.storageKey&&this.action(e,"Views",()=>this.viewsDialog()),typeof this.options.assistant=="function"&&this.result){const n=this.action(e,"Ask",()=>this.assistantDialog());n.replaceChildren(z("sparkle"),h("span",t("Ask"),{className:"tv-label"})),n.title=t("Ask for a view in your own words")}this.editable&&!this.remote&&(this.action(e,"Calculated field",()=>this.formulaDialog()),this.action(e,"Add record",()=>this.addRecordDialog()))}describeFilter(t){const e=this.t;if(Array.isArray(t.any)||Array.isArray(t.all))return e(t.any?"any of":"all of")+": "+(t.any??t.all).map(r=>this.describeFilter(r)).join(t.any?" | ":" & ");const s=this.fields.find(r=>r.name===t.field),i=this.columnCaption(t.field),n=r=>typeof r=="number"&&s?.format?Q(s.format,r):String(r);if(t.op==="in"||t.op==="notIn")return i+" "+e(t.op==="in"?"is one of":"is none of")+" "+(t.values??[]).map(n).join(", ");const o=ue[t.op]??ge.find(r=>r[0]===t.op)?.[1]??t.op;return[i,e(o).toLowerCase(),t.value,t.op==="between"||t.op==="notBetween"?t.value2:null].filter(r=>r!=null&&r!=="").join(" ")}renderChips(){const t=this.t;this.chips.replaceChildren();let e=0;const s=(o,r,l,a)=>{const c=h("span",null,{className:"tv-chip tv-chip-"+o});c.append(h("span",t(r),{className:"tv-chip-kind"}),h("span",l)),c.append(M("close",t("Remove")+" · "+t(r)+" "+l,()=>this.perform(a))),this.chips.append(c),e++};for(const[o,r]of[["filters","Filter"],["sort","Sort"],["groups","Group"]])this.state[o].forEach((l,a)=>{const c=o==="filters"?this.describeFilter(l):this.columnCaption(l.field)+(o==="sort"?" "+t(l.desc?"Descending":"Ascending").toLowerCase():"");s(o,r,c.trim(),()=>this.update({[o]:this.state[o].filter((d,f)=>a!==f),collapsed:[]}))});const i=this.state.tree;i&&s("tree","Tree",i.level?this.columnCaption(i.level):this.columnCaption(i.parent)+" → "+this.columnCaption(i.key??""),()=>this.setTree(null));const n=(this.state.pinnedRows?.top?.length??0)+(this.state.pinnedRows?.bottom?.length??0);n&&s("pinned","Pinned",n+" "+t(n===1?"row":"rows"),()=>this.applyLayout({pinnedRows:void 0})),e>1&&this.action(this.chips,"Clear all",()=>this.update({filters:[],sort:[],groups:[],collapsed:[],tree:void 0,treeCollapsed:[]}),"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,n=i.sort.find(d=>d.field===t),o=i.groups.some(d=>d.field===t),r=i.columns.find(d=>d.field===t)?.pinned,l=d=>()=>this.perform(d),a=d=>l(()=>this.update({sort:[{field:t,desc:d},...i.sort.filter(f=>f.field!==t)]})),c=i.columns.filter(d=>!d.hidden).length;gt(this.root,e,[[s("Sort ascending"),a(!1),{icon:"up",checked:!!n&&!n.desc}],[s("Sort descending"),a(!0),{icon:"down",checked:!!n?.desc}],n?[s("Clear sort"),l(()=>this.update({sort:i.sort.filter(d=>d.field!==t)}))]:!1,null,[s("Filter")+"…",()=>this.filterDialog(t),{icon:"filter"}],[s(o?"Ungroup":"Group by"),l(()=>this.update({groups:o?i.groups.filter(d=>d.field!==t):[...i.groups,{field:t}],collapsed:[]})),{icon:"group"}],null,[s(r?"Unpin":"Pin"),l(()=>this.update({columns:i.columns.map(d=>d.field===t?{...d,pinned:!r}:d)})),{icon:"pin"}],[s("Hide column"),l(()=>this.update({columns:i.columns.map(d=>d.field===t?{...d,hidden:!0}:d)})),{icon:"hide",disabled:c<=1}],[s("Autosize column"),l(()=>this.autosizeColumn(t)),{icon:"fit"}],[s("Rename column")+"…",()=>this.renameColumn(t),{icon:"rename"}],null,[s("Conditional formatting")+"…",()=>this.formatDialog(t),{icon:"palette"}],[s("Sparkline")+"…",()=>this.sparklineDialog(t),{icon:"chart",checked:!!i.columns.find(d=>d.field===t)?.sparkline}]].filter(d=>d!==!1))}filterDialog(t){return fe(this,t)}orderDialog(t){const e=this.t,s=t?"groups":"sort";R(this.root,e(t?"Group by":"Sort by"),e,(i,n)=>{const o=this.fieldSelect(),r=k([["asc",e("Ascending")],["desc",e("Descending")]]);i.append(g(e("Field"),o)),t||i.append(g(e("Order"),r)),t&&this.action(i,"Show as tree…",()=>this.treeDialog(),"tv-link"),n(t?"Add group":"Add sort",()=>this.update({[s]:[...this.state[s].filter(l=>l.field!==o.value),{field:o.value,desc:r.value==="desc"}],collapsed:[]}))})}summaryDialog(){const t=this.t;R(this.root,t("Summary"),t,(e,s)=>{const i=this.fieldSelect(this.state.total?.field??"",!0),n=k(_.map(([o,r])=>[o,t(r)]),this.state.total?.agg);e.append(g(t("Field"),i),g(t("Summary"),n)),s("Apply",()=>this.update({total:i.value?{field:i.value,agg:n.value}:null}))})}columnsDialog(){const t=this.t,e=structuredClone(this.state.columns);R(this.root,t("Columns"),t,(s,i)=>{const n=h("div");s.append(n);const o=()=>{n.replaceChildren(),e.forEach((l,a)=>{const c=h("div",null,{className:"tv-column"}),d=h("input",null,{type:"checkbox",checked:!l.hidden});d.onchange=()=>{l.hidden=!d.checked};const f=h("input",null,{type:"number",min:48,max:800,value:l.width??"",placeholder:"px"});f.setAttribute("aria-label",t("Width")+" "+l.field),f.onchange=()=>{l.width=f.value?Math.max(48,Math.min(800,Number(f.value))):void 0};const p=h("input",null,{value:l.format??this.fields.find(b=>b.name===l.field)?.format??"General"});p.title=t("Format"),p.setAttribute("aria-label",t("Format")+" "+l.field),p.onchange=()=>{l.format=p.value||"General"};const v=h("input",null,{type:"checkbox",checked:!!l.pinned});v.onchange=()=>{l.pinned=v.checked};const x=b=>{e.splice(a,1),e.splice(a+b,0,l),o()},w=N("↑",()=>x(-1)),S=N("↓",()=>x(1));w.disabled=a===0,S.disabled=a===e.length-1,w.setAttribute("aria-label",t("Move up")+" "+l.field),S.setAttribute("aria-label",t("Move down")+" "+l.field),c.append(g(l.field,d),g(t("Pin"),v),f,p,w,S),n.append(c)})};o();const r=k([["compact",t("Compact")],["normal",t("Normal")],["comfortable",t("Comfortable")]],this.density);s.append(g(t("Row height"),r)),i("Apply",async()=>{r.value!==this.density&&await this.setDensity(r.value),await this.update({columns:e})})})}renameColumn(t){const e=this.t,i=[...this.content.querySelectorAll("thead tr.tv-heading-row th[data-field]")].find(l=>l.dataset.field===t)?.querySelector(".tv-sort");if(!i){R(this.root,e("Rename column"),e,(l,a)=>{const c=h("input",null,{value:this.columnCaption(t)});l.append(g(e("Column name"),c)),a("Apply",()=>this.setColumnCaption(t,c.value))});return}const n=h("input",null,{value:this.columnCaption(t),className:"tv-rename",size:6,spellcheck:!1});n.setAttribute("aria-label",e("Column name")),i.replaceWith(n),n.focus(),n.select();let o=!1;const r=l=>{o||(o=!0,l&&n.value.trim()&&n.value.trim()!==this.columnCaption(t)?this.perform(()=>this.setColumnCaption(t,n.value)):this.renderRows())};n.addEventListener("keydown",l=>{l.stopPropagation(),l.key==="Enter"?(l.preventDefault(),r(!0)):l.key==="Escape"&&(l.preventDefault(),r(!1))}),n.addEventListener("blur",()=>r(!0));for(const l of["pointerdown","click","dblclick"])n.addEventListener(l,a=>a.stopPropagation())}setColumnCaption(t,e){const s=String(e??"").trim(),i=this.fields.find(r=>r.name===t)?.caption||t,o=(this.state.columns.some(r=>r.field===t)?this.state.columns:[...this.state.columns,{field:t}]).map(r=>{if(r.field!==t)return r;const{caption:l,...a}=r;return s&&s!==i?{...a,caption:s}:a});return this.applyLayout({columns:o})}sparklineDialog(t){const e=this.t,s=this.state.columns.find(i=>i.field===t)?.sparkline;R(this.root,e("Sparkline")+" · "+this.columnCaption(t),e,(i,n)=>{const o=k([["line",e("Line")],["column",e("Column")],["winloss",e("Win/loss")]],s?.type??"line");i.append(g(e("Type"),o),h("p",e("Draw the numbers in the cell, or the values of these fields:"),{className:"tv-muted"}));const r=h("div",null,{className:"tv-values"}),l=this.fields.filter(a=>a.type==="number").map(a=>{const c=h("input",null,{type:"checkbox",checked:!!s?.fields?.includes(a.name)});return r.append(g(this.columnCaption(a.name),c)),[c,a.name]});i.append(r),s&&n("Remove sparkline",()=>this.setColumnSparkline(t,null),"danger"),n("Apply",()=>{const a=l.filter(([c])=>c.checked).map(([,c])=>c);return this.setColumnSparkline(t,{type:o.value,...a.length&&{fields:a}})},"primary")})}setColumnSparkline(t,e){const i=(this.state.columns.some(n=>n.field===t)?this.state.columns:[...this.state.columns,{field:t}]).map(n=>{if(n.field!==t)return n;const{sparkline:o,...r}=n;return e?{...r,sparkline:e}:r});return this.applyLayout({columns:i})}async askAssistant(t){const e=this.options.assistant;if(typeof e!="function")throw new Error("Asking needs the assistant option.");if(!this.result)throw new Error("No table loaded.");const s=this.fields.map(({name:o,caption:r,type:l,format:a})=>({name:o,caption:r,type:l,format:a})),i=await e({prompt:String(t??""),state:this.getState(),fields:s,schema:me(s),language:this.language}),n=i?.state??null;if(n!=null){const o=pe(n,s);if(o.length)throw new Error(this.t("The answer could not be applied.")+" "+o.slice(0,3).join(" "));const r=structuredClone(n);if(r.columns){const l=new Set(r.columns.map(a=>a.field));r.columns=[...r.columns,...this.state.columns.filter(a=>!l.has(a.field))]}r.tree&&(r.groups=[]),await this.update({...r,collapsed:r.collapsed??[]})}return{state:n,message:typeof i?.message=="string"?i.message:""}}assistantDialog(){const t=this.t;R(this.root,t("Ask"),t,e=>{const s=h("textarea",null,{rows:3,placeholder:t("For example: revenue by region for 2026, largest first")});s.setAttribute("aria-label",t("Ask for a view in your own words"));const i=h("p",null,{className:"tv-assistant-reply"});i.setAttribute("aria-live","polite");const n=N(t("Ask"),async()=>{if(!(!s.value.trim()||n.disabled)){n.disabled=!0,i.textContent=t("Thinking…");try{const{state:o,message:r}=await this.askAssistant(s.value);i.textContent=r||(o?t("Done."):""),o&&!r&&n.closest("dialog")?.close()}catch(o){i.textContent=t(o.message),this.emit("error",o)}finally{n.disabled=!1}}},"tv-primary");s.addEventListener("keydown",o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),n.click())}),e.append(g(t("Ask for a view in your own words"),s),i,n)})}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);R(this.root,t("Saved views"),t,(i,n)=>{const o=h("div");i.append(o);for(const[l,a]of e){const c=h("div",null,{className:"tv-column"});c.append(h("strong",l),N(t("Restore"),()=>this.perform(async()=>{await this.setState(a),c.closest("dialog").close()})),N(t("Remove"),()=>{e.delete(l),s(),c.remove()})),o.append(c)}e.size||(o.textContent=t("No saved views"));const r=h("input");i.append(g(t("View name"),r)),n("Reset view",()=>this.setState(st(this.fields))),n("Save view",()=>{if(!r.value.trim())throw new Error(t("View name"));e.set(r.value.trim(),this.getState()),s()},"primary")})}pivotDialog(){const t=this.t,e=this.state.columns.filter(n=>!n.hidden).map(n=>[n.field,this.columnCaption(n.field)]),s=n=>this.fields.find(o=>o.name===n)?.type,i=[["normal",t("No calculation")],["percentOfTotal",t("% of grand total")],["percentOfCol",t("% of column total")],["percentOfRow",t("% of row total")],["runTotal",t("Running total")],["rankDescending",t("Rank, largest first")],["rankAscending",t("Rank, smallest first")],["index",t("Index")]];R(this.root,t("Pivot"),t,(n,o)=>{const r=k(e),l=k([["",t("None")],...e]),a=k([["",t("None")],...e]),c=b=>e.some(([q])=>q===b),d=this.state.groups.map(b=>b.field).find(c)??e.map(([b])=>b).find(b=>s(b)==="string");d&&(r.value=d),n.append(g(t("Rows"),r),g(t("Then by"),l),g(t("Columns"),a));const f=h("div",null,{className:"tv-pivot-values"}),p=[],v=(b,q="sum",P="normal")=>{const K=h("div",null,{className:"tv-column"}),C=k(e,b),T=k(_.filter(([U])=>U!=="distinct").map(([U,A])=>[U,t(A)]),q),D=k(i,P);C.setAttribute("aria-label",t("Value")),T.setAttribute("aria-label",t("Summary")),D.setAttribute("aria-label",t("Show values as"));const H={f:C,a:T,c:D},W=M("close",t("Remove"),()=>{p.length!==1&&(p.splice(p.indexOf(H),1),K.remove())});K.append(C,T,D,W),f.append(K),p.push(H)},x=this.state.total?.field,w=x&&c(x)&&s(x)==="number"?x:this.fields.find(b=>b.type==="number"&&c(b.name))?.name;v(w??e[0]?.[0],this.state.total&&this.state.total.agg!=="distinct"?this.state.total.agg:"sum");const S=N(t("Add value"),()=>v(this.fields.find(b=>b.type==="number"&&c(b.name))?.name??e[0]?.[0]));S.classList.add("tv-add-rule"),n.append(h("span",t("Values"),{className:"tv-form-heading"}),f,S),o("Apply",()=>this.openPivot({rows:[r.value,l.value].filter(Boolean),columns:[a.value].filter(Boolean),values:p.map(({f:b,a:q,c:P})=>({field:b.value,agg:q.value,showAs:P.value}))}))})}async openPivot(t){if(this.base)throw new Error("Go back to the records first.");if(this.remote&&!this.remote.pivot)throw new Error("A pivot needs local records.");if(!this.fields||!this.client&&!this.remote)throw new Error("No table loaded.");const e=this.remote,s=new AbortController;await this.track("pivot",this.t("Building pivot"),async i=>{let n;if(e){const o=await e.pivot({state:this.getState(),spec:structuredClone(t),signal:s.signal});if(!Array.isArray(o?.fields)||!Array.isArray(o?.rows))throw new Error("Invalid table response.");const r=new et;if(n=await r.call("data",{data:o.rows,fields:o.fields,editable:!1}),i.cancelled)return r.close();this.client=r}else if(n=await this.client.call("pivot",t),i.cancelled)return this.client.call("records");this.base={title:this.title.textContent,state:this.getState(),key:this.storageKey,editable:this.editable,remote:e},this.remote=null,this.rows?.reset(),this.rows=null,this.editable=!1,await this.activate(n,this.base.title+" · "+this.t("Pivot"),null)},()=>s.abort())}async closePivot(){const t=this.base;t&&(this.base=null,this.editable=t.editable,t.remote?(this.client?.close(),this.client=null,this.remote=t.remote,this.fields=this.options.fields):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}))}))}async chartDialog(t){const e=this.result.columns.filter(o=>this.fields.find(r=>r.name===o)?.type==="number");if(!e.length)throw new Error("No data");const s=t&&e.includes(t)?t:e.at(-1),i=async o=>{const r=await this.client.call("chart",{field:o});return{data:{categories:r.map(l=>l.label),series:[{name:this.columnCaption(o),values:r.map(l=>l.value)}]},format:this.fieldIndex.get(o)?.format}},n=await i(s);this.showChart(this.t("Top 20 by absolute value"),n.data,n.format,"bar",{fields:e.map(o=>[o,this.columnCaption(o)]),value:s,load:i})}addRecordDialog(){const t=this.t;R(this.root,t("Add record"),t,(e,s)=>{const i=new Map;for(const n of this.fields.filter(o=>o.editable)){const o=n.type==="boolean"&&n.editor!=="checkbox"?(()=>{const r=k([["",""],["true","TRUE"],["false","FALSE"]]);return{kind:"text",node:r,focus:r,read:()=>r.value}})():bt(n,{raw:null,text:"",t});e.append(kt(n.caption||n.name,o)),i.set(n.name,{field:n,editor:o})}s("Add",()=>{const n={};for(const[o,{field:r,editor:l}]of i){const a=l.read();if(a===""||a===!1)continue;const c=yt(r,l.kind,a);if(c)throw new Error(c);n[o]=a}return this.change("add",{records:[n]})})})}formulaDialog(){const t=this.t;R(this.root,t("Calculated field"),t,(e,s)=>{const i=h("input"),n=h("input",null,{placeholder:"=[@Units]*[@Price]"});e.append(g(t("Name"),i),g(t("Formula"),n)),s("Add",()=>this.addCalculatedField(i.value,n.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||(Ht(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/this.rowHeight),i=this.windowSize(),n=this.rowTop(this.content.scrollTop),o=Math.floor(n/this.stride);if((o>=this.offset+2||this.offset===0)&&(o+s<=this.offset+this.limit-2||this.offset+this.limit>=t.count)&&this.limit>=i)return;const l=Math.min(Math.max(0,t.count-i),Math.max(0,o-it));this.offset===l&&this.limit===i||(this.offset=l,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=h("table");s.setAttribute("aria-label",this.title.textContent);const i=s.createTHead();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 n=this.fieldIndex,o=this.colWindow=Kt(this,t),r=u=>{const m=h(u,null,{className:"tv-gap"});return m.setAttribute("aria-hidden","true"),m},l=this.columnBands();l&&this.renderBands(i,o,t,l);const a=i.insertRow();a.className="tv-heading-row";const c=h("th",null,{scope:"col",className:"tv-row-action"});c.append(h("span",e("Details"),{className:"tv-sr"})),this.selection?.mode==="multiple"&&c.prepend(this.selectAllBox()),a.append(c);const d=t.columns.map(u=>this.columnCaption(u));for(const u of o.slots){if(typeof u=="object"){a.append(r("th"));continue}const m=t.columns[u],y=h("th",null,{scope:"col"}),E=this.state.sort.find(X=>X.field===m),j=this.state.sort.indexOf(E);j===0&&y.setAttribute("aria-sort",E.desc?"descending":"ascending");const L=d[u],O=N(L,X=>this.perform(()=>{const tt={field:m,desc:E?!E.desc:!1},at=this.state.sort,Nt=E?at.map(ct=>ct.field===m?tt:ct):[...at,tt];return this.update({sort:X.shiftKey?Nt:[tt]})}));O.className="tv-sort",O.title=e("Shift-click to sort by another column"),E?(y.classList.add("tv-sorted"),O.append(z(E.desc?"down":"up")),this.state.sort.length>1&&O.append(h("sup",String(j+1),{className:"tv-sort-order"})),O.setAttribute("aria-label",L+", "+e(E.desc?"Descending":"Ascending"))):O.append(h("span",null,{className:"tv-sort-space"})),n.get(m)?.type==="number"&&y.classList.add("tv-number"),y.append(O),y.dataset.field=m,$(y,this.columnWidth(m));const B=M("chevron",e("Column menu")+" · "+L,()=>this.columnMenu(m,B),"tv-field-menu");B.setAttribute("aria-haspopup","menu"),B.setAttribute("aria-expanded","false");const I=h("span",null,{className:"tv-resize"});I.setAttribute("aria-hidden","true"),I.title=e("Drag to resize, double-click to fit"),y.append(B,I),a.append(y)}this.state.filterRow&&this.renderFilterRow(s);const f=t.columns.map(u=>this.columnWidth(u)),p=this.rtl??=getComputedStyle(this.root).direction==="rtl",v=t.columns.map((u,m)=>{const y=this.columnIndex.get(u)?.rules;return y?.length?{rules:y,range:t.stats?.[u]??Bt(t.rows,m)}:null}),x={r:t,win:o,widths:f,formats:v,rtl:p,captions:d,numeric:t.columns.map(u=>n.get(u)?.type==="number"),toggles:t.columns.map(u=>te(this,u)&&xt(n.get(u))==="checkbox"),sparks:t.columns.map(u=>this.columnIndex.get(u)?.sparkline??null),renderers:t.columns.map(u=>this.options.renderers?.[u]),tree:!!this.state.tree,needle:this.finder?.text?this.finder.text.toLowerCase():"",current:this.finder?.current??null,flashes:this.flashes?.size?this.flashes:null,now:performance.now()},w=s.createTBody();this.virtual=this.continuous&&t.count>100;const S=Math.min(this.rowHeight,8e6/Math.max(1,t.count)),b=this.virtual&&this.stride&&S!==this.stride?S/this.stride:1;this.stride=S,s.classList.toggle("tv-virtual",this.virtual);const q=u=>{if(u<=0)return;const m=w.insertRow();m.className="tv-spacer",m.setAttribute("aria-hidden","true");const y=m.insertCell();y.colSpan=t.columns.length+1,y.style.height=u+"px"},P=this.detailHeight(0,t.offset),K=this.detailHeight(t.offset+t.rows.length,1/0);this.virtual&&q(t.offset*this.stride+P);let C=t.offset-1;const T=[];for(const u of t.rows){C++;const m=w.insertRow();if(m.dataset.view=C,u.loading){m.className="tv-loading",m.insertCell();for(const L of o.slots){const O=m.insertCell();typeof L=="number"&&O.append(h("span",null,{className:"tv-skeleton"}))}continue}if(u.group!==void 0){m.className="tv-group";const L=this.state.total?o.slots.indexOf(t.columns.indexOf(this.state.total.field)):-1,O=m.insertCell();O.colSpan=L>0?L+1:o.slots.length+1;const B=N(u.group,()=>this.perform(async()=>{if(this.remote){const I=new Set(this.state.collapsed);I.has(u.path)?I.delete(u.path):I.add(u.path),await this.update({collapsed:[...I]})}else{const I=await this.client.call("toggle",{index:u.index,offset:this.offset,limit:this.limit});this.state.collapsed=I.collapsed,await this.refresh(!1)}}));if(B.className="tv-group-toggle",B.prepend(z(u.collapsed?"chevron-right":"chevron")),B.style.marginInlineStart=u.level*16+"px",B.setAttribute("aria-expanded",String(!u.collapsed)),O.append(B),L>0){const I=m.insertCell();I.className="tv-number tv-group-total",I.textContent=u.summary,L<o.slots.length-1&&(m.insertCell().colSpan=o.slots.length-1-L)}else u.summary&&O.append(h("strong",u.summary,{className:"tv-group-total"}));continue}const y=m.insertCell();if(y.className="tv-row-action",this.options.rowDrag&&y.append(le(this,u)),this.selection){const L=this.selectionBox(u);y.append(L),m.classList.toggle("tv-row-selected",L.checked)}this.options.rowNumbers&&y.append(h("span",String(u.number??C+1),{className:"tv-row-number"})),this.options.detailRenderer&&y.append(this.expandButton(u,C));const E=N(null,()=>this.perform(()=>this.details(u)),"tv-icon-btn tv-open-btn");E.setAttribute("aria-label",e("Record details")+" "+(u.values[0]||u.id)),y.append(E),m.dataset.recordIndex=T.length,T.push(this.drawCells(m,u,x,C)),m.ondblclick=()=>this.perform(()=>this.details(u));const j=this.opened.get(u.id);j&&j.index===C&&this.renderDetail(w,t.columns.length+1,j)}this.virtual&&q(this.stride*(t.count-t.offset)-t.rows.length*this.rowHeight+K);for(const u of t.pinned?.top??[])this.drawPinned(i.insertRow(),u,x,"top");if(t.pinned?.bottom?.length){const u=s.createTFoot();for(const m of t.pinned.bottom)this.drawPinned(u.insertRow(),m,x,"bottom")}if(this.state.totalsRow&&this.renderTotals(s,f),o.fixed){Wt(this,t,o);const u=h("colgroup"),m=y=>{const E=h("col");E.style.width=y+"px",u.append(E)};m(o.fixed.lead);for(const y of o.slots)m(typeof y=="object"?y.gap:o.fixed.widths[y]);s.prepend(u),s.style.tableLayout="fixed",s.style.width=o.fixed.total+"px"}const D=this.range,H=document.activeElement,W=this.content.contains(H)?Tt(H):null,U=W?{id:this.grid?.records[W.row]?.id,col:W.col,step:{row:0,col:0},quiet:!0}:null;s.columnAt=[-1,...o.slots.map(u=>typeof u=="number"?u:-1)],this.grid=Et(this,s,T);const A=this.focusAfter??U;this.focusAfter=null;const Rt=this.content.scrollLeft,At=this.content.scrollTop,ot=this.content.contains(document.activeElement)?document.activeElement:null,rt=ot?.dataset.focus,Y=ot?.selectionStart;this.content.replaceChildren(s);const lt=o.measure&&T.length?T[0].find(Boolean):null;if(lt&&zt(this,t,a,o.measure,lt),this.stickRows(s),A?.view!=null&&this.grid){const u=Math.max(0,Math.min(t.count-1,A.view)),m=t.rows[u-t.offset],y=m?this.grid.records.indexOf(m):-1;y>=0?this.grid.focusAt(y,A.col):!m&&(A.tries??0)<8&&(this.focusAfter={...A,view:u,tries:(A.tries??0)+1})}else if(A?.step&&this.grid){const u=this.grid.records.findIndex(m=>m.id===A.id);u>=0&&this.grid.focusAt(u+A.step.row,A.col+A.step.col,A.quiet)}if(D&&(!A||A===U)){const u=this.grid?.positionOf(D.anchor.id,D.anchor.field),m=this.grid?.positionOf(D.focus.id,D.focus.field);u&&m&&this.grid.cells[u.row][u.col]&&this.grid.cells[m.row][m.col]?this.grid.select(u,m,!!W):this.setRange(null)}for(const u of s.querySelectorAll("tr.tv-detail"))u.entry&&(u.entry.height=u.offsetHeight);if(rt){const u=[...s.querySelectorAll("[data-focus]")].find(m=>m.dataset.focus===rt);u&&(u.focus({preventScroll:!0}),Y!=null&&u.setSelectionRange&&u.setSelectionRange(Y,Y))}const Z=this.root.querySelector(".tv-menu");if(Z&&!Z.anchor?.isConnected&&Z.dispatchEvent(new Event("tv-close")),!t.rows.length){const u=h("div",null,{className:"tv-empty"});u.append(h("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=Rt,this.content.scrollTop=At*b,s.setAttribute("aria-busy",String(!!t.loading)),this.positionPinned(s),qt(this,s),se(this,s),this.options.rowDrag&&oe(this,s),this.selectionSummary=h("output",null,{className:"tv-selection-summary"}),this.selectionSummary.setAttribute("aria-live","polite"),this.footer.replaceChildren(),this.footer.append(h("strong",this.countText(t)),this.selectionStatus),this.state.total&&this.footer.append(h("span",e(_.find(u=>u[0]===this.state.total.agg)?.[1]||"Summary")+" · "+this.columnCaption(this.state.total.field)+" "+t.summary));const V=h("div",null,{className:"tv-actions"});if(t.count>100&&this.action(V,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(V,"Previous",()=>this.page(-1));u.disabled=!t.offset,V.append(h("span",e("Page")+" "+(Math.floor(t.offset/this.limit)+1)+" / "+(t.exact===!1?"?":Math.max(1,Math.ceil(t.count/this.limit)))));const m=this.action(V,"Next",()=>this.page(1));m.disabled=t.offset+this.limit>=t.count}if(t.columnCount>this.columnLimit)for(const[u,m]of[["←",-1],["→",1]]){const y=this.action(V,u,()=>(this.columnOffset+=m*this.columnLimit,this.refresh(!1)));y.setAttribute("aria-label",e("Columns")+" "+e(m<0?"Previous":"Next")),y.disabled=m<0?!this.columnOffset:this.columnOffset+this.columnLimit>=t.columnCount}this.footer.append(this.selectionSummary,V)}drawCells(t,e,s,i){const{r:n,win:o,widths:r,formats:l}=s,a=new Array(n.columns.length);for(const c of o.slots){if(typeof c=="object"){t.insertCell().className="tv-gap";continue}const d=e.values[c]??"",f=t.insertCell();a[c]=f;const p=n.columns[c],v=s.renderers[c],x=s.sparks[c];if(typeof v=="function"){const w=v({id:e.id,field:p,text:d});w instanceof Node?f.replaceChildren(w):f.textContent=w==null?d:String(w)}else if(x){const w=e.series?.[p]??ie(e.raw?.[c]??d);f.append(ne(x.type,w,{label:s.captions[c],width:Math.max(40,(r[c]??this.measured?.widths.get(p)??120)-26),height:Math.max(14,this.rowHeight-14)})),f.classList.add("tv-spark-cell")}else if(s.toggles[c]&&i!=null){const w=e.raw?.[c]===!0||/^(true|yes|1)$/i.test(d),S=h("input",null,{type:"checkbox",checked:w,tabIndex:-1,className:"tv-cell-check"});S.setAttribute("aria-label",s.captions[c]),S.addEventListener("click",b=>{b.preventDefault(),ee(this,e,c)}),f.append(S)}else f.textContent=d;if(s.tree&&c===0){const w=h("span",null,{className:"tv-tree-indent"});w.style.width=(e.level??0)*16+"px";const S=e.hasChildren&&i!=null?this.treeToggle(e,i):h("span",null,{className:"tv-tree-leaf"});f.prepend(w,S),f.classList.add("tv-tree-cell")}s.numeric[c]&&f.classList.add("tv-number"),r[c]&&!o.fixed&&$(f,r[c]),l[c]&&ft(f,ut(l[c].rules,e.raw?.[c],d,l[c].range,s.rtl)),s.flashes&&s.flashes.get(e.id+""+p)>s.now&&f.classList.add("tv-flash"),s.needle&&d.toLowerCase().includes(s.needle)&&(f.classList.add("tv-find-hit"),s.current&&s.current.id===e.id&&s.current.field===p&&f.classList.add("tv-find-current"))}return a}drawPinned(t,e,s,i){t.className="tv-pinned-row tv-pinned-"+i,t.dataset.pinnedId=e.id;const n=this.t,o=t.insertCell();o.className="tv-row-action";const r=M("pin",n("Unpin row")+" "+(e.values[0]||e.id),()=>this.perform(()=>this.pinRecords([e.id],null)));r.dataset.focus="unpin:"+e.id;const l=N(null,()=>this.perform(()=>this.details(e)),"tv-icon-btn tv-open-btn");l.setAttribute("aria-label",n("Record details")+" "+(e.values[0]||e.id)),o.append(r,l),this.drawCells(t,e,s,null)}columnCaption(t){const e=this.indexedColumns===this.state?.columns?this.columnIndex.get(t):this.state?.columns.find(i=>i.field===t);return e?.caption?e.caption:(this.indexedFields===this.fields?this.fieldIndex?.get(t):this.fields?.find(i=>i.name===t))?.caption||t}columnBands(){const t=new Map;for(const s of this.fields??[])s.group&&t.set(s.name,String(s.group));const e=this.options.columnGroups;if(Array.isArray(e))for(const s of e)for(const i of s?.fields??[])t.set(i,String(s?.caption??""));return[...t.values()].some(Boolean)?t:null}renderBands(t,e,s,i){const n=t.insertRow();n.className="tv-band-row";const o=h("th",null,{className:"tv-row-action"});o.setAttribute("aria-hidden","true"),n.append(o);let r=0;for(;r<s.columns.length&&this.columnIndex.get(s.columns[r])?.pinned;)r++;let l=null;for(const a of e.slots){if(typeof a=="object"){l=null;const p=h("th",null,{className:"tv-gap"});p.setAttribute("aria-hidden","true"),n.append(p);continue}const c=i.get(s.columns[a])??"",d=a<r;if(l&&c&&l.caption===c&&l.side===d){l.cell.colSpan++;continue}const f=h("th",c,{className:c?"tv-band":"tv-band tv-band-empty"});c?f.scope="colgroup":f.setAttribute("aria-hidden","true"),f.dataset.first=a,n.append(f),l={caption:c,side:d,cell:f}}}stickRows(t){let e=0;for(const n of t.tHead?.rows??[]){for(const o of n.cells)o.style.top=e+"px";e+=n.offsetHeight}const s=[...t.tFoot?.rows??[]].reverse();let i=0;for(const n of s){for(const o of n.cells)o.style.bottom=i+"px";i+=n.offsetHeight}}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?.querySelector("tr.tv-heading-row");if(!s)return;let i=0;for(;i<e.columns.length&&this.columnIndex.get(e.columns[i])?.pinned;)i++;if(!i)return;const n=this.colWindow?.fixed,o=[];for(let a=0;a<i;a++)o.push(this.liveWidths.get(e.columns[a])??n?.widths[a]??s.cells[a+1].offsetWidth);const r=[...t.rows].filter(a=>!a.classList.contains("tv-group")&&!a.classList.contains("tv-band-row")),l=[0];for(let a=0;a<i;a++){for(const c of r){const d=c.cells[a+1];d&&d.colSpan===1&&(d.classList.add("tv-pinned"),d.style.insetInlineStart=l[a]+"px")}l.push(l[a]+o[a])}for(const a of t.tHead?.querySelector("tr.tv-band-row")?.cells??[]){const c=Number(a.dataset.first);!Number.isInteger(c)||c>=i||(a.classList.add("tv-pinned"),a.style.insetInlineStart=l[c]+"px")}}revealColumn(t){pt(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 l=this.remote?this.rows:null;if(l&&!l.exact&&t>=l.count-l.blockSize){if(await l.reach(t),l.error)throw l.error;if(l.exact&&t>=l.count)throw new RangeError(`Row ${t} is past the last row.`)}const a=l?l.count:e.count,c=this.windowSize(),d=Math.min(Math.max(0,a-c),Math.max(0,t-it));(d!==this.offset||c!==this.limit||this.result.loading||a!==e.count)&&(this.offset=d,this.limit=c,await this.refresh(!1)),this.content.scrollTop=t*this.stride+this.detailHeight(0,t)}}else{const l=Math.floor(t/this.limit)*this.limit;l!==e.offset&&(this.offset=l,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(),n=s.getBoundingClientRect(),o=this.content.querySelector("thead")?.getBoundingClientRect().height??0,r=this.content.querySelector("tfoot")?.getBoundingClientRect().height??0;n.top<i.top+o?this.content.scrollTop-=i.top+o-n.top:n.bottom>i.bottom-r&&(this.content.scrollTop+=n.bottom-(i.bottom-r))}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 n=this.result.columns.indexOf(t);if(n<0)return;if(pt(this,n))return this.renderRows();const o=[...this.content.querySelectorAll("thead tr.tv-heading-row th[data-field]")].find(f=>f.dataset.field===t);if(!o||o.classList.contains("tv-pinned"))return;const r=this.content.getBoundingClientRect(),l=o.getBoundingClientRect();let a=0;for(const f of this.content.querySelectorAll("thead tr.tv-heading-row th.tv-pinned"))a=Math.max(a,f.getBoundingClientRect().right-r.left);const c=this.content.querySelector("thead tr.tv-heading-row th.tv-row-action")?.getBoundingClientRect().width??0,d=r.left+Math.max(a,c);l.left<d?this.content.scrollLeft-=d-l.left:l.right>r.right&&(this.content.scrollLeft+=l.right-r.right)}setLanguage(t){this.language=t||nt(),this.t=mt(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 dt(t):null,this.selectedCount=0,this.selectionKey=null,this.result&&this.renderRows(),this.renderSelectionStatus(),this.selection&&this.paintSelection()}autosizeColumn(t){const e=Mt(this,t);return e&&this.setColumnWidth(t,e),e}async moveColumn(t,e){const s=this.state.columns.filter(o=>o.field!==t),i=this.state.columns.find(o=>o.field===t);if(!i)return;const n=e?s.findIndex(o=>o.field===e):-1;s.splice(n<0?s.length:n,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 n=h("th",null,{className:"tv-row-action"});if(this.state.filters.some(r=>r.quick)){const r=M("close",e("Clear column filters"),()=>this.perform(()=>this.update({filters:this.state.filters.filter(l=>!l.quick),collapsed:[]})));r.dataset.focus="quick-clear",n.append(r)}i.append(n),this.quickText??=new Map;for(const r of this.colWindow.slots){if(typeof r=="object"){i.append(h("th",null,{className:"tv-gap"}));continue}const l=s.columns[r],a=this.fieldIndex.get(l),c=a?.caption||l,d=this.state.filters.find(v=>v.quick&&v.field===l),f=h("input",null,{type:"text",value:this.quickText.get(l)??d?.text??"",placeholder:a?.type==="number"||a?.type==="date"?"> < = ..":e("Contains"),autocomplete:"off",spellcheck:!1,size:4});f.setAttribute("aria-label",e("Filter")+" · "+c),f.dataset.focus="quick:"+l,a?.type==="number"&&(f.inputMode="text"),f.addEventListener("input",()=>{this.quickText.set(l,f.value),clearTimeout(this.quickTimer),this.quickTimer=setTimeout(()=>this.perform(()=>this.applyQuickFilters()),300)}),f.addEventListener("keydown",v=>{v.key==="Escape"&&f.value?(v.stopPropagation(),f.value="",f.dispatchEvent(new Event("input"))):v.key==="Enter"&&(clearTimeout(this.quickTimer),this.perform(()=>this.applyQuickFilters()))});const p=h("th");p.append(f),a?.type==="number"&&p.classList.add("tv-number"),$(p,this.columnWidth(l)),i.append(p)}}applyQuickFilters(){const t=this.quickText;if(!t?.size)return;let e=this.state.filters;for(const[s,i]of t){const n=this.fields.find(l=>l.name===s)?.type,o=Pt(s,i,n),r=e.findIndex(l=>l.quick&&l.field===s);r>=0&&(e=e.filter((l,a)=>a!==r)),o&&(e=[...e,o])}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})}get opened(){return this._opened??=new Map}get expanded(){let t=null;for(const e of this.opened.values())t=e;return t}set expanded(t){this.opened.clear(),t&&this.opened.set(t.id,t)}isExpanded(t){return this.opened.has(t)}detailHeight(t,e){let s=0;for(const i of this.opened.values())i.index>=t&&i.index<e&&(s+=i.height);return s}rowTop(t){if(!this.opened.size)return t;let e=0;for(const s of[...this.opened.values()].sort((i,n)=>i.index-n.index)){const i=(s.index+1)*this.stride+e;t<=i||!s.height||(e+=Math.min(s.height,t-i))}return t-e}expandButton(t,e){const s=this.opened.get(t.id),i=!!s&&s.index===e,n=this.t(i?"Collapse details":"Expand details")+" "+(t.values[0]||t.id),o=M(i?"chevron":"chevron-right",n,()=>this.perform(()=>this.toggleDetail(t,e)),"tv-expand",!1);return o.setAttribute("aria-expanded",String(i)),o.dataset.focus="expand:"+t.id,i&&o.setAttribute("aria-controls",this.detailId(s)),o}rowsKey(){const{search:t,filters:e,sort:s,groups:i,collapsed:n,collapseLevel:o,tree:r,treeCollapsed:l}=this.state,a=this.result;return JSON.stringify([t,e,s,i,n,o,r,l,a?.exact===!1?null:a?.count,a?.matches])}checkExpanded(){const t=this.result;if(!this.opened.size)return;const e=this.rowsKey();for(const s of[...this.opened.values()]){const i=s.index-t.offset,n=i>=0&&i<t.rows.length&&t.rows[i]?.id!==s.id&&!t.rows[i]?.loading;(s.key!==e||n)&&this.opened.delete(s.id)}}detailId(t){return(this.uid??="tv"+Math.random().toString(36).slice(2,8))+"-detail-"+(t?.seq??0)}toggleDetail(t,e){if(this.opened.has(t.id))this.opened.delete(t.id);else{const s=this.result.columns,i={id:t.id,values:Object.fromEntries(s.map((r,l)=>[r,t.values[l]])),raw:Object.fromEntries(s.map((r,l)=>[r,t.raw?.[l]??null]))},n=this.options.detailRenderer(i),o=n instanceof Node?n:h("div",n==null?"":String(n));this.options.detailMode!=="multiple"&&this.opened.clear(),this.detailSeq=(this.detailSeq??0)+1,this.opened.set(t.id,{id:t.id,index:e,node:o,height:0,key:this.rowsKey(),seq:this.detailSeq})}this.renderRows()}renderDetail(t,e,s){const i=t.insertRow();i.className="tv-detail",i.entry=s;const n=i.insertCell();n.colSpan=e;const o=h("div",null,{className:"tv-detail-panel",id:this.detailId(s)});o.setAttribute("role","region"),o.setAttribute("aria-label",this.t("Record details")),o.append(s.node),n.append(o)}formatDialog(t){const e=this.t,s=this.fields.find(a=>a.name===t),i=s?.type==="number",n=structuredClone(this.state.columns.find(a=>a.field===t)?.rules??[]),o=[...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")]],r=[["good",e("Green fill")],["bad",e("Red fill")],["warn",e("Amber fill")],["info",e("Blue fill")],["strong",e("Bold text")]],l=a=>a.type==="bar"?e("Data bar"):a.type==="scale"?e("Colour scale"):[o.find(([c])=>c===a.op)?.[1]??a.op,a.value,a.op==="between"?"– "+a.value2:""].join(" ").trim()+" · "+(r.find(([c])=>c===a.style)?.[1]??e("Custom"));R(this.root,e("Conditional formatting")+" · "+(s?.caption||t),e,(a,c)=>{const d=h("div",null,{className:"tv-rule-list"}),f=()=>{d.replaceChildren(),n.length||d.append(h("p",e("No rules"),{className:"tv-muted"})),n.forEach((C,T)=>{const D=h("div",null,{className:"tv-column"}),H=h("span",null,{className:"tv-swatch"});ft(H,ut([C],1,"",{min:0,max:2})),D.append(H,h("span",l(C))),D.append(M("close",e("Remove")+" · "+l(C),()=>{n.splice(T,1),f()})),d.append(D)})};f();const p=k(o),v=k(r),x=h("input",null,{inputMode:i?"decimal":"text"}),w=h("input",null,{inputMode:"decimal"}),S=g(e("Value"),x),b=g(e("Second value"),w),q=g(e("Style"),v),P=()=>{const C=p.value==="bar"||p.value==="scale";S.hidden=q.hidden=C,b.hidden=p.value!=="between"};p.onchange=P,P();const K=N(e("Add rule"),()=>{const C=p.value;if(C==="bar"||C==="scale")n.push({type:C});else{if(x.value.trim()==="")return x.focus();const T={type:"value",op:C,value:x.value.trim(),style:v.value};C==="between"&&(T.value2=w.value.trim()),n.push(T)}x.value=w.value="",f()});K.classList.add("tv-add-rule"),a.append(d,g(e("Rule"),p),S,b,q,K),c("Clear rules",()=>this.setColumnRules(t,[]),"danger"),c("Apply",()=>this.setColumnRules(t,n),"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(n=>n.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,n=t.createTFoot().insertRow();n.className="tv-totals";const o=h("th",null,{scope:"row",className:"tv-row-action"});o.append(z("sigma"),h("span",s("Totals"),{className:"tv-sr"})),n.append(o);for(const r of this.colWindow.slots){const l=n.insertCell();if(typeof r=="object"){l.className="tv-gap";continue}const a=i.columns[r],c=this.columnIndex.get(a),d=this.fieldIndex.get(a),f=c?.total,p=d?.caption||a,v=_.find(([S])=>S===f)?.[1],x=i.totals?.[a]??"",w=N(null,()=>gt(this.root,w,[[s("None"),()=>this.perform(()=>this.setColumnTotal(a,null)),{checked:!f,icon:f?void 0:"check"}],..._.filter(([S])=>S!=="distinct").map(([S,b])=>[s(b),()=>this.perform(()=>this.setColumnTotal(a,S)),{checked:f===S,icon:f===S?"check":void 0,disabled:S!=="count"&&d?.type!=="number"&&d?.type!=="date"}])]));w.className="tv-total",w.setAttribute("aria-haspopup","menu"),w.setAttribute("aria-label",p+" · "+(v?s(v)+" "+x:s("No total"))),v&&w.append(h("span",s(v),{className:"tv-total-kind"}),h("span",x,{className:"tv-total-value"})),d?.type==="number"&&l.classList.add("tv-number"),e[r]&&!this.colWindow.fixed&&$(l,e[r]),l.append(w)}}selectAllBox(){const t=h("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,n=e.all?e.ids.size===0||i:this.selectedCount>0&&i;t.checked=n,t.indeterminate=!n&&!e.empty}selectionBox(t){const e=h("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(h("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 n;e.empty?n=0:this.remote?n=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)?n=s.matches:n=await this.client.call("selectionCount",{selection:e.toJSON()}),!(this.closed||i!==this.selectionKey)&&(this.selectedCount=n,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 n=this.result.columns;if(e)n=e.map(o=>o.field),t={...t,values:e.map(o=>o.value)};else if(this.result.columnCount>n.length&&(!this.remote||this.remote.detail)){const o=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});n=o.map(r=>r.field),t={...t,values:o.map(r=>r.value)}}R(this.root,s("Record details"),s,(o,r)=>{const l=[];n.forEach((a,c)=>{const d=this.fields.find(f=>f.name===a);if(this.editable&&(this.remote?d?.editable===!0:d?.editable)){const f=bt(d,{raw:t.raw?.[this.result.columns.indexOf(a)]??null,text:t.values[c],t:s});o.append(kt(d.caption||a,f)),l.push({field:a,info:d,editor:f,old:f.read()})}else o.append(g(d?.caption||a,h("output",t.values[c])))}),this.editable&&!this.remote&&r("Remove record",()=>this.change("remove",{ids:[t.id]}),"danger"),this.editable&&!this.remote&&r("Paste rows",()=>this.pasteDialog(t)),r("Copy row",()=>navigator.clipboard.writeText(t.values.join(" "))),this.editable&&r("Save changes",()=>{const a=l.filter(c=>c.editor.read()!==c.old);for(const c of a){const d=yt(c.info,c.editor.kind,c.editor.read());if(d)throw new Error(d)}return this.change("edit",{revision:i,cells:a.map(c=>({id:t.id,field:c.field,value:c.editor.read()}))})},"primary")})}pasteDialog(t){const e=this.t;R(this.root,e("Paste rows"),e,(s,i)=>{const n=k(this.result.columns.map(l=>[l,l])),o=h("textarea",null,{rows:5}),r=h("input",null,{type:"number",min:1,value:1});s.append(g(e("Starting field"),n),g(e("Use Tab to separate fields and a new line for each record."),o),g(e("Number of records"),r)),i("Apply",async()=>{await this.change("paste",{id:t.id,field:n.value,lines:ht(o.value),repeat:Number(r.value)})})})}shareDialog(){const t=this.t,e=this.options.sharing;R(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 n=h("input",null,{value:this.lastShare.url,readOnly:!0});s.append(g(t("Share link"),n)),i("Copy link",()=>navigator.clipboard.writeText(n.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 n=new File([await this.exportResults("xlsx")],"Results.xlsx",{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});if(!navigator.canShare({files:[n]}))throw new Error("File sharing is unavailable on this device.");R(this.root,t("Share"),t,(o,r)=>r("Share",()=>navigator.share({files:[n],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,layout:i=!1}={}){const n=await this.exportResults(t,{selected:e,layout:i}),o=URL.createObjectURL(n),r=e?this.selectedCount:this.result?.matches;return h("a",null,{href:o,download:s||this.title.textContent+(Number.isSafeInteger(r)?"-"+r:"")+"."+t}).click(),setTimeout(()=>URL.revokeObjectURL(o),3e4),n}async exportDialog(){clearTimeout(this.searchTimer),await this.refresh();const t=this.t;R(this.root,t("Export results")+" · "+this.countText(),t,(e,s)=>{const i=k((this.remote?.formats??["xlsx","csv","pdf"]).map(c=>[c,{xlsx:"Excel (.xlsx)",csv:"CSV (.csv)",pdf:"PDF (.pdf)"}[c]]));e.append(g(t("Format"),i));const n=this.selection,o=n&&!n.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;o&&e.append(g(t("Records"),o));const r=h("input",null,{type:"checkbox",checked:!1}),l=g(t("Keep the layout: groups, totals, widths and formatting"),r),a=()=>l.hidden=i.value==="csv"||!!this.remote;i.addEventListener("change",a),a(),e.append(l),s("Download",()=>this.downloadResults(i.value,{selected:o?.value==="selected",layout:r.checked&&!l.hidden}))})}async exportResults(t,{selected:e=!1,layout:s=!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 i=this.getState(),n=e&&this.selection&&!this.selection.empty?this.selection.toJSON():void 0;if(e&&!n)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(n&&!this.remote.selectionExport)throw new Error("This source cannot export selected records.");return this.remote.exportResults({state:i,format:t,signal:this.abort?.signal,...n&&{selection:n}})}return this.client.call("export",{format:t,state:i,selection:n,layout:s&&t!=="csv"?this.exportLayout():null})}async copyCells(t=!1){if(!this.grid)throw new Error("Select cells first.");const e=this.grid.copyText(t);return await navigator.clipboard.writeText(e),this.status.textContent=this.t("Copied"),e}async pasteFromClipboard(t,e){const s=await navigator.clipboard.readText();return this.change("paste",{id:t,field:e,lines:ht(s),repeat:1})}filterByValue(t,e,s=!0,i=!1){const n=i?{field:t,op:s?"blank":"notBlank"}:{field:t,op:s?"in":"notIn",values:[e]};return this.update({filters:[...this.state.filters,n],collapsed:[]})}sortField(t,e){return this.update({sort:[{field:t,desc:e===!0},...this.state.sort.filter(s=>s.field!==t)]})}groupField(t){return this.update({groups:[...this.state.groups.filter(e=>e.field!==t),{field:t}],tree:void 0,collapsed:[]})}canPinRows(){return!this.base&&(!this.remote||this.remote.pinnedRows===!0)}pinnedSide(t){const e=this.state.pinnedRows;return e?.top?.includes(t)?"top":e?.bottom?.includes(t)?"bottom":null}pinRecords(t,e){if(!this.canPinRows())throw new Error("This source cannot pin rows.");if(e!=null&&e!=="top"&&e!=="bottom")throw new Error('Pin rows to "top" or "bottom".');const s=this.state.pinnedRows??{},i=o=>(o??[]).filter(r=>!t.includes(r)),n={top:i(s.top),bottom:i(s.bottom)};return e&&(n[e]=[...n[e],...t]),this.applyLayout({pinnedRows:n.top.length||n.bottom.length?n:void 0})}treeToggle(t,e){const s=this.t(t.collapsed?"Expand":"Collapse")+" "+(t.values[0]||t.id),i=M(t.collapsed?"chevron-right":"chevron",s,()=>this.perform(()=>this.toggleTreeRow(t,e)),"tv-tree-toggle",!1);return i.setAttribute("aria-expanded",String(!t.collapsed)),i.dataset.focus="tree:"+t.id,i}async toggleTreeRow(t,e){if(this.remote){const i=new Set(this.state.treeCollapsed??[]);return i.has(t.id)?i.delete(t.id):i.add(t.id),this.applyLayout({treeCollapsed:[...i]})}const s=await this.client.call("toggle",{index:e,offset:this.offset,limit:this.limit});this.state.treeCollapsed=s.treeCollapsed??[],this.state.collapseLevel=void 0,await this.refresh(!1)}setTree(t){return this.update({tree:t??void 0,treeCollapsed:[],groups:t?[]:this.state.groups,collapsed:[]})}async setTreeCollapsed(t){if(!this.state.tree)throw new Error("The records are not shown as a tree.");return t?this.remote?this.applyLayout({treeCollapsed:[],collapseLevel:0}):this.applyLayout({treeCollapsed:await this.client.call("treeParents"),collapseLevel:void 0}):this.applyLayout({treeCollapsed:[],collapseLevel:void 0})}treeDialog(){const t=this.t;R(this.root,t("Show as tree"),t,(e,s)=>{const i=this.state.tree??{},n=this.fieldSelect(i.key??"",!0),o=this.fieldSelect(i.parent??"",!0),r=this.fieldSelect(i.level??"",!0);e.append(h("p",t("Each record goes under the record whose key its parent field holds. Or give a field with an outline level instead."),{className:"tv-muted"}),g(t("Key field"),n),g(t("Parent field"),o),g(t("Level field"),r)),this.state.tree&&s("Remove tree",()=>this.setTree(null),"danger"),s("Apply",()=>{if(r.value)return this.setTree({level:r.value});if(!o.value||!n.value)throw new Error("Choose the key field and the parent field.");return this.setTree({key:n.value,parent:o.value})},"primary")})}async moveRecords(t,e,s="user"){if(!this.result)throw new Error("No table loaded.");if(this.base)throw new Error("A pivot is read-only. Go back to the records first.");if(this.state.sort.length||this.state.groups.length||this.state.tree)throw new Error("Clear the sort and the groups to move records.");if([...t,e].some(n=>n!=null&&this.pinnedSide(n)))throw new Error("Unpin the rows before moving them.");const i=vt({ids:[...t],before:e??null,source:s});return this.emit("rowMove",i)?(this.remote||(await this.client.call("move",{ids:t,before:e??null}),this.editable&&(this.dirty=!0),await this.refresh(!1),this.emit("change",{action:"move",ids:[...t],before:e??null,source:s})),!0):!1}async moveRecordBy(t,e){let s;if(this.remote){const i=this.result.rows.filter(o=>o.group===void 0&&!o.loading),n=i.findIndex(o=>o.id===t);s=n<0?void 0:e<0?i[n-1]?.id:n<i.length-1?i[n+2]?.id??null:void 0}else s=await this.client.call("neighbour",{id:t,by:e});return s===void 0?!1:this.moveRecords([t],s)}async applyTransaction(t={}){if(!this.result||!this.client)throw new Error(this.remote?"Update the server and call refresh(); a remote source has no local records.":"No table loaded.");if(this.base)throw new Error("A pivot is read-only. Go back to the records first.");const e=await this.client.call("transaction",t);return this.options.flashChanges&&this.flashCells(e.changed,!1),await this.refresh(!1),this.emit("change",{action:"transaction",...structuredClone(t),ids:e.added,source:"api"}),{added:e.added,updated:e.changed.length,removed:e.removed.length}}flashCells(t,e=!0){const s=performance.now()+900;this.flashes??=new Map;for(const{id:i,field:n}of t)this.flashes.set(i+""+n,s);clearTimeout(this.flashTimer),this.flashTimer=setTimeout(()=>{const i=performance.now();for(const[n,o]of this.flashes)o<=i&&this.flashes.delete(n)},1e3),e&&this.result&&this.renderRows()}openFind(t){if(this.remote)throw new Error("Find needs local records; search the server source instead.");if(!this.result)throw new Error("No table loaded.");const e=this.t;if(!this.findBar){const s=h("div",null,{className:"tv-find"});s.setAttribute("role","search");const i=h("input",null,{type:"search",placeholder:e("Find in cells"),autocomplete:"off",spellcheck:!1});i.setAttribute("aria-label",e("Find in cells"));const n=h("output",null,{className:"tv-find-count"});n.setAttribute("aria-live","polite");const o=M("chevron-up",e("Previous match"),()=>this.perform(()=>this.findNext(!0))),r=M("chevron",e("Next match"),()=>this.perform(()=>this.findNext(!1))),l=M("close",e("Close find"),()=>this.closeFind());s.append(z("search"),i,n,o,r,l),i.addEventListener("input",()=>{clearTimeout(this.findTimer),this.findTimer=setTimeout(()=>this.perform(()=>this.setFindText(i.value)),150)}),i.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),clearTimeout(this.findTimer),this.perform(async()=>{this.finder?.text!==i.value&&await this.setFindText(i.value),await this.findNext(a.shiftKey)})):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),this.closeFind())}),this.findBar={bar:s,input:i,count:n},this.toolbar.after(s)}return t!=null&&(this.findBar.input.value=t),this.findBar.input.focus(),this.findBar.input.select(),this.setFindText(this.findBar.input.value)}async setFindText(t){this.finder={text:t,current:null},this.renderRows(),await this.countFound()}async countFound(){const t=this.finder;if(!this.findBar||!t)return;if(!t.text){this.findBar.count.textContent="";return}const{count:e,index:s,complete:i}=await this.client.call("findCount",{text:t.text,row:t.current?.row??-1,field:t.current?.field??null});if(this.finder!==t)return;const n=e.toLocaleString(this.language)+(i?"":"+");this.findBar.count.textContent=e===0?this.t("No matches"):s>=0?`${s+1} / ${n}`:n+" "+this.t("matches")}async findNext(t=!1){const e=this.finder;if(!e?.text)return null;const s=Yt(this.state,this.fields.map(r=>r.name)),i=e.current??this.focusedPlace(),n=await this.client.call("find",{text:e.text,row:i?.row??-1,col:i?s.indexOf(i.field):-1,back:t});if(this.finder!==e)return null;if(!n)return e.current=null,await this.countFound(),null;e.current=n,await this.showRow(n.row),await this.showColumn(n.field,s),this.renderRows();const o=this.grid?.positionOf(n.id,n.field);return o&&this.grid.focusAt(o.row,o.col,!0),this.findBar?.input.focus(),await this.countFound(),{id:n.id,field:n.field}}focusedPlace(){const t=this.grid?.focused();if(!t)return null;const e=this.result.rows.findIndex(s=>s.id===t.id&&s.group===void 0);return e<0?null:{row:this.result.offset+e,field:t.field}}closeFind(){if(!this.findBar)return;const t=this.finder?.current;this.findBar.bar.remove(),this.findBar=null,this.finder=null,clearTimeout(this.findTimer),this.result&&this.renderRows();const e=t&&this.grid?.positionOf(t.id,t.field);e&&this.grid.cells[e.row][e.col]?this.grid.focusAt(e.row,e.col,!0):(this.content.querySelector('td[tabindex="0"]')??this.toolbar.querySelector("input"))?.focus({preventScroll:!0})}chartRange(){const t=this.grid?.rectangle();if(!t||t.bottom===t.top&&t.right===t.left)throw new Error("Select cells first.");const e=this.grid.records.slice(t.top,t.bottom+1),s=this.result.columns.slice(t.left,t.right+1),i=s.map(l=>({field:l,caption:this.columnCaption(l),numeric:this.fieldIndex.get(l)?.type==="number"})),n=e.map(l=>({raw:(l.raw??[]).slice(t.left,t.right+1),values:l.values.slice(t.left,t.right+1)})),o=he(i,n);if(!o)throw new Error("Select cells with numbers to chart them.");const r=this.fieldIndex.get(s[i.findIndex(l=>l.numeric)])?.format;this.showChart(this.t("Chart"),o,r,"column")}showChart(t,e,s,i="column",n=null){const o=this.t,r=l=>s&&s!=="General"?Q(s,l):Number.isInteger(l)?Q("#,##0",l):Q("#,##0.##",l);R(this.root,t,o,l=>{const a=k(ae.map(p=>[p,o({column:"Column",bar:"Bar",line:"Line",pie:"Pie"}[p])]),i),c=h("figure",null,{className:"tv-chart-figure"}),d=()=>c.replaceChildren(ce({type:a.value,...e,title:t,format:r}));if(a.onchange=d,n){const p=k(n.fields,n.value);p.onchange=()=>this.perform(async()=>{const v=p.value,x=await n.load(v);p.value===v&&(e=x.data,s=x.format,d())}),l.append(g(o("Value"),p))}d();const f=N(o("Download SVG"),()=>{const p=URL.createObjectURL(de(c.firstChild));h("a",null,{href:p,download:(this.title.textContent||"Chart")+".svg"}).click(),setTimeout(()=>URL.revokeObjectURL(p),3e4)});f.classList.add("tv-chart-save"),l.append(g(o("Chart type"),a),c,f)})}exportLayout(){const t=this.columnBands(),e=[];for(const s of this.state.columns){const i=s.width??this.measured?.widths.get(s.field);Number.isFinite(i)&&e.push([s.field,i])}return{bands:t?[...t]:[],widths:e,totals:this.state.totalsRow===!0}}destroy(){this.closed||(this.load&&(this.load.cancel?.(),this.endLoad(this.load,"cancelled")),this.closed=!0,this.events.clear(),clearTimeout(this.flashTimer),clearTimeout(this.findTimer),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())}}function nt(){const F=Gt();return F!=="en"?F:Ut()??"en"}function be(F){return F?.map(t=>!Array.isArray(t?.options)||!t.options.length||t.validator||xt(t)==="multiselect"?t:{...t,validator:{type:"list",items:t.options.map(String)}})}function kt(F,t){if(t.kind!=="multiselect")return g(F,t.node,t.focus);const e=h("div",null,{className:"tv-field-group"});return e.append(h("span",F),t.node),e}export{St as DENSITY,_e as mountTable};
@@ -1 +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};
1
+ function a(o,t,s={}){const l=document.createElement(o);return t!=null&&(l.textContent=t),Object.assign(l,s),l}function x(o,t,s=""){const l=a("button",o,{type:"button",className:s});return l.addEventListener("click",t),l}const L={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",copy:"M5.5 5.5h7v7h-7zM10.5 5.5v-2h-7v7h2",paste:"M5.5 3.5h-2v10h9v-10h-2M6 2.5h4v2H6z",chart:"M3 13.5h10M4.5 11.5v-4M8 11.5v-7M11.5 11.5v-5",search:"M7 11.5a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9zM10.5 10.5L14 14",export:"M8 2.5v8M5 7.5l3 3 3-3M3 12.5v1h10v-1",details:"M3 3.5h10v9H3zM5.5 6.5h5M5.5 9.5h3",remove:"M3.5 4.5h9M6.5 4.5v-2h3v2M5 4.5l.5 9h5l.5-9","pin-top":"M3 2.5h10M8 13.5v-8M5 8.5l3-3 3 3","pin-bottom":"M3 13.5h10M8 2.5v8M5 7.5l3 3 3-3",tree:"M3 3.5h4M5 3.5v9h3M5 8h3M10 8h3M10 12.5h3",grip:"M6 4h.01M10 4h.01M6 8h.01M10 8h.01M6 12h.01M10 12h.01",rename:"M3 12.5l1-3 6.5-6.5 2 2L6 11.5zM9.5 4l2 2",sparkle:"M8 2.5l1.3 3.2 3.2 1.3-3.2 1.3L8 11.5 6.7 8.3 3.5 7l3.2-1.3zM12.5 11l.6 1.4 1.4.6-1.4.6-.6 1.4-.6-1.4-1.4-.6 1.4-.6z",density:"M2.5 4h11M2.5 8h11M2.5 12h11","chevron-up":"M4 10l4-4 4 4",fill:"M3 3.5h6v6H3zM11 7.5v5h-5M9.5 11l1.5 1.5 1.5-1.5","filter-out":"M2.5 3.5h11L9.5 8.5v4l-3-1.5V8.5zM11 11l3 3M14 11l-3 3"},k=new Map;function E(o){let t=k.get(o);if(!t){const s="http://www.w3.org/2000/svg";t=document.createElementNS(s,"svg"),t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("aria-hidden","true"),t.setAttribute("class","tv-icon");const l=document.createElementNS(s,"path");l.setAttribute("d",L[o]),t.append(l),k.set(o,t)}return t.cloneNode(!0)}function z(o,t,s,l="",h=!0){const i=x(null,s,("tv-icon-btn "+l).trim());return i.append(E(o)),i.setAttribute("aria-label",t),h&&(i.title=t),i}function C(o,t){const s=a("select");for(const[l,h]of o)s.add(new Option(h,l));return t!=null&&(s.value=t),s}function N(o,t,s=t){const l=a("label");return s.setAttribute("aria-label",o),l.append(a("span",o),t),s.type==="checkbox"&&l.classList.add("tv-check"),l}function H(o,t,s,{onClose:l,focusBack:h}={}){const i=o.querySelector(".tv-menu");if(i&&(i.dispatchEvent(new Event("tv-close")),i.anchor===t))return null;const r=a("div",null,{className:"tv-menu"});r.anchor=t,r.setAttribute("role","menu");const f=[];for(const e of s){if(!e){r.append(a("div",null,{className:"tv-menu-sep",role:"separator"}));continue}const[n,v,c={}]=e,d=a("button",null,{type:"button",className:"tv-menu-item",tabIndex:-1,disabled:!!c.disabled});d.setAttribute("role",c.checked!=null?"menuitemcheckbox":"menuitem"),c.checked!=null&&d.setAttribute("aria-checked",String(!!c.checked));const y=c.icon&&L[c.icon]?E(c.icon):a("span",null,{className:"tv-icon"});d.append(y,a("span",n)),c.shortcut&&d.append(a("kbd",c.shortcut,{className:"tv-shortcut"})),d.addEventListener("click",()=>{u(!1),v()}),r.append(d),f.push(d)}const m=()=>{if(!t.isConnected)return u(!1);const e=o.getBoundingClientRect(),n=t.getBoundingClientRect(),v=(t.closest("th")??t).getBoundingClientRect();if(n.right<e.left||n.left>e.right||n.bottom<e.top||n.top>e.bottom)return u(!1);const c=r.offsetWidth;let d=v.left-e.left;d+c>e.width-8&&(d=n.right-e.left-c),r.style.left=Math.max(8,Math.min(d,e.width-c-8))+"px";const y=n.bottom-e.top+4,A=y+r.offsetHeight<=e.height-8;r.style.top=(A?y:Math.max(8,n.top-e.top-r.offsetHeight-4))+"px"},b=e=>{const n=f.filter(c=>!c.disabled);if(!n.length)return;const v=n.indexOf(document.activeElement);n[(v+e+n.length)%n.length].focus()},g=e=>{if(e.key==="ArrowDown")b(1);else if(e.key==="ArrowUp")b(-1);else if(e.key==="Home"||e.key==="End"){const n=f.filter(v=>!v.disabled);n[e.key==="Home"?0:n.length-1]?.focus()}else if(e.key==="Escape")u(!0);else if(e.key==="Tab")u(!1);else return;e.preventDefault(),e.stopPropagation()},M=e=>{!r.contains(e.target)&&!t.contains(e.target)&&u(!1)};let w=!1;const u=e=>{if(w)return;w=!0,r.remove(),t.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",M,!0),window.removeEventListener("resize",p),o.querySelector(".tv-data")?.removeEventListener("scroll",m);const n=h??t;e&&n.isConnected&&n.focus(),l?.()},p=()=>u(!1);return r.addEventListener("keydown",g),r.addEventListener("tv-close",p),o.append(r),t.setAttribute("aria-expanded","true"),m(),document.addEventListener("pointerdown",M,!0),window.addEventListener("resize",p),o.querySelector(".tv-data")?.addEventListener("scroll",m,{passive:!0}),f.find(e=>!e.disabled)?.focus(),r}function S(o,t,s,l){const h=document.activeElement,i=a("dialog",null,{className:"tv-dialog"}),r=a("header"),f=z("close",s("Close"),()=>i.close(),"tv-close");r.append(a("h2",t),f);const m=a("div",null,{className:"tv-form"}),b=a("div",null,{className:"tv-dialog-actions"}),g=a("p",null,{className:"tv-error"});g.setAttribute("role","alert"),i.setAttribute("aria-label",t),i.append(r,m,g,b),o.append(i);const M=[],w=(u,p,e="")=>{const n=x(s(u),async()=>{if(!n.disabled){n.disabled=!0;try{await p(),i.close()}catch(v){g.textContent=s(v.message)}finally{n.disabled=!1}}},e?"tv-"+e:"");return b.append(n),M.push([n,e]),n};return i.addEventListener("close",()=>{if(i.remove(),o.querySelector("dialog[open]")||h?.isConnected)return;[...o.querySelectorAll("button")].find(p=>p.textContent===h?.textContent&&p.getAttribute("aria-label")===h?.getAttribute("aria-label"))?.focus()},{once:!0}),l(m,w,i),M.length===1&&!M[0][1]&&M[0][0].classList.add("tv-primary"),M.length||b.remove(),i.showModal(),i}export{x as button,a as el,E as icon,z as iconButton,N as labeled,H as menu,S as modal,C as select};
@@ -0,0 +1 @@
1
+ const a=["normal","percentOfTotal","percentOfCol","percentOfRow","runTotal","rankDescending","rankAscending","index"],t=new Set(["percentOfTotal","percentOfCol","percentOfRow"]);function s(o){const n=Array.isArray(o.rows)&&o.rows.length?o.rows:[o.rowField].filter(Boolean),e=Array.isArray(o.columns)?o.columns:[o.columnField].filter(Boolean),l=Array.isArray(o.values)&&o.values.length?o.values:o.valueField?[{field:o.valueField,agg:o.agg??"sum"}]:[];return{rows:n,columns:e,values:l.map(r=>({field:r.field,agg:r.agg??"sum",showAs:a.includes(r.showAs)?r.showAs:"normal"}))}}export{t as PERCENT_SHOW_AS,a as PIVOT_SHOW_AS,s as pivotSpec};
@@ -1 +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};
1
+ import{PivotCache as L,PivotTable as U}from"../pivot/engine.js";import{Workbook as X}from"../core/workbook.js";import{NUM as T,STR as _,BOOL as j,ERR as x}from"../core/sheet.js";import{MAX_COLS as z,MAX_ROWS as B}from"../core/address.js";import{display as D}from"./model.js";import{worksheetTable as I}from"./worksheet-table.js";import{PERCENT_SHOW_AS as V,pivotSpec as q}from"./pivot-spec.js";import{PIVOT_SHOW_AS as re,pivotSpec as le}from"./pivot-spec.js";function se(R,W){const{view:m,table:u}=R;m.refresh();const o=q(W);if(!o.rows.length||!o.values.length)throw new Error("Choose a row field and a value.");if(o.rows.some(e=>o.columns.includes(e))||new Set(o.rows).size!==o.rows.length)throw new Error("Choose different row and column fields.");const y=[...new Set([...o.rows,...o.columns,...o.values.map(e=>e.field)])],N=new Set(m.columns.map(e=>e.field)),P=y.map(e=>{if(!N.has(e))throw new Error("Field unavailable.");const t=u.column(e),s=m.filteredCount,r=new Float64Array(s),l=new Uint8Array(s);u.ensure(t);for(let n=0;n<s;n++){const M=m.perm[n];r[n]=t.raw(M),l[n]=t.kind(M)}return{name:e,nums:r,kinds:l,numFmt:t.format}}),$=L.fromColumns(P,m.filteredCount,u.manager.strings),f=e=>y.indexOf(e),b=e=>o.values.length>1||e.showAs!=="normal"?`${e.field} (${e.agg}${e.showAs!=="normal"?", "+e.showAs:""})`:e.field,v=new U($,{rows:o.rows.map(f),cols:o.columns.map(f),values:o.values.map(e=>({field:f(e.field),agg:e.agg,name:b(e),showAs:e.showAs==="normal"?null:{type:e.showAs,baseField:f(o.rows[0])}})),layout:"tabular"});v.update();const{cells:a,firstDataRow:i,rows:S,cols:c}=v.result.layout;if(S>B||c>z)throw new Error("The pivot exceeds the worksheet dimensions.");const w=new X,p=w.sheet,h=o.rows.length,d=Array.from({length:c},()=>[]),O=new Map;for(let e=0;e<a.count;e++)O.set(a.rows[e]*c+a.cols[e],e);const G=e=>e.agg==="count"?"General":V.has(e.showAs)?"0.00%":e.showAs.startsWith("rank")?"0":u.column(e.field).format,k=o.columns.map(e=>u.column(e).format),C=i>1?1:0;for(let e=C;e<i;e++){let t=null;for(let s=h;s<c;s++){const r=O.get(e*c+s),l=r===void 0?null:a.valueAt(r);let n=l==null||l===""?null:typeof l=="number"?D(l,k[Math.min(e-C,k.length-1)]):String(l);n!=null?t=n:e<i-1&&(n=t),n!=null&&!d[s].includes(n)&&d[s].push(n)}}const g=Array.from({length:c},(e,t)=>t<h?o.rows[t]:d[t].join(" · ")||b(o.values[0])),E=new Map;g.forEach((e,t)=>{const s=E.get(e)??0;E.set(e,s+1),s&&(g[t]=e+" ("+(s+1)+")")});const H=e=>o.values[(e-h)%o.values.length],A=new Map,F=e=>(A.has(e)||A.set(e,e&&e!=="General"?w.styles.derive(0,{numFmt:e}):0),A.get(e));for(let e=0;e<a.count;e++){const t=a.rows[e],s=a.cols[e],r=a.valueAt(e);if(t<i||r==null)continue;const l=typeof r=="number"?T:typeof r=="boolean"?j:typeof r=="string"?_:x;p.setCell(t-i+1,s,l,l===_?w.strings.add(r):l===x?r.index:Number(r));const n=s>=h?F(G(H(s))):l===T?F(u.column(o.rows[s]).format):0;n&&p.setStyle(t-i+1,s,n)}return I(w,p,{r0:0,c0:0,r1:S-i,c1:c-1},g)}export{re as PIVOT_SHOW_AS,le as pivotSpec,se as pivotTable};