#!/bin/sh
# Upstream runs its suite through its own runner, which Debian does not ship.
# Build a gap cursor between two atoms and apply it to a transaction instead.
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-gapcursor ] || ln -s ../. node_modules/prosemirror-gapcursor
for m in prosemirror-model prosemirror-state prosemirror-view prosemirror-keymap prosemirror-transform; 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 {EditorState} from "prosemirror-state"
import {GapCursor, gapCursor} from "prosemirror-gapcursor"

const schema = new Schema({
  nodes: {
    doc: {content: "block+"},
    paragraph: {content: "text*", group: "block", toDOM: () => ["p", 0]},
    atom: {group: "block", atom: true, toDOM: () => ["div"]},
    text: {},
  },
})

const doc = schema.nodeFromJSON({
  type: "doc",
  content: [{type: "atom"}, {type: "atom"}],
})
const state = EditorState.create({doc, plugins: [gapCursor()]})

const $pos = doc.resolve(1)
if (!GapCursor.valid($pos))
  throw new Error("expected a valid gap position between two atoms")

const sel = new GapCursor($pos)
if (!(sel instanceof GapCursor))
  throw new Error("not a GapCursor")
if (sel.jsonID !== "gapcursor")
  throw new Error(`wrong jsonID ${sel.jsonID}`)
const json = sel.toJSON()
if (json.type !== "gapcursor" || json.pos !== 1)
  throw new Error(`unexpected JSON ${JSON.stringify(json)}`)

// setSelection validates the position, so this only works for a real gap.
const tr = state.tr.setSelection(sel)
if (!(tr.selection instanceof GapCursor))
  throw new Error("selection was not applied")

// Inside a textblock there is no gap to fill.
const textDoc = schema.nodeFromJSON({
  type: "doc",
  content: [{type: "paragraph", content: [{type: "text", text: "hi"}]}],
})
if (GapCursor.valid(textDoc.resolve(1)))
  throw new Error("a position inside a paragraph should not be a gap")

console.log("built a gap cursor and applied it to a transaction")
JS

node check.mjs
rm -f check.mjs
