| 1 | // link-dialog.mjs over a stub <dialog>: one answer per opening, and a |
| 2 | // second open() while it is up joins the first rather than leaving a |
| 3 | // promise nobody will ever settle. |
| 4 | import test from 'node:test' |
| 5 | import assert from 'node:assert/strict' |
| 6 | import { mountLinkDialog } from './link-dialog.mjs' |
| 7 | |
| 8 | function stubDialog () { |
| 9 | const input = { value: '', select () {} } |
| 10 | const listeners = {} |
| 11 | return { |
| 12 | input, |
| 13 | returnValue: '', |
| 14 | shown: 0, |
| 15 | querySelector: () => input, |
| 16 | addEventListener (name, fn) { listeners[name] = fn }, |
| 17 | showModal () { this.shown++ }, |
| 18 | close (value) { this.returnValue = value; listeners.close() } |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | test('open resolves to the button that closed it and the trimmed field', async () => { |
| 23 | const d = stubDialog() |
| 24 | const dialog = mountLinkDialog(d) |
| 25 | const p = dialog.open('https://old') |
| 26 | assert.equal(d.input.value, 'https://old') |
| 27 | assert.equal(dialog.isOpen, true) |
| 28 | d.input.value = ' https://new ' |
| 29 | d.close('insert') |
| 30 | assert.deepEqual(await p, { action: 'insert', href: 'https://new' }) |
| 31 | assert.equal(dialog.isOpen, false) |
| 32 | // Escape closes with no returnValue: that is cancel. |
| 33 | const q = dialog.open('') |
| 34 | d.close('') |
| 35 | assert.deepEqual(await q, { action: 'cancel', href: '' }) |
| 36 | }) |
| 37 | |
| 38 | test('a second open while the dialog is up joins the first', async () => { |
| 39 | const d = stubDialog() |
| 40 | const dialog = mountLinkDialog(d) |
| 41 | const first = dialog.open('https://a') |
| 42 | d.input.value = 'https://typed' |
| 43 | const second = dialog.open('https://b') |
| 44 | assert.equal(d.shown, 1) |
| 45 | assert.equal(d.input.value, 'https://typed', 'the field is not reseeded under the person') |
| 46 | d.close('remove') |
| 47 | assert.deepEqual(await first, { action: 'remove', href: 'https://typed' }) |
| 48 | assert.deepEqual(await second, { action: 'remove', href: 'https://typed' }) |
| 49 | }) |
| 50 | |
| 51 | test('a missing dialog mounts as nothing', () => { |
| 52 | assert.equal(mountLinkDialog(null), null) |
| 53 | }) |
| 54 | |