import { expect, fixture } from '@open-wc/testing' import { html } from 'lit' import { addressController, writeAddress } from '@operato/utils/address.js' import { decodeListQuery, encodeListQuery } from '@operato/utils/list-query.js' import type { DataGrist } from '../src/data-grist.js' import '../src/data-grist.js' const turn = () => new Promise(resolve => setTimeout(resolve, 0)) const native = () => (window as any).navigation const filters = (month: number) => [{ name: 'month', operator: 'eq', value: month }] const address = (month: number) => `?${encodeListQuery({ filters: filters(month) })}` async function until(check: () => boolean) { for (let i = 0; i < 200; i++) { if (check()) return await new Promise(resolve => setTimeout(resolve, 5)) } throw new Error('intent sequence did not settle') } /** Product oracle: only the latest accepted intent changes the query, records, edits or history. */ class Intended { entries: number[] = [10] cursor = 0 edited = false reads = [10] get month() { return this.entries[this.cursor] } accept(month: number) { if (month === this.month) return this.entries.splice(++this.cursor) this.entries.push(month) this.edited = false this.reads.push(month) } back() { this.cursor-- this.edited = false this.reads.push(this.month) } } describe('overlapping user intents against query and displayed state', () => { let previousOnError: typeof window.onerror const resizeNotice = (event: ErrorEvent) => { if (event.message.includes('ResizeObserver loop')) { event.preventDefault() event.stopImmediatePropagation() } } before(() => { window.addEventListener('error', resizeNotice, true) previousOnError = window.onerror window.onerror = (message, ...rest) => String(message).includes('ResizeObserver loop') ? true : previousOnError?.call(window, message, ...rest) }) after(() => { window.removeEventListener('error', resizeNotice, true) window.onerror = previousOnError }) it('checks every edit, question, refusal, supersession, adoption and browser traversal', async () => { const controller = addressController() controller.registerQuery() const coverage = new Set() for (let seed = 1; seed <= 12; seed++) { await writeAddress(address(10)) const floorKey = native().currentEntry.key const reads: number[] = [] let shown: number[] = [] const grist = await fixture( html` { const month = Number(list.find((filter: any) => filter.name === 'month').value) reads.push(month) return { records: [{ id: String(month), month }], total: 1 } }} @list-adopted=${(event: CustomEvent) => { shown = event.detail.records.map((row: any) => row.month) }} >` ) await until(() => grist.data?.records?.[0]?.month === 10) const expected = new Intended() // Initial configuration may make the initial read once or more; subsequent intent reads must match exactly. reads.splice(0, reads.length, 10) let decision: ((answer: boolean) => void) | undefined let gated = false const stopGuard = controller.guard({ discards: () => grist.dirtyRecords.length > 0, approve: change => { if (!grist.dirtyRecords.length) return true return new Promise(resolve => { const endQuestion = gated ? controller.beginQuestion() : () => {} const finish = (answer: boolean) => { endQuestion() resolve(answer) } decision = finish change.signal.addEventListener('abort', () => finish(false), { once: true }) }) }, committed: () => grist.reset() }) const verify = async (step: string) => { await turn() await grist.updateComplete expect(grist.filters, step).to.deep.equal(filters(expected.month)) expect( grist.data.records.map(row => row.month), step ).to.deep.equal([expected.month]) expect(shown, step).to.deep.equal([expected.month]) expect(grist.dirtyRecords.length > 0, step).to.equal(expected.edited) expect(reads, step).to.deep.equal(expected.reads) const entries = native().entries() const floor = entries.findIndex((entry: any) => entry.key === floorKey) expect(floor, step).to.be.at.least(0) expect( entries .slice(floor) .map((entry: any) => (decodeListQuery(new URL(entry.url).search).filters as any[])[0].value), step ).to.deep.equal(expected.entries) expect(native().currentEntry.index - floor, step).to.equal(expected.cursor) } let random = seed try { for (let step = 0; step < 18; step++) { random = (Math.imul(random, 1664525) + 1013904223) >>> 0 const action = random % 5 coverage.add(action) const label = `seed ${seed}, step ${step}, action ${action}` const next = 20 + seed * 100 + step // Real grid edit, independent of the oracle's edit flag. grist.dirtyData.records[0].__dirty__ = 'M' grist.dirtyData.records[0].memo = label grist.refresh() expected.edited = true await verify(label + ' edited') decision = undefined gated = action !== 2 && action !== 4 const first = writeAddress(address(next)) await turn() await verify(label + ' before decision') await until(() => !!decision) const answerFirst = decision! await verify(label + ' question pending') if (action === 0) { answerFirst(false) expect(await first, label).to.equal(false) } else if (action === 1) { // Requests made under a real modal question are rejected without fetching or changing the view. expect(await writeAddress(address(next + 10000)), label).to.equal(false) await verify(label + ' outside request refused') answerFirst(true) expect(await first, label).to.equal(true) expected.accept(next) } else if (action === 2) { // An asynchronous owner decision can be superseded before a dialog is installed. decision = undefined const second = writeAddress(address(next + 10000)) await until(() => !!decision) decision!(true) expect(await second, label).to.equal(true) expected.accept(next + 10000) answerFirst(true) expect(await first, label).to.equal(false) } else if (action === 3) { answerFirst(true) expect(await first, label).to.equal(true) expected.accept(next) } else { if (expected.cursor > 0) { // Browser navigation aborts the outstanding application approval; an old yes cannot revive it. decision = undefined const movement = native().back() movement.finished.catch(() => {}) await until(() => !!decision) decision!(true) await movement.finished expected.back() answerFirst(true) expect(await first, label).to.equal(false) } else { answerFirst(false) expect(await first, label).to.equal(false) } } await until(() => grist.data.records[0]?.month === expected.month) await verify(label + ' completed') } } finally { stopGuard() grist.remove() } } expect([...coverage].sort()).to.deep.equal([0, 1, 2, 3, 4]) }).timeout(45000) })