oficina / sheets Public

Clone
git clone https://amadan.net/oficina/sheets

Plain git — no account needed to clone.

Download

Download this file

1/* The grid.
2 *
3 * It paints strings the server computed and never evaluates a formula
4 * itself. parseFormulas is off below, deliberately: our engine and
5 * Jspreadsheet's would disagree on the first SUM(1,2,"3"), and invisibly:
6 * both would look like a number in a cell.
7 *
8 * Cell data holds DISPLAY strings; the raw input lives in a side map,
9 * so the grid shows 42 and the formula bar =6*7, as a spreadsheet does;
10 * raw in the data would show =6*7 in every cell.
11 *
12 * The chrome above and below the grid is not wired here. This module
13 * publishes window.SheetsGrid and menubar.js and commands.js build on
14 * it, because everything they add — a menu bar, a toolbar, shortcuts,
15 * format writes — would otherwise put this file past the 300-line cap
16 * and, worse, put the selection model and the button wiring in one
17 * place where only the first has any reason to be subtle.
18 */
19(function () {
20 'use strict';
21
22 var surface = document.querySelector('[data-sheet-surface]');
23 if (!surface || typeof jspreadsheet !== 'function') return;
24
25 var sheetId = surface.dataset.sheetId;
26 var tabId = surface.dataset.tabId;
27 var rows = parseInt(surface.dataset.rows, 10) || 100;
28 var cols = parseInt(surface.dataset.cols, 10) || 26;
29 var base = '/api/sheets/' + sheetId + '/tabs/' + tabId;
30 var host = surface.querySelector('[data-sheet-grid]');
31
32 /* paint.js, or no-ops. Resolved once so no call site guards, and so a
33 * module that failed to load costs styling and not the grid. */
34 var noop = function () {};
35 var paint = window.SheetsPaint || { bind: noop, repaint: noop, sweep: noop };
36
37 /* A per-tab id so this tab can recognise its own edit coming back
38 * over the stream. Without it the tab you typed in repaints the cell
39 * you are still editing. */
40 var clientId = 'c' + Math.random().toString(36).slice(2) + Date.now().toString(36);
41
42 /* meta is everything known about a cell that is not its painted
43 * string: "r,c" -> {raw, f, n}. One map rather than three parallel
44 * ones, because every path that adds a cell has to add it to all of
45 * them and every path that clears has to clear all of them — and the
46 * one that forgets is invisible until a format outlives its cell. */
47 var meta = Object.create(null);
48 var styles = Object.create(null); /* format key -> the style */
49 var held = Object.create(null); /* "r,c" -> a display that landed under an open editor */
50 var version = 0; /* the newest version painted */
51 var ws = null;
52 var sel = null; /* {r,c,r2,c2}; r,c is the anchor */
53 var applying = false; /* true while we write into the grid ourselves */
54 var listeners = [];
55
56 function key(r, c) { return r + ',' + c; }
57 function at(r, c) { return meta[key(r, c)] || {}; }
58
59 function blank() {
60 var grid = [], r, c, row;
61 for (r = 0; r < rows; r++) {
62 for (row = [], c = 0; c < cols; c++) row.push('');
63 grid.push(row);
64 }
65 return grid;
66 }
67
68 /* applyBatch paints a server response.
69 *
70 * Out-of-order paints are discarded BY VERSION, not by arrival (spec
71 * §7). Without this, optimistic painting plus last-write-wins
72 * produces a visibly wrong grid under two concurrent editors — the
73 * exact bug the optimism is meant to hide.
74 *
75 * A format write does not advance the version (nothing is appended to
76 * the event log for it), so the equal case must pass, not be
77 * discarded — hence `<` and not `<=`. */
78 function applyBatch(payload) {
79 if (!payload || !payload.cells) return;
80 if (payload.version && payload.version < version) return;
81 if (payload.version) version = payload.version;
82
83 /* MERGE, never replace. A batch carries only the formats it
84 * mentions, so replacing would drop every style outside the edited
85 * cell the first time somebody typed into an imported sheet. */
86 if (payload.formats) {
87 Object.keys(payload.formats).forEach(function (k) {
88 styles[k] = payload.formats[k];
89 });
90 }
91
92 /* Layout arrives with its batch: a column widened elsewhere widens here. */
93 if (window.SheetsSizes) window.SheetsSizes.apply(ws, payload.sizes);
94
95 applying = true;
96 try {
97 payload.cells.forEach(function (cell) {
98 if (cell.r >= rows || cell.c >= cols) return;
99 meta[key(cell.r, cell.c)] = { raw: cell.raw || '', f: cell.f, n: cell.n };
100 /* Never set the td under an open editor (that wiped the edit, and
101 * closing it saved an empty cell): hold the display until it closes. */
102 var ed = ws.edition;
103 if (ed && +ed[2] === cell.c && +ed[3] === cell.r) held[key(cell.r, cell.c)] = cell.display;
104 else ws.setValueFromCoords(cell.c, cell.r, cell.display, true);
105 paint.repaint(cell.r, cell.c);
106 });
107 } finally {
108 applying = false;
109 }
110 if (payload.resync) refetch();
111 announce();
112 }
113
114 function refetch() {
115 fetch(base + '/cells?rows=' + rows + '&cols=' + cols, { credentials: 'same-origin' })
116 .then(function (r) { return r.ok ? r.json() : null; })
117 .then(function (payload) {
118 if (!payload) return;
119 /* A snapshot supersedes everything, including formats a cell
120 * lost while this tab was disconnected — those cells are simply
121 * absent from it, so nothing below would ever unpaint them. */
122 version = 0;
123 meta = Object.create(null);
124 styles = Object.create(null);
125 paint.sweep(host);
126 applyBatch(payload);
127 })
128 .catch(function () { /* the stream's own reconnect will try again */ });
129 }
130
131 /* post sends one change (a cell, a format patch, a size: one exchange,
132 * so the version check and failure path cannot drift between three) and
133 * paints the batch it produced, even over typed text: the server owns
134 * the displayed string ("=6*7" is "42"). Every failure refetches: the
135 * write may or may not have landed, and the grid must not keep showing
136 * something the server never accepted. */
137 function post(path, body) {
138 body.client = clientId;
139 return fetch(base + path, {
140 method: 'POST',
141 credentials: 'same-origin',
142 headers: { 'Content-Type': 'application/json' },
143 body: JSON.stringify(body)
144 }).then(function (resp) {
145 if (!resp.ok) { refetch(); return false; }
146 return resp.json().then(function (payload) { applyBatch(payload); return true; });
147 }).catch(function () { refetch(); return false; });
148 }
149
150 function write(r, c, text) {
151 return post('/cells', { r: r, c: c, raw: text });
152 }
153
154 function announce() {
155 listeners.forEach(function (fn) { fn(sel); });
156 }
157
158 function boot(payload) {
159 var data = blank();
160 (payload.cells || []).forEach(function (cell) {
161 if (cell.r >= rows || cell.c >= cols) return;
162 data[cell.r][cell.c] = cell.display;
163 meta[key(cell.r, cell.c)] = { raw: cell.raw || '', f: cell.f, n: cell.n };
164 });
165 if (payload.formats) styles = payload.formats;
166 version = payload.version || 0;
167
168 var opts = {
169 parseFormulas: false, /* Our engine computes; the client paints. See the file comment. */
170 /* Library menu and Ctrl+S CSV bypass our write/export paths. false: browser menu. */
171 contextMenu: function () { return false; }, allowExport: false,
172
173 /* Every handler below is a SPREADSHEET-level option, not a
174 * worksheet one. Nested inside worksheets[0] they are accepted
175 * without complaint and never called — the grid renders, the
176 * console stays clean, and no edit is ever sent anywhere. That
177 * is how they were first written here, and only driving two real
178 * browser tabs found it. */
179 onchange: function (instance, cell, c, r, value) {
180 if (applying) return;
181 delete held[key(r, c)]; /* this edit's own response will paint it */
182 write(parseInt(r, 10), parseInt(c, 10), value === null ? '' : String(value));
183 },
184 onselection: function (instance, x1, y1, x2, y2) {
185 sel = { r: parseInt(y1, 10), c: parseInt(x1, 10),
186 r2: parseInt(y2, 10), c2: parseInt(x2, 10) };
187 announce();
188 },
189 /* F2 or double-click shows the formula, filled a frame later (no input
190 * yet); typing replaces the cell (typestart.js), so is never filled. */
191 /* An edit closed without writing (Escape, or Enter on unchanged
192 * text): show what landed under it meanwhile, not the stale text. */
193 oneditionend: function (instance, td, c, r) {
194 var k = key(parseInt(r, 10), parseInt(c, 10)), d = held[k];
195 if (d === undefined) return;
196 delete held[k];
197 applying = true;
198 try { ws.setValueFromCoords(parseInt(c, 10), parseInt(r, 10), d, true); } finally { applying = false; }
199 },
200 oneditionstart: function (instance, td, c, r) {
201 var text = at(parseInt(r, 10), parseInt(c, 10)).raw;
202 if (!text || (window.SheetsTypeStart && window.SheetsTypeStart.replacing)) return;
203 requestAnimationFrame(function () {
204 var input = td.querySelector('input, textarea');
205 if (input) { input.value = text; input.select(); }
206 });
207 },
208
209 worksheets: [{
210 data: data,
211 /* What "no alignment" means; see sheets.css's alignment block.
212 * A WORKSHEET option — the exact mirror of the handlers above,
213 * which are spreadsheet-level. Each is silently ignored in the
214 * other's position: accepted, never read. */
215 defaultColAlign: 'left',
216 minDimensions: [cols, rows],
217 tableOverflow: true,
218 columnSorting: false, /* sorting is a later slice; a half-done sort is worse than none */
219 /* Each of these changes the library's model only, never the server's, and then every
220 * later write lands at shifted coordinates (header + Delete, row drag). */
221 columnDrag: false, rowDrag: false, allowInsertRow: false, allowInsertColumn: false,
222 allowDeleteRow: false, allowDeleteColumn: false
223 }]
224 };
225 /* The resize callbacks are SPREADSHEET-level options, like the
226 * handlers above. sizes.js adds them here, on the way in — nested
227 * a level deeper they are accepted in silence and never called. */
228 if (window.SheetsSizes) {
229 window.SheetsSizes.extend(opts, {
230 base: base, client: clientId,
231 mayWrite: surface.dataset.mayWrite === '1',
232 paint: applyBatch
233 });
234 }
235 var sheet = jspreadsheet(host, opts);
236 ws = sheet.worksheets ? sheet.worksheets[0] : sheet[0];
237 if (window.SheetsSizes) window.SheetsSizes.apply(ws, payload.sizes);
238
239 /* The library keeps its own client-side undo stack and its document
240 * keydown is registered before ours. Left on, Ctrl-Z reverts
241 * locally, then our handler posts the server undo and refetches:
242 * the net state is right and the grid flashes on the way. Undo is
243 * the server's (spec §7) — there is one undo, not two that can
244 * disagree — so the local stack is switched off rather than raced. */
245 ws.ignoreHistory = true;
246
247 /* paint.js owns the td and the drawing; this says what a cell is. */
248 paint.bind(ws, function (r, c) {
249 var m = at(r, c);
250 return { style: styles[m.f], n: m.n };
251 });
252
253 /* Paint the formats the snapshot arrived with. Deferred a frame:
254 * the records array is populated during construction, and painting
255 * inside the same tick reaches a table the library has not finished
256 * laying out. */
257 requestAnimationFrame(function () {
258 Object.keys(meta).forEach(function (k) {
259 var parts = k.split(',');
260 paint.repaint(parseInt(parts[0], 10), parseInt(parts[1], 10));
261 });
262 });
263
264 if (window.SheetsLive) window.SheetsLive.start(sheetId, tabId, clientId, applyBatch, refetch);
265 document.dispatchEvent(new CustomEvent('sheets:ready'));
266 }
267
268 /* The API the chrome is built on. Deliberately small: everything the
269 * menu bar and toolbar need to read the selection, change a cell and
270 * change a format, and nothing that would let them paint a string the
271 * server did not render. */
272 window.SheetsGrid = {
273 write: write,
274 post: post,
275 refetch: refetch,
276 rows: rows,
277 cols: cols,
278 mayWrite: surface.dataset.mayWrite === '1',
279 selection: function () { return sel; },
280 rawAt: function (r, c) { return at(r, c).raw || ''; },
281 styleAt: function (r, c) { return styles[at(r, c).f] || null; },
282 worksheet: function () { return ws; },
283 focus: function () { if (host) host.focus(); },
284 onSelection: function (fn) { listeners.push(fn); if (sel) fn(sel); }
285 };
286
287 fetch(base + '/cells?rows=' + rows + '&cols=' + cols, { credentials: 'same-origin' })
288 .then(function (r) {
289 if (!r.ok) throw new Error('window');
290 return r.json();
291 })
292 .then(boot)
293 .catch(function () {
294 var note = document.querySelector('[data-sheet-live]');
295 if (note) {
296 note.dataset.state = 'off';
297 note.textContent = 'Could not load this sheet. Reload, or use the table view.';
298 }
299 });
300}());
301