2025-05-12 05:38:44 +09:00

60 lines
2.2 KiB
JavaScript

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = __importDefault(require("is"));
const immutable_1 = __importDefault(require("immutable"));
const promise_1 = __importDefault(require("../../utils/promise"));
const editHTMLElement_1 = __importDefault(require("./editHTMLElement"));
/**
Return language for a code blocks from a list of class names
@param {Array<String>}
@return {string}
*/
function getLanguageForClass(classNames) {
return immutable_1.default.List(classNames)
.map((cl) => {
// Markdown
// @ts-expect-error ts-migrate(2339) FIXME: Property 'search' does not exist on type 'unknown'... Remove this comment to see the full error message
if (cl.search("lang-") === 0) {
// @ts-expect-error ts-migrate(2339) FIXME: Property 'slice' does not exist on type 'unknown'.
return cl.slice("lang-".length);
}
// Asciidoc
// @ts-expect-error ts-migrate(2339) FIXME: Property 'search' does not exist on type 'unknown'... Remove this comment to see the full error message
if (cl.search("language-") === 0) {
// @ts-expect-error ts-migrate(2339) FIXME: Property 'slice' does not exist on type 'unknown'.
return cl.slice("language-".length);
}
return null;
})
.find((cl) => {
return Boolean(cl);
});
}
/**
Highlight all code elements
@param {Function(lang, body) -> String} highlight
@param {HTMLDom} $
@return {Promise}
*/
function highlightCode(highlight, $) {
return (0, editHTMLElement_1.default)($, "code", ($code) => {
const classNames = ($code.attr("class") || "").split(" ");
const lang = getLanguageForClass(classNames);
const source = $code.text();
return (0, promise_1.default)(highlight(lang, source)).then((r) => {
if (is_1.default.string(r.html)) {
$code.html(r.html);
}
else {
$code.text(r.text);
}
});
});
}
exports.default = highlightCode;