rehype-han 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +43 -0
  3. package/index.js +322 -0
  4. package/package.json +43 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # rehype-han
2
+
3
+ Rehype plugin that wraps punctuation marks in an element with the class `cjk-punc`.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install rehype-han
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```js
14
+ import { unified } from 'unified';
15
+ import rehypeParse from 'rehype-parse';
16
+ import rehypeStringify from 'rehype-stringify';
17
+ import rehypeHan from 'rehype-han';
18
+
19
+ const file = await unified()
20
+ .use(rehypeParse, { fragment: true })
21
+ .use(rehypeHan)
22
+ .use(rehypeStringify)
23
+ .process("<p>Mom's note——“中文”</p>");
24
+
25
+ console.log(String(file));
26
+ // => <p>Mom's note——</span><span class="cjk-punc">“</span>中文<span class="cjk-punc">”</span></p>
27
+ ```
28
+
29
+ ## Options
30
+
31
+ - `className` (string, default: `cjk-punc`): base class applied to punctuation wrappers.
32
+ - `tagName` (string, default: `span`): element used for punctuation wrappers.
33
+ - `ignoreTags` (string[], default: `['script', 'style', 'noscript', 'code', 'pre', 'kbd', 'samp']`): tags whose descendants are left unchanged.
34
+
35
+ ## Behavior
36
+
37
+ - Wrapping targets punctuation from Unicode `\p{P}` (including ASCII and full-width/CJK variants).
38
+ - Exactly two consecutive em dashes (`——`) are wrapped as one token.
39
+ - Exactly two consecutive CJK ellipsis characters (`……`) are wrapped as one token.
40
+ - Single `-`, `–`, and `—` are intentionally excluded and never wrapped.
41
+ - Percent-like signs `%`, `%`, `﹪`, `‰`, and `‱` are excluded from wrapping.
42
+ - Latin-word apostrophes are excluded for `Latin + (' or ’) + Latin` and trailing possessives `Latin + (' or ’) + (space, punctuation, or end)` (for example `Mom’s`, `I’d`, `we’re`, `students' work`).
43
+ - Punctuation already inside an existing configured wrapper is not wrapped again.
package/index.js ADDED
@@ -0,0 +1,322 @@
1
+ import { visitParents } from 'unist-util-visit-parents';
2
+
3
+ const DEFAULT_IGNORE_TAGS = [
4
+ 'script',
5
+ 'style',
6
+ 'noscript',
7
+ 'code',
8
+ 'pre',
9
+ 'kbd',
10
+ 'samp',
11
+ ];
12
+
13
+ const PUNCTUATION_REGEX = /\p{P}/u;
14
+ const LATIN_LETTER_REGEX = /\p{Script=Latin}/u;
15
+ const WHITESPACE_REGEX = /\s/u;
16
+ const EXCLUDED_PUNCTUATION = new Set([
17
+ '-',
18
+ '–',
19
+ '—',
20
+ '%',
21
+ '%',
22
+ '﹪',
23
+ '‰',
24
+ '‱',
25
+ ]);
26
+ const ENGLISH_IN_WORD_APOSTROPHES = new Set(["'", '’']);
27
+ const EM_DASH = '—';
28
+ const DOUBLE_EM_DASH = '——';
29
+ const ELLIPSIS = '…';
30
+ const DOUBLE_ELLIPSIS = '……';
31
+ const LEFT_COMPRESSION_MARKS = new Set(['“', '‘', '《', '「', '『', '(']);
32
+ const RIGHT_COMPRESSION_MARKS = new Set(['”', '’', '》', '」', '』', ')']);
33
+ const ADJACENCY_TARGET_MARKS = new Set([
34
+ ',',
35
+ '。',
36
+ '?',
37
+ '!',
38
+ ';',
39
+ ':',
40
+ '、',
41
+ ]);
42
+ const ADJ_LEFT_CLASS = 'adj-l';
43
+ const ADJ_RIGHT_CLASS = 'adj-r';
44
+ const ADJ_MIDDLE_CLASS = 'adj-m';
45
+
46
+ function isWrappablePunctuation(ch) {
47
+ return PUNCTUATION_REGEX.test(ch) && !EXCLUDED_PUNCTUATION.has(ch);
48
+ }
49
+
50
+ function isLatinLetter(ch) {
51
+ return Boolean(ch) && LATIN_LETTER_REGEX.test(ch);
52
+ }
53
+
54
+ function isEnglishWordApostrophe(chars, index) {
55
+ const ch = chars[index];
56
+ const previousChar = chars[index - 1];
57
+ const nextChar = chars[index + 1];
58
+
59
+ if (!ENGLISH_IN_WORD_APOSTROPHES.has(ch)) {
60
+ return false;
61
+ }
62
+
63
+ if (!isLatinLetter(previousChar)) {
64
+ return false;
65
+ }
66
+
67
+ if (isLatinLetter(nextChar)) {
68
+ return true;
69
+ }
70
+
71
+ return (
72
+ !nextChar ||
73
+ WHITESPACE_REGEX.test(nextChar) ||
74
+ PUNCTUATION_REGEX.test(nextChar)
75
+ );
76
+ }
77
+
78
+ function splitPunctuationChunks(value) {
79
+ const chars = Array.from(value);
80
+ const parts = [];
81
+ let textBuffer = '';
82
+
83
+ for (let index = 0; index < chars.length; index += 1) {
84
+ const ch = chars[index];
85
+
86
+ if (ch === EM_DASH && chars[index + 1] === EM_DASH) {
87
+ if (textBuffer) {
88
+ parts.push({ type: 'text', value: textBuffer });
89
+ textBuffer = '';
90
+ }
91
+
92
+ parts.push({ type: 'punctuation', value: DOUBLE_EM_DASH });
93
+ index += 1;
94
+ continue;
95
+ }
96
+
97
+ if (ch === ELLIPSIS && chars[index + 1] === ELLIPSIS) {
98
+ if (textBuffer) {
99
+ parts.push({ type: 'text', value: textBuffer });
100
+ textBuffer = '';
101
+ }
102
+
103
+ parts.push({ type: 'punctuation', value: DOUBLE_ELLIPSIS });
104
+ index += 1;
105
+ continue;
106
+ }
107
+
108
+ if (isWrappablePunctuation(ch) && !isEnglishWordApostrophe(chars, index)) {
109
+ if (textBuffer) {
110
+ parts.push({ type: 'text', value: textBuffer });
111
+ textBuffer = '';
112
+ }
113
+
114
+ parts.push({ type: 'punctuation', value: ch });
115
+ continue;
116
+ }
117
+
118
+ textBuffer += ch;
119
+ }
120
+
121
+ if (textBuffer) {
122
+ parts.push({ type: 'text', value: textBuffer });
123
+ }
124
+
125
+ return parts;
126
+ }
127
+
128
+ function getAdjacencyClasses(parts) {
129
+ const adjacencyClasses = new Map();
130
+
131
+ function addAdjacencyClass(index, className) {
132
+ const classes = adjacencyClasses.get(index);
133
+
134
+ if (classes) {
135
+ classes.add(className);
136
+ return;
137
+ }
138
+
139
+ adjacencyClasses.set(index, new Set([className]));
140
+ }
141
+
142
+ function isQuoteBracketWrapper(value) {
143
+ return (
144
+ LEFT_COMPRESSION_MARKS.has(value) || RIGHT_COMPRESSION_MARKS.has(value)
145
+ );
146
+ }
147
+
148
+ for (let index = 0; index < parts.length; index += 1) {
149
+ const part = parts[index];
150
+
151
+ if (part.type !== 'punctuation') {
152
+ continue;
153
+ }
154
+
155
+ if (LEFT_COMPRESSION_MARKS.has(part.value)) {
156
+ const leftNeighbor = parts[index - 1];
157
+
158
+ if (
159
+ leftNeighbor &&
160
+ leftNeighbor.type === 'punctuation' &&
161
+ ADJACENCY_TARGET_MARKS.has(leftNeighbor.value)
162
+ ) {
163
+ addAdjacencyClass(index - 1, ADJ_LEFT_CLASS);
164
+ }
165
+ }
166
+
167
+ if (RIGHT_COMPRESSION_MARKS.has(part.value)) {
168
+ const rightNeighbor = parts[index + 1];
169
+ let leftNeighborIndex = index - 1;
170
+
171
+ while (leftNeighborIndex >= 0) {
172
+ const leftNeighbor = parts[leftNeighborIndex];
173
+
174
+ if (leftNeighbor.type !== 'punctuation') {
175
+ break;
176
+ }
177
+
178
+ if (isQuoteBracketWrapper(leftNeighbor.value)) {
179
+ leftNeighborIndex -= 1;
180
+ continue;
181
+ }
182
+
183
+ if (ADJACENCY_TARGET_MARKS.has(leftNeighbor.value)) {
184
+ addAdjacencyClass(leftNeighborIndex, ADJ_LEFT_CLASS);
185
+ }
186
+
187
+ break;
188
+ }
189
+
190
+ if (
191
+ rightNeighbor &&
192
+ rightNeighbor.type === 'punctuation' &&
193
+ ADJACENCY_TARGET_MARKS.has(rightNeighbor.value)
194
+ ) {
195
+ addAdjacencyClass(index + 1, ADJ_RIGHT_CLASS);
196
+ }
197
+ }
198
+ }
199
+
200
+ for (const [index, classes] of adjacencyClasses) {
201
+ if (classes.has(ADJ_LEFT_CLASS) && classes.has(ADJ_RIGHT_CLASS)) {
202
+ adjacencyClasses.set(index, new Set([ADJ_MIDDLE_CLASS]));
203
+ }
204
+ }
205
+
206
+ return adjacencyClasses;
207
+ }
208
+
209
+ function toClassList(className) {
210
+ return className
211
+ .split(/\s+/)
212
+ .map((entry) => entry.trim())
213
+ .filter(Boolean);
214
+ }
215
+
216
+ function hasClassName(properties, className) {
217
+ if (!properties || !properties.className) {
218
+ return false;
219
+ }
220
+
221
+ const expectedClassNames = toClassList(className);
222
+ const classList = Array.isArray(properties.className)
223
+ ? properties.className
224
+ : String(properties.className).split(/\s+/);
225
+
226
+ return expectedClassNames.every((entry) => classList.includes(entry));
227
+ }
228
+
229
+ function hasIgnoredAncestor(ancestors, ignoreTags) {
230
+ return ancestors.some(
231
+ (node) => node.type === 'element' && ignoreTags.has(node.tagName)
232
+ );
233
+ }
234
+
235
+ function hasWrapperAncestor(ancestors, tagName, className) {
236
+ return ancestors.some(
237
+ (node) =>
238
+ node.type === 'element' &&
239
+ node.tagName === tagName &&
240
+ hasClassName(node.properties, className)
241
+ );
242
+ }
243
+
244
+ export default function rehypeLangEn(options = {}) {
245
+ const className =
246
+ typeof options.className === 'string' && options.className.trim()
247
+ ? options.className.trim()
248
+ : 'cjk-punc';
249
+
250
+ const tagName =
251
+ typeof options.tagName === 'string' && options.tagName.trim()
252
+ ? options.tagName.trim()
253
+ : 'span';
254
+
255
+ const ignoreTags = new Set(
256
+ Array.isArray(options.ignoreTags) && options.ignoreTags.length > 0
257
+ ? options.ignoreTags.map((tag) => String(tag))
258
+ : DEFAULT_IGNORE_TAGS
259
+ );
260
+
261
+ const classList = toClassList(className);
262
+
263
+ return (tree) => {
264
+ visitParents(tree, 'text', (node, ancestors) => {
265
+ const parent = ancestors[ancestors.length - 1];
266
+
267
+ if (!parent || parent.type !== 'element') {
268
+ return;
269
+ }
270
+
271
+ if (hasIgnoredAncestor(ancestors, ignoreTags)) {
272
+ return;
273
+ }
274
+
275
+ if (hasWrapperAncestor(ancestors, tagName, className)) {
276
+ return;
277
+ }
278
+
279
+ if (!node.value || typeof node.value !== 'string') {
280
+ return;
281
+ }
282
+
283
+ const parts = splitPunctuationChunks(node.value);
284
+ const adjacencyClasses = getAdjacencyClasses(parts);
285
+
286
+ if (parts.length === 1 && parts[0].type === 'text') {
287
+ return;
288
+ }
289
+
290
+ const replacement = parts.map((part, partIndex) => {
291
+ if (part.type === 'text') {
292
+ return { type: 'text', value: part.value };
293
+ }
294
+
295
+ const markClassList = classList.slice();
296
+ const extraClasses = adjacencyClasses.get(partIndex);
297
+
298
+ if (extraClasses) {
299
+ for (const entry of extraClasses) {
300
+ if (!markClassList.includes(entry)) {
301
+ markClassList.push(entry);
302
+ }
303
+ }
304
+ }
305
+
306
+ return {
307
+ type: 'element',
308
+ tagName,
309
+ properties: { className: markClassList },
310
+ children: [{ type: 'text', value: part.value }],
311
+ };
312
+ });
313
+
314
+ const nodeIndex = parent.children.indexOf(node);
315
+ if (nodeIndex === -1) {
316
+ return;
317
+ }
318
+
319
+ parent.children.splice(nodeIndex, 1, ...replacement);
320
+ });
321
+ };
322
+ }
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "rehype-han",
3
+ "version": "0.1.0",
4
+ "description": "Rehype plugin to wrap text segments with proper tags.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "exports": "./index.js",
8
+ "files": [
9
+ "index.js",
10
+ "README.md"
11
+ ],
12
+ "keywords": [
13
+ "rehype",
14
+ "rehype-plugin",
15
+ "unist",
16
+ "hast",
17
+ "latin",
18
+ "cjk"
19
+ ],
20
+ "license": "MIT",
21
+ "author": "ivorkchan",
22
+ "engines": {
23
+ "node": ">=16"
24
+ },
25
+ "scripts": {
26
+ "test": "node --test",
27
+ "lint": "eslint .",
28
+ "lint:fix": "eslint . --fix",
29
+ "format": "prettier . --write --ignore-unknown",
30
+ "format:check": "prettier . --check --ignore-unknown"
31
+ },
32
+ "dependencies": {
33
+ "unist-util-visit-parents": "^6.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "@eslint/js": "^10.0.1",
37
+ "eslint": "^10.0.0",
38
+ "prettier": "^3.8.1",
39
+ "rehype-parse": "^9.0.0",
40
+ "rehype-stringify": "^9.0.0",
41
+ "unified": "^11.0.0"
42
+ }
43
+ }