-
Notifications
You must be signed in to change notification settings - Fork 433
Expand file tree
/
Copy pathdot.ts
More file actions
220 lines (201 loc) · 6.48 KB
/
dot.ts
File metadata and controls
220 lines (201 loc) · 6.48 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
/*
* graphviz.ts
*
* Copyright (C) 2022 Posit Software, PBC
*/
import { LanguageCellHandlerContext, LanguageHandler } from "./types.ts";
import { baseHandler, install } from "./base.ts";
import { resourcePath } from "../resources.ts";
import { join, toFileUrl } from "../../deno_ral/path.ts";
import {
isIpynbOutput,
isJavascriptCompatible,
isLatexOutput,
isRevealjsOutput,
isTypstOutput,
} from "../../config/format.ts";
import { QuartoMdCell } from "../lib/break-quarto-md.ts";
import { mappedConcat, mappedIndexToLineCol } from "../lib/mapped-text.ts";
import { lineOffsets } from "../lib/text.ts";
import {
kFigAlign,
kFigHeight,
kFigResponsive,
kFigWidth,
kIpynbProduceSourceNotebook,
} from "../../config/constants.ts";
import {
fixupAlignment,
makeResponsive,
resolveSize,
setSvgSize,
} from "../svg.ts";
import { Element, parseHtml } from "../deno-dom.ts";
const dotHandler: LanguageHandler = {
...baseHandler,
type: "cell",
stage: "post-engine",
languageName: "dot",
defaultOptions: {
echo: false,
eval: true,
include: true,
"graph-layout": "dot",
},
comment: "//",
async cell(
handlerContext: LanguageCellHandlerContext,
cell: QuartoMdCell,
options: Record<string, unknown>,
) {
const cellContent = handlerContext.cellContent(cell);
const graphvizModule = await import(
toFileUrl(resourcePath(join("js", "graphviz-wasm.js"))).href
);
let svg;
// use console["log"] here instead of dot notation
// to allow us to lint for the dot notation usage which
// we want to disallow throughout the codebase
const oldConsoleLog = console["log"];
const oldConsoleWarn = console["warn"];
console["log"] = () => {};
console["warn"] = () => {};
try {
svg = await graphvizModule.graphviz().layout(
cellContent.value,
"svg",
options["graph-layout"],
);
} catch (e) {
if (!(e instanceof Error)) throw e;
const m = (e.message as string).match(
/(.*)syntax error in line (\d+)(.*)/,
);
if (m) {
const number = Number(m[2]) - 1;
const locF = mappedIndexToLineCol(cellContent);
const offsets = Array.from(lineOffsets(cellContent.value));
const offset = offsets[number];
const mapResult = cellContent.map(offset, true);
const { line } = locF(offset);
e.message = (e.message as string).replace(
m[0],
`${m[1]}syntax error in file ${
mapResult!.originalString.fileName
}, line ${line + 1}${m[3]}`,
);
}
throw e;
} finally {
console["log"] = oldConsoleLog;
console["warn"] = oldConsoleWarn;
}
const makeFigLink = (
sourceName: string,
width?: number,
height?: number,
includeCaption?: boolean,
) => {
const figEnvSpecifier =
isLatexOutput(handlerContext.options.format.pandoc)
? ` fig-env='${cell.options?.["fig-env"] || "figure"}'`
: "";
const heightOffset = isTypstOutput(handlerContext.options.format.pandoc)
? 0.1
: 0.0;
let posSpecifier = "";
if (
isLatexOutput(handlerContext.options.format.pandoc) &&
cell.options?.["fig-pos"] !== false
) {
const v = Array.isArray(cell.options?.["fig-pos"])
? cell.options?.["fig-pos"].join("")
: cell.options?.["fig-pos"];
posSpecifier = ` fig-pos='${v || "H"}'`;
}
const idSpecifier = (cell.options?.label && includeCaption)
? ` #${cell.options?.label}`
: "";
const widthSpecifier = width
? `width="${Math.round(width * 100) / 100}in"`
: "";
const heightSpecifier = height
? ` height="${(Math.round(height * 100) / 100) + heightOffset}in"`
: "";
const captionSpecifier = includeCaption
? (cell.options?.["fig-cap"] || "")
: "";
return `\n{${widthSpecifier}${heightSpecifier}${posSpecifier}${figEnvSpecifier}${idSpecifier}}\n`;
};
const fixupRevealAlignment = (svg: Element) => {
if (isRevealjsOutput(handlerContext.options.context.format.pandoc)) {
const align = (options?.[kFigAlign] as string) ?? "center";
fixupAlignment(svg, align);
}
};
if (
isJavascriptCompatible(handlerContext.options.format) &&
!isIpynbOutput(handlerContext.options.format.pandoc)
) {
const responsive = options?.[kFigResponsive] ??
handlerContext.options.context.format.metadata
?.[kFigResponsive];
svg = (await parseHtml(svg)).querySelector("svg")!.outerHTML;
if (
responsive && options[kFigWidth] === undefined &&
options[kFigHeight] === undefined
) {
svg = await makeResponsive(svg, fixupRevealAlignment);
} else {
svg = await setSvgSize(svg, options, fixupRevealAlignment);
}
svg = mappedConcat(["```{=html}\n", svg, "\n```\n"]);
return this.build(handlerContext, cell, svg, options);
} else {
const {
filenames: [sourceName],
} = await handlerContext.createPngsFromHtml({
prefix: "dot-figure-",
selector: "svg",
count: 1,
deviceScaleFactor: Number(options.deviceScaleFactor) || 4,
html: `<!DOCTYPE html><html><body>${svg}</body></html>`,
});
const {
widthInInches,
heightInInches,
} = await resolveSize(svg, options);
const isIpynbSourceOutput =
isIpynbOutput(handlerContext.options.context.format.pandoc) &&
handlerContext.options.context.format
.render[kIpynbProduceSourceNotebook];
if (isIpynbSourceOutput) {
// If we're producing a source notebook, we know that we're just
// producing an image, so present the output as an image in
// a markdown cell (and allow the figure attributes through)
const figLink = makeFigLink(
sourceName,
widthInInches,
heightInInches,
true,
);
return mappedConcat(["\n:::{.cell .markdown}", figLink, ":::\n"]);
} else {
return this.build(
handlerContext,
cell,
mappedConcat([
makeFigLink(
sourceName,
widthInInches,
heightInInches,
),
// `\n{width="${widthInInches}in" height="${heightInInches}in" fig-pos='H'}\n`,
]),
options,
);
}
}
},
};
install(dotHandler);