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

572 lines · 16743 bytes

19 symbols in this file
  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, anchor: string): string {
 16  return `<tbody class="table-more-toggle" data-table-more="${anchor}">\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 isTableMoreCloser(t: any): boolean {
127  return t?.type === 'html_block' && typeof t.content === 'string' &&
128    t.content.includes('</tbody>')
129}
130
131// Owners for chained <more>; cross-tbody ^^ clones via emitted check.
132function chainedRowOwners(tokens: any[]): any[] {
133  let closeIdx = -1
134  for (let k = tokens.length - 1; k >= 0; k--) {
135    if (tokens[k].type === 'table_close') {
136      closeIdx = k
137      break
138    }
139  }
140  if (closeIdx === -1) return []
141  const openIdx = findTableOpen(tokens, closeIdx)
142  if (openIdx === -1) return []
143  const rows: any[][] = []
144  let cur: any[] | null = null
145  for (let k = openIdx; k < tokens.length; k++) {
146    const t = tokens[k]
147    if (t.type === 'tr_open') cur = []
148    else if (t.type === 'tr_close') {
149      if (cur) rows.push(cur)
150      cur = null
151    } else if (
152      cur && (t.type === 'td_open' || t.type === 'th_open')
153    ) {
154      cur.push(t)
155    }
156  }
157  const remaining: number[] = []
158  const holder: any[] = []
159  let owners: any[] = []
160  for (const row of rows) {
161    const next: any[] = []
162    let c = 0
163    for (const td of row) {
164      while ((remaining[c] ?? 0) > 0) {
165        next[c] = holder[c]
166        c++
167      }
168      const w = colspanOf(td)
169      for (let k = 0; k < w; k++) next[c + k] = td
170      const rs = rowspanOf(td)
171      if (rs > 1) {
172        for (let k = 0; k < w; k++) {
173          remaining[c + k] = rs
174          holder[c + k] = td
175        }
176      }
177      c += w
178    }
179    while ((remaining[c] ?? 0) > 0) {
180      next[c] = holder[c]
181      c++
182    }
183    for (let k = 0; k < remaining.length; k++) {
184      if (remaining[k] > 0) remaining[k]--
185    }
186    owners = next
187  }
188  return owners
189}
190
191function cloneCellContent(state: any, owner: any) {
192  const tokens = state.tokens
193  const idx = tokens.indexOf(owner)
194  if (idx === -1) return
195  const end = tokens.length
196  let depth = 1
197  for (let k = idx + 1; k < end && depth > 0; k++) {
198    const t = tokens[k]
199    const isOpen = (t.type === 'td_open' || t.type === 'th_open') &&
200      t.nesting === 1
201    const isClose = (t.type === 'td_close' || t.type === 'th_close') &&
202      t.nesting === -1
203    if (isOpen) {
204      depth++
205    } else if (isClose) {
206      depth--
207      if (depth === 0) break
208    } else {
209      const cp = state.push(t.type, t.tag, t.nesting)
210      cp.attrs = t.attrs ? t.attrs.map((a: any) => [a[0], a[1]]) : t.attrs
211      cp.content = t.content
212      cp.map = t.map ? t.map.slice() : t.map
213      cp.children = []
214      cp.block = t.block
215      cp.info = t.info
216      cp.markup = t.markup
217      cp.meta = t.meta ? { ...t.meta } : t.meta
218    }
219  }
220}
221
222function findTableClose(tokens: any[], from: number): number {
223  let depth = 0
224  for (let j = from; j < tokens.length; j++) {
225    if (tokens[j].type === 'table_open') depth++
226    else if (tokens[j].type === 'table_close') {
227      depth--
228      if (depth === 0) return j
229    }
230  }
231  return -1
232}
233
234function countCells(
235  tokens: any[],
236  from: number,
237  to: number,
238  type: string
239): number {
240  let count = 0
241  for (let k = from; k < to; k++) {
242    if (tokens[k].type === type) count++
243  }
244  return count
245}
246
247function findTableOpen(tokens: any[], tableCloseIdx: number): number {
248  let depth = 0
249  for (let k = tableCloseIdx; k >= 0; k--) {
250    if (tokens[k].type === 'table_close') depth++
251    else if (tokens[k].type === 'table_open') {
252      if (depth <= 1) return k
253      depth--
254    }
255  }
256  return -1
257}
258
259function countTableCols(tokens: any[], tableCloseIdx: number): number {
260  const openIdx = findTableOpen(tokens, tableCloseIdx)
261  if (openIdx === -1) return 0
262  let theadOpen = -1
263  let theadClose = -1
264  for (let k = openIdx; k < tableCloseIdx; k++) {
265    if (tokens[k].type === 'thead_open' && theadOpen === -1) {
266      theadOpen = k
267    }
268    if (tokens[k].type === 'thead_close') {
269      theadClose = k
270      break
271    }
272  }
273  if (theadOpen !== -1 && theadClose !== -1) {
274    return countCells(tokens, theadOpen, theadClose, 'th_open')
275  }
276  return 0
277}
278
279// One global serial anchor per <more> section, in document order.
280function nextSectionAnchor(state: any): string {
281  const n = state.env.__tableMoreCount ?? 0
282  state.env.__tableMoreCount = n + 1
283  return String(n)
284}
285
286export function tableMorePlugin(md: MarkdownIt): void {
287  md.block.ruler.before(
288    'html_block',
289    'table_more_marker',
290    (state, startLine, endLine, silent) => {
291      const pos = state.bMarks[startLine] + state.tShift[startLine]
292      const max = state.eMarks[startLine]
293      if (!MARKER_RE.test(state.src.slice(pos, max).trim())) {
294        return false
295      }
296      // Marker after table or previous <more> section; else literal text.
297      const prev = state.tokens[state.tokens.length - 1]
298      const afterTable = !!prev && prev.type === 'table_close'
299      let afterChained = !!prev && isTableMoreCloser(prev)
300      if (afterChained) {
301        // Guard against arbitrary </tbody> html.
302        let lastClose = -1
303        for (let k = state.tokens.length - 1; k >= 0; k--) {
304          if (state.tokens[k].type === 'table_close') {
305            lastClose = k
306            break
307          }
308        }
309        let hasMarker = false
310        if (lastClose !== -1) {
311          for (let k = lastClose + 1; k < state.tokens.length; k++) {
312            if (state.tokens[k].type === 'table_more') {
313              hasMarker = true
314              break
315            }
316          }
317        }
318        if (!hasMarker) afterChained = false
319      }
320      if (!afterTable && !afterChained) return false
321      if (silent) return true
322
323      // Full table follows: let the table parser handle it, merge later.
324      // Chained sections support bare rows only.
325      let line = startLine + 1
326      while (line < endLine && getLine(state, line).trim() === '') line++
327      const next1 = line < endLine ? getLine(state, line) : ''
328      const next2 = line + 1 < endLine ? getLine(state, line + 1) : ''
329      const fullTableFollows = isPipeLine(next1) && isDelimiterRow(next2)
330      if (afterChained && fullTableFollows) return false
331
332      let up: any[] = afterTable
333        ? prevRowCells(state.tokens)
334        : chainedRowOwners(state.tokens)
335      const emitted = new Set(state.tokens)
336      const marker = state.push('table_more', '', 0)
337      marker.map = [startLine, startLine + 1]
338      marker.content = ''
339
340      if (fullTableFollows) {
341        state.line = startLine + 1
342        return true
343      }
344
345      let rows = 0
346      while (line < endLine && isPipeLine(getLine(state, line))) {
347        const cells = splitCells(getLine(state, line))
348        const trOpen = state.push('tr_open', 'tr', 1)
349        trOpen.map = [line, line + 1]
350        const cur: any[] = []
351        let c = 0
352        let openTd: any = null
353        let openStart = 0
354        let span = 1
355        const flush = () => {
356          if (openTd) {
357            if (span > 1) openTd.attrSet('colspan', span)
358            for (let k = 0; k < span; k++) cur[openStart + k] = openTd
359            openTd = null
360            span = 1
361          }
362        }
363        for (const raw of cells) {
364          if (raw.trim() === '^^' && c < up.length && up[c]) {
365            flush()
366            const above = up[c]
367            const w = colspanOf(above)
368            if (emitted.has(above)) {
369              const td = state.push(
370                above.tag === 'th' ? 'th_open' : 'td_open',
371                above.tag,
372                1
373              )
374              td.attrs = above.attrs
375                ? above.attrs
376                  .filter((a: any) => a[0] !== 'rowspan')
377                  .map((a: any) => [a[0], a[1]])
378                : []
379              if (w > 1) td.attrSet('colspan', w)
380              cloneCellContent(state, above)
381              state.push(
382                above.tag === 'th' ? 'th_close' : 'td_close',
383                above.tag,
384                -1
385              )
386              for (let k = 0; k < w; k++) cur[c + k] = td
387            } else {
388              const rs = rowspanOf(above)
389              above.attrSet('rowspan', rs + 1)
390              for (let k = 0; k < w; k++) cur[c + k] = above
391            }
392            c += w
393            continue
394          }
395          if (raw === '' && openTd) {
396            span++
397            c++
398            continue
399          }
400          flush()
401          const td = state.push('td_open', 'td', 1)
402          td.attrs = []
403          const inline = state.push('inline', '', 0)
404          inline.content = raw.trim()
405          inline.map = [line, line + 1]
406          inline.children = []
407          state.push('td_close', 'td', -1)
408          openTd = td
409          openStart = c
410          c++
411        }
412        flush()
413        state.push('tr_close', 'tr', -1)
414        up = cur
415        rows++
416        line++
417      }
418
419      if (rows > 0) {
420        const closer = state.push('html_block', '', 0)
421        closer.map = [line, line]
422        closer.content = '</tbody>\n'
423      }
424      state.line = line
425      return true
426    }
427  )
428
429  // Unmatched markers (no second table) render as nothing.
430  md.renderer.rules.table_more = () => ''
431
432  md.core.ruler.after('block', 'table_more_merge', (state: any) => {
433    const tokens = state.tokens as any[]
434    let i = 0
435    while (i < tokens.length) {
436      if (
437        tokens[i].type !== 'table_close' ||
438        tokens[i + 1]?.type !== 'table_more'
439      ) {
440        i++
441        continue
442      }
443
444      // full second table follows the marker.
445      if (tokens[i + 2]?.type === 'table_open') {
446        const openIdx = i + 2
447        const closeIdx = findTableClose(tokens, openIdx)
448        if (closeIdx === -1) {
449          i++
450          continue
451        }
452
453        let theadOpen = -1
454        let theadClose = -1
455        for (let k = openIdx; k < closeIdx; k++) {
456          if (tokens[k].type === 'thead_open' && theadOpen === -1) {
457            theadOpen = k
458          }
459          if (tokens[k].type === 'thead_close') {
460            theadClose = k
461            break
462          }
463        }
464        const bodyStart = theadClose !== -1 ? theadClose + 1 : openIdx + 1
465        const kept = tokens.slice(bodyStart, closeIdx)
466
467        let cols = theadOpen !== -1 && theadClose !== -1
468          ? countCells(tokens, theadOpen, theadClose, 'th_open')
469          : 0
470        if (cols <= 0) cols = countTableCols(tokens, i)
471        if (cols <= 0) cols = 1
472
473        const hidden = kept.filter((t) => t.type === 'tr_open').length
474        if (hidden === 0) {
475          i = closeIdx + 1
476          continue
477        }
478
479        for (const t of kept) {
480          if (t.type === 'tbody_open') t.attrJoin('class', 'table-more-hidden')
481        }
482
483        // Toggle + hidden rows go inside the first table, before its close.
484        const marker = tokens[i + 1]
485        marker.type = 'html_block'
486        marker.tag = ''
487        marker.nesting = 0
488        marker.attrs = null
489        marker.children = null
490        marker.info = ''
491        marker.markup = ''
492        marker.content = buildToggleHtml(cols, nextSectionAnchor(state))
493
494        const merged = tokens.slice(0, i)
495        merged.push(marker)
496        merged.push(...kept)
497        merged.push(tokens[i])
498        merged.push(...tokens.slice(closeIdx + 1))
499        tokens.splice(0, tokens.length, ...merged)
500        i += 2 + kept.length
501        continue
502      }
503
504      // Chained bare rows: one toggle per <more> section.
505      if (tokens[i + 2]?.type === 'tr_open') {
506        let j = i + 1
507        const sections: { marker: any; kept: any[]; closer: any }[] = []
508        while (tokens[j]?.type === 'table_more') {
509          const rStart = j + 1
510          if (tokens[rStart]?.type !== 'tr_open') break
511          let k = rStart
512          while (k < tokens.length && ROW_TOKEN_TYPES.has(tokens[k].type)) k++
513          const closer = tokens[k]
514          if (!isTableMoreCloser(closer)) break
515          const kept = tokens.slice(rStart, k)
516          const hidden = kept.filter((t) => t.type === 'tr_open').length
517          if (hidden === 0) {
518            j = k + 1
519            continue
520          }
521          sections.push({ marker: tokens[j], kept, closer })
522          j = k + 1
523        }
524        if (sections.length === 0) {
525          i++
526          continue
527        }
528
529        let cols = countTableCols(tokens, i)
530        if (cols <= 0) {
531          const firstKept = sections[0].kept
532          const firstTr = firstKept.findIndex((t) => t.type === 'tr_open')
533          const end = firstKept.findIndex(
534            (t, idx) => idx > firstTr && t.type === 'tr_close'
535          )
536          cols = countCells(
537            firstKept,
538            firstTr,
539            end === -1 ? firstKept.length : end,
540            'td_open'
541          )
542        }
543        if (cols <= 0) cols = 1
544
545        const segment: any[] = []
546        for (const s of sections) {
547          const m = s.marker
548          m.type = 'html_block'
549          m.tag = ''
550          m.nesting = 0
551          m.attrs = null
552          m.children = null
553          m.info = ''
554          m.markup = ''
555          m.content = buildToggleHtml(cols, nextSectionAnchor(state)) +
556            '<tbody class="table-more-hidden">\n'
557          segment.push(m, ...s.kept, s.closer)
558        }
559
560        const merged = tokens.slice(0, i)
561        merged.push(...segment)
562        merged.push(tokens[i])
563        merged.push(...tokens.slice(j))
564        tokens.splice(0, tokens.length, ...merged)
565        i += segment.length + 1
566        continue
567      }
568
569      i++
570    }
571  })
572}