-
Notifications
You must be signed in to change notification settings - Fork 515
/
extract-summary.ts
58 lines (55 loc) · 1.88 KB
/
extract-summary.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
import * as cheerio from "cheerio";
import { ProseSection, Section } from "../libs/types/document.js";
/**
* Given an array of sections, return a plain text
* string of a summary. No HTML or Kumascript allowed.
*/
export function extractSummary(sections: Section[]): string {
let summary = ""; // default and fallback is an empty string.
function extractFirstGoodParagraph($): string {
const seoSummary = $("span.seoSummary, .summary");
if (seoSummary.length && seoSummary.text()) {
return seoSummary.text();
}
let summary = "";
$("p").each((i, p) => {
// The `.each()` can only take a callback, so we need a solution
// to exit early once we've found the first working summary.
if (summary) return; // it already been found!
const text = $(p).text().trim();
// Avoid those whose paragraph is just a failing KS macro
if (text && !text.includes("Redirect") && !text.startsWith("{{")) {
summary = text;
}
});
return summary;
}
// If the sections contains a "Summary" one, use that, otherwise
// use the first prose one.
const summarySections = sections.filter(
(section: Section): section is ProseSection =>
section.type === "prose" && section.value.title === "Summary"
);
if (summarySections.length) {
const $ = cheerio.load(summarySections[0].value.content ?? "");
summary = extractFirstGoodParagraph($);
} else {
for (const section of sections) {
if (
section.type !== "prose" ||
!section.value ||
!section.value.content
) {
continue;
}
const $ = cheerio.load(section.value.content);
// Remove non-p tags that we should not be looking inside.
$("div.notecard, div.note, div.blockIndicator").remove();
summary = extractFirstGoodParagraph($);
if (summary) {
break;
}
}
}
return summary;
}