Files
website/node_modules/@astrojs/starlight/integrations/code-rtl-support.ts
2024-05-06 17:15:30 -04:00

32 lines
1013 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { Root } from 'hast';
import { CONTINUE, SKIP, visit } from 'unist-util-visit';
/**
* rehype plugin that adds `dir` attributes to `<code>` and `<pre>`
* elements that dont already have them.
*
* `<code>` will become `<code dir="auto">`
* `<pre>` will become `<pre dir="ltr">`
*
* `<code>` _inside_ `<pre>` is skipped, so respects the `ltr` on its parent.
*
* Reasoning:
* - `<pre>` is usually a code block and code should be LTR even in an RTL document
* - `<code>` is often LTR, but could also be RTL. `dir="auto"` ensures the bidirectional
* algorithm treats the contents of `<code>` in isolation and gives its best guess.
*/
export function rehypeRtlCodeSupport() {
return () => (root: Root) => {
visit(root, 'element', (el) => {
if (el.tagName === 'pre' || el.tagName === 'code') {
el.properties ||= {};
if (!('dir' in el.properties)) {
el.properties.dir = { pre: 'ltr', code: 'auto' }[el.tagName];
}
return SKIP;
}
return CONTINUE;
});
};
}