wikiparser-node 0.11.0 → 1.0.0-beta.1

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