Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/features/share/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { timeParam } from './model.js'
import { ctaVisible, type ViewCta, type ViewData } from './content.js'
import { ctaVisible, pickRendition, type ViewCta, type ViewData } from './content.js'

export type Mode = 'network' | 'embed' | 'static'
export type Gate = 'password' | 'people' | 'workspace' | 'denied' | 'email' | 'expired' | 'encrypted'
Expand Down Expand Up @@ -190,7 +190,9 @@ export function viewerBody(d: ViewData, o: PageOptions): string {
const hideBrand = d.brand.hideBranding
const logo = d.brand.logo && o.logo ? `<img class="sv-logo" data-sv-logo src="${esc(o.logo)}" width="28" height="28" alt="">` : ''
const mediaBase = o.media
const video = o.videoFile ?? 'video'
// The source names its file (a height, or the original), so the bytes behind it never change while the page plays: a
// plain `video` answers with the best rendition finished so far, which changes as the renditions are made.
const video = o.videoFile ?? `video?q=${pickRendition(d.qualities, undefined)?.height ?? 'original'}`
return `<main class="sv${o.mode === 'embed' ? ' is-embed' : ''}" data-share-view data-mode="${o.mode}" data-share-id="${esc(d.shareId)}"${styleFor(d.brand.accent)}${blank ? ' data-locked="encrypted" hidden' : ''}>
${o.hideTitle ? '' : `<header class="sv-head" data-sv-head>
<div class="sv-brand">${logo}<span class="sv-brand-name" data-sv-brand-name>${t(d.brand.name)}</span></div>
Expand Down
4 changes: 3 additions & 1 deletion tests/analytics-folder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ describe('folder destinations', () => {
const lines = text.split('\r\n')
expect(lines[0]).toBe(tableSpec('fact_views').columns.map((c) => c.name).join(','))
expect(lines.filter(Boolean)).toHaveLength(3)
expect(text).toContain(`${REC},visit-fofo-0001,${shareId},share,`)
// A share id is random and can begin with '-', which a spreadsheet file defuses with a leading apostrophe.
const sheetId = /^[=+\-@]/.test(shareId) ? `'${shareId}` : shareId
expect(text).toContain(`${REC},visit-fofo-0001,${sheetId},share,`)
const recs = await readFile(path.join(dir, 'dim_recordings.csv'), 'utf8')
expect(recs).toContain('"Folder, ""tour"""')
expect((await stat(path.join(dir, viewsFile))).mode & 0o777).toBe(0o600)
Expand Down
3 changes: 2 additions & 1 deletion tests/mp4-ingest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ describe('a real take recorded as fragmented MP4', () => {
res.on('end', () => resolve(text))
}).on('error', reject)
})
expect(page).toContain(`src="/s-api/${made.json.share.shareId}/media/video"`)
// The page names the file it plays: the original, or a rendition when one was finished before the page was drawn.
expect(page).toMatch(new RegExp(`src="/s-api/${made.json.share.shareId}/media/video\\?q=(original|\\d{3,4})"`))
})
})
5 changes: 4 additions & 1 deletion tests/redactmore-e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,11 @@ describe.skipIf(!ffmpegAvailable())('the Privacy panel and Settings, Redaction',
return (await list.getAttribute('data-count')) === '4'
}).toBe(true)
await poll(() => panel.locator('[data-redact-apply-all]').isEnabled()).toBe(true)
// The apply answers once every file is written (the recording first, then the comments and the exports).
const applied = page.waitForResponse((r) => r.request().method() === 'POST' && new URL(r.url()).pathname === `/api/redact/${ID}`, { timeout: 60_000 })
await panel.locator('[data-redact-apply-all]').click()
await poll(async () => (await readFile(recordingJson, 'utf8')).includes(KEY)).toBe(false)
expect((await applied).status()).toBe(200)
expect(await readFile(recordingJson, 'utf8')).not.toContain(KEY)
const engage = await new EngageStore(app.features.library, dataDir).read(ID)
expect(engage.comments[0]!.text).toBe('Write to [redacted email]')
expect(await readFile(path.join(dataDir, 'recordings', ID, 'documents-export-abcd1234.srt'), 'utf8')).toContain('Mail [redacted email] now')
Expand Down
20 changes: 20 additions & 0 deletions tests/renditions-share.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,26 @@ describe('the share page and the tools', () => {
expect(embed.body.toString('utf8')).toMatch(/"qualities":\[\{"height":360,"width":640/)
})

it('names the file its video plays, so a rendition finished later never changes the bytes under it', async () => {
const file = path.join(folder, 'share-renditions.json')
const full = await readFile(file, 'utf8')
const src = (html: string): string => new URL(/data-sv-video[^>]* src="([^"]+)"/.exec(html)![1]!.replace(/&amp;/g, '&'), `${shareBase}/v/`).toString()
const head = (url: string) => request(url, 'GET', undefined, { Range: 'bytes=0-65535' })
try {
for (const kept of [1, 0]) {
// The ladder part made: the page is drawn now, and the rest of the ladder finishes while it plays.
await writeFile(file, JSON.stringify({ ...JSON.parse(full), renditions: JSON.parse(full).renditions.slice(0, kept) }))
const url = src((await request(`${shareBase}/v/${shareId}`)).body.toString('utf8'))
expect(url).toMatch(kept ? /media\/video\?q=360$/ : /media\/video\?q=original$/)
const before = (await head(url)).body
await writeFile(file, full)
expect((await head(url)).body.equals(before)).toBe(true)
}
} finally {
await writeFile(file, full)
}
})

it('formrec_share and formrec_shares report the available qualities', async () => {
const deps = { library: app.features.library, dataDir: app.features.dataDir } as never
const rt = runtimeFor(app.features)
Expand Down
68 changes: 68 additions & 0 deletions tests/shell-first-paint.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/**
* The app's first frame is the whole shell: Chrome paints nothing until the page's HTML is parsed to its end, so a
* slow parse (CPU load, a slow disk) never shows a half-made title bar that then moves. The page is served with a
* pause in the middle of the View menu's button, where a paint would show that button empty.
* Needs `npm run build`.
*/
import { afterAll, beforeAll, expect, it } from 'vitest'
import http from 'node:http'
import { existsSync } from 'node:fs'
import path from 'node:path'
import type { AddressInfo } from 'node:net'
import { chromium, type Browser } from 'playwright'
import { createApp, type App } from '../src/app.js'
import { tempDir } from './helpers.js'

const WEB = path.resolve(import.meta.dirname, '..', 'dist', 'web')
const TOKEN = 'p'.repeat(40)
const PAUSE_MS = 1500
let app: App
let slow: http.Server
let base: string
let browser: Browser

beforeAll(async () => {
if (!existsSync(path.join(WEB, 'index.html'))) throw new Error('run npm run build first')
app = createApp({ dataDir: await tempDir('formrec-first-paint-'), token: TOKEN, webDir: WEB })
await new Promise<void>((r) => app.server.listen(0, '127.0.0.1', r))
const up = `http://127.0.0.1:${(app.server.address() as AddressInfo).port}`
// In front of the app: everything passes through, except that the page stops for a while inside the View button.
slow = http.createServer((req, res) => {
void (async () => {
const r = await fetch(up + (req.url ?? '/'), { headers: { cookie: req.headers.cookie ?? '' } })
const body = Buffer.from(await r.arrayBuffer())
const type = r.headers.get('content-type') ?? ''
const cookie = r.headers.get('set-cookie')
res.writeHead(r.status, { 'Content-Type': type, ...(cookie ? { 'Set-Cookie': cookie } : {}) })
const mark = 'aria-expanded="false">View'
const at = type.includes('text/html') ? body.indexOf(mark) : -1
if (at < 0) return void res.end(body)
const cut = at + mark.length - 'View'.length
res.write(body.subarray(0, cut))
await new Promise((d) => setTimeout(d, PAUSE_MS))
res.end(body.subarray(cut))
})().catch(() => res.destroy())
})
await new Promise<void>((r) => slow.listen(0, '127.0.0.1', r))
base = `http://127.0.0.1:${(slow.address() as AddressInfo).port}`
browser = await chromium.launch()
}, 60_000)

afterAll(async () => {
await browser?.close()
slow?.close()
await app?.close()
})

it('paints nothing until the shell is parsed to its end', async () => {
const page = await browser.newPage({ viewport: { width: 1280, height: 800 } })
await page.goto(`${base}/?token=${TOKEN}#/shared`, { timeout: 60_000 })
await page.waitForFunction(() => performance.getEntriesByType('paint').length > 0)
const t = await page.evaluate(() => ({
paint: performance.getEntriesByType('paint')[0]!.startTime,
parsed: (performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming).domInteractive,
}))
expect(t.parsed).toBeGreaterThan(PAUSE_MS - 100)
expect(t.paint).toBeGreaterThanOrEqual(t.parsed - 50)
await page.close()
}, 120_000)
3 changes: 3 additions & 0 deletions web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
<link rel="stylesheet" href="/styles/clips.css">
<link rel="stylesheet" href="/styles/variants.css">
<script type="module" src="/app.js"></script>
<!-- The first frame waits for the whole shell: under CPU load Chrome otherwise paints a half-parsed title bar. -->
<link rel="expect" href="#shell-end" blocking="render">
</head>
<body>
<div class="shell">
Expand Down Expand Up @@ -347,5 +349,6 @@ <h3 class="settings-sechead" id="set-about">About</h3>
</div>
</div>
</dialog>
<span id="shell-end" hidden></span>
</body>
</html>
Loading