client: Add syntax highlight for code note previews

This commit is contained in:
Elian Doran 2024-11-07 23:53:02 +02:00
parent 1816fcd3ac
commit 91fa1a6cb1
No known key found for this signature in database
2 changed files with 38 additions and 17 deletions

View File

@ -10,7 +10,8 @@ import treeService from "./tree.js";
import FNote from "../entities/fnote.js";
import FAttachment from "../entities/fattachment.js";
import imageContextMenuService from "../menus/image_context_menu.js";
import { applySyntaxHighlight } from "./syntax_highlight.js";
import { applySingleBlockSyntaxHighlight, applySyntaxHighlight } from "./syntax_highlight.js";
import mime_types from "./mime_types.js";
let idCounter = 1;
@ -113,11 +114,18 @@ async function renderText(note, $renderedContent) {
}
}
/** @param {FNote} note */
/**
* Renders a code note, by displaying its content and applying syntax highlighting based on the selected MIME type.
*
* @param {FNote} note
*/
async function renderCode(note, $renderedContent) {
const blob = await note.getBlob();
$renderedContent.append($("<pre>").text(blob.content));
const $codeBlock = $("<pre>");
$codeBlock.text(blob.content);
applySingleBlockSyntaxHighlight($codeBlock, mime_types.normalizeMimeTypeForCKEditor(note.mime));
$renderedContent.append($codeBlock);
}
function renderImage(entity, $renderedContent, options = {}) {

View File

@ -29,27 +29,40 @@ export async function applySyntaxHighlight($container) {
const codeBlocks = $container.find("pre code");
for (const codeBlock of codeBlocks) {
$(codeBlock).parent().toggleClass("hljs");
const text = codeBlock.innerText;
const normalizedMimeType = extractLanguageFromClassList(codeBlock);
if (!normalizedMimeType) {
continue;
}
let highlightedText = null;
if (normalizedMimeType === mime_types.MIME_TYPE_AUTO) {
highlightedText = hljs.highlightAuto(text);
} else if (normalizedMimeType) {
const language = mime_types.getHighlightJsNameForMime(normalizedMimeType);
highlightedText = hljs.highlight(text, { language });
}
if (highlightedText) {
codeBlock.innerHTML = highlightedText.value;
applySingleBlockSyntaxHighlight($(codeBlock, normalizedMimeType));
}
}
/**
* Applies syntax highlight to the given code block (assumed to be <pre><code>), using highlight.js.
*
* @param {*} $codeBlock
* @param {*} normalizedMimeType
*/
export async function applySingleBlockSyntaxHighlight($codeBlock, normalizedMimeType) {
$codeBlock.parent().toggleClass("hljs");
const text = $codeBlock.text();
let highlightedText = null;
if (normalizedMimeType === mime_types.MIME_TYPE_AUTO) {
highlightedText = hljs.highlightAuto(text);
} else if (normalizedMimeType) {
const language = mime_types.getHighlightJsNameForMime(normalizedMimeType);
if (language) {
highlightedText = hljs.highlight(text, { language });
} else {
console.warn(`Unknown mime type: ${normalizedMimeType}.`);
}
}
if (highlightedText) {
$codeBlock.html(highlightedText.value);
}
}
/**