#!/bin/sh
# Upstream runs its suite through vitest, which Debian does not ship. Build a
# table with the package's own schema helpers and check the resulting map.
set -eu

# NODE_PATH does not apply to ESM imports, and during the build pkg-js-tools
# has not linked anything yet, so provide the modules the test imports.
mkdir -p node_modules
[ -e node_modules/prosemirror-tables ] || ln -s ../. node_modules/prosemirror-tables
for m in prosemirror-model prosemirror-view prosemirror-state prosemirror-transform prosemirror-keymap orderedmap w3c-keyname; do
	[ -e "node_modules/$m" ] || ln -s "/usr/share/nodejs/$m" "node_modules/$m"
done

cat > check.mjs <<'JS'
import {Schema} from "prosemirror-model"
import {tableNodes, TableMap} from "prosemirror-tables"

const nodes = tableNodes({tableGroup: "block", cellContent: "paragraph+"})
const schema = new Schema({
  nodes: {
    doc: {content: "block+"},
    ...nodes,
    paragraph: {content: "text*", toDOM: () => ["p", 0]},
    text: {},
  },
})

const cell = text => ({
  type: "table_cell",
  content: [{type: "paragraph", content: [{type: "text", text}]}],
})
const row = (...cells) => ({type: "table_row", content: cells})

const table = schema.nodeFromJSON({
  type: "table",
  content: [row(cell("a"), cell("b")), row(cell("c"), cell("d"))],
})
const map = TableMap.get(table)
if (map.width !== 2 || map.height !== 2)
  throw new Error(`wrong table shape ${map.width}x${map.height}`)
if (map.map.length !== 4)
  throw new Error(`wrong cell count ${map.map.length}`)

// A colspan has to widen the map without adding a cell.
const wide = schema.nodeFromJSON({
  type: "table",
  content: [row({
    type: "table_cell",
    attrs: {colspan: 2},
    content: [{type: "paragraph", content: [{type: "text", text: "wide"}]}],
  })],
})
const wideMap = TableMap.get(wide)
if (wideMap.width !== 2)
  throw new Error(`colspan not reflected in the map: ${wideMap.width}`)
console.log("built a table and mapped its cells")
JS

node check.mjs
rm -f check.mjs
