Skip to content

Commit

Permalink
Use first word only from info string to match language in code block …
Browse files Browse the repository at this point in the history
…highlighting (#1354)
  • Loading branch information
emmatown authored Nov 20, 2024
1 parent b755793 commit 02a7441
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/mighty-apples-tan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystatic/core': patch
---

Improve syntax highlighting in the `fields.mdx`/`fields.markdoc` editor to only use the first word in the info string to match the language. This is primarily for `fields.mdx` to allow additional information in the info string beyond the editor. In `fields.markdoc` additional content after the first word will be stripped since Markdoc expresses additional information using Markdoc annotations which Keystatic already exposes UI for if `options.codeBlock.schema` is configured.
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,21 @@ function getDecorationsForIndividualNode(node: Node): InlineDecorationSpec[] {
if (!node.type.spec.code || !node.childCount) return emptyDecorations;
const text = node.content.child(0).text;
if (!text) return emptyDecorations;
const lang = node.attrs.language;
if (
typeof lang !== 'string' ||
!Object.prototype.hasOwnProperty.call(Prism.languages, node.attrs.language)
) {
let lang = node.attrs.language;
if (typeof lang !== 'string') return emptyDecorations;
lang = lang.trim();
const spaceIndex = lang.indexOf(' ');
if (spaceIndex !== -1) {
lang = lang.slice(0, spaceIndex);
}
lang = lang.toLowerCase();
if (!Object.prototype.hasOwnProperty.call(Prism.languages, lang)) {
return emptyDecorations;
}
const prismLang = Prism.languages[lang];
if (typeof prismLang !== 'object') return emptyDecorations;
const decorations: InlineDecorationSpec[] = [];
const tokens = Prism.tokenize(text, Prism.languages[node.attrs.language]);
const tokens = Prism.tokenize(text, prismLang);
function consumeTokens(start: number, tokens: (string | Prism.Token)[]) {
for (const token of tokens) {
const length = getPrismTokenLength(token);
Expand Down

0 comments on commit 02a7441

Please sign in to comment.