tty-table browser example

tty-table in the browser

HTML

<script src="https://cdn.jsdelivr.net/npm/tty-table@7/dist/browser/tty-table.global.js"></script>

JavaScript

const Table = TtyTable.default

let header = [
  {
    value: "item",
    headerColor: "cyan",
    color: "white",
    align: "left",
    width: 20
  },
  {
    value: "price",
    color: "red",
    width: 10,
    formatter: function (value) {
      var str = `$${value.toFixed(2)}`
      if (value > 5) {
        str = this.style(str, "green")
      }
      return str
    }
  },
  {
    alias: "Is organic?",
    value: "organic",
    width: 15,
    formatter: function (value) {
      if (value === "yes") {
        value = this.style(value, "bgGreen", "black")
      } else {
        value = this.style(value, "bgRed", "white")
      }
      return value
    }
  }
]

const rows = [
  ["tallarin verde", 5.50, "yes"],
  ["aji de gallina", 4.50, "no"],
]

const footer = [
  "TOTAL",
  function (cellValue, columnIndex, rowIndex, rowData) {
    let total = rowData.reduce((prev, curr) => prev + curr[1], 0).toFixed(2)
    return `$${total}`
  },
  function (cellValue, columnIndex, rowIndex, rowData) {
    let total = rowData.reduce((prev, curr) => prev + ((curr[2] === "yes") ? 1 : 0), 0)
    return `${(total / rowData.length * 100).toFixed(2)}%`
  }
]

const options = {
  borderStyle: "solid",
  borderColor: "green",
  paddingBottom: 0,
  headerAlign: "center",
  align: "center",
  color: "white",
  truncate: "..."
}

let ANSI = Table(header, rows, footer, options).render()
console.log(ANSI)

document.body.insertAdjacentHTML("beforeend", "<pre id=\"example\"></pre>")

// ansi_up v6 is ESM-only; dynamic import works from the classic fiddle panel
import("https://cdn.jsdelivr.net/npm/ansi_up@6/+esm").then(({ AnsiUp }) => {
  const ansi_up = new AnsiUp()
  document.getElementById("example").innerHTML = ansi_up.ansi_to_html(ANSI)
})