forked from quarto-dev/quarto-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat-html-scss.ts
More file actions
806 lines (737 loc) · 21.6 KB
/
format-html-scss.ts
File metadata and controls
806 lines (737 loc) · 21.6 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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
/*
* format-html-scss.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import { existsSync } from "../../deno_ral/fs.ts";
import { dirname, extname, isAbsolute, join } from "../../deno_ral/path.ts";
import { formatResourcePath } from "../../core/resources.ts";
import {
asBootstrapColor,
asCssColor,
asCssFont,
asCssNumber,
asCssSize,
} from "../../core/css.ts";
import { mergeLayers, sassLayer } from "../../core/sass.ts";
import { outputVariable, SassVariable, sassVariable } from "../../core/sass.ts";
import {
Format,
SassBundle,
SassBundleWithBrand,
SassLayer,
} from "../../config/types.ts";
import { Metadata } from "../../config/types.ts";
import { kGrid, kTheme } from "../../config/constants.ts";
import {
kPageFooter,
kSiteNavbar,
kSiteSidebar,
kWebsite,
} from "../../project/types/website/website-constants.ts";
import {
bootstrapFunctions,
bootstrapMixins,
bootstrapResourceDir,
bootstrapRules,
bootstrapVariables,
bslibComponentMixins,
bslibComponentRules,
bslibResourceDir,
htmlToolsRules,
kBootstrapDependencyName,
quartoBootstrapCustomizationLayer,
quartoBootstrapFunctions,
quartoBootstrapMixins,
quartoBootstrapRules,
quartoCodeFilenameRules,
quartoCopyCodeDefaults,
quartoCopyCodeRules,
quartoDefaults,
quartoFunctions,
quartoGlobalCssVariableRules,
quartoLinkExternalRules,
quartoRules,
quartoUses,
sassUtilFunctions,
} from "./format-html-shared.ts";
import { readHighlightingTheme } from "../../quarto-core/text-highlighting.ts";
import { warn } from "log";
export interface Themes {
light: string[];
dark?: string[];
}
function layerQuartoScss(
key: string,
dependency: string,
sassLayer: (SassLayer | "brand")[],
format: Format,
darkLayer?: (SassLayer | "brand")[],
darkDefault?: boolean,
loadPaths?: string[],
): SassBundleWithBrand {
// Compose the base Quarto SCSS
const uses = quartoUses();
const defaults = [
quartoDefaults(format),
quartoBootstrapDefaults(format.metadata),
quartoCopyCodeDefaults(),
].join("\n");
const mixins = [quartoBootstrapMixins()].join("\n");
const functions = [quartoFunctions(), quartoBootstrapFunctions()].join("\n");
const rules = [
quartoRules(),
quartoCopyCodeRules(),
quartoBootstrapRules(),
quartoGlobalCssVariableRules(),
quartoLinkExternalRules(),
quartoCodeFilenameRules(),
].join("\n");
const quartoScss = {
uses,
defaults,
functions,
mixins,
rules,
};
// Compose the framework level SCSS (bootstrap)
// The bootstrap framework functions
const frameworkFunctions = [
bootstrapFunctions(),
sassUtilFunctions("color-contrast.scss"),
].join(
"\n",
);
// The bootstrap framework variables
const frameworkVariables = [
bootstrapVariables(),
pandocVariablesToThemeScss(format.metadata),
].join("\n");
const frameworkMixins = [bootstrapMixins(), bslibComponentMixins()].join(
"\n",
);
const frameworkRules = [
bootstrapRules(),
bslibComponentRules(),
htmlToolsRules(),
].join("\n");
const bootstrapScss = {
uses: "",
defaults: frameworkVariables,
functions: frameworkFunctions,
mixins: frameworkMixins,
rules: frameworkRules,
};
// Compute the load paths
const resolvedLoadPaths = [
...(loadPaths || []),
bootstrapResourceDir(),
bslibResourceDir(),
];
return {
dependency,
key,
user: sassLayer,
quarto: quartoScss,
framework: bootstrapScss,
loadPaths: resolvedLoadPaths,
dark: darkLayer
? {
user: darkLayer,
default: darkDefault,
}
: undefined,
attribs: { id: "quarto-bootstrap" },
};
}
export function resolveBootstrapScss(
input: string,
format: Format,
sassLayers: SassLayer[],
): SassBundleWithBrand[] {
// Quarto built in css
const quartoThemesDir = formatResourcePath(
"html",
join("bootstrap", "themes"),
);
// Resolve the provided themes to a set of variables and styles
const theme = format.metadata[kTheme] || [];
const [themeSassLayers, defaultDark, loadPaths] = resolveThemeLayer(
format,
input,
theme,
quartoThemesDir,
sassLayers,
);
// Find light and dark sass layers
const sassBundles: SassBundleWithBrand[] = [];
// light
sassBundles.push(
layerQuartoScss(
"quarto-theme",
kBootstrapDependencyName,
themeSassLayers.light,
format,
themeSassLayers.dark,
defaultDark,
loadPaths,
),
);
return sassBundles;
}
export interface ThemeSassLayer {
light: (SassLayer | "brand")[];
dark?: (SassLayer | "brand")[];
}
function layerTheme(
input: string,
themes: string[],
quartoThemesDir: string,
): { layers: (SassLayer | "brand")[]; loadPaths: string[] } {
let injectedCustomization = false;
const loadPaths: string[] = [];
const layers = themes.flatMap((theme) => {
const isAbs = isAbsolute(theme);
const isScssFile = [".scss", ".css"].includes(extname(theme));
if (theme === "brand") {
// provide a brand order marker for downstream
// processing to know where to insert the brand scss
return "brand";
} else if (isAbs && isScssFile) {
// Absolute path to a SCSS file
if (existsSync(theme)) {
const themeDir = dirname(theme);
loadPaths.push(themeDir);
return sassLayer(theme);
} else {
warn(`Theme file not found: ${theme}`);
}
} else if (isScssFile) {
// Relative path to a SCSS file
const themePath = join(dirname(input), theme);
if (existsSync(themePath)) {
const themeDir = dirname(themePath);
loadPaths.push(themeDir);
return sassLayer(themePath);
} else {
warn(`Theme file not found: ${themePath}`);
}
} else {
// The directory for this theme
const resolvedThemePath = join(quartoThemesDir, `${theme}.scss`);
// Read the sass layers
if (existsSync(resolvedThemePath)) {
// The theme appears to be a built in theme
// The theme layer from a built in theme
const themeLayer = sassLayer(resolvedThemePath);
// Inject customization of the theme (this should go just after the theme)
injectedCustomization = true;
return [themeLayer, quartoBootstrapCustomizationLayer()];
}
}
return {
uses: "",
defaults: "",
functions: "",
mixins: "",
rules: "",
};
});
// If no themes were provided, we still should inject our customization
if (!injectedCustomization) {
layers.unshift(quartoBootstrapCustomizationLayer());
}
return { layers, loadPaths };
}
export function resolveTextHighlightingLayer(
input: string,
format: Format,
style: "dark" | "light",
) {
const layer = {
uses: "",
defaults: "",
functions: "",
mixins: "",
rules: "",
};
const themeDescriptor = readHighlightingTheme(
dirname(input),
format.pandoc,
style,
);
if (format.metadata[kCodeBlockBackground] === undefined) {
// Inject a background color, if present
if (themeDescriptor && !themeDescriptor.isAdaptive) {
const backgroundColor = () => {
if (themeDescriptor.json["background-color"]) {
return themeDescriptor.json["background-color"] as string;
} else {
const editorColors = themeDescriptor.json["editor-colors"] as
| Record<string, string>
| undefined;
if (editorColors && editorColors["BackgroundColor"]) {
return editorColors["BackgroundColor"] as string;
} else {
return undefined;
}
}
};
const background = backgroundColor();
if (background) {
layer.defaults = outputVariable(
sassVariable(
"code-block-bg",
asCssColor(background),
),
true,
);
}
}
// Inject a text color regardless of adaptive status. Adaptive themes
// handle their own bg, but when separate light/dark themes are paired
// (e.g. kate + zenburn), the dark theme still needs its text-color
// emitted as $code-block-color so Bootstrap rules can apply it.
if (themeDescriptor) {
const textColor = themeDescriptor.json["text-color"] as string;
if (textColor) {
layer.defaults = layer.defaults + "\n" + outputVariable(
sassVariable(
"code-block-color",
asCssColor(textColor),
),
true,
);
}
}
}
if (themeDescriptor) {
const readTextColor = (name: string) => {
const textStyles = themeDescriptor.json["text-styles"];
if (textStyles && typeof textStyles === "object") {
const commentColor = (textStyles as Record<string, unknown>)[name];
if (commentColor && typeof commentColor === "object") {
const textColor =
(commentColor as Record<string, unknown>)["text-color"];
return textColor;
} else {
return undefined;
}
} else {
return undefined;
}
};
const commentColor = readTextColor("Comment");
if (commentColor) {
layer.defaults = layer.defaults + "\n" + outputVariable(
sassVariable(
"btn-code-copy-color",
asCssColor(commentColor),
),
true,
);
}
const functionColor = readTextColor("Function");
if (functionColor) {
layer.defaults = layer.defaults + "\n" + outputVariable(
sassVariable(
"btn-code-copy-color-active",
asCssColor(functionColor),
),
true,
);
}
}
return layer;
}
// Resolve the themes into a ThemeSassLayer
function resolveThemeLayer(
format: Format,
input: string,
themes: string | string[] | Themes | unknown,
quartoThemesDir: string,
sassLayers: SassLayer[],
): [ThemeSassLayer, boolean, string[]] {
let theme = undefined;
let defaultDark = false;
if (typeof themes === "string") {
// The themes is just a string
theme = { light: [themes] };
} else if (Array.isArray(themes)) {
// The themes is an array
theme = { light: themes };
} else if (typeof themes === "object") {
// The themes are an object - look at each key and
// deal with them either as a string or a string[]
const themeArr = (theme?: unknown): string[] => {
const themes: string[] = [];
if (theme) {
if (typeof theme === "string") {
themes.push(theme);
} else if (Array.isArray(theme)) {
themes.push(...theme);
}
}
return themes;
};
const themeObj = themes as Record<string, unknown>;
// See whether the dark or light theme is the default
const keyList = Object.keys(themeObj);
defaultDark = keyList.length > 1 && keyList[0] === "dark";
theme = {
light: themeArr(themeObj.light),
dark: themeObj.dark ? themeArr(themeObj.dark) : undefined,
};
} else {
theme = { light: [] };
}
const lightLayerContext = layerTheme(input, theme.light, quartoThemesDir);
lightLayerContext.layers.unshift(...sassLayers);
const highlightingLayer = resolveTextHighlightingLayer(
input,
format,
"light",
);
if (highlightingLayer) {
lightLayerContext.layers.unshift(highlightingLayer);
}
const darkLayerContext = theme.dark
? layerTheme(input, theme.dark, quartoThemesDir)
: undefined;
if (darkLayerContext) {
darkLayerContext.layers.unshift(...sassLayers);
const darkHighlightingLayer = resolveTextHighlightingLayer(
input,
format,
"dark",
);
if (darkHighlightingLayer) {
darkLayerContext.layers.unshift(darkHighlightingLayer);
}
}
const themeSassLayer = {
light: lightLayerContext.layers,
dark: darkLayerContext?.layers,
};
const loadPaths = [
...lightLayerContext.loadPaths,
...darkLayerContext?.loadPaths || [],
];
return [themeSassLayer, defaultDark, loadPaths];
}
function pandocVariablesToThemeDefaults(
metadata: Metadata,
): SassVariable[] {
const explicitVars: SassVariable[] = [];
// Helper for adding explicitly set variables
const add = (
defaults: SassVariable[],
name: string,
value?: unknown,
formatter?: (val: unknown) => unknown,
) => {
if (value) {
const sassVar = sassVariable(name, value, formatter);
defaults.push(sassVar);
}
};
// Pass through to some bootstrap variables
add(explicitVars, "line-height-base", metadata["linestretch"], asCssNumber);
add(explicitVars, "font-size-root", metadata["fontsize"]);
add(explicitVars, "body-bg", metadata["backgroundcolor"]);
add(explicitVars, "body-color", metadata["fontcolor"]);
add(explicitVars, "link-color", metadata["linkcolor"]);
add(explicitVars, "font-family-base", metadata["mainfont"], asCssFont);
add(explicitVars, "font-family-code", metadata["monofont"], asCssFont);
add(explicitVars, "mono-background-color", metadata["monobackgroundcolor"]);
// Deal with sizes
const explicitSizes = [
"max-width",
"margin-top",
"margin-bottom",
"margin-left",
"margin-right",
];
explicitSizes.forEach((attrib) => {
add(explicitVars, attrib, metadata[attrib], asCssSize);
});
// Resolve any grid variables
const gridObj = metadata[kGrid] as Metadata;
if (gridObj) {
add(explicitVars, "grid-sidebar-width", gridObj["sidebar-width"]);
add(explicitVars, "grid-margin-width", gridObj["margin-width"]);
add(explicitVars, "grid-body-width", gridObj["body-width"]);
add(explicitVars, "grid-column-gutter-width", gridObj["gutter-width"]);
}
return explicitVars;
}
function pandocVariablesToThemeScss(
metadata: Metadata,
asDefaults = false,
) {
return pandocVariablesToThemeDefaults(metadata).map(
(variable) => {
return outputVariable(variable, asDefaults);
},
).join("\n");
}
const kCodeBorderLeft = "code-block-border-left";
const kCodeBlockBackground = "code-block-bg";
const kBackground = "background";
const kForeground = "foreground";
const kTogglePosition = "toggle-position";
const kColor = "color";
const kBorder = "border";
// Quarto variables and styles
export const quartoBootstrapDefaults = (metadata: Metadata) => {
const varFilePath = formatResourcePath(
"html",
join("bootstrap", "_bootstrap-variables.scss"),
);
const variables = [Deno.readTextFileSync(varFilePath)];
const colorDefaults: string[] = [];
const navbar = (metadata[kWebsite] as Metadata)?.[kSiteNavbar];
if (navbar && typeof navbar === "object") {
// Forward navbar background color
const navbarBackground = (navbar as Record<string, unknown>)[kBackground];
if (navbarBackground !== undefined) {
resolveBootstrapColorDefault(navbarBackground, colorDefaults);
variables.push(
outputVariable(
sassVariable(
"navbar-bg",
navbarBackground,
typeof navbarBackground === "string" ? asBootstrapColor : undefined,
),
),
);
}
// Forward navbar foreground color
const navbarForeground = (navbar as Record<string, unknown>)[kForeground];
if (navbarForeground !== undefined) {
resolveBootstrapColorDefault(navbarForeground, colorDefaults);
variables.push(
outputVariable(
sassVariable(
"navbar-fg",
navbarForeground,
typeof navbarForeground === "string" ? asBootstrapColor : undefined,
),
),
);
}
// Forward the toggle-position
const navbarTogglePosition =
(navbar as Record<string, unknown>)[kTogglePosition];
if (navbarTogglePosition !== undefined) {
variables.push(
outputVariable(
sassVariable(
"navbar-toggle-position",
navbarTogglePosition,
),
),
);
}
}
const sidebars = (metadata[kWebsite] as Metadata)?.[kSiteSidebar];
const sidebar = Array.isArray(sidebars)
? sidebars[0]
: typeof sidebars === "object"
? (sidebars as Metadata)
: undefined;
if (sidebar) {
// Forward background color
const sidebarBackground = sidebar[kBackground];
if (sidebarBackground !== undefined) {
resolveBootstrapColorDefault(sidebarBackground, colorDefaults);
variables.push(
outputVariable(
sassVariable(
"sidebar-bg",
sidebarBackground,
typeof sidebarBackground === "string"
? asBootstrapColor
: undefined,
),
),
);
} else if (sidebar.style === "floating" || navbar) {
// If this is a floating sidebar or there is a navbar present,
// default to a body colored sidebar
variables.push(
`$sidebar-bg: if(variable-exists(body-bg), $body-bg, #fff) !default;`,
);
}
// Forward foreground color
const sidebarForeground = sidebar[kForeground];
if (sidebarForeground !== undefined) {
resolveBootstrapColorDefault(sidebarForeground, colorDefaults);
variables.push(
outputVariable(
sassVariable(
"sidebar-fg",
sidebarForeground,
typeof sidebarForeground === "string"
? asBootstrapColor
: undefined,
),
),
);
}
// Enable the sidebar border for docked by default
const sidebarBorder = sidebar[kBorder];
variables.push(
outputVariable(
sassVariable(
"sidebar-border",
sidebarBorder !== undefined
? sidebarBorder
: sidebar.style === "docked",
),
),
);
} else {
// If there is no sidebar, default to body color for any sidebar that may appear
variables.push(
`$sidebar-bg: if(variable-exists(body-bg), $body-bg, #fff) !default;`,
);
}
const footer = (metadata[kWebsite] as Metadata)?.[kPageFooter] as Metadata;
if (footer !== undefined && typeof footer === "object") {
// Forward footer color
const footerBg = footer[kBackground];
if (footerBg !== undefined) {
resolveBootstrapColorDefault(footerBg, colorDefaults);
variables.push(
outputVariable(
sassVariable(
"footer-bg",
footerBg,
typeof footerBg === "string" ? asBootstrapColor : undefined,
),
),
);
}
// Forward footer foreground
const footerFg = footer[kForeground];
if (footerFg !== undefined) {
resolveBootstrapColorDefault(footerFg, colorDefaults);
variables.push(
outputVariable(
sassVariable(
"footer-fg",
footerFg,
typeof footerFg === "string" ? asBootstrapColor : undefined,
),
),
);
}
// Forward footer border
const footerBorder = footer[kBorder];
// Enable the border unless it is explicitly disabled
const showBorder = footerBorder !== undefined
? footerBorder
: sidebar?.style === "docked";
if (showBorder) {
variables.push(
outputVariable(
sassVariable(
"footer-border",
true,
),
),
);
}
// If the footer border is a color, set that
if (footerBorder !== undefined && typeof footerBorder === "string") {
resolveBootstrapColorDefault(footerBorder, colorDefaults);
variables.push(
outputVariable(
sassVariable(
"footer-border-color",
footerBorder,
asBootstrapColor,
),
),
);
}
// Forward any footer color
const footerColor = footer[kColor];
if (footerColor && typeof footerColor === "string") {
resolveBootstrapColorDefault(footerColor, colorDefaults);
variables.push(
outputVariable(
sassVariable(
"footer-color",
footerColor,
asBootstrapColor,
),
),
);
}
}
// Forward codeleft-border
const codeblockLeftBorder = metadata[kCodeBorderLeft];
const codeblockBackground = metadata[kCodeBlockBackground];
if (codeblockLeftBorder !== undefined) {
resolveBootstrapColorDefault(codeblockLeftBorder, colorDefaults);
variables.push(
outputVariable(
sassVariable(
kCodeBorderLeft,
codeblockLeftBorder,
typeof codeblockLeftBorder === "string"
? asBootstrapColor
: undefined,
),
),
);
if (codeblockBackground === undefined && codeblockLeftBorder !== false) {
variables.push(outputVariable(sassVariable(kCodeBlockBackground, false)));
}
}
// code background color
if (codeblockBackground !== undefined) {
variables.push(outputVariable(sassVariable(
kCodeBlockBackground,
codeblockBackground,
typeof codeblockBackground === "string" ? asBootstrapColor : undefined,
)));
}
// Ensure any color variable defaults are present
colorDefaults.forEach((colorDefault) => {
variables.push(colorDefault);
});
// Any of the variables that we added from metadata should go first
// So they provide the defaults
return variables.reverse().join("\n");
};
function resolveBootstrapColorDefault(value: unknown, variables: string[]) {
if (value) {
const variable = bootstrapColorDefault(value);
if (
variable &&
!variables.find((existingVar) => {
return existingVar === variable;
})
) {
variables.unshift(variable);
}
}
}
function bootstrapColorDefault(value: unknown) {
if (typeof value === "string") {
return bootstrapColorVars[value];
}
}
const bootstrapColorVars: Record<string, string> = {
primary: "$primary: #0d6efd !default;",
secondary: "$secondary: #6c757d !default;",
success: "$success: #198754 !default;",
info: "$info: #0dcaf0 !default;",
warning: "$warning: #ffc107 !default;",
danger: "$danger: #dc3545 !default;",
light: "$light: #f8f9fa !default;",
dark: "$dark: #212529 !default;",
};