oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1/* Commands: what every menu item, toolbar button and shortcut does.
2 *
3 * One dispatch table, read by three callers — a click on a [data-cmd],
4 * a keyboard shortcut, and the toolbar's own state reflection. Three
5 * separate implementations of "make this bold" is how a menu item and
6 * its shortcut end up disagreeing, and only one of them gets fixed.
7 *
8 * Every control that needs this module is rendered hidden and revealed
9 * below. A button that does nothing because its script did not load is
10 * worse than no button, and this app has a scriptless path — the table
11 * view — to send people to instead.
12 */
13(function () {
14 'use strict';
15
16 var surface = document.querySelector('[data-sheet-surface]');
17 if (!surface) return;
18
19 function ready() {
20 var g = window.SheetsGrid;
21 if (!g) return;
22
23 /* ---- what a command does ---------------------------------------
24 *
25 * A toggle sends its TARGET state, worked out from the anchor cell,
26 * rather than sending "toggle". Over a mixed selection those differ:
27 * every spreadsheet makes the whole selection bold when any of it is
28 * not, and a per-cell flip would invert a checkerboard instead. */
29 var anchor = function () {
30 var s = g.selection();
31 return s ? (g.styleAt(s.r, s.c) || {}) : {};
32 };
33
34 /* format posts a patch for the current selection.
35 *
36 * It lives here rather than in grid.js because it is a command, and
37 * because the patch's shape — only the fields being changed, never
38 * the whole style — is a decision about what the buttons mean. See
39 * the Go side's formatPatch for why that distinction is the design
40 * and not an optimisation. */
41 function format(patch) {
42 var s = g.selection();
43 if (!s) return;
44 var body = { r1: s.r, c1: s.c, r2: s.r2, c2: s.c2 };
45 Object.keys(patch).forEach(function (k) { body[k] = patch[k]; });
46 g.post('/format', body);
47 }
48
49 var CMDS = {
50 undo: function () {
51 /* The same route the scriptless form posts to, so there is one
52 * undo and not two that can disagree. */
53 fetch('/sheets/' + surface.dataset.sheetId + '/undo', {
54 method: 'POST',
55 credentials: 'same-origin',
56 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
57 body: ''
58 }).then(g.refetch).catch(g.refetch);
59 },
60 bold: function () { format({ bold: !anchor().b }); },
61 italic: function () { format({ italic: !anchor().i }); },
62 align: function (v) { format({ align: anchor().a === v ? '' : v }); },
63 numfmt: function (v) { format({ numfmt: v }); },
64 fill: function (v) { format({ fill: v }); },
65 ink: function (v) { format({ ink: v }); },
66 'clear-format': function () {
67 format({ bold: false, italic: false, align: '', numfmt: '', fill: 'none', ink: 'none' });
68 },
69
70 clear: function () { eachSelected(function (r, c) { g.write(r, c, ''); }); },
71
72 /* Fill down and fill right are the menu equivalents of the grid's
73 * drag handle (AGENTS.md: every drag-only affordance has one).
74 * They copy the anchor's raw INPUT, not its displayed value, so
75 * filling a formula down fills the formula. */
76 'fill-down': function () { fillFrom(1, 0); },
77 'fill-right': function () { fillFrom(0, 1); },
78
79 'autofit-columns': function () { if (window.SheetsAutoFit) window.SheetsAutoFit(); },
80 'select-all': function () {
81 var ws = g.worksheet();
82 if (ws && ws.updateSelectionFromCoords) {
83 ws.updateSelectionFromCoords(0, 0, g.cols - 1, g.rows - 1);
84 }
85 },
86 /* clipboard.js, not the library. ws.copy() threw on every call
87 * and ws.copy(true) silently did nothing; both were dispatched,
88 * both rendered, and TestEveryMenuCommandIsImplemented was green
89 * throughout, because a command in the table is not a command
90 * that works. */
91 copy: function () { clip('copy'); },
92 cut: function () { clip('cut'); },
93 paste: function () { clip('paste'); },
94
95 /* Insert a function over the run of cells directly above the
96 * anchor, which is what somebody clicking "SUM" under a column of
97 * numbers means. An empty run inserts the call with no arguments
98 * rather than guessing a range that is not there. */
99 fn: function (name) {
100 var s = g.selection();
101 if (!s) return;
102 var top = s.r;
103 while (top > 0 && g.rawAt(top - 1, s.c) !== '') top--;
104 var arg = top < s.r ? colName(s.c) + (top + 1) + ':' + colName(s.c) + s.r : '';
105 g.write(s.r, s.c, '=' + name + '(' + arg + ')');
106 }
107 };
108
109 function clip(name) {
110 var c = window.SheetsClipboard;
111 if (c && c[name]) c[name]();
112 }
113
114 function colName(c) {
115 var out = '';
116 c += 1;
117 while (c > 0) { out = String.fromCharCode(65 + (c - 1) % 26) + out; c = Math.floor((c - 1) / 26); }
118 return out;
119 }
120
121 function eachSelected(fn) {
122 var s = g.selection();
123 if (!s) return;
124 for (var r = Math.min(s.r, s.r2); r <= Math.max(s.r, s.r2); r++) {
125 for (var c = Math.min(s.c, s.c2); c <= Math.max(s.c, s.c2); c++) fn(r, c);
126 }
127 }
128
129 function fillFrom(dr, dc) {
130 var s = g.selection();
131 if (!s) return;
132 var from = g.rawAt(s.r, s.c);
133 /* Over a selection, fill the rest of it from the anchor; over a
134 * single cell, fill the one next along — which is what the drag
135 * handle does with a one-cell drag. */
136 var lastR = Math.max(s.r, s.r2), lastC = Math.max(s.c, s.c2);
137 if (lastR === s.r && lastC === s.c) {
138 var r = Math.min(s.r + dr, g.rows - 1), c = Math.min(s.c + dc, g.cols - 1);
139 if (r !== s.r || c !== s.c) copyInto(r, c, from, s);
140 return;
141 }
142 eachSelected(function (r, c) {
143 if (r === s.r && c === s.c) return;
144 copyInto(r, c, from, s);
145 });
146 }
147
148 /* Spec §4.2: a filled cell is a COPIED cell, so it names where it
149 * came from and the server offsets its relative references. Without
150 * this, filling `=A1*2` down a column wrote `=A1*2` into every cell
151 * and the whole column showed one number. */
152 function copyInto(r, c, raw, from) {
153 g.post('/cells', { r: r, c: c, raw: raw, fromR: from.r, fromC: from.c });
154 }
155
156 function run(name, value) {
157 var fn = CMDS[name];
158 if (fn) fn(value);
159 }
160
161 /* ---- wiring ----------------------------------------------------- */
162
163 document.querySelectorAll('[data-needs-js]').forEach(function (el) {
164 el.hidden = false;
165 el.removeAttribute('data-needs-js');
166 });
167 document.querySelectorAll('[data-cmd][hidden]').forEach(function (el) {
168 el.hidden = false;
169 });
170
171 document.addEventListener('click', function (e) {
172 var el = e.target.closest('[data-cmd]');
173 if (!el || el.tagName === 'SUMMARY') return;
174 e.preventDefault();
175 run(el.dataset.cmd, el.dataset.value !== undefined ? el.dataset.value : el.dataset.fn);
176 var panel = el.closest('[data-tool-menu]');
177 /* A toolbar button clicked with the pointer keeps focus, so typing
178 * after Bold went nowhere; the keyboard goes back to the cell. A
179 * button reached with the keyboard keeps it, to reach the next. */
180 if (!panel) { if (e.detail > 0) g.focus(); return; }
181 /* Closing the panel leaves focus on a button inside a closed
182 * <details>, which drops it to <body> — so the keyboard ends up
183 * at the top of the document after picking a colour. Hand it back
184 * to the grid, which is the same rule menubar.js applies to a
185 * menu item: the thing you asked for happened to a cell, so that
186 * is where you want to be next. */
187 panel.open = false;
188 g.focus();
189 });
190
191 /* The menu's resize forms. The size route takes one axis at a time
192 * and applies to the selection's anchor, which is the column or row
193 * the cursor is in — the same thing dragging its edge would do. */
194 document.querySelectorAll('[data-size-form]').forEach(function (form) {
195 form.addEventListener('submit', function (e) {
196 e.preventDefault();
197 var sel = g.selection();
198 var px = parseInt(form.querySelector('input[name=size]').value, 10);
199 if (!sel || !isFinite(px)) return;
200 var body = form.dataset.axis === 'col' ? { col: sel.c } : { row: sel.r };
201 body.size = px;
202 g.post('/size', body);
203 var menu = form.closest('details');
204 if (menu) menu.open = false;
205 g.focus();
206 });
207 });
208
209 /* ---- shortcuts ---------------------------------------------------
210 *
211 * Never while a cell editor, the formula bar or the name box has
212 * focus: there Ctrl+B belongs to the text field, and stealing it
213 * would make the editor feel broken.
214 *
215 * Ctrl+R is deliberately absent. It is reload in every browser, and
216 * fill right is not worth taking it. */
217 var KEYS = { b: 'bold', i: 'italic', d: 'fill-down', z: 'undo' };
218
219 document.addEventListener('keydown', function (e) {
220 var t = e.target;
221 if (t && !t.hasAttribute('data-type-holder') && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
222
223 /* Delete is deliberately NOT handled here. The vendored grid
224 * already clears the selection through its own setValue, which
225 * fires onchange and reaches write() — so handling it too posted
226 * every selected cell twice, and Backspace (which the library
227 * also handles) only once, which is worse than either. The menu
228 * item stays: it is the affordance, and it runs the same code the
229 * key does, once. */
230 if (!e.ctrlKey && !e.metaKey) return;
231 if (e.altKey || e.shiftKey) return;
232 var cmd = KEYS[e.key.toLowerCase()];
233 if (!cmd) return;
234 if (cmd !== 'undo' && !g.mayWrite) return;
235 e.preventDefault();
236 run(cmd);
237 });
238
239 /* ---- the toolbar reflects the anchor cell -------------------------
240 *
241 * A toolbar that does not show the selection's state is decoration:
242 * you cannot tell whether pressing B will bold or un-bold. */
243 var toggles = document.querySelectorAll('[data-tool][aria-pressed]');
244 var fillChip = document.querySelector('[data-fill-chip]');
245 var inkChip = document.querySelector('[data-ink-chip]');
246
247 g.onSelection(function () {
248 var st = anchor();
249 toggles.forEach(function (btn) {
250 var on = false;
251 if (btn.dataset.cmd === 'bold') on = !!st.b;
252 else if (btn.dataset.cmd === 'italic') on = !!st.i;
253 else if (btn.dataset.cmd === 'align') on = st.a === btn.dataset.value;
254 btn.setAttribute('aria-pressed', on ? 'true' : 'false');
255 });
256 chip(fillChip, st.fh, st.fc, '--sheet-h', '--sheet-c');
257 chip(inkChip, st.kh, st.kc, '--sheet-kh', '--sheet-kc');
258 });
259
260 function chip(el, h, c, hProp, cProp) {
261 if (!el) return;
262 if (typeof h !== 'number' || typeof c !== 'number') {
263 el.removeAttribute('data-set');
264 return;
265 }
266 el.style.setProperty(hProp, String(h));
267 el.style.setProperty(cProp, String(c));
268 el.setAttribute('data-set', '');
269 }
270
271 /* ---- the toolbar is one tab stop ---------------------------------
272 *
273 * Fourteen buttons, fourteen tab stops, is a strip a keyboard user
274 * has to walk through to reach the grid. Roving tabindex with arrow
275 * keys is the convention for a toolbar, and matches what the menu
276 * bar beside it does. */
277 var strip = document.querySelector('[data-toolbar]');
278 if (!strip) return;
279 var stops = Array.prototype.slice.call(strip.querySelectorAll('[data-tool]'));
280 if (!stops.length) return;
281 stops.forEach(function (el, i) { el.tabIndex = i === 0 ? 0 : -1; });
282
283 strip.addEventListener('keydown', function (e) {
284 if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
285 var i = stops.indexOf(e.target.closest('[data-tool]'));
286 if (i < 0) return;
287 e.preventDefault();
288 /* Jspreadsheet listens for arrows on document and would walk the
289 * cell cursor as well. */
290 e.stopPropagation();
291 var next = stops[(i + (e.key === 'ArrowRight' ? 1 : -1) + stops.length) % stops.length];
292 stops.forEach(function (el) { el.tabIndex = -1; });
293 next.tabIndex = 0;
294 next.focus();
295 });
296 }
297
298 if (window.SheetsGrid) ready();
299 else document.addEventListener('sheets:ready', ready, { once: true });
300}());
301