forked from rehype-pretty/rehype-pretty-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
168 lines (144 loc) · 4.92 KB
/
Copy pathutils.ts
File metadata and controls
168 lines (144 loc) · 4.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import type { Theme } from './types';
import type { Element, ElementContent, Root, RootContent, Text } from 'hast';
import type { ThemeRegistrationRaw } from 'shiki';
import rangeParser from 'parse-numeric-range';
export function isJSONTheme(value: any): value is ThemeRegistrationRaw {
return value ? Object.hasOwn(value, 'tokenColors') : false;
}
export function isElement(
value: ElementContent | Element | Root | RootContent | null | undefined,
): value is Element {
return value ? value.type === 'element' : false;
}
export function isText(value: ElementContent | null): value is Text {
return value ? value.type === 'text' : false;
}
export function isInlineCode(
element: Element,
parent: Element | Root | undefined,
bypass = false,
): element is Element {
if (bypass) {
return false;
}
return (
(element.tagName === 'code' &&
isElement(parent) &&
parent.tagName !== 'pre') ||
element.tagName === 'inlineCode'
);
}
export function isBlockCode(element: Element): element is Element {
return (
element.tagName === 'pre' &&
Array.isArray(element.children) &&
element.children.length === 1 &&
isElement(element.children[0]) &&
element.children[0].tagName === 'code'
);
}
export function getInlineCodeLang(meta: string, defaultFallbackLang: string) {
const placeholder = '\u0000';
let temp = meta.replace(/\\\\/g, placeholder);
temp = temp.replace(/\\({:[a-zA-Z.-]+})$/, '$1');
const lang = temp.match(/{:([a-zA-Z.-]+)}$/)?.[1];
return (
lang?.replace(new RegExp(placeholder, 'g'), '\\') || defaultFallbackLang
);
}
export function parseBlockMetaString(
element: Element,
filter: (s: string) => string,
defaultFallback: string,
) {
let meta = filter(
(element.data?.meta ?? element.properties?.metastring ?? '') as string,
);
const titleMatch = meta.match(/title="([^"]*)"/);
const title = titleMatch?.[1] ?? null;
meta = meta.replace(titleMatch?.[0] ?? '', '');
const captionMatch = meta.match(/caption="([^"]*)"/);
const caption = captionMatch?.[1] ?? null;
meta = meta.replace(captionMatch?.[0] ?? '', '');
let lang = defaultFallback;
if (
element.properties &&
Array.isArray(element.properties.className) &&
typeof element.properties.className[0] === 'string' &&
element.properties.className[0].startsWith('language-')
) {
lang = element.properties.className[0].replace('language-', '');
}
return {
title,
caption,
lang,
meta,
};
}
export function getThemeNames(theme: Theme | Record<string, Theme>) {
if (isJSONTheme(theme)) {
return [theme.name];
}
if (typeof theme === 'string') {
return [theme];
}
return Object.values(theme).map((theme) =>
typeof theme === 'string' ? theme : theme.name,
);
}
export function replaceLineClass(element: Element) {
if (
Array.isArray(element.properties?.className) &&
element.properties.className.includes('line')
) {
const className = element.properties.className.filter((c) => c !== 'line');
element.properties.className = className.length > 0 ? className : undefined;
element.properties['data-line'] = '';
}
}
// `showLineNumbers`, optionally `showLineNumbers{N}`, bounded by
// whitespace or the ends of the meta string. Only lookahead is used, so
// this stays parseable on Safari < 16.4, which lacks lookbehind.
const showLineNumbersRegex = /(?:^|\s)(showLineNumbers(?:\{(\d+)\})?)(?=\s|$)/g;
/**
* Finds the `showLineNumbers` option in a block meta string.
*
* Whitespace boundaries alone do not prove the token is an option: it can
* also be part of a delimited character-highlight annotation, as in
* `/foo showLineNumbers bar/`, where it is highlight text. `takenSpans`
* holds the `[start, end)` offsets already claimed by those annotations,
* and any match overlapping one of them is skipped.
*
* Returns `null` when the option is absent, otherwise `startAt` — the
* line number given by `showLineNumbers{N}`, or `null` for a bare token.
*/
export function getShowLineNumbers(
meta: string,
takenSpans: Array<[number, number]>,
) {
for (const match of meta.matchAll(showLineNumbersRegex)) {
const token = match[1];
if (!token) continue;
// `match[0]` may carry a leading whitespace boundary character.
const start = (match.index ?? 0) + (match[0].length - token.length);
const end = start + token.length;
if (takenSpans.some(([from, to]) => start < to && end > from)) continue;
return { startAt: match[2] ? Number(match[2]) : null };
}
return null;
}
export function getLineId(lineNumber: number, meta: string) {
const segments = meta.match(/\{[^}]+\}#[a-zA-Z0-9]+/g);
if (!segments) return null;
for (const segment of segments) {
const [range, id] = segment.split('#');
if (!(range && id)) continue;
const match = range.match(/\{(.*?)\}/);
const capture = match?.[1];
if (capture && rangeParser(capture).includes(lineNumber)) {
return id;
}
}
return null;
}