Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use first word only from info string to match language in code block highlighting #1354

Merged
merged 2 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading