| 1 | // chipview.mjs — a link chip in the editor (spec §4.2, §6.6). The chip |
| 2 | // is drawn by the schema's own toDOM, so it is the server's markup; its |
| 3 | // state (team, alias, pending, a date) comes from resolutions.mjs, never |
| 4 | // from the node. When an answer arrives the chip is drawn again in |
| 5 | // place, without a transaction: nothing in the document changed. |
| 6 | |
| 7 | import { DOMSerializer } from 'prosemirror-model' |
| 8 | import { linkKey } from './resolutions.mjs' |
| 9 | |
| 10 | function keyOf (node) { |
| 11 | return node.type.name === 'datelink' |
| 12 | ? linkKey(node.attrs.date, node.attrs.anchor) |
| 13 | : linkKey(node.attrs.target, node.attrs.anchor) |
| 14 | } |
| 15 | |
| 16 | function draw (node) { |
| 17 | return DOMSerializer.renderSpec(document, node.type.spec.toDOM(node)).dom |
| 18 | } |
| 19 | |
| 20 | export class ChipView { |
| 21 | constructor (node, resolutions) { |
| 22 | this.node = node |
| 23 | this.dom = draw(node) |
| 24 | this.unwatch = resolutions.watch(keys => { |
| 25 | if (keys.has(keyOf(this.node))) this.redraw() |
| 26 | }) |
| 27 | } |
| 28 | |
| 29 | // redraw takes the new drawing's attributes and children into the |
| 30 | // element the view already holds. |
| 31 | redraw () { |
| 32 | const fresh = draw(this.node) |
| 33 | if (fresh.nodeName !== this.dom.nodeName) return |
| 34 | for (const { name } of [...this.dom.attributes]) { |
| 35 | if (name !== 'contenteditable' && !fresh.hasAttribute(name)) this.dom.removeAttribute(name) |
| 36 | } |
| 37 | for (const { name, value } of fresh.attributes) this.dom.setAttribute(name, value) |
| 38 | this.dom.replaceChildren(...fresh.childNodes) |
| 39 | } |
| 40 | |
| 41 | update (node) { |
| 42 | if (node.type !== this.node.type || keyOf(node) !== keyOf(this.node) || |
| 43 | node.attrs.shown !== this.node.attrs.shown) return false |
| 44 | this.node = node |
| 45 | return true |
| 46 | } |
| 47 | |
| 48 | // The chip is one atom: what happens inside it is not an edit. |
| 49 | ignoreMutation () { return true } |
| 50 | |
| 51 | destroy () { this.unwatch() } |
| 52 | } |
| 53 | |
| 54 | // chipViews is the view's nodeViews for every chip kind. |
| 55 | export function chipViews (resolutions) { |
| 56 | const make = node => new ChipView(node, resolutions) |
| 57 | return { wikilink: make, datelink: make } |
| 58 | } |
| 59 | |
| 60 | // chipHref is where a chip leads, read from its drawing. |
| 61 | export function chipHref (view, pos) { |
| 62 | const dom = view.nodeDOM(pos) |
| 63 | return dom?.getAttribute?.('href') ?? null |
| 64 | } |
| 65 | |