wikiparser-node 0.7.0 → 0.7.1-b

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 (87) hide show
  1. package/bundle/bundle.min.js +40 -0
  2. package/extensions/editor.css +60 -0
  3. package/extensions/editor.js +324 -0
  4. package/extensions/ui.css +119 -0
  5. package/package.json +12 -11
  6. package/README.md +0 -39
  7. package/config/default.json +0 -832
  8. package/config/llwiki.json +0 -630
  9. package/config/moegirl.json +0 -728
  10. package/config/zhwiki.json +0 -1269
  11. package/index.js +0 -321
  12. package/lib/element.js +0 -611
  13. package/lib/node.js +0 -772
  14. package/lib/ranges.js +0 -130
  15. package/lib/text.js +0 -215
  16. package/lib/title.js +0 -80
  17. package/mixin/attributeParent.js +0 -117
  18. package/mixin/fixedToken.js +0 -40
  19. package/mixin/hidden.js +0 -21
  20. package/mixin/singleLine.js +0 -31
  21. package/mixin/sol.js +0 -65
  22. package/parser/brackets.js +0 -120
  23. package/parser/commentAndExt.js +0 -62
  24. package/parser/converter.js +0 -46
  25. package/parser/externalLinks.js +0 -33
  26. package/parser/hrAndDoubleUnderscore.js +0 -38
  27. package/parser/html.js +0 -42
  28. package/parser/links.js +0 -94
  29. package/parser/list.js +0 -59
  30. package/parser/magicLinks.js +0 -41
  31. package/parser/quotes.js +0 -64
  32. package/parser/selector.js +0 -177
  33. package/parser/table.js +0 -114
  34. package/src/arg.js +0 -203
  35. package/src/atom/hidden.js +0 -13
  36. package/src/atom/index.js +0 -43
  37. package/src/attribute.js +0 -420
  38. package/src/attributes.js +0 -452
  39. package/src/charinsert.js +0 -97
  40. package/src/converter.js +0 -176
  41. package/src/converterFlags.js +0 -284
  42. package/src/converterRule.js +0 -258
  43. package/src/extLink.js +0 -179
  44. package/src/gallery.js +0 -151
  45. package/src/hasNowiki/index.js +0 -44
  46. package/src/hasNowiki/pre.js +0 -40
  47. package/src/heading.js +0 -134
  48. package/src/html.js +0 -248
  49. package/src/imageParameter.js +0 -277
  50. package/src/imagemap.js +0 -199
  51. package/src/imagemapLink.js +0 -41
  52. package/src/index.js +0 -913
  53. package/src/link/category.js +0 -49
  54. package/src/link/file.js +0 -282
  55. package/src/link/galleryImage.js +0 -120
  56. package/src/link/index.js +0 -383
  57. package/src/magicLink.js +0 -149
  58. package/src/nested/choose.js +0 -24
  59. package/src/nested/combobox.js +0 -23
  60. package/src/nested/index.js +0 -96
  61. package/src/nested/references.js +0 -23
  62. package/src/nowiki/comment.js +0 -71
  63. package/src/nowiki/dd.js +0 -59
  64. package/src/nowiki/doubleUnderscore.js +0 -56
  65. package/src/nowiki/hr.js +0 -41
  66. package/src/nowiki/index.js +0 -56
  67. package/src/nowiki/list.js +0 -16
  68. package/src/nowiki/noinclude.js +0 -28
  69. package/src/nowiki/quote.js +0 -69
  70. package/src/onlyinclude.js +0 -64
  71. package/src/paramTag/index.js +0 -89
  72. package/src/paramTag/inputbox.js +0 -44
  73. package/src/parameter.js +0 -239
  74. package/src/syntax.js +0 -91
  75. package/src/table/index.js +0 -984
  76. package/src/table/td.js +0 -339
  77. package/src/table/tr.js +0 -319
  78. package/src/tagPair/ext.js +0 -138
  79. package/src/tagPair/include.js +0 -60
  80. package/src/tagPair/index.js +0 -126
  81. package/src/transclude.js +0 -824
  82. package/tool/index.js +0 -1202
  83. package/util/base.js +0 -17
  84. package/util/debug.js +0 -73
  85. package/util/diff.js +0 -76
  86. package/util/lint.js +0 -54
  87. package/util/string.js +0 -107
@@ -1,984 +0,0 @@
1
- 'use strict';
2
-
3
- const {generateForChild} = require('../../util/lint'),
4
- {noWrap} = require('../../util/string'),
5
- {isPlainObject} = require('../../util/base'),
6
- assert = require('assert/strict'),
7
- Parser = require('../..'),
8
- Token = require('..'),
9
- TrToken = require('./tr'),
10
- TdToken = require('./td'),
11
- SyntaxToken = require('../syntax');
12
-
13
- const openingPattern = /^(?:\{\||\{\{\{\s*!\s*\}\}|\{\{\s*\(!\s*\}\})$/u,
14
- closingPattern = /^\n[^\S\n]*(?:\|\}|\{\{\s*!\s*\}\}\}|\{\{\s*!\)\s*\}\})$/u;
15
-
16
- /**
17
- * 比较两个表格坐标
18
- * @param {TableCoords} coords1 坐标1
19
- * @param {TableCoords} coords2 坐标2
20
- */
21
- const cmpCoords = (coords1, coords2) => {
22
- const diff = coords1.row - coords2.row;
23
- return diff === 0 ? coords1.column - coords2.column : diff;
24
- };
25
-
26
- /**
27
- * 是否是行尾
28
- * @param {Token} cell 表格单元格
29
- */
30
- const isRowEnd = ({type}) => type === 'tr' || type === 'table-syntax';
31
-
32
- /**
33
- * 是否是合并单元格的第一列
34
- * @param {TableCoords[]} rowLayout 行布局
35
- * @param {number} i 单元格序号
36
- * @param {boolean} oneCol 是否仅有一列
37
- */
38
- const isStartCol = (rowLayout, i, oneCol = false) => {
39
- const coords = rowLayout[i];
40
- return rowLayout[i - 1] !== coords && (!oneCol || rowLayout[i + 1] !== coords);
41
- };
42
-
43
- /**
44
- * 设置表格格式
45
- * @param {Map<TdToken, boolean>} cells 单元格
46
- * @param {string|Record<string, string|boolean>} attr 属性
47
- * @param {boolean} multi 是否对所有单元格设置,或是仅对行首单元格设置
48
- * @complexity `n`
49
- */
50
- const format = (cells, attr = {}, multi = false) => {
51
- for (const [token, start] of cells) {
52
- if (multi || start) {
53
- if (typeof attr === 'string') {
54
- token.setSyntax(attr);
55
- } else {
56
- for (const [k, v] of Object.entries(attr)) {
57
- token.setAttr(k, v);
58
- }
59
- }
60
- }
61
- }
62
- };
63
-
64
- /**
65
- * 填补缺失单元格
66
- * @param {number} y 行号
67
- * @param {TrToken} rowToken 表格行
68
- * @param {TableCoords[][]} layout 表格布局
69
- * @param {number} maxCol 最大列数
70
- * @param {Token} token 待填充的单元格
71
- * @complexity `n`
72
- */
73
- const fill = (y, rowToken, layout, maxCol, token) => {
74
- const rowLayout = layout[y],
75
- {childNodes} = rowToken,
76
- lastIndex = childNodes.findLastIndex(child => child instanceof TdToken && child.subtype !== 'caption') + 1
77
- || undefined;
78
- Parser.run(() => {
79
- for (let i = 0; i < maxCol; i++) {
80
- if (!rowLayout[i]) {
81
- rowToken.insertAt(token.cloneNode(), lastIndex);
82
- }
83
- }
84
- });
85
- };
86
-
87
- /** @extends {Array<TableCoords[]>} */
88
- class Layout extends Array {
89
- /**
90
- * 打印表格布局
91
- * @complexity `n`
92
- */
93
- print() {
94
- const hBorders = new Array(this.length + 1).fill().map((_, i) => {
95
- const prev = this[i - 1] ?? [],
96
- next = this[i] ?? [];
97
- return new Array(Math.max(prev.length, next.length)).fill().map((__, j) => prev[j] !== next[j]);
98
- }),
99
- vBorders = this.map(cur => new Array(cur.length + 1).fill().map((_, j) => cur[j - 1] !== cur[j]));
100
- let out = '';
101
- for (let i = 0; i <= this.length; i++) {
102
- const hBorder = hBorders[i],
103
- vBorderTop = vBorders[i - 1] ?? [],
104
- vBorderBottom = vBorders[i] ?? [],
105
- // eslint-disable-next-line no-sparse-arrays
106
- border = [' ',,, '┌',, '┐', '─', '┬',, '│', '└', '├', '┘', '┤', '┴', '┼'];
107
- for (let j = 0; j <= hBorder.length; j++) {
108
- // eslint-disable-next-line no-bitwise
109
- const bit = (vBorderTop[j] << 3) + (vBorderBottom[j] << 0) + (hBorder[j - 1] << 2) + (hBorder[j] << 1);
110
- out += `${border[bit]}${hBorder[j] ? '─' : ' '}`;
111
- }
112
- out += '\n';
113
- }
114
- console.log(out.slice(0, -1));
115
- }
116
- }
117
-
118
- /**
119
- * 表格
120
- * @classdesc `{childNodes: [SyntaxToken, AttributesToken, ?Token, ...TdToken, ...TrToken, ?SyntaxToken]}`
121
- */
122
- class TableToken extends TrToken {
123
- type = 'table';
124
-
125
- /** 表格是否闭合 */
126
- get closed() {
127
- return this.lastChild.type === 'table-syntax';
128
- }
129
-
130
- set closed(closed) {
131
- if (closed === true && !this.closed) {
132
- this.close(this.closest('parameter') ? '\n{{!)}}' : '\n|}');
133
- }
134
- }
135
-
136
- /**
137
- * @param {string} syntax 表格语法
138
- * @param {string} attr 表格属性
139
- * @param {accum} accum
140
- */
141
- constructor(syntax, attr = '', config = Parser.getConfig(), accum = []) {
142
- super(syntax, attr, config, accum, openingPattern);
143
- this.setAttribute('acceptable', {
144
- Token: 2, SyntaxToken: [0, -1], AttributesToken: 1, TdToken: '2:', TrToken: '2:',
145
- });
146
- }
147
-
148
- /**
149
- * @override
150
- * @template {TrToken|SyntaxToken} T
151
- * @param {T} token 待插入的子节点
152
- * @param {number} i 插入位置
153
- * @returns {T}
154
- * @complexity `n`
155
- * @throws `SyntaxError` 表格的闭合部分非法
156
- */
157
- insertAt(token, i = this.length) {
158
- const previous = this.childNodes.at(i - 1);
159
- if (token.type === 'td' && previous.type === 'tr') {
160
- Parser.warn('改为将单元格插入当前行。');
161
- return previous.insertAt(token);
162
- } else if (i > 0 && i === this.length && token instanceof SyntaxToken
163
- && (token.getAttribute('pattern') !== closingPattern || !closingPattern.test(token.text()))
164
- ) {
165
- throw new SyntaxError(`表格的闭合部分不符合语法!${noWrap(String(token))}`);
166
- }
167
- return super.insertAt(token, i);
168
- }
169
-
170
- /**
171
- * @override
172
- * @param {number} start 起始位置
173
- */
174
- lint(start = 0) {
175
- const errors = super.lint(start);
176
- if (!this.closed) {
177
- const {firstChild, lastChild: tr} = this,
178
- {lastChild: td} = tr,
179
- error = generateForChild(firstChild, {start}, '未闭合的表格');
180
- errors.push({...error, excerpt: String(td?.type === 'td' ? td : tr).slice(0, 50)});
181
- }
182
- return errors;
183
- }
184
-
185
- /**
186
- * 闭合表格语法
187
- * @complexity `n`
188
- * @param {string} syntax 表格结尾语法
189
- * @throws `SyntaxError` 表格的闭合部分不符合语法
190
- */
191
- close(syntax = '\n|}', halfParsed = false) {
192
- halfParsed &&= Parser.running;
193
- const config = this.getAttribute('config'),
194
- accum = this.getAttribute('accum'),
195
- inner = !halfParsed && Parser.parse(syntax, this.getAttribute('include'), 2, config),
196
- {lastChild} = this;
197
- if (!halfParsed && !closingPattern.test(inner.text())) {
198
- throw new SyntaxError(`表格的闭合部分不符合语法!${noWrap(syntax)}`);
199
- } else if (lastChild instanceof SyntaxToken) {
200
- lastChild.replaceChildren(...inner.childNodes);
201
- } else {
202
- super.insertAt(Parser.run(() => {
203
- const token = new SyntaxToken(syntax, closingPattern, 'table-syntax', config, accum, {
204
- 'Stage-1': ':', '!ExtToken': '', TranscludeToken: ':',
205
- });
206
- if (inner) {
207
- token.replaceChildren(...inner.childNodes);
208
- }
209
- return token;
210
- }));
211
- }
212
- }
213
-
214
- /**
215
- * @override
216
- * @returns {number}
217
- * @complexity `n`
218
- */
219
- getRowCount() {
220
- return super.getRowCount()
221
- + this.childNodes.filter(child => child.type === 'tr' && child.getRowCount()).length;
222
- }
223
-
224
- /** @override */
225
- getPreviousRow() { // eslint-disable-line class-methods-use-this
226
- return undefined;
227
- }
228
-
229
- /**
230
- * @override
231
- * @complexity `n`
232
- */
233
- getNextRow() {
234
- return this.getNthRow(super.getRowCount() ? 1 : 0);
235
- }
236
-
237
- /**
238
- * 获取第n行
239
- * @param {number} n 行号
240
- * @param {boolean} force 是否将表格自身视为第一行
241
- * @param {boolean} insert 是否用于判断插入新行的位置
242
- * @returns {TrToken}
243
- * @complexity `n`
244
- * @throws `RangeError` 不存在该行
245
- */
246
- getNthRow(n, force, insert) {
247
- if (!Number.isInteger(n)) {
248
- this.typeError('getNthRow', 'Number');
249
- }
250
- const nRows = this.getRowCount(),
251
- isRow = super.getRowCount();
252
- n = n < 0 ? n + nRows : n;
253
- if (n === 0 && (isRow || force && nRows === 0)) {
254
- return this;
255
- } else if (n < 0 || n > nRows || n === nRows && !insert) {
256
- throw new RangeError(`不存在第 ${n} 行!`);
257
- } else if (isRow) {
258
- n--;
259
- }
260
- for (const child of this.childNodes.slice(2)) {
261
- if (child.type === 'tr' && child.getRowCount()) {
262
- n--;
263
- if (n < 0) {
264
- return child;
265
- }
266
- } else if (child.type === 'table-syntax') {
267
- return child;
268
- }
269
- }
270
- return undefined;
271
- }
272
-
273
- /**
274
- * 获取所有行
275
- * @returns {TrToken[]}
276
- * @complexity `n`
277
- */
278
- getAllRows() {
279
- return [
280
- ...super.getRowCount() ? [this] : [],
281
- ...this.childNodes.filter(child => child.type === 'tr' && child.getRowCount()),
282
- ];
283
- }
284
-
285
- /**
286
- * 获取指定坐标的单元格
287
- * @param {TableCoords & TableRenderedCoords} coords 表格坐标
288
- * @complexity `n`
289
- */
290
- getNthCell(coords) {
291
- if (coords.row === undefined) {
292
- coords = this.toRawCoords(coords);
293
- }
294
- return coords && this.getNthRow(coords.row).getNthCol(coords.column);
295
- }
296
-
297
- /**
298
- * 获取表格布局
299
- * @param {TableCoords & TableRenderedCoords} stop 中止条件
300
- * @complexity `n`
301
- */
302
- getLayout(stop = {}) {
303
- const rows = this.getAllRows(),
304
- {length} = rows,
305
- /** @type {Layout} */ layout = new Layout(length).fill().map(() => []);
306
- for (let i = 0; i < length; i++) {
307
- if (i > (stop.row ?? stop.y)) {
308
- break;
309
- }
310
- const rowLayout = layout[i];
311
- let j = 0,
312
- k = 0,
313
- last;
314
- for (const cell of rows[i].childNodes.slice(2)) {
315
- if (cell instanceof TdToken) {
316
- if (cell.isIndependent()) {
317
- last = cell.subtype !== 'caption';
318
- }
319
- if (last) {
320
- const /** @type {TableCoords} */ coords = {row: i, column: j},
321
- {rowspan, colspan} = cell;
322
- j++;
323
- while (rowLayout[k]) {
324
- k++;
325
- }
326
- if (i === stop.row && j > stop.column) {
327
- layout[i][k] = coords;
328
- return layout;
329
- }
330
- for (let y = i; y < Math.min(i + rowspan, length); y++) {
331
- for (let x = k; x < k + colspan; x++) {
332
- layout[y][x] = coords;
333
- }
334
- }
335
- k += colspan;
336
- if (i === stop.y && k > stop.x) {
337
- return layout;
338
- }
339
- }
340
- } else if (isRowEnd(cell)) {
341
- break;
342
- }
343
- }
344
- }
345
- return layout;
346
- }
347
-
348
- /**
349
- * 打印表格布局
350
- * @complexity `n`
351
- */
352
- printLayout() {
353
- this.getLayout().print();
354
- }
355
-
356
- /**
357
- * 转换为渲染后的表格坐标
358
- * @param {TableCoords} coord wikitext中的表格坐标
359
- * @returns {TableRenderedCoords}
360
- * @complexity `n`
361
- */
362
- toRenderedCoords({row, column}) {
363
- if (!Number.isInteger(row) || !Number.isInteger(column)) {
364
- this.typeError('toRenderedCoords', 'Number');
365
- }
366
- const rowLayout = this.getLayout({row, column})[row],
367
- x = rowLayout?.findIndex(coords => cmpCoords(coords, {row, column}) === 0);
368
- return rowLayout && (x === -1 ? undefined : {y: row, x});
369
- }
370
-
371
- /**
372
- * 转换为wikitext中的表格坐标
373
- * @param {TableRenderedCoords} coord 渲染后的表格坐标
374
- * @complexity `n`
375
- */
376
- toRawCoords({x, y}) {
377
- if (!Number.isInteger(x) || !Number.isInteger(y)) {
378
- this.typeError('toRawCoords', 'Number');
379
- }
380
- const rowLayout = this.getLayout({x, y})[y],
381
- coords = rowLayout?.[x];
382
- if (coords) {
383
- return {...coords, start: coords.row === y && rowLayout[x - 1] !== coords};
384
- } else if (rowLayout || y > 0) {
385
- return x === rowLayout?.length
386
- ? {row: y, column: (rowLayout.findLast(({row}) => row === y)?.column ?? -1) + 1, start: true}
387
- : undefined;
388
- }
389
- return {row: 0, column: 0, start: true};
390
- }
391
-
392
- /**
393
- * 获取完整行
394
- * @param {number} y 行号
395
- * @complexity `n²`
396
- */
397
- getFullRow(y) {
398
- if (!Number.isInteger(y)) {
399
- this.typeError('getFullRow', 'Number');
400
- }
401
- const rows = this.getAllRows();
402
- return new Map(
403
- this.getLayout({y})[y]?.map(({row, column}) => [rows[row].getNthCol(column), row === y]),
404
- );
405
- }
406
-
407
- /**
408
- * 获取完整列
409
- * @param {number} x 列号
410
- * @complexity `n`
411
- */
412
- getFullCol(x) {
413
- if (!Number.isInteger(x)) {
414
- this.typeError('getFullCol', 'Number');
415
- }
416
- const layout = this.getLayout(),
417
- colLayout = layout.map(row => row[x]).filter(Boolean),
418
- rows = this.getAllRows();
419
- return new Map(
420
- colLayout.map(coords => [rows[coords.row].getNthCol(coords.column), layout[coords.row][x - 1] !== coords]),
421
- );
422
- }
423
-
424
- /**
425
- * 设置行格式
426
- * @param {number} y 行号
427
- * @param {string|Record<string, string|boolean>} attr 表格属性
428
- * @param {boolean} multiRow 是否对所有单元格设置,或是仅对行首单元格设置
429
- * @complexity `n²`
430
- */
431
- formatTableRow(y, attr = {}, multiRow = false) {
432
- format(this.getFullRow(y), attr, multiRow);
433
- }
434
-
435
- /**
436
- * 设置列格式
437
- * @param {number} x 列号
438
- * @param {string|Record<string, string|boolean>} attr 表格属性
439
- * @param {boolean} multiCol 是否对所有单元格设置,或是仅对行首单元格设置
440
- * @complexity `n`
441
- */
442
- formatTableCol(x, attr = {}, multiCol = false) {
443
- format(this.getFullCol(x), attr, multiCol);
444
- }
445
-
446
- /**
447
- * 填补表格行
448
- * @param {number} y 行号
449
- * @param {string|Token} inner 填充内容
450
- * @param {'td'|'th'|'caption'} subtype 单元格类型
451
- * @param {Record<string, string>} attr 表格属性
452
- * @complexity `n`
453
- */
454
- fillTableRow(y, inner, subtype = 'td', attr = {}) {
455
- const rowToken = this.getNthRow(y),
456
- layout = this.getLayout({y}),
457
- maxCol = Math.max(...layout.map(({length}) => length)),
458
- token = TdToken.create(inner, subtype, attr, this.getAttribute('include'), this.getAttribute('config'));
459
- fill(y, rowToken, layout, maxCol, token);
460
- }
461
-
462
- /**
463
- * 填补表格
464
- * @param {string|Token} inner 填充内容
465
- * @param {'td'|'th'|'caption'} subtype 单元格类型
466
- * @param {Record<string, string>} attr 表格属性
467
- * @complexity `n`
468
- */
469
- fillTable(inner, subtype = 'td', attr = {}) {
470
- const rowTokens = this.getAllRows(),
471
- layout = this.getLayout(),
472
- maxCol = Math.max(...layout.map(({length}) => length)),
473
- token = TdToken.create(inner, subtype, attr, this.getAttribute('include'), this.getAttribute('config'));
474
- for (let y = 0; y < rowTokens.length; y++) {
475
- fill(y, rowTokens[y], layout, maxCol, token);
476
- }
477
- }
478
-
479
- /**
480
- * @override
481
- * @param {string|Token} inner 单元格内部wikitext
482
- * @param {TableCoords & TableRenderedCoords} coords 单元格坐标
483
- * @param {'td'|'th'|'caption'} subtype 单元格类型
484
- * @param {Record<string, string|boolean>} attr 单元格属性
485
- * @returns {TdToken}
486
- * @complexity `n`
487
- * @throws `RangeError` 指定的坐标不是单元格起始点
488
- */
489
- insertTableCell(inner, coords, subtype = 'td', attr = {}) {
490
- if (coords.column === undefined) {
491
- const {x, y} = coords;
492
- coords = this.toRawCoords(coords);
493
- if (!coords?.start) {
494
- throw new RangeError(`指定的坐标不是单元格起始点:(${x}, ${y})`);
495
- }
496
- }
497
- const rowToken = this.getNthRow(coords.row ?? 0, true);
498
- return rowToken === this
499
- ? super.insertTableCell(inner, coords, subtype, attr)
500
- : rowToken.insertTableCell(inner, coords, subtype, attr);
501
- }
502
-
503
- /**
504
- * 在开头插入一行
505
- * @complexity `n`
506
- */
507
- #prependTableRow() {
508
- const row = Parser.run(() => new TrToken('\n|-', undefined, this.getAttribute('config'))),
509
- {childNodes} = this,
510
- [,, plain] = childNodes,
511
- start = plain?.constructor === Token ? 3 : 2,
512
- /** @type {TdToken[]} */ tdChildren = childNodes.slice(start),
513
- index = tdChildren.findIndex(({type}) => type !== 'td');
514
- this.insertAt(row, index === -1 ? -1 : index + start);
515
- Parser.run(() => {
516
- for (const cell of tdChildren.slice(0, index === -1 ? undefined : index)) {
517
- if (cell.subtype !== 'caption') {
518
- row.insertAt(cell);
519
- }
520
- }
521
- });
522
- return row;
523
- }
524
-
525
- /**
526
- * 插入表格行
527
- * @param {number} y 行号
528
- * @param {Record<string, string|boolean>} attr 表格行属性
529
- * @param {string|Token} inner 内部wikitext
530
- * @param {'td'|'th'|'caption'} subtype 单元格类型
531
- * @param {Record<string, string|boolean>} innerAttr 单元格属性
532
- * @complexity `n`
533
- */
534
- insertTableRow(y, attr = {}, inner = undefined, subtype = 'td', innerAttr = {}) {
535
- if (!isPlainObject(attr)) {
536
- this.typeError('insertTableRow', 'Object');
537
- }
538
- let reference = this.getNthRow(y, false, true);
539
- const AttributesToken = require('../attributes');
540
- /** @type {TrToken & AttributesToken}} */
541
- const token = Parser.run(() => new TrToken('\n|-', undefined, this.getAttribute('config')));
542
- for (const [k, v] of Object.entries(attr)) {
543
- token.setAttr(k, v);
544
- }
545
- if (reference.type === 'table') { // `row === 0`且表格自身是有效行
546
- reference = this.#prependTableRow();
547
- }
548
- this.insertBefore(token, reference);
549
- if (inner !== undefined) {
550
- const td = token.insertTableCell(inner, {column: 0}, subtype, innerAttr),
551
- /** @type {WeakSet<TableCoords>} */ set = new WeakSet(),
552
- layout = this.getLayout({y}),
553
- maxCol = Math.max(...layout.map(({length}) => length)),
554
- rowLayout = layout[y];
555
- Parser.run(() => {
556
- for (let i = 0; i < maxCol; i++) {
557
- const coords = rowLayout[i];
558
- if (!coords) {
559
- token.insertAt(td.cloneNode());
560
- } else if (!set.has(coords)) {
561
- set.add(coords);
562
- if (coords.row < y) {
563
- this.getNthCell(coords).rowspan++;
564
- }
565
- }
566
- }
567
- });
568
- }
569
- return token;
570
- }
571
-
572
- /**
573
- * 插入表格列
574
- * @param {number} x 列号
575
- * @param {string|Token} inner 内部wikitext
576
- * @param {'td'|'th'|'caption'} subtype 单元格类型
577
- * @param {Record<string, string>} attr 单元格属性
578
- * @complexity `n²`
579
- * @throws `RangeError` 列号过大
580
- */
581
- insertTableCol(x, inner, subtype = 'td', attr = {}) {
582
- if (!Number.isInteger(x)) {
583
- this.typeError('insertTableCol', 'Number');
584
- }
585
- const layout = this.getLayout(),
586
- rowLength = layout.map(({length}) => length),
587
- minCol = Math.min(...rowLength);
588
- if (x > minCol) {
589
- throw new RangeError(`表格第 ${rowLength.indexOf(minCol)} 行仅有 ${minCol} 列!`);
590
- }
591
- const token = TdToken.create(inner, subtype, attr, this.getAttribute('include'), this.getAttribute('config'));
592
- for (let i = 0; i < layout.length; i++) {
593
- const coords = layout[i][x],
594
- prevCoords = x === 0 ? true : layout[i][x - 1];
595
- if (!prevCoords) {
596
- continue;
597
- } else if (prevCoords !== coords) {
598
- const rowToken = this.getNthRow(i);
599
- rowToken.insertBefore(token.cloneNode(), rowToken.getNthCol(coords.column, true));
600
- } else if (coords?.row === i) {
601
- this.getNthCell(coords).colspan++;
602
- }
603
- }
604
- }
605
-
606
- /**
607
- * 移除表格行
608
- * @param {number} y 行号
609
- * @complexity `n²`
610
- */
611
- removeTableRow(y) {
612
- const rows = this.getAllRows(),
613
- layout = this.getLayout(),
614
- rowLayout = layout[y],
615
- /** @type {WeakSet<TableCoords>} */ set = new WeakSet();
616
- for (let x = rowLayout.length - 1; x >= 0; x--) {
617
- const coords = rowLayout[x];
618
- if (set.has(coords)) {
619
- continue;
620
- }
621
- set.add(coords);
622
- const token = rows[coords.row].getNthCol(coords.column);
623
- let {rowspan} = token;
624
- if (rowspan > 1) {
625
- token.rowspan = --rowspan;
626
- if (coords.row === y) {
627
- const {colspan, subtype} = token,
628
- attr = token.getAttrs();
629
- for (let i = y + 1; rowspan && i < rows.length; i++, rowspan--) {
630
- const {column} = layout[i].slice(x + colspan).find(({row}) => row === i) ?? {};
631
- if (column !== undefined) {
632
- rows[i].insertTableCell('', {column}, subtype, {...attr, rowspan});
633
- break;
634
- }
635
- }
636
- }
637
- }
638
- }
639
- const rowToken = rows[y].type === 'table' ? this.#prependTableRow() : rows[y];
640
- rowToken.remove();
641
- return rowToken;
642
- }
643
-
644
- /**
645
- * 移除表格列
646
- * @param {number} x 列号
647
- * @complexity `n²`
648
- */
649
- removeTableCol(x) {
650
- for (const [token, start] of this.getFullCol(x)) {
651
- const {colspan, lastChild} = token;
652
- if (colspan > 1) {
653
- token.colspan = colspan - 1;
654
- if (start) {
655
- lastChild.replaceChildren();
656
- }
657
- } else {
658
- token.remove();
659
- }
660
- }
661
- }
662
-
663
- /**
664
- * 合并单元格
665
- * @param {[number, number]} xlim 列范围
666
- * @param {[number, number]} ylim 行范围
667
- * @complexity `n²`
668
- * @throws `RangeError` 待合并区域与外侧区域有重叠
669
- */
670
- mergeCells(xlim, ylim) {
671
- if (![...xlim, ...ylim].every(Number.isInteger)) {
672
- this.typeError('mergeCells', 'Number');
673
- }
674
- const layout = this.getLayout(),
675
- maxCol = Math.max(...layout.map(({length}) => length));
676
- xlim = xlim.map(x => x < 0 ? x + maxCol : x);
677
- ylim = ylim.map(y => y < 0 ? y + layout.length : y);
678
- const [xmin, xmax] = xlim.sort(),
679
- [ymin, ymax] = ylim.sort(),
680
- set = new Set(layout.slice(ymin, ymax).flatMap(rowLayout => rowLayout.slice(xmin, xmax)));
681
- if ([...layout[ymin - 1] ?? [], ...layout[ymax] ?? []].some(coords => set.has(coords))
682
- || layout.some(rowLayout => set.has(rowLayout[xmin - 1]) || set.has(rowLayout[xmax]))
683
- ) {
684
- throw new RangeError('待合并区域与外侧区域有重叠!');
685
- }
686
- const corner = layout[ymin][xmin],
687
- rows = this.getAllRows(),
688
- cornerCell = rows[corner.row].getNthCol(corner.column);
689
- cornerCell.rowspan = ymax - ymin;
690
- cornerCell.colspan = xmax - xmin;
691
- set.delete(corner);
692
- for (const token of [...set].map(({row, column}) => rows[row].getNthCol(column))) {
693
- token.remove();
694
- }
695
- return cornerCell;
696
- }
697
-
698
- /**
699
- * 分裂单元格
700
- * @param {TableCoords & TableRenderedCoords} coords 单元格坐标
701
- * @param {Set<'rowspan'|'colspan'>} dirs 分裂方向
702
- * @complexity `n²`
703
- * @throws `RangeError` 指定的坐标不是单元格起始点
704
- */
705
- #split(coords, dirs) {
706
- const cell = this.getNthCell(coords),
707
- attr = cell.getAttrs(),
708
- {subtype} = cell;
709
- attr.rowspan ||= 1;
710
- attr.colspan ||= 1;
711
- for (const dir of dirs) {
712
- if (attr[dir] === 1) {
713
- dirs.delete(dir);
714
- }
715
- }
716
- if (dirs.size === 0) {
717
- return;
718
- }
719
- let {x, y} = coords;
720
- if (x !== undefined) {
721
- coords = this.toRawCoords(coords);
722
- }
723
- if (coords.start === false || x === undefined) {
724
- ({x, y} = this.toRenderedCoords(coords));
725
- }
726
- const splitting = {rowspan: 1, colspan: 1};
727
- for (const dir of dirs) {
728
- cell.setAttr(dir, 1);
729
- splitting[dir] = attr[dir];
730
- delete attr[dir];
731
- }
732
- for (let j = y; j < y + splitting.rowspan; j++) {
733
- for (let i = x; i < x + splitting.colspan; i++) {
734
- if (i > x || j > y) {
735
- try {
736
- this.insertTableCell('', {x: i, y: j}, subtype, attr);
737
- } catch (e) {
738
- if (e instanceof RangeError && e.message.startsWith('指定的坐标不是单元格起始点:')) {
739
- break;
740
- }
741
- throw e;
742
- }
743
- }
744
- }
745
- }
746
- }
747
-
748
- /**
749
- * 分裂成多行
750
- * @param {TableCoords & TableRenderedCoords} coords 单元格坐标
751
- * @complexity `n²`
752
- */
753
- splitIntoRows(coords) {
754
- this.#split(coords, new Set(['rowspan']));
755
- }
756
-
757
- /**
758
- * 分裂成多列
759
- * @param {TableCoords & TableRenderedCoords} coords 单元格坐标
760
- * @complexity `n²`
761
- */
762
- splitIntoCols(coords) {
763
- this.#split(coords, new Set(['colspan']));
764
- }
765
-
766
- /**
767
- * 分裂成单元格
768
- * @param {TableCoords & TableRenderedCoords} coords 单元格坐标
769
- * @complexity `n²`
770
- */
771
- splitIntoCells(coords) {
772
- this.#split(coords, new Set(['rowspan', 'colspan']));
773
- }
774
-
775
- /**
776
- * 复制一行并插入该行之前
777
- * @param {number} row 行号
778
- * @complexity `n²`
779
- */
780
- replicateTableRow(row) {
781
- let rowToken = this.getNthRow(row);
782
- if (rowToken.type === 'table') {
783
- rowToken = this.#prependTableRow();
784
- }
785
- const /** @type {TrToken} */ replicated = this.insertBefore(rowToken.cloneNode(), rowToken);
786
- for (const [token, start] of this.getFullRow(row)) {
787
- if (start) {
788
- token.rowspan = 1;
789
- } else {
790
- token.rowspan++;
791
- }
792
- }
793
- return replicated;
794
- }
795
-
796
- /**
797
- * 复制一列并插入该列之前
798
- * @param {number} x 列号
799
- * @complexity `n`
800
- */
801
- replicateTableCol(x) {
802
- const /** @type {TdToken[]} */ replicated = [];
803
- for (const [token, start] of this.getFullCol(x)) {
804
- if (start) {
805
- const newToken = token.cloneNode();
806
- newToken.colspan = 1;
807
- token.before(newToken);
808
- replicated.push(newToken);
809
- } else {
810
- token.colspan++;
811
- }
812
- }
813
- return replicated;
814
- }
815
-
816
- /**
817
- * 移动表格行
818
- * @param {number} y 行号
819
- * @param {number} before 新位置
820
- * @complexity `n²`
821
- * @throws `RangeError` 无法移动
822
- */
823
- moveTableRowBefore(y, before) {
824
- if (!Number.isInteger(y) || !Number.isInteger(before)) {
825
- this.typeError('moveTableRowBefore', 'Number');
826
- }
827
- const layout = this.getLayout();
828
-
829
- /**
830
- * @type {(i: number) => number[]}
831
- * @complexity `n`
832
- */
833
- const occupied = i => layout[i].map(({row}, j) => row === i ? j : undefined).filter(j => j !== undefined);
834
- try {
835
- assert.deepStrictEqual(occupied(y), occupied(before));
836
- } catch (e) {
837
- if (e instanceof assert.AssertionError) {
838
- throw new RangeError(`第 ${y} 行与第 ${before} 行的构造不同,无法移动!`);
839
- }
840
- throw e;
841
- }
842
- const rowToken = this.removeTableRow(y);
843
- for (const coords of layout[before]) {
844
- if (coords.row < before) {
845
- this.getNthCell(coords).rowspan++;
846
- }
847
- }
848
- let beforeToken = this.getNthRow(before);
849
- if (beforeToken.type === 'table') {
850
- beforeToken = this.#prependTableRow();
851
- }
852
- this.insertBefore(rowToken, beforeToken);
853
- return rowToken;
854
- }
855
-
856
- /**
857
- * 移动表格行
858
- * @param {number} y 行号
859
- * @param {number} after 新位置
860
- * @complexity `n²`
861
- * @throws `RangeError` 无法移动
862
- */
863
- moveTableRowAfter(y, after) {
864
- if (!Number.isInteger(y) || !Number.isInteger(after)) {
865
- this.typeError('moveTableRowAfter', 'Number');
866
- }
867
- const layout = this.getLayout(),
868
- afterToken = this.getNthRow(after),
869
- /** @type {TdToken[]} */
870
- cells = afterToken.childNodes.filter(child => child instanceof TdToken && child.subtype !== 'caption');
871
-
872
- /**
873
- * @type {(i: number, oneRow?: boolean) => number[]}
874
- * @complexity `n`
875
- */
876
- const occupied = (i, oneRow = false) => layout[i].map(
877
- ({row, column}, j) => row === i && (!oneRow || cells[column].rowspan === 1) ? j : undefined,
878
- ).filter(j => j !== undefined);
879
- try {
880
- assert.deepStrictEqual(occupied(y), occupied(after, true));
881
- } catch (e) {
882
- if (e instanceof assert.AssertionError) {
883
- throw new RangeError(`第 ${y} 行与第 ${after} 行的构造不同,无法移动!`);
884
- }
885
- throw e;
886
- }
887
- const rowToken = this.removeTableRow(y);
888
- for (const coords of layout[after]) {
889
- if (coords.row < after) {
890
- this.getNthCell(coords).rowspan++;
891
- } else {
892
- const cell = cells[coords.column],
893
- {rowspan} = cell;
894
- if (rowspan > 1) {
895
- cell.rowspan = rowspan + 1;
896
- }
897
- }
898
- }
899
- if (afterToken === this) {
900
- const index = this.childNodes.slice(2).findIndex(isRowEnd);
901
- this.insertAt(rowToken, index + 2);
902
- } else {
903
- this.insertBefore(rowToken, afterToken);
904
- }
905
- return rowToken;
906
- }
907
-
908
- /**
909
- * 移动表格列
910
- * @param {number} x 列号
911
- * @param {number} reference 新位置
912
- * @param {boolean} after 在新位置之后或之前
913
- * @complexity `n`
914
- * @throws `RangeError` 无法移动
915
- */
916
- #moveCol(x, reference, after = false) {
917
- if (!Number.isInteger(x) || !Number.isInteger(reference)) {
918
- this.typeError(`moveTableCol${after ? 'After' : 'Before'}`, 'Number');
919
- }
920
- const layout = this.getLayout();
921
- if (layout.some(rowLayout => isStartCol(rowLayout, x) !== isStartCol(rowLayout, reference, after))) {
922
- throw new RangeError(`第 ${x} 列与第 ${reference} 列的构造不同,无法移动!`);
923
- }
924
- const /** @type {WeakSet<TableCoords>} */ setX = new WeakSet(),
925
- /** @type {WeakSet<TableCoords>} */ setRef = new WeakSet(),
926
- rows = this.getAllRows();
927
- for (let i = 0; i < layout.length; i++) {
928
- const rowLayout = layout[i],
929
- coords = rowLayout[x],
930
- refCoords = rowLayout[reference],
931
- start = isStartCol(rowLayout, x);
932
- if (refCoords && !start && !setRef.has(refCoords)) {
933
- setRef.add(refCoords);
934
- rows[refCoords.row].getNthCol(refCoords.column).colspan++;
935
- }
936
- if (coords && !setX.has(coords)) {
937
- setX.add(coords);
938
- const rowToken = rows[i];
939
- let token = rowToken.getNthCol(coords.column);
940
- const {colspan} = token;
941
- if (colspan > 1) {
942
- token.colspan = colspan - 1;
943
- if (start) {
944
- const original = token;
945
- token = token.cloneNode();
946
- original.lastChild.replaceChildren();
947
- token.colspan = 1;
948
- }
949
- }
950
- if (start) {
951
- const col = rowLayout.slice(reference + Number(after)).find(({row}) => row === i)?.column;
952
- rowToken.insertBefore(
953
- token, col === undefined && rowToken.type === 'table'
954
- ? rowToken.childNodes.slice(2).find(isRowEnd)
955
- : col !== undefined && rowToken.getNthCol(col),
956
- );
957
- }
958
- }
959
- }
960
- }
961
-
962
- /**
963
- * 移动表格列
964
- * @param {number} x 列号
965
- * @param {number} before 新位置
966
- * @complexity `n`
967
- */
968
- moveTableColBefore(x, before) {
969
- this.#moveCol(x, before);
970
- }
971
-
972
- /**
973
- * 移动表格列
974
- * @param {number} x 列号
975
- * @param {number} after 新位置
976
- * @complexity `n`
977
- */
978
- moveTableColAfter(x, after) {
979
- this.#moveCol(x, after, true);
980
- }
981
- }
982
-
983
- Parser.classes.TableToken = __filename;
984
- module.exports = TableToken;