-
Notifications
You must be signed in to change notification settings - Fork 86
/
processHtml.ts
446 lines (396 loc) · 12.4 KB
/
processHtml.ts
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
// This code is a Qiskit project.
//
// (C) Copyright IBM 2024.
//
// This code is licensed under the Apache License, Version 2.0. You may
// obtain a copy of this license in the LICENSE file in the root directory
// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
//
// Any modifications or derivative works of this code must retain this
// copyright notice, and modified files need to carry a notice indicating
// that they have been altered from the originals.
import { last } from "lodash";
import { CheerioAPI, Cheerio, load } from "cheerio";
import { Image } from "./HtmlToMdResult";
import { Metadata, ApiType } from "./Metadata";
import { getLastPartFromFullIdentifier } from "../stringUtils";
export type ProcessedHtml = {
html: string;
meta: Metadata;
images: Image[];
isReleaseNotes: boolean;
};
export function processHtml(options: {
html: string;
url: string;
imageDestination: string;
baseSourceUrl: string;
releaseNotesTitle: string;
}): ProcessedHtml {
const { html, url, imageDestination, baseSourceUrl, releaseNotesTitle } =
options;
const $ = load(html);
const $main = $(`[role='main']`);
const isReleaseNotes = url.endsWith("release_notes.html");
const images = loadImages($, $main, url, imageDestination, isReleaseNotes);
if (url.endsWith("release_notes.html")) {
renameAllH1s($, releaseNotesTitle);
}
// Warning: the sequence of operations often matters.
removeHtmlExtensionsInRelativeLinks($, $main);
removePermalinks($main);
removeDownloadSourceCode($main);
handleSphinxDesignCards($, $main);
addLanguageClassToCodeBlocks($, $main);
replaceSourceLinksWithGitHub($, $main, baseSourceUrl);
convertRubricsToHeaders($, $main);
processSimpleFieldLists($, $main);
removeColonSpans($main);
preserveMathBlockWhitespace($, $main);
const meta: Metadata = {};
processMembersAndSetMeta($, $main, meta);
maybeSetModuleMetadata($, $main, meta);
if (meta.apiType === "module") {
updateModuleHeadings($, $main, meta);
}
return { html: $main.html()!, meta, images, isReleaseNotes };
}
export function loadImages(
$: CheerioAPI,
$main: Cheerio<any>,
url: string,
imageDestination: string,
isReleaseNotes: boolean,
): Image[] {
return $main
.find("img")
.toArray()
.map((img) => {
const $img = $(img);
const imageUrl = new URL($img.attr("src")!, url);
const src = imageUrl.toString();
const filename = last(src.split("/"));
let dest = `${imageDestination}/${filename}`;
if (isReleaseNotes) {
// Release notes links should point to the current version
dest = dest.replace(/[0-9].*\//, "");
}
$img.attr("src", dest);
return { src, dest: dest };
});
}
export function removeHtmlExtensionsInRelativeLinks(
$: CheerioAPI,
$main: Cheerio<any>,
): void {
$main.find("a").each((_, link) => {
const $link = $(link);
const href = $link.attr("href");
if (href && !href.startsWith("http")) {
$link.attr("href", href.replaceAll(".html", ""));
}
});
}
export function renameAllH1s($: CheerioAPI, releaseNotesTitle: string): void {
$("h1").html(releaseNotesTitle);
}
export function removePermalinks($main: Cheerio<any>): void {
for (const [prefix, suffix] of [
["Permalink", "headline"],
["Permalink", "heading"],
["Permalink", "definition"],
["Link", "heading"],
["Link", "definition"],
]) {
$main.find(`a[title="${prefix} to this ${suffix}"]`).remove();
}
}
export function removeDownloadSourceCode($main: Cheerio<any>): void {
$main.find("p > a.reference.download.internal").closest("p").remove();
}
/**
* Flattens out sphinx-design cards, which are collapsible normally.
*
* Sets the card summary as a header and removes the blockquote from the body.
*
* This is only used by the historical API docs for qiskit-ibm-runtime. We disabled sphinx-design
* for every project moving forward.
*/
export function handleSphinxDesignCards(
$: CheerioAPI,
$main: Cheerio<any>,
): void {
$main.find(".sd-summary-title").each((_, quote) => {
const $quote = $(quote);
$quote.replaceWith(`<h3>${$quote.html()}</h3>`);
});
$main.find(".sd-card-body blockquote").each((_, quote) => {
const $quote = $(quote);
$quote.replaceWith($quote.children());
});
}
export function addLanguageClassToCodeBlocks(
$: CheerioAPI,
$main: Cheerio<any>,
): void {
$main.find("pre").each((_, pre) => {
const $pre = $(pre);
$pre.replaceWith(
`<pre><code class="language-python">${$pre.html()}</code></pre>`,
);
});
}
// TODO(#519): figure out if this is working.
export function replaceSourceLinksWithGitHub(
$: CheerioAPI,
$main: Cheerio<any>,
baseSourceUrl: string,
): void {
$main.find("a").each((_, a) => {
const $a = $(a);
const href = $a.attr("href");
if (
href === undefined ||
href.startsWith("http:") ||
!href.includes("_modules/")
) {
return;
}
//_modules/qiskit_ibm_runtime/ibm_backend
const match = href.match(/_modules\/(.*?)(#|$)/)!;
const newHref = `${baseSourceUrl}${match[1]}.py`;
$a.attr("href", newHref);
});
}
export function convertRubricsToHeaders(
$: CheerioAPI,
$main: Cheerio<any>,
): void {
// Rubrics correspond to method and attribute headers.
// TODO(#479): ensure our understanding of what .rubric corresponds to is correct and figure out
// if always using <h2> makes sense.
$main.find(".rubric").each((_, el) => {
const $el = $(el);
$el.replaceWith(`<h2>${$el.html()}</h2>`);
});
}
export function processSimpleFieldLists(
$: CheerioAPI,
$main: Cheerio<any>,
): void {
// TODO(#479): Have a better understanding of what dl.field-list.simple corresponds to
// and confirm this behavior makes sense.
$main
.find("dl.field-list.simple")
.toArray()
.map((dl) => {
const $dl = $(dl);
$dl
.find("dt")
.toArray()
.forEach((dt) => {
const $dt = $(dt);
$dt.replaceWith(`<strong>${$dt.html()}</strong>`);
});
$dl
.find("dd")
.toArray()
.forEach((dd) => {
const $dd = $(dd);
$dd.replaceWith(`<div>${$dd.html()}</div>`);
});
$dl.replaceWith(`<div>${$dl.html()}</div>`);
});
}
export function removeColonSpans($main: Cheerio<any>): void {
$main.find(".colon").remove();
}
export function processMembersAndSetMeta(
$: CheerioAPI,
$main: Cheerio<any>,
meta: Metadata,
): void {
let continueMapMembers = true;
while (continueMapMembers) {
// members can be recursive, so we need to pick elements one by one
const dl = $main
.find(
"dl.py.class, dl.py.property, dl.py.method, dl.py.attribute, dl.py.function, dl.py.exception",
)
.get(0);
if (!dl) {
continueMapMembers = false;
continue;
}
const $dl = $(dl);
const replacement = $dl
.children()
.toArray()
.map((child) => {
const $child = $(child);
$child.find(".viewcode-link").closest("a").remove();
const id = $dl.find("dt").attr("id") || "";
const apiType = getApiType($dl);
if (child.name !== "dt" || !apiType) {
return `<div>${$child.html()}</div>`;
}
const priorApiType = meta.apiType;
if (!priorApiType) {
meta.apiType = apiType;
meta.apiName = id;
}
if (apiType == "class") {
findByText($, $main, "em.property", "class").remove();
return `<span class="target" id="${id}"/><p><code>${$child.html()}</code></p>`;
}
if (apiType == "property") {
if (!priorApiType && id) {
$dl.siblings("h1").text(getLastPartFromFullIdentifier(id));
}
findByText($, $main, "em.property", "property").remove();
const signature = $child.find("em").text()?.replace(/^:\s+/, "");
if (signature.trim().length === 0) return;
return `<span class="target" id='${id}'/><p><code>${signature}</code></p>`;
}
if (apiType == "method") {
if (id) {
if (!priorApiType) {
$dl.siblings("h1").text(getLastPartFromFullIdentifier(id));
} else {
// Inline methods
$(`<h3>${getLastPartFromFullIdentifier(id)}</h3>`).insertBefore(
$dl,
);
}
}
findByText($, $main, "em.property", "method").remove();
return `<span class="target" id='${id}'/><p><code>${$child.html()}</code></p>`;
}
if (apiType == "attribute") {
if (!priorApiType) {
if (id) {
$dl.siblings("h1").text(getLastPartFromFullIdentifier(id));
}
findByText($, $main, "em.property", "attribute").remove();
const signature = $child.find("em").text()?.replace(/^:\s+/, "");
if (signature.trim().length === 0) return;
return `<span class="target" id='${id}'/><p><code>${signature}</code></p>`;
}
// Else, the attribute is embedded on the class
const text = $child.text();
const equalIndex = text.indexOf("=");
const colonIndex = text.indexOf(":");
let name = text;
let type: string | undefined;
let value: string | undefined;
if (colonIndex > 0 && equalIndex > 0) {
name = text.substring(0, colonIndex);
type = text.substring(colonIndex + 1, equalIndex);
value = text.substring(equalIndex);
} else if (colonIndex > 0) {
name = text.substring(0, colonIndex);
type = text.substring(colonIndex + 1);
} else if (equalIndex > 0) {
name = text.substring(0, equalIndex);
value = text.substring(equalIndex);
}
const output = [`<span class="target" id='${id}'/><h3>${name}</h3>`];
if (type) {
output.push(`<p><code>${type}</code></p>`);
}
if (value) {
output.push(`<p><code>${value}</code></p>`);
}
return output.join("\n");
}
if (apiType === "function") {
findByText($, $main, "em.property", "function").remove();
return `<span class="target" id="${id}"/><p><code>${$child.html()}</code></p>`;
}
if (apiType === "exception") {
findByText($, $main, "em.property", "exception").remove();
return `<span class="target" id="${id}"/><p><code>${$child.html()}</code></p>`;
}
throw new Error(`Unhandled Python type: ${apiType}`);
})
.join("\n");
$dl.replaceWith(`<div>${replacement}</div>`);
}
}
export function maybeSetModuleMetadata(
$: CheerioAPI,
$main: Cheerio<any>,
meta: Metadata,
): void {
const modulePrefix = "module-";
const moduleIdWithPrefix = $main
.find("span, section")
.toArray()
.map((el) => $(el).attr("id"))
.find((id) => id?.startsWith(modulePrefix));
if (moduleIdWithPrefix) {
meta.apiType = "module";
meta.apiName = moduleIdWithPrefix.slice(modulePrefix.length);
}
}
export function preserveMathBlockWhitespace(
$: CheerioAPI,
$main: Cheerio<any>,
): void {
$main
.find("div.math")
.toArray()
.map((el) => {
const $el = $(el);
$el.replaceWith(`<pre class="math">${$el.html()}</pre>`);
});
}
export function updateModuleHeadings(
$: CheerioAPI,
$main: Cheerio<any>,
meta: Metadata,
): void {
$main
.find("h1,h2")
.toArray()
.forEach((el) => {
const $el = $(el);
const $a = $($el.find("a"));
const signature = $a.text();
$a.remove();
let title = $el.text();
title = title.replace("()", "");
let replacement = `<${el.tagName}>${title}</${el.tagName}>`;
if (signature.trim().length > 0) {
replacement += `<span class="target" id="module-${meta.apiName}" /><p><code>${signature}</code></p>`;
}
$el.replaceWith(replacement);
});
}
/**
* Find the element that both matches the `selector` and whose content is the same as `text`
*/
function findByText(
$: CheerioAPI,
$main: Cheerio<any>,
selector: string,
text: string,
): Cheerio<any> {
return $main.find(selector).filter((i, el) => $(el).text().trim() === text);
}
function getApiType($dl: Cheerio<any>): ApiType | undefined {
for (const className of [
"function",
"class",
"exception",
"method",
"property",
"attribute",
"module",
]) {
if ($dl.hasClass(className)) {
return className as ApiType;
}
}
return undefined;
}