TrialAndErrorOrg/parsers

[ooxast-util-to-jast] Store information about column alignment in tabular

Closed this issue · 1 comments

[ooxast-util-to-jast] Store information about column alignment in tabular

error out while underfull ones are fine

https://github.com/JournalOfTrialAndError/JOTE/blob/5f8ab764a09da5debb4200ac3a996ced2ca2bbf4/libs/ooxast/ooxast-util-to-jast/src/lib/handlers/table.ts#L16

// based on https://github.com/syntax-tree/hast-util-to-mdast/blob/main/lib/handlers/em

import { Table, isElement, Element, Tr, Col } from 'ooxast'
import { all } from '../all'
import { J, Node } from '../types'
import { visit as origVisit } from 'unist-util-visit'
import { CommandArg } from 'jast'

// try to turn of typechecking for visit as it it bugged
// https://github.com/syntax-tree/unist-util-visit/issues/33
const visit = origVisit as any
export function table(j: J, table: Table) {
  let columns: string[] = []
  let hasCols = false
  // tables can be def'd in terms of cols or rows
  // TODO: [ooxast-util-to-jast] Store information about column alignment in tabular
  visit(
    table,
    (node: Node) => isElement(node) && ['col', 'tr'].includes(node.name),
    (node: Col | Tr) => {
      if (node.name === 'col') {
        hasCols = true
        columns.push('c')
        return
      }

      if (hasCols) return
      let tempCols: string[] = []

      node?.children?.forEach((child) => {
        isElement(child) && child.name === 'td' && tempCols.push('c')
      })
      // Just make the table as wide as it needs to be, overfull tables
      // error out while  underfull ones are fine
      if (tempCols.length > columns.length) columns = tempCols
      tempCols = []
      return
    }
  )

  const colAlignment = columns.join(` ${j.columnSeparator ? '|' : ''} `)
  const colAlignArg: CommandArg = {
    type: 'commandArg',
    children: [{ type: 'text', value: colAlignment }],
  }

  const contents = all(j, table)
  contents.unshift(colAlignArg)

  return { type: 'environment', name: 'tabular', children: contents }
}

ee96e422f7f1f07b82eafc9fda2d9a044c20d64f