-
Notifications
You must be signed in to change notification settings - Fork 431
Expand file tree
/
Copy pathpandoc-html.ts
More file actions
632 lines (576 loc) · 18.7 KB
/
pandoc-html.ts
File metadata and controls
632 lines (576 loc) · 18.7 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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
/*
* pandoc-html.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { join } from "../../deno_ral/path.ts";
import { cloneDeep, uniqBy } from "../../core/lodash.ts";
import {
Format,
FormatExtras,
kDependencies,
kQuartoCssVariables,
kTextHighlightingMode,
SassBundle,
SassBundleWithBrand,
SassLayer,
} from "../../config/types.ts";
import { ProjectContext } from "../../project/types.ts";
import { cssImports, cssResources } from "../../core/css.ts";
import { cleanSourceMappingUrl, compileSass } from "../../core/sass.ts";
import { kQuartoHtmlDependency } from "../../format/html/format-html-constants.ts";
import {
kAbbrevs,
readHighlightingTheme,
} from "../../quarto-core/text-highlighting.ts";
import { isHtmlOutput } from "../../config/format.ts";
import {
cssHasDarkModeSentinel,
generateCssKeyValues,
} from "../../core/pandoc/css.ts";
import { kMinimal } from "../../format/html/format-html-shared.ts";
import { kSassBundles } from "../../config/types.ts";
import { md5HashBytes } from "../../core/hash.ts";
import { InternalError } from "../../core/lib/error.ts";
import { assert } from "testing/asserts";
import { safeModeFromFile } from "../../deno_ral/fs.ts";
// The output target for a sass bundle
// (controls the overall style tag that is emitted)
interface SassTarget {
name: string;
bundles: SassBundle[];
attribs: Record<string, string>;
}
export async function resolveSassBundles(
inputDir: string,
extras: FormatExtras,
format: Format,
project: ProjectContext,
) {
extras = cloneDeep(extras);
const mergedBundles: Record<string, SassBundleWithBrand[]> = {};
// groups the bundles by dependency name
const group = (
bundles: SassBundleWithBrand[],
groupedBundles: Record<string, SassBundleWithBrand[]>,
) => {
bundles.forEach((bundle) => {
if (!groupedBundles[bundle.dependency]) {
groupedBundles[bundle.dependency] = [];
}
groupedBundles[bundle.dependency].push(bundle);
});
};
// group available sass bundles
if (extras?.["html"]?.[kSassBundles]) {
group(extras["html"][kSassBundles], mergedBundles);
}
// Go through and compile the cssPath for each dependency
let hasDarkStyles = false;
let defaultStyle: "dark" | "light" | undefined = undefined;
for (const dependency of Object.keys(mergedBundles)) {
// compile the cssPath
const bundlesWithBrand = mergedBundles[dependency];
// first, pull out the brand-specific layers
//
// the brand bundle itself doesn't have any 'brand' entries;
// those are used to specify where the brand-specific layers should be inserted
// in the final bundle.
const maybeBrandBundle = bundlesWithBrand.find((bundle) =>
bundle.key === "brand"
);
assert(
!maybeBrandBundle ||
!maybeBrandBundle.user?.find((v) => v === "brand") &&
!maybeBrandBundle.dark?.user?.find((v) => v === "brand"),
);
const foundBrand = { light: false, dark: false };
const bundles: SassBundle[] = bundlesWithBrand.filter((bundle) =>
bundle.key !== "brand"
).map((bundle) => {
const userBrand = bundle.user?.findIndex((layer) => layer === "brand");
let cloned = false;
if (userBrand && userBrand !== -1) {
bundle = cloneDeep(bundle);
cloned = true;
bundle.user!.splice(userBrand, 1, ...(maybeBrandBundle?.user || []));
foundBrand.light = true;
}
const darkBrand = bundle.dark?.user?.findIndex((layer) =>
layer === "brand"
);
if (darkBrand && darkBrand !== -1) {
if (!cloned) {
bundle = cloneDeep(bundle);
}
bundle.dark!.user!.splice(
darkBrand,
1,
...(maybeBrandBundle?.dark?.user || []),
);
foundBrand.dark = true;
}
return bundle as SassBundle;
});
if (maybeBrandBundle && (!foundBrand.light || !foundBrand.dark)) {
bundles.unshift({
dependency,
key: "brand",
user: !foundBrand.light && maybeBrandBundle.user as SassLayer[] || [],
dark: !foundBrand.dark && maybeBrandBundle.dark?.user && {
user: maybeBrandBundle.dark.user as SassLayer[],
default: maybeBrandBundle.dark.default,
} || undefined,
});
}
// See if any bundles are providing dark specific css
const hasDark = bundles.some((bundle) => bundle.dark !== undefined);
defaultStyle = bundles.some((bundle) =>
bundle.dark !== undefined && bundle.dark.default
)
? "dark"
: "light";
const targets: SassTarget[] = [{
name: `${dependency}.min.css`,
bundles: (bundles as any),
attribs: {
"append-hash": "true",
},
}];
if (hasDark) {
// Note that the other bundle provides light
targets[0].attribs = {
...targets[0].attribs,
...attribForThemeStyle("light"),
};
// Provide a dark bundle for this
const darkBundles = bundles.map((bundle) => {
bundle = cloneDeep(bundle);
bundle.user = bundle.dark?.user || bundle.user;
bundle.quarto = bundle.dark?.quarto || bundle.quarto;
bundle.framework = bundle.dark?.framework || bundle.framework;
// Mark this bundle with a dark key so it is differentiated from the light theme
bundle.key = bundle.key + "-dark";
return bundle;
});
const darkTarget = {
name: `${dependency}-dark.min.css`,
bundles: darkBundles as any,
attribs: {
"append-hash": "true",
...attribForThemeStyle("dark"),
},
};
if (defaultStyle === "dark") {
targets.push(darkTarget);
} else {
targets.unshift(darkTarget);
}
hasDarkStyles = true;
}
for (const target of targets) {
let cssPath: string | undefined;
cssPath = await compileSass(target.bundles, project);
// First, Clean CSS
cleanSourceMappingUrl(cssPath);
// look for a sentinel 'dark' value, extract variables
const cssResult = await processCssIntoExtras(cssPath, extras, project);
cssPath = cssResult.path;
// it can happen that processing generate an empty css file (e.g quarto-html deps with Quarto CSS variables)
// in that case, no need to insert the cssPath in the dependency
if (!cssPath) continue;
if (Deno.readTextFileSync(cssPath).length === 0) {
continue;
}
// Process attributes (forward on to the target)
for (const bundle of target.bundles) {
if (bundle.attribs) {
for (const key of Object.keys(bundle.attribs)) {
if (target.attribs[key] === undefined) {
target.attribs[key] = bundle.attribs[key];
}
}
}
}
target.attribs["data-mode"] = cssResult.dark ? "dark" : "light";
// Find any imported stylesheets or url references
// (These could come from user scss that is merged into our theme, for example)
const css = Deno.readTextFileSync(cssPath);
const toDependencies = (paths: string[]) => {
return paths.map((path) => {
return {
name: path,
path: project ? join(project.dir, path) : path,
attribs: target.attribs,
};
});
};
const resources = toDependencies(cssResources(css));
const imports = toDependencies(cssImports(css));
// Push the compiled Css onto the dependency
const extraDeps = extras.html?.[kDependencies];
if (extraDeps) {
const existingDependency = extraDeps.find((extraDep) =>
extraDep.name === dependency
);
let targetName = target.name;
if (target.attribs["append-hash"] === "true") {
const hashFragment = `-${await md5HashBytes(
Deno.readFileSync(cssPath),
)}`;
let extension = "";
if (target.name.endsWith(".min.css")) {
extension = ".min.css";
} else if (target.name.endsWith(".css")) {
extension = ".css";
} else {
throw new InternalError("Unexpected target name: " + target.name);
}
targetName =
targetName.slice(0, target.name.length - extension.length) +
hashFragment + extension;
} else {
targetName = target.name;
}
if (existingDependency) {
if (!existingDependency.stylesheets) {
existingDependency.stylesheets = [];
}
existingDependency.stylesheets.push({
name: targetName,
path: cssPath,
attribs: target.attribs,
});
// Add any css references
existingDependency.stylesheets.push(...imports);
existingDependency.resources?.push(...resources);
} else {
extraDeps.push({
name: dependency,
stylesheets: [{
name: targetName,
path: cssPath,
attribs: target.attribs,
}, ...imports],
resources,
});
}
}
}
}
// Resolve generated quarto css variables
if (hasDarkStyles && defaultStyle !== "dark") {
// Put dark stylesheet first if light is default (for NoJS)
extras = await resolveQuartoSyntaxHighlighting(
inputDir,
extras,
format,
project,
"dark",
defaultStyle,
);
}
extras = await resolveQuartoSyntaxHighlighting(
inputDir,
extras,
format,
project,
hasDarkStyles ? "light" : "default",
defaultStyle,
);
if (hasDarkStyles && defaultStyle === "dark") {
// Put dark stylesheet second if dark is default (for NoJS)
extras = await resolveQuartoSyntaxHighlighting(
inputDir,
extras,
format,
project,
"dark",
defaultStyle,
);
}
if (isHtmlOutput(format.pandoc, true)) {
// We'll take care of text highlighting for HTML
setTextHighlightStyle("none", extras);
}
return extras;
}
// Generates syntax highlighting Css and Css variables
async function resolveQuartoSyntaxHighlighting(
inputDir: string,
extras: FormatExtras,
format: Format,
project: ProjectContext,
style: "dark" | "light" | "default",
defaultStyle?: "dark" | "light",
) {
// if
const minimal = format.metadata[kMinimal] === true;
if (minimal) {
return extras;
}
extras = cloneDeep(extras);
// If we're using default highlighting, use theme darkness to select highlight style
const mediaAttr = attribForThemeStyle(style);
if (style === "default") {
if (extras.html?.[kTextHighlightingMode] === "dark") {
style = "dark";
}
}
mediaAttr.id = "quarto-text-highlighting-styles";
// Generate and inject the text highlighting css
const cssFileName = `quarto-syntax-highlighting${
style === "dark" ? "-dark" : ""
}`;
// Read the highlight style (theme name)
const themeDescriptor = readHighlightingTheme(inputDir, format.pandoc, style);
if (themeDescriptor) {
// Other variables that need to be injected (if any)
const extraVariables = extras.html?.[kQuartoCssVariables] || [];
for (let i = 0; i < extraVariables.length; ++i) {
// For the same reason as outlined in https://github.com/rstudio/bslib/issues/1104,
// we need to patch the text to include a semicolon inside the declaration
// if it doesn't have one.
// This happens because scss-parser is brittle, and will fail to parse a declaration
// if it doesn't end with a semicolon.
//
// In addition, we know that some our variables come from the output
// of sassCompile which
// - misses the last semicolon
// - emits a :root declaration
// - triggers the scss-parser bug
// So we'll attempt to target the last declaration in the :root
// block specifically and add a semicolon if it doesn't have one.
let variable = extraVariables[i].trim();
if (
variable.endsWith("}") && variable.startsWith(":root") &&
!variable.match(/.*;\s?}$/)
) {
variable = variable.slice(0, -1) + ";}";
extraVariables[i] = variable;
}
}
// The text highlighting CSS variables
const highlightCss = generateThemeCssVars(themeDescriptor.json);
if (highlightCss) {
const rules = [
highlightCss,
"",
"/* other quarto variables */",
...extraVariables,
];
// The text highlighting CSS rules
const textHighlightCssRules = generateThemeCssClasses(
themeDescriptor.json,
);
if (textHighlightCssRules) {
rules.push(...textHighlightCssRules);
}
// Add this string literal to the rule set, which prevents pandoc
// from inlining this style sheet
// See https://github.com/jgm/pandoc/commit/7c0a80c323f81e6262848bfcfc922301e3f406e0
rules.push(".prevent-inlining { content: '</'; }");
// Compile the scss
const highlightCssPath = await compileSass(
[{
key: cssFileName + ".css",
quarto: {
uses: "",
defaults: "",
functions: "",
mixins: "",
rules: rules.join("\n"),
},
}],
project,
false,
);
// Find the bootstrap or quarto-html dependency and inject this stylesheet
const extraDeps = extras.html?.[kDependencies];
if (extraDeps) {
// Inject an scss variable for setting the background color of code blocks
// with defaults, before the other bootstrap variables?
// don't put it in css (basically use the value to set the default), allow
// default to be override by user
const quartoDependency = extraDeps.find((extraDep) =>
extraDep.name === kQuartoHtmlDependency
);
const existingDependency = quartoDependency;
if (existingDependency) {
existingDependency.stylesheets = existingDependency.stylesheets ||
[];
const hash = await md5HashBytes(Deno.readFileSync(highlightCssPath));
existingDependency.stylesheets.push({
name: cssFileName + `-${hash}.css`,
path: highlightCssPath,
attribs: mediaAttr,
});
}
}
}
}
return extras;
}
// Generates CSS variables based upon the syntax highlighting rules in a theme file
function generateThemeCssVars(
themeJson: Record<string, unknown>,
) {
const textStyles = themeJson["text-styles"] as Record<
string,
Record<string, unknown>
>;
if (textStyles) {
const lines: string[] = [];
lines.push("/* quarto syntax highlight colors */");
lines.push(":root {");
Object.keys(textStyles).forEach((styleName) => {
const abbr = kAbbrevs[styleName];
if (abbr) {
const textValues = textStyles[styleName];
Object.keys(textValues).forEach((textAttr) => {
switch (textAttr) {
case "text-color":
lines.push(
` --quarto-hl-${abbr}-color: ${
textValues[textAttr] ||
"inherit"
};`,
);
break;
}
});
}
});
lines.push("}");
return lines.join("\n");
}
return undefined;
}
// Generates CSS rules based upon the syntax highlighting rules in a theme file
function generateThemeCssClasses(
themeJson: Record<string, unknown>,
) {
const textStyles = themeJson["text-styles"] as Record<
string,
Record<string, unknown>
>;
if (textStyles) {
const lines: string[] = [];
Object.keys(textStyles).forEach((styleName) => {
const abbr = kAbbrevs[styleName];
if (abbr !== undefined) {
const textValues = textStyles[styleName];
const cssValues = generateCssKeyValues(textValues);
if (abbr !== "") {
lines.push(`\ncode span.${abbr} {`);
lines.push(...cssValues);
lines.push("}\n");
} else {
[
"pre > code.sourceCode > span",
"code span",
"code.sourceCode > span",
"div.sourceCode,\ndiv.sourceCode pre.sourceCode",
]
.forEach((selector) => {
lines.push(`\n${selector} {`);
lines.push(...cssValues);
lines.push("}\n");
});
}
}
});
return lines;
}
return undefined;
}
interface CSSResult {
path: string | undefined;
dark: boolean;
}
// Processes CSS into format extras (scanning for variables and removing them)
async function processCssIntoExtras(
cssPath: string,
extras: FormatExtras,
project: ProjectContext,
): Promise<CSSResult> {
const { temp } = project;
extras.html = extras.html || {};
const css = Deno.readTextFileSync(cssPath);
// Extract dark sentinel value
const hasDarkSentinel = cssHasDarkModeSentinel(css);
if (!extras.html[kTextHighlightingMode] && hasDarkSentinel) {
setTextHighlightStyle("dark", extras);
}
// Extract variables
const matches = css.matchAll(kVariablesRegex);
if (matches) {
extras.html[kQuartoCssVariables] = extras.html[kQuartoCssVariables] || [];
let dirty = false;
for (const match of matches) {
const variables = match[1];
extras.html[kQuartoCssVariables]?.push(variables);
dirty = true;
}
// Don't include duplicate variables
extras.html[kQuartoCssVariables] = uniqBy(
extras.html[kQuartoCssVariables],
(val: string) => {
return val;
},
);
if (dirty) {
const cleanedCss = css.replaceAll(kVariablesRegex, "");
let newCssPath: string | undefined;
if (cleanedCss.trim() === "") {
newCssPath = undefined;
} else {
const hash = await md5HashBytes(new TextEncoder().encode(cleanedCss));
newCssPath = temp.createFile({ suffix: `-${hash}.css` });
Deno.writeTextFileSync(newCssPath, cleanedCss, {
mode: safeModeFromFile(cssPath),
});
}
return {
dark: hasDarkSentinel,
path: newCssPath,
};
}
}
return {
dark: hasDarkSentinel,
path: cssPath,
};
}
const kVariablesRegex =
/\/\*\! quarto-variables-start \*\/([\S\s]*)\/\*\! quarto-variables-end \*\//g;
// Attributes for the style tag
function attribForThemeStyle(
style: "dark" | "light" | "default",
): Record<string, string> {
const colorModeAttrs = (mode: string) => {
const attr: Record<string, string> = {
class: `quarto-color-scheme${
mode === "dark" ? " quarto-color-alternate" : ""
}`,
};
return attr;
};
switch (style) {
case "dark":
return colorModeAttrs("dark");
case "light":
return colorModeAttrs("light");
case "default":
default:
return {};
}
}
// Note the text highlight style in extras
export function setTextHighlightStyle(
style: "light" | "dark" | "none",
extras: FormatExtras,
) {
extras.html = extras.html || {};
extras.html[kTextHighlightingMode] = style;
}