docs/.vitepress/configs/markdown/tableMore.ts

c739d46770b526bab469834941ec98439942ca2c
wotaku/docs/.vitepress/configs/markdown/tableMore.ts

477 lines · 13910 bytes

  1import type MarkdownIt from 'markdown-it'
  2
  3const MARKER_RE = /^<more\s*\/?>$/i
  4
  5const ROW_TOKEN_TYPES = new Set([
  6  'tr_open',
  7  'tr_close',
  8  'td_open',
  9  'td_close',
 10  'th_open',
 11  'th_close',
 12  'inline'
 13])
 14
 15function buildToggleHtml(cols: number): string {
 16  return `<tbody class="table-more-toggle">\n` +
 17    `<tr class="table-more-toggle-row">\n` +
 18    `<td colspan="${cols}">\n` +
 19    `<label class="table-more-label">\n` +
 20    `<input type="checkbox" class="table-more-checkbox" aria-label="Toggle more rows">\n` +
 21    `<span class="table-more-text table-more-text--more">Show more</span>\n` +
 22    `<span class="table-more-text table-more-text--less">Show less</span>\n` +
 23    `<span class="table-more-icon i-mdi-chevron-down" aria-hidden="true"></span>\n` +
 24    `</label>\n</td>\n</tr>\n</tbody>\n`
 25}
 26
 27function getLine(state: any, n: number): string {
 28  return state.src.slice(
 29    state.bMarks[n] + state.tShift[n],
 30    state.eMarks[n]
 31  )
 32}
 33
 34function isPipeLine(line: string): boolean {
 35  return line.trim().startsWith('|')
 36}
 37
 38function splitCells(line: string): string[] {
 39  let s = line.trim()
 40  if (s.startsWith('|')) s = s.slice(1)
 41  if (s.endsWith('|') && !s.endsWith('\\|')) s = s.slice(0, -1)
 42  return s.split(/(?<!\\)\|/).map((c) =>
 43    c.replace(/\\\|/g, '|').replace(/\\\\/g, '\\')
 44  )
 45}
 46
 47function isDelimiterRow(line: string): boolean {
 48  const cells = splitCells(line)
 49  return cells.length > 0 &&
 50    cells.every((c) => /^:?-+:?$/.test(c.trim()))
 51}
 52
 53function colspanOf(td: any): number {
 54  const cols = td ? Number(td.attrGet('colspan')) : NaN
 55  return Number.isFinite(cols) && cols > 0 ? Math.floor(cols) : 1
 56}
 57
 58function rowspanOf(td: any): number {
 59  const rs = td ? Number(td.attrGet('rowspan')) : NaN
 60  return Number.isFinite(rs) && rs > 0 ? Math.floor(rs) : 1
 61}
 62
 63function prevRowCells(tokens: any[]): any[] {
 64  let end = tokens.length - 1
 65  while (end >= 0 && tokens[end].type === 'table_close') end--
 66  if (end < 0 || tokens[end].type !== 'tbody_close') return []
 67  let open = end
 68  let depth = 0
 69  while (open >= 0) {
 70    if (tokens[open].type === 'tbody_close') depth++
 71    else if (tokens[open].type === 'tbody_open') {
 72      depth--
 73      if (depth === 0) break
 74    }
 75    open--
 76  }
 77  if (open < 0) return []
 78  const rows: any[][] = []
 79  let cur: any[] | null = null
 80  for (let k = open + 1; k < end; k++) {
 81    const t = tokens[k]
 82    if (t.type === 'tr_open') cur = []
 83    else if (t.type === 'tr_close') {
 84      if (cur) rows.push(cur)
 85      cur = null
 86    } else if (
 87      cur && (t.type === 'td_open' || t.type === 'th_open')
 88    ) {
 89      cur.push(t)
 90    }
 91  }
 92  const remaining: number[] = []
 93  const holder: any[] = []
 94  let owners: any[] = []
 95  for (const row of rows) {
 96    const next: any[] = []
 97    let c = 0
 98    for (const td of row) {
 99      while ((remaining[c] ?? 0) > 0) {
100        next[c] = holder[c]
101        c++
102      }
103      const w = colspanOf(td)
104      for (let k = 0; k < w; k++) next[c + k] = td
105      const rs = rowspanOf(td)
106      if (rs > 1) {
107        for (let k = 0; k < w; k++) {
108          remaining[c + k] = rs
109          holder[c + k] = td
110        }
111      }
112      c += w
113    }
114    while ((remaining[c] ?? 0) > 0) {
115      next[c] = holder[c]
116      c++
117    }
118    for (let k = 0; k < remaining.length; k++) {
119      if (remaining[k] > 0) remaining[k]--
120    }
121    owners = next
122  }
123  return owners
124}
125
126function cloneCellContent(state: any, owner: any) {
127  const tokens = state.tokens
128  const idx = tokens.indexOf(owner)
129  if (idx === -1) return
130  const end = tokens.length
131  let depth = 1
132  for (let k = idx + 1; k < end && depth > 0; k++) {
133    const t = tokens[k]
134    const isOpen = (t.type === 'td_open' || t.type === 'th_open') &&
135      t.nesting === 1
136    const isClose = (t.type === 'td_close' || t.type === 'th_close') &&
137      t.nesting === -1
138    if (isOpen) {
139      depth++
140    } else if (isClose) {
141      depth--
142      if (depth === 0) break
143    } else {
144      const cp = state.push(t.type, t.tag, t.nesting)
145      cp.attrs = t.attrs ? t.attrs.map((a: any) => [a[0], a[1]]) : t.attrs
146      cp.content = t.content
147      cp.map = t.map ? t.map.slice() : t.map
148      cp.children = []
149      cp.block = t.block
150      cp.info = t.info
151      cp.markup = t.markup
152      cp.meta = t.meta ? { ...t.meta } : t.meta
153    }
154  }
155}
156
157function findTableClose(tokens: any[], from: number): number {
158  let depth = 0
159  for (let j = from; j < tokens.length; j++) {
160    if (tokens[j].type === 'table_open') depth++
161    else if (tokens[j].type === 'table_close') {
162      depth--
163      if (depth === 0) return j
164    }
165  }
166  return -1
167}
168
169function countCells(
170  tokens: any[],
171  from: number,
172  to: number,
173  type: string
174): number {
175  let count = 0
176  for (let k = from; k < to; k++) {
177    if (tokens[k].type === type) count++
178  }
179  return count
180}
181
182function findTableOpen(tokens: any[], tableCloseIdx: number): number {
183  let depth = 0
184  for (let k = tableCloseIdx; k >= 0; k--) {
185    if (tokens[k].type === 'table_close') depth++
186    else if (tokens[k].type === 'table_open') {
187      if (depth <= 1) return k
188      depth--
189    }
190  }
191  return -1
192}
193
194function countTableCols(tokens: any[], tableCloseIdx: number): number {
195  const openIdx = findTableOpen(tokens, tableCloseIdx)
196  if (openIdx === -1) return 0
197  let theadOpen = -1
198  let theadClose = -1
199  for (let k = openIdx; k < tableCloseIdx; k++) {
200    if (tokens[k].type === 'thead_open' && theadOpen === -1) {
201      theadOpen = k
202    }
203    if (tokens[k].type === 'thead_close') {
204      theadClose = k
205      break
206    }
207  }
208  if (theadOpen !== -1 && theadClose !== -1) {
209    return countCells(tokens, theadOpen, theadClose, 'th_open')
210  }
211  return 0
212}
213
214function stampTableAnchor(state: any, tokens: any[], tableCloseIdx: number) {
215  const openIdx = findTableOpen(tokens, tableCloseIdx)
216  if (openIdx === -1) return
217  const n = state.env.__tableMoreCount ?? 0
218  state.env.__tableMoreCount = n + 1
219  tokens[openIdx].attrJoin('data-table-more', String(n))
220}
221
222export function tableMorePlugin(md: MarkdownIt): void {
223  md.block.ruler.before(
224    'html_block',
225    'table_more_marker',
226    (state, startLine, endLine, silent) => {
227      const pos = state.bMarks[startLine] + state.tShift[startLine]
228      const max = state.eMarks[startLine]
229      if (!MARKER_RE.test(state.src.slice(pos, max).trim())) {
230        return false
231      }
232      // Only a marker directly after a table; otherwise literal text.
233      const prev = state.tokens[state.tokens.length - 1]
234      if (!prev || prev.type !== 'table_close') return false
235      if (silent) return true
236
237      // Full table follows: let the table parser handle it, merge later.
238      let line = startLine + 1
239      while (line < endLine && getLine(state, line).trim() === '') line++
240      const next1 = line < endLine ? getLine(state, line) : ''
241      const next2 = line + 1 < endLine ? getLine(state, line + 1) : ''
242      const fullTableFollows = isPipeLine(next1) && isDelimiterRow(next2)
243
244      let up: any[] = prevRowCells(state.tokens)
245      const emitted = new Set(state.tokens)
246      const marker = state.push('table_more', '', 0)
247      marker.map = [startLine, startLine + 1]
248      marker.content = ''
249
250      if (fullTableFollows) {
251        state.line = startLine + 1
252        return true
253      }
254
255      let rows = 0
256      while (line < endLine && isPipeLine(getLine(state, line))) {
257        const cells = splitCells(getLine(state, line))
258        const trOpen = state.push('tr_open', 'tr', 1)
259        trOpen.map = [line, line + 1]
260        const cur: any[] = []
261        let c = 0
262        let openTd: any = null
263        let openStart = 0
264        let span = 1
265        const flush = () => {
266          if (openTd) {
267            if (span > 1) openTd.attrSet('colspan', span)
268            for (let k = 0; k < span; k++) cur[openStart + k] = openTd
269            openTd = null
270            span = 1
271          }
272        }
273        for (const raw of cells) {
274          if (raw.trim() === '^^' && c < up.length && up[c]) {
275            flush()
276            const above = up[c]
277            const w = colspanOf(above)
278            if (emitted.has(above)) {
279              const td = state.push(
280                above.tag === 'th' ? 'th_open' : 'td_open',
281                above.tag,
282                1
283              )
284              td.attrs = above.attrs
285                ? above.attrs
286                  .filter((a: any) => a[0] !== 'rowspan')
287                  .map((a: any) => [a[0], a[1]])
288                : []
289              if (w > 1) td.attrSet('colspan', w)
290              cloneCellContent(state, above)
291              state.push(
292                above.tag === 'th' ? 'th_close' : 'td_close',
293                above.tag,
294                -1
295              )
296              for (let k = 0; k < w; k++) cur[c + k] = td
297            } else {
298              const rs = rowspanOf(above)
299              above.attrSet('rowspan', rs + 1)
300              for (let k = 0; k < w; k++) cur[c + k] = above
301            }
302            c += w
303            continue
304          }
305          if (raw === '' && openTd) {
306            span++
307            c++
308            continue
309          }
310          flush()
311          const td = state.push('td_open', 'td', 1)
312          td.attrs = []
313          const inline = state.push('inline', '', 0)
314          inline.content = raw.trim()
315          inline.map = [line, line + 1]
316          inline.children = []
317          state.push('td_close', 'td', -1)
318          openTd = td
319          openStart = c
320          c++
321        }
322        flush()
323        state.push('tr_close', 'tr', -1)
324        up = cur
325        rows++
326        line++
327      }
328
329      if (rows > 0) {
330        const closer = state.push('html_block', '', 0)
331        closer.map = [line, line]
332        closer.content = '</tbody>\n'
333      }
334      state.line = line
335      return true
336    }
337  )
338
339  // Unmatched markers (no second table) render as nothing.
340  md.renderer.rules.table_more = () => ''
341
342  md.core.ruler.after('block', 'table_more_merge', (state: any) => {
343    const tokens = state.tokens as any[]
344    let i = 0
345    while (i < tokens.length) {
346      if (
347        tokens[i].type !== 'table_close' ||
348        tokens[i + 1]?.type !== 'table_more'
349      ) {
350        i++
351        continue
352      }
353
354      // full second table follows the marker.
355      if (tokens[i + 2]?.type === 'table_open') {
356        const openIdx = i + 2
357        const closeIdx = findTableClose(tokens, openIdx)
358        if (closeIdx === -1) {
359          i++
360          continue
361        }
362
363        let theadOpen = -1
364        let theadClose = -1
365        for (let k = openIdx; k < closeIdx; k++) {
366          if (tokens[k].type === 'thead_open' && theadOpen === -1) {
367            theadOpen = k
368          }
369          if (tokens[k].type === 'thead_close') {
370            theadClose = k
371            break
372          }
373        }
374        const bodyStart = theadClose !== -1 ? theadClose + 1 : openIdx + 1
375        const kept = tokens.slice(bodyStart, closeIdx)
376
377        let cols = theadOpen !== -1 && theadClose !== -1
378          ? countCells(tokens, theadOpen, theadClose, 'th_open')
379          : 0
380        if (cols <= 0) cols = countTableCols(tokens, i)
381        if (cols <= 0) cols = 1
382
383        const hidden = kept.filter((t) => t.type === 'tr_open').length
384        if (hidden === 0) {
385          i = closeIdx + 1
386          continue
387        }
388
389        for (const t of kept) {
390          if (t.type === 'tbody_open') t.attrJoin('class', 'table-more-hidden')
391        }
392
393        stampTableAnchor(state, tokens, i)
394
395        // Toggle + hidden rows go inside the first table, before its close.
396        const marker = tokens[i + 1]
397        marker.type = 'html_block'
398        marker.tag = ''
399        marker.nesting = 0
400        marker.attrs = null
401        marker.children = null
402        marker.info = ''
403        marker.markup = ''
404        marker.content = buildToggleHtml(cols)
405
406        const merged = tokens.slice(0, i)
407        merged.push(marker)
408        merged.push(...kept)
409        merged.push(tokens[i])
410        merged.push(...tokens.slice(closeIdx + 1))
411        tokens.splice(0, tokens.length, ...merged)
412        i += 2 + kept.length
413        continue
414      }
415
416      // bare continuation rows follow the marker.
417      if (tokens[i + 2]?.type === 'tr_open') {
418        let j = i + 2
419        while (j < tokens.length && ROW_TOKEN_TYPES.has(tokens[j].type)) j++
420        const closer = tokens[j]
421        if (
422          !closer || closer.type !== 'html_block' ||
423          !closer.content.includes('</tbody>')
424        ) {
425          i++
426          continue
427        }
428        const kept = tokens.slice(i + 2, j)
429        const hidden = kept.filter((t) => t.type === 'tr_open').length
430        if (hidden === 0) {
431          tokens.splice(i + 1, j - i)
432          continue
433        }
434
435        let cols = countTableCols(tokens, i)
436        if (cols <= 0) {
437          const firstTr = kept.findIndex((t) => t.type === 'tr_open')
438          const end = kept.findIndex(
439            (t, idx) => idx > firstTr && t.type === 'tr_close'
440          )
441          cols = countCells(
442            kept,
443            firstTr,
444            end === -1 ? kept.length : end,
445            'td_open'
446          )
447        }
448        if (cols <= 0) cols = 1
449
450        stampTableAnchor(state, tokens, i)
451
452        const marker = tokens[i + 1]
453        marker.type = 'html_block'
454        marker.tag = ''
455        marker.nesting = 0
456        marker.attrs = null
457        marker.children = null
458        marker.info = ''
459        marker.markup = ''
460        marker.content = buildToggleHtml(cols) +
461          '<tbody class="table-more-hidden">\n'
462
463        // Move the toggle + bare rows inside the first table.
464        const segment = tokens.slice(i + 1, j + 1)
465        const merged = tokens.slice(0, i)
466        merged.push(...segment)
467        merged.push(tokens[i])
468        merged.push(...tokens.slice(j + 1))
469        tokens.splice(0, tokens.length, ...merged)
470        i += segment.length + 1
471        continue
472      }
473
474      i++
475    }
476  })
477}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form