(function(root) { 'use strict'; const limits={bytes:256*1024,rows:200,columns:32,cellBytes:16*1024}; const bytes=s=>new TextEncoder().encode(s).length; function parseRecords(source,separator) { if(typeof source!=='string'||bytes(source)>limits.bytes||source.includes('\0'))throw Error('size'); const bom=source.startsWith('\ufeff')?'\ufeff':'',rows=[]; let i=bom.length,lineEnding='',cells=[]; while(ilimits.cellBytes||cells.length>=limits.columns)throw Error('size'); cells.push({value,raw:source.slice(start,i),original:value}); if(source[i]===separator){i++;continue;} let end=''; if(source[i]==='\r'){if(source[i+1]!=='\n')throw Error('syntax');end='\r\n';i+=2;} else if(source[i]==='\n'){end='\n';i++;} if(!lineEnding&&end)lineEnding=end; rows.push({cells,end});cells=[];if(rows.length>limits.rows)throw Error('size'); } return {source,bom,lineEnding:lineEnding||'\r\n',rows}; } function parse(source){return parseRecords(source,',');} function encode(value){return /[",\r\n]/.test(value)||/^\s/.test(value)?'"'+value.replace(/"/g,'""')+'"':value;} function serialize(model){ const source=model.bom+model.rows.map(row=>{const record=row.cells.map(c=>c.value===c.original?c.raw:encode(c.value)).join(',');return record+(row.end||(!record?model.lineEnding:''));}).join(''); parse(source);return source; } function edit(source,action,row=0,column=0,value=''){ const m=parse(source),blank=()=>({value:'',raw:'',original:''}); if(action==='cell'){ if(!m.rows[row]?.cells[column]||typeof value!=='string')throw Error('cell'); m.rows[row].cells[column].value=value; }else if(action==='add-row'){ const last=m.rows.at(-1),cols=Math.max(1,...m.rows.map(r=>r.cells.length)); if(last&&!last.end)last.end=m.lineEnding; // A newline is necessary to distinguish a blank final row from no row. m.rows.push({cells:Array.from({length:cols},blank),end:m.lineEnding}); }else if(action==='add-column'){ if(!m.rows.length)m.rows.push({cells:[blank()],end:m.lineEnding}); const cols=Math.max(...m.rows.map(r=>r.cells.length)); for(const r of m.rows){while(r.cells.lengthr.cells[column]))throw Error('column'); for(const r of m.rows){r.cells.splice(column,1);if(!r.cells.length)r.cells.push(blank());} }else throw Error('action'); return serialize(m); } function paste(source,row,column,clipboard){ // Clipboard tables use tabs, not commas. Parse and validate the entire // operation before returning anything to the editor or its undo history. const m=parse(source),incoming=parseRecords(clipboard,'\t'); if(!Number.isInteger(row)||!Number.isInteger(column)||row<0||column<0||row>=limits.rows||column>=limits.columns)throw Error('cell'); if(!incoming.rows.length)return source; const width=Math.max(...incoming.rows.map(r=>r.cells.length)); if(row+incoming.rows.length>limits.rows||column+width>limits.columns)throw Error('size'); const blank=()=>({value:'',raw:'',original:''}); while(m.rows.length