diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs
new file mode 100644
index 0000000..99f60b0
--- /dev/null
+++ b/.git-blame-ignore-revs
@@ -0,0 +1,3 @@
+# Prettier reformat (formatting only). Tell git blame to skip it:
+# git config blame.ignoreRevsFile .git-blame-ignore-revs
+f15c95643662c452e929e508997e410f262d84ee
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index e951c6b..b4c3434 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -7,7 +7,7 @@ on:
jobs:
test:
- runs-on: ubuntu-24.04 # Playwright 1.56 has no browsers for Ubuntu 26.04, which ubuntu-latest became
+ runs-on: ubuntu-24.04 # Playwright 1.56 has no browsers for Ubuntu 26.04, which ubuntu-latest became
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
@@ -39,6 +39,8 @@ jobs:
run: python3 tools/vendor_libs.py --check
- run: npm ci
+ - name: Code is formatted (fix with npx prettier --write .)
+ run: npx prettier --check .
- run: npx playwright install --with-deps chromium
- name: Browser tests
run: npx playwright test
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 0000000..c851e64
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1,33 @@
+# Dependencies, test output
+node_modules/
+test-results/
+playwright-report/
+
+# Lockfiles
+package-lock.json
+branding/package-lock.json
+
+# Vendored third-party code (tools/vendor_libs.py checks it byte for byte)
+app/vendor/
+
+# Markdown and docs: hand-written prose, left alone
+*.md
+docs/
+
+# Generated by tools/build.py (it copies shared/ into these; formatting them would be undone on the next build)
+/overlay/ink_overlay.html
+/index.html
+# Also written by tools/build.py (version stamp, offline file list). Its regexes expect the current markup
+# (e.g. `content="...">`), so Prettier's rewrite (` />`, wrapped lines) makes `build.py --check` fail
+app/sw.js
+app/version.json
+app/index.html
+app/report/index.html
+
+# Old overlay saved as a compatibility fixture; tests load it as-is
+tests/fixtures/Old_v13.html
+
+# tools/build_overlay.py inlines this into the overlay and deletes the line ending in `// @strip-inline`
+# (the export list). Prettier wraps that export over many lines and moves the marker, so `export` leaks
+# into the inline `);
+ `
+ );
const profile = path.join(site.dir, 'profile');
- chrome = spawn(process.env.PW_CHROMIUM || chromium.executablePath(), ['--headless=new', '--no-sandbox', '--no-first-run',
- '--disable-background-networking', '--disable-component-update', '--user-data-dir=' + profile, site.url.replace('app/', 'driver.html')], { stdio: 'ignore' });
+ chrome = spawn(
+ process.env.PW_CHROMIUM || chromium.executablePath(),
+ [
+ '--headless=new',
+ '--no-sandbox',
+ '--no-first-run',
+ '--disable-background-networking',
+ '--disable-component-update',
+ '--user-data-dir=' + profile,
+ site.url.replace('app/', 'driver.html'),
+ ],
+ { stdio: 'ignore' }
+ );
try {
const r = await got;
- expect(r).toEqual({ installed: true, controlled: true, waiting: true, oldBefore: true, newAfter: true, caches: ['overboard-' + site.swVersion()] });
+ expect(r).toEqual({
+ installed: true,
+ controlled: true,
+ waiting: true,
+ oldBefore: true,
+ newAfter: true,
+ caches: ['overboard-' + site.swVersion()],
+ });
} finally {
chrome.kill();
await new Promise((r) => chrome.once('exit', r));
diff --git a/tests/overlay.spec.js b/tests/overlay.spec.js
index 9ae7593..2dcd413 100644
--- a/tests/overlay.spec.js
+++ b/tests/overlay.spec.js
@@ -10,20 +10,49 @@ test.beforeEach(async ({ page }) => {
});
async function stroke(page, pts, o = {}) {
- await page.evaluate(([pts, o]) => new Promise(async (res) => {
- const c = document.getElementById('ink-canvas');
- const ev = (t, x, y) => c.dispatchEvent(new PointerEvent(t, { bubbles: true, cancelable: true, pointerType: o.type || 'pen', pointerId: 3, buttons: t === 'pointerup' ? 0 : (o.buttons || 1), button: 0, clientX: x, clientY: y, screenX: x, screenY: y }));
- ev('pointerdown', ...pts[0]);
- for (const p of pts.slice(1)) { await new Promise((r) => setTimeout(r, 4)); ev('pointermove', ...p); }
- await new Promise((r) => setTimeout(r, 20));
- ev('pointerup', ...pts[pts.length - 1]); res();
- }), [pts, o]);
+ await page.evaluate(
+ ([pts, o]) =>
+ new Promise(async (res) => {
+ const c = document.getElementById('ink-canvas');
+ const ev = (t, x, y) =>
+ c.dispatchEvent(
+ new PointerEvent(t, {
+ bubbles: true,
+ cancelable: true,
+ pointerType: o.type || 'pen',
+ pointerId: 3,
+ buttons: t === 'pointerup' ? 0 : o.buttons || 1,
+ button: 0,
+ clientX: x,
+ clientY: y,
+ screenX: x,
+ screenY: y,
+ })
+ );
+ ev('pointerdown', ...pts[0]);
+ for (const p of pts.slice(1)) {
+ await new Promise((r) => setTimeout(r, 4));
+ ev('pointermove', ...p);
+ }
+ await new Promise((r) => setTimeout(r, 20));
+ ev('pointerup', ...pts[pts.length - 1]);
+ res();
+ }),
+ [pts, o]
+ );
}
-const line = (x0, y0, x1, y1) => Array.from({ length: 31 }, (_, i) => [x0 + (x1 - x0) * i / 30, y0 + (y1 - y0) * i / 30]);
-const alpha = (page, x, y, id = 'ink-canvas') => page.evaluate(([x, y, id]) => {
- const c = document.getElementById(id), r = c.getBoundingClientRect(), s = c.width / r.width;
- return c.getContext('2d').getImageData(Math.round((x - r.left) * s), Math.round((y - r.top) * s), 1, 1).data[3];
-}, [x, y, id]);
+const line = (x0, y0, x1, y1) =>
+ Array.from({ length: 31 }, (_, i) => [x0 + ((x1 - x0) * i) / 30, y0 + ((y1 - y0) * i) / 30]);
+const alpha = (page, x, y, id = 'ink-canvas') =>
+ page.evaluate(
+ ([x, y, id]) => {
+ const c = document.getElementById(id),
+ r = c.getBoundingClientRect(),
+ s = c.width / r.width;
+ return c.getContext('2d').getImageData(Math.round((x - r.left) * s), Math.round((y - r.top) * s), 1, 1).data[3];
+ },
+ [x, y, id]
+ );
const on = (page) => page.evaluate(() => document.querySelector('#ink-bar [data-color].on').dataset.color);
test('demo page carries the current overlay', async ({ page }) => {
@@ -46,7 +75,15 @@ test('pen, highlighter colors, palm erase, finger scroll', async ({ page }) => {
expect(await alpha(page, 650, 500, 'ink-hl')).toBe(0);
expect(await alpha(page, 550, 400)).toBeGreaterThan(200);
const y0 = await page.evaluate(() => scrollY);
- await stroke(page, [[600, 700], [600, 600], [600, 500]], { type: 'mouse' });
+ await stroke(
+ page,
+ [
+ [600, 700],
+ [600, 600],
+ [600, 500],
+ ],
+ { type: 'mouse' }
+ );
expect(await page.evaluate(() => scrollY)).toBeGreaterThan(y0);
});
@@ -56,7 +93,7 @@ test('holding + keeps stepping, and ink saves in the browser', async ({ page })
await page.mouse.down();
await page.waitForTimeout(1200);
await page.mouse.up();
- expect(Number(await page.textContent('#ink-size .num'))).toBeGreaterThanOrEqual(5); // 2.5 + several 0.5 steps
+ expect(Number(await page.textContent('#ink-size .num'))).toBeGreaterThanOrEqual(5); // 2.5 + several 0.5 steps
await stroke(page, line(500, 400, 800, 400));
await stroke(page, line(500, 450, 800, 450));
await page.click('[data-act="undo"]');
@@ -66,23 +103,39 @@ test('holding + keeps stepping, and ink saves in the browser', async ({ page })
/* ---- Highlighter ▾ in the overlay: the same shared menu as the PDF app (Cover + strength) ---- */
const { tapOn } = require('./support/app');
-const rgba = (page, x, y, id) => page.evaluate(([x, y, id]) => {
- const c = document.getElementById(id) || document.querySelector(id), r = c.getBoundingClientRect();
- return Array.from(c.getContext('2d').getImageData(Math.round((x - r.left) * c.width / r.width), Math.round((y - r.top) * c.height / r.height), 1, 1).data);
-}, [x, y, id]);
+const rgba = (page, x, y, id) =>
+ page.evaluate(
+ ([x, y, id]) => {
+ const c = document.getElementById(id) || document.querySelector(id),
+ r = c.getBoundingClientRect();
+ return Array.from(
+ c
+ .getContext('2d')
+ .getImageData(
+ Math.round(((x - r.left) * c.width) / r.width),
+ Math.round(((y - r.top) * c.height) / r.height),
+ 1,
+ 1
+ ).data
+ );
+ },
+ [x, y, id]
+ );
-test('Cover: the ▾ menu works with pen and finger taps; covers are opaque on the top layer and erase with the palm', async ({ page }) => {
- await tapOn(page, '[data-act="hl-menu"]', 'mouse'); // finger
+test('Cover: the ▾ menu works with pen and finger taps; covers are opaque on the top layer and erase with the palm', async ({
+ page,
+}) => {
+ await tapOn(page, '[data-act="hl-menu"]', 'mouse'); // finger
await expect(page.locator('#ob-hlmenu')).toBeVisible();
await page.waitForTimeout(300);
- await expect(page.locator('#ob-hlmenu')).toBeVisible(); // lifting didn't close it
+ await expect(page.locator('#ob-hlmenu')).toBeVisible(); // lifting didn't close it
await tapOn(page, '#ob-hlmenu [data-cover="#111111"]', 'pen');
await expect(page.locator('#ob-hlmenu')).toBeHidden();
await expect(page.locator('[data-act="hilite"]')).toHaveText('Cover');
await stroke(page, line(500, 400, 800, 400));
expect(await rgba(page, 650, 400, 'ink-canvas')).toEqual([17, 17, 17, 255]);
expect(await alpha(page, 650, 400, 'ink-hl')).toBe(0);
- await stroke(page, line(650, 360, 650, 440), { buttons: 32 }); // palm reveals
+ await stroke(page, line(650, 360, 650, 440), { buttons: 32 }); // palm reveals
expect(await alpha(page, 650, 400)).toBe(0);
expect(await alpha(page, 550, 400)).toBe(255);
const s = (await savedInk(page)).periods.P1;
@@ -91,7 +144,7 @@ test('Cover: the ▾ menu works with pen and finger taps; covers are opaque on t
// strength slider: full-strength yellow on the multiply layer
await tapOn(page, '[data-act="hl-menu"]', 'pen');
await page.locator('#ob-hl-strength').fill('100');
- await expect(page.locator('#ob-hlmenu')).toBeVisible(); // the slider keeps it open
+ await expect(page.locator('#ob-hlmenu')).toBeVisible(); // the slider keeps it open
await expect(page.locator('[data-act="hilite"]')).toHaveText('Highlighter');
await page.keyboard.press('Escape');
await expect(page.locator('#ob-hlmenu')).toBeHidden();
@@ -100,30 +153,46 @@ test('Cover: the ▾ menu works with pen and finger taps; covers are opaque on t
expect(await rgba(page, 650, 500, 'ink-hl')).toEqual([253, 216, 53, 255]);
});
-const savePdf = async (page) => { await page.click('[data-act="file"]'); await page.click('#ob-filemenu [data-act="print"]'); }; // Save PDF is in the File menu
+const savePdf = async (page) => {
+ await page.click('[data-act="file"]');
+ await page.click('#ob-filemenu [data-act="print"]');
+}; // Save PDF is in the File menu
-test('Save PDF with covers: the teacher is told the text can still be copied; covers print solid above the page', async ({ page }) => {
- await page.evaluate(() => { window.print = () => { window.__printed = (window.__printed || 0) + 1; }; });
- const box = await page.locator('.page').first().boundingBox(), y = box.y + 200, x0 = box.x + 100;
- await stroke(page, line(x0, y, x0 + 300, y)); // pen: no notice
+test('Save PDF with covers: the teacher is told the text can still be copied; covers print solid above the page', async ({
+ page,
+}) => {
+ await page.evaluate(() => {
+ window.print = () => {
+ window.__printed = (window.__printed || 0) + 1;
+ };
+ });
+ const box = await page.locator('.page').first().boundingBox(),
+ y = box.y + 200,
+ x0 = box.x + 100;
+ await stroke(page, line(x0, y, x0 + 300, y)); // pen: no notice
await savePdf(page);
expect(await page.evaluate(() => window.__printed)).toBe(1);
await tapOn(page, '[data-act="hl-menu"]', 'pen');
await tapOn(page, '#ob-hlmenu [data-cover="#a6a6a6"]', 'pen');
await stroke(page, line(x0, y + 60, x0 + 300, y + 60));
let msg = '';
- page.once('dialog', (d) => { msg = d.message(); d.dismiss(); });
+ page.once('dialog', (d) => {
+ msg = d.message();
+ d.dismiss();
+ });
await savePdf(page);
expect(msg).toContain('still in it');
- expect(await page.evaluate(() => window.__printed)).toBe(1); // cancelled
+ expect(await page.evaluate(() => window.__printed)).toBe(1); // cancelled
page.once('dialog', (d) => d.accept());
await savePdf(page);
expect(await page.evaluate(() => window.__printed)).toBe(2);
await page.evaluate(() => window.dispatchEvent(new Event('beforeprint')));
- const layers = await page.evaluate(() => [...document.querySelectorAll('.page')[0].querySelectorAll('canvas.ink-print')].map((c) => c.style.mixBlendMode));
- expect(layers).toEqual(['']); // no highlights: one layer, covers on it
- expect(await rgba(page, x0 + 150, y + 60, '.page canvas.ink-print')).toEqual([166, 166, 166, 255]); // light gray
+ const layers = await page.evaluate(() =>
+ [...document.querySelectorAll('.page')[0].querySelectorAll('canvas.ink-print')].map((c) => c.style.mixBlendMode)
+ );
+ expect(layers).toEqual(['']); // no highlights: one layer, covers on it
+ expect(await rgba(page, x0 + 150, y + 60, '.page canvas.ink-print')).toEqual([166, 166, 166, 255]); // light gray
await page.evaluate(() => window.dispatchEvent(new Event('afterprint')));
});
@@ -132,7 +201,7 @@ const lsKeys = (page) => page.evaluate(() => Object.keys(localStorage).filter((k
test('ink comes back after a reload right after writing, and no copy is left in localStorage', async ({ page }) => {
await stroke(page, line(500, 400, 800, 400));
- await page.reload(); // well inside the 5 s save wait
+ await page.reload(); // well inside the 5 s save wait
await overlayReady(page);
expect(await alpha(page, 650, 400)).toBeGreaterThan(200);
await expect(page.locator('#ink-status')).toContainText('ink restored from this browser');
@@ -140,19 +209,33 @@ test('ink comes back after a reload right after writing, and no copy is left in
expect(await lsKeys(page)).toEqual([]);
});
-test('if the database save is cut off as the tab closes, the localStorage backup keeps the stroke', async ({ page }) => {
+test('if the database save is cut off as the tab closes, the localStorage backup keeps the stroke', async ({
+ page,
+}) => {
await stroke(page, line(500, 400, 800, 400));
- await page.evaluate(() => { IDBObjectStore.prototype.put = () => { throw new Error('cut off'); }; });
+ await page.evaluate(() => {
+ IDBObjectStore.prototype.put = () => {
+ throw new Error('cut off');
+ };
+ });
await page.reload();
await overlayReady(page);
expect(await alpha(page, 650, 400)).toBeGreaterThan(200);
- expect((await savedInk(page)).periods.P1).toHaveLength(1); // moved into IndexedDB on opening
+ expect((await savedInk(page)).periods.P1).toHaveLength(1); // moved into IndexedDB on opening
expect(await lsKeys(page)).toEqual([]);
});
test('ink saved in localStorage by v20 and older moves to IndexedDB', async ({ page }) => {
- const old = { v: 2, t: Date.now(), active: 'P2', periods: { P1: [], P2: [{ c: '#1565c0', w: 4, p: [300, 400, 700, 400] }], P3: [], P4: [] } };
- await page.evaluate((old) => localStorage.setItem('ink-v2:' + location.pathname + ':' + document.title, JSON.stringify(old)), old);
+ const old = {
+ v: 2,
+ t: Date.now(),
+ active: 'P2',
+ periods: { P1: [], P2: [{ c: '#1565c0', w: 4, p: [300, 400, 700, 400] }], P3: [], P4: [] },
+ };
+ await page.evaluate(
+ (old) => localStorage.setItem('ink-v2:' + location.pathname + ':' + document.title, JSON.stringify(old)),
+ old
+ );
await page.reload();
await overlayReady(page);
await expect(page.locator('#ink-status')).toContainText('P2 · ink restored from this browser');
@@ -164,12 +247,25 @@ test('ink saved in localStorage by v20 and older moves to IndexedDB', async ({ p
test('more ink than localStorage could hold (about 8 MB) still saves', async ({ page }) => {
const n = 10000;
await page.evaluate(async (n) => {
- const key = 'ink-v2:' + location.pathname + ':' + document.title, p = [];
- for (let j = 0; j < 80; j++) p.push(3000 + j * 0.7, 5000.3 + j); // off to the side, out of the way
- const D = { v: 2, t: Date.now(), active: 'P1', periods: { P1: Array.from({ length: n }, () => ({ c: '#111111', w: 2.5, p })), P2: [], P3: [], P4: [] } };
+ const key = 'ink-v2:' + location.pathname + ':' + document.title,
+ p = [];
+ for (let j = 0; j < 80; j++) p.push(3000 + j * 0.7, 5000.3 + j); // off to the side, out of the way
+ const D = {
+ v: 2,
+ t: Date.now(),
+ active: 'P1',
+ periods: { P1: Array.from({ length: n }, () => ({ c: '#111111', w: 2.5, p })), P2: [], P3: [], P4: [] },
+ };
if (JSON.stringify(D).length < 7e6) throw new Error('test ink too small');
- const db = await new Promise((res) => { const rq = indexedDB.open('ink-data'); rq.onsuccess = () => res(rq.result); });
- await new Promise((res) => { const tx = db.transaction('ink', 'readwrite'); tx.objectStore('ink').put(D, key); tx.oncomplete = res; });
+ const db = await new Promise((res) => {
+ const rq = indexedDB.open('ink-data');
+ rq.onsuccess = () => res(rq.result);
+ });
+ await new Promise((res) => {
+ const tx = db.transaction('ink', 'readwrite');
+ tx.objectStore('ink').put(D, key);
+ tx.oncomplete = res;
+ });
db.close();
}, n);
await page.reload();
diff --git a/tests/report.spec.js b/tests/report.spec.js
index 4b8721e..263c983 100644
--- a/tests/report.spec.js
+++ b/tests/report.spec.js
@@ -7,7 +7,9 @@ const { openOverlay } = require('./support/overlay');
const RELAY = 'https://relay.example/exec';
async function openReport(page, query = '?from=app') {
- await page.addInitScript((url) => { window.__obReportRelay = url; }, RELAY);
+ await page.addInitScript((url) => {
+ window.__obReportRelay = url;
+ }, RELAY);
await page.goto('app/report/' + query);
await expect(page.locator('[data-screen="welcome"]')).toBeVisible();
}
@@ -17,17 +19,39 @@ async function press(page, go) {
await page.click(`[data-go="${go}"]:visible`);
}
/* a line down the drawing area with synthetic pointer events, like the board sends them */
-const line = (page, x, o = {}) => page.evaluate(({ x, o }) => {
- const pad = document.getElementById('pad'), r = pad.getBoundingClientRect();
- const type = o.type || 'pen', buttons = o.buttons || 1, w = o.w || 1;
- const ev = (t, cx, cy) => (document.elementFromPoint(cx, cy) || pad).dispatchEvent(new PointerEvent(t, { bubbles: true, cancelable: true,
- pointerType: type, pointerId: o.id || 5, isPrimary: true, buttons: t === 'pointerup' ? 0 : buttons, button: t === 'pointermove' ? -1 : (buttons & 32 ? 5 : 0),
- clientX: cx, clientY: cy, width: w, height: w, pressure: 0.5 }));
- const X = r.left + x, Y = r.top + 30;
- ev('pointerdown', X, Y);
- for (let i = 1; i <= 30; i++) ev('pointermove', X, Y + i * 6);
- ev('pointerup', X, Y + 180);
-}, { x, o });
+const line = (page, x, o = {}) =>
+ page.evaluate(
+ ({ x, o }) => {
+ const pad = document.getElementById('pad'),
+ r = pad.getBoundingClientRect();
+ const type = o.type || 'pen',
+ buttons = o.buttons || 1,
+ w = o.w || 1;
+ const ev = (t, cx, cy) =>
+ (document.elementFromPoint(cx, cy) || pad).dispatchEvent(
+ new PointerEvent(t, {
+ bubbles: true,
+ cancelable: true,
+ pointerType: type,
+ pointerId: o.id || 5,
+ isPrimary: true,
+ buttons: t === 'pointerup' ? 0 : buttons,
+ button: t === 'pointermove' ? -1 : buttons & 32 ? 5 : 0,
+ clientX: cx,
+ clientY: cy,
+ width: w,
+ height: w,
+ pressure: 0.5,
+ })
+ );
+ const X = r.left + x,
+ Y = r.top + 30;
+ ev('pointerdown', X, Y);
+ for (let i = 1; i <= 30; i++) ev('pointermove', X, Y + i * 6);
+ ev('pointerup', X, Y + 180);
+ },
+ { x, o }
+ );
const seen = (page) => page.locator('#seen .msg').textContent();
const title = (page) => page.locator('#steps .title').textContent();
@@ -35,14 +59,15 @@ test('each step records what actually arrives, even the wrong input, and Next al
await openReport(page);
await press(page, 'start');
await expect(page.locator('#steps .count')).toHaveText('Step 1 of 5');
- expect(await page.evaluate(() => getComputedStyle(document.body).touchAction)).toBe('none'); // drawing steps: a finger draws
+ expect(await page.evaluate(() => getComputedStyle(document.body).touchAction)).toBe('none'); // drawing steps: a finger draws
// the finger step gets the pen (a board that reports fingers as a pen)
- await line(page, 100); await line(page, 200);
+ await line(page, 100);
+ await line(page, 200);
expect(await seen(page)).toBe('✓ Got it! I saw 2 lines.');
await expect(page.locator('#seen .detail')).toHaveText('Your board said: pen ×2');
await press(page, 'next');
expect(await title(page)).toBe('Now draw 2 lines with the pen');
- await line(page, 300, { type: 'mouse' }); // the pen step gets a mouse
+ await line(page, 300, { type: 'mouse' }); // the pen step gets a mouse
await press(page, 'next');
// the palm step gets nothing at all: still fine
expect(await seen(page)).toBe('Waiting… touch the white area.');
@@ -50,7 +75,11 @@ test('each step records what actually arrives, even the wrong input, and Next al
await expect(page.locator('[data-go="skip"]')).toHaveText('My board has no eraser');
await press(page, 'skip');
// two fingers arrive as scrolling
- await page.evaluate(() => document.getElementById('pad').dispatchEvent(new WheelEvent('wheel', { deltaY: 60, bubbles: true, cancelable: true })));
+ await page.evaluate(() =>
+ document
+ .getElementById('pad')
+ .dispatchEvent(new WheelEvent('wheel', { deltaY: 60, bubbles: true, cancelable: true }))
+ );
expect(await seen(page)).toContain('Something happened, but not a line');
await press(page, 'next');
await expect(page.locator('[data-screen="questions"]')).toBeVisible();
@@ -62,11 +91,15 @@ test('each step records what actually arrives, even the wrong input, and Next al
const step = (id) => r.steps.find((s) => s.id === id);
expect(step('finger').seen).toMatchObject({ lines: 2, types: { pen: 2 }, kinds: { pen: 2 } });
expect(step('pen').seen).toMatchObject({ lines: 1, types: { mouse: 1 }, kinds: { finger: 1 } });
- expect(step('palm').seen).toMatchObject({ downs: 0, lines: 0, buttonPresses: { mouse: 1 } }); // pressing Next isn't the step's input
+ expect(step('palm').seen).toMatchObject({ downs: 0, lines: 0, buttonPresses: { mouse: 1 } }); // pressing Next isn't the step's input
expect(step('palm').skipped).toBe(false);
expect(step('eraser').skipped).toBe(true);
expect(step('two').seen).toMatchObject({ wheel: 1, downs: 0 });
- expect(step('finger').events.find((e) => e.ev === 'pointerdown')).toMatchObject({ type: 'pen', on: 'pad', buttons: 1 });
+ expect(step('finger').events.find((e) => e.ev === 'pointerdown')).toMatchObject({
+ type: 'pen',
+ on: 'pad',
+ buttons: 1,
+ });
expect(r.startedWith.pointerType).toBe('mouse');
expect(r.from).toBe('app');
expect(r.release).toMatch(/^v\d+$/);
@@ -75,17 +108,40 @@ test('each step records what actually arrives, even the wrong input, and Next al
test('a palm sliding onto Next does not skip the step; the eraser button is counted', async ({ page }) => {
await openReport(page);
- await press(page, 'start'); await press(page, 'next'); await press(page, 'next');
+ await press(page, 'start');
+ await press(page, 'next');
+ await press(page, 'next');
expect(await title(page)).toBe('Wipe with your flat hand');
- await line(page, 150, { buttons: 32 }); // SMART: a palm is the pen with its eraser button
+ await line(page, 150, { buttons: 32 }); // SMART: a palm is the pen with its eraser button
await page.waitForTimeout(500);
const next = await page.locator('[data-go="next"]').boundingBox();
- await page.evaluate(({ x, y }) => {
- const b = document.elementFromPoint(x, y);
- b.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerType: 'pen', buttons: 32, button: 5, clientX: x, clientY: y }));
- b.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, pointerType: 'pen', buttons: 0, button: 5, clientX: x, clientY: y }));
- b.click();
- }, { x: next.x + next.width / 2, y: next.y + next.height / 2 });
+ await page.evaluate(
+ ({ x, y }) => {
+ const b = document.elementFromPoint(x, y);
+ b.dispatchEvent(
+ new PointerEvent('pointerdown', {
+ bubbles: true,
+ pointerType: 'pen',
+ buttons: 32,
+ button: 5,
+ clientX: x,
+ clientY: y,
+ })
+ );
+ b.dispatchEvent(
+ new PointerEvent('pointerup', {
+ bubbles: true,
+ pointerType: 'pen',
+ buttons: 0,
+ button: 5,
+ clientX: x,
+ clientY: y,
+ })
+ );
+ b.click();
+ },
+ { x: next.x + next.width / 2, y: next.y + next.height / 2 }
+ );
expect(await title(page)).toBe('Wipe with your flat hand');
await expect(page.locator('#seen .detail')).toHaveText('Your board said: pen (eraser button)');
const palm = (await page.evaluate(() => window.__obReport())).steps[2].seen;
@@ -114,23 +170,39 @@ test('Send posts the report to the relay and says thank you', async ({ page }) =
let body = null;
await page.route(RELAY, async (route) => {
body = JSON.parse(route.request().postData());
- route.fulfill({ contentType: 'application/json', headers: { 'Access-Control-Allow-Origin': '*' }, body: JSON.stringify({ ok: true, issue: 12, url: 'https://github.com/BPMData/OverBoard/issues/12' }) });
+ route.fulfill({
+ contentType: 'application/json',
+ headers: { 'Access-Control-Allow-Origin': '*' },
+ body: JSON.stringify({ ok: true, issue: 12, url: 'https://github.com/BPMData/OverBoard/issues/12' }),
+ });
});
await openReport(page, '?from=overlay&ov=v19');
await toReview(page);
await press(page, 'send');
await expect(page.locator('[data-screen="done"]')).toBeVisible();
- await expect(page.locator('[data-screen="done"] .issue')).toHaveAttribute('href', 'https://github.com/BPMData/OverBoard/issues/12');
- expect(body).toMatchObject({ app: 'OverBoard', kind: 'board-report', from: 'overlay', overlayVersion: 'v19', website: '',
+ await expect(page.locator('[data-screen="done"] .issue')).toHaveAttribute(
+ 'href',
+ 'https://github.com/BPMData/OverBoard/issues/12'
+ );
+ expect(body).toMatchObject({
+ app: 'OverBoard',
+ kind: 'board-report',
+ from: 'overlay',
+ overlayVersion: 'v19',
+ website: '',
answers: { brand: 'promethean', model: 'ActivPanel 9', problems: ['palm-draws'] },
- private: { email: 'teacher@example.com', comments: 'Room 12, the palm draws' } });
+ private: { email: 'teacher@example.com', comments: 'Room 12, the palm draws' },
+ });
expect(body.steps.map((s) => s.id)).toEqual(['finger', 'pen', 'palm', 'eraser', 'two']);
expect(body.system.browser).toMatch(/\d/);
});
test('when sending fails: download, copy, or email the report; no other site is contacted', async ({ page }) => {
const outside = [];
- await page.route(/^https?:\/\/(?!127\.0\.0\.1)/, (r) => { outside.push(r.request().url()); r.abort(); });
+ await page.route(/^https?:\/\/(?!127\.0\.0\.1)/, (r) => {
+ outside.push(r.request().url());
+ r.abort();
+ });
await openReport(page);
await toReview(page);
expect(outside).toEqual([]);
@@ -158,26 +230,42 @@ test('PDF app: File ▸ Board not working? and the start screen link open the re
test('HTML overlay: File ▸ Board not working? opens the website page with the overlay version', async ({ page }) => {
await openOverlay(page);
- await page.evaluate(() => { window.__opened = []; window.open = (u) => { window.__opened.push(u); return null; }; });
+ await page.evaluate(() => {
+ window.__opened = [];
+ window.open = (u) => {
+ window.__opened.push(u);
+ return null;
+ };
+ });
await page.click('#ink-bar [data-act="file"]');
await page.click('#ob-filemenu [data-act="report"]');
const v = (await page.content()).match(/INK OVERLAY START \((v\d+)\)/)[1];
- expect(await page.evaluate(() => window.__opened)).toEqual(['https://bpmdata.github.io/OverBoard/app/report/?from=overlay&ov=' + v + '&lang=en']);
+ expect(await page.evaluate(() => window.__opened)).toEqual([
+ 'https://bpmdata.github.io/OverBoard/app/report/?from=overlay&ov=' + v + '&lang=en',
+ ]);
await expect(page.locator('#ob-filemenu')).toBeHidden();
});
-test('the page speaks the language it was opened in, switches from its 🌐 list, and sends the language with the report', async ({ page }) => {
+test('the page speaks the language it was opened in, switches from its 🌐 list, and sends the language with the report', async ({
+ page,
+}) => {
let body = null;
await page.route(RELAY, async (route) => {
body = JSON.parse(route.request().postData());
- route.fulfill({ contentType: 'application/json', headers: { 'Access-Control-Allow-Origin': '*' }, body: JSON.stringify({ ok: true, issue: 3, url: 'https://github.com/BPMData/OverBoard/issues/3' }) });
+ route.fulfill({
+ contentType: 'application/json',
+ headers: { 'Access-Control-Allow-Origin': '*' },
+ body: JSON.stringify({ ok: true, issue: 3, url: 'https://github.com/BPMData/OverBoard/issues/3' }),
+ });
});
await openReport(page, '?from=overlay&ov=v24&lang=es');
await expect(page.locator('[data-screen="welcome"] h1')).toHaveText('¿OverBoard no funciona en tu pizarra?');
await expect(page.locator('#lang')).toHaveValue('es');
// the 🌐 list is on the first screen; switching changes every word at once
await page.selectOption('#lang', 'fr');
- await expect(page.locator('[data-screen="welcome"] h1')).toHaveText('OverBoard ne fonctionne pas sur votre tableau ?');
+ await expect(page.locator('[data-screen="welcome"] h1')).toHaveText(
+ 'OverBoard ne fonctionne pas sur votre tableau ?'
+ );
await expect(page.locator('[data-go="start"]')).toHaveText('Commencer');
await page.selectOption('#lang', 'ar');
await expect(page.locator('html')).toHaveAttribute('dir', 'rtl');
@@ -197,5 +285,5 @@ test('the page speaks the language it was opened in, switches from its 🌐 list
await press(page, 'send');
await expect(page.locator('[data-screen="done"] h1')).toHaveText('¡Gracias!');
expect(body.lang).toBe('es');
- expect(body.steps[0].asked).toBe('Draw 2 lines with your finger'); // the report itself stays in English for us
+ expect(body.steps[0].asked).toBe('Draw 2 lines with your finger'); // the report itself stays in English for us
});
diff --git a/tests/savefile.spec.js b/tests/savefile.spec.js
index dd48ba7..93eedb4 100644
--- a/tests/savefile.spec.js
+++ b/tests/savefile.spec.js
@@ -14,35 +14,87 @@ const inkIn = (html) => JSON.parse(DATA_RE.exec(html)[2]);
const withInk = (html, D) => html.replace(DATA_RE, (m, a, b, c) => a + JSON.stringify(D) + c);
async function fakePicker(page, name, text, refuse = 0) {
- await page.addInitScript(([name, text, refuse]) => {
- window.__file = text; window.__asked = 0;
- let perm = 'prompt', tapped = false, refusals = refuse;
- document.addEventListener('pointerdown', () => { tapped = true; }, true); // a tap lets the browser ask once
- const ask = window.confirm.bind(window);
- window.confirm = (m) => { tapped = false; return ask(m); }; // a question box uses the tap up
- const h = {
- kind: 'file', name,
- async getFile() { return new File([window.__file], name, { type: 'text/html' }); },
- async createWritable() {
- if (perm !== 'granted') throw new DOMException('not allowed', 'NotAllowedError');
- const parts = []; return { async write(b) { parts.push(b); }, async close() { window.__file = parts.join(''); }, async abort() {} };
- },
- async queryPermission() { return perm; },
- async requestPermission() {
- if (!tapped || refusals-- > 0) { tapped = false; throw new DOMException('User activation is required to request permissions.', 'SecurityError'); }
- tapped = false; window.__asked++; perm = 'granted'; return perm;
- },
- };
- window.showOpenFilePicker = async () => [h];
- }, [name, text, refuse]);
+ await page.addInitScript(
+ ([name, text, refuse]) => {
+ window.__file = text;
+ window.__asked = 0;
+ let perm = 'prompt',
+ tapped = false,
+ refusals = refuse;
+ document.addEventListener(
+ 'pointerdown',
+ () => {
+ tapped = true;
+ },
+ true
+ ); // a tap lets the browser ask once
+ const ask = window.confirm.bind(window);
+ window.confirm = (m) => {
+ tapped = false;
+ return ask(m);
+ }; // a question box uses the tap up
+ const h = {
+ kind: 'file',
+ name,
+ async getFile() {
+ return new File([window.__file], name, { type: 'text/html' });
+ },
+ async createWritable() {
+ if (perm !== 'granted') throw new DOMException('not allowed', 'NotAllowedError');
+ const parts = [];
+ return {
+ async write(b) {
+ parts.push(b);
+ },
+ async close() {
+ window.__file = parts.join('');
+ },
+ async abort() {},
+ };
+ },
+ async queryPermission() {
+ return perm;
+ },
+ async requestPermission() {
+ if (!tapped || refusals-- > 0) {
+ tapped = false;
+ throw new DOMException('User activation is required to request permissions.', 'SecurityError');
+ }
+ tapped = false;
+ window.__asked++;
+ perm = 'granted';
+ return perm;
+ },
+ };
+ window.showOpenFilePicker = async () => [h];
+ },
+ [name, text, refuse]
+ );
}
async function draw(page, y = 300) {
await page.evaluate(async (y) => {
- const c = document.getElementById('ink-canvas'), b = c.getBoundingClientRect();
- const ev = (t, x) => c.dispatchEvent(new PointerEvent(t, { bubbles: true, cancelable: true, pointerType: 'pen', pointerId: 3, buttons: t === 'pointerup' ? 0 : 1, button: 0, clientX: x, clientY: b.top + y }));
+ const c = document.getElementById('ink-canvas'),
+ b = c.getBoundingClientRect();
+ const ev = (t, x) =>
+ c.dispatchEvent(
+ new PointerEvent(t, {
+ bubbles: true,
+ cancelable: true,
+ pointerType: 'pen',
+ pointerId: 3,
+ buttons: t === 'pointerup' ? 0 : 1,
+ button: 0,
+ clientX: x,
+ clientY: b.top + y,
+ })
+ );
ev('pointerdown', b.left + 700);
- for (let x = 710; x <= 900; x += 10) { await new Promise((r) => setTimeout(r, 4)); ev('pointermove', b.left + x); }
- await new Promise((r) => setTimeout(r, 20)); ev('pointerup', b.left + 900);
+ for (let x = 710; x <= 900; x += 10) {
+ await new Promise((r) => setTimeout(r, 4));
+ ev('pointermove', b.left + x);
+ }
+ await new Promise((r) => setTimeout(r, 20));
+ ev('pointerup', b.left + 900);
}, y);
}
const saveBtn = (page) => page.locator('#ob-filemenu [data-act="savefile"]');
@@ -53,10 +105,13 @@ async function saveTap(page) {
async function open(page, file, again = false) {
await page.setViewportSize({ width: 1400, height: 900 });
// again: the file changed on disk; ask past the browser's cache (the test server only knows file times to the second)
- await page.goto(url(file) + (again ? '?' + Date.now() : '')); await overlayReady(page);
+ await page.goto(url(file) + (again ? '?' + Date.now() : ''));
+ await overlayReady(page);
}
-test('save ink into a differently named board copy: the browser asks before our "different file" question', async ({ page }, info) => {
+test('save ink into a differently named board copy: the browser asks before our "different file" question', async ({
+ page,
+}, info) => {
const inked = info.outputPath('pet_board_inked.html');
fs.writeFileSync(inked, DEMO);
await fakePicker(page, 'pet_board_clean.html', DEMO);
@@ -65,50 +120,64 @@ test('save ink into a differently named board copy: the browser asks before our
await page.click('#ink-bar [data-period="P2"]');
await draw(page, 400);
let asked = '';
- page.on('dialog', (d) => { asked = d.message(); d.accept(); });
- await saveTap(page); // the first tap explains
- await saveTap(page); // the second opens the file window
+ page.on('dialog', (d) => {
+ asked = d.message();
+ d.accept();
+ });
+ await saveTap(page); // the first tap explains
+ await saveTap(page); // the second opens the file window
await expect(saveBtn(page)).toHaveText('Saved to file!');
expect(asked).toContain('pet_board_clean.html');
expect(await page.evaluate(() => window.__asked)).toBe(1);
const ink = inkIn(await page.evaluate(() => window.__file));
- expect([ink.periods.P1.length, ink.periods.P2.length]).toEqual([1, 1]); // every period's ink
+ expect([ink.periods.P1.length, ink.periods.P2.length]).toEqual([1, 1]); // every period's ink
expect(ink.w).toBeGreaterThanOrEqual(ink.t);
});
-test('when the browser still won\'t ask, the button says to tap again, and the next tap saves', async ({ page }, info) => {
+test("when the browser still won't ask, the button says to tap again, and the next tap saves", async ({
+ page,
+}, info) => {
const inked = info.outputPath('pet_board.html');
fs.writeFileSync(inked, DEMO);
- await fakePicker(page, 'pet_board.html', DEMO, 1); // refuses the first time
+ await fakePicker(page, 'pet_board.html', DEMO, 1); // refuses the first time
await open(page, inked);
await draw(page);
await saveTap(page);
await saveTap(page);
await expect(saveBtn(page)).toHaveText('Tap again to allow');
- await expect(page.locator('#ob-filemenu')).toBeVisible(); // still open, the button right there
+ await expect(page.locator('#ob-filemenu')).toBeVisible(); // still open, the button right there
await saveBtn(page).click();
await expect(saveBtn(page)).toHaveText('Saved to file!');
expect(inkIn(await page.evaluate(() => window.__file)).periods.P1).toHaveLength(1);
});
-test('ink written into a board copy shows, even if this browser used that copy more recently than the ink was drawn', async ({ page }, info) => {
+test('ink written into a board copy shows, even if this browser used that copy more recently than the ink was drawn', async ({
+ page,
+}, info) => {
const clean = info.outputPath('pet_board_clean.html');
fs.writeFileSync(clean, DEMO);
await open(page, clean);
- await draw(page); // try the clean copy out, then clear it: this browser now keeps an empty, newer copy
- await page.click('#ink-bar [data-act="clear-all"]'); await page.click('#ink-bar [data-act="clear-all"]');
+ await draw(page); // try the clean copy out, then clear it: this browser now keeps an empty, newer copy
+ await page.click('#ink-bar [data-act="clear-all"]');
+ await page.click('#ink-bar [data-act="clear-all"]');
await page.evaluate(() => window.dispatchEvent(new Event('pagehide')));
await page.waitForTimeout(300);
// another browser (Edge) wrote ink drawn an hour ago into this file, just now
- const now = Date.now(), stroke = { c: '#111', w: 3, e: 0, p: [100, 100, 300, 100] };
- fs.writeFileSync(clean, withInk(DEMO, { v: 2, t: now - 3600e3, w: now, active: 'P1', periods: { P1: [stroke], P2: [], P3: [], P4: [] } }));
+ const now = Date.now(),
+ stroke = { c: '#111', w: 3, e: 0, p: [100, 100, 300, 100] };
+ fs.writeFileSync(
+ clean,
+ withInk(DEMO, { v: 2, t: now - 3600e3, w: now, active: 'P1', periods: { P1: [stroke], P2: [], P3: [], P4: [] } })
+ );
await open(page, clean, true);
await expect(page.locator('#ink-status')).toContainText('ink loaded from file');
- await page.click('#ink-bar [data-act="undo"]'); // the file's ink is what's on screen: Undo takes its line away
+ await page.click('#ink-bar [data-act="undo"]'); // the file's ink is what's on screen: Undo takes its line away
await expect(page.locator('#ink-bar [data-act="redo"]')).toBeEnabled();
});
-test('a file without OverBoard in it: Not saved!, said plainly, and the browser never asks to edit it', async ({ page }, info) => {
+test('a file without OverBoard in it: Not saved!, said plainly, and the browser never asks to edit it', async ({
+ page,
+}, info) => {
const inked = info.outputPath('pet_board.html');
fs.writeFileSync(inked, DEMO);
const plain = '
Plain worksheet
';
@@ -121,5 +190,5 @@ test('a file without OverBoard in it: Not saved!, said plainly, and the browser
await expect(saveBtn(page)).toHaveText('Not saved!');
await expect(page.locator('#ink-status')).toContainText("doesn't have OverBoard in it");
expect(await page.evaluate(() => window.__asked)).toBe(0);
- expect(await page.evaluate(() => window.__file)).toBe(plain); // untouched
+ expect(await page.evaluate(() => window.__file)).toBe(plain); // untouched
});
diff --git a/tests/select.spec.js b/tests/select.spec.js
index ebcd24e..a117a71 100644
--- a/tests/select.spec.js
+++ b/tests/select.spec.js
@@ -4,14 +4,21 @@ const { test } = require('@playwright/test');
const { expect, openApp, openPdf, strokes } = require('./support/app');
const { openOverlay, savedInk } = require('./support/overlay');
-const line = (x0, y0, x1, y1) => Array.from({ length: 31 }, (_, i) => [x0 + (x1 - x0) * i / 30, y0 + (y1 - y0) * i / 30]);
-const loop = (x0, y0, x1, y1) => [...line(x0, y0, x1, y0), ...line(x1, y0, x1, y1), ...line(x1, y1, x0, y1), ...line(x0, y1, x0, y0)];
+const line = (x0, y0, x1, y1) =>
+ Array.from({ length: 31 }, (_, i) => [x0 + ((x1 - x0) * i) / 30, y0 + ((y1 - y0) * i) / 30]);
+const loop = (x0, y0, x1, y1) => [
+ ...line(x0, y0, x1, y0),
+ ...line(x1, y0, x1, y1),
+ ...line(x1, y1, x0, y1),
+ ...line(x0, y1, x0, y0),
+];
const menu = (page) => page.locator('#ob-selmenu');
test.describe('PDF app', () => {
const draw = (page, pts, o) => page.evaluate(([pts, o]) => __t.stroke(1, pts, o), [pts, o || {}]);
test.beforeEach(async ({ page }) => {
- await openApp(page); await openPdf(page, 'worksheet.pdf');
+ await openApp(page);
+ await openPdf(page, 'worksheet.pdf');
await draw(page, line(100, 200, 300, 200));
await draw(page, line(100, 400, 300, 400));
});
@@ -25,9 +32,10 @@ test.describe('PDF app', () => {
await expect(menu(page)).toContainText('1 mark selected');
await expect(menu(page).locator('[data-to]')).toHaveText(['P2', 'P3', 'P4']);
await menu(page).locator('[data-to="P3"]').click();
- const p1 = await strokes(page, 'P1'), p3 = await strokes(page, 'P3');
+ const p1 = await strokes(page, 'P1'),
+ p3 = await strokes(page, 'P3');
expect(p1).toHaveLength(2);
- expect(p3).toEqual([p1[0]]); // the same mark, page and points
+ expect(p3).toEqual([p1[0]]); // the same mark, page and points
await expect(page.locator('#ink-status')).toContainText('P3');
// the toolbar's Select button turns it off and lets the selection go
await page.click('[data-act="select"]');
@@ -37,16 +45,16 @@ test.describe('PDF app', () => {
test('copy, switch period, tap and paste in the same spot; drag to move; Undo; Delete', async ({ page }) => {
await page.click('[data-act="select"]');
- await draw(page, loop(80, 150, 320, 450)); // both lines
+ await draw(page, loop(80, 150, 320, 450)); // both lines
await expect(menu(page)).toContainText('2 marks selected');
await menu(page).locator('[data-sel="copy"]').click();
await page.click('[data-period="P2"]');
await expect(page.locator('.ob-selbox')).toHaveCount(0);
- await draw(page, [[450, 300]]); // a tap on the page offers to paste
+ await draw(page, [[450, 300]]); // a tap on the page offers to paste
await expect(menu(page)).toContainText('Paste 2 marks');
await menu(page).locator('[data-sel="same"]').click();
expect(await strokes(page, 'P2')).toEqual(await strokes(page, 'P1'));
- await expect(page.locator('.ob-selbox')).toBeVisible(); // what was pasted is selected
+ await expect(page.locator('.ob-selbox')).toBeVisible(); // what was pasted is selected
// drag the selection 50 points down
await draw(page, line(200, 300, 200, 350));
const moved = await strokes(page, 'P2');
@@ -64,12 +72,12 @@ test.describe('PDF app', () => {
});
test('a copy looks like the ink on the page: erased parts stay erased', async ({ page }) => {
- await draw(page, line(200, 180, 200, 220), { type: 'pen', buttons: 32 }); // palm wipe across the middle of the top line
+ await draw(page, line(200, 180, 200, 220), { type: 'pen', buttons: 32 }); // palm wipe across the middle of the top line
await page.click('[data-act="select"]');
await draw(page, loop(80, 170, 320, 230));
await menu(page).locator('[data-to="P2"]').click();
const p2 = await strokes(page, 'P2');
- expect(p2.length).toBe(2); // the line, in two pieces, and no eraser
+ expect(p2.length).toBe(2); // the line, in two pieces, and no eraser
expect(p2.every((s) => !s.e)).toBe(true);
expect(Math.max(...p2[0].p.filter((_, i) => i % 2 === 0))).toBeLessThan(200);
expect(Math.min(...p2[1].p.filter((_, i) => i % 2 === 0))).toBeGreaterThan(200);
@@ -81,7 +89,7 @@ test.describe('PDF app', () => {
await page.keyboard.press('Escape');
await expect(page.locator('.ob-selbox')).toHaveCount(0);
await draw(page, loop(80, 170, 320, 230));
- await page.mouse.click(0, 0); // closes the menu, keeps the selection
+ await page.mouse.click(0, 0); // closes the menu, keeps the selection
await expect(menu(page)).toBeHidden();
const [x, y] = await page.evaluate(() => __t.client(1, 200, 200));
await page.mouse.click(x, y, { button: 'right' });
@@ -95,14 +103,36 @@ test.describe('PDF app', () => {
test.describe('HTML overlay', () => {
async function stroke(page, pts) {
- await page.evaluate((pts) => new Promise(async (res) => {
- const c = document.getElementById('ink-canvas');
- const ev = (t, x, y) => c.dispatchEvent(new PointerEvent(t, { bubbles: true, cancelable: true, pointerType: 'pen', pointerId: 3, buttons: t === 'pointerup' ? 0 : 1, button: 0, clientX: x, clientY: y, screenX: x, screenY: y }));
- ev('pointerdown', ...pts[0]);
- for (const p of pts.slice(1)) { await new Promise((r) => setTimeout(r, 4)); ev('pointermove', ...p); }
- await new Promise((r) => setTimeout(r, 20));
- ev('pointerup', ...pts[pts.length - 1]); res();
- }), pts);
+ await page.evaluate(
+ (pts) =>
+ new Promise(async (res) => {
+ const c = document.getElementById('ink-canvas');
+ const ev = (t, x, y) =>
+ c.dispatchEvent(
+ new PointerEvent(t, {
+ bubbles: true,
+ cancelable: true,
+ pointerType: 'pen',
+ pointerId: 3,
+ buttons: t === 'pointerup' ? 0 : 1,
+ button: 0,
+ clientX: x,
+ clientY: y,
+ screenX: x,
+ screenY: y,
+ })
+ );
+ ev('pointerdown', ...pts[0]);
+ for (const p of pts.slice(1)) {
+ await new Promise((r) => setTimeout(r, 4));
+ ev('pointermove', ...p);
+ }
+ await new Promise((r) => setTimeout(r, 20));
+ ev('pointerup', ...pts[pts.length - 1]);
+ res();
+ }),
+ pts
+ );
}
test.beforeEach(async ({ page }) => {
await page.setViewportSize({ width: 1400, height: 900 });
@@ -140,7 +170,7 @@ test.describe('HTML overlay', () => {
let ink = await savedInk(page);
expect(ink.periods.P3).toHaveLength(1);
const ys = ink.periods.P3[0].p.filter((_, i) => i % 2 === 1);
- expect(Math.abs(ys[0] - (ink.periods.P1[0].p[1] + 400))).toBeLessThan(2); // centered where the tap was
+ expect(Math.abs(ys[0] - (ink.periods.P1[0].p[1] + 400))).toBeLessThan(2); // centered where the tap was
await page.keyboard.press('Delete');
ink = await savedInk(page);
expect(ink.periods.P3).toHaveLength(0);
diff --git a/tests/settings.spec.js b/tests/settings.spec.js
index b07cfca..d6b2eaa 100644
--- a/tests/settings.spec.js
+++ b/tests/settings.spec.js
@@ -4,21 +4,49 @@ const { test } = require('@playwright/test');
const { expect, openApp, openPdf, fileMenu } = require('./support/app');
const { openOverlay, savedInk } = require('./support/overlay');
-const line = (x0, y0, x1, y1) => Array.from({ length: 31 }, (_, i) => [x0 + (x1 - x0) * i / 30, y0 + (y1 - y0) * i / 30]);
-const stroke = (page, pts) => page.evaluate((pts) => new Promise(async (res) => {
- const c = document.getElementById('ink-canvas');
- const ev = (t, x, y) => c.dispatchEvent(new PointerEvent(t, { bubbles: true, cancelable: true, pointerType: 'pen', pointerId: 3, buttons: t === 'pointerup' ? 0 : 1, button: 0, clientX: x, clientY: y }));
- ev('pointerdown', ...pts[0]);
- for (const p of pts.slice(1)) { await new Promise((r) => setTimeout(r, 4)); ev('pointermove', ...p); }
- await new Promise((r) => setTimeout(r, 20));
- ev('pointerup', ...pts[pts.length - 1]); res();
-}), pts);
+const line = (x0, y0, x1, y1) =>
+ Array.from({ length: 31 }, (_, i) => [x0 + ((x1 - x0) * i) / 30, y0 + ((y1 - y0) * i) / 30]);
+const stroke = (page, pts) =>
+ page.evaluate(
+ (pts) =>
+ new Promise(async (res) => {
+ const c = document.getElementById('ink-canvas');
+ const ev = (t, x, y) =>
+ c.dispatchEvent(
+ new PointerEvent(t, {
+ bubbles: true,
+ cancelable: true,
+ pointerType: 'pen',
+ pointerId: 3,
+ buttons: t === 'pointerup' ? 0 : 1,
+ button: 0,
+ clientX: x,
+ clientY: y,
+ })
+ );
+ ev('pointerdown', ...pts[0]);
+ for (const p of pts.slice(1)) {
+ await new Promise((r) => setTimeout(r, 4));
+ ev('pointermove', ...p);
+ }
+ await new Promise((r) => setTimeout(r, 20));
+ ev('pointerup', ...pts[pts.length - 1]);
+ res();
+ }),
+ pts
+ );
const periodButtons = (page) => page.locator('#ink-periods button').allTextContents();
-const openSettings = async (page) => { await fileMenu(page, 'settings'); await expect(page.locator('#ob-settings')).toBeVisible(); };
+const openSettings = async (page) => {
+ await fileMenu(page, 'settings');
+ await expect(page.locator('#ob-settings')).toBeVisible();
+};
const done = (page) => page.click('#ob-settings [data-s="done"]');
test.describe('HTML overlay', () => {
- test.beforeEach(async ({ page }) => { await page.setViewportSize({ width: 1400, height: 900 }); await openOverlay(page); });
+ test.beforeEach(async ({ page }) => {
+ await page.setViewportSize({ width: 1400, height: 900 });
+ await openOverlay(page);
+ });
test('a name style and more periods: 5 periods become one "▾" button with a list', async ({ page }) => {
await openSettings(page);
@@ -31,7 +59,13 @@ test.describe('HTML overlay', () => {
await expect(page.locator('#ob-settings')).toBeHidden();
expect(await periodButtons(page)).toEqual(['Block A ▾']);
await page.click('#ink-periods [data-act="period-menu"]');
- await expect(page.locator('#ob-permenu button')).toHaveText(['Block A', 'Block B', 'Block C', 'Block D', 'Block E']);
+ await expect(page.locator('#ob-permenu button')).toHaveText([
+ 'Block A',
+ 'Block B',
+ 'Block C',
+ 'Block D',
+ 'Block E',
+ ]);
await page.click('#ob-permenu [data-period="Block C"]');
await expect(page.locator('#ob-permenu')).toBeHidden();
expect(await periodButtons(page)).toEqual(['Block C ▾']);
@@ -42,7 +76,12 @@ test.describe('HTML overlay', () => {
expect(await page.evaluate(() => JSON.parse(localStorage.getItem('ob-periods')))).toEqual(Object.keys(d.periods));
// the toolbar still fits a 1080p board
await page.setViewportSize({ width: 1920, height: 950 });
- expect(await page.evaluate(() => { const b = document.getElementById('ink-bar'); return b.scrollHeight <= b.clientHeight; })).toBe(true);
+ expect(
+ await page.evaluate(() => {
+ const b = document.getElementById('ink-bar');
+ return b.scrollHeight <= b.clientHeight;
+ })
+ ).toBe(true);
});
test('renaming a period keeps its ink; typing does not undo ink', async ({ page }) => {
@@ -50,7 +89,7 @@ test.describe('HTML overlay', () => {
await openSettings(page);
const first = page.locator('#ob-settings .ob-names input').first();
await first.fill('Gold');
- await first.press('Control+z'); // the text box's own undo, not the ink's
+ await first.press('Control+z'); // the text box's own undo, not the ink's
await first.fill('Gold');
await done(page);
expect(await periodButtons(page)).toEqual(['Gold', 'P2', 'P3', 'P4']);
@@ -75,7 +114,7 @@ test.describe('HTML overlay', () => {
await page.click('#ob-settings [data-s="fewer"]');
page.once('dialog', (d) => d.dismiss());
await done(page);
- await expect(page.locator('#ob-settings')).toBeVisible(); // said no: nothing changed
+ await expect(page.locator('#ob-settings')).toBeVisible(); // said no: nothing changed
expect(await periodButtons(page)).toEqual(['P1', 'P2', 'P3', 'P4']);
page.once('dialog', (d) => d.accept());
await done(page);
@@ -127,6 +166,6 @@ test('PDF app: the same Settings in File ▸; new PDFs start with the saved peri
await page.click('[data-period="B1"]');
expect(await page.evaluate(() => window.__overboard.data.active)).toBe('B1');
await fileMenu(page, 'close');
- await openPdf(page, 'book.pdf'); // a PDF opened for the first time
+ await openPdf(page, 'book.pdf'); // a PDF opened for the first time
expect(await periodButtons(page)).toEqual(['A1', 'A2', 'B1', 'B2']);
});
diff --git a/tests/site.spec.js b/tests/site.spec.js
index ee84a0e..3931f3a 100644
--- a/tests/site.spec.js
+++ b/tests/site.spec.js
@@ -8,7 +8,7 @@ test('every app module loads at the current version', async ({ page }) => {
page.on('request', (r) => urls.push(r.url()));
await openApp(page);
const mods = urls.filter((u) => /\/(app|shared)\/[\w-]+\.js(\?|$)/.test(u));
- expect(mods.length).toBeGreaterThanOrEqual(version.js.length - 1); // export.js loads on first export
+ expect(mods.length).toBeGreaterThanOrEqual(version.js.length - 1); // export.js loads on first export
for (const u of mods) expect(u).toMatch(new RegExp(`\\?v=${version.v}$`));
});
@@ -31,7 +31,10 @@ test('the app still starts if version.json cannot be read', async ({ page }) =>
test('opening and exporting a PDF contacts no other site', async ({ page }) => {
const outside = [];
- await page.route(/^https?:\/\/(?!127\.0\.0\.1)/, (r) => { outside.push(r.request().url()); r.abort(); });
+ await page.route(/^https?:\/\/(?!127\.0\.0\.1)/, (r) => {
+ outside.push(r.request().url());
+ r.abort();
+ });
await openApp(page);
await openPdf(page, 'book.pdf');
await page.evaluate(() => __t.stroke(1, __t.line(100, 100, 300, 100)));
@@ -41,13 +44,17 @@ test('opening and exporting a PDF contacts no other site', async ({ page }) => {
});
test('the toolbar fits a 1080p board without scrolling; File menu opens beside it', async ({ page }) => {
- await page.setViewportSize({ width: 1920, height: 950 }); // Chrome's page area on a 1920x1080 screen
+ await page.setViewportSize({ width: 1920, height: 950 }); // Chrome's page area on a 1920x1080 screen
await openApp(page);
await openPdf(page, 'book.pdf');
- const bar = await page.evaluate(() => { const b = document.getElementById('ink-bar'); return { scroll: b.scrollHeight, client: b.clientHeight }; });
+ const bar = await page.evaluate(() => {
+ const b = document.getElementById('ink-bar');
+ return { scroll: b.scrollHeight, client: b.clientHeight };
+ });
expect(bar.scroll).toBeLessThanOrEqual(bar.client);
await page.click('[data-act="file"]');
- const box = await page.locator('#ob-filemenu').boundingBox(), barBox = await page.locator('#ink-bar').boundingBox();
+ const box = await page.locator('#ob-filemenu').boundingBox(),
+ barBox = await page.locator('#ink-bar').boundingBox();
expect(box.x).toBeGreaterThan(barBox.x + barBox.width);
expect(box.y + box.height).toBeLessThanOrEqual(950);
await page.mouse.click(1000, 500);
diff --git a/tests/support/app.js b/tests/support/app.js
index 2636e33..2dc9eb2 100644
--- a/tests/support/app.js
+++ b/tests/support/app.js
@@ -9,7 +9,7 @@ async function openApp(page, { fakeFs = false } = {}) {
await page.addInitScript({ path: path.join(__dirname, 'pointer.js') });
if (fakeFs) await page.addInitScript({ path: path.join(__dirname, 'fakefs.js') });
await page.goto('app/');
- await page.waitForFunction(() => window.__overboard); // the loader has started the app
+ await page.waitForFunction(() => window.__overboard); // the loader has started the app
}
async function openPdf(page, name) {
@@ -36,9 +36,25 @@ async function download(page, action) {
async function tap(page, x, y, pointerType = 'pen') {
const s = await page.context().newCDPSession(page);
await s.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, pointerType });
- await s.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', buttons: 1, clickCount: 1, pointerType });
- await new Promise((r) => setTimeout(r, 40)); // the app drops sub-15 ms blips (hand/pen switching)
- await s.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', buttons: 0, clickCount: 1, pointerType });
+ await s.send('Input.dispatchMouseEvent', {
+ type: 'mousePressed',
+ x,
+ y,
+ button: 'left',
+ buttons: 1,
+ clickCount: 1,
+ pointerType,
+ });
+ await new Promise((r) => setTimeout(r, 40)); // the app drops sub-15 ms blips (hand/pen switching)
+ await s.send('Input.dispatchMouseEvent', {
+ type: 'mouseReleased',
+ x,
+ y,
+ button: 'left',
+ buttons: 0,
+ clickCount: 1,
+ pointerType,
+ });
await s.detach();
}
async function tapOn(page, selector, pointerType) {
diff --git a/tests/support/fakefs.js b/tests/support/fakefs.js
index ff6a870..d46234b 100644
--- a/tests/support/fakefs.js
+++ b/tests/support/fakefs.js
@@ -3,12 +3,34 @@ window.__files = {};
window.__pickName = null;
function fakeHandle(name) {
return {
- kind: 'file', name,
- async getFile() { return new File([window.__files[name] || new Blob()], name, { type: 'application/pdf' }); },
- async createWritable() { const parts = []; return { async write(b) { parts.push(b); }, async close() { window.__files[name] = new Blob(parts); window.__writes = (window.__writes || 0) + 1; }, async abort() {} }; },
- async queryPermission() { return window.__perm || 'granted'; },
- async requestPermission() { return 'granted'; },
+ kind: 'file',
+ name,
+ async getFile() {
+ return new File([window.__files[name] || new Blob()], name, { type: 'application/pdf' });
+ },
+ async createWritable() {
+ const parts = [];
+ return {
+ async write(b) {
+ parts.push(b);
+ },
+ async close() {
+ window.__files[name] = new Blob(parts);
+ window.__writes = (window.__writes || 0) + 1;
+ },
+ async abort() {},
+ };
+ },
+ async queryPermission() {
+ return window.__perm || 'granted';
+ },
+ async requestPermission() {
+ return 'granted';
+ },
};
}
-window.showSaveFilePicker = async (o) => { window.__pickOpts = o; return fakeHandle(window.__pickName || o.suggestedName); };
+window.showSaveFilePicker = async (o) => {
+ window.__pickOpts = o;
+ return fakeHandle(window.__pickName || o.suggestedName);
+};
window.__fileBytes = async (name) => Array.from(new Uint8Array(await window.__files[name].arrayBuffer()));
diff --git a/tests/support/overlay.js b/tests/support/overlay.js
index fb37b83..6d9bb79 100644
--- a/tests/support/overlay.js
+++ b/tests/support/overlay.js
@@ -8,18 +8,30 @@ async function openOverlay(page, url = './') {
const overlayReady = (page) => page.waitForSelector('#ink-bar[data-ready]', { state: 'attached' });
/* save now (as if the tab closed) and return this worksheet's ink as saved in IndexedDB */
-const savedInk = (page) => page.evaluate(async () => {
- window.dispatchEvent(new Event('pagehide'));
- const key = Object.keys(localStorage).find((k) => k.startsWith('ink-v2:'));
- for (let i = 0; i < 100 && key && localStorage.getItem(key) !== null; i++) await new Promise((r) => setTimeout(r, 20)); // the backup goes once IndexedDB has the ink
- const db = await new Promise((res, rej) => { const rq = indexedDB.open('ink-data'); rq.onsuccess = () => res(rq.result); rq.onerror = rej; });
- const prefix = 'ink-v2:' + location.pathname + ':';
- const out = await new Promise((res) => {
- const st = db.transaction('ink').objectStore('ink'), rq = st.getAllKeys();
- rq.onsuccess = () => { const k = rq.result.find((k) => k.startsWith(prefix)); if (!k) return res(null); const g = st.get(k); g.onsuccess = () => res(g.result); };
+const savedInk = (page) =>
+ page.evaluate(async () => {
+ window.dispatchEvent(new Event('pagehide'));
+ const key = Object.keys(localStorage).find((k) => k.startsWith('ink-v2:'));
+ for (let i = 0; i < 100 && key && localStorage.getItem(key) !== null; i++)
+ await new Promise((r) => setTimeout(r, 20)); // the backup goes once IndexedDB has the ink
+ const db = await new Promise((res, rej) => {
+ const rq = indexedDB.open('ink-data');
+ rq.onsuccess = () => res(rq.result);
+ rq.onerror = rej;
+ });
+ const prefix = 'ink-v2:' + location.pathname + ':';
+ const out = await new Promise((res) => {
+ const st = db.transaction('ink').objectStore('ink'),
+ rq = st.getAllKeys();
+ rq.onsuccess = () => {
+ const k = rq.result.find((k) => k.startsWith(prefix));
+ if (!k) return res(null);
+ const g = st.get(k);
+ g.onsuccess = () => res(g.result);
+ };
+ });
+ db.close();
+ return out;
});
- db.close();
- return out;
-});
module.exports = { openOverlay, overlayReady, savedInk };
diff --git a/tests/support/pointer.js b/tests/support/pointer.js
index de40034..59da18e 100644
--- a/tests/support/pointer.js
+++ b/tests/support/pointer.js
@@ -1,26 +1,56 @@
// Injected into test pages: draw with synthetic pointer events at page coordinates (PDF points), read ink pixels.
window.__t = {
client(n, x, y) {
- const { viewer } = window.__overboard, P = viewer.pages[n - 1], r = P.el.getBoundingClientRect(), z = viewer.zoom;
+ const { viewer } = window.__overboard,
+ P = viewer.pages[n - 1],
+ r = P.el.getBoundingClientRect(),
+ z = viewer.zoom;
return [r.left + (x + 36) * z, r.top + y * z];
},
async stroke(n, pts, o = {}) {
- const type = o.type || 'pen', buttons = o.buttons || 1, id = o.id || 7;
+ const type = o.type || 'pen',
+ buttons = o.buttons || 1,
+ id = o.id || 7;
const box = document.getElementById('ob-pages');
const ev = (t, x, y) => {
const target = document.elementFromPoint(x, y) || box;
- target.dispatchEvent(new PointerEvent(t, { bubbles: true, cancelable: true, composed: true, pointerType: type, pointerId: id, isPrimary: true, buttons: t === 'pointerup' ? 0 : buttons, button: t === 'pointermove' ? -1 : (buttons & 32 ? 5 : 0), clientX: x, clientY: y, screenX: x, screenY: y }));
+ target.dispatchEvent(
+ new PointerEvent(t, {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ pointerType: type,
+ pointerId: id,
+ isPrimary: true,
+ buttons: t === 'pointerup' ? 0 : buttons,
+ button: t === 'pointermove' ? -1 : buttons & 32 ? 5 : 0,
+ clientX: x,
+ clientY: y,
+ screenX: x,
+ screenY: y,
+ })
+ );
};
let c = this.client(n, pts[0][0], pts[0][1]);
ev('pointerdown', c[0], c[1]);
- for (const p of pts.slice(1)) { await new Promise(r => setTimeout(r, 4)); const k = o.fixedScreen ? null : this.client(n, p[0], p[1]); c = k || c; ev('pointermove', c[0], c[1]); }
- await new Promise(r => setTimeout(r, 20));
+ for (const p of pts.slice(1)) {
+ await new Promise((r) => setTimeout(r, 4));
+ const k = o.fixedScreen ? null : this.client(n, p[0], p[1]);
+ c = k || c;
+ ev('pointermove', c[0], c[1]);
+ }
+ await new Promise((r) => setTimeout(r, 20));
ev('pointerup', c[0], c[1]);
},
- line(x0, y0, x1, y1, k = 30) { const a = []; for (let i = 0; i <= k; i++) a.push([x0 + (x1 - x0) * i / k, y0 + (y1 - y0) * i / k]); return a; },
+ line(x0, y0, x1, y1, k = 30) {
+ const a = [];
+ for (let i = 0; i <= k; i++) a.push([x0 + ((x1 - x0) * i) / k, y0 + ((y1 - y0) * i) / k]);
+ return a;
+ },
// read a pixel's alpha/color off a page's ink canvas at page point (x,y)
px(n, x, y, layer = 'ink') {
- const P = window.__overboard.viewer.pages[n - 1], c = P[layer];
+ const P = window.__overboard.viewer.pages[n - 1],
+ c = P[layer];
if (!c) return null;
const d = c.getContext('2d').getImageData(Math.round(c._ox + x * c._sc), Math.round(y * c._sc), 1, 1).data;
return Array.from(d);
diff --git a/tests/support/render.js b/tests/support/render.js
index e9e5bb5..60fdbc3 100644
--- a/tests/support/render.js
+++ b/tests/support/render.js
@@ -4,21 +4,31 @@ const fs = require('fs');
async function pdfPixels(page, file, pageNo, points) {
const b64 = fs.readFileSync(file).toString('base64');
- return page.evaluate(async ({ b64, pageNo, points }) => {
- const lib = await import(new URL('vendor/pdfjs-dist@4.10.38/pdf.min.mjs', new URL('/app/', location.href)).href);
- lib.GlobalWorkerOptions.workerSrc = new URL('/app/vendor/pdfjs-dist@4.10.38/pdf.worker.min.mjs', location.href).href;
- const data = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
- const pdf = await lib.getDocument({ data }).promise;
- const pg = await pdf.getPage(pageNo), vp = pg.getViewport({ scale: 2 });
- const c = document.createElement('canvas');
- c.width = vp.width; c.height = vp.height;
- const g = c.getContext('2d', { willReadFrequently: true });
- await pg.render({ canvasContext: g, viewport: vp }).promise;
- const out = points.map(([x, y]) => Array.from(g.getImageData(Math.round(x * 2), Math.round(y * 2), 1, 1).data.slice(0, 3)));
- const attachments = await pdf.getAttachments();
- await pdf.destroy();
- return { pages: pdf.numPages, px: out, attachments: attachments ? Object.keys(attachments) : [] };
- }, { b64, pageNo, points });
+ return page.evaluate(
+ async ({ b64, pageNo, points }) => {
+ const lib = await import(new URL('vendor/pdfjs-dist@4.10.38/pdf.min.mjs', new URL('/app/', location.href)).href);
+ lib.GlobalWorkerOptions.workerSrc = new URL(
+ '/app/vendor/pdfjs-dist@4.10.38/pdf.worker.min.mjs',
+ location.href
+ ).href;
+ const data = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
+ const pdf = await lib.getDocument({ data }).promise;
+ const pg = await pdf.getPage(pageNo),
+ vp = pg.getViewport({ scale: 2 });
+ const c = document.createElement('canvas');
+ c.width = vp.width;
+ c.height = vp.height;
+ const g = c.getContext('2d', { willReadFrequently: true });
+ await pg.render({ canvasContext: g, viewport: vp }).promise;
+ const out = points.map(([x, y]) =>
+ Array.from(g.getImageData(Math.round(x * 2), Math.round(y * 2), 1, 1).data.slice(0, 3))
+ );
+ const attachments = await pdf.getAttachments();
+ await pdf.destroy();
+ return { pages: pdf.numPages, px: out, attachments: attachments ? Object.keys(attachments) : [] };
+ },
+ { b64, pageNo, points }
+ );
}
/* the text (per page) and link annotations a PDF file carries, read with PDF.js like any PDF reader would */
@@ -26,14 +36,19 @@ async function pdfText(page, file) {
const b64 = fs.readFileSync(file).toString('base64');
return page.evaluate(async (b64) => {
const lib = await import(new URL('vendor/pdfjs-dist@4.10.38/pdf.min.mjs', new URL('/app/', location.href)).href);
- lib.GlobalWorkerOptions.workerSrc = new URL('/app/vendor/pdfjs-dist@4.10.38/pdf.worker.min.mjs', location.href).href;
+ lib.GlobalWorkerOptions.workerSrc = new URL(
+ '/app/vendor/pdfjs-dist@4.10.38/pdf.worker.min.mjs',
+ location.href
+ ).href;
const data = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
const pdf = await lib.getDocument({ data }).promise;
- const text = [], links = [];
+ const text = [],
+ links = [];
for (let n = 1; n <= pdf.numPages; n++) {
const pg = await pdf.getPage(n);
text.push((await pg.getTextContent()).items.map((i) => i.str).join(' '));
- for (const a of await pg.getAnnotations()) if (a.subtype === 'Link') links.push({ page: n, url: a.url || null, dest: !!a.dest });
+ for (const a of await pg.getAnnotations())
+ if (a.subtype === 'Link') links.push({ page: n, url: a.url || null, dest: !!a.dest });
}
await pdf.destroy();
return { text, links };
diff --git a/tests/support/site.js b/tests/support/site.js
index 3a2c156..8604752 100644
--- a/tests/support/site.js
+++ b/tests/support/site.js
@@ -7,19 +7,34 @@ const http = require('http');
const { execFileSync } = require('child_process');
const ROOT = path.join(__dirname, '..', '..');
-const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png' };
+const TYPES = {
+ '.html': 'text/html',
+ '.js': 'text/javascript',
+ '.mjs': 'text/javascript',
+ '.css': 'text/css',
+ '.json': 'application/json',
+ '.png': 'image/png',
+};
-async function serveCopy(handlers = {}) { // handlers: { '/path': (url, res) => ... } for test-only endpoints
+async function serveCopy(handlers = {}) {
+ // handlers: { '/path': (url, res) => ... } for test-only endpoints
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'overboard-'));
- for (const p of ['app', 'shared', 'tools', 'overlay', 'index.html']) fs.cpSync(path.join(ROOT, p), path.join(dir, p), { recursive: true });
+ for (const p of ['app', 'shared', 'tools', 'overlay', 'index.html'])
+ fs.cpSync(path.join(ROOT, p), path.join(dir, p), { recursive: true });
const server = http.createServer((req, res) => {
const u = new URL(req.url, 'http://x');
if (handlers[u.pathname]) return handlers[u.pathname](u, res);
let p = decodeURIComponent(u.pathname);
if (p.endsWith('/')) p += 'index.html';
const file = path.join(dir, path.normalize(p));
- if (!file.startsWith(dir) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) { res.writeHead(404); return res.end(); }
- res.writeHead(200, { 'Content-Type': TYPES[path.extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache' });
+ if (!file.startsWith(dir) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) {
+ res.writeHead(404);
+ return res.end();
+ }
+ res.writeHead(200, {
+ 'Content-Type': TYPES[path.extname(file)] || 'application/octet-stream',
+ 'Cache-Control': 'no-cache',
+ });
res.end(fs.readFileSync(file));
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
@@ -30,7 +45,10 @@ async function serveCopy(handlers = {}) { // handlers: { '/path': (url, res) =
write: (rel, text) => fs.writeFileSync(path.join(dir, rel), text),
build: () => execFileSync('python3', [path.join(dir, 'tools', 'build.py')], { stdio: 'pipe' }),
swVersion: () => /const VERSION = '(\w+)'/.exec(site.read('app/sw.js'))[1],
- close: () => { server.close(); fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); },
+ close: () => {
+ server.close();
+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
+ },
};
return site;
}
@@ -39,15 +57,24 @@ async function serveCopy(handlers = {}) { // handlers: { '/path': (url, res) =
const swReady = (page) => page.evaluate(() => navigator.serviceWorker.ready.then((r) => r.active.scriptURL));
/* in the page: check for a new version and wait for its download to finish or fail */
-const swUpdate = (page) => page.evaluate(async () => {
- const reg = await navigator.serviceWorker.getRegistration();
- const found = new Promise((res) => reg.addEventListener('updatefound', () => {
- const w = reg.installing;
- w.addEventListener('statechange', () => { if (w.state === 'installed' || w.state === 'redundant') res(w.state); });
- }, { once: true }));
- await reg.update();
- return found;
-});
+const swUpdate = (page) =>
+ page.evaluate(async () => {
+ const reg = await navigator.serviceWorker.getRegistration();
+ const found = new Promise((res) =>
+ reg.addEventListener(
+ 'updatefound',
+ () => {
+ const w = reg.installing;
+ w.addEventListener('statechange', () => {
+ if (w.state === 'installed' || w.state === 'redundant') res(w.state);
+ });
+ },
+ { once: true }
+ )
+ );
+ await reg.update();
+ return found;
+ });
const cacheNames = (page) => page.evaluate(() => caches.keys());
diff --git a/tests/text.spec.js b/tests/text.spec.js
index 9520715..67d74da 100644
--- a/tests/text.spec.js
+++ b/tests/text.spec.js
@@ -11,33 +11,57 @@ test.beforeEach(async ({ page }) => {
await page.setViewportSize({ width: 1600, height: 1000 });
});
-const textReady = (page, n) => page.waitForFunction((n) => {
- const v = __overboard.viewer, P = v.pages[n - 1];
- return P.text && P.text.div.querySelector('.endOfContent') && P.imgZoom === v.zoom;
-}, n);
-const go = async (page, n) => { await page.evaluate((n) => __overboard.viewer.goTo(n), n); await textReady(page, n); };
+const textReady = (page, n) =>
+ page.waitForFunction((n) => {
+ const v = __overboard.viewer,
+ P = v.pages[n - 1];
+ return P.text && P.text.div.querySelector('.endOfContent') && P.imgZoom === v.zoom;
+ }, n);
+const go = async (page, n) => {
+ await page.evaluate((n) => __overboard.viewer.goTo(n), n);
+ await textReady(page, n);
+};
/* where a text span is on screen: its rect, and screen points 10%/50%/90% along its text */
-const span = (page, n, start) => page.evaluate(([n, start]) => {
- const P = __overboard.viewer.pages[n - 1];
- const el = [...P.text.div.querySelectorAll('span')].find((s) => s.textContent.startsWith(start));
- const r = el.getBoundingClientRect();
- const along = (f) => r.width > r.height ? [r.left + f * r.width, r.top + r.height / 2] : [r.left + r.width / 2, r.top + f * r.height];
- return { w: r.width, h: r.height, pts: [0.1, 0.5, 0.9].map(along) };
-}, [n, start]);
+const span = (page, n, start) =>
+ page.evaluate(
+ ([n, start]) => {
+ const P = __overboard.viewer.pages[n - 1];
+ const el = [...P.text.div.querySelectorAll('span')].find((s) => s.textContent.startsWith(start));
+ const r = el.getBoundingClientRect();
+ const along = (f) =>
+ r.width > r.height
+ ? [r.left + f * r.width, r.top + r.height / 2]
+ : [r.left + r.width / 2, r.top + f * r.height];
+ return { w: r.width, h: r.height, pts: [0.1, 0.5, 0.9].map(along) };
+ },
+ [n, start]
+ );
/* brightness of the rendered page image under a screen point */
-const imgAt = (page, n, [x, y]) => page.evaluate(([n, x, y]) => {
- const P = __overboard.viewer.pages[n - 1], r = P.sheet.getBoundingClientRect();
- const d = P.img.getContext('2d').getImageData(Math.floor((x - r.left) * P.img.width / r.width), Math.floor((y - r.top) * P.img.height / r.height), 1, 1).data;
- return d[0] + d[1] + d[2];
-}, [n, x, y]);
+const imgAt = (page, n, [x, y]) =>
+ page.evaluate(
+ ([n, x, y]) => {
+ const P = __overboard.viewer.pages[n - 1],
+ r = P.sheet.getBoundingClientRect();
+ const d = P.img
+ .getContext('2d')
+ .getImageData(
+ Math.floor(((x - r.left) * P.img.width) / r.width),
+ Math.floor(((y - r.top) * P.img.height) / r.height),
+ 1,
+ 1
+ ).data;
+ return d[0] + d[1] + d[2];
+ },
+ [n, x, y]
+ );
const linkCenter = async (page, i) => {
await page.waitForFunction(() => __overboard.viewer.pages[0].text?.links);
return page.evaluate((i) => {
- const r = __overboard.viewer.pages[0].text.links.children[i].getBoundingClientRect();
- return [r.left + r.width / 2, r.top + r.height / 2];
+ const r = __overboard.viewer.pages[0].text.links.children[i].getBoundingClientRect();
+ return [r.left + r.width / 2, r.top + r.height / 2];
}, i);
};
@@ -54,7 +78,8 @@ test('text lines up with the page image at every zoom, on portrait, landscape an
expect(long / zoom, `page ${n} zoom ${z}: text length in points`).toBeGreaterThan(150);
expect(long / zoom, `page ${n} zoom ${z}: text length in points`).toBeLessThan(260);
expect(s.h > s.w, `page ${n}: runs down the page only when rotated`).toBe(n === 4);
- for (const p of s.pts) expect(await imgAt(page, n, p), `page ${n} zoom ${z}: over the scanned heading`).toBeLessThan(200);
+ for (const p of s.pts)
+ expect(await imgAt(page, n, p), `page ${n} zoom ${z}: over the scanned heading`).toBeLessThan(200);
}
}
});
@@ -66,29 +91,57 @@ test('the text never takes the pen, palm or a Type tap', async ({ page }) => {
const [x, y] = (await span(page, 2, 'Answer key line 1')).pts[1];
const onText = () => page.evaluate(([x, y]) => !!document.elementFromPoint(x, y).closest('.textLayer'), [x, y]);
expect(await onText()).toBe(false);
- await page.evaluate(() => __t.stroke(2, __t.line(80, 170, 400, 170))); // right across the text
+ await page.evaluate(() => __t.stroke(2, __t.line(80, 170, 400, 170))); // right across the text
expect(await strokes(page)).toHaveLength(1);
- await page.evaluate(() => __t.stroke(2, __t.line(200, 150, 200, 200), { buttons: 32 })); // palm
+ await page.evaluate(() => __t.stroke(2, __t.line(200, 150, 200, 200), { buttons: 32 })); // palm
expect((await strokes(page)).slice(-1)[0].e).toBe(1);
await page.click('[data-act="type"]');
expect(await onText()).toBe(false);
});
-test('Type: a drag on the PDF text selects and copies it; a tap on it types a note; a drag beside it scrolls', async ({ page, context }) => {
+test('Type: a drag on the PDF text selects and copies it; a tap on it types a note; a drag beside it scrolls', async ({
+ page,
+ context,
+}) => {
await context.grantPermissions(['clipboard-read', 'clipboard-write']);
await openApp(page);
await openPdf(page, 'links.pdf');
await go(page, 2);
await page.click('[data-act="type"]');
const s = await span(page, 2, 'Answer key line 1:');
- const from = [s.pts[0][0] - 0.08 * s.w, s.pts[0][1]], to = [s.pts[2][0] + 0.09 * s.w, s.pts[2][1]];
+ const from = [s.pts[0][0] - 0.08 * s.w, s.pts[0][1]],
+ to = [s.pts[2][0] + 0.09 * s.w, s.pts[2][1]];
const y0 = await page.evaluate(() => scrollY);
- await page.evaluate(([a, b]) => new Promise(async (res) => { // a pen drag in screen coordinates
- const ev = (t, x, y) => (document.elementFromPoint(x, y) || document.body).dispatchEvent(new PointerEvent(t, { bubbles: true, cancelable: true, pointerType: 'pen', pointerId: 5, isPrimary: true, buttons: t === 'pointerup' ? 0 : 1, button: t === 'pointermove' ? -1 : 0, clientX: x, clientY: y, screenX: x, screenY: y }));
- ev('pointerdown', ...a);
- for (let i = 1; i <= 10; i++) { await new Promise((r) => setTimeout(r, 4)); ev('pointermove', a[0] + (b[0] - a[0]) * i / 10, a[1] + (b[1] - a[1]) * i / 10); }
- ev('pointerup', ...b); res();
- }), [from, to]);
+ await page.evaluate(
+ ([a, b]) =>
+ new Promise(async (res) => {
+ // a pen drag in screen coordinates
+ const ev = (t, x, y) =>
+ (document.elementFromPoint(x, y) || document.body).dispatchEvent(
+ new PointerEvent(t, {
+ bubbles: true,
+ cancelable: true,
+ pointerType: 'pen',
+ pointerId: 5,
+ isPrimary: true,
+ buttons: t === 'pointerup' ? 0 : 1,
+ button: t === 'pointermove' ? -1 : 0,
+ clientX: x,
+ clientY: y,
+ screenX: x,
+ screenY: y,
+ })
+ );
+ ev('pointerdown', ...a);
+ for (let i = 1; i <= 10; i++) {
+ await new Promise((r) => setTimeout(r, 4));
+ ev('pointermove', a[0] + ((b[0] - a[0]) * i) / 10, a[1] + ((b[1] - a[1]) * i) / 10);
+ }
+ ev('pointerup', ...b);
+ res();
+ }),
+ [from, to]
+ );
expect(await page.evaluate(() => getSelection().toString())).toContain('Answer key line 1');
expect(await page.evaluate(() => scrollY)).toBe(y0);
await expect(page.locator('#ink-status')).toContainText('Text copied');
@@ -101,7 +154,10 @@ test('Type: a drag on the PDF text selects and copies it; a tap on it types a no
expect(await page.evaluate(() => getSelection().toString())).toBe('');
});
-test('links: a finger tap follows them (contents entries jump inside the PDF, web links open a new tab); the pen writes over them', async ({ page, context }) => {
+test('links: a finger tap follows them (contents entries jump inside the PDF, web links open a new tab); the pen writes over them', async ({
+ page,
+ context,
+}) => {
await context.route('https://example.org/**', (r) => r.fulfill({ body: 'ok' }));
await openApp(page);
await openPdf(page, 'links.pdf');
@@ -116,10 +172,10 @@ test('links: a finger tap follows them (contents entries jump inside the PDF, we
expect(await current(page)).toBe(1);
await page.click('[data-act="undo"]');
- await tap(page, ...(await linkCenter(page, 1)), 'mouse'); // finger (the board sends "mouse"): Chapter 2 -> page 3
+ await tap(page, ...(await linkCenter(page, 1)), 'mouse'); // finger (the board sends "mouse"): Chapter 2 -> page 3
await expect.poll(current).toBe(3);
await go(page, 1);
- await tap(page, ...(await linkCenter(page, 2)), 'mouse'); // Chapter 3 -> page 4
+ await tap(page, ...(await linkCenter(page, 2)), 'mouse'); // Chapter 3 -> page 4
await expect.poll(current).toBe(4);
await go(page, 1);
const [tab] = await Promise.all([context.waitForEvent('page'), tap(page, ...(await linkCenter(page, 3)), 'mouse')]);
@@ -184,7 +240,9 @@ test('Find text searches the whole book and jumps to the match', async ({ page }
await expect(page.locator('#ob-find')).toBeHidden();
expect(await page.locator('mark.hit').count()).toBe(0);
- await fileMenu(page, 'find'); // also in the File menu
+ await fileMenu(page, 'find'); // also in the File menu
await page.fill('#ob-find-q', 'chapter 16. lorem');
- await expect(page.locator('#ob-find .msg')).toHaveText('Showing the first 500 matches. Try more words.', { timeout: 30000 }); // 600 in chapter 16
+ await expect(page.locator('#ob-find .msg')).toHaveText('Showing the first 500 matches. Try more words.', {
+ timeout: 30000,
+ }); // 600 in chapter 16
});
diff --git a/tests/timer.spec.js b/tests/timer.spec.js
index f450d27..1e4f247 100644
--- a/tests/timer.spec.js
+++ b/tests/timer.spec.js
@@ -22,10 +22,19 @@ const audio = (page) => page.evaluate(() => ({ ...window.__audio }));
/* a tiny real .wav file (0.1 s of silence) */
function wav(samples = 800) {
const b = Buffer.alloc(44 + samples * 2);
- b.write('RIFF', 0); b.writeUInt32LE(36 + samples * 2, 4); b.write('WAVE', 8);
- b.write('fmt ', 12); b.writeUInt32LE(16, 16); b.writeUInt16LE(1, 20); b.writeUInt16LE(1, 22);
- b.writeUInt32LE(8000, 24); b.writeUInt32LE(16000, 28); b.writeUInt16LE(2, 32); b.writeUInt16LE(16, 34);
- b.write('data', 36); b.writeUInt32LE(samples * 2, 40);
+ b.write('RIFF', 0);
+ b.writeUInt32LE(36 + samples * 2, 4);
+ b.write('WAVE', 8);
+ b.write('fmt ', 12);
+ b.writeUInt32LE(16, 16);
+ b.writeUInt16LE(1, 20);
+ b.writeUInt16LE(1, 22);
+ b.writeUInt32LE(8000, 24);
+ b.writeUInt32LE(16000, 28);
+ b.writeUInt16LE(2, 32);
+ b.writeUInt16LE(16, 34);
+ b.write('data', 36);
+ b.writeUInt32LE(samples * 2, 40);
return b;
}
@@ -50,13 +59,22 @@ const swatches = (page) => page.locator('#ink-colors [data-color]').evaluateAll(
const onSwatch = (page) => page.evaluate(() => document.querySelector('#ink-colors [data-color].on')?.dataset.color);
/* the sound kept in a database's "ink" store, or undefined */
-const keptSound = (page, db) => page.evaluate((db) => new Promise((res) => {
- const rq = indexedDB.open(db);
- rq.onsuccess = () => {
- const d = rq.result, g = d.transaction('ink').objectStore('ink').get('ob-timer-sound');
- g.onsuccess = () => { d.close(); res(g.result ? { name: g.result.name, bytes: g.result.data.byteLength } : undefined); };
- };
-}), db);
+const keptSound = (page, db) =>
+ page.evaluate(
+ (db) =>
+ new Promise((res) => {
+ const rq = indexedDB.open(db);
+ rq.onsuccess = () => {
+ const d = rq.result,
+ g = d.transaction('ink').objectStore('ink').get('ob-timer-sound');
+ g.onsuccess = () => {
+ d.close();
+ res(g.result ? { name: g.result.name, bytes: g.result.data.byteLength } : undefined);
+ };
+ };
+ }),
+ db
+ );
test.describe('HTML overlay', () => {
test.beforeEach(async ({ page }) => {
@@ -66,16 +84,25 @@ test.describe('HTML overlay', () => {
await openOverlay(page);
});
- test('big taps set the time, holding + speeds up, and Start turns on sound and counts down to an alert', async ({ page }) => {
+ test('big taps set the time, holding + speeds up, and Start turns on sound and counts down to an alert', async ({
+ page,
+ }) => {
await expect(timerBtn(page)).toHaveText('⏱ Timer');
await timerBtn(page).click();
const val = page.locator('#ob-timerset .ob-tm-val');
- await expect(val).toHaveText('5:00'); // the first time: 5 minutes
+ await expect(val).toHaveText('5:00'); // the first time: 5 minutes
await expect(page.locator('#ob-timerset [data-min="5"]')).toHaveClass(/\bon\b/);
- await expect(page.locator('#ob-timerset [data-min]')).toHaveText(['1 min', '2 min', '3 min', '5 min', '10 min', '15 min']);
+ await expect(page.locator('#ob-timerset [data-min]')).toHaveText([
+ '1 min',
+ '2 min',
+ '3 min',
+ '5 min',
+ '10 min',
+ '15 min',
+ ]);
await page.click('#ob-timerset [data-min="2"]');
await expect(val).toHaveText('2:00');
- await page.click('#ob-timerset [data-ts="more"]'); // one tap = one minute
+ await page.click('#ob-timerset [data-ts="more"]'); // one tap = one minute
await expect(val).toHaveText('3:00');
await page.click('#ob-timerset [data-ts="less"]');
await expect(val).toHaveText('2:00');
@@ -86,16 +113,16 @@ test.describe('HTML overlay', () => {
await page.clock.runFor(1500);
await page.mouse.up();
expect(parseInt(await val.textContent(), 10)).toBeGreaterThanOrEqual(12);
- expect(await audio(page)).toMatchObject({ made: 0 }); // nothing about sound loads until Start
+ expect(await audio(page)).toMatchObject({ made: 0 }); // nothing about sound loads until Start
await page.click('#ob-timerset [data-min="1"]');
await page.click('#ob-timerset [data-ts="start"]');
await expect(page.locator('#ob-timer')).toBeVisible();
const a = await audio(page);
- expect(a.made).toBe(1); // tapping Start made and switched on the sound
+ expect(a.made).toBe(1); // tapping Start made and switched on the sound
expect(a.resumed).toBeGreaterThanOrEqual(1);
await expect(face(page)).toHaveText(/^(1:00|0:5\d)$/);
- await expect(timerBtn(page)).toHaveText(/^⏱ (1:00|0:5\d)$/); // the toolbar button shows the time left
+ await expect(timerBtn(page)).toHaveText(/^⏱ (1:00|0:5\d)$/); // the toolbar button shows the time left
await page.clock.runFor(20000);
await expect(face(page)).toHaveText(/^0:(40|3\d)$/);
@@ -103,23 +130,23 @@ test.describe('HTML overlay', () => {
await expect(page.locator('#ob-timer [data-tm="pause"]')).toHaveText('Resume');
const paused = await face(page).textContent();
await page.clock.runFor(10000);
- await expect(face(page)).toHaveText(paused); // paused: no time passes
+ await expect(face(page)).toHaveText(paused); // paused: no time passes
await page.click('#ob-timer [data-tm="pause"]');
await expect(page.locator('#ob-timer [data-tm="pause"]')).toHaveText('Pause');
- await page.click('#ob-timer [data-tm="plus"]'); // +1 minute
+ await page.click('#ob-timer [data-tm="plus"]'); // +1 minute
await expect(face(page)).toHaveText(/^1:[34]\d$/);
await page.clock.runFor(101000);
- await expect(page.locator('#ob-timer')).toHaveClass(/\bup\b/); // zero: the box flashes and says so
+ await expect(page.locator('#ob-timer')).toHaveClass(/\bup\b/); // zero: the box flashes and says so
await expect(page.locator('#ob-timer .ob-tm-msg')).toBeVisible();
await expect(page.locator('#ob-timer .ob-tm-msg')).toHaveText("Time's up!");
await expect(face(page)).toHaveText('0:00');
- expect((await audio(page)).tones).toBeGreaterThan(0); // the built-in chime played
- await page.click('#ob-timer .ob-tm-face'); // a tap stops the alert
+ expect((await audio(page)).tones).toBeGreaterThan(0); // the built-in chime played
+ await page.click('#ob-timer .ob-tm-face'); // a tap stops the alert
await expect(page.locator('#ob-timer')).not.toHaveClass(/\bup\b/);
await expect(face(page)).toHaveText('1:00');
await expect(page.locator('#ob-timer [data-tm="pause"]')).toHaveText('Start');
- await page.click('#ob-timer [data-tm="close"]'); // not running: closes at once
+ await page.click('#ob-timer [data-tm="close"]'); // not running: closes at once
await expect(page.locator('#ob-timer')).toBeHidden();
await expect(timerBtn(page)).toHaveText('⏱ Timer');
// next time it starts at the last time used
@@ -141,10 +168,12 @@ test.describe('HTML overlay', () => {
await expect(page.locator('#ob-timer')).toBeHidden();
});
- test('the timer stays out of the ink: it can be dragged and made small, and drawing still works', async ({ page }) => {
+ test('the timer stays out of the ink: it can be dragged and made small, and drawing still works', async ({
+ page,
+ }) => {
await startTimer(page, 5);
const before = await page.locator('#ob-timer').boundingBox();
- expect(before.x + before.width).toBeGreaterThan(1300); // starts in the top corner away from the toolbar
+ expect(before.x + before.width).toBeGreaterThan(1300); // starts in the top corner away from the toolbar
expect(before.y).toBeLessThan(60);
// drag the numbers with a finger
const f = await face(page).boundingBox();
@@ -155,7 +184,9 @@ test.describe('HTML overlay', () => {
const after = await page.locator('#ob-timer').boundingBox();
expect(after.x).toBeLessThan(before.x - 450);
expect(after.y).toBeGreaterThan(before.y + 250);
- expect(await page.evaluate(() => JSON.parse(localStorage.getItem('ob-timer-pos')))).toMatchObject({ x: Math.round(after.x) });
+ expect(await page.evaluate(() => JSON.parse(localStorage.getItem('ob-timer-pos')))).toMatchObject({
+ x: Math.round(after.x),
+ });
// small, then a tap makes it big again
await page.click('#ob-timer [data-tm="small"]');
await expect(page.locator('#ob-timer')).toHaveClass(/\bsmall\b/);
@@ -170,25 +201,47 @@ test.describe('HTML overlay', () => {
await expect(page.locator('#ob-timer')).not.toHaveClass(/\bsmall\b/);
// a pen stroke on the page still writes while the timer is up
const t = await page.locator('#ob-timer').boundingBox();
- await page.evaluate(([x0, x1, y]) => new Promise(async (res) => {
- const c = document.getElementById('ink-canvas');
- const ev = (type, x) => c.dispatchEvent(new PointerEvent(type, { bubbles: true, cancelable: true, pointerType: 'pen', pointerId: 3, buttons: type === 'pointerup' ? 0 : 1, button: 0, clientX: x, clientY: y }));
- ev('pointerdown', x0);
- for (let i = 1; i <= 30; i++) { await new Promise((r) => setTimeout(r, 4)); ev('pointermove', x0 + (x1 - x0) * i / 30); }
- ev('pointerup', x1); res();
- }), [t.x - 200, t.x + 100, t.y + t.height / 2]);
+ await page.evaluate(
+ ([x0, x1, y]) =>
+ new Promise(async (res) => {
+ const c = document.getElementById('ink-canvas');
+ const ev = (type, x) =>
+ c.dispatchEvent(
+ new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ pointerType: 'pen',
+ pointerId: 3,
+ buttons: type === 'pointerup' ? 0 : 1,
+ button: 0,
+ clientX: x,
+ clientY: y,
+ })
+ );
+ ev('pointerdown', x0);
+ for (let i = 1; i <= 30; i++) {
+ await new Promise((r) => setTimeout(r, 4));
+ ev('pointermove', x0 + ((x1 - x0) * i) / 30);
+ }
+ ev('pointerup', x1);
+ res();
+ }),
+ [t.x - 200, t.x + 100, t.y + t.height / 2]
+ );
await page.clock.runFor(100);
const d = await savedInk(page);
expect(d.periods.P1).toHaveLength(1);
});
- test('Settings ▸ Timer sound: your own .wav, Test sound, kept after a reload, back to the chime', async ({ page }) => {
+ test('Settings ▸ Timer sound: your own .wav, Test sound, kept after a reload, back to the chime', async ({
+ page,
+ }) => {
await openSettings(page);
await expect(soundNow(page)).toHaveText('At zero it plays: the built-in chime');
await expect(page.locator('#ob-settings [data-snd="chime"]')).toBeHidden();
await page.click('#ob-settings [data-snd="test"]');
expect(await audio(page)).toMatchObject({ made: 1 });
- await expect.poll(async () => (await audio(page)).tones).toBeGreaterThan(0); // Test sound plays the chime
+ await expect.poll(async () => (await audio(page)).tones).toBeGreaterThan(0); // Test sound plays the chime
await page.setInputFiles(soundInput, { name: 'bell.wav', mimeType: 'audio/wav', buffer: wav() });
await expect(soundNow(page)).toHaveText('At zero it plays: bell.wav');
@@ -205,7 +258,7 @@ test.describe('HTML overlay', () => {
await startTimer(page, 1);
await page.clock.runFor(61000);
await expect(page.locator('#ob-timer')).toHaveClass(/\bup\b/);
- expect(await audio(page)).toMatchObject({ played: 1, tones: 0 }); // your sound, not the chime
+ expect(await audio(page)).toMatchObject({ played: 1, tones: 0 }); // your sound, not the chime
await openSettings(page);
await page.click('#ob-settings [data-snd="chime"]');
@@ -215,28 +268,36 @@ test.describe('HTML overlay', () => {
test('a sound file that is too big, or not a sound, is refused with a message', async ({ page }) => {
await openSettings(page);
- await page.setInputFiles(soundInput, { name: 'long.mp3', mimeType: 'audio/mpeg', buffer: Buffer.alloc(5 * 1024 * 1024 + 1) });
- await expect(page.locator('#ob-settings .ob-tm-sound .ob-snd-err')).toHaveText('That file is over 5 MB. Pick a shorter sound.');
+ await page.setInputFiles(soundInput, {
+ name: 'long.mp3',
+ mimeType: 'audio/mpeg',
+ buffer: Buffer.alloc(5 * 1024 * 1024 + 1),
+ });
+ await expect(page.locator('#ob-settings .ob-tm-sound .ob-snd-err')).toHaveText(
+ 'That file is over 5 MB. Pick a shorter sound.'
+ );
await page.setInputFiles(soundInput, { name: 'notes.txt', mimeType: 'text/plain', buffer: Buffer.from('hello') });
- await expect(page.locator('#ob-settings .ob-tm-sound .ob-snd-err')).toHaveText("That file can't be played. Pick a .wav or .mp3.");
+ await expect(page.locator('#ob-settings .ob-tm-sound .ob-snd-err')).toHaveText(
+ "That file can't be played. Pick a .wav or .mp3."
+ );
await expect(soundNow(page)).toHaveText('At zero it plays: the built-in chime');
expect(await keptSound(page, 'ink-data')).toBeUndefined();
});
test('the swatches change with the tool: pen, highlighter, cover', async ({ page }) => {
expect(await swatches(page)).toEqual(['#111111', '#1565c0', '#d32f2f', '#e0218a', '#2e7d32']);
- expect(await onSwatch(page)).toBe('#e0218a'); // the pen starts pink
+ expect(await onSwatch(page)).toBe('#e0218a'); // the pen starts pink
await page.click('#ink-bar [data-act="hilite"]');
expect(await swatches(page)).toEqual(['#fdd835', '#2e7d32', '#e0218a', '#1565c0', '#e8441a']);
- expect(await onSwatch(page)).toBe('#fdd835'); // the highlighter starts yellow
- await expect(page.locator('#ink-colors [data-color="#fdd835"]')).toHaveAttribute('title', /^Yellow: /); // the selected color's tooltip offers the laser pointer
+ expect(await onSwatch(page)).toBe('#fdd835'); // the highlighter starts yellow
+ await expect(page.locator('#ink-colors [data-color="#fdd835"]')).toHaveAttribute('title', /^Yellow: /); // the selected color's tooltip offers the laser pointer
await page.click('#ink-bar [data-act="hl-menu"]');
await page.click('#ob-hlmenu [data-mode="cover"][data-cover="#111111"]');
expect(await swatches(page)).toEqual(['#111111', '#a6a6a6', '#ffffff', '#fdd835', '#e0218a']);
await page.click('#ink-colors [data-color="#ffffff"]');
expect(await onSwatch(page)).toBe('#ffffff');
await expect(page.locator('#ink-colors [data-color="#ffffff"]')).toHaveAttribute('title', 'Cover: white');
- await page.click('#ink-bar [data-act="hilite"]'); // back to the pen: its own colors and its own color
+ await page.click('#ink-bar [data-act="hilite"]'); // back to the pen: its own colors and its own color
expect(await swatches(page)).toEqual(['#111111', '#1565c0', '#d32f2f', '#e0218a', '#2e7d32']);
expect(await onSwatch(page)).toBe('#e0218a');
});
@@ -248,12 +309,18 @@ test.describe('HTML overlay', () => {
await page.waitForSelector('#ink-bar[data-ready]', { state: 'attached' });
await timerBtn(page).click();
await page.click('#ob-timerset [data-ts="start"]');
- const clipped = await page.evaluate(() => [...document.querySelectorAll('#ob-timer button, #ob-timerset button')]
- .filter((b) => b.offsetParent && b.scrollWidth > b.clientWidth + 1).map((b) => b.textContent));
+ const clipped = await page.evaluate(() =>
+ [...document.querySelectorAll('#ob-timer button, #ob-timerset button')]
+ .filter((b) => b.offsetParent && b.scrollWidth > b.clientWidth + 1)
+ .map((b) => b.textContent)
+ );
expect({ code, clipped }).toEqual({ code, clipped: [] });
- await timerBtn(page).click(); // the setup box, over the running timer
- const clippedSet = await page.evaluate(() => [...document.querySelectorAll('#ob-timerset button')]
- .filter((b) => b.offsetParent && b.scrollWidth > b.clientWidth + 1).map((b) => b.textContent));
+ await timerBtn(page).click(); // the setup box, over the running timer
+ const clippedSet = await page.evaluate(() =>
+ [...document.querySelectorAll('#ob-timerset button')]
+ .filter((b) => b.offsetParent && b.scrollWidth > b.clientWidth + 1)
+ .map((b) => b.textContent)
+ );
expect({ code, clippedSet }).toEqual({ code, clippedSet: [] });
await page.keyboard.press('Escape');
}
@@ -280,7 +347,7 @@ test.describe('PDF app', () => {
await expect(page.locator('#ob-timer')).not.toHaveClass(/\bup\b/);
});
- test('its own sound is kept in the app\'s database', async ({ page }) => {
+ test("its own sound is kept in the app's database", async ({ page }) => {
await openSettings(page);
await page.setInputFiles(soundInput, { name: 'gong.wav', mimeType: 'audio/wav', buffer: wav() });
await expect(soundNow(page)).toHaveText('At zero it plays: gong.wav');
diff --git a/tests/turn.spec.js b/tests/turn.spec.js
index eb43570..e69d499 100644
--- a/tests/turn.spec.js
+++ b/tests/turn.spec.js
@@ -11,8 +11,13 @@ test.beforeEach(async ({ page }) => {
});
const draw = (page, n, pts) => page.evaluate(([n, pts]) => __t.stroke(n, pts), [n, pts]);
-const line = (x0, y0, x1, y1) => Array.from({ length: 31 }, (_, i) => [x0 + (x1 - x0) * i / 30, y0 + (y1 - y0) * i / 30]);
-const size = (page, n) => page.evaluate((n) => { const P = __overboard.viewer.pages[n - 1]; return [P.w, P.h]; }, n);
+const line = (x0, y0, x1, y1) =>
+ Array.from({ length: 31 }, (_, i) => [x0 + ((x1 - x0) * i) / 30, y0 + ((y1 - y0) * i) / 30]);
+const size = (page, n) =>
+ page.evaluate((n) => {
+ const P = __overboard.viewer.pages[n - 1];
+ return [P.w, P.h];
+ }, n);
const settle = (page) => page.waitForFunction(() => __overboard.viewer.pages[0].img);
test('Turn page turns the page and its ink; four turns bring it back', async ({ page }) => {
@@ -20,13 +25,13 @@ test('Turn page turns the page and its ink; four turns bring it back', async ({
await draw(page, 1, line(100, 190, 300, 190));
const before = (await strokes(page))[0].p.slice();
await fileMenu(page, 'turn-page');
- await expect(page.locator('#ob-filemenu')).toBeVisible(); // stays open: tap again to keep turning
+ await expect(page.locator('#ob-filemenu')).toBeVisible(); // stays open: tap again to keep turning
expect(await size(page, 1)).toEqual([h, w]);
- expect(await size(page, 2)).toEqual([w, h]); // only this page
+ expect(await size(page, 2)).toEqual([w, h]); // only this page
let p = (await strokes(page))[0].p;
- expect(p[0]).toBeCloseTo(h - before[1], 1); // a quarter turn clockwise: (x, y) -> (h - y, x)
+ expect(p[0]).toBeCloseTo(h - before[1], 1); // a quarter turn clockwise: (x, y) -> (h - y, x)
expect(p[1]).toBeCloseTo(before[0], 1);
- await fileMenu(page, 'turn-page'); // upside down
+ await fileMenu(page, 'turn-page'); // upside down
expect(await size(page, 1)).toEqual([w, h]);
p = (await strokes(page))[0].p;
expect(p[0]).toBeCloseTo(w - before[0], 1);
@@ -51,9 +56,12 @@ test('Turn all pages, then Export PDF comes out turned with the ink in place', a
const dl = await download(page, () => fileMenu(page, 'export'));
const file = info.outputPath('out.pdf');
await dl.saveAs(file);
- const r = await pdfPixels(page, file, 1, [[w - 200, h - 190], [200, 190]]);
- expect(dark(r.px[0])).toBe(true); // the ink, where it shows on screen
- expect(white(r.px[1])).toBe(true); // not where it was before the turn
+ const r = await pdfPixels(page, file, 1, [
+ [w - 200, h - 190],
+ [200, 190],
+ ]);
+ expect(dark(r.px[0])).toBe(true); // the ink, where it shows on screen
+ expect(white(r.px[1])).toBe(true); // not where it was before the turn
});
test('a turned PDF exports even with no ink, and the turn survives a reload', async ({ page }) => {
@@ -63,6 +71,7 @@ test('a turned PDF exports even with no ink, and the turn survives a reload', as
await page.reload();
await page.waitForFunction(() => window.__overboard && __overboard.viewer.stats().images >= 1);
expect(await page.evaluate(() => __overboard.data.rot)).toEqual({ 1: 90 });
- const [w, h] = await size(page, 1), [w2, h2] = await size(page, 2);
+ const [w, h] = await size(page, 1),
+ [w2, h2] = await size(page, 2);
expect([w, h]).toEqual([h2, w2]);
});
diff --git a/tests/type.spec.js b/tests/type.spec.js
index c9a8397..901b10c 100644
--- a/tests/type.spec.js
+++ b/tests/type.spec.js
@@ -9,15 +9,22 @@ const box = (page) => page.locator('.ob-note-edit');
test.describe('PDF app', () => {
const draw = (page, pts, o) => page.evaluate(([pts, o]) => __t.stroke(1, pts, o), [pts, o || {}]);
const at = (page, x, y) => page.evaluate(([x, y]) => __t.client(1, x, y), [x, y]);
- const ink = async (page, x, y) => (await page.evaluate(([x, y]) => __t.px(1, x, y), [x, y]) || [0, 0, 0, 0])[3];
- const notePx = async (page, s) => { // the darkest ink pixel inside the note's box
+ const ink = async (page, x, y) => ((await page.evaluate(([x, y]) => __t.px(1, x, y), [x, y])) || [0, 0, 0, 0])[3];
+ const notePx = async (page, s) => {
+ // the darkest ink pixel inside the note's box
let best = 0;
- for (let x = s.p[0]; x < s.p[2]; x += 2) for (let y = s.p[1]; y < s.p[3]; y += 2) best = Math.max(best, await ink(page, x, y));
+ for (let x = s.p[0]; x < s.p[2]; x += 2)
+ for (let y = s.p[1]; y < s.p[3]; y += 2) best = Math.max(best, await ink(page, x, y));
return best;
};
- test.beforeEach(async ({ page }) => { await openApp(page); await openPdf(page, 'worksheet.pdf'); });
+ test.beforeEach(async ({ page }) => {
+ await openApp(page);
+ await openPdf(page, 'worksheet.pdf');
+ });
- test('tap to type a note; Escape keeps it; Undo and Redo; tap it to change it; empty removes it', async ({ page }) => {
+ test('tap to type a note; Escape keeps it; Undo and Redo; tap it to change it; empty removes it', async ({
+ page,
+ }) => {
await page.click('[data-act="type"]');
await expect(page.locator('[data-act="type"]')).toHaveClass(/on/);
await tap(page, ...(await at(page, 100, 200)), 'pen');
@@ -31,7 +38,7 @@ test.describe('PDF app', () => {
expect(s).toHaveLength(1);
expect(s[0]).toMatchObject({ t: 'Hello\nworld', page: 1 });
expect(s[0].p[0]).toBeCloseTo(100, 0);
- expect(s[0].p[3] - s[0].p[1]).toBeGreaterThan(2 * s[0].f); // two lines
+ expect(s[0].p[3] - s[0].p[1]).toBeGreaterThan(2 * s[0].f); // two lines
expect(await notePx(page, s[0])).toBeGreaterThan(200);
await page.click('[data-act="undo"]');
@@ -56,10 +63,15 @@ test.describe('PDF app', () => {
expect(await strokes(page)).toHaveLength(0);
});
- test('a drag scrolls instead of typing; a tap beside an open note only finishes it; the Eraser turns Type off', async ({ page }) => {
+ test('a drag scrolls instead of typing; a tap beside an open note only finishes it; the Eraser turns Type off', async ({
+ page,
+ }) => {
await page.click('[data-act="type"]');
const y0 = await page.evaluate(() => scrollY);
- await draw(page, Array.from({ length: 10 }, (_, i) => [200, 500 - i * 20]));
+ await draw(
+ page,
+ Array.from({ length: 10 }, (_, i) => [200, 500 - i * 20])
+ );
expect(await page.evaluate(() => scrollY)).toBeGreaterThan(y0);
expect(await strokes(page)).toHaveLength(0);
await expect(box(page)).toHaveCount(0);
@@ -80,7 +92,7 @@ test.describe('PDF app', () => {
await tap(page, ...(await at(page, 100, 200)), 'pen');
await page.keyboard.type('Answer: 42');
await page.keyboard.press('Escape');
- await page.click('[data-act="type"]'); // off: the pen writes again
+ await page.click('[data-act="type"]'); // off: the pen writes again
let s = (await strokes(page))[0];
// Select: tap the note, drag it 100 points down
@@ -88,7 +100,10 @@ test.describe('PDF app', () => {
const mid = [(s.p[0] + s.p[2]) / 2, (s.p[1] + s.p[3]) / 2];
await draw(page, [mid]);
await expect(page.locator('#ob-selmenu')).toContainText('1 mark selected');
- await draw(page, Array.from({ length: 11 }, (_, i) => [mid[0], mid[1] + i * 10]));
+ await draw(
+ page,
+ Array.from({ length: 11 }, (_, i) => [mid[0], mid[1] + i * 10])
+ );
s = (await strokes(page))[0];
expect(s.t).toBe('Answer: 42');
expect(s.p[1]).toBeCloseTo(200 - s.f * 0.625 + 100, 0);
@@ -98,13 +113,23 @@ test.describe('PDF app', () => {
expect((await dl.createReadStream()) !== null).toBe(true);
// a palm swipe across one corner removes the whole note
- await draw(page, [[s.p[0] - 10, s.p[1] + 2], [s.p[0] + 4, s.p[1] + 2]], { buttons: 32 });
+ await draw(
+ page,
+ [
+ [s.p[0] - 10, s.p[1] + 2],
+ [s.p[0] + 4, s.p[1] + 2],
+ ],
+ { buttons: 32 }
+ );
expect(await notePx(page, s)).toBe(0);
});
});
test.describe('HTML overlay', () => {
- test.beforeEach(async ({ page }) => { await page.setViewportSize({ width: 1400, height: 900 }); await openOverlay(page); });
+ test.beforeEach(async ({ page }) => {
+ await page.setViewportSize({ width: 1400, height: 900 });
+ await openOverlay(page);
+ });
test('tap to type a note, Escape keeps it (saved), Undo removes it', async ({ page }) => {
await page.click('#ink-bar [data-act="type"]');
@@ -125,18 +150,48 @@ test.describe('HTML overlay', () => {
await context.grantPermissions(['clipboard-read', 'clipboard-write']);
await page.evaluate(() => {
const p = document.createElement('p');
- p.id = 'ws-text'; p.textContent = 'Photosynthesis makes sugar'; p.style.cssText = 'font-size:32px;margin:40px';
+ p.id = 'ws-text';
+ p.textContent = 'Photosynthesis makes sugar';
+ p.style.cssText = 'font-size:32px;margin:40px';
(document.querySelector('.page') || document.body).prepend(p);
});
await page.click('#ink-bar [data-act="type"]');
- const r = await page.evaluate(() => { const t = document.getElementById('ws-text').firstChild, g = document.createRange(); g.selectNodeContents(t); const b = g.getBoundingClientRect(); return [b.left, b.right, b.top + b.height / 2]; });
- await page.evaluate(([x0, x1, y]) => new Promise(async (res) => {
- const c = document.getElementById('ink-canvas');
- const ev = (t, x) => c.dispatchEvent(new PointerEvent(t, { bubbles: true, cancelable: true, pointerType: 'pen', pointerId: 3, buttons: t === 'pointerup' ? 0 : 1, button: 0, clientX: x, clientY: y, screenX: x, screenY: y }));
- ev('pointerdown', x0 + 2);
- for (let i = 1; i <= 10; i++) { await new Promise((r) => setTimeout(r, 4)); ev('pointermove', x0 + 2 + (x1 - x0) * i / 10); }
- ev('pointerup', x1 - 1); res();
- }), r);
+ const r = await page.evaluate(() => {
+ const t = document.getElementById('ws-text').firstChild,
+ g = document.createRange();
+ g.selectNodeContents(t);
+ const b = g.getBoundingClientRect();
+ return [b.left, b.right, b.top + b.height / 2];
+ });
+ await page.evaluate(
+ ([x0, x1, y]) =>
+ new Promise(async (res) => {
+ const c = document.getElementById('ink-canvas');
+ const ev = (t, x) =>
+ c.dispatchEvent(
+ new PointerEvent(t, {
+ bubbles: true,
+ cancelable: true,
+ pointerType: 'pen',
+ pointerId: 3,
+ buttons: t === 'pointerup' ? 0 : 1,
+ button: 0,
+ clientX: x,
+ clientY: y,
+ screenX: x,
+ screenY: y,
+ })
+ );
+ ev('pointerdown', x0 + 2);
+ for (let i = 1; i <= 10; i++) {
+ await new Promise((r) => setTimeout(r, 4));
+ ev('pointermove', x0 + 2 + ((x1 - x0) * i) / 10);
+ }
+ ev('pointerup', x1 - 1);
+ res();
+ }),
+ r
+ );
expect(await page.evaluate(() => getSelection().toString())).toContain('Photosynthesis makes suga');
expect(await page.evaluate(() => navigator.clipboard.readText())).toContain('Photosynthesis');
await expect(page.locator('.ob-note-edit')).toHaveCount(0);
@@ -145,7 +200,11 @@ test.describe('HTML overlay', () => {
test('with Type off, a finger tap presses a button on the worksheet', async ({ page }) => {
await page.evaluate(() => {
const b = document.createElement('button');
- b.id = 'ws-btn'; b.textContent = 'Reveal'; b.onclick = () => { window.__pressed = (window.__pressed || 0) + 1; };
+ b.id = 'ws-btn';
+ b.textContent = 'Reveal';
+ b.onclick = () => {
+ window.__pressed = (window.__pressed || 0) + 1;
+ };
(document.querySelector('.page') || document.body).prepend(b);
});
const r = await page.locator('#ws-btn').boundingBox();
diff --git a/tools/board-probe.html b/tools/board-probe.html
index e30f5fc..5dff5d4 100644
--- a/tools/board-probe.html
+++ b/tools/board-probe.html
@@ -1,206 +1,516 @@
-
-
-
-Ink Input Probe
-
-
-
-
-
-
-
-
Touch here with: the pen, one finger, two fingers, a fist, your flat palm, the side of your hand, the board eraser. Do each a few times.
-
-
-
-
Last touch
-
Nothing yet
-
-
-
SMART board driver
-
Connecting…
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+ Touch here with: the pen, one finger, two fingers, a fist, your flat palm, the side of your hand, the board
+ eraser. Do each a few times.
+
+
+
+
+
Last touch
+
Nothing yet
+
+
+
SMART board driver
+
Connecting…
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+ /* ---------- buttons ---------- */
+ document.getElementById('copy').addEventListener('click', function () {
+ var out = JSON.stringify({
+ ua: navigator.userAgent,
+ maxTouchPoints: navigator.maxTouchPoints,
+ dpr: window.devicePixelRatio,
+ sdkPort: sdkPort,
+ totals: tot,
+ log: LOG,
+ });
+ var btn = this;
+ function done(ok) {
+ btn.textContent = ok ? 'Copied!' : 'Copy failed';
+ setTimeout(function () {
+ btn.textContent = 'Copy log';
+ }, 2000);
+ }
+ if (navigator.clipboard)
+ navigator.clipboard.writeText(out).then(
+ function () {
+ done(true);
+ },
+ function () {
+ fallback();
+ }
+ );
+ else fallback();
+ function fallback() {
+ var ta = document.createElement('textarea');
+ ta.value = out;
+ document.body.appendChild(ta);
+ ta.select();
+ var ok = false;
+ try {
+ ok = document.execCommand('copy');
+ } catch (_) {}
+ ta.remove();
+ done(ok);
+ }
+ });
+ document.getElementById('clear').addEventListener('click', function () {
+ LOG = [];
+ tot = {};
+ logEl.textContent = '';
+ totEl.innerHTML = '';
+ lastEl.textContent = 'Nothing yet';
+ size();
+ });
+ add('env', { ua: navigator.userAgent, maxTouchPoints: navigator.maxTouchPoints, dpr: window.devicePixelRatio });
+ })();
+
+