-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom-Pluto.js
461 lines (405 loc) · 13 KB
/
custom-Pluto.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// ==UserScript==
// @name Custom Pluto
// @namespace https://tampermonkey.net/
// @version 0.2
// @description Customize your Pluto notebook
// @author Lucio Cornejo
// @match *localhost:1234/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @grant none
// ==/UserScript==
(function() {
'use strict';
// Apply customization to notebook
if (!document.querySelector("pluto-notebook")) return;
/*
Custom styling
*/
// Variable for light(0)/dark(1) theme toggle
document.documentElement.style.cssText = "--theme: 1";
const customStyle = document.createElement("style")
customStyle.innerHTML =
/*
Dark mode
*/
"html {filter: invert(var(--theme)); }\n" +
// Do not alter to dark mode
`input, img,
pluto-logs-container,
.plot-container, .plotly {
filter: invert(var(--theme));
}\n` +
// Set tab size to 2
".cm-content { tab-size: 2 !important; }\n" +
/*
Style table of contents
*/
// Fix padding issue in table of contents
`a.H3 { padding-left: 20px !important; }
.toc-row a { white-space: normal !important; }
/* .plutoui-toc.aside { left: 0; width: 10rem !important; } */ \n` +
/*
Other changes
*/
// Center content of notebook
"/* main { align-self: unset !important; } */ \n" +
// Add left space for better cell drag icon visibility
"main { margin-left: 20px !important; }\n" +
/*
Style terminal output
*/
`pluto-log-dot-sizer { width: 75vw; }
pluto-log-dot {
width: 100%;
padding: 0.5rem;
line-height: 1.5rem;
background: black !important;
}
pluto-logs-container {
background-color: black !important;
}`;
document.head.appendChild(customStyle);
/*
Add button to toggle light and dark mode
*/
const toggleExport = document.querySelector("#at_the_top .toggle_export");
const toggleTheme = document.createElement("button");
toggleTheme.innerText = "Toggle light/dark mode";
toggleTheme.style.cssText = `
color: crimson;
cursor: pointer;
margin-right: 2rem;
border-radius: 50px;
padding: 0.3rem 0.55rem;
background-color: white;
filter: drop-shadow(0 0 0.25rem var(--ui-button-color));
`
toggleTheme.onclick = function () {
document.documentElement.style.setProperty(
"--theme",
String((parseInt(
document.documentElement.style
.getPropertyValue("--theme")
) + 1) % 2
))
}
toggleExport.before(toggleTheme);
/*
Obtain pluto-cell HTML element
*/
function getPlutoCell(el) {
try {
if (el.tagName !== "PLUTO-CELL") {
return getPlutoCell(el.parentElement);
}
return el;
} catch (e) { }
}
/*
Create two lines of code,
for first and last line, respectively,
of Pluto code cell.
*/
function insertCode(textStart, textEnd) {
const divStart = document.createElement("div");
divStart.classList.add("cm-line");
const spanStart = document.createElement("span");
spanStart.classList.add("ͼx");
spanStart.innerText = textStart;
divStart.appendChild(spanStart);
const divEnd = document.createElement("div");
divEnd.classList.add("cm-line");
const spanEnd = document.createElement("span");
spanEnd.classList.add("ͼx");
spanEnd.innerText = textEnd;
divEnd.appendChild(spanEnd);
return [divStart, divEnd];
}
/*
Extract raw code from Pluto cell
*/
function extractCellCode(plutoCell) {
const linesContainer = Array.from(
plutoCell.querySelector("[role='textbox']")
.children
);
let codeText = "";
linesContainer.forEach(lineContainer => {
lineContainer.childNodes.forEach(line => {
codeText += extractLineText(line);
});
codeText += "\n";
});
codeText = codeText.split("\n");
codeText.pop();
return codeText;
/*
// Check that code text extraction is correct
linesContainer[0].parentElement.innerHTML = codeText
.map(line => `<div><span>${line}</span></div>`)
.join('');
*/
}
function extractLineText(line) {
if (line.nodeName === "#text") return line.nodeValue;
if (line.nodeName === "SPAN") {
// Case like <span><span>text</span></span> .
// Such HTML structure is sometimes triggered
// automatically by Pluto for first and last cell lines.
if (line.classList.contains("cm-matchingBracket")) {
return extractLineText(line.firstChild);
}
// Case where span elements are used to contain
// information about the code line, not the text itself.
if (line.childElementCount) return "";
// Usual case: <span>text</span>
return line.innerText;
}
// Case where the code text is inside a span element
// contained in a <pluto-variable-link> element.
if (line.nodeName === 'PLUTO-VARIABLE-LINK') {
return extractLineText(line.firstChild);
}
return "";
}
/*
When some keyboard keys combination of the form
("Alt" or "Control" or "Shift") +
"numeric_or_alphabetic key"
is pressed, toggle insertion of two lines of code
into selected Pluto code cell.
*/
function keysAction(event, keys, firstLine, lastLine) {
/*
The keys parameter is an array of 2, 3 or 4 elements,
filled with ".key" values obtained after a keydown
event is registered by JavaScript.
Such values can be obtained from this website:
https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values
*/
// Example:
// keys = ["Alt", "s"] will be turned to ["altKey", "s"],
// where it is assumed that only the last element of the
// keys array is a key not in ["Alt", "Control", "Shift"].
// Specially deal with the cases where the
// Alt, Control or Shift key was/were pressed
const specialKeys = {
Alt: "altKey", Control: "ctrlKey", Shift: "shiftKey"
}
keys = keys.map(function(key) {
return Object.keys(specialKeys).includes(key)
? specialKeys[key]
: key;
});
// Check if the specific keys combination defined
// by the keys array was pressed by the user.
const keysCombinationPressed =
keys.every((element, index) => {
// Case for non special key
if (index === keys.length - 1) {
// Was non special key (upper or lower case) pressed?
return event.key.toLowerCase() === element;
// Lower case is used due to sometimes
// the non special key being registered
// as upper case when other special keys
// are also being pressed.
} else {
// Was the special key pressed?
return event[element];
}
});
if (keysCombinationPressed) {
const cellCode = getPlutoCell(getSelection().anchorNode)
.querySelector("div[role='textbox'].cm-content");
/* Create HTML for two new code lines */
const [beginDiv, endDiv] = insertCode(firstLine, lastLine);
/*
Check if the two new lines' code is already
present in the current cell,
and remove them, if that's the case.
*/
let currentFirstLine = "";
// Read text from each node in current cell's
// first line. Sometimes the code is not inserted
// into span elements, but as #text.
cellCode.firstElementChild.childNodes.forEach(
line => {
if (line.nodeName === "#text") {
currentFirstLine += line.nodeValue;
} else {
// We assume the line is an HTML element
currentFirstLine += line.innerText;
}
});
if (firstLine === currentFirstLine) {
cellCode.firstElementChild.remove()
} else {
cellCode.firstElementChild.before(beginDiv);
}
let currentLastLine = "";
cellCode.lastElementChild.childNodes.forEach(
line => {
if (line.nodeName === "#text") {
currentLastLine += line.nodeValue;
} else {
// We assume the line is an HTML element
currentLastLine += line.innerText;
}
});
if (lastLine === currentLastLine) {
cellCode.lastElementChild.remove();
} else {
cellCode.appendChild(endDiv);
}
}
}
document.addEventListener("keydown", function (evt) {
// Avoid keydown event repetition due to holding key
if (evt.repeat) return;
/*
Insert "begin ... end" code in Pluto cell
Keyboard shortcut: Control+Alt+b
*/
keysAction(evt, ["Control", "Alt", "b"], "begin", "end");
/*
Insert "let ... end" code in Pluto cell
Keyboard shortcut: Control+Alt+l
*/
keysAction(evt, ["Control", "Alt", "l"], "let", "end");
/*
Insert "with_terminal() do ... end" code in Pluto cell
Keyboard shortcut: Control+Alt+t
*/
keysAction(evt, ["Control", "Alt", "t"], "with_terminal() do", "end");
/*
Insert 'md""" ... """' code in Pluto cell
Keyboard shortcut: Control+Alt+m
*/
keysAction(evt, ["Control", "Alt", "m"], "md\"\"\"", "\"\"\"");
/*
Toggle visibility of markdown cells' code: Alt+m
*/
if (
evt.altKey &&
!evt.ctrlKey &&
!evt.shiftKey &&
evt.key.toLowerCase() === "m"
) {
document.querySelectorAll(
"pluto-cell:has(pluto-output .markdown)"
).forEach(cell => {
// Even if the Pluto cell has no class,
// or has only the classes
// "show_input" and "code_folded", the
// following code will toggle the
// visibility of the markdown cell's code.
cell.classList.toggle("show_input");
cell.classList.toggle("code_folded");
});
}
/*
Toggle code cell visibility: Alt+v
*/
if (
evt.altKey &&
!evt.ctrlKey &&
!evt.shiftKey &&
evt.key.toLowerCase() === "v"
) {
getPlutoCell(getSelection().anchorNode)
.querySelector("button.foldcode").click();
}
/*
Add cell before: Control+Shift+Enter
*/
if (
!evt.altKey &&
evt.ctrlKey &&
evt.shiftKey &&
evt.key.toLowerCase() === "enter"
) {
getPlutoCell(getSelection().anchorNode).querySelector("button.add_cell.before").click();
}
/*
Add cell after: Alt+Enter
*/
if (
evt.altKey &&
!evt.ctrlKey &&
!evt.shiftKey &&
evt.key.toLowerCase() === "enter"
) {
getPlutoCell(getSelection().anchorNode)
.querySelector("button.add_cell.after").click();
}
/*
Toggle live documentation: Control+Alt+d
*/
if (
evt.altKey &&
evt.ctrlKey &&
!evt.shiftKey &&
evt.key.toLowerCase() === "d"
) {
if (document.querySelector("pluto-helpbox header input")) {
document.querySelector("pluto-helpbox").classList.toggle("hidden");
document.querySelector("pluto-helpbox button").click();
} else {
document.querySelector("pluto-helpbox").classList.toggle("hidden");
document.querySelector("pluto-helpbox header").click();
}
}
/*
Split cell: Control+Alt+s
*/
if (
evt.altKey &&
evt.ctrlKey &&
!evt.shiftKey &&
evt.key.toLowerCase() === "s"
) {
(async function () {
// Get code line where mouse is located
let oldLine = getSelection().anchorNode;
while (!oldLine.classList) { oldLine = oldLine.parentElement }
while (!oldLine.classList.contains("cm-line")) {
oldLine = oldLine.parentElement
}
// Extract code text from selected line
let oldLineCode = "";
oldLine.childNodes.forEach(node => {
oldLineCode += extractLineText(node);
});
oldLineCode;
// Extract code text from selected cell
const oldCell = getPlutoCell(getSelection().anchorNode);
let oldCellCode = extractCellCode(oldCell);
// Split code text based on selected line
const lineIndex = oldCellCode.indexOf(oldLineCode);
const newCellCode = oldCellCode.slice(lineIndex);
oldCellCode = oldCellCode.slice(0, lineIndex);
/*
Due to Pluto only allowing one line per cell,
unless something like "begin ... end" is used,
and the fact that splitting a one line cell does
not make much sense, we will replicate the first
and last line of the old cell, into the new one.
*/
oldCellCode.push(newCellCode.at(-1));
newCellCode.unshift(oldCellCode[0]);
// Create new cell
oldCell.querySelector("button.add_cell.after").click();
await new Promise(r => setTimeout(r, 500));
const newCell = oldCell.nextElementSibling;
// Update code in cells
oldCell.querySelector('[role="textbox"]').innerHTML =
oldCellCode.map(line => `<div><span>${line}</span></div>`)
.join('');
newCell.querySelector('[role="textbox"]').innerHTML =
newCellCode.map(line => `<div><span>${line}</span></div>`)
.join('');
return ;
})()
}
});
})();