import { describe, expect, it, vi } from 'vitest'; import { toPageRef } from '@embedpdf/core'; import { boot, documentEvent, image, LATTICE } from './harness'; /** The render plugin through the real kernel: the ledger, the two raster * doors, policy conformance, the tile surface, the permission twin. */ describe('the ledger — confirmed events and the invalidate verb', () => { it('a confirmed annotation event bumps the epoch for that page only, annotated product only', async () => { const fixture = await boot(); expect(fixture.render.getRenderEpoch(toPageRef(22))).toBe(0); fixture.emit( documentEvent({ type: 'annotations.updated', page: toPageRef(22), origin: { kind: 'local' }, }), ); expect(fixture.render.getRenderEpoch(toPageRef(22))).toBe(1); expect(fixture.render.getRenderEpoch(toPageRef(22), { includeAnnotations: false })).toBe(0); expect(fixture.render.getRenderEpoch(toPageRef(11))).toBe(0); await fixture.kernel.destroy(); }); it('bumps for every origin; onInvalidated carries the event origin, or null for the invalidate verb', async () => { const fixture = await boot(); const seen: string[] = []; fixture.render.onInvalidated((event) => seen.push( `${event.scope}:${event.origin?.kind ?? 'caller'}:` + event.pages.map((page) => page.objectNumber), ), ); fixture.emit( documentEvent({ type: 'annotations.reordered', page: toPageRef(11), origin: { kind: 'remote', sessionId: 'other', subject: 'alice', at: new Date(1).toISOString(), serverSequence: 7, }, }), ); fixture.emit(documentEvent({ type: 'forms.repaired', origin: { kind: 'local' } })); fixture.render.invalidate({ pages: [toPageRef(22)], scope: 'content' }); fixture.render.invalidate(); expect(seen).toEqual([ 'annotations:remote:11', 'fields:local:11,22,33', 'content:caller:22', 'content:caller:11,22,33', ]); await fixture.kernel.destroy(); }); it('invalidate scopes: content reaches every picture, annotations and fields only the pictures that draw them', async () => { const fixture = await boot(); const epoch = (layers: { includeAnnotations?: boolean; includeFormFields?: boolean }) => fixture.render.getRenderEpoch(toPageRef(22), layers); const page = { includeAnnotations: false }; const annotations = { includeAnnotations: true, includeFormFields: false }; const fields = { includeAnnotations: false, includeFormFields: true }; fixture.render.invalidate({ pages: [toPageRef(22)], scope: 'content' }); expect([epoch(page), epoch(annotations), epoch(fields), epoch({})]).toEqual([1, 1, 1, 1]); fixture.render.invalidate({ pages: [toPageRef(22)], scope: 'annotations' }); expect([epoch(page), epoch(annotations), epoch(fields), epoch({})]).toEqual([1, 2, 1, 2]); fixture.render.invalidate({ pages: [toPageRef(22)], scope: 'fields' }); expect([epoch(page), epoch(annotations), epoch(fields), epoch({})]).toEqual([1, 2, 2, 3]); expect(fixture.render.getRenderEpoch(toPageRef(11))).toBe(0); await fixture.kernel.destroy(); }); it('a desynced stream repaints the content of every page, with no origin', async () => { const fixture = await boot(); const seen: { scope: string; origin: unknown }[] = []; fixture.render.onInvalidated((event) => seen.push(event)); fixture.emit( documentEvent({ type: 'stream.desynced', reason: 'backlog-overflow', at: new Date(0).toISOString(), }), ); expect(seen).toHaveLength(1); expect(seen[0]).toMatchObject({ scope: 'content', origin: null }); expect(fixture.render.getRenderEpoch(toPageRef(11), { includeAnnotations: false })).toBe(1); await fixture.kernel.destroy(); }); it('the engine’s fonts changing repaints the content of every page; a write’s font change, only its own facts', async () => { const fixture = await boot(); const contentEpochs = () => [11, 22, 33].map((page) => fixture.render.getRenderEpoch(toPageRef(page), { includeAnnotations: false }), ); // A font registered after the first pages were drawn: no write behind it. fixture.emit(documentEvent({ type: 'fonts.changed', origin: { kind: 'local' } })); expect(contentEpochs()).toEqual([1, 1, 1]); fixture.emit( documentEvent({ type: 'fonts.changed', origin: { kind: 'local', transaction: { id: 'op-1', index: 1, count: 2 } }, }), ); expect(contentEpochs()).toEqual([1, 1, 1]); await fixture.kernel.destroy(); }); it('a redaction apply is a content fact for the applied pages', async () => { const fixture = await boot(); fixture.emit( documentEvent({ type: 'redaction.applied', origin: { kind: 'local' }, results: [ { status: 'applied', page: toPageRef(11) }, { status: 'skipped', page: toPageRef(22) }, ], }), ); expect(fixture.render.getRenderEpoch(toPageRef(11), { includeAnnotations: false })).toBe(1); expect(fixture.render.getRenderEpoch(toPageRef(22), { includeAnnotations: false })).toBe(0); await fixture.kernel.destroy(); }); }); describe('policy conformance — the host door', () => { it('keys are computable the moment the capability exists — the kernel materialized the policy', async () => { const fixture = await boot({ policy: LATTICE }); expect(fixture.render.getRenderPolicy()).toEqual(LATTICE); expect(fixture.render.getSourceKey(toPageRef(11), { scale: 1 })).toBe('11|w640|a1f1|e0'); await fixture.kernel.destroy(); }); it('continuous conforms to the exact device width, capped at the budget', async () => { const fixture = await boot(); expect(fixture.render.getRenderPolicy()).toEqual({ kind: 'continuous' }); expect(fixture.render.getSourceKey(toPageRef(11), { scale: 0.5 })).toBe('11|w306|a1f1|e0'); expect(fixture.render.conformViewport(toPageRef(11), 0.5)).toEqual({ kind: 'width', width: 306, }); expect(fixture.render.getSourceKey(toPageRef(11), { scale: 1.53 })).toBe('11|w640|a1f1|e0'); expect(fixture.render.getSourceKey(toPageRef(11), { scale: 8 })).toBe('11|w640|a1f1|e0'); await fixture.kernel.destroy(); }); it('continuous with a ladder quantize opts into rung caching; the budget filters an advertised ladder', async () => { const ladder = await boot({ config: { fullPage: { quantize: [320, 640, 1280], maxWidth: 1280 } }, }); expect(ladder.render.getSourceKey(toPageRef(11), { scale: 0.5 })).toBe('11|w320|a1f1|e0'); expect(ladder.render.getSourceKey(toPageRef(11), { scale: 8 })).toBe('11|w1280|a1f1|e0'); const capped = await boot({ policy: LATTICE, config: { fullPage: { maxWidth: 700 } } }); expect(capped.render.conformViewport(toPageRef(11), 8)).toEqual({ kind: 'width', width: 640 }); await ladder.kernel.destroy(); await capped.kernel.destroy(); }); it('zoom inside a rung produces the same key; an epoch bump mints a new one', async () => { const fixture = await boot({ policy: LATTICE }); const at12 = fixture.render.getSourceKey(toPageRef(11), { scale: 1.2 }); expect(at12).toBe('11|w1280|a1f1|e0'); expect(fixture.render.getSourceKey(toPageRef(11), { scale: 1.5 })).toBe(at12); expect(fixture.render.getSourceKey(toPageRef(11), { scale: 2.2 })).toBe('11|w2560|a1f1|e0'); fixture.render.invalidate({ pages: [toPageRef(11)], scope: 'content' }); expect(fixture.render.getSourceKey(toPageRef(11), { scale: 1.2 })).not.toBe(at12); await fixture.kernel.destroy(); }); it('asks for a page a pending change makes once the engine has it, and never for one that went first', async () => { const fixture = await boot(); const blank = (objectNumber: number) => ({ label: { key: 'pages.insertBlank' }, ops: [ { type: 'pages.insertBlank' as const, spec: { size: { width: 612, height: 792 } }, objectNumbers: [objectNumber], }, ], }); fixture.stage(blank(44)); const picture = fixture.render.renderSource(toPageRef(44), { scale: 1 }); await new Promise((resolve) => setTimeout(resolve)); expect(fixture.imageCalls).toHaveLength(0); // The engine has the page once its event lands. const shown = fixture.kernel.documents.listPages('d'); fixture.emit( documentEvent({ type: 'pages.inserted', layout: { pageCount: shown.length, labels: [], pages: shown, namedPages: [] }, origin: { kind: 'local' }, }), ); await new Promise((resolve) => setTimeout(resolve)); expect(fixture.imageCalls.map((call) => call.pageObjectNumber)).toEqual([44]); fixture.tasks[0]!.resolve(image()); await picture; const refused = fixture.stage(blank(45)); const never = fixture.render.renderSource(toPageRef(45), { scale: 1 }); refused.reject(new Error('refused')); await expect(never).rejects.toMatchObject({ code: 'not-found' }); expect(fixture.imageCalls).toHaveLength(1); await fixture.kernel.destroy(); }); it('draws a pending copy as the page it copies, before the engine has it', async () => { const fixture = await boot(); fixture.stage({ label: { key: 'pages.duplicate' }, ops: [{ type: 'pages.copy', pages: [toPageRef(11)], objectNumbers: [46] }], }); const picture = fixture.render.renderSource(toPageRef(46), { scale: 1 }); expect(fixture.imageCalls.map((call) => call.pageObjectNumber)).toEqual([11]); fixture.tasks[0]!.resolve(image()); await picture; await fixture.kernel.destroy(); }); it('renderSource sends the conformed viewport; same-rung asks collapse to one engine call', async () => { const fixture = await boot({ policy: LATTICE }); const first = fixture.render.renderSource(toPageRef(11), { scale: 1.2 }); const second = fixture.render.renderSource(toPageRef(11), { scale: 1.5 }); expect(fixture.imageCalls).toHaveLength(1); expect(fixture.imageCalls[0]!.options.viewport).toEqual({ kind: 'width', width: 1280 }); expect(fixture.imageCalls[0]!.options.format).toBeUndefined(); // no strategy format: the engine's default fixture.tasks[0]!.resolve(image()); expect(await first).toBe(await second); // A rung re-ask after resolution serves from the LRU — still one call. await fixture.render.renderSource(toPageRef(11), { scale: 1.3 }); expect(fixture.imageCalls).toHaveLength(1); await fixture.kernel.destroy(); }); it('one consumer aborting a shared fetch leaves it alive; the last one aborts the engine call', async () => { const fixture = await boot({ policy: LATTICE }); const controller = new AbortController(); const doomed = fixture.render.renderSource(toPageRef(11), { scale: 1.2, signal: controller.signal, }); const survivor = fixture.render.renderSource(toPageRef(11), { scale: 1.5 }); controller.abort(); await expect(doomed).rejects.toBeTruthy(); expect(fixture.tasks[0]!.task.aborted).toBeUndefined(); fixture.tasks[0]!.resolve(image()); await survivor; const only = new AbortController(); const alone = fixture.render.renderSource(toPageRef(22), { scale: 1.2, signal: only.signal }); only.abort(); await expect(alone).rejects.toBeTruthy(); expect(fixture.tasks[1]!.task.aborted).toBeTruthy(); void fixture.render.renderSource(toPageRef(22), { scale: 1.2 }).catch(() => {}); // not sticky expect(fixture.imageCalls).toHaveLength(3); await fixture.kernel.destroy(); }); it("format is a strategy value: 'bmp' rides into engine calls under continuous and keys", async () => { const fixture = await boot({ config: { format: 'bmp', quality: 0.9 } }); void fixture.render.renderSource(toPageRef(11), { scale: 0.5 }).catch(() => {}); expect(fixture.imageCalls[0]!.options.format).toBe('bmp'); expect(fixture.imageCalls[0]!.options.quality).toBe(0.9); expect(fixture.render.getSourceKey(toPageRef(11), { scale: 0.5 })).toBe('11|w306|a1f1|e0|fbmp'); await fixture.kernel.destroy(); // …and under a lattice 'bmp' conforms to the deployment's formats (BMP is local-only). const cloud = await boot({ policy: LATTICE, config: { format: 'bmp' } }); void cloud.render.renderSource(toPageRef(11), { scale: 0.5 }).catch(() => {}); expect(cloud.imageCalls[0]!.options.format).toBe('webp'); expect(cloud.render.getSourceKey(toPageRef(11), { scale: 0.5 })).toBe('11|w320|a1f1|e0|fwebp'); await cloud.kernel.destroy(); }); it('paint settings are reference-stable and reflect the config', async () => { const on = await boot(); expect(on.render.getPaintSettings()).toEqual({ tiles: true }); expect(on.render.getPaintSettings()).toBe(on.render.getPaintSettings()); const off = await boot({ config: { tiles: false } }); expect(off.render.getPaintSettings().tiles).toBe(false); await on.kernel.destroy(); await off.kernel.destroy(); }); }); describe('the public door — exact sizes', () => { it('renderPage honours the requested width, or scale × page width, and defaults to scale 1', async () => { const fixture = await boot({ policy: LATTICE }); void fixture.render.renderPage(toPageRef(11), { width: 200 }).catch(() => {}); void fixture.render.renderPage(toPageRef(11), { scale: 0.25 }).catch(() => {}); void fixture.render.renderPage(toPageRef(11)).catch(() => {}); expect(fixture.imageCalls.map((call) => call.options.viewport)).toEqual([ { kind: 'width', width: 200 }, { kind: 'width', width: 153 }, { kind: 'width', width: 612 }, ]); await fixture.kernel.destroy(); }); it('renders part of a page at its own size, cut at the page’s edge, outside the store', async () => { const fixture = await boot({ policy: LATTICE }); const rect = { x: 100, y: 50, width: 200, height: 100 }; void fixture.render.renderPage(toPageRef(11), { rect, scale: 2 }).catch(() => {}); void fixture.render.renderPage(toPageRef(11), { rect, scale: 2 }).catch(() => {}); void fixture.render .renderPage(toPageRef(11), { rect: { x: 500, y: 700, width: 300, height: 300 }, width: 90 }) .catch(() => {}); expect(fixture.imageCalls.map((call) => [call.options.target, call.options.viewport])).toEqual([ [ { kind: 'rect', rect }, { kind: 'scale', scale: 2 }, ], // A part is for its caller alone: the same ask renders again. [ { kind: 'rect', rect }, { kind: 'scale', scale: 2 }, ], [ { kind: 'rect', rect: { x: 500, y: 700, width: 112, height: 92 } }, { kind: 'width', width: 90 }, ], ]); expect(fixture.imageCalls.every((call) => call.priority === 'high')).toBe(true); await fixture.kernel.destroy(); }); it('refuses a rect that misses the page, and turns a picture without the store', async () => { const fixture = await boot(); await expect( fixture.render.renderPage(toPageRef(11), { rect: { x: 700, y: 0, width: 50, height: 50 } }), ).rejects.toMatchObject({ code: 'invalid-input' }); expect(fixture.imageCalls).toHaveLength(0); void fixture.render.renderPage(toPageRef(11), { rotation: 90, width: 300 }).catch(() => {}); void fixture.render.renderPage(toPageRef(11), { rotation: 90, width: 300 }).catch(() => {}); expect(fixture.imageCalls.map((call) => [call.options.rotation, call.options.target])).toEqual([ [90, undefined], [90, undefined], ]); await fixture.kernel.destroy(); }); it('a part stops its engine call when the signal fires', async () => { const fixture = await boot(); const stop = new AbortController(); const part = fixture.render.renderPage(toPageRef(11), { rect: { x: 0, y: 0, width: 10, height: 10 }, signal: stop.signal, }); stop.abort(); await expect(part).rejects.toMatchObject({ code: 'operation-cancelled' }); expect(fixture.tasks[0]!.task.aborted).toBeDefined(); await fixture.kernel.destroy(); }); it('shares the raster store with the host door when the size matches', async () => { const fixture = await boot({ policy: LATTICE }); const conformed = fixture.render.renderSource(toPageRef(11), { scale: 1 }); // w640 fixture.tasks[0]!.resolve(image('shared')); await conformed; const exact = await fixture.render.renderPage(toPageRef(11), { width: 640 }); expect(exact).toBe(await conformed); expect(fixture.imageCalls).toHaveLength(1); // A per-call format is part of the identity: a different encode renders again. void fixture.render.renderPage(toPageRef(11), { width: 640, format: 'png' }).catch(() => {}); expect(fixture.imageCalls).toHaveLength(2); expect(fixture.imageCalls[1]!.options.format).toBe('png'); await fixture.kernel.destroy(); }); it('renderThumbnail asks for the thumbnail; renderPages reports in input order with per-page failures', async () => { const fixture = await boot(); void fixture.render.renderThumbnail(toPageRef(11)).catch(() => {}); expect(fixture.imageCalls[0]!.options.viewport).toEqual({ kind: 'thumbnail' }); const batch = fixture.render.renderPages([toPageRef(22), toPageRef(99), toPageRef(33)], { width: 100, concurrency: 1, }); await Promise.resolve(); fixture.tasks[1]!.resolve(image('22')); await vi.waitFor(() => expect(fixture.tasks).toHaveLength(3)); fixture.tasks[2]!.reject(new Error('engine said no')); const result = await batch; expect(result.applied.map((entry) => entry.page.objectNumber)).toEqual([22]); expect( result.failed.map((failure) => [ typeof failure.ref === 'number' ? failure.ref : failure.ref.objectNumber, failure.error.code, ]), ).toEqual([ [99, 'not-found'], [33, 'operation-failed'], ]); await fixture.kernel.destroy(); }); it('thumbnails need doc.render.thumbnail, not doc.render, by either door', async () => { const fixture = await boot({ allows: (capability) => capability !== 'doc.render' }); expect(fixture.render.canRender()).toBe(false); expect(fixture.render.canRenderThumbnail()).toBe(true); void fixture.render.renderThumbnail(toPageRef(11)).catch(() => {}); void fixture.render.renderSource(toPageRef(22), { scale: 1, thumbnail: true }).catch(() => {}); expect(fixture.imageCalls.map((call) => call.options.viewport)).toEqual([ { kind: 'thumbnail' }, { kind: 'thumbnail' }, ]); // One thumbnail per page, whatever the scale: the key has no width. expect(fixture.render.getSourceKey(toPageRef(22), { scale: 1, thumbnail: true })).toBe( fixture.render.getSourceKey(toPageRef(22), { scale: 3, thumbnail: true }), ); await expect(fixture.render.renderPage(toPageRef(11))).rejects.toMatchObject({ code: 'permission-denied', }); await fixture.kernel.destroy(); const screenOnly = await boot({ allows: (capability) => capability !== 'doc.render.thumbnail', }); await expect(screenOnly.render.renderThumbnail(toPageRef(11))).rejects.toMatchObject({ code: 'permission-denied', }); await screenOnly.kernel.destroy(); }); it('unknown pages are not-found; completed and failed renders are announced', async () => { const fixture = await boot(); await expect(fixture.render.renderPage(toPageRef(99))).rejects.toMatchObject({ code: 'not-found', }); const log: string[] = []; fixture.render.onRenderCompleted((event) => log.push(`ok:${event.page.objectNumber}`)); fixture.render.onRenderFailed((event) => log.push(`fail:${event.page.objectNumber}:${event.error.code}`), ); const ok = fixture.render.renderPage(toPageRef(11)); fixture.tasks[0]!.resolve(image()); await ok; const bad = fixture.render.renderPage(toPageRef(22)); fixture.tasks[1]!.reject(new Error('boom')); await expect(bad).rejects.toMatchObject({ code: 'operation-failed' }); expect(log).toEqual(['ok:11', 'fail:22:operation-failed']); await fixture.kernel.destroy(); }); }); describe('the tile surface — pure reads, page-space regions', () => { const deep = { desiredDeviceWidth: 612 * 8, visibleRect: { x: 0, y: 0, width: 80, height: 80 } }; it('createViewDemand is stable per view and reference-counted; getPlan is pure', async () => { const fixture = await boot({ config: { tiles: { settleMs: 0, bleedPx: 0 } } }); const main = fixture.render.createViewDemand('stage'); expect(fixture.render.createViewDemand('stage')).toBe(main); expect(fixture.render.createViewDemand('stage-thumbs')).not.toBe(main); // Nothing set: the empty plan, and no engine work from a read. expect(fixture.render.createViewDemand('stage').getPlan(toPageRef(11)).paint).toEqual([]); expect(fixture.imageCalls).toHaveLength(0); // A thumbnail-sized demand never engages. main.setDemand(toPageRef(11), { desiredDeviceWidth: 120 }); expect(main.getPlan(toPageRef(11)).engaged).toBe(false); // A deep demand engages and schedules the want set; the read returns the paint plan it produced. main.setDemand(toPageRef(11), deep); expect(main.getPlan(toPageRef(11)).engaged).toBe(true); expect(fixture.imageCalls.length).toBeGreaterThan(0); const before = fixture.imageCalls.length; expect(main.getPlan(toPageRef(11))).toBe(main.getPlan(toPageRef(11))); expect(fixture.imageCalls.length).toBe(before); // reads never fetch main.destroy(); main.destroy(); main.destroy(); // the last reference releases the view's pages await fixture.kernel.destroy(); }); it('tile regions are asked for in page space — a crop offset changes nothing', async () => { const crop = { left: 10, bottom: 20, right: 622, top: 812 }; const fixture = await boot({ config: { tiles: { settleMs: 0, bleedPx: 0 } }, crop }); const view = fixture.render.createViewDemand('stage'); view.setDemand(toPageRef(11), deep); const first = fixture.imageCalls[0]!.options.target as { kind: string; rect: Record; }; expect(first.kind).toBe('rect'); // The page's top-left tile starts at page-space (0,0), wherever the crop box sits in the file. expect(first.rect.x).toBe(0); expect(first.rect.y).toBe(0); expect(fixture.imageCalls[0]!.options.viewport).toEqual({ kind: 'scale', scale: 8 }); view.destroy(); await fixture.kernel.destroy(); }); it('a tile arrival re-plans outside any read and wakes subscribers', async () => { const fixture = await boot({ config: { tiles: { settleMs: 0, bleedPx: 0 } } }); const view = fixture.render.createViewDemand('stage'); view.setDemand(toPageRef(11), deep); const planned = view.getPlan(toPageRef(11)); expect(planned.fetching.length).toBeGreaterThan(0); let wakes = 0; fixture.kernel.subscribe(() => wakes++); fixture.tasks.forEach((pending) => pending.resolve(image())); await vi.waitFor(() => expect(view.getPlan(toPageRef(11)).paint.length).toBeGreaterThan(0)); expect(view.getPlan(toPageRef(11))).not.toBe(planned); expect(wakes).toBeGreaterThan(0); view.destroy(); await fixture.kernel.destroy(); }); }); describe('the twin law (permissions.md) — canRender and the fetch gates', () => { it('canRender mirrors doc.render; a denied session never spends an engine round-trip', async () => { const allowed = await boot({ allow: true }); expect(allowed.render.canRender()).toBe(true); const denied = await boot({ allow: false }); expect(denied.render.canRender()).toBe(false); await expect(denied.render.renderPage(toPageRef(11))).rejects.toMatchObject({ code: 'permission-denied', permission: 'doc.render', }); await expect(denied.render.renderSource(toPageRef(11), { scale: 1 })).rejects.toMatchObject({ code: 'permission-denied', }); await expect(denied.render.renderPages([toPageRef(11)])).rejects.toMatchObject({ code: 'permission-denied', }); expect(denied.imageCalls).toHaveLength(0); void allowed.render.renderPage(toPageRef(11)).catch(() => {}); expect(allowed.imageCalls).toHaveLength(1); await allowed.kernel.destroy(); await denied.kernel.destroy(); }); }); describe('settings', () => { it('are the defaults with what the app registered over them', async () => { const fixture = await boot({ config: { fullPage: { maxWidth: 1280 }, tiles: { size: 256 } } }); const settings = fixture.render.getSettings(); expect(settings.fullPage).toEqual({ maxWidth: 1280, quantize: 'exact' }); expect(settings.tiles).toMatchObject({ size: 256, maxScale: 128, settleMs: 150 }); expect(settings.debug).toBe(false); await fixture.kernel.destroy(); }); it('apply at once: a new budget changes the conformed width, and reset goes back', async () => { const fixture = await boot(); const changed: string[][] = []; fixture.render.onSettingsChanged((event) => changed.push([...event.changedKeys])); expect(fixture.render.getSourceKey(toPageRef(11), { scale: 8 })).toBe('11|w640|a1f1|e0'); fixture.render.updateSettings({ fullPage: { maxWidth: 1000 } }); expect(fixture.render.getSourceKey(toPageRef(11), { scale: 8 })).toBe('11|w1000|a1f1|e0'); expect(fixture.render.getSettings().fullPage.quantize).toBe('exact'); // merged, not replaced fixture.render.updateSettings({ tiles: false }); expect(fixture.render.getPaintSettings().tiles).toBe(false); fixture.render.resetSettings(); expect(fixture.render.getSourceKey(toPageRef(11), { scale: 8 })).toBe('11|w640|a1f1|e0'); expect(fixture.render.getPaintSettings().tiles).toBe(true); expect(changed).toEqual([['fullPage'], ['tiles'], ['fullPage', 'tiles']]); await fixture.kernel.destroy(); }); }); describe('page arguments and cancelling', () => { it('take a page as its ref or its index', async () => { const fixture = await boot(); const byIndex = fixture.render.renderPage(1, { width: 100 }); fixture.tasks[0]!.resolve(image('22')); await byIndex; expect(fixture.imageCalls[0]!.pageObjectNumber).toBe(22); fixture.render.invalidate({ pages: [2] }); expect(fixture.render.getRenderEpoch(2)).toBe(1); expect(fixture.render.getRenderEpoch(toPageRef(33))).toBe(1); await fixture.kernel.destroy(); }); it('read a page that isn’t in the document as empty, and refuse it in a verb', async () => { const fixture = await boot(); expect(fixture.render.getRenderEpoch(7)).toBe(0); await expect(fixture.render.renderPage(7)).rejects.toMatchObject({ code: 'not-found' }); const seen: unknown[] = []; fixture.render.onInvalidated((event) => seen.push(event.pages)); fixture.render.invalidate({ pages: [7, 0] }); expect(seen).toEqual([[toPageRef(11)]]); await fixture.kernel.destroy(); }); it('rejects operation-cancelled when the signal fires', async () => { const fixture = await boot(); const controller = new AbortController(); const single = fixture.render.renderPage(0, { signal: controller.signal }); const batch = fixture.render.renderPages([1, 2], { signal: controller.signal }); controller.abort(); await expect(single).rejects.toMatchObject({ code: 'operation-cancelled' }); await expect(batch).rejects.toMatchObject({ code: 'operation-cancelled' }); await fixture.kernel.destroy(); }); }); describe('the view a render is for, and its priority', () => { it('a layer’s base and tiles name its view, an app’s render names none; every render asks high', async () => { const fixture = await boot({ config: { tiles: { settleMs: 0, bleedPx: 0 } } }); const sources = [ fixture.render.renderSource(toPageRef(11), { scale: 1, view: 'stage' }), fixture.render.renderPage(toPageRef(22), { width: 300 }), ]; // 1224 device px across a 612pt page: past the 640px base, so tiles engage. const view = fixture.render.createViewDemand('stage-thumbs'); view.setDemand(toPageRef(33), { desiredDeviceWidth: 1224, visibleRect: { x: 0, y: 0, width: 612, height: 300 }, }); const viewOf = (page: number, tile: boolean) => fixture.imageCalls .filter( (call) => call.pageObjectNumber === page && (call.options.target !== undefined) === tile, ) .map((call) => call.view); expect(viewOf(11, false)).toEqual(['stage']); expect(viewOf(22, false)).toEqual([undefined]); expect(viewOf(33, true).length).toBeGreaterThan(0); expect(new Set(viewOf(33, true))).toEqual(new Set(['stage-thumbs'])); // Every render is the picture of a page itself. expect(new Set(fixture.imageCalls.map((call) => call.priority))).toEqual(new Set(['high'])); fixture.tasks.forEach((pending) => pending.resolve(image())); await Promise.all(sources); view.destroy(); await fixture.kernel.destroy(); }); }); describe('what a picture draws', () => { it('left out, it draws what the session may read; asking for more is refused', async () => { const fixture = await boot({ allows: (capability) => capability !== 'doc.annotate.read' }); const page = fixture.render.renderPage(toPageRef(11), { width: 100 }); expect(fixture.imageCalls[0]!.options).toMatchObject({ includeAnnotations: false, includeFormFields: true, }); await expect( fixture.render.renderPage(toPageRef(11), { width: 100, includeAnnotations: true }), ).rejects.toMatchObject({ code: 'permission-denied' }); // A layer that paints the form fields leaves them out: the page alone. const layer = fixture.render.renderSource(toPageRef(22), { scale: 1, includeFormFields: false, }); expect(fixture.imageCalls[1]!.options).toMatchObject({ includeAnnotations: false, includeFormFields: false, }); // Neither render is answered: closing the document ends both. const closed = Promise.all([ expect(page).rejects.toMatchObject({ code: 'instance-closed' }), expect(layer).rejects.toMatchObject({ code: 'instance-closed' }), ]); await fixture.kernel.destroy(); await closed; }); it('tells a view what the session may read, as the same object until it changes', async () => { const reader = await boot({ allows: (capability) => capability !== 'doc.annotate.read' }); expect(reader.render.getLayerRights()).toEqual({ annotations: false, formFields: true }); expect(reader.render.getLayerRights()).toBe(reader.render.getLayerRights()); await reader.kernel.destroy(); const everything = await boot(); expect(everything.render.getLayerRights()).toEqual({ annotations: true, formFields: true }); await everything.kernel.destroy(); }); it('each picture has its own key, and moves with the facts it draws', async () => { const fixture = await boot(); const keyOf = (layers: { includeAnnotations?: boolean; includeFormFields?: boolean }) => fixture.render.getSourceKey(toPageRef(11), { scale: 1, ...layers }); expect(keyOf({})).toBe('11|w612|a1f1|e0'); expect(keyOf({ includeFormFields: false })).toBe('11|w612|a1f0|e0'); expect(keyOf({ includeAnnotations: false })).toBe('11|w612|a0f0|e0'); expect(keyOf({ includeAnnotations: false, includeFormFields: true })).toBe('11|w612|a0f1|e0'); fixture.emit( documentEvent({ type: 'forms.valueSet', origin: { kind: 'local' }, meta: { changedWidgets: [{ page: toPageRef(11) }] }, }), ); expect(keyOf({ includeFormFields: false })).toBe('11|w612|a1f0|e0'); expect(keyOf({})).toBe('11|w612|a1f1|e1'); await fixture.kernel.destroy(); }); }); describe('painting the pictures another way', () => { const painter = (views: string[] = ['main']) => ({ paints: (view: string) => views.includes(view), paint: () => ({ update: () => {}, destroy: () => {} }), }); it('holds one painter, wakes the views, and gives it back once', async () => { const fixture = await boot(); const woken = vi.fn(); fixture.kernel.subscribe(woken); expect(fixture.render.getPicturePainter()).toBeNull(); const held = painter(); const giveBack = fixture.render.handOverPictures(held); expect(fixture.render.getPicturePainter()).toBe(held); expect(woken).toHaveBeenCalled(); woken.mockClear(); giveBack(); expect(fixture.render.getPicturePainter()).toBeNull(); expect(woken).toHaveBeenCalled(); woken.mockClear(); giveBack(); // giving it back twice is harmless expect(woken).not.toHaveBeenCalled(); await fixture.kernel.destroy(); }); it('refuses a second painter, and a stale give-back never drops the next one', async () => { const fixture = await boot(); const giveBack = fixture.render.handOverPictures(painter()); expect(() => fixture.render.handOverPictures(painter(['thumbnails']))).toThrow( expect.objectContaining({ code: 'conflict' }), ); giveBack(); const next = painter(); fixture.render.handOverPictures(next); giveBack(); expect(fixture.render.getPicturePainter()).toBe(next); await fixture.kernel.destroy(); }); }); describe('appearance pictures', () => { const page = toPageRef(11); const ref = (objectNumber: number) => ({ kind: 'objectNumber' as const, page, objectNumber }); /** The engine's picture of an item in a state. */ const drawn = (objectNumber: number, state: string | null) => ({ ref: ref(objectNumber), mode: 'normal', state, rect: { x: 0, y: 0, width: 10, height: 10 }, image: `image ${objectNumber} ${state}`, }); it('one fetch per page, family, scale and items; each picture tagged with its item’s version', async () => { const fixture = await boot(); const ask = (version: number) => fixture.render.renderAppearances(page, { family: 'widgets', scale: 2, items: [{ ref: ref(5), version }], }); const first = ask(2); const second = ask(2); expect(fixture.appearanceCalls).toEqual([ { pageObjectNumber: 11, family: 'widgets', options: { viewport: { kind: 'scale', scale: 2 }, modes: ['normal'] }, }, ]); // Every state is held; a picture of an item nobody asked for isn't. fixture.appearanceTasks[0]!.resolve({ appearances: [drawn(5, 'Off'), drawn(5, 'Yes'), drawn(9, null)], }); const tagged = [ { ...drawn(5, 'Off'), version: 2 }, { ...drawn(5, 'Yes'), version: 2 }, ]; expect(await first).toEqual(tagged); expect(await second).toEqual(tagged); await ask(2); expect(fixture.appearanceCalls).toHaveLength(1); // The item was drawn again: the next ask fetches. void ask(3).catch(() => undefined); expect(fixture.appearanceCalls).toHaveLength(2); await fixture.kernel.destroy(); }); it('keeps the last sets of a page, so an undo back to one asks for nothing', async () => { const fixture = await boot(); const ask = (version: number) => { const asked = fixture.render.renderAppearances(page, { family: 'annotations', scale: 1, items: [{ ref: ref(7), version }], }); fixture.appearanceTasks.at(-1)?.resolve({ appearances: [drawn(7, null)] }); return asked; }; await ask(0); await ask(1); expect(fixture.appearanceCalls).toHaveLength(2); expect(fixture.appearanceCalls.every((call) => call.family === 'annotations')).toBe(true); // Undone: the page is back to its first set. expect(await ask(0)).toEqual([{ ...drawn(7, null), version: 0 }]); expect(fixture.appearanceCalls).toHaveLength(2); // Four newer sets later, the first is gone. for (const version of [2, 3, 4, 5]) await ask(version); await ask(0); expect(fixture.appearanceCalls).toHaveLength(7); await fixture.kernel.destroy(); }); it('keeps an item’s last pictures after it left its page, per family', async () => { const fixture = await boot(); const asked = fixture.render.renderAppearances(page, { family: 'widgets', scale: 1, items: [{ ref: ref(5), version: 1 }], }); fixture.appearanceTasks[0]!.resolve({ appearances: [drawn(5, 'Off'), drawn(5, 'Yes')] }); await asked; expect(fixture.render.getKeptAppearances('widgets', ref(5))).toEqual([ { ...drawn(5, 'Off'), version: 1 }, { ...drawn(5, 'Yes'), version: 1 }, ]); expect(fixture.render.getKeptAppearances('annotations', ref(5))).toEqual([]); await fixture.kernel.destroy(); }); it('a view that leaves doesn’t stop the fetch another view still waits for', async () => { const fixture = await boot(); const options = { family: 'widgets' as const, scale: 1, items: [{ ref: ref(5), version: 0 }] }; const leaving = new AbortController(); const left = fixture.render.renderAppearances(page, { ...options, signal: leaving.signal }); const staying = fixture.render.renderAppearances(page, options); leaving.abort(); await expect(left).rejects.toBeDefined(); expect(fixture.appearanceTasks[0]!.task.aborted).toBeUndefined(); fixture.appearanceTasks[0]!.resolve({ appearances: [drawn(5, null)] }); expect(await staying).toEqual([{ ...drawn(5, null), version: 0 }]); await fixture.kernel.destroy(); }); it('needs doc.forms.read for widgets and doc.annotate.read for annotations', async () => { for (const [family, scope] of [ ['widgets', 'doc.forms.read'], ['annotations', 'doc.annotate.read'], ] as const) { const fixture = await boot({ allows: (capability) => capability !== scope }); await expect( fixture.render.renderAppearances(page, { family, scale: 1, items: [] }), ).rejects.toMatchObject({ code: 'permission-denied' }); expect(fixture.appearanceCalls).toHaveLength(0); await fixture.kernel.destroy(); } }); });