@8sheets/data-grid 1.1.2 → 1.2.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 (226) hide show
  1. package/README.md +1 -1
  2. package/a11y/cell-alt-text.js +1 -1
  3. package/api/serialize.js +1 -1
  4. package/api/style-refs.js +1 -1
  5. package/calc/adjust.js +1 -1
  6. package/calc/compile.js +1 -1
  7. package/calc/engine.js +1 -1
  8. package/calc/functions/array.js +1 -1
  9. package/calc/functions/database.js +1 -1
  10. package/calc/functions/date.js +1 -1
  11. package/calc/functions/engineering.js +1 -1
  12. package/calc/functions/financial.js +1 -1
  13. package/calc/functions/helpers.js +1 -1
  14. package/calc/functions/index.js +3 -2
  15. package/calc/functions/info.js +1 -1
  16. package/calc/functions/logical.js +1 -1
  17. package/calc/functions/lookup.js +1 -1
  18. package/calc/functions/math.js +1 -1
  19. package/calc/functions/stat.js +1 -1
  20. package/calc/functions/text.js +1 -1
  21. package/calc/parser.js +2 -2
  22. package/calc/shown-refs.js +1 -0
  23. package/calc/values.js +1 -1
  24. package/calcx/calc-control.js +1 -0
  25. package/calcx/external-read.js +1 -1
  26. package/calcx/external.js +1 -1
  27. package/cells/axis-ops.js +1 -1
  28. package/cells/cell-styles-xml.js +1 -1
  29. package/cells/cf-engine.js +1 -1
  30. package/cells/cf-file.js +1 -1
  31. package/cells/docprops-xml.js +2 -2
  32. package/cells/filter-eval.js +1 -0
  33. package/cells/filter-file.js +1 -1
  34. package/cells/find-engine.js +1 -1
  35. package/cells/goto.js +1 -1
  36. package/cells/name-box.js +1 -1
  37. package/cells/note-box.js +3 -0
  38. package/cells/options.js +1 -1
  39. package/cells/outline-column.js +1 -1
  40. package/cells/protected-menu.js +1 -0
  41. package/cells/rich-data-xml.js +1 -1
  42. package/cells/sheet-views-file.js +2 -0
  43. package/cells/shift-check.js +1 -1
  44. package/cells/sort-compare.js +1 -0
  45. package/cells/ui-kit.js +1 -1
  46. package/cells/undo-group.js +1 -1
  47. package/celltypes/dropdowns.js +2 -2
  48. package/core/address.js +1 -1
  49. package/core/autofill.js +1 -1
  50. package/core/axis.js +1 -1
  51. package/core/cond-format.js +1 -1
  52. package/core/culture.js +5 -1
  53. package/core/custom-views.js +1 -1
  54. package/core/data-tools.js +1 -0
  55. package/core/date-codes.js +1 -0
  56. package/core/default-names.js +1 -1
  57. package/core/formula-refs.js +1 -1
  58. package/core/input.js +1 -1
  59. package/core/numfmt.js +1 -1
  60. package/core/precision.js +1 -0
  61. package/core/region-input.js +1 -1
  62. package/core/rule-refs.js +1 -0
  63. package/core/shared-view.js +1 -0
  64. package/core/sheet.js +1 -1
  65. package/core/sparklines.js +1 -1
  66. package/core/sparse.js +1 -1
  67. package/core/spills.js +1 -0
  68. package/core/strings.js +1 -1
  69. package/core/structure.js +1 -1
  70. package/core/table-columns.js +1 -0
  71. package/core/tables.js +2 -2
  72. package/core/validation-ranges.js +1 -1
  73. package/core/whatif.js +1 -1
  74. package/core/workbook.js +1 -1
  75. package/datasheets/formula.js +1 -1
  76. package/datasheets/path-binding.js +1 -1
  77. package/datasheets/persist-writer.js +1 -1
  78. package/datasheets/report.js +1 -1
  79. package/extras/getdata/persist.js +2 -2
  80. package/extras/getdata/rows.js +1 -1
  81. package/extras/getdata/shared-steps.js +1 -0
  82. package/extras/getdata/steps-formula.js +1 -0
  83. package/extras/getdata/steps-more.js +1 -0
  84. package/extras/getdata/steps-tables.js +1 -0
  85. package/extras/getdata/steps.js +1 -1
  86. package/i18n/de/a11y.js +1 -0
  87. package/i18n/de/cells.js +2 -0
  88. package/i18n/de/charts.js +1 -0
  89. package/i18n/de/common.js +1 -0
  90. package/i18n/de/datasheets.js +1 -0
  91. package/i18n/de/format.js +1 -0
  92. package/i18n/de/misc.js +1 -0
  93. package/i18n/de/pivot.js +1 -0
  94. package/i18n/de/proofing.js +1 -0
  95. package/i18n/de/ribbon.js +1 -0
  96. package/i18n/de/shapes.js +1 -0
  97. package/i18n/de/shell.js +3 -0
  98. package/i18n/de/touch.js +1 -0
  99. package/i18n/de.js +1 -0
  100. package/i18n/en/cells.js +2 -1
  101. package/i18n/en/charts.js +1 -1
  102. package/i18n/en/format.js +1 -1
  103. package/i18n/en/misc.js +1 -1
  104. package/i18n/en/pivot.js +1 -1
  105. package/i18n/en/proofing.js +1 -1
  106. package/i18n/en/ribbon.js +1 -1
  107. package/i18n/en/shapes.js +1 -1
  108. package/i18n/en/shell.js +3 -2
  109. package/i18n/en/touch.js +1 -1
  110. package/i18n/es/a11y.js +1 -0
  111. package/i18n/es/cells.js +2 -0
  112. package/i18n/es/charts.js +1 -0
  113. package/i18n/es/common.js +1 -0
  114. package/i18n/es/datasheets.js +1 -0
  115. package/i18n/es/format.js +1 -0
  116. package/i18n/es/misc.js +1 -0
  117. package/i18n/es/pivot.js +1 -0
  118. package/i18n/es/proofing.js +1 -0
  119. package/i18n/es/ribbon.js +1 -0
  120. package/i18n/es/shapes.js +1 -0
  121. package/i18n/es/shell.js +3 -0
  122. package/i18n/es/touch.js +1 -0
  123. package/i18n/es.js +1 -0
  124. package/i18n/fr/a11y.js +1 -0
  125. package/i18n/fr/cells.js +2 -0
  126. package/i18n/fr/charts.js +1 -0
  127. package/i18n/fr/common.js +1 -0
  128. package/i18n/fr/datasheets.js +1 -0
  129. package/i18n/fr/format.js +1 -0
  130. package/i18n/fr/misc.js +1 -0
  131. package/i18n/fr/pivot.js +1 -0
  132. package/i18n/fr/proofing.js +1 -0
  133. package/i18n/fr/ribbon.js +1 -0
  134. package/i18n/fr/shapes.js +1 -0
  135. package/i18n/fr/shell.js +3 -0
  136. package/i18n/fr/touch.js +1 -0
  137. package/i18n/fr.js +1 -0
  138. package/i18n/index.js +1 -1
  139. package/i18n/languages.js +1 -1
  140. package/i18n/pl/cells.js +2 -1
  141. package/i18n/pl/charts.js +1 -1
  142. package/i18n/pl/format.js +1 -1
  143. package/i18n/pl/misc.js +1 -1
  144. package/i18n/pl/pivot.js +1 -1
  145. package/i18n/pl/proofing.js +1 -1
  146. package/i18n/pl/ribbon.js +1 -1
  147. package/i18n/pl/shapes.js +1 -1
  148. package/i18n/pl/shell.js +3 -2
  149. package/i18n/pl/touch.js +1 -1
  150. package/io/blob-sink.js +1 -0
  151. package/io/canonical-xml.js +1 -0
  152. package/io/client.js +1 -1
  153. package/io/crypto/cfb-build.js +1 -0
  154. package/io/crypto/cfb-read.js +1 -1
  155. package/io/crypto/cfb-write.js +1 -1
  156. package/io/crypto/errors.js +1 -1
  157. package/io/csv.js +8 -8
  158. package/io/foreign-sheets.js +2 -2
  159. package/io/io.worker.js +1 -1
  160. package/io/open-package.js +1 -0
  161. package/io/package-paths.js +1 -1
  162. package/io/plan.js +1 -1
  163. package/io/text-split.js +3 -3
  164. package/io/xls/chart-sheet.js +1 -0
  165. package/io/xls/chart.js +1 -0
  166. package/io/xls/crypt.js +1 -0
  167. package/io/xls/dml-color.js +1 -0
  168. package/io/xls/drawing.js +1 -0
  169. package/io/xls/formula.js +1 -0
  170. package/io/xls/geometry.js +1 -0
  171. package/io/xls/index.js +1 -0
  172. package/io/xls/pictures.js +1 -0
  173. package/io/xls/pivot.js +1 -0
  174. package/io/xls/props.js +1 -0
  175. package/io/xls/records.js +1 -0
  176. package/io/xls/shapes.js +1 -0
  177. package/io/xls/sheet-ext.js +1 -0
  178. package/io/xls/sheet.js +1 -0
  179. package/io/xls/styles.js +1 -0
  180. package/io/xls/vba.js +1 -0
  181. package/io/xls/workbook.js +1 -0
  182. package/io/xlsb/filter.js +1 -0
  183. package/io/xlsb/formula.js +2 -0
  184. package/io/xlsb/functions.js +1 -0
  185. package/io/xlsb/index.js +1 -0
  186. package/io/xlsb/parts.js +1 -0
  187. package/io/xlsb/pivot.js +1 -0
  188. package/io/xlsb/records.js +1 -0
  189. package/io/xlsb/sheet-ext.js +1 -0
  190. package/io/xlsb/sheet.js +1 -0
  191. package/io/xlsb/slicer.js +1 -0
  192. package/io/xlsb/styles.js +1 -0
  193. package/io/xlsb/workbook.js +1 -0
  194. package/io/xlsb/xml.js +2 -0
  195. package/io/xlsx-read.js +1 -1
  196. package/io/xlsx-styles.js +2 -2
  197. package/io/xlsx-tail.js +1 -1
  198. package/io/xlsx-write.js +2 -2
  199. package/io/xml-escape.js +1 -1
  200. package/io/xml-scan.js +2 -2
  201. package/io/zip-reader.js +1 -1
  202. package/objects/chart-model.js +1 -1
  203. package/objects/drawing-xml.js +1 -1
  204. package/package.json +1 -1
  205. package/pivot/calc-items.js +1 -0
  206. package/pivot/engine.js +1 -1
  207. package/pivot/xml.js +2 -2
  208. package/print/note-pages.js +2 -2
  209. package/print/page-setup.js +1 -1
  210. package/print/paginate.js +1 -1
  211. package/print/pdf-crypt.js +1 -0
  212. package/print/pdf-tags.js +1 -0
  213. package/print/pdf.js +24 -13
  214. package/print/render-page.js +3 -3
  215. package/print/shown-notes.js +1 -0
  216. package/shapes/form-xml.js +1 -1
  217. package/slicers/custom-styles.js +1 -1
  218. package/slicers/format.js +1 -1
  219. package/slicers/structured.js +1 -1
  220. package/slicers/write.js +1 -1
  221. package/table-view/files.js +1 -1
  222. package/table-view/mount.js +1 -1
  223. package/table-view/version.js +1 -1
  224. package/ui/icons.js +1 -1
  225. package/ui/menu-base.js +1 -1
  226. package/ui/protection-ui.js +1 -1
@@ -1 +1 @@
1
- import{Workbook as B}from"../core/workbook.js";import{BOOL as T,ERR as O,NUM as D,STR as F}from"../core/sheet.js";import{Engine as W}from"../calc/engine.js";import{readCsv as _,CsvWriter as Z}from"../io/csv.js";import{ansiEncoding as H}from"../io/encoding.js";import{buildBlock as U,newBlockBuffers as G}from"../io/export-blocks.js";import{buildPlan as J}from"../io/plan.js";import{writeXlsx as V}from"../io/xlsx-write.js";import{MAX_ROWS as A,MAX_COLS as I,colIndex as q,colName as K}from"../core/address.js";import{changeOutline as Q}from"../core/whatif.js";import{display as Y}from"./model.js";async function he(a,w={},p){if(/\.(?:csv|tsv|txt)$/i.test(a.name)){const e=new B;let s=0;const u={size:a.size,slice:(...n)=>a.slice(...n),stream:()=>a.stream().pipeThrough(new TransformStream({transform(n,t){s+=n.byteLength,t.enqueue(n)}}))};return await _(u,{onProgress:n=>p?.({records:Math.max(0,n-1),loaded:s,total:a.size}),delimiter:w.delimiter||(/\.tsv$/i.test(a.name)?" ":void 0),textColumns:new Set(w.textColumns),fallback:H(globalThis.navigator?.language),preserveIdentifiers:!0,addString:n=>e.strings.add(n),styleFor:n=>e.styles.derive(0,{numFmt:n}),onBatch:n=>e.sheet.applyBatch(n)}),{book:e,tables:[]}}const{IoClient:o}=await import("../io/client.js"),f=new o;try{const e=p?await j(a):null,s=await f.open(a,{onProgress:({cells:r})=>p?.({records:e?.columns?Math.floor(r/e.columns):null,loaded:r,total:e?.cells??null})}),{tables:u=[],names:n=[],fullCalcOnLoad:t,manualCalc:c}=f.meta;s.engine=new W(s),s.engine.manual=c,s.engine.setNames(n),s.engine.setTables(u.map(r=>({...r,sheet:s.sheets[r.sheetIndex]}))),s.engine.buildGraph({fullCalc:t}),c||await s.engine.whenIdle();const{openZip:m}=await import("../io/zip-reader.js"),h=await m(await f.packageOf(a));if([...h.entries.keys()].some(r=>r.startsWith("customXml/"))){const{DataSheets:r}=await import("../datasheets/manager.js"),y=new r(s);if(await y.load(h))for(const x of y.manager.tables.values())x.autoSync=!1,x.remote=null}return{book:s,tables:u}}finally{f.close()}}async function j(a){try{const{openZip:w}=await import("../io/zip-reader.js"),p=await w(a);let o=0,f=0,e=0;for(const s of p.entries.keys()){if(!/^xl\/worksheets\/[^/]+\.xml$/.test(s))continue;const u=(await p.stream(s)).pipeThrough(new TextDecoderStream).getReader();let n="";for(;n.length<4096&&!/<(?:\w+:)?sheetData/.test(n);){const{done:h,value:r}=await u.read();if(h)break;n+=r}u.cancel().catch(()=>{});const t=n.match(/<(?:\w+:)?dimension\s+ref="\$?([A-Z]+)\$?(\d+)(?::\$?([A-Z]+)\$?(\d+))?"/);if(!t)return null;const c=t[3]?q(t[3])-q(t[1])+1:1,m=t[4]?Number(t[4])-Number(t[2])+1:1;o+=c*m,c*m>e&&(e=c*m,f=c)}return o>1?{cells:o,columns:f}:null}catch{return null}}function ge({book:a,tables:w}){const p=[];return a.sheets.forEach((o,f)=>{if(!(o.hidden||o.isChartSheet)){if(o.kindName==="table"){const e=o.view.spec,s=o.table.byName,u=c=>c.filter(m=>s.has(m.field)),n=u(e.columns).map(({field:c,caption:m,hidden:h,pinned:r,format:y})=>({field:c,caption:m,hidden:h,pinned:r,format:y})),t=n.some(c=>!c.hidden)?{columns:n,search:e.search,sort:u(e.sort),filters:u(e.filters),groups:u(e.groups).map(({field:c})=>({field:c})),total:u(e.totals)[0]??null,collapsed:[...o.view.collapsedPaths]}:null;p.push({name:o.name,sheet:f,native:!0,initialState:t,range:{r0:0,c0:0,r1:o.maxRow,c1:o.maxCol}});return}for(const e of w.filter(s=>s.sheetIndex===f))p.push({name:e.name,sheet:f,headers:e.columns,headerRows:e.headerRows,range:{r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1}});o.maxCol>=0&&o.maxRow>=0&&p.push({name:o.name,sheet:f,whole:!0,range:{r0:0,c0:0,r1:o.maxRow,c1:o.maxCol}})}}),p.sort((o,f)=>+!!o.whole-+!!f.whole)}async function we(a,w,{layout:p=null}={}){const{view:o}=a;if(o.refresh(),p&&w!=="csv")return ne(a,w,p);const f=o.columns,e=[],s={write:t=>{e.push(new Blob([t]))}};if(w==="csv"){const t=new Z(s,",",{bom:!0});await t.batch(f.map((m,h)=>[0,h,m.caption]));let c=[];for(let m=0;m<o.filteredCount;m++)for(let h=0;h<f.length;h++){const r=f[h];c.push([m+1,h,Y(r.col.get(o.perm[m]),r.format)]),c.length===2048&&(await t.batch(c),c=[])}return await t.batch(c),await t.finish(o.filteredCount),new Blob(e,{type:"text/csv;charset=utf-8"})}if(!["xlsx","pdf"].includes(w)||o.filteredCount>=A||f.length>I)throw new Error("The result exceeds the XLSX row limit or the format is unsupported.");const u=new B,n=u.sheet;return n.name="Results",f.forEach((t,c)=>{n.setCell(0,c,F,u.strings.add(t.caption));const m=u.styles.derive(0,{numFmt:t.format});for(let h=0;h<o.filteredCount;h++){const r=o.perm[h],y=t.col.kind(r);if(!y)continue;const x=t.col.get(r),S=y===F?u.strings.add(x):y===T?Number(x):y===O?x.index:x;n.setCell(h+1,c,y,S),m&&y===D&&n.setStyle(h+1,c,m)}}),L(u,n,w)}async function L(a,w,p){const o=[],f={write:u=>{o.push(new Blob([u]))}};if(p==="pdf"){const{createPrintJob:u}=await import("../print/paginate.js"),{writeJobPdf:n}=await import("../print/render-page.js"),t=(await import("../print/page-setup.js")).getPageSetup(w);return t.fitToPage=!0,t.fitToWidth=1,t.fitToHeight=0,await n(u(a,{sheets:[0]}),f,{title:"Results"}),new Blob(o,{type:"application/pdf"})}const e=J(a,{strings:0,styles:0,sheets:0}),s=G();return await V(f,e,{block:(u,n)=>U(w,a.strings,n,s)}),new Blob(o,{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})}const z={bold:!0,fill:"#F2F2F2"},ee={bold:!0,fill:"#F7F7F7"},P={good:{fill:"#D9F2E1",color:"#14532D"},bad:{fill:"#FDE0DD",color:"#8A1C12"},warn:{fill:"#FCEFC9",color:"#6B4A00"},info:{fill:"#DDE9FB",color:"#163D7A"},strong:{bold:!0}},te={gt:"greaterThan",gte:"greaterThanOrEqual",lt:"lessThan",lte:"lessThanOrEqual",equal:"equal",notEqual:"notEqual",between:"between"},X=a=>typeof a=="number"||/^-?\d+(\.\d+)?$/.test(String(a))?String(a):`"${String(a).replace(/"/g,'""')}"`;function oe(a,w,p,o,f){const e=[];for(const s of w??[]){const u={priority:f++};if(s.type==="bar")e.push({...u,type:"dataBar",formulas:[],dataBar:{cfvo:[{type:"min"},{type:"max"}],color:{rgb:"FF638EC6"},showValue:!0}});else if(s.type==="scale")e.push({...u,type:"colorScale",formulas:[],colorScale:{cfvo:[{type:"min"},{type:"percentile",val:"50"},{type:"max"}],colors:[{rgb:"FFF8696B"},{rgb:"FFFFEB84"},{rgb:"FF63BE7B"}]}});else if(s.type==="value"){const n=s.color||s.background?{...s.background&&{fill:s.background},...s.color&&{color:s.color}}:P[s.style]??P.info;a.dxfs??=[],a.dxfs.push(n);const t=a.dxfs.length-1;if(s.op==="contains"){const c=X(String(s.value));e.push({...u,dxfId:t,type:"containsText",operator:"containsText",text:String(s.value),formulas:[`NOT(ISERROR(SEARCH(${c},${o})))`]})}else e.push({...u,dxfId:t,type:"cellIs",operator:te[s.op]??"equal",formulas:[s.value,s.op==="between"?s.value2:void 0].filter(c=>c!==void 0).map(X)})}}return e.length?{sqref:p,rules:e}:null}async function ne(a,w,p){const{view:o,table:f}=a,e=o.columns,s=new Map(p.bands??[]),u=new Map(p.widths??[]),n=new B,t=n.sheet;t.name="Results";const c=n.styles.derive(0,z),m=n.styles.derive(0,ee),h=e.map(d=>n.styles.derive(0,{numFmt:d.format}));let r=0;if([...s.values()].some(Boolean)){let d=0;for(let i=0;i<=e.length;i++){const l=i<e.length?s.get(e[i].field)??"":null,b=s.get(e[d]?.field)??"";if(!(i<e.length&&l===b)){b&&(t.setCell(r,d,F,n.strings.add(b)),i-1>d&&t.addMerge({r0:r,c0:d,r1:r,c1:i-1}));for(let g=d;g<i;g++)t.setStyle(r,g,n.styles.derive(0,{...z,hAlign:"center"}));d=i}}r++}e.forEach((d,i)=>{t.setCell(r,i,F,n.strings.add(d.caption)),t.setStyle(r,i,c)});const y=++r;if(o.count+y+1>=A||e.length>I)throw new Error("The result exceeds the XLSX row limit or the format is unsupported.");const x=(d,i,l,b)=>{if(l==null||l==="")return;const g=typeof l=="number"?D:typeof l=="boolean"?T:typeof l=="string"?F:l?.index!=null?O:F,v=g===F?n.strings.add(String(l?.code??l)):g===T?Number(l):g===O?l.index:l;t.setCell(d,i,g,v),b&&t.setStyle(d,i,b)},S=a.total?.field,E=e.findIndex(d=>d.field===S),R=[],C=r;for(let d=0;d<o.count;d++,r++){const i=o.rowInfo(d);if(i.kind==="record"){a.rowValues(e,i.record).forEach((b,g)=>x(r,g,b,typeof b=="number"?h[g]:0)),R.push(o.spec.hierarchy?i.level:o.spec.groups.length);continue}x(r,0,o.groupCaption(i.node),m);for(let l=1;l<e.length;l++)t.setStyle(r,l,m);if(E>=0&&i.kind==="group"){const l=o.summaryFor(i.node,S);x(r,E,Number.isFinite(l)?l:null,n.styles.derive(m,{numFmt:e[E].format}))}R.push(i.level)}let $=0;R.forEach((d,i)=>{const l=Math.min(7,d);l&&Q(t,"row",C+i,C+i,l),$=Math.max($,l)});const N=r-1;if(p.totals){const{aggregate:d}=await import("../datasheets/view.js"),i=new Map((a.layout??[]).map(l=>[l.field,l.total]));e.forEach((l,b)=>{const g=i.get(l.field),v=g?d(l.col,g,o.perm,0,o.filteredCount):null;t.setStyle(r,b,c),b===0&&!g&&x(r,0,"Total",c),Number.isFinite(v)&&x(r,b,v,n.styles.derive(c,{numFmt:g==="count"?"#,##0":l.format}))}),r++}e.forEach((d,i)=>{const l=u.get(d.field);Number.isFinite(l)&&t.cols.setSize(i,Math.round(l))}),t.colsChanged=!0,t.frozenRows=y,t.viewChanged=!0;const k=[];let M=1;if(N>=C){const d=new Map((a.layout??[]).map(i=>[i.field,i.rules]));e.forEach((i,l)=>{const b=K(l),g=oe(n,d.get(i.field),`${b}${C+1}:${b}${N+1}`,`${b}${C+1}`,M);g&&(k.push(g),M+=g.rules.length)})}return k.length&&(t.cf=k,t.cfChanged=!0),L(n,t,w)}export{we as exportResults,he as openFile,ge as sourcesOf};
1
+ import{Workbook as B}from"../core/workbook.js";import{BOOL as T,ERR as O,NUM as D,STR as F}from"../core/sheet.js";import{Engine as W}from"../calc/engine.js";import{readCsv as _,CsvWriter as Z}from"../io/csv.js";import{ansiEncoding as H}from"../io/encoding.js";import{buildBlock as U,newBlockBuffers as G}from"../io/export-blocks.js";import{buildPlan as J}from"../io/plan.js";import{writeXlsx as V}from"../io/xlsx-write.js";import{MAX_ROWS as A,MAX_COLS as I,colIndex as q,colName as K}from"../core/address.js";import{changeOutline as Q}from"../core/whatif.js";import{display as Y}from"./model.js";async function he(a,w={},p){if(/\.(?:csv|tsv|txt)$/i.test(a.name)){const e=new B;let n=0;const u={size:a.size,slice:(...s)=>a.slice(...s),stream:()=>a.stream().pipeThrough(new TransformStream({transform(s,t){n+=s.byteLength,t.enqueue(s)}}))};return await _(u,{onProgress:s=>p?.({records:Math.max(0,s-1),loaded:n,total:a.size}),delimiter:w.delimiter||(/\.tsv$/i.test(a.name)?" ":void 0),textColumns:new Set(w.textColumns),fallback:H(globalThis.navigator?.language),preserveIdentifiers:!0,sepLine:!0,addString:s=>e.strings.add(s),styleFor:s=>e.styles.derive(0,{numFmt:s}),onBatch:s=>e.sheet.applyBatch(s)}),{book:e,tables:[]}}const{IoClient:o}=await import("../io/client.js"),f=new o;try{const e=p?await j(a):null,n=await f.open(a,{onProgress:({cells:r})=>p?.({records:e?.columns?Math.floor(r/e.columns):null,loaded:r,total:e?.cells??null})}),{tables:u=[],names:s=[],fullCalcOnLoad:t,manualCalc:c}=f.meta;n.engine=new W(n),n.engine.manual=c,n.engine.precise=f.meta.fullPrecision===!1,n.engine.setNames(s),n.engine.setTables(u.map(r=>({...r,sheet:n.sheets[r.sheetIndex]}))),n.engine.buildGraph({fullCalc:t}),c||await n.engine.whenIdle();const{openZip:m}=await import("../io/zip-reader.js"),h=await m(await f.packageOf(a));if([...h.entries.keys()].some(r=>r.startsWith("customXml/"))){const{DataSheets:r}=await import("../datasheets/manager.js"),y=new r(n);if(await y.load(h))for(const x of y.manager.tables.values())x.autoSync=!1,x.remote=null}return{book:n,tables:u}}finally{f.close()}}async function j(a){try{const{openZip:w}=await import("../io/zip-reader.js"),p=await w(a);let o=0,f=0,e=0;for(const n of p.entries.keys()){if(!/^xl\/worksheets\/[^/]+\.xml$/.test(n))continue;const u=(await p.stream(n)).pipeThrough(new TextDecoderStream).getReader();let s="";for(;s.length<4096&&!/<(?:\w+:)?sheetData/.test(s);){const{done:h,value:r}=await u.read();if(h)break;s+=r}u.cancel().catch(()=>{});const t=s.match(/<(?:\w+:)?dimension\s+ref="\$?([A-Z]+)\$?(\d+)(?::\$?([A-Z]+)\$?(\d+))?"/);if(!t)return null;const c=t[3]?q(t[3])-q(t[1])+1:1,m=t[4]?Number(t[4])-Number(t[2])+1:1;o+=c*m,c*m>e&&(e=c*m,f=c)}return o>1?{cells:o,columns:f}:null}catch{return null}}function ge({book:a,tables:w}){const p=[];return a.sheets.forEach((o,f)=>{if(!(o.hidden||o.isChartSheet)){if(o.kindName==="table"){const e=o.view.spec,n=o.table.byName,u=c=>c.filter(m=>n.has(m.field)),s=u(e.columns).map(({field:c,caption:m,hidden:h,pinned:r,format:y})=>({field:c,caption:m,hidden:h,pinned:r,format:y})),t=s.some(c=>!c.hidden)?{columns:s,search:e.search,sort:u(e.sort),filters:u(e.filters),groups:u(e.groups).map(({field:c})=>({field:c})),total:u(e.totals)[0]??null,collapsed:[...o.view.collapsedPaths]}:null;p.push({name:o.name,sheet:f,native:!0,initialState:t,range:{r0:0,c0:0,r1:o.maxRow,c1:o.maxCol}});return}for(const e of w.filter(n=>n.sheetIndex===f))p.push({name:e.name,sheet:f,headers:e.columns,headerRows:e.headerRows,range:{r0:e.r0,c0:e.c0,r1:e.r1-e.totalsRows,c1:e.c1}});o.maxCol>=0&&o.maxRow>=0&&p.push({name:o.name,sheet:f,whole:!0,range:{r0:0,c0:0,r1:o.maxRow,c1:o.maxCol}})}}),p.sort((o,f)=>+!!o.whole-+!!f.whole)}async function we(a,w,{layout:p=null}={}){const{view:o}=a;if(o.refresh(),p&&w!=="csv")return ne(a,w,p);const f=o.columns,e=[],n={write:t=>{e.push(new Blob([t]))}};if(w==="csv"){const t=new Z(n,",",{bom:!0});await t.batch(f.map((m,h)=>[0,h,m.caption]));let c=[];for(let m=0;m<o.filteredCount;m++)for(let h=0;h<f.length;h++){const r=f[h];c.push([m+1,h,Y(r.col.get(o.perm[m]),r.format)]),c.length===2048&&(await t.batch(c),c=[])}return await t.batch(c),await t.finish(o.filteredCount),new Blob(e,{type:"text/csv;charset=utf-8"})}if(!["xlsx","pdf"].includes(w)||o.filteredCount>=A||f.length>I)throw new Error("The result exceeds the XLSX row limit or the format is unsupported.");const u=new B,s=u.sheet;return s.name="Results",f.forEach((t,c)=>{s.setCell(0,c,F,u.strings.add(t.caption));const m=u.styles.derive(0,{numFmt:t.format});for(let h=0;h<o.filteredCount;h++){const r=o.perm[h],y=t.col.kind(r);if(!y)continue;const x=t.col.get(r),S=y===F?u.strings.add(x):y===T?Number(x):y===O?x.index:x;s.setCell(h+1,c,y,S),m&&y===D&&s.setStyle(h+1,c,m)}}),L(u,s,w)}async function L(a,w,p){const o=[],f={write:u=>{o.push(new Blob([u]))}};if(p==="pdf"){const{createPrintJob:u}=await import("../print/paginate.js"),{writeJobPdf:s}=await import("../print/render-page.js"),t=(await import("../print/page-setup.js")).getPageSetup(w);return t.fitToPage=!0,t.fitToWidth=1,t.fitToHeight=0,await s(u(a,{sheets:[0]}),f,{title:"Results"}),new Blob(o,{type:"application/pdf"})}const e=J(a,{strings:0,styles:0,sheets:0}),n=G();return await V(f,e,{block:(u,s)=>U(w,a.strings,s,n)}),new Blob(o,{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})}const P={bold:!0,fill:"#F2F2F2"},ee={bold:!0,fill:"#F7F7F7"},z={good:{fill:"#D9F2E1",color:"#14532D"},bad:{fill:"#FDE0DD",color:"#8A1C12"},warn:{fill:"#FCEFC9",color:"#6B4A00"},info:{fill:"#DDE9FB",color:"#163D7A"},strong:{bold:!0}},te={gt:"greaterThan",gte:"greaterThanOrEqual",lt:"lessThan",lte:"lessThanOrEqual",equal:"equal",notEqual:"notEqual",between:"between"},X=a=>typeof a=="number"||/^-?\d+(\.\d+)?$/.test(String(a))?String(a):`"${String(a).replace(/"/g,'""')}"`;function oe(a,w,p,o,f){const e=[];for(const n of w??[]){const u={priority:f++};if(n.type==="bar")e.push({...u,type:"dataBar",formulas:[],dataBar:{cfvo:[{type:"min"},{type:"max"}],color:{rgb:"FF638EC6"},showValue:!0}});else if(n.type==="scale")e.push({...u,type:"colorScale",formulas:[],colorScale:{cfvo:[{type:"min"},{type:"percentile",val:"50"},{type:"max"}],colors:[{rgb:"FFF8696B"},{rgb:"FFFFEB84"},{rgb:"FF63BE7B"}]}});else if(n.type==="value"){const s=n.color||n.background?{...n.background&&{fill:n.background},...n.color&&{color:n.color}}:z[n.style]??z.info;a.dxfs??=[],a.dxfs.push(s);const t=a.dxfs.length-1;if(n.op==="contains"){const c=X(String(n.value));e.push({...u,dxfId:t,type:"containsText",operator:"containsText",text:String(n.value),formulas:[`NOT(ISERROR(SEARCH(${c},${o})))`]})}else e.push({...u,dxfId:t,type:"cellIs",operator:te[n.op]??"equal",formulas:[n.value,n.op==="between"?n.value2:void 0].filter(c=>c!==void 0).map(X)})}}return e.length?{sqref:p,rules:e}:null}async function ne(a,w,p){const{view:o,table:f}=a,e=o.columns,n=new Map(p.bands??[]),u=new Map(p.widths??[]),s=new B,t=s.sheet;t.name="Results";const c=s.styles.derive(0,P),m=s.styles.derive(0,ee),h=e.map(d=>s.styles.derive(0,{numFmt:d.format}));let r=0;if([...n.values()].some(Boolean)){let d=0;for(let i=0;i<=e.length;i++){const l=i<e.length?n.get(e[i].field)??"":null,b=n.get(e[d]?.field)??"";if(!(i<e.length&&l===b)){b&&(t.setCell(r,d,F,s.strings.add(b)),i-1>d&&t.addMerge({r0:r,c0:d,r1:r,c1:i-1}));for(let g=d;g<i;g++)t.setStyle(r,g,s.styles.derive(0,{...P,hAlign:"center"}));d=i}}r++}e.forEach((d,i)=>{t.setCell(r,i,F,s.strings.add(d.caption)),t.setStyle(r,i,c)});const y=++r;if(o.count+y+1>=A||e.length>I)throw new Error("The result exceeds the XLSX row limit or the format is unsupported.");const x=(d,i,l,b)=>{if(l==null||l==="")return;const g=typeof l=="number"?D:typeof l=="boolean"?T:typeof l=="string"?F:l?.index!=null?O:F,v=g===F?s.strings.add(String(l?.code??l)):g===T?Number(l):g===O?l.index:l;t.setCell(d,i,g,v),b&&t.setStyle(d,i,b)},S=a.total?.field,E=e.findIndex(d=>d.field===S),R=[],C=r;for(let d=0;d<o.count;d++,r++){const i=o.rowInfo(d);if(i.kind==="record"){a.rowValues(e,i.record).forEach((b,g)=>x(r,g,b,typeof b=="number"?h[g]:0)),R.push(o.spec.hierarchy?i.level:o.spec.groups.length);continue}x(r,0,o.groupCaption(i.node),m);for(let l=1;l<e.length;l++)t.setStyle(r,l,m);if(E>=0&&i.kind==="group"){const l=o.summaryFor(i.node,S);x(r,E,Number.isFinite(l)?l:null,s.styles.derive(m,{numFmt:e[E].format}))}R.push(i.level)}let $=0;R.forEach((d,i)=>{const l=Math.min(7,d);l&&Q(t,"row",C+i,C+i,l),$=Math.max($,l)});const N=r-1;if(p.totals){const{aggregate:d}=await import("../datasheets/view.js"),i=new Map((a.layout??[]).map(l=>[l.field,l.total]));e.forEach((l,b)=>{const g=i.get(l.field),v=g?d(l.col,g,o.perm,0,o.filteredCount):null;t.setStyle(r,b,c),b===0&&!g&&x(r,0,"Total",c),Number.isFinite(v)&&x(r,b,v,s.styles.derive(c,{numFmt:g==="count"?"#,##0":l.format}))}),r++}e.forEach((d,i)=>{const l=u.get(d.field);Number.isFinite(l)&&t.cols.setSize(i,Math.round(l))}),t.colsChanged=!0,t.frozenRows=y,t.viewChanged=!0;const k=[];let M=1;if(N>=C){const d=new Map((a.layout??[]).map(i=>[i.field,i.rules]));e.forEach((i,l)=>{const b=K(l),g=oe(s,d.get(i.field),`${b}${C+1}:${b}${N+1}`,`${b}${C+1}`,M);g&&(k.push(g),M+=g.rules.length)})}return k.length&&(t.cf=k,t.cfChanged=!0),L(s,t,w)}export{we as exportResults,he as openFile,ge as sourcesOf};
@@ -1 +1 @@
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,.xltm",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
+ 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,.xlsb,.xls,.xlt,.xltx,.xltm",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
- const o="1.1.2";export{o as VERSION};
1
+ const o="1.2.0";export{o as VERSION};