-
Notifications
You must be signed in to change notification settings - Fork 432
Expand file tree
/
Copy pathcodetools.ts
More file actions
407 lines (377 loc) · 14.8 KB
/
codetools.ts
File metadata and controls
407 lines (377 loc) · 14.8 KB
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
/*
* codetools.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { Document, Element } from "../../core/deno-dom.ts";
import {
kHtmlEmptyPostProcessResult,
kMarkdownBlockSeparator,
} from "./constants.ts";
import { HtmlPostProcessResult } from "./types.ts";
import { Format } from "../../config/types.ts";
import {
kCodeTools,
kCodeToolsHideAllCode,
kCodeToolsHideAllSections,
kCodeToolsMenuCaption,
kCodeToolsShowAllCode,
kCodeToolsShowAllSections,
kCodeToolsSourceCode,
kCodeToolsViewSource,
kKeepSource,
} from "../../config/constants.ts";
import {
ExecutionEngineInstance,
ExecutionTarget,
} from "../../execute/types.ts";
import { isHtmlOutput } from "../../config/format.ts";
import { executionEngineCanKeepSource } from "../../execute/engine-info.ts";
import { formatHasBootstrap } from "../../format/html/format-html-info.ts";
import { withTiming } from "../../core/timing.ts";
import { kSectionCollapse } from "../../format/html/format-html-shared.ts";
const kHideAllCodeLinkId = "quarto-hide-all-code";
const kShowAllCodeLinkId = "quarto-show-all-code";
const kShowAllSectionsLinkId = "quarto-show-all-sections";
const kHideAllSectionsLinkId = "quarto-hide-all-sections";
const kViewSourceLinkId = "quarto-view-source";
const kEmbeddedSourceClass = "quarto-embedded-source-code";
export const kEmbeddedSourceModalId = kEmbeddedSourceClass + "-modal";
const kEmbeddedSourceModalLabelId = kEmbeddedSourceClass + "-modal-label";
const kKeepSourceSentinel = "quarto-executable-code-5450563D";
export const kCodeToolsSourceButtonId = "quarto-code-tools-source";
export const kCodeToolsMenuButtonId = "quarto-code-tools-menu";
export const kDataQuartoSourceUrl = "data-quarto-source-url";
export function formatHasCodeTools(format: Format) {
const codeTools = format.render?.[kCodeTools];
return !!codeTools && isHtmlOutput(format.pandoc, true) &&
formatHasBootstrap(format);
}
export function resolveKeepSource(
format: Format,
engine: ExecutionEngineInstance,
target: ExecutionTarget,
) {
// keep source if requested (via keep-source or code-tools), we are targeting html,
// and engine can keep it (e.g. we wouldn't keep an .ipynb file as source)
const codeTools = format.render?.[kCodeTools];
if (
codeTools === true ||
(typeof codeTools === "object" &&
(codeTools?.source === undefined || codeTools?.source === true))
) {
format.render[kKeepSource] = true;
}
format.render[kKeepSource] = format.render[kKeepSource] &&
isHtmlOutput(format.pandoc, true) &&
formatHasBootstrap(format) &&
executionEngineCanKeepSource(engine, target);
}
export function keepSourceBlock(format: Format, source: string) {
if (format.render[kKeepSource]) {
// read code
let code = Deno.readTextFileSync(source).trimLeft();
if (!code.endsWith("\n")) {
code = code + "\n";
}
// make sure that quarto code blocks get correct highlighting
code = code.replaceAll(
/\n```{(\w+)}\s*\n/g,
"\n" + kKeepSourceSentinel + "\n\n```$1\n",
);
const kKeepSourceBackticks = "```````````````````";
return `${kMarkdownBlockSeparator}::: {.${kEmbeddedSourceClass}}\n${kKeepSourceBackticks}` +
`{.markdown shortcodes="false"}\n${code}` +
`${kKeepSourceBackticks}\n:::\n`;
} else {
return "";
}
}
export function codeToolsPostprocessor(format: Format) {
return (doc: Document): Promise<HtmlPostProcessResult> => {
return withTiming("codeToolsPostprocessor", () => {
if (format.render[kKeepSource]) {
// fixup the lines in embedded source
const lines = doc.querySelectorAll(
`.${kEmbeddedSourceClass} > div.sourceCode > pre > code > span`,
);
if (lines.length > 0) {
const newLines: Element[] = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i] as Element;
if (line.innerText === kKeepSourceSentinel) {
i += 2;
const codeBlockLine = lines[i] as Element;
const anchor = codeBlockLine.querySelector("a");
const text = codeBlockLine.innerText;
codeBlockLine.textContent = "";
codeBlockLine.appendChild(anchor!);
const newSpan = doc.createElement("span");
newSpan.classList.add("in");
newSpan.innerText = text.replace(
/```(\w+)/,
"```{$1}",
);
codeBlockLine.appendChild(newSpan);
newLines.push(codeBlockLine);
} else {
newLines.push(line);
}
}
if (newLines.length !== lines.length) {
const parent = (lines[0] as Element).parentElement!;
parent.innerHTML = "";
newLines.forEach((line) => {
parent.appendChild(line);
parent.appendChild(doc.createTextNode("\n"));
});
}
}
}
// provide code tools in header
if (formatHasCodeTools(format)) {
// resolve what sort of code tools we will present
const codeTools = resolveCodeTools(format, doc);
if (codeTools.source || codeTools.toggle || codeTools.section) {
const title = doc.querySelector("#title-block-header h1");
const header = title !== null
? (title as Element).parentElement
: doc.querySelector("main.content");
if (header) {
const titleDiv = doc.createElement("div");
titleDiv.classList.add("quarto-title-block");
const layoutDiv = doc.createElement("div");
titleDiv.appendChild(layoutDiv);
if (title) {
header?.replaceChild(titleDiv, title);
layoutDiv.appendChild(title);
} else {
// create an empty title
const h1El = doc.createElement("h1");
layoutDiv.appendChild(h1El);
layoutDiv.classList.add("quarto-title-tools-only");
}
const button = doc.createElement("button");
button.setAttribute("type", "button");
button.classList.add("btn");
button.classList.add("code-tools-button");
const icon = doc.createElement("i");
icon.classList.add("bi");
button.appendChild(icon);
if (codeTools.caption !== "none") {
button.appendChild(doc.createTextNode(" " + codeTools.caption));
}
layoutDiv.appendChild(button);
if (title) {
header!.appendChild(titleDiv);
} else {
header!.prepend(titleDiv);
}
if (codeTools.toggle || codeTools.section) {
button.setAttribute("id", kCodeToolsMenuButtonId);
button.classList.add("dropdown-toggle");
button.setAttribute("data-bs-toggle", "dropdown");
button.setAttribute("aria-expanded", "false");
const ul = doc.createElement("ul");
ul.classList.add("dropdown-menu");
ul.classList.add("dropdown-menu-end");
ul.setAttribute("aria-labelelledby", kCodeToolsMenuButtonId);
const addListItem = (id: string, text: string) => {
const a = doc.createElement("a");
a.setAttribute("id", id);
a.classList.add("dropdown-item");
a.setAttribute("href", "javascript:void(0)");
a.setAttribute("role", "button");
a.appendChild(doc.createTextNode(text));
const li = doc.createElement("li");
li.appendChild(a);
ul.appendChild(li);
return li;
};
const addDivider = () => {
const hr = doc.createElement("hr");
hr.classList.add("dropdown-divider");
const li = doc.createElement("li");
li.appendChild(hr);
ul.appendChild(li);
};
if (codeTools.toggle) {
addListItem(
kShowAllCodeLinkId,
format.language[kCodeToolsShowAllCode]!,
);
addListItem(
kHideAllCodeLinkId,
format.language[kCodeToolsHideAllCode]!,
);
}
if (codeTools.section) {
if (codeTools.toggle) {
addDivider();
}
addListItem(
kShowAllSectionsLinkId,
format.language[kCodeToolsShowAllSections]!,
);
addListItem(
kHideAllSectionsLinkId,
format.language[kCodeToolsHideAllSections]!,
);
}
if (codeTools.source) {
addDivider();
const vsLi = addListItem(
kViewSourceLinkId,
format.language[kCodeToolsViewSource]!,
);
if (typeof (codeTools.source) === "string") {
(vsLi.firstChild as Element).setAttribute(
kDataQuartoSourceUrl,
codeTools.source,
);
}
}
layoutDiv.appendChild(ul);
} else {
// no toggle, so just a button to show source code
button.setAttribute("id", kCodeToolsSourceButtonId);
if (typeof (codeTools.source) === "string") {
button.setAttribute(kDataQuartoSourceUrl, codeTools.source);
}
}
}
if (codeTools.source) {
// grab the embedded source code element
const embeddedCode = doc.querySelector(`.${kEmbeddedSourceClass}`);
if (embeddedCode) {
// create a bootstrap model to wrap it
const modalDiv = doc.createElement("div");
modalDiv.classList.add("modal");
modalDiv.classList.add("fade");
modalDiv.setAttribute("id", kEmbeddedSourceModalId);
modalDiv.setAttribute("tabindex", "-1");
modalDiv.setAttribute(
"aria-labelledby",
kEmbeddedSourceModalLabelId,
);
modalDiv.setAttribute("aria-hidden", "true");
const modalDialogDiv = doc.createElement("div");
modalDialogDiv.classList.add("modal-dialog");
modalDialogDiv.classList.add("modal-dialog-scrollable");
const modalContentDiv = doc.createElement("div");
modalContentDiv.classList.add("modal-content");
const modalDialogHeader = doc.createElement("div");
modalDialogHeader.classList.add("modal-header");
const h5 = doc.createElement("h5");
h5.classList.add("modal-title");
h5.setAttribute("id", kEmbeddedSourceModalLabelId);
h5.appendChild(
doc.createTextNode(format.language[kCodeToolsSourceCode]!),
);
modalDialogHeader.appendChild(h5);
const button = doc.createElement("button");
button.classList.add("btn-close");
button.setAttribute("data-bs-dismiss", "modal");
modalDialogHeader.appendChild(button);
modalContentDiv.appendChild(modalDialogHeader);
const modalBody = doc.createElement("div");
modalBody.classList.add("modal-body");
modalContentDiv.appendChild(modalBody);
modalDialogDiv.appendChild(modalContentDiv);
modalDiv.appendChild(modalDialogDiv);
// insert it next to the main content
const mainEl = doc.querySelector("main.content");
if (mainEl) {
const mainParentEl = mainEl.parentElement;
mainParentEl?.insertBefore(modalDiv, mainParentEl.lastChild);
} else {
embeddedCode.parentElement?.insertBefore(
modalDiv,
embeddedCode,
);
}
modalBody.appendChild(embeddedCode);
embeddedCode.classList.remove(kEmbeddedSourceClass);
}
}
// if code is statically hidden, hide code-tools chrome as well.
// note that we're querying on pre.hidden and div.hidden both
//
// because for regular code cells, the hidden class hasn't been
// hoisted to the parent by the html postprocessor yet,
// but for OJS cells, they're emitted as hidden from the start.
for (
const el of Array.from(
doc.querySelectorAll(
"details div pre.hidden",
),
)
) {
const det = el.parentElement!.parentElement;
det!.classList.add("hidden");
}
}
}
return Promise.resolve(kHtmlEmptyPostProcessResult);
});
};
}
interface CodeTools {
source: boolean | string;
toggle: boolean;
caption: string;
section: boolean;
}
function resolveCodeTools(format: Format, doc: Document): CodeTools {
// determine user prefs
const kCodeCaption = format.language[kCodeToolsMenuCaption]!;
const codeTools = format?.render[kCodeTools];
const codeToolsResolved = {
source: typeof codeTools === "boolean"
? codeTools
: codeTools?.source !== undefined
? codeTools?.source
: true,
toggle: typeof codeTools === "boolean"
? codeTools
: codeTools?.toggle !== undefined
? !!codeTools?.toggle
: true,
caption: typeof codeTools === "boolean"
? kCodeCaption
: codeTools?.caption || kCodeCaption,
section: typeof codeTools === "boolean"
? codeTools
: codeTools?.section !== undefined
? codeTools?.section
: true,
};
// if we have request source without an external url,
// make sure we are able to keep source
if (codeToolsResolved.source === true) {
codeToolsResolved.source = !!format.render[kKeepSource];
}
// if we have requested toggle, make sure there are things to toggle
if (codeToolsResolved.toggle) {
const codeDetails = doc.querySelector(".cell > details > .sourceCode");
// we don't OJS hidden cells in this check, since when echo: false, we emit them hidden
const codeHidden = doc.querySelector(
".cell .sourceCode.hidden:not(div pre.js)",
);
codeToolsResolved.toggle = !!codeDetails || !!codeHidden;
}
// if we have requested section, make sure there are things to collapse
if (codeToolsResolved.section === true) {
codeToolsResolved.section = !!format.metadata[kSectionCollapse];
}
// Change the default caption based on what tools are shown
if (
codeToolsResolved.section &&
(codeTools === true ||
(typeof codeTools !== "boolean" && codeTools?.caption === undefined))
) {
codeToolsResolved.caption = "Tools";
}
// return resolved
return codeToolsResolved;
}