@podlite/schema 0.0.38 → 0.0.39
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.
- package/CHANGELOG.podlite +10 -0
- package/esm/index.d.ts +2 -0
- package/esm/index.js +1 -0
- package/esm/index.js.map +1 -1
- package/esm/plugin-tables.js +397 -46
- package/esm/plugin-tables.js.map +1 -1
- package/esm/selectors.d.ts +18 -0
- package/esm/selectors.js +158 -0
- package/esm/selectors.js.map +1 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +4 -1
- package/lib/plugin-tables.js +397 -46
- package/lib/selectors.d.ts +18 -0
- package/lib/selectors.js +163 -0
- package/package.json +1 -1
package/lib/plugin-tables.js
CHANGED
|
@@ -9,13 +9,271 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
9
9
|
* and the remaining content is treated as the definition for the term.
|
|
10
10
|
*/
|
|
11
11
|
const makeTransformer_1 = __importDefault(require("./helpers/makeTransformer"));
|
|
12
|
+
const config_1 = __importDefault(require("./helpers/config"));
|
|
12
13
|
function flattenDeep(arr) {
|
|
13
14
|
return arr.reduce((acc, val) => (Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val)), []);
|
|
14
15
|
}
|
|
16
|
+
// ─── CSV source for =table (spec §1672) ────────────────────────────────────
|
|
17
|
+
// Parse CSV content per RFC 4180: comma delimiter, `"`-quoted fields with
|
|
18
|
+
// `""` as embedded-quote escape. Supports LF or CRLF line endings. Leading
|
|
19
|
+
// indentation typical of =data block bodies is stripped from each line.
|
|
20
|
+
function parseCsv(text) {
|
|
21
|
+
const rows = [];
|
|
22
|
+
let field = '';
|
|
23
|
+
let row = [];
|
|
24
|
+
let inQuote = false;
|
|
25
|
+
let i = 0;
|
|
26
|
+
while (i < text.length) {
|
|
27
|
+
const c = text[i];
|
|
28
|
+
if (inQuote) {
|
|
29
|
+
if (c === '"' && text[i + 1] === '"') {
|
|
30
|
+
field += '"';
|
|
31
|
+
i += 2;
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (c === '"') {
|
|
35
|
+
inQuote = false;
|
|
36
|
+
i++;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
field += c;
|
|
40
|
+
i++;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (c === '"' && field === '') {
|
|
44
|
+
inQuote = true;
|
|
45
|
+
i++;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (c === ',') {
|
|
49
|
+
row.push(field);
|
|
50
|
+
field = '';
|
|
51
|
+
i++;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
if (c === '\r') {
|
|
55
|
+
i++;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (c === '\n') {
|
|
59
|
+
row.push(field);
|
|
60
|
+
rows.push(row);
|
|
61
|
+
row = [];
|
|
62
|
+
field = '';
|
|
63
|
+
i++;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
field += c;
|
|
67
|
+
i++;
|
|
68
|
+
}
|
|
69
|
+
if (field !== '' || row.length > 0) {
|
|
70
|
+
row.push(field);
|
|
71
|
+
rows.push(row);
|
|
72
|
+
}
|
|
73
|
+
// Drop rows that are entirely blank (empty content after trim).
|
|
74
|
+
return rows.filter(r => !(r.length === 1 && r[0].trim() === ''));
|
|
75
|
+
}
|
|
76
|
+
// Parse a TSV (tab-separated values) blob. Unlike CSV, TSV has no quoting
|
|
77
|
+
// mechanism — fields are split strictly on tabs and `"` is a literal
|
|
78
|
+
// character. Tabs and newlines inside fields are not representable in TSV.
|
|
79
|
+
function parseTsv(text) {
|
|
80
|
+
const lines = text.split(/\r?\n/);
|
|
81
|
+
const rows = lines.map(line => line.split('\t'));
|
|
82
|
+
return rows.filter(r => !(r.length === 1 && r[0].trim() === ''));
|
|
83
|
+
}
|
|
84
|
+
// Locate the first `=data` block with a matching `:key` attribute anywhere
|
|
85
|
+
// in the document tree.
|
|
86
|
+
function findDataBlockByKey(tree, key) {
|
|
87
|
+
let found = null;
|
|
88
|
+
const walk = node => {
|
|
89
|
+
if (found)
|
|
90
|
+
return;
|
|
91
|
+
if (Array.isArray(node)) {
|
|
92
|
+
node.forEach(walk);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (!node || typeof node !== 'object')
|
|
96
|
+
return;
|
|
97
|
+
if (node.type === 'block' && node.name === 'data') {
|
|
98
|
+
const attrs = (0, config_1.default)(node, {});
|
|
99
|
+
if (attrs.getFirstValue('key') === key) {
|
|
100
|
+
found = node;
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (Array.isArray(node.content))
|
|
105
|
+
node.content.forEach(walk);
|
|
106
|
+
};
|
|
107
|
+
walk(tree);
|
|
108
|
+
return found;
|
|
109
|
+
}
|
|
110
|
+
function extractDataText(dataNode) {
|
|
111
|
+
if (!dataNode || !Array.isArray(dataNode.content))
|
|
112
|
+
return '';
|
|
113
|
+
const verbatim = dataNode.content.find(c => c && c.type === 'verbatim');
|
|
114
|
+
return verbatim && typeof verbatim.value === 'string' ? verbatim.value : '';
|
|
115
|
+
}
|
|
116
|
+
// Detect whether the =table body is a single-line source reference like
|
|
117
|
+
// `data:key` or `file:path` (spec §1672). Returns the parsed reference or
|
|
118
|
+
// null if the body is ordinary table content.
|
|
119
|
+
function detectSourceReference(tableNode) {
|
|
120
|
+
const texts = [];
|
|
121
|
+
const walker = (0, makeTransformer_1.default)({
|
|
122
|
+
'row:text': r => {
|
|
123
|
+
texts.push(r.value);
|
|
124
|
+
return r;
|
|
125
|
+
},
|
|
126
|
+
'head:text': h => {
|
|
127
|
+
texts.push(h.value);
|
|
128
|
+
return h;
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
walker(tableNode, {});
|
|
132
|
+
const joined = texts.join('\n').trim();
|
|
133
|
+
const lines = joined
|
|
134
|
+
.split(/\r?\n/)
|
|
135
|
+
.map(l => l.trim())
|
|
136
|
+
.filter(l => l.length > 0);
|
|
137
|
+
if (lines.length !== 1)
|
|
138
|
+
return null;
|
|
139
|
+
const m = lines[0].match(/^(data|file):(\S+)$/);
|
|
140
|
+
if (!m)
|
|
141
|
+
return null;
|
|
142
|
+
return { scheme: m[1], target: m[2] };
|
|
143
|
+
}
|
|
144
|
+
function buildCellBlock(text) {
|
|
145
|
+
return {
|
|
146
|
+
name: 'cell',
|
|
147
|
+
type: 'block',
|
|
148
|
+
margin: '',
|
|
149
|
+
content: [{ type: 'text', value: text }],
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function buildRowBlock(cells, isHeader) {
|
|
153
|
+
const block = {
|
|
154
|
+
name: 'row',
|
|
155
|
+
type: 'block',
|
|
156
|
+
margin: '',
|
|
157
|
+
content: cells,
|
|
158
|
+
};
|
|
159
|
+
if (isHeader) {
|
|
160
|
+
block.config = [{ name: 'header', value: true, type: 'boolean' }];
|
|
161
|
+
}
|
|
162
|
+
return block;
|
|
163
|
+
}
|
|
164
|
+
// Convert parsed CSV/TSV rows to plain `=row`/`=cell` blocks. The spec is
|
|
165
|
+
// silent on how to mark a header row in `=table data:<key>` references, so
|
|
166
|
+
// no row receives `:header` here. Authors who need a header row can use a
|
|
167
|
+
// structured table with explicit `=begin row :header`, or a Markdown GFM
|
|
168
|
+
// table with a separator line.
|
|
169
|
+
function csvToTableContent(csvRows) {
|
|
170
|
+
return csvRows.map(row => {
|
|
171
|
+
const cells = row.map(v => buildCellBlock(v.trim()));
|
|
172
|
+
return buildRowBlock(cells, false);
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
// ─── Error recovery (design notes Rules 2-4) ───────────────────────────────
|
|
176
|
+
// Rule 2 — table-level cell count validation. Pad short rows with empty
|
|
177
|
+
// cells; truncate long rows. Emit a warning whenever a row is changed.
|
|
178
|
+
// Expected count is taken from the `:header` row if present, otherwise from
|
|
179
|
+
// the row with the maximum cell count.
|
|
180
|
+
//
|
|
181
|
+
// Skipped when any cell uses `:colspan` or `:rowspan`: a spanning cell
|
|
182
|
+
// occupies multiple columns, so naive cell counting would misreport row
|
|
183
|
+
// width and drop legitimate spanned cells.
|
|
184
|
+
function normalizeCellCounts(tableNode, source = 'table') {
|
|
185
|
+
if (!tableNode || !Array.isArray(tableNode.content))
|
|
186
|
+
return tableNode;
|
|
187
|
+
const rows = tableNode.content.filter(c => c && c.type === 'block' && c.name === 'row');
|
|
188
|
+
if (rows.length === 0)
|
|
189
|
+
return tableNode;
|
|
190
|
+
const cellsOf = row => (Array.isArray(row.content) ? row.content.filter(c => c && c.name === 'cell') : []);
|
|
191
|
+
const isHeaderRow = row => Array.isArray(row.config) && row.config.some(a => a.name === 'header' && a.value === true);
|
|
192
|
+
const cellHasSpan = cell => Array.isArray(cell.config) && cell.config.some(a => a.name === 'colspan' || a.name === 'rowspan');
|
|
193
|
+
const rowHasSpan = row => cellsOf(row).some(cellHasSpan);
|
|
194
|
+
if (rows.some(rowHasSpan))
|
|
195
|
+
return tableNode;
|
|
196
|
+
const headerRow = rows.find(isHeaderRow);
|
|
197
|
+
const expected = headerRow ? cellsOf(headerRow).length : Math.max(...rows.map(r => cellsOf(r).length));
|
|
198
|
+
if (expected === 0)
|
|
199
|
+
return tableNode;
|
|
200
|
+
let mutated = false;
|
|
201
|
+
const newContent = tableNode.content.map(child => {
|
|
202
|
+
if (!child || child.type !== 'block' || child.name !== 'row')
|
|
203
|
+
return child;
|
|
204
|
+
const cells = cellsOf(child);
|
|
205
|
+
if (cells.length === expected)
|
|
206
|
+
return child;
|
|
207
|
+
if (cells.length < expected) {
|
|
208
|
+
const padding = [];
|
|
209
|
+
for (let i = cells.length; i < expected; i++)
|
|
210
|
+
padding.push(buildCellBlock(''));
|
|
211
|
+
console.warn(`[${source}] row has ${cells.length} cells, expected ${expected} — padded with ${padding.length} empty`);
|
|
212
|
+
mutated = true;
|
|
213
|
+
return { ...child, content: [...child.content, ...padding] };
|
|
214
|
+
}
|
|
215
|
+
// cells.length > expected → truncate
|
|
216
|
+
const dropped = cells.length - expected;
|
|
217
|
+
console.warn(`[${source}] row has ${cells.length} cells, expected ${expected} — truncated ${dropped}`);
|
|
218
|
+
mutated = true;
|
|
219
|
+
// Keep non-cell entries (e.g. blanklines) and the first `expected` cells
|
|
220
|
+
let keepCells = expected;
|
|
221
|
+
const trimmed = [];
|
|
222
|
+
for (const c of child.content || []) {
|
|
223
|
+
if (c && c.type === 'block' && c.name === 'cell') {
|
|
224
|
+
if (keepCells > 0) {
|
|
225
|
+
trimmed.push(c);
|
|
226
|
+
keepCells--;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
trimmed.push(c);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return { ...child, content: trimmed };
|
|
234
|
+
});
|
|
235
|
+
return mutated ? { ...tableNode, content: newContent } : tableNode;
|
|
236
|
+
}
|
|
237
|
+
// Rule 3 — mixed separator detection (text-mode only). Inspects each line
|
|
238
|
+
// for visible separators (`|` / `+`) surrounded by whitespace; lines without
|
|
239
|
+
// any visible separator fall back to whitespace separation. Warns when more
|
|
240
|
+
// than one separator type is observed within a single table.
|
|
241
|
+
function detectMixedSeparators(lines) {
|
|
242
|
+
const seen = new Set();
|
|
243
|
+
for (const line of lines) {
|
|
244
|
+
if (!line || typeof line !== 'string')
|
|
245
|
+
continue;
|
|
246
|
+
if (/\s\|\s/.test(line))
|
|
247
|
+
seen.add('pipe');
|
|
248
|
+
else if (/\s\+\s/.test(line))
|
|
249
|
+
seen.add('plus');
|
|
250
|
+
else if (line.trim().length > 0)
|
|
251
|
+
seen.add('whitespace');
|
|
252
|
+
if (seen.size > 1)
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
if (seen.size > 1) {
|
|
256
|
+
console.warn(`[table] mixed separator types detected: ${Array.from(seen).join(', ')} — recommend a single style`);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
// Rule 4 — replace =table with =code block. Used when a referenced =data
|
|
260
|
+
// source has a non-CSV mime type: the spec mandates the source be rendered
|
|
261
|
+
// as a code block so the user can still see the underlying content.
|
|
262
|
+
function buildCodeFromDataBlock(tableNode, dataBlock) {
|
|
263
|
+
return {
|
|
264
|
+
type: 'block',
|
|
265
|
+
name: 'code',
|
|
266
|
+
margin: tableNode.margin || '',
|
|
267
|
+
content: Array.isArray(dataBlock.content) ? dataBlock.content : [],
|
|
268
|
+
config: Array.isArray(tableNode.config) ? tableNode.config : [],
|
|
269
|
+
};
|
|
270
|
+
}
|
|
15
271
|
/**
|
|
16
272
|
* Helpers section
|
|
17
273
|
*/
|
|
18
|
-
//
|
|
274
|
+
// Bit-mask helper used by the positional column extractor for multi-line
|
|
275
|
+
// rows. Compares two same-length digit strings character by character via
|
|
276
|
+
// `cb`, returning the joined result.
|
|
19
277
|
const strbin = (str1, str2, cb) => {
|
|
20
278
|
let res = [];
|
|
21
279
|
for (let i = 0; str1.length > i; i++) {
|
|
@@ -23,62 +281,109 @@ const strbin = (str1, str2, cb) => {
|
|
|
23
281
|
}
|
|
24
282
|
return res.join('');
|
|
25
283
|
};
|
|
26
|
-
//
|
|
284
|
+
// Build a unified column-position mask across a set of lines. Used as a
|
|
285
|
+
// fallback when a row spans multiple lines (continuation lines that align
|
|
286
|
+
// content by character position rather than by separator). Returns a binary
|
|
287
|
+
// string where `0` runs mark column ranges and `1` runs mark gaps.
|
|
27
288
|
const makeMask = (lines, separators) => {
|
|
28
|
-
// calculate template length
|
|
29
289
|
const tmplLength = Math.max(...[...lines, ...separators].map(s => s.length));
|
|
30
|
-
// make bin mask for each string
|
|
31
290
|
const masks = lines.map(str => {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
'0000000011111111111110001111111111111000001111111111111111111111111111' ]
|
|
35
|
-
then not(mask) ... then & masks
|
|
36
|
-
*/
|
|
37
|
-
// enlarge string to tmplLength
|
|
38
|
-
let tstr = str + ' '.repeat(tmplLength - str.length);
|
|
39
|
-
let mask = [];
|
|
291
|
+
const tstr = str + ' '.repeat(tmplLength - str.length);
|
|
292
|
+
const mask = [];
|
|
40
293
|
const re = /\s+[+|\s]\s/g;
|
|
41
294
|
let match;
|
|
42
295
|
while ((match = re.exec(tstr)) != null) {
|
|
43
296
|
const tmpMask = '1'.repeat(match.index) + '0'.repeat(match[0].length);
|
|
44
297
|
mask.push(tmpMask + '1'.repeat(tmplLength - tmpMask.length));
|
|
45
298
|
}
|
|
46
|
-
return mask.reduce((a, b) =>
|
|
47
|
-
return strbin(a, b, (i1, i2) => i1 & i2);
|
|
48
|
-
}, '1'.repeat(tmplLength));
|
|
299
|
+
return mask.reduce((a, b) => strbin(a, b, (i1, i2) => i1 & i2), '1'.repeat(tmplLength));
|
|
49
300
|
});
|
|
50
|
-
// make result mask
|
|
51
301
|
const inverted = masks.map(m => strbin(m, '', i1 => (i1 == 0 ? 1 : 0)));
|
|
52
|
-
|
|
53
|
-
return strbin(a, b, (i1, i2) => i1 & i2);
|
|
54
|
-
}, '1'.repeat(tmplLength));
|
|
55
|
-
return columnTemplate;
|
|
302
|
+
return inverted.reduce((a, b) => strbin(a, b, (i1, i2) => i1 & i2), '1'.repeat(tmplLength));
|
|
56
303
|
};
|
|
304
|
+
// Apply a column-position template to a multi-line text block, extracting
|
|
305
|
+
// per-column substrings and aggregating across lines (continuation lines
|
|
306
|
+
// append to the cell at the same column position).
|
|
57
307
|
const extractColumnsByTemplate = (text, template) => {
|
|
58
|
-
const lines = flattenDeep(text
|
|
59
|
-
.split(/\n/) // split each row by eol
|
|
60
|
-
.filter(str => str.length > 0));
|
|
308
|
+
const lines = flattenDeep(text.split(/\n/).filter(s => s.length > 0));
|
|
61
309
|
const cols = lines.map(line => {
|
|
62
310
|
const re = /((1+|0+))/g;
|
|
63
|
-
|
|
311
|
+
const columns = [];
|
|
64
312
|
let match;
|
|
65
313
|
while ((match = re.exec(template)) != null) {
|
|
66
|
-
if (match[0][0] == 1)
|
|
314
|
+
if (match[0][0] == '1')
|
|
67
315
|
continue;
|
|
68
|
-
|
|
69
|
-
columns.push(s);
|
|
316
|
+
columns.push(line.substring(match.index, match.index + match[0].length));
|
|
70
317
|
}
|
|
71
318
|
return columns;
|
|
72
319
|
});
|
|
73
|
-
|
|
74
|
-
|
|
320
|
+
const result = [];
|
|
321
|
+
cols.reduce((a, b) => {
|
|
75
322
|
for (let i = 0; i < b.length; i++) {
|
|
76
323
|
a[i] = (a[i] === undefined ? '' : a[i]) + ' ' + b[i];
|
|
77
324
|
}
|
|
78
325
|
return a;
|
|
79
|
-
},
|
|
326
|
+
}, result);
|
|
80
327
|
return result;
|
|
81
328
|
};
|
|
329
|
+
const detectLineSeparator = (line) => {
|
|
330
|
+
if (/(?:^|\s)\|(?:\s|$)/.test(line))
|
|
331
|
+
return 'pipe';
|
|
332
|
+
if (/(?:^|\s)\+(?:\s|$)/.test(line))
|
|
333
|
+
return 'plus';
|
|
334
|
+
return 'whitespace';
|
|
335
|
+
};
|
|
336
|
+
const trimEdgeEmpty = (cells) => {
|
|
337
|
+
// A leading `|` produces an empty cell at index 0; a trailing `|` does the
|
|
338
|
+
// same at the end. Drop those edge artifacts. Empty cells in the middle of
|
|
339
|
+
// the row are preserved.
|
|
340
|
+
let start = 0;
|
|
341
|
+
let end = cells.length;
|
|
342
|
+
if (cells[start] === '')
|
|
343
|
+
start++;
|
|
344
|
+
if (end > start && cells[end - 1] === '')
|
|
345
|
+
end--;
|
|
346
|
+
return cells.slice(start, end);
|
|
347
|
+
};
|
|
348
|
+
const splitLineByPipe = (line) => trimEdgeEmpty(line.split(/\s*\|\s*/).map(c => c.trim()));
|
|
349
|
+
const splitLineByPlus = (line) => trimEdgeEmpty(line.split(/\s*\+\s*/).map(c => c.trim()));
|
|
350
|
+
const splitLineByWhitespace = (line) => line
|
|
351
|
+
.trim()
|
|
352
|
+
.split(/\s{2,}/)
|
|
353
|
+
.filter(c => c !== '');
|
|
354
|
+
const splitLineCells = (line) => {
|
|
355
|
+
const trimmed = line.trim();
|
|
356
|
+
if (trimmed === '')
|
|
357
|
+
return [];
|
|
358
|
+
const kind = detectLineSeparator(line);
|
|
359
|
+
if (kind === 'pipe')
|
|
360
|
+
return splitLineByPipe(line);
|
|
361
|
+
if (kind === 'plus')
|
|
362
|
+
return splitLineByPlus(line);
|
|
363
|
+
return splitLineByWhitespace(line);
|
|
364
|
+
};
|
|
365
|
+
// Convert a row's raw text (which may span multiple lines) to cell values.
|
|
366
|
+
// Multi-line rows: take the separator kind from the first non-blank line and
|
|
367
|
+
// apply it to every line of the row, then aggregate column-wise so that a
|
|
368
|
+
// continuation line (e.g. wrapped cell content) appends to the cell from the
|
|
369
|
+
// previous line in the same column.
|
|
370
|
+
const rowToCells = (rowValue) => {
|
|
371
|
+
const lines = rowValue.split(/\r?\n/).filter(l => l.trim() !== '');
|
|
372
|
+
if (lines.length === 0)
|
|
373
|
+
return [];
|
|
374
|
+
if (lines.length === 1)
|
|
375
|
+
return splitLineCells(lines[0]);
|
|
376
|
+
const kind = detectLineSeparator(lines[0]);
|
|
377
|
+
const splitFn = kind === 'pipe' ? splitLineByPipe : kind === 'plus' ? splitLineByPlus : splitLineByWhitespace;
|
|
378
|
+
const lineCells = lines.map(splitFn);
|
|
379
|
+
const maxCols = Math.max(...lineCells.map(c => c.length));
|
|
380
|
+
const merged = [];
|
|
381
|
+
for (let i = 0; i < maxCols; i++) {
|
|
382
|
+
const parts = lineCells.map(line => line[i] ?? '').filter(p => p !== '');
|
|
383
|
+
merged.push(parts.join(' '));
|
|
384
|
+
}
|
|
385
|
+
return merged;
|
|
386
|
+
};
|
|
82
387
|
/**
|
|
83
388
|
* Main transforms
|
|
84
389
|
*/
|
|
@@ -102,14 +407,43 @@ const isStructured = tableNode => Array.isArray(tableNode.content) &&
|
|
|
102
407
|
exports.default = () => tree => {
|
|
103
408
|
const transformer = (0, makeTransformer_1.default)({
|
|
104
409
|
table: node => {
|
|
105
|
-
//
|
|
410
|
+
// CSV/data source reference (spec §1672):
|
|
411
|
+
// =table data:<key> → resolve =data block with :key<key>
|
|
412
|
+
// =table file:<path> → defer to host reader (not implemented here)
|
|
413
|
+
const ref = detectSourceReference(node);
|
|
414
|
+
if (ref && ref.scheme === 'data') {
|
|
415
|
+
const dataBlock = findDataBlockByKey(tree, ref.target);
|
|
416
|
+
if (!dataBlock) {
|
|
417
|
+
// Rule 4: source not found → empty table (still a =table block)
|
|
418
|
+
console.warn(`[table] no =data block found for data:${ref.target} — rendered as empty`);
|
|
419
|
+
return { ...node, content: [] };
|
|
420
|
+
}
|
|
421
|
+
const mimeType = (0, config_1.default)(dataBlock, {}).getFirstValue('mime-type');
|
|
422
|
+
const isCsv = mimeType === 'text/csv';
|
|
423
|
+
const isTsv = mimeType === 'text/tab-separated-values';
|
|
424
|
+
if (isCsv || isTsv) {
|
|
425
|
+
const text = extractDataText(dataBlock);
|
|
426
|
+
const rows = isCsv ? parseCsv(text) : parseTsv(text);
|
|
427
|
+
if (rows.length === 0) {
|
|
428
|
+
console.warn(`[table] ${isCsv ? 'CSV' : 'TSV'} parse produced no rows for data:${ref.target} — rendered as empty`);
|
|
429
|
+
return { ...node, content: [] };
|
|
430
|
+
}
|
|
431
|
+
const filledNode = { ...node, content: csvToTableContent(rows) };
|
|
432
|
+
return normalizeCellCounts(filledNode, `table data:${ref.target}`);
|
|
433
|
+
}
|
|
434
|
+
// Rule 4: source not tabular → render as code block so content remains visible
|
|
435
|
+
console.warn(`[table] =data :key<${ref.target}> has non-tabular mime-type ${mimeType || '(none)'} — rendered as =code`);
|
|
436
|
+
return buildCodeFromDataBlock(node, dataBlock);
|
|
437
|
+
}
|
|
438
|
+
// structured mode: transform row children (wrap implicit cells), then
|
|
439
|
+
// apply Rule 2 cell count normalization.
|
|
106
440
|
if (isStructured(node)) {
|
|
107
441
|
const transformedContent = (node.content || []).map(c => {
|
|
108
442
|
if (c && c.name === 'row')
|
|
109
443
|
return wrapImplicitCells(c);
|
|
110
444
|
return c;
|
|
111
445
|
});
|
|
112
|
-
return { ...node, content: transformedContent };
|
|
446
|
+
return normalizeCellCounts({ ...node, content: transformedContent }, 'table');
|
|
113
447
|
}
|
|
114
448
|
let rows = [];
|
|
115
449
|
const collectValues = row => {
|
|
@@ -134,6 +468,8 @@ exports.default = () => tree => {
|
|
|
134
468
|
// split each row into lines
|
|
135
469
|
const lines = flattenDeep(rows.map(splitToLines));
|
|
136
470
|
const separators = flattenDeep(seps.map(splitToLines));
|
|
471
|
+
// Rule 3: warn on mixed separator types within a single table
|
|
472
|
+
detectMixedSeparators(lines);
|
|
137
473
|
// collect text rows
|
|
138
474
|
let textRows = [];
|
|
139
475
|
(0, makeTransformer_1.default)({
|
|
@@ -141,33 +477,48 @@ exports.default = () => tree => {
|
|
|
141
477
|
textRows.push(row.value);
|
|
142
478
|
},
|
|
143
479
|
})(node);
|
|
144
|
-
const columnTemplate = makeMask(lines, separators);
|
|
145
480
|
const makeBlock = (name, content, extra = {}) => {
|
|
146
481
|
return { ...extra, name, type: 'block', content: Array.isArray(content) ? content : [content] };
|
|
147
482
|
};
|
|
148
483
|
const makeRow = cells => makeBlock('row', cells);
|
|
149
484
|
const makeHeaderRow = cells => makeBlock('row', cells, { config: [{ name: 'header', value: true, type: 'boolean' }] });
|
|
150
485
|
const makeCell = text => makeBlock('cell', { type: 'text', value: text });
|
|
151
|
-
//
|
|
486
|
+
// Routing: per-line separator detection (Rule 1) is used only when a
|
|
487
|
+
// line with a visible separator (`|` or `+`) coexists with one that
|
|
488
|
+
// has only whitespace separation — the Scenario 2 case where the
|
|
489
|
+
// legacy positional mask collapses columns. Tables with a uniform
|
|
490
|
+
// separator, or with both visible kinds (pipe + plus) handled by the
|
|
491
|
+
// shared mask, fall back to the legacy positional template, which
|
|
492
|
+
// preserves continuation-line alignment in multi-line rows and keeps
|
|
493
|
+
// byte-for-byte AST/HTML output stable.
|
|
494
|
+
const columnTemplate = makeMask(lines, separators);
|
|
495
|
+
const seenSeparatorKinds = new Set(lines.map(detectLineSeparator));
|
|
496
|
+
const hasVisible = seenSeparatorKinds.has('pipe') || seenSeparatorKinds.has('plus');
|
|
497
|
+
const hasWhitespace = seenSeparatorKinds.has('whitespace');
|
|
498
|
+
const useMixedSplitting = hasVisible && hasWhitespace;
|
|
499
|
+
const splitToCells = (rowValue) => {
|
|
500
|
+
if (useMixedSplitting) {
|
|
501
|
+
const rowLines = rowValue.split(/\r?\n/).filter(l => l.trim() !== '');
|
|
502
|
+
if (rowLines.length <= 1)
|
|
503
|
+
return rowToCells(rowValue);
|
|
504
|
+
}
|
|
505
|
+
return extractColumnsByTemplate(rowValue, columnTemplate);
|
|
506
|
+
};
|
|
152
507
|
const res = (0, makeTransformer_1.default)({
|
|
153
508
|
'row:text': row => {
|
|
154
509
|
if (textRows.length == 1) {
|
|
155
|
-
//
|
|
510
|
+
// No separator blocks: each line of the only text row becomes its own row
|
|
156
511
|
const textRowsLines = flattenDeep([row.value].map(splitToLines));
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
512
|
+
if (useMixedSplitting) {
|
|
513
|
+
return textRowsLines.map(line => makeRow(splitLineCells(line).map(makeCell)));
|
|
514
|
+
}
|
|
515
|
+
return textRowsLines.map(line => makeRow(extractColumnsByTemplate(line, columnTemplate).map(makeCell)));
|
|
161
516
|
}
|
|
162
|
-
|
|
163
|
-
return makeRow(cols.map(makeCell));
|
|
164
|
-
},
|
|
165
|
-
'head:text': head => {
|
|
166
|
-
const cols = extractColumnsByTemplate(head.value, columnTemplate);
|
|
167
|
-
return makeHeaderRow(cols.map(makeCell));
|
|
517
|
+
return makeRow(splitToCells(row.value).map(makeCell));
|
|
168
518
|
},
|
|
519
|
+
'head:text': head => makeHeaderRow(splitToCells(head.value).map(makeCell)),
|
|
169
520
|
})(node);
|
|
170
|
-
return res;
|
|
521
|
+
return normalizeCellCounts(res, 'table');
|
|
171
522
|
},
|
|
172
523
|
});
|
|
173
524
|
return transformer(tree, {});
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { PodliteDocument, PodNode } from './index';
|
|
2
|
+
/**
|
|
3
|
+
* Minimal corpus item that the selector engine needs. Concrete consumers
|
|
4
|
+
* (publisher's `publishRecord`, editor preview, etc.) supply richer
|
|
5
|
+
* objects; only `file` and `node` are read here.
|
|
6
|
+
*/
|
|
7
|
+
export declare type SelectorDoc = {
|
|
8
|
+
file: string;
|
|
9
|
+
node: PodNode | PodliteDocument;
|
|
10
|
+
};
|
|
11
|
+
export declare type ParsedSelector = {
|
|
12
|
+
scheme?: string;
|
|
13
|
+
document?: string;
|
|
14
|
+
anchor?: string;
|
|
15
|
+
blockFilters: string[];
|
|
16
|
+
};
|
|
17
|
+
export declare const parseSelector: (selector: string) => ParsedSelector | undefined;
|
|
18
|
+
export declare const runSelector: <T extends SelectorDoc>(selector: string, docs: T[]) => PodNode[] | T[];
|