diff --git a/.github/workflows/screennote-rebuild.yml b/.github/workflows/screennote-rebuild.yml new file mode 100644 index 0000000..e309e9e --- /dev/null +++ b/.github/workflows/screennote-rebuild.yml @@ -0,0 +1,114 @@ +name: ScreenNote Cloudflare rebuild + +on: + workflow_dispatch: + push: + branches: + - rebuild/cloudflare-web-first + paths: + - "rebuild/**" + - ".github/workflows/screennote-rebuild.yml" + pull_request: + branches: + - main + paths: + - "rebuild/**" + - ".github/workflows/screennote-rebuild.yml" + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + test-and-build: + name: test-and-build + runs-on: ubuntu-latest + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_D1_API_TOKEN: ${{ secrets.CLOUDFLARE_D1_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: "90cefa028781f749f5816c5748f04cd2" + defaults: + run: + working-directory: rebuild + steps: + - uses: actions/checkout@v4 + - name: Require D1 credentials when schema migrations change + if: ${{ (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && env.CLOUDFLARE_D1_API_TOKEN == '' }} + shell: bash + run: | + before="${{ github.event.before || '' }}" + if [[ -z "$before" || "$before" =~ ^0+$ ]]; then + before="$(git rev-parse HEAD^ 2>/dev/null || git rev-list --max-parents=0 HEAD)" + fi + if git diff --name-only "$before" "$GITHUB_SHA" -- rebuild/worker/migrations | grep -q .; then + echo "::error::D1 migration files changed but CLOUDFLARE_D1_API_TOKEN is not configured. Add the dedicated D1 write token before deploying schema changes." + exit 1 + fi + - uses: actions/setup-node@v4 + with: + node-version: 24 + - run: npm install --no-audit --no-fund + - run: npx playwright install --with-deps chromium + - run: npm run typecheck + - run: npm test + - run: npm run build + env: + SCREENNOTE_WORKER_FIRST_ALL: "1" + - run: npm run perf:budget + - run: npm run e2e + - uses: actions/upload-artifact@v4 + if: failure() + with: + name: screennote-e2e-failure-diagnostics + path: rebuild/test-results/** + if-no-files-found: warn + retention-days: 3 + - uses: actions/upload-artifact@v4 + with: + name: screennote-build-output + path: rebuild/.cloudflare/output/v1/** + if-no-files-found: error + - uses: actions/upload-artifact@v4 + if: always() + with: + name: screennote-visual-evidence + path: rebuild/test-results/screenshots/** + if-no-files-found: warn + - name: Apply D1 migrations with the dedicated database token + if: ${{ (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && env.CLOUDFLARE_D1_API_TOKEN != '' }} + env: + CLOUDFLARE_API_TOKEN: ${{ env.CLOUDFLARE_D1_API_TOKEN }} + run: node scripts/apply-migrations.mjs + - name: Warn when D1 migration credentials are not configured + if: ${{ (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && env.CLOUDFLARE_D1_API_TOKEN == '' }} + run: echo "::warning::D1 migrations were skipped. Apply any pending SQL in Cloudflare before deploying schema changes." + - name: Deploy isolated Cloudflare development Worker + if: ${{ (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && env.CLOUDFLARE_API_TOKEN != '' }} + env: + SCREENNOTE_WORKER_FIRST_ALL: "1" + run: npm run deploy + - name: Verify deployed app and real share lifecycle + if: ${{ (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && env.CLOUDFLARE_API_TOKEN != '' }} + run: node scripts/live-smoke.mjs + - name: Verify deployed UI and real D1/R2 through a separate guest browser + if: ${{ (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && env.CLOUDFLARE_API_TOKEN != '' }} + env: + SCREENNOTE_LIVE_URL: https://screennote-dev.buttercoder-dev.workers.dev + run: node scripts/live-browser-smoke.mjs + - uses: actions/upload-artifact@v4 + if: ${{ always() }} + with: + name: screennote-live-browser-evidence + path: rebuild/test-results/live-browser-smoke/** + if-no-files-found: warn + retention-days: 3 + + build: + name: build + runs-on: ubuntu-latest + needs: test-and-build + steps: + - run: echo "ScreenNote rebuild build gate passed." diff --git a/README.md b/README.md index e0166cf..d5cc5dd 100644 --- a/README.md +++ b/README.md @@ -1,65 +1,27 @@ -![CI](https://github.com/buttercode101/ScreenNote/actions/workflows/verify.yml/badge.svg) - # ScreenNote -**Show what you mean. Share a short video. Keep the conversation at the right moment.** - -ScreenNote lets you record or import a short explanation, review it privately, and choose when to publish a viewing link. Viewers can leave timestamped comments and reply to any reply, including their own. Optional playback bubbles bring a conversation back into view at its moment in the video. - -[Open ScreenNote](https://screennote-woad.vercel.app) · [Get started](#your-first-screennote) · [Development](#quick-start) · [Technical notes](docs/TECHNICAL-NOTES.md) · [Verification](REPOSITORY-VERIFICATION.md) - -## Your first ScreenNote - -1. Record your screen in a compatible desktop browser, or import an MP4/WebM from your device. -2. Review playback, name the clip and optionally trim a new copy. The original stays available locally. -3. Explicitly publish a link with a 1, 3 or 7 day expiry and optional password. -4. Let a recipient watch, react and discuss a specific moment. Reply, resolve a thread or reopen it through a reply. -5. Export the video and your private owner recovery keys. Stop sharing or delete the published clip when finished. - -## Useful for - -| Task | How ScreenNote helps | -| --- | --- | -| Explain a confusing screen | Show the steps instead of writing a long message | -| Report a bug | Show the failure and discuss its exact timestamp | -| Review a design | Keep feedback and follow-up replies together | -| Hand over work | Leave a short walkthrough that the recipient can watch later | - -## What is included - -- Local recording library, MP4/WebM import, download and real local trim. -- Optional microphone, system audio and camera bubble where the browser supports capture. -- Explicit publishing, expiring links, password protection and creator controls. -- Timestamped threads, reply-to-any-reply, comment editing/removal in the author's original browser, creator moderation and open/resolved filtering. -- Optional playback bubbles, timeline markers, comment links and drafts retained across refreshes. -- Owner-supplied captions, transcripts and bug reports; automatic transcription is not included. - -## Limits that matter - -Clips are limited to ten minutes and 50 MB. Shared storage uses a 1,000,000,000-byte budget with temporary upload reservations; there is no fixed 16-slot cap. Available clip count depends on sizes, active reservations and provider quotas. Each clip allows up to 100 comments. Names are unverified; owner and author controls depend on private browser capabilities. - -Local recordings are browser data, not a backup. Recovery-key files restore management capabilities, not video files. Issued media URLs may continue working for ten minutes after sharing stops. Playback bubbles do not appear in native fullscreen or picture-in-picture. Phones without browser screen capture can import a device recording. +**The temporary screen note that ends when the conversation ends.** -## Quick start +ScreenNote is a web-first tool for short screen explanations and focused async feedback. Record or import a clip, review and trim it locally, then explicitly publish a temporary link. Viewers do not need an account. Timestamped comments, replies and frame-point annotations stay attached to the exact moment. When the share expires or the creator stops sharing, the cloud copy and its discussion are deleted. -Use Node.js 24 and npm: +## Product principles -```bash -npm ci -npm test -npm run build -python3 -m http.server 3000 --directory dist -``` +- Local-first originals; no cloud upload before an explicit publish action. +- Temporary shared copies, with 1, 3 or 7 day expiry. +- Optional password protection and anonymous viewing. +- Timestamped threaded comments, resolve/reopen and frame-point annotations. +- Playback bubbles and structured coding-agent handoff export. +- Portable recovery keys for creator control. +- Cloudflare Workers, D1 and private R2 storage. +- No permanent cloud video library and no account required for the core flow. -Open http://localhost:3000. This static preview supports local media workflows; it does **not** run the publishing API. Complete publishing requires Vercel Node Functions and the existing private storage gateway. Server configuration and migration instructions are retained in [technical notes](docs/TECHNICAL-NOTES.md#development). Production capture requires HTTPS and compatible browser permissions. +## Rebuild status -## Project guide +The active implementation is in [rebuild/](rebuild/README.md) on branch rebuild/cloudflare-web-first. -- [Fresh repository checks](REPOSITORY-VERIFICATION.md) -- [Conversation design and acceptance](verification/conversations-2026-10-26.md) -- [Storage-capacity evidence](verification/storage-capacity-2026-10-26.md) -- [Launch and physical-device gates](LAUNCH-READINESS.md) -- [Architecture and historical releases](docs/TECHNICAL-NOTES.md) -- [Contributing](CONTRIBUTING.md) · [Security reporting](SECURITY.md) +- TypeScript checks, unit tests, production build and Playwright browser acceptance are automated in GitHub Actions. +- The D1 schema migrations for temporary shares and frame annotations have been applied to the isolated development database. +- Cloudflare development Worker deployment is not yet complete. The workflow needs a repository Actions secret named CLOUDFLARE_API_TOKEN with scoped Workers Scripts, D1 and R2 edit permissions. +- The existing Vercel deployment is intentionally untouched until the Cloudflare replacement passes deployed integration and production acceptance. -Current source version: **0.5.0**. The old Blob suspension is historical; it does not mean historical media was migrated. Physical handsets and native capture permissions remain separate acceptance gates. +See [rebuild/README.md](rebuild/README.md) for architecture, limits, development instructions and remaining release gates. diff --git a/rebuild/.gitignore b/rebuild/.gitignore new file mode 100644 index 0000000..bc66e31 --- /dev/null +++ b/rebuild/.gitignore @@ -0,0 +1,13 @@ +node_modules/ +dist/ +.cloudflare/ +.dev.vars +.dev.vars.* +.env +.env.* +!.env.example +coverage/ +*.log +legacy/dist/ + +legacy/dist/ diff --git a/rebuild/CLOUDFLARE_DEPLOYMENT.md b/rebuild/CLOUDFLARE_DEPLOYMENT.md new file mode 100644 index 0000000..4c596f5 --- /dev/null +++ b/rebuild/CLOUDFLARE_DEPLOYMENT.md @@ -0,0 +1,7 @@ +# Cloudflare deployment + +The rebuild is deployed through the `ScreenNote Cloudflare rebuild` GitHub Actions workflow. The workflow runs typecheck, unit tests, production build, Playwright E2E, then deploys the isolated Cloudflare Worker when the repository secret `CLOUDFLARE_API_TOKEN` is configured. + +The deploy token is scoped to Worker deployment and the bindings needed by the Worker. It does not need D1 write permission. The development database's password-attempt migration (`worker/migrations/0004_password_attempt_limits.sql`) was applied directly to the isolated D1 database. For automatic future D1 migrations, add a separate repository secret `CLOUDFLARE_D1_API_TOKEN` with D1 edit/query permission; the migration step is skipped when that secret is absent. Do not broaden the Worker deploy token just to run migrations. + +Cloudflare Pages project `screennote-web` is reserved for the Pages Direct Upload path if Git integration remains unavailable. The Worker deployment is the API and application runtime; do not publish an unverified Pages URL as the product URL. diff --git a/rebuild/COMPETITIVE-RESEARCH-2026-11-26.md b/rebuild/COMPETITIVE-RESEARCH-2026-11-26.md new file mode 100644 index 0000000..a3c9e62 --- /dev/null +++ b/rebuild/COMPETITIVE-RESEARCH-2026-11-26.md @@ -0,0 +1,157 @@ +# ScreenNote competitive research & product direction +**Research date:** 26 November 2026 +**Scope:** asynchronous screen recording, visual feedback, annotation, playback, editing and sharing. +**Source policy:** competitor feature claims below are drawn from their public product or help documentation. Product recommendations and performance targets are ScreenNote design decisions, not claims about competitor internals. + +## Competitive landscape + +### Loom — the familiar async video message +Loom's public Starter plan lists screen-and-camera recording, system audio, comments/reactions, transcripts, and a 5-minute / 25-video limit. Its video settings support creator control over comments, reactions, transcript visibility and downloads. +- Sources: https://www.loom.com/pricing +- https://support.atlassian.com/loom/docs/edit-your-video-settings-disable-comments-emoji-reactions-downloads-and-more + +**Pattern to retain:** make capture and link sharing familiar; preserve recipient interaction controls. +**Opportunity for ScreenNote:** make the core workflow account-free for viewers, local-first for creators, and explicitly temporary rather than pushing users toward a permanent library. + +### Claap — feedback tied to a moment +Claap documents timestamped comments, pinning a moment during recording, keyboard shortcuts, and area annotations made by selecting a region of the video. Its recording overlay can be moved and offers pause, restart, stop/save, pin and delete. +- Sources: https://help.claap.io/en/articles/6286747-add-and-manage-comments-on-a-claap-video +- https://help.claap.io/en/articles/6268467-how-to-record-a-video-using-the-claap-chrome-extension +- https://help.claap.io/en/articles/16600260-what-you-can-do-with-a-claap-meeting + +**Pattern to retain:** time-anchored discussion, quick capture controls, in-context visual feedback. +**Opportunity for ScreenNote:** preserve a clear source-frame coordinate system and keep annotations readable on portrait, 4:3 and 16:9 recordings; make review actions understandable without onboarding. + +### Tella — creator-quality recording and editing +Tella describes screen/camera recording, multiple clips, video uploads, trimming/cropping, transcript-based editing, subtitles, zoom effects, dynamic layouts, and sharing/analytics. +- Sources: https://www.tella.com/features +- https://www.tella.com/ (product overview) + +**Pattern to retain:** recording should lead naturally into review/edit/share; use deliberate preview and editor controls. +**Opportunity for ScreenNote:** prioritize fast, precise feedback and safe local editing over a large, complex creator suite. + +### Zight — broad capture and visual communication +Zight lists screen recording, webcam recording, system audio, annotations, screenshots/GIFs, editing, sharing, request links and bug-report workflows. +- Sources: https://zight.com/features +- https://support.zight.com/hc/en-us/articles/5823722434711-How-To-Annotate-Video-How-to-Draw-On-Video +- https://support.zight.com/hc/en-us/articles/6657856296855-How-do-I-record-my-screen-audio-and-webcam-simultaneously + +**Pattern to retain:** annotate with clear tools, and connect the capture to the action it should trigger. +**Opportunity for ScreenNote:** avoid feature sprawl; make a focused review brief, anchored comments, and a clear close-the-loop status the fastest path. + +## Design and interaction principles + +1. **One primary action per moment.** Record, review, or publish should each have a clear visual priority. Secondary actions remain discoverable without competing. +2. **Local-first trust.** Explain that original media stays on-device until the creator chooses to publish. Show publish progress and expiry before upload, not after. +3. **Context travels with feedback.** Comments carry time; frame annotations carry normalized coordinates; clicking either seeks to the exact context. +4. **Review state is legible.** Show whether feedback is needed, resolved, or awaiting a response. Make status changes reversible where possible. +5. **No ornamental dashboard.** Prefer a useful library, strong empty state, concise metadata, and clear recovery actions over decorative charts or excessive cards. +6. **Respect media proportions.** Video is rendered at its natural aspect ratio with contained controls; avoid cropping content to force uniform cards. +7. **Accessibility is part of polish.** Keyboard focus, reduced motion, meaningful labels, contrast, and 44px touch targets are acceptance criteria. + +## Performance targets + +Google's Core Web Vitals "good" thresholds are evaluated at the 75th percentile of page visits: +- **LCP:** <= 2.5 seconds +- **INP:** <= 200 milliseconds +- **CLS:** <= 0.1 + +Source: https://web.dev/articles/defining-core-web-vitals-thresholds (updated 7 May 2025) + +These are the public web baselines, not ScreenNote's stretch goals. ScreenNote should additionally measure and report: +- Cold dashboard load and editor-ready time on a mid-range Android device. +- Time from user gesture to recording UI ready (capture permission remains browser-controlled). +- Time to local persistence after stop; do not wait for upload to finish before preserving the original. +- Upload throughput and resumability on constrained/mobile networks. +- Playback startup, seeking response, and comment-to-frame seek latency. +- Memory use and long-session stability during 10-minute capture. +- UI responsiveness while thumbnail generation, upload, or video decoding is active. + +Chrome's screen-capture documentation confirms that `getDisplayMedia()` invokes the browser's user-facing picker and can return selected tab/window/screen video (and audio where supported); browser permission and supported audio tracks are not controllable by ScreenNote. +Source: https://developer.chrome.com/docs/extensions/how-to/web-platform/screen-capture + +## Free-tier and pricing reality (checked 26 November 2026) + +| Product | Current public entry point | What the free/entry tier tells us | +|---|---|---| +| Loom | Starter $0; pricing page displays Business $18/user/month and Business + AI $24/user/month (billing selection can change checkout) | Starter lists 25 videos, 5-minute screen recordings, up to 720p, comments/reactions and transcription. Paid plans remove recording/storage limits and add editing. | +| Tella | Pro $13/user/month; Premium $19/user/month (annual billing shown) | Competes on creator-quality editing: 4K export, clip/timeline editing, transcript edits, captions, layouts, zooms and long clips. The official pricing page shows plan/billing choices; treat checkout as authoritative. | +| Zight | Share $0; Create $9.95/user/month billed annually ($12.95 monthly); Collaborate $12/user/month billed annually | Share includes capture/sharing, video requests, screenshots and 15-second GIFs; Create adds unlimited recording/uploads, annotation/editing, transcription and limited AI actions. Scale is custom. | +| Claap | Basic free license; Pro/Business paid | Free users can participate in a workspace with limited recording/upload minutes and core comments/reactions; advanced collaboration/privacy/AI capacity is plan-dependent. | + +**Strategic implication:** do not try to win by copying a paid editor's entire feature checklist. ScreenNote's creator value should be local recording/import, precise review, and a polished temporary share workflow with clear lifecycle controls. Keep local creation generous; make cloud retention, storage volume, team administration and advanced workflow capabilities the cost-aware monetization boundary. No competitor prices or limits should be hard-coded into ScreenNote. + +Official sources: +- Loom pricing: https://www.loom.com/pricing and https://www.atlassian.com/software/loom/pricing +- Tella feature/pricing overview: https://www.tella.com/features and https://www.tella.com/pricing +- Zight plans: https://zight.com/pricing +- Claap licenses: https://help.claap.io/en/articles/6517952-understanding-claap-plans-licenses-and-pricing + +\n**Price snapshot note (26 November 2026):** amounts are USD as shown on official pricing/help pages at research time; billing cadence, region, tax and checkout selection can change the payable amount. These are competitor observations, not ScreenNote pricing recommendations. Tella: https://www.tella.com/pricing · Zight: https://zight.com/pricing and https://support.zight.com/hc/en-us/articles/5825001220631-Plans-Pricing-and-Plan-Changes · Loom: https://www.loom.com/pricing.\n\n## Feature-gap matrix and response + +| Workflow | Competitor evidence | ScreenNote response / gap to close | +|---|---|---| +| Capture modes | Loom, Claap, Tella and Zight document screen, camera and/or combined capture. | Keep the browser flow simple; expose mic/system audio/camera as clear toggles, preserve import as an equal first-class path, and communicate browser capability limits before capture. | +| Feedback precision | Claap documents timestamps, pinned moments and area annotations; Loom offers video comments/reactions. | Combine timestamp + normalized frame-point + drawn region, with accurate seek and annotation persistence across trim. | +| Post-capture polish | Tella documents clip workflows, transcript editing, subtitles and zoom effects; Zight documents trim and annotations. | Keep editing lightweight and safe: non-destructive trim, original retained, annotations/captions/chapters in one review workspace. | +| Guest collaboration | Loom/Claap support shared links and video discussion; Claap documents public links without requiring an account. | Account-free guest review is the default; comments and review decisions remain tied to a temporary share and expire with it. | +| Privacy and lifecycle | Competitors provide privacy controls; ScreenNote's documented model is local-first and temporary by design. | Make local-only vs published status unmistakable, show expiry/password before publishing, and verify revoke/expiry deletes media and discussion from D1/R2. | +| Workflow completion | Zight has request links and bug-report flows; Loom has integrations and analytics. | Close the loop with a compact review brief, approve/changes/question decisions, resolve/reopen threads, and exportable Markdown handoff—without turning the app into a heavyweight team suite. | +| Visual quality | Tella emphasizes creator-grade output; major products use familiar video-player conventions. | Avoid feature parity clutter. A quiet editorial interface, reliable responsive video, strong typography and one clear primary action per state should make the product feel considered. | + +## ScreenNote performance stretch goals + +These are **acceptance targets, not measured results**. Measure with Lighthouse/CrUX and real-device traces; report p75 separately for mobile and desktop. + +| Metric | Public good baseline | ScreenNote stretch target | +|---|---:|---:| +| LCP | <= 2.5 s | <= 1.8 s | +| INP | <= 200 ms | <= 150 ms | +| CLS | <= 0.1 | <= 0.05 | +| Comment-to-frame seek | no standard CWV metric | <= 100 ms after click on local/shared playback | +| Local recording persistence | no standard CWV metric | begin chunk persistence during capture; stop should finalize without a full-file re-encode | +| Editor readiness | no universal competitor benchmark published | <= 2.0 s on the defined mid-range Android test device with a representative 1080p clip | +| Upload feedback | no comparable public benchmark found | progress updates at least every 500 ms; never block local save on cloud publish | + +Do not claim ScreenNote is faster than a competitor until the same workload, device, browser, network and capture settings have been measured against that competitor. + +## ScreenNote's differentiated product promise + +**A temporary, private-by-default video review room—not another permanent video library.** + +The most defensible product focus: +- Record or import without account friction. +- Keep the original locally; explicitly publish a temporary review copy. +- Share a short, clear link with expiry and optional password. +- Give precise timestamped comments and frame-point annotations. +- Capture a review purpose, focus and expected outcome. +- Resolve feedback and export a structured handoff for a developer or coding agent. +- Make revoke/expire/delete behavior transparent and auditable. + +## Visual direction implemented in this branch + +**Field Notes:** warm mineral paper, restrained evergreen, quiet sage surfaces, soft graphite text, precise mono metadata, and generous but disciplined spacing. No purple/blue gradients, neon-lime UI, oversized decorative cards, or new font downloads. The current system font stack is retained; typography tokens control scale, line-height and rhythm. + +Light and dark modes use the same semantic tokens. Dark mode is warm charcoal/forest rather than pure black; the accent becomes a muted light sage for accessible contrast. + +## Verification status — 26 November 2026 + +### Completed on the isolated Cloudflare rebuild + +- Automated responsive containment at 13 widths from 320px through 1920px, in light and dark modes, plus short landscape viewports; no document or tested control-panel horizontal escape. +- Screenshot evidence captured for 320/375px mobile, 768px tablet, 1120px laptop and 1440px desktop, with dedicated editor and preview viewport captures. +- Automated keyboard focus traversal, accessible names, 44px mobile targets for primary controls and the share/comment actions, and light/dark text contrast checks. +- End-to-end coverage for local import, preview/editor, recording settings, captions and chapter exports, annotations/undo/delete, annotated-frame and annotated-copy export, library backup/restore, offline local editing, guest share/review, password gate, review decisions, reactions, creator controls, and privacy route. +- Production-built client budget passes: JavaScript 112.9 KiB gzip against 130 KiB; CSS 12.8 KiB gzip against 16 KiB. These are transfer-size checks, not Core Web Vitals measurements. +- Latest isolated Cloudflare deployment passed live API acceptance against D1/R2 and a separate guest browser: resumable upload, password protection/lockout, byte-range media, comments/replies/edit/delete, rate limiting, resolve, review/reaction, owner controls, revoke and cleanup. +- The latest live guest-review screenshots were inspected at 320px and 1440px. The comment-action spacing and singular comment-count details were corrected and verified in the final evidence. + +### Remaining real-device proof before public launch + +- Run Lighthouse/CrUX or equivalent real-user measurement on physical mid-range Android and desktop hardware; report p75 LCP, INP and CLS. The stretch targets remain goals, not measured results. +- Confirm capture permission/audio-track behavior on real Chrome/Edge/Safari/Firefox devices; browser picker and system-audio availability vary by platform. +- Repeat long-duration recording, thermal/memory and constrained-network upload tests on actual mobile hardware. + +### Deployment and schema note + +The rebuild is deployed only to the isolated development Worker; the existing Vercel production app remains untouched. CI did not apply D1 migrations because the dedicated D1 write token is not configured. No migration files changed in the latest UI/research revisions, and the deployed live D1/R2 acceptance passed against the current schema. Configure the dedicated D1 token before making or deploying any future migration change. diff --git a/rebuild/DESIGN-SYSTEM.md b/rebuild/DESIGN-SYSTEM.md new file mode 100644 index 0000000..d4f6c5d --- /dev/null +++ b/rebuild/DESIGN-SYSTEM.md @@ -0,0 +1,89 @@ +# ScreenNote design system — Field Notes + +**Status:** semantic token foundation exists in `rebuild/src/styles.css`; full legacy selector migration and light/dark acceptance remain in progress. Do not treat the token table as proof that every component is already compliant. +**Font policy:** retain the existing system font stack; no remote font or subscription dependency. + +## Brand direction + +Field Notes is a calm, warm, editorial workspace: mineral paper, deep evergreen, restrained sage, precise mono metadata, and quiet borders. The product should feel like a considered creative tool—not a generic AI dashboard. + +- Evergreen is reserved for primary actions, selected states, focus and meaningful links. +- Sage is a supporting surface/highlight, not a page-wide wash. +- Rust is for destructive, error or caution states. +- Avoid neon lime, purple/blue gradients, glossy glass, oversized decorative cards and emoji iconography. +- Use Lucide line icons consistently; keep video itself uncropped and visually dominant. + +## Semantic color tokens + +| Token | Light | Dark | Purpose | +|---|---|---|---| +| `--sn-paper` | `#f4f2ec` | `#171d19` | App/page background | +| `--sn-surface` | `#fbfaf6` | `#202822` | Cards, panels | +| `--sn-raised` | `#fffefa` | `#263129` | Inputs, raised controls | +| `--sn-ink` | `#202a24` | `#edf0e9` | Primary text | +| `--sn-muted` | `#626c63` | `#b0b9af` | Secondary text | +| `--sn-subtle` | `#879087` | `#89958a` | Tertiary metadata | +| `--sn-line` | `#d9ddd4` | `#39453c` | Borders/dividers | +| `--sn-line-strong` | `#bcc5b9` | `#536256` | Emphasized borders | +| `--sn-accent` | `#315b45` | `#a8c7ad` | Primary action/selected state | +| `--sn-accent-hover` | `#254a37` | `#bdd6c0` | Action hover | +| `--sn-accent-soft` | `#e5ece4` | `#2d3c31` | Selected/quiet action surface | +| `--sn-accent-ink` | `#fffdf8` | `#172019` | Text on accent | +| `--sn-highlight` | `#d9dfc7` | `#435343` | Subtle emphasis | +| `--sn-alert` | `#a6533d` | `#e1a08a` | Error/destructive state | +| `--sn-alert-soft` | `#f3e5df` | `#3c2b27` | Alert surface | + +The legacy aliases (`--paper`, `--panel`, `--white`, `--ink`, `--muted`, `--line`, `--acid`, `--acid-ink`, `--rust`, `--shadow`) map to semantic tokens so existing components remain compatible while migrating. + +## Typography + +Use the existing stack: + +```css +system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif +``` + +Metadata may use the existing system monospace stack. + +| Token | Size | Line height | Use | +|---|---:|---:|---| +| `--sn-text-xs` | 12px | 1.4 | Dense metadata | +| `--sn-text-sm` | 13px | 1.5 | Secondary controls/body | +| `--sn-text-md` | 15px | 1.58 | Default reading size | +| `--sn-text-lg` | 18px | 1.4 | Section lead | +| `--sn-text-xl` | 22px | 1.3 | Card/section heading | +| `--sn-text-2xl` | 30px | 1.22 | Page heading | +| `--sn-text-display` | `clamp(36px, 5.2vw, 62px)` | 1.12 | Landing headline | + +Headings use tight negative tracking and balanced wrapping. Body copy uses comfortable leading; timestamps and technical metadata use tabular/monospace numerals. Avoid shrinking text merely to fit—allow wrapping and reflow. The editor title area is capped at 620px on desktop and shrinks with the viewport so long recording names cannot crowd the close control. + +## Spacing, radius and depth + +Spacing scale: `4, 8, 12, 16, 20, 24, 32, 40, 48, 64px` (`--sn-space-1` through `--sn-space-16`). + +Radius scale: `4, 7, 12, 18px` (`--sn-radius-xs` through `--sn-radius-lg`). Use small radii for controls and medium/large only for primary work surfaces. + +Shadows are layered and restrained: +- `--sn-shadow-sm`: quiet elevation for cards/controls. +- `--sn-shadow-md`: hover or modal separation. +- `--sn-shadow-lg`: modal/overlay only. + +## Interaction and accessibility rules + +- Primary action is visually singular in each state. +- Interactive targets are at least 44px high where practical. +- Every interactive control has a visible keyboard focus ring. +- Reduced-motion preference disables nonessential animation. +- Normal text contrast must remain at least 4.5:1; large text at least 3:1. +- Light/dark mode changes semantic tokens, not individual hard-coded component colors. +- Keep controls, tables, comments, long titles and metadata contained at 320px; never force horizontal page scroll. +- Video previews use `object-fit: contain` and preserve the source aspect ratio. + +## Performance guardrails + +These are product targets, not measured field results: p75 LCP <= 1.8s, INP <= 150ms, CLS <= 0.05. Measure separately on mobile and desktop; never state competitor superiority without matched-device/network tests. + + +## 26 November execution note + +The base legacy root palette declarations were removed in favor of the semantic token layer. The UI stack now uses `--sn-font-ui`, and shared line-height tokens are applied to the main reading surfaces and headings. Theme-specific toast/error contrast and review-status surfaces were corrected. This is an incremental migration; remaining hard-coded component colors and all real-device/theme-state evidence still require full audit. diff --git a/rebuild/EXECUTION-AUDIT-2026-11-26.md b/rebuild/EXECUTION-AUDIT-2026-11-26.md new file mode 100644 index 0000000..f75c758 --- /dev/null +++ b/rebuild/EXECUTION-AUDIT-2026-11-26.md @@ -0,0 +1,85 @@ +# ScreenNote full-scope execution audit — 26 November 2026 + +This is the active completion ledger for the Cloudflare-first ScreenNote rebuild. It is an execution record, not a plan-only deliverable. A passing build or a feature being mentioned in a document is not accepted as proof that the product requirement is complete. + +## Original assignment + +Take over the isolated Cloudflare rebuild and make the whole product substantially better than the original and competitive with leading async video tools. Research current industry leaders and apply the evidence to product decisions; refine the existing font stack's hierarchy and line spacing; establish a premium, coherent design-token system for light and dark modes; overhaul every screen, route, component, responsive behavior and state; improve and add genuinely useful product capabilities; preserve existing behavior; and inspect, fix, test and verify the actual deployed application end-to-end. Continue through discovered defects instead of stopping after a single feature or a few screenshots. + +## Current baseline and safety boundary + +- Repository: `buttercode101/ScreenNote` +- Work branch: `rebuild/cloudflare-web-first` +- Isolated development Worker: `https://screennote-dev.buttercoder-dev.workers.dev` +- Production branch remains `main`; production is not being changed or cut over during this acceptance work. +- Current product candidate is not yet certified as a complete replacement. +- Current branch must be tested and deployed after each meaningful implementation batch. + +## Source-level findings confirmed during this audit + +1. The design-system document describes Field Notes semantic tokens, but the stylesheet retains earlier hard-coded palette declarations and older theme-specific override blocks. The token system exists, but its application is not yet complete and consistent across all components. +2. The share-link success toast used fixed white text with a background derived from the current text token. In dark mode this could produce pale text on a pale surface. Corrected with theme-semantic surface/text/border tokens. +3. The light alert token `#a6533d` had a 4.35:1 contrast ratio on its alert surface, below WCAG AA's 4.5:1 normal-text requirement. Changed to `#963f2d` (5.61:1 on the light alert surface). Dark alert contrast remains above 6:1. +4. The product differentiation document explicitly marks version-aware review and the privacy-safe Repro Capsule as roadmap work, not shipped capabilities. The current candidate therefore does not yet deliver all of its own differentiation proposal. +5. The existing handoff export omitted guest review decisions and used a relative media path; deleted comment text could be included in the exported discussion. Reworked the share export into a versioned review packet with absolute share/media URLs, guest decisions, review brief, captions/chapters, annotations, bug report and deleted-comment text redaction. Added both JSON and Markdown guest-facing exports; automated coverage is being added. +6. The candidate still has a Vercel compatibility proxy for legacy `/api/clip` contracts. The frontend is independent, but the whole service is not yet fully Cloudflare-native. +7. Automated viewport and transfer-size checks are not real-device Core Web Vitals measurements. Physical Android/desktop capture behavior, long-session stability, p75 LCP/INP/CLS, manual screen-reader acceptance and full reference-vs-candidate parity remain external or incomplete gates. + +## Completion ledger + +### Research and product strategy +- [x] Competitor feature/pricing research documented with official sources and limitations. +- [ ] Keep researching the relevant competitors and validate differentiators against current workflows—not just pricing pages. +- [ ] Turn the complete research into an implemented, tested product advantage rather than a proposal document alone. + +### Product differentiation and feature completeness +- [x] Review brief, guest review decisions, review status, reactions and basic handoff export exist in the current code. +- [ ] Complete review lifecycle: owner sees all guest responses, clear outstanding actions, resolution, revised version, and final handoff. +- [ ] Implement version-aware review with safe comment carry-forward and explicit time/frame drift handling. +- [ ] Implement the privacy-safe Repro Capsule only with explicit permission, local preview/redaction and no credential/header/body capture by default. +- [ ] Complete structured issue packet exports and verify accurate content, privacy and interoperability. +- [ ] Ensure every proposed feature is implemented end-to-end or explicitly removed from the product promise; no roadmap item may be presented as shipped. + +### Design and UI quality +- [ ] Audit every route, modal, menu, form, editor tab, share state, empty/loading/success/error/offline state. +- [ ] Finish semantic token migration; remove conflicting legacy theme overrides and hard-coded UI colors where semantic tokens are appropriate. +- [ ] Verify every text/surface/control combination in both themes, including transient toasts, alerts, disabled, selected, hover and focus states. +- [ ] Refine font hierarchy, line-height, spacing and reading rhythm across landing/workspace, editor, preview, guest share and privacy page. +- [ ] Complete mobile/tablet/desktop and short-landscape behavior; verify text wrapping, overflow, video proportions, touch targets, keyboard and zoom. +- [ ] Review every interaction and destructive path; maintain accessibility names, focus behavior, reduced motion and screen-reader usability. + +### Reliability, parity and security +- [ ] Complete full user journey from fresh browser to local recording/import, edit, publish, guest review, owner resolution, export, revoke and cleanup. +- [ ] Complete Vercel-reference vs Cloudflare-candidate parity tests using equivalent synthetic data; compare media bytes/outputs, permissions, persistence and failures. +- [ ] Verify interrupted network upload/resume, retry, idempotency, quotas, cleanup and concurrent D1/R2 operations. +- [ ] Remove or formally disposition the legacy Vercel compatibility proxy after contract and migration acceptance. +- [ ] Complete independent threat model and review of secrets, privacy, rate limits, abuse, retention and deletion. +- [ ] Keep production unchanged until backup, migration, rollback and cutover acceptance are proven. + +### Performance and release proof +- [ ] Measure real-device performance on physical mid-range Android and desktop; report LCP, INP and CLS separately and distinguish lab from field data. +- [ ] Test long recordings, memory/thermal behavior, browser capture permission/audio differences and constrained mobile networks. +- [ ] Inspect final screenshots for every major surface/state in both themes; fix discovered issues and rerun. +- [ ] Keep a truthful evidence record: commit SHA, CI runs, deployed Worker version, live API/browser evidence, known limitations and remaining release gates. + +## Work started in this execution + +- Fixed theme inversion/contrast on share-link toast and error surfaces. +- Increased the light alert token to a WCAG-AA-compliant color. +- Added a light/dark contrast regression test for toast, toast metadata/action and error surfaces. +- Expanded guest share export to a versioned JSON review packet and Markdown handoff; redacts deleted comment text and includes guest decisions and absolute URLs. +- Added end-to-end assertions for export contents and deleted-comment privacy. CI/deployment results are pending for the latest branch head. + +## Acceptance rule + +Do not mark this rebuild complete because a workflow is green, the Worker is deployed, or one screen looks polished. Close every applicable ledger item with implementation and evidence, disclose external gates, and keep production isolated until the user explicitly authorizes cutover. + + +## Addendum — current execution batch + +- Semantic root palette cleanup and typography/line-height token application are committed. +- Review status chip surfaces now use semantic accent/alert tokens. +- Guest share review packet now exports JSON and Markdown, uses absolute share/media URLs, includes guest decisions, and redacts deleted comment text. +- Repro Capsule extension, parser, editor import, unit tests, extension privacy-boundary tests and E2E import/export assertions are committed. +- Latest observed workflow for commit `1ef0aa1be7a767d3abb759fa8af085b68da93e0a` is running; do not report the current batch as green until its E2E and isolated deployment/live browser jobs complete. +- The previous 7782 commit Cloudflare workflow failed typecheck due a malformed regression-test fixture; that fixture was corrected in commit `1ef0aa1...` and is being rerun. The failure was in the test source, not in the application code. diff --git a/rebuild/FEATURE-PARITY-ACCEPTANCE.md b/rebuild/FEATURE-PARITY-ACCEPTANCE.md new file mode 100644 index 0000000..4ca6cac --- /dev/null +++ b/rebuild/FEATURE-PARITY-ACCEPTANCE.md @@ -0,0 +1,181 @@ +# ScreenNote parity and replacement acceptance + +**Baseline date:** 2026-11-25 +**Canonical repository:** `buttercode101/ScreenNote` +**Production reference:** Vercel, branch `main`, commit `5107d2f3d70ab31430e196890ae5c50335cf8d6e` +**Replacement candidate:** Cloudflare branch `rebuild/cloudflare-web-first`, latest inspected Vercel preview commit `96d39af695b89b40d2c2710eecf37f34e7b48f84` +**Decision:** Keep Vercel production unchanged. Cloudflare is a development candidate, not a production replacement. + +This document separates documented implementation from verified parity. A feature marked "documented" is not thereby proven equivalent in the deployed candidate. + +## 1. Release and deployment facts + +| Item | Vercel reference | Cloudflare candidate | +|---|---|---| +| Deployment | Production deployment READY, 2026-11-08 | Cloudflare dev Worker documented live, 2026-11-25 | +| Source branch | `main` | `rebuild/cloudflare-web-first` | +| Architecture | Static browser app + Vercel Node Functions + private Supabase Storage/Postgres gateway | React workspace + Cloudflare Worker + D1 + private R2 | +| Environment | Existing production | Isolated dev resources | +| Production cutover | Serving users | Not approved | +| Domain | `screennote-woad.vercel.app` | `screennote-dev.buttercoder-dev.workers.dev` | + +Evidence: +- Root README states the publishing API requires Vercel Node Functions and its private storage gateway. +- Rebuild README describes isolated Worker/D1/R2 resources and says production cutover is a separate decision. +- Latest Vercel deployment inspection: production READY on main; Cloudflare branch also has a READY Vercel preview, which is not evidence of Cloudflare production readiness. + +## 2. Feature parity ledger + +Status meanings: +- **Documented**: candidate README claims implementation; deployed parity still needs direct route/API/UI evidence. +- **Not established**: candidate documentation does not establish an equivalent implementation. +- **Known limitation**: candidate documentation explicitly describes a reduced capability. +- **External gate**: cannot be completed by repository automation alone. + +| Capability | Vercel reference evidence | Cloudflare candidate evidence | Acceptance required | +|---|---|---|---| +| Guest-first use; no account | Root README, first-run flow | Guest sessions documented | Fresh browser, no account, complete full journey | +| Browser screen capture | Root README; launch readiness | Capture documented | Real desktop browser source picker, permission deny/retry, device changes | +| Microphone/system audio/camera bubble | Root README | Optional tracks/composition documented | Real device/track selection and truthful unsupported states | +| Pause/resume/finalize | Release verdict and capture tests | Documented | Real MediaRecorder lifecycle, interrupted capture and recovery | +| Local library / IndexedDB | Root README and technical notes | IndexedDB library documented | Persistence, quota exhaustion, corrupt data, reload and browser restart | +| MP4/WebM import | Release verdict | MP4/WebM/MOV documented | MIME and magic-byte validation, malformed and oversized inputs | +| Local trim preserving original | Release verdict | Trim to WebM copy documented | Compare original bytes and output playback/duration/audio | +| Explicit temporary publishing | Vercel live smoke and API tests | Worker lifecycle documented and live smoke reported | Real publish from UI through storage, retry and rollback | +| Expiring links (1/3/7 days) | Root README | Documented | Clock-controlled tests plus real elapsed-time expiry | +| Password-protected shares | Release verdict | Password UI E2E plus live D1 lockout smoke; wrong-password and five-attempt lockout verified | Independent brute-force/enumeration review, password rotation policy and broader abuse testing | +| Private video delivery / range seeking | Technical notes | R2 private media and byte ranges documented | Unauthorized access, range edge cases, cache headers and revoked URL behavior | +| Comments/replies/edit/delete | Release verdict | Nested comments documented | Ownership, concurrency, idempotency, refresh and deep links | +| Resolve/reopen moderation | Release verdict | Documented | All creator/author permission combinations | +| Playback bubbles and timeline markers | Root README | Documented | Seek accuracy, keyboard access, fullscreen/PiP boundaries | +| Frame-point annotations | Not established as a named shipped capability in root README | Frame-point annotations documented | Verify actual UI editing, persistence, export and mobile usability | +| Captions SRT/VTT import/export | Technical notes document owner-supplied captions | Implemented in `legacy/lib/enrichment.js` and `legacy/public/extras-ui.js`; Playwright imports, saves and exports VTT | Verify malformed/edge-case parser coverage and shared persistence on live Worker | +| Searchable transcript | Technical notes document searchable timestamp transcript | Implemented as search over owner-supplied caption cues in `extras-ui.js`; no automatic transcription | Verify cue ordering, empty search, Unicode/case handling and seek behavior; do not imply AI transcription | +| Chapters | Technical notes list chapters | Implemented in `enrichment.js` and `extras-ui.js`; chapter navigation is rendered in viewer | Verify malformed timestamps, ordering, boundary conditions and live persistence | +| Advanced annotation/redaction/mask tools | Technical notes list rectangles, arrows, highlights, opaque masks and blur; marked copies | `markup.js` and editor UI implement rectangle, arrow, highlight, opaque redaction and blur marks; marks are frame-normalized | Verify mark persistence, export/trim rendering, blur/redaction correctness, keyboard/touch usability and output pixel evidence | +| Structured coding-agent handoff | Not established in root README | Recursive discussion JSON documented; explicitly lacks extracted transcript/keyframes | Schema compatibility, export/import, escaping, large discussion | +| Bug reports | Technical notes list structured reports and Markdown download | Implemented in `enrichment.js` and `extras-ui.js`; owner-supplied fields, optional explicit user-agent inclusion and Markdown export | Verify URL credential rejection, long text, shared visibility warning and live persistence | +| Recovery keys | Release verdict confirms management restore (not video backup) | Portable key export/import documented | Restore in a separate browser/profile, wrong key, partial restore and revocation | +| Offline behavior | Release verdict confirms offline banner/publish gate | Offline/online events update the connection banner; service-worker offline library E2E exists | Verify all routes/assets cached, offline editing/import/trim, stale API failures and retry/reconnect behavior | +| Upload resume/retry | Release verdict confirms per-part retry and resume | `app.js` resumes from `upload-state`, skips acknowledged chunks and retries transfers | Verify real interrupted network resume, duplicate part idempotency, expiry/re-reservation and orphan cleanup under live R2/D1 | +| Storage/capacity handling | 50 MB per clip; 10 min; 1 GB budget; 100 comments | 100 MB per upload; 10 min; 200 comments; dev R2/D1 | Confirm actual quotas, atomic reservations, concurrency, cleanup and abuse cost | +| Accessibility | 44px targets, focus, skip link, aria-live documented for Vercel | E2E checks visible control names, modal focus cycling and 44px touch controls; automated light/dark text-token contrast meets WCAG AA | Manual screen-reader, reduced-motion and full component contrast review remains open | +| Responsive visual QA | 11-viewport re-run explicitly outstanding in Vercel verdict | 13 widths in light/dark, short-landscape heights, 320px 2× device-scale, screenshot evidence and containment checks pass | Real browser zoom, device orientation changes and physical-device acceptance remain open | +| Physical Android/iOS | Explicitly unverified in Vercel verdict | Explicitly outstanding | External device acceptance; no false certification | +| Security review | Existing CSP, IDOR/storage gateway tests; remaining P2 items listed | Worker tests and live D1/R2 smoke cover origin rejection, headers, owner-key controls, password lockout, comment throttling, range access and deletion; scheduled rate-limit cleanup added | Independent threat model/security review, storage-abuse/concurrency tests and full secrets/data-deletion review remain open | + +## 3. Independent frontend acceptance + +The Cloudflare application now has its own React 19 + TypeScript + Vite entrypoint and an independent design system. The build no longer bundles or serves the legacy Vercel HTML, CSS or browser JavaScript. The legacy source is retained only as a migration/reference corpus. + +Verified by the rebuild workflow: +- React entrypoint is served from `/src/main.tsx` in development and the Vite-generated asset bundle in production. +- The legacy `/app.js` and `/style.css` requests are absent from the new frontend. +- Independent warm-paper / near-black / acid-lime visual language, Space Grotesk / Source Sans 3 / DM Mono typography, and custom recording/library composition. +- Playwright responsive checks at 13 viewport widths, light and dark themes, import/preview/share journey, and no horizontal viewport overflow. +- Build and deployed live API acceptance run separately; the existing Vercel production deployment is not modified. + +The frontend is independent; the service is not yet fully Vercel-independent. A compatibility fallback remains for the old `/api/clip` contract so existing legacy shares are not silently abandoned. The new React frontend uses Cloudflare's Worker API for new sharing flows. + +## 3A. 25–26 November implementation update — pending full acceptance + +The Cloudflare branch has moved beyond the earlier primary-flow-only UI. The following capabilities are now surfaced in the independent React application. They are **implemented in the branch**, but must not be marked release-accepted until the current Worker build, live D1/R2 smoke, Playwright evidence and failure-path tests pass. + +| Capability | Current implementation | Remaining proof | +|---|---|---| +| Separate Preview and Edit | Dedicated playback preview and editing workspace; recording cards expose both actions; post-publish toast has Open preview and Copy link | Deployed navigation, keyboard and viewport checks | +| Local editing | Editable title, trim-to-new-copy, preserve-original behavior | Verify source/output playback, audio, duration and metadata retention | +| Markup | Rectangle, arrow, highlight, blur and opaque redaction; undo/clear; annotated-copy export | Verify actual encoded pixels, blur/redaction boundaries, audio continuity and long-video behavior | +| Captions/transcript | Owner-supplied SRT/VTT import, cue validation, local search and timestamp seeking | Live share round-trip, Unicode and malformed-file acceptance | +| Chapters | Timestamped chapter editing and viewer navigation | Live share round-trip and edge cases | +| Bug reports | Structured fields and Markdown export; explicit shared-visibility notice | URL and long-text security cases; live viewer acceptance | +| Review status | Needs feedback / changes requested / approved stored in local clip and shared context | Live D1 persistence and viewer permissions | +| Shared context | Owner-key protected Worker endpoint; viewer displays captions, transcript search, chapters, annotations and report | Real deployed D1 migration and password-gated read/write checks | +| Anonymous reactions | New D1 `share_reactions` table and `/reactions` API; one like/thanks/idea reaction per browser key, with counts and removal | Live share test, one-vote identity, 500-voter limit and UI accessibility | +| Portable library backup | ZIP export/restore includes local media, editing metadata and private share-management keys; duplicate-safe restore; thumbnails are regenerated on restore | Device storage/quota, corrupt archive, large archive and separate-profile restore | +| Library thumbnails | Locally generated JPEG preview frames for imported, recorded, trimmed and annotated copies; lazy generation for older clips | Low-memory mobile decoding and large-library performance | +| Recording setup | 720p saver / 1080p balanced / up-to-1440p clear profiles, microphone source refresh/selection, system audio, camera bubble size/corner, 3-second cancellable countdown, pause/resume | Real device/source picker tests; unsupported mobile browser behavior | +| Offline behavior | Connection banner; local preview/edit/download remain available; publishing is blocked offline | Offline reload/cache behavior and reconnect/resume | +| Resumable share upload | 2 MiB chunks, D1 part state, R2 part objects, bounded streaming assembly, retry helper, local pending-reservation state and progress | Live interrupted-network resume, duplicate part idempotency, expired reservation, cleanup and storage-abuse tests | + +Important distinctions: +- Captions are owner-supplied. There is no automatic speech-to-text transcription. +- The current markup tools apply spatial marks to the video image; they are not a frame-by-frame keyframe editor. +- Camera placement offers four corners, custom horizontal/vertical sliders, size selection, direct pointer drag and keyboard-arrow positioning. Bounds now match the recorder's shorter-dimension bubble geometry for landscape and portrait canvases. +- Resumable upload uses application-level R2 part objects and a streamed final assembly, not R2's native multipart API. +- Browser viewport emulation is not physical Android/iOS acceptance. + +## 4. Immediate parity blockers + +1. The core editor/context and sharing flows now have deployed Worker smoke and Playwright evidence, including annotated export playhead/pause restoration, frame capture, captions/chapters, review settings and responsive states. Full Vercel-vs-Cloudflare output parity (including encoded pixels/audio) is still not established. +2. Automatic transcript extraction, generated keyframes and frame-by-frame keyframe editing are not implemented. Transcript search is over owner-supplied captions only. +3. Camera bubble drag positioning and keyboard placement are implemented and covered by Playwright. Native desktop capture, real display-source selection, actual microphone/camera track selection and browser-specific permission behavior still require physical desktop/mobile testing. +4. Recovery-key restore in a separate browser, real elapsed-time expiry, independent security review, manual accessibility and physical-device QA remain open. +5. Candidate upload/comment limits differ from Vercel. Live tests now cover resumable upload assembly and comment throttling; real interrupted-network resume, reservation expiry, concurrency and storage-abuse acceptance remain open. +6. Existing production data must not be copied, migrated, deleted, or invalidated as part of development smoke tests. + +## 5. Required engineering sequence + +### Gate A — source inventory +Enumerate every route, screen, state, browser capability, API operation, data model, migration, background task, and user-visible promise in both implementations. Map each item to exact source files and tests. This ledger is a starting point, not a substitute for source-level inventory. + +### Gate B — feature restoration +Implement every missing Vercel capability on Cloudflare, preserving local-first originals, explicit publishing, anonymous viewing, temporary retention, recovery controls, and existing privacy promises. No mock API may count as integration acceptance. + +### Gate C — backend and data correctness +Test D1 transaction/concurrency behavior, R2 multipart/resumable uploads, orphan cleanup, expiry, range reads, deletion, rate limits, token rotation, idempotency and storage quota failures. Test with synthetic data only. Never touch production user data. + +### Gate D — product and UI quality +Audit all routes and interaction states in light/dark mode at 320, 360, 375, 390, 414, 600, 768, 834, 1024, 1120, 1280, 1440 and 1920 CSS px; include short landscape heights, zoom, long text, keyboard, touch and screen-reader paths. Repair overflow, focus, contrast, target size, motion and empty/loading/error states. + +### Gate E — independent acceptance +Run the same black-box journey suite against Vercel and Cloudflare using equivalent synthetic fixtures. Compare outputs, permissions, media bytes, discussion data, expiry and failure behavior. Add tests for every discovered mismatch. Passing candidate-only tests is insufficient. + +### Gate F — cutover safety +Only after all prior gates pass: rehearse backup/restore, define an explicit data migration and rollback plan, verify domain/TLS/cache/security configuration, run production smoke tests with synthetic content, and obtain a separate production cutover decision. Vercel remains available until rollback is proven. + +## 5. Non-negotiable acceptance criteria + +- 100% of shipped Vercel capabilities have an explicit disposition and evidence. +- No silent loss of data or capability. +- No test relies solely on mocked backend responses for an end-to-end claim. +- Every critical user journey passes on the deployed Cloudflare candidate. +- Security and privacy behavior is at least as strong as the reference. +- UI and accessibility regressions are fixed, not waived to make CI green. +- Physical-device limitations are disclosed honestly. +- No production migration or destructive action without a verified backup and explicit cutover authorization. + +## 6. Current verdict + +**Cloudflare development backend: promising, partial acceptance evidence.** +**Feature-complete replacement: not established.** +**Production replacement: not approved.** + +The next engineering work must be source-level inventory and parity implementation, not another claim of completion based on a narrow smoke suite. + + +## 7. 26 November execution audit — verified progress, remaining gates + +Latest verified rebuild commit: `e5886ac9480a19762a6ac85cec7aa5851122df5a` +Cloudflare dev Worker version serving 100%: `ad557a01-0150-4414-9856-4347b8e35e3e` +GitHub Actions push workflow: `45772322115` — typecheck, unit tests, build, Playwright E2E, isolated Worker deploy and live D1/R2 smoke all passed. The paired verification workflow also passed. + +Verified in this audit pass: +- Annotated-video export now stops on source errors, rejects incomplete output, bounds completion/cleanup, and restores the original playhead and paused/playing state; Playwright checks restoration. +- Recording bubble geometry uses normalized aspect-aware bounds; pointer drag and keyboard arrows are covered. +- Recording-card actions wrap at narrow widths; metadata keeps usable width; titles are visually clamped to two lines at all widths with the complete title retained in the DOM/title attribute. +- Share password gate wrong/correct UI flow and responsive state are covered; deployed password lockout is verified after fixing a cleanup query that had reset active attempts. +- Live comment throttling is verified against the deployed Worker; scheduled maintenance prunes stale rate-limit/password-attempt rows. +- Live D1/R2 smoke verifies guest upload/resume state, password access/lockout, range playback, review decisions/status, reactions, comments/replies/edit/delete/resolve, and share revocation/deletion. +- Responsive Playwright coverage checks 13 viewport widths (320, 360, 375, 390, 414, 600, 768, 834, 1024, 1120, 1280, 1440, 1920) in light and dark themes, plus 320×480, 568×320, 844×390 and 1024×600 short-landscape heights and a 320 CSS-pixel 2× device-scale context. Screenshot artifacts were inspected at 320px and 1440px. +- Automated contrast assertions now check text-token combinations against WCAG AA 4.5:1 in light and dark themes; light muted and rust tokens were darkened to pass. + +Still not release-accepted: +- Physical Android/iOS, real display-capture source picker, actual camera/microphone hardware selection, browser-specific permissions and device orientation changes. +- Manual screen-reader/reduced-motion review, browser zoom and full component/state contrast audit. +- Separate-profile recovery-key restore, real elapsed-time expiry and full upload interruption/concurrency/storage-quota testing. +- Black-box parity comparison against Vercel for every shipped capability, media bytes/audio/encoded markup correctness, and removal of the legacy `/api/clip` compatibility proxy after a migration plan. +- Automatic speech-to-text and frame-by-frame keyframe editing remain intentionally unimplemented; transcript search is owner-supplied captions only. +- The repository secret `CLOUDFLARE_D1_API_TOKEN` is not configured. No migration was needed for the latest verified commits because the rate-limit table was already present and directly verified in dev D1; future schema-changing deploys must supply the dedicated D1 edit token. Do not broaden the Worker deploy token. + +Vercel production remains untouched. This is a verified Cloudflare development candidate, not a feature-complete or production-approved replacement. diff --git a/rebuild/PRODUCT-DIFFERENTIATION-2026-11-25.md b/rebuild/PRODUCT-DIFFERENTIATION-2026-11-25.md new file mode 100644 index 0000000..a554a2e --- /dev/null +++ b/rebuild/PRODUCT-DIFFERENTIATION-2026-11-25.md @@ -0,0 +1,196 @@ +# ScreenNote product differentiation research + +**Research date:** 2026-11-25 +**Target:** Cloudflare-first ScreenNote rebuild +**Scope:** Product positioning and feature decisions informed by current competitor feature pages and market comparisons. This is research, not proof of customer demand; validate the proposed workflow with real users before pricing it as a paid promise. + +## Executive decision + +Do not compete as another screen recorder with a longer feature checklist. Screen recording, transcript editing, captions, chapters, AI summaries, zoom effects, sharing, comments, and analytics are already established across the category. + +Position ScreenNote as: + +> **The private, account-free way to turn a screen recording into a review that someone can act on—and a clean handoff to the person who will fix or approve it.** + +The product's core object should become a **Review** rather than a video file. A Review contains the video, a short brief, exact-moment feedback, a decision, a version history, and an exportable action packet. Keep the original local and make publishing explicit. + +This is a strategic hypothesis, not a claim that no competitor offers any individual part. The differentiation is the end-to-end experience, privacy defaults, guest access, and a practical handoff designed around solo builders, freelancers, small agencies, QA and support—not another generic video messenger. + +## Competitive evidence + +### Loom — async communication plus AI automation + +Loom's current official materials list auto titles, summaries, chapters, tasks, CTAs, transcript editing, filler/silence removal, AI workflows, bug reports and agent-oriented recording. Its Starter plan is free but limits recordings to 25 videos and 5 minutes each; Business + AI is listed at $24 per user/month. + +**Implication:** summaries, chapters, transcript editing and “AI-powered video” are not sufficient differentiation. ScreenNote must win on a more focused workflow and a more user-controlled experience. + +Sources: +- https://www.loom.com/pricing +- https://support.atlassian.com/loom/docs/loom-ai-features/ + +### Tella — polished production and creator editing + +Tella promotes screen/camera recording, clip-based recording, transcript editing, automatic subtitles, zooms, layouts, transitions, backgrounds, analytics, sharing, and custom branding. Its listed Pro/Premium pricing is around $13–$19 per user/month billed annually, with plan and credit details varying. + +**Implication:** “beautiful recording + good editor” is crowded. Avoid spending the roadmap merely reproducing production effects. + +Sources: +- https://www.tella.com/features +- https://www.tella.com/pricing + +### Cap — local control and developer/agent workflow + +Cap is open source and offers local recording/editing, hosted sharing, custom S3 storage, self-hosting, transcripts, comments, analytics, CLI and MCP access. Its free personal tier includes a full local recorder/editor; paid cloud features are listed around $8.16/month when billed annually. + +**Implication:** privacy/local-first alone is not a moat. ScreenNote must make local-first useful in the complete review workflow and be honest about what is uploaded, stored and retained. + +Sources: +- https://github.com/CapSoftware/Cap +- https://cap.so/ +- https://cap.so/faq + +### Bug-report tools — technical context and reproducibility + +Current category comparisons distinguish tools that capture console logs, network requests, browser/device details and user actions from general video recorders. Loom helps explain what happened, but technical context is often still collected separately; specialized tools such as Jam and Marker.io focus on developer-ready evidence. + +**Implication:** a ScreenNote “repro capsule” is promising, but it must be privacy-safe and genuinely capture reliable context. Do not label manually typed steps or browser metadata as automatic telemetry. + +Source: +- https://midge.dev/docs/guides/best-bug-reporting-tools + +### Video review tools — frame-accurate feedback and approval + +Frame.io, Filestage, Ziflow and related review products already provide timestamped/frame-accurate feedback, markup, review states and version-oriented workflows. Some are expensive for small teams and focus on professional media pipelines. + +**Implication:** comments and approval alone are not unique. ScreenNote should make the workflow frictionless for an external guest and connect feedback directly to a practical fix/handoff, without requiring every reviewer to become a workspace member. + +Source: +- https://www.upsys-consulting.com/en/blog/best-video-feedback-tools + +## Proposed signature workflow: Review → Resolve → Ship + +### 1. Review Brief (first implementation priority) + +Before publishing, let the owner add a compact brief: +- **Purpose:** what the viewer is looking at. +- **Focus:** one or two things to inspect. +- **Expected outcome:** what “correct” looks like. +- **Requested action:** review, approve, reproduce, or provide feedback. +- Optional due date / audience label. + +Display the brief above the player, not buried in a description. Preserve it in the share metadata and include it in the handoff export. A good brief reduces vague feedback and makes the recording useful even if the viewer never watches every second. + +### 2. Guest decision workflow + +Add explicit reviewer actions: +- **Looks good** +- **Needs changes** +- **Ask a question** + +A decision must be attached to a reviewer identity label, timestamp, and current version. A change request should require or strongly encourage a comment anchored to a timestamp/frame. Owners can resolve requests and publish a new version. + +Guests must not need an account. Avoid implying verified identity when the reviewer is anonymous; label it clearly as a guest response. Rate-limit and protect the endpoint against spam. + +### 3. Repro Capsule (signature technical capability) + +For web bug reports, add an optional browser extension (not silent page scripts) that can explicitly capture: +- Current page URL and viewport/browser information. +- User-approved click/keyboard event outline. +- Console errors and failed requests, with sensitive headers, cookies, tokens, query parameters and response bodies excluded by default. +- Optional screenshots/keyframes at user-selected moments. +- A structured, editable reproduction checklist. + +The user reviews the capsule locally before publishing. Sensitive fields are scrubbed before upload; the user can remove entries. No background surveillance, no raw credential capture, no automatic upload without a clear consent action. + +Export a self-contained Markdown/JSON issue packet with video link, timestamps, steps, expected/actual result, environment, selected logs and reviewer comments. Integrate GitHub Issues first; add Linear only after a reliable OAuth/API implementation and permission review. + +**Why this matters:** the deliverable is not just “watch this video”; it is “here is enough evidence to reproduce, triage and fix the problem.” + +### 4. Version-aware review + +Treat each revision as a version of the same Review: +- Keep prior versions and their status. +- Carry unresolved comments forward by timestamp, with explicit “may have moved” indicators. +- Show resolved/unresolved feedback and a simple version change summary. +- Never silently shift or delete a comment when a trim changes timing. +- Allow owner to mark a version approved or superseded. + +### 5. One-click “Preview share” and audience test + +After publishing, show: +- **Open share preview** (opens the exact public/guest experience in a new tab). +- **Copy link** +- **View as guest** (test password gate, brief, player, comments and CTA without owner credentials). +- **Manage / stop sharing** + +Do not make “copy link” the only success action. A user needs to inspect what the recipient will actually see before sending. + +## Roadmap order — implementation, not a feature dump + +### P0 — Make the share experience a complete review +1. Review Brief fields and persistence in share details. +2. Public viewer renders brief and requested action clearly. +3. Guest decision endpoint/state with spam controls and anonymous-label honesty. +4. Owner sees decisions, feedback and resolved state in library/editor. +5. Post-publish preview / guest-view action. +6. Tests for password shares, expiry, revoked links, refresh, duplicate submissions, and mobile viewer. + +### P1 — Make feedback actionable +1. Version model and safe version publishing. +2. Timestamp/frame anchors for comments and annotations. +3. Issue packet export: Markdown + JSON, captions/chapters, selected comments, report and environment. +4. GitHub issue creation via explicit user-authorized integration; never expose tokens in client bundles. +5. A clean “next action” summary from review status and unresolved comments (deterministic first; optional AI later). + +### P2 — Repro Capsule +1. Prototype extension permission model and event capture. +2. Local redaction/preview before upload. +3. Console error capture and failed-request metadata (no secrets/body by default). +4. Stable JSON schema + import/export + regression fixtures. +5. Browser compatibility/security review before wider release. + +### P3 — Paid value (after usage validation) +Keep the basic local recorder and guest review useful without an account. Charge only for repeatable team value: +- Team review spaces and shared ownership. +- Longer retention / more hosted storage and bandwidth. +- Branded share pages/custom domain. +- Version history and audit trail. +- Review analytics and workflow integrations. +- Repro Capsule integrations / team triage workflow. + +Do not charge merely to remove arbitrary friction from the free local workflow. Do not launch a paid tier until storage, bandwidth, support burden and actual willingness to pay are measured. + +## Product principles + +- Guest-first: viewers do not need accounts. +- Local-first: originals stay on-device until the owner explicitly publishes. +- Private by default: temporary links, clear expiry, stop-share control, and no public indexing. +- Human review: AI is optional, explainable and never silently uploads sensitive material. +- Honest capability labels: browser-only recording must not pretend it captured DOM, console or network details it cannot access. +- Actionable output: every review should end with a decision, a question, a reproducible issue, or an explicit no-action outcome. +- Reliable over impressive: ship small, complete workflows with real backend state and tests; do not add decorative AI features or fake analytics. + +## Success metrics to instrument (privacy-respecting, opt-in where appropriate) + +- Record-to-first-preview completion. +- Publish success and retry rate. +- Share opened → feedback/decision conversion. +- Time from first feedback to owner resolution. +- Percentage of reviews with a clear brief. +- Version reshare rate and unresolved-comment carryover correctness. +- Guest completion without account creation. +- Repro packet usefulness measured by developer feedback, not by counting generated files. + +## Release acceptance for the signature workflow + +A release is not accepted until a fresh guest can open a share without an account, understand the brief, watch and seek, leave timestamped feedback, choose a review decision, refresh without losing it, and the owner can see the decision, resolve it, publish a revised version, and export an accurate issue packet. Test password-protected, expired and revoked links; 320px mobile; keyboard-only; both themes; concurrent reviewer submissions; and failed/offline states. + +This document is the product direction and acceptance definition. It does not claim these proposed features have already been implemented or deployed. + + +## 26 November implementation update + +- The guest share now offers a JSON review packet and a Markdown review handoff, including guest decisions and complete review context. Deleted comment bodies are redacted from both formats. +- The optional Chrome/Edge Repro Capsule extension and editor import path are implemented on the isolated rebuild branch. Capture is explicit, local-only, permission-limited, and excludes typed values/form data/network/console/screenshot capture. The import parser validates schema, caps step count and size, strips URL credentials/query/fragment, and formats a reviewable reproduction outline. +- Automated unit, extension-boundary and editor-import tests have been added. They are not a substitute for manual installation/testing in actual Chrome and Edge. +- Version-aware media review remains unimplemented: current comments are not safely migrated across different media versions. Do not claim that feature is shipped. diff --git a/rebuild/README.md b/rebuild/README.md new file mode 100644 index 0000000..c890e3b --- /dev/null +++ b/rebuild/README.md @@ -0,0 +1,43 @@ +# ScreenNote — Cloudflare application + +This branch is a separately implemented Cloudflare-first product. It is not a visual clone or a repackaged copy of the Vercel frontend. + +## Application boundary + +- **Frontend:** React 19 + TypeScript + Vite. The deployed entrypoint is `rebuild/index.html` and `rebuild/src/main.tsx`. +- **Design system:** independent editorial interface: Space Grotesk / Source Sans 3 / DM Mono, warm mineral paper, near-black recording surface and acid-lime action colour. It does not load the Vercel stylesheet or Vercel HTML/JS. +- **Build assets:** `scripts/prepare-public.mjs` now copies only the offline service worker and app icon. It does not bundle or copy the legacy browser app. +- **Backend:** Cloudflare Worker with D1 metadata and R2 media storage. +- **Local-first data:** IndexedDB stores original recordings on the user's device; publishing is explicit. +- **Legacy source:** `legacy/` remains in this branch as a behavior/feature reference and migration source only. It is not the deployed UI. + +## Important backend limitation + +The Worker still has a temporary `/api/clip` compatibility proxy to the Vercel API for older 0.5.0 clients and data contracts. The new frontend is independent of the Vercel frontend, but the entire service is not yet independent of Vercel. Do not describe the API layer as fully Cloudflare-native until the proxy is removed after contract-parity tests and an explicit legacy-link migration plan. + +Vercel production remains unchanged. + +## Build and test + +```sh +npm install +npm run typecheck +npm test +npm run build +npm run e2e +``` + +The build emits the Vite/React app. Legacy HTML, CSS and browser JavaScript are deliberately excluded from the Worker asset bundle. + +## Release gates + +See `FEATURE-PARITY-ACCEPTANCE.md`. The independent frontend is a new implementation; feature parity, Worker/API independence, visual acceptance, security review, accessibility review, and physical-device checks remain separate release gates. + + +## Review handoff and Repro Capsule + +The temporary share viewer can export a versioned review packet in JSON or Markdown. It includes the share/video URLs, expiry and password state, review brief/status, guest decisions, timestamped discussion, frame points, owner annotations, captions, chapters and bug-report context. Deleted comment bodies are redacted. Guest labels are unverified and the export is a handoff artifact, not an authenticated identity record. + +The optional Chrome/Edge Manifest V3 extension is in [extension/](extension/README.md). It starts only after a user click, captures a short click/navigation-key outline in the active tab, has no host permissions or network code, and asks the user to review/edit the JSON before download. Import it from the editor's **Captions & context → Bug report → Import Repro Capsule** action. ScreenNote sanitizes URL credentials, query and fragment again on import. Imported context remains local until the creator explicitly saves/publishes it; publishing makes saved context visible to share-link viewers. + +The extension does not collect screenshots, form values, typed characters, cookies, network requests or console logs. It is an interaction outline, not automatic full telemetry or a guaranteed reproduction. diff --git a/rebuild/cloudflare.config.ts b/rebuild/cloudflare.config.ts new file mode 100644 index 0000000..7e3ecf9 --- /dev/null +++ b/rebuild/cloudflare.config.ts @@ -0,0 +1,29 @@ +import { bindings, defineConfig, triggers } from "cf/config"; +import * as entrypoint from "./worker/index.ts" with { type: "cf-worker" }; + +const workerFirstAll = process.env.SCREENNOTE_WORKER_FIRST_ALL === "1"; + +export default defineConfig({ + worker: { + name: "screennote-dev", + entrypoint, + compatibilityDate: "2026-11-24", + compatibilityFlags: ["nodejs_compat"], + assets: { + notFoundHandling: "single-page-application", + runWorkerFirst: workerFirstAll ? ["/*"] : ["/api/*"] + }, + env: { + DB: bindings.d1({ name: "screennote-dev", id: "44a5859b-6411-4513-bd17-3302fbbc0575" }), + MEDIA: bindings.r2({ name: "screennote-media-dev" }), + STATIC: bindings.r2({ name: "screennote-static-dev" }), + ASSETS: bindings.assets() + }, + triggers: [triggers.scheduled({ schedule: "*/15 * * * *" })], + observability: { + enabled: true, + logs: { enabled: true, invocationLogs: true, headSamplingRate: 1 }, + traces: { enabled: true, headSamplingRate: 0.1 } + } + } +}); \ No newline at end of file diff --git a/rebuild/desktop/README.md b/rebuild/desktop/README.md new file mode 100644 index 0000000..ea73796 --- /dev/null +++ b/rebuild/desktop/README.md @@ -0,0 +1,41 @@ +# ScreenNote desktop companion — architecture + +## Product decision + +The web application ships first. A desktop companion is part of the product architecture, not a second product or a separate backend. + +The desktop client should reuse the React interface and ScreenNote API, while replacing browser capture with native capture adapters where the operating system offers capabilities the browser cannot reliably provide. + +## Proposed shell + +- Tauri 2 for a small native application shell. +- Reuse the web UI from `../src` and the same design system. +- Rust commands expose native capture, file access, OS permissions and secure local storage. +- Keep the capture engine behind a platform-neutral interface so the UI does not depend on Windows/macOS/Linux implementation details. + +## Capture adapters + +| Platform | Screen capture | System audio | +|---|---|---| +| Windows | Windows Graphics Capture | WASAPI loopback | +| macOS | ScreenCaptureKit | CoreAudio / ScreenCaptureKit audio | +| Linux | xdg-desktop-portal + PipeWire | PipeWire | + +Camera and microphone capture should use OS permission-aware native APIs or the browser media layer where reliable. The desktop client must never silently start capture. + +## Shared product services + +- Reuse the guest/session and recording metadata API. +- Reuse private R2 media storage and the same upload authorization rules. +- Keep local recordings available if the user declines cloud upload. +- Share links, playback, comments and AI processing remain server-side product capabilities, not desktop-only features. + +## Desktop release gates + +1. Web recording, local recovery and cloud upload are stable. +2. Native capture proof-of-concept passes on each target OS. +3. Permission prompts, system audio routing and device changes are tested. +4. Long recordings survive app crashes and OS sleep/resume. +5. Signed installers, auto-update and crash reporting are ready. + +Initial desktop target order: Windows, macOS, then Linux. This is a proposed implementation direction; platform prototypes must validate capture and audio quality before a release commitment. \ No newline at end of file diff --git a/rebuild/e2e/visual.spec.ts b/rebuild/e2e/visual.spec.ts new file mode 100644 index 0000000..62c9426 --- /dev/null +++ b/rebuild/e2e/visual.spec.ts @@ -0,0 +1,562 @@ +import { expect, test } from "@playwright/test"; +import { mkdir, readFile } from "node:fs/promises"; +import path from "node:path"; + +const viewports = [ + {width:320,height:780,name:"320-mobile"}, + {width:360,height:800,name:"360-mobile"}, + {width:375,height:812,name:"375-mobile"}, + {width:390,height:844,name:"390-mobile"}, + {width:414,height:896,name:"414-mobile"}, + {width:600,height:900,name:"600-small-tablet"}, + {width:768,height:1024,name:"768-tablet"}, + {width:834,height:1112,name:"834-tablet"}, + {width:1024,height:900,name:"1024-laptop"}, + {width:1120,height:900,name:"1120-laptop"}, + {width:1280,height:900,name:"1280-desktop"}, + {width:1440,height:960,name:"1440-desktop"}, + {width:1920,height:1080,name:"1920-wide"} +]; + +async function contained(page: import("@playwright/test").Page, width:number) { + const m=await page.evaluate(()=>{ + const selectors="button,input,select,textarea,.clip-card,.clip-grid,.capture-panel,.preview-modal,.publish-modal,.preview-workspace,.preview-workspace-content,.editor-workspace,.editor-topline,.editor-body,.editor-stage,.editor-toolbar,.editor-side,.editor-card,.annotation-list,.context-editor,.editor-tabs,.share-page,.share-topbar,.share-layout,.share-video-wrap,.share-discussion,.share-comment-form,.guest-review-panel,.review-decision-options,.review-response-list,[role=dialog]"; + const offenders=[...document.querySelectorAll(selectors)].filter(el=>{ + const style=getComputedStyle(el),r=el.getBoundingClientRect(); + return style.display!=="none"&&style.visibility!=="hidden"&&r.width>0&&(r.left < -1 || r.right > innerWidth+1); + }).map(el=>({tag:el.tagName,selector:el.className?.toString?.()||el.id||"",left:Math.round(el.getBoundingClientRect().left),right:Math.round(el.getBoundingClientRect().right),width:Math.round(el.getBoundingClientRect().width)})); + return {doc:document.documentElement.scrollWidth,body:document.body.scrollWidth,viewport:innerWidth,offenders}; + }); + expect(m.doc, `document horizontal overflow at ${width}px: ${JSON.stringify(m)}`).toBeLessThanOrEqual(width+1); + expect(m.body, `body horizontal overflow at ${width}px: ${JSON.stringify(m)}`).toBeLessThanOrEqual(width+1); + expect(m.offenders, `visible controls or content panels escape viewport at ${width}px`).toEqual([]); +} + +async function assertNamedControls(page:import("@playwright/test").Page){ + const missing=await page.evaluate(()=>{ + const elements=[...document.querySelectorAll('button,input:not([type="hidden"]),select,textarea,[role="button"],[role="slider"]')].filter(el=>{const style=getComputedStyle(el);return style.display!=="none"&&style.visibility!=="hidden"&&el.getClientRects().length>0}); + const name=(el:HTMLElement)=>{ + const aria=el.getAttribute("aria-label")?.trim(); + const labelled=el.getAttribute("aria-labelledby")?.split(/\\s+/).map(id=>document.getElementById(id)?.textContent?.trim()||"").join(" ").trim(); + const labels=el instanceof HTMLInputElement||el instanceof HTMLSelectElement||el instanceof HTMLTextAreaElement?[...(el.labels||[])].map(label=>label.textContent?.trim()||"").join(" ").trim():""; + const text=el.tagName==="BUTTON"||el.getAttribute("role")==="button"?el.textContent?.trim():""; + return aria||labelled||labels||el.getAttribute("title")?.trim()||text||""; + }; + return elements.filter(el=>!name(el)).map(el=>({tag:el.tagName,type:(el as HTMLInputElement).type||"",id:el.id,classes:el.className?.toString?.()||""})); + }); + expect(missing, "visible controls must expose an accessible name").toEqual([]); +} + +async function assertTextContrast(page:import("@playwright/test").Page,label:string){ + const violations=await page.evaluate(()=>{ + const parse=(value:string)=>{const numbers=value.match(/[\d.]+/g)?.map(Number)||[];return numbers.length>=3?{r:numbers[0],g:numbers[1],b:numbers[2],a:numbers.length>3?numbers[3]:1}:null}; + const linear=(v:number)=>{v/=255;return v<=.04045?v/12.92:((v+.055)/1.055)**2.4}; + const luminance=(v:{r:number;g:number;b:number})=>.2126*linear(v.r)+.7152*linear(v.g)+.0722*linear(v.b); + const ratio=(a:{r:number;g:number;b:number},b:{r:number;g:number;b:number})=>{const values=[luminance(a),luminance(b)].sort((x,y)=>y-x);return(values[0]+.05)/(values[1]+.05)}; + const nodes=[...document.querySelectorAll("body *")]; + const failures:string[]=[]; + for(const el of nodes){ + const own=getComputedStyle(el),rect=el.getBoundingClientRect(); + if(own.display==="none"||own.visibility==="hidden"||!rect.width||!rect.height||el.closest('[aria-hidden="true"]'))continue; + const text=Array.from(el.childNodes).filter(n=>n.nodeType===Node.TEXT_NODE).map(n=>n.textContent||"").join(" ").trim(); + if(!text)continue; + const foreground=parse(own.color);if(!foreground)continue; + let background={r:255,g:255,b:255}; + const chain:HTMLElement[]=[];let parent:HTMLElement|null=el;while(parent){chain.unshift(parent);parent=parent.parentElement;} + for(const ancestor of chain){const color=parse(getComputedStyle(ancestor).backgroundColor);if(color&&color.a>0){background={r:color.r*color.a+background.r*(1-color.a),g:color.g*color.a+background.g*(1-color.a),b:color.b*color.a+background.b*(1-color.a)};}} + const fg={r:foreground.r*foreground.a+background.r*(1-foreground.a),g:foreground.g*foreground.a+background.g*(1-foreground.a),b:foreground.b*foreground.a+background.b*(1-foreground.a)}; + const size=parseFloat(own.fontSize)||16,weight=parseInt(own.fontWeight)||400,minimum=size>=24||(size>=18.66&&weight>=700)?3:4.5; + const value=ratio(fg,background); + if(value+0.01{await mkdir("test-results/screenshots",{recursive:true});}); + +test("independent React workspace is contained at 13 widths, short landscape heights and light/dark",async({page})=>{ + await page.goto("/"); + await expect(page.getByRole("heading",{level:1,name:/Make it clear/i})).toBeVisible(); + await assertTextContrast(page,"workspace light"); + await page.setViewportSize({width:320,height:780}); + const mobileHeader=await page.evaluate(()=>({topbar:document.querySelector(".topbar")?.getBoundingClientRect().height,breadcrumb:document.querySelector(".breadcrumb")?.getBoundingClientRect().height,secure:document.querySelector(".secure-label")?.getBoundingClientRect().width})); + expect(mobileHeader.topbar, "mobile utility bar should remain compact").toBeLessThanOrEqual(64); + expect(mobileHeader.breadcrumb, "mobile breadcrumb should stay on one line").toBeLessThanOrEqual(22); + expect(mobileHeader.secure, "mobile privacy status should collapse to its icon").toBeLessThanOrEqual(18); + await expect(page.locator(".empty-state")).toHaveCSS("border-style","solid"); + await expect(page.locator('script[type="module"][src="/src/main.tsx"]')).toHaveCount(1); + await expect(page.locator("#app")).toHaveCount(0); + for(const v of viewports){ + await page.setViewportSize({width:v.width,height:v.height}); + await contained(page,v.width); + if([320,375,768,1120,1440].includes(v.width))await page.screenshot({path:`test-results/screenshots/${v.name}-light.png`,fullPage:true}); + } + await page.getByRole("button",{name:"Toggle appearance"}).click(); + await expect(page.locator("html")).toHaveAttribute("data-theme","dark"); + await assertTextContrast(page,"workspace dark"); + await expect(page.locator('meta[name="theme-color"]')).toHaveAttribute("content","#171d19"); + await expect(page.locator(".capture-panel")).toHaveCSS("background-color","rgb(41, 59, 46)"); + for(const v of viewports){ + await page.setViewportSize({width:v.width,height:v.height}); + await contained(page,v.width); + if([320,375,768,1120,1440].includes(v.width))await page.screenshot({path:`test-results/screenshots/${v.name}-dark.png`,fullPage:true}); + } + const landscape=[{width:320,height:480},{width:568,height:320},{width:844,height:390},{width:1024,height:600}]; + for(const v of landscape){await page.setViewportSize(v);await contained(page,v.width);} + await page.getByRole("button",{name:"Toggle appearance"}).click(); + await expect(page.locator('meta[name="theme-color"]')).toHaveAttribute("content","#f4f2ec"); + for(const v of landscape){await page.setViewportSize(v);await contained(page,v.width);} + await page.setViewportSize({width:320,height:640}); + await contained(page,320); +}); + +test("high-DPI mobile viewport keeps controls contained and reachable",async({browser})=>{ + const context=await browser.newContext({viewport:{width:320,height:640},deviceScaleFactor:2}); + const page=await context.newPage(); + await page.goto("/"); + await contained(page,320); + await page.getByRole("button",{name:"Open preferences"}).click(); + await expect(page.getByRole("dialog",{name:/Preferences & backups/i})).toBeVisible(); + await contained(page,320); + await page.getByRole("button",{name:/Close preferences/i}).click(); + await context.close(); +}); + +test("imported recording opens the full editor with preview, annotations, captions and sharing",async({page})=>{ + test.setTimeout(90000); + await page.goto("/"); + await page.locator('input[type="file"]').first().setInputFiles(path.resolve("legacy/public/sample.webm")); + await expect(page.getByRole("heading",{name:"sample"})).toBeVisible({timeout:15000}); + await expect(page.locator(".clip-thumb")).toBeVisible(); + await expect(page.locator(".clip-thumb img, .clip-thumb-fallback").first()).toBeVisible({timeout:10000}); + await assertNamedControls(page); + await expect(page.getByRole("button",{name:/Preview/i})).toBeVisible(); + await expect(page.getByRole("button",{name:/Edit/i})).toBeVisible(); + await page.setViewportSize({width:320,height:780}); + const clipActionHeights=await page.locator(".clip-actions .icon-button").evaluateAll(nodes=>nodes.map(node=>node.getBoundingClientRect().height)); + expect(clipActionHeights.length).toBeGreaterThan(0);expect(clipActionHeights.every(height=>height>=44)).toBe(true); + const clipTitleBlock=await page.locator(".clip-info > div:first-child").first().boundingBox();expect(clipTitleBlock?.width).toBeGreaterThan(180); + await page.setViewportSize({width:1280,height:900}); + await page.getByRole("button",{name:/Preview/i}).click(); + await expect(page.locator(".preview-workspace")).toBeVisible(); + await assertTextContrast(page,"preview light"); + await page.evaluate(()=>document.documentElement.setAttribute("data-theme","dark")); + await assertTextContrast(page,"preview dark"); + await page.evaluate(()=>document.documentElement.setAttribute("data-theme","light")); + await expect(page.locator(".preview-workspace video")).toBeVisible(); + await assertNamedControls(page); + const previewDialog=page.locator(".preview-workspace"),previewButtons=previewDialog.locator("button"); + await previewButtons.first().focus();await page.keyboard.press("Shift+Tab");await expect(previewButtons.last()).toBeFocused();await page.keyboard.press("Tab");await expect(previewButtons.first()).toBeFocused(); + await expect(previewButtons.first()).toHaveCSS("outline-color","rgb(49, 91, 69)"); + for(const width of [320,375,768,1120,1440]){await page.setViewportSize({width,height:900});await contained(page,width);if([320,1440].includes(width)){await page.screenshot({path:`test-results/screenshots/preview-${width}.png`,fullPage:true});await page.screenshot({path:`test-results/screenshots/preview-viewport-${width}.png`});}} + await page.getByRole("button",{name:/Open editor/i}).click(); + await expect(page.locator(".editor-workspace")).toBeVisible(); + await assertTextContrast(page,"editor light"); + await page.evaluate(()=>document.documentElement.setAttribute("data-theme","dark")); + await assertTextContrast(page,"editor dark"); + await page.evaluate(()=>document.documentElement.setAttribute("data-theme","light")); + await assertNamedControls(page); + await expect(page.locator(".editor-video-wrap video")).toBeVisible(); + await page.locator(".editor-title-button").click(); + await page.locator(".editor-title-wrap input").fill("A".repeat(100)); + await page.keyboard.press("Enter"); + await expect(page.locator(".editor-title-button")).toHaveText("A".repeat(100)); + await expect(page.locator(".editor-title-button")).toHaveAttribute("title","A".repeat(100)); + await expect(page.locator(".editor-title-button")).toHaveCSS("-webkit-line-clamp","2"); + const editorTitleWidth=await page.locator(".editor-title-wrap").evaluate(node=>node.getBoundingClientRect().width);expect(editorTitleWidth).toBeLessThanOrEqual(621); + await page.getByRole("button",{name:/Captions & context/i}).click(); + await expect(page.getByText(/OWNER-SUPPLIED CAPTIONS/i)).toBeVisible(); + const capsule={schema:"screennote.repro-capsule",version:1,createdAt:"2026-11-26T12:00:00.000Z",durationMs:1200,page:{url:"https://user:secret@example.com/checkout?session=private#payment",title:"Checkout",userAgent:"Playwright test browser",viewport:{width:390,height:844}},steps:[{atMs:250,action:"click",target:{tag:"button",role:"button",label:"Continue to payment"}},{atMs:900,action:"key",key:"Enter",target:{tag:"button",role:"button",label:"Pay"}}]}; + await page.locator('input[accept=".json,application/json"]').setInputFiles({name:"repro-capsule.json",mimeType:"application/json",buffer:Buffer.from(JSON.stringify(capsule))}); + await expect(page.getByRole("status")).toContainText(/Repro Capsule imported locally/i); + await expect(page.locator(".context-editor label").filter({hasText:"Page URL"}).locator("input")).toHaveValue("https://example.com/checkout"); + await expect(page.getByLabel("Reproduction steps")).toHaveValue(/Continue to payment/); + await expect(page.getByLabel("Reproduction steps")).toHaveValue(/Press Enter/); + await expect(page.getByLabel("Environment (optional)")).toHaveValue(/390×844 viewport/); + + await page.locator(".context-editor textarea").first().fill("WEBVTT\n\n00:00:00.100 --> 00:00:00.500\nOpening frame"); + await page.getByRole("button",{name:/Save context/i}).click(); + await expect(page.getByRole("status").filter({hasText:/Changes saved/i})).toBeVisible(); + const srtDownloadPromise=page.waitForEvent("download"); + await page.getByRole("button",{name:/Export SRT/i}).click(); + expect((await srtDownloadPromise).suggestedFilename()).toMatch(/\.srt$/); + await page.locator(".context-editor textarea").nth(1).fill("0:00 Introduction"); + const chapterDownloadPromise=page.waitForEvent("download"); + await page.getByRole("button",{name:/Export chapters JSON/i}).click(); + expect((await chapterDownloadPromise).suggestedFilename()).toMatch(/chapters\.json$/); + await page.getByRole("button",{name:/Edit & annotate/i}).click(); + await page.getByRole("button",{name:"Blur"}).click(); + const canvas=page.locator(".annotation-overlay"); + const rect=await canvas.boundingBox(); + if(rect) { await page.mouse.move(rect.x+rect.width*.2,rect.y+rect.height*.2);await page.mouse.down();await page.mouse.move(rect.x+rect.width*.45,rect.y+rect.height*.4,{steps:4});await page.mouse.up(); } + await expect(page.getByText(/1 marks on this video/i)).toBeVisible(); + await page.keyboard.press("Control+z"); + await expect(page.getByText(/0 marks on this video/i)).toBeVisible(); + if(rect) { await page.mouse.move(rect.x+rect.width*.2,rect.y+rect.height*.2);await page.mouse.down();await page.mouse.move(rect.x+rect.width*.45,rect.y+rect.height*.4,{steps:4});await page.mouse.up(); } + await expect(page.getByText(/1 marks on this video/i)).toBeVisible(); + await expect(page.getByRole("button",{name:"Jump to blur mark 1"})).toBeVisible(); + await page.getByRole("button",{name:"Delete mark 1"}).click(); + await expect(page.getByText(/0 marks on this video/i)).toBeVisible(); + if(rect) { await page.mouse.move(rect.x+rect.width*.2,rect.y+rect.height*.2);await page.mouse.down();await page.mouse.move(rect.x+rect.width*.45,rect.y+rect.height*.4,{steps:4});await page.mouse.up(); } + await expect(page.getByText(/1 marks on this video/i)).toBeVisible(); + const frameDownloadPromise=page.waitForEvent("download"); + await page.getByRole("button",{name:/Capture annotated frame/i}).click(); + expect((await frameDownloadPromise).suggestedFilename()).toMatch(/-frame-\d+ms\.png$/); + await expect(page.getByRole("status").filter({hasText:/Annotated frame saved as PNG/i})).toBeVisible(); + const editorVideo=page.locator(".editor-video-wrap video"); + const originalPlayhead=await editorVideo.evaluate(async node=>{const v=node as HTMLVideoElement;v.pause();const target=Math.min(.35,Math.max(.1,(v.duration||1)*.3));if(Math.abs(v.currentTime-target)>.02)await new Promise(resolve=>{const done=()=>resolve();v.addEventListener("seeked",done,{once:true});v.currentTime=target;window.setTimeout(done,1500)});return target;}); + await page.getByRole("button",{name:/Export annotated copy/i}).click(); + await expect(page.getByRole("status").filter({hasText:/Annotated copy saved/i})).toBeVisible({timeout:30000}); + const restored=await editorVideo.evaluate(node=>({time:(node as HTMLVideoElement).currentTime,paused:(node as HTMLVideoElement).paused}));expect(restored.paused).toBe(true);expect(Math.abs(restored.time-originalPlayhead)).toBeLessThan(.1); + await page.getByRole("button",{name:/Save all changes/i}).click(); + await expect(page.getByRole("status").filter({hasText:/Changes saved/i})).toBeVisible(); + const savedLongTitle=page.locator('.clip-card h3[title="'+ "A".repeat(100) +'"]'); + await expect(savedLongTitle).toBeVisible(); + await expect(savedLongTitle).toHaveCSS("-webkit-line-clamp","2"); + for(const width of [320,375,768,1120,1440]){await page.setViewportSize({width,height:900});await contained(page,width);if(width===320){const heights=await page.locator(".editor-toolbar button,.editor-tabs button").evaluateAll(nodes=>nodes.filter(node=>getComputedStyle(node).display!=="none").map(node=>node.getBoundingClientRect().height));expect(heights.length).toBeGreaterThan(0);expect(heights.every(height=>height>=44)).toBe(true);}if([320,1440].includes(width)){await page.screenshot({path:`test-results/screenshots/editor-${width}.png`,fullPage:true});await page.screenshot({path:`test-results/screenshots/editor-viewport-${width}.png`});}} + for(const v of [{width:568,height:320},{width:844,height:390},{width:1024,height:600}]){await page.setViewportSize(v);await contained(page,v.width);await expect(page.getByRole("button",{name:"Close editor"})).toBeVisible();} + await page.setViewportSize({width:1280,height:900}); + await page.getByRole("button",{name:/Share a reviewed copy/i}).click(); + await expect(page.getByRole("heading",{name:"Make a temporary link"})).toBeVisible(); + const modalLayer=await page.locator(".modal-backdrop").evaluate(el=>Number(getComputedStyle(el).zIndex)); + const editorLayer=await page.locator(".editor-workspace").evaluate(el=>Number(getComputedStyle(el).zIndex)); + expect(modalLayer).toBeGreaterThan(editorLayer); + await expect(page.getByText(/Only this shared copy is uploaded/i)).toBeVisible(); + await page.locator(".review-brief-fields > summary").click({force:true}); + await expect(page.locator(".review-brief-fields")).toHaveJSProperty("open",true); + await page.getByLabel("Review purpose").fill("Check the checkout flow"); + await page.getByLabel("Review focus areas").fill("Watch the payment confirmation step"); + await page.getByLabel("Expected outcome").fill("A successful payment shows a receipt"); + await page.getByLabel("Requested action").selectOption("approve"); + await expect(page.getByLabel("Requested action")).toHaveValue("approve"); + await page.getByRole("button",{name:"Close share settings"}).click(); + await page.getByRole("button",{name:"Close editor"}).click(); +}); + +test("recording setup exposes quality, microphone and camera placement controls",async({page})=>{ + await page.goto("/"); + await page.locator("summary").filter({hasText:/Recording quality, microphone and camera settings/i}).click(); + await expect(page.getByLabel("Recording quality")).toBeVisible(); + await page.getByLabel("Recording quality").selectOption("clear"); + await expect(page.getByLabel("Recording quality")).toHaveValue("clear"); + await expect(page.getByLabel("Microphone source")).toBeVisible(); + await expect(page.getByLabel("Camera bubble size")).toBeVisible(); + await page.getByRole("checkbox",{name:"Camera bubble"}).check(); + await page.getByLabel("Camera bubble position").selectOption("top-left"); + await expect(page.getByLabel("Camera bubble position")).toHaveValue("top-left"); + await page.getByLabel("Camera bubble position").selectOption("custom"); + await expect(page.getByLabel("Camera bubble horizontal position")).toBeVisible(); + await page.getByLabel("Camera bubble horizontal position").fill("0.3"); + await expect(page.getByLabel("Camera bubble horizontal position")).toHaveValue("0.3"); + const stage=page.getByRole("group",{name:"16 by 9 screen preview"}),handle=page.getByRole("slider",{name:"Move camera bubble"}); + await expect(handle).toBeVisible();const before=await handle.getAttribute("aria-valuetext"); + await handle.focus();await handle.press("ArrowRight");await expect(handle).not.toHaveAttribute("aria-valuetext",before!); + const stageBox=await stage.boundingBox(),handleBox=await handle.boundingBox();expect(stageBox&&handleBox).toBeTruthy(); + await page.mouse.move(handleBox!.x+handleBox!.width/2,handleBox!.y+handleBox!.height/2);await page.mouse.down(); + await page.mouse.move(stageBox!.x+stageBox!.width*.65+handleBox!.width/2,stageBox!.y+stageBox!.height*.45+handleBox!.height/2);await page.mouse.up(); + await expect(handle).toHaveAttribute("aria-valuetext",/Horizontal 6[0-9]%, vertical 4[0-9]%/); +}); +test("preferences export and restore a portable local library backup",async({page})=>{ + test.setTimeout(90000); + await page.goto("/"); + await page.locator('input[type="file"]').first().setInputFiles(path.resolve("legacy/public/sample.webm")); + await expect(page.getByRole("heading",{name:"sample"})).toBeVisible({timeout:15000}); + await page.getByRole("button",{name:"Open preferences"}).click(); + await assertNamedControls(page); + const preferences=page.getByRole("dialog",{name:/Preferences & backups/i}),preferenceControls=preferences.locator('button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),a[href],[tabindex="0"]'); + await preferenceControls.last().focus();await page.keyboard.press("Tab");await expect(preferenceControls.first()).toBeFocused(); + await expect(page.getByRole("dialog",{name:/Preferences & backups/i})).toBeVisible(); + const downloadPromise=page.waitForEvent("download"); + await page.getByRole("button",{name:/Back up my library/i}).click(); + const download=await downloadPromise; + expect(download.suggestedFilename()).toBe("screennote-library-backup.zip"); + const filePath=await download.path(); + if(!filePath)throw new Error("Backup download did not produce a file."); + await page.locator('input[type="file"]').last().setInputFiles(filePath); + await expect(page.getByRole("status").filter({hasText:/duplicate\(s\) were skipped/i})).toBeVisible(); + await page.getByRole("button",{name:/Close preferences/i}).click(); +}); +test("offline mode preserves local preview and editing while preventing publishing",async({page})=>{ + await page.goto("/"); + await page.locator('input[type="file"]').first().setInputFiles(path.resolve("legacy/public/sample.webm")); + await expect(page.getByRole("heading",{name:"sample"})).toBeVisible({timeout:15000}); + await page.context().setOffline(true); + await expect(page.getByText(/Offline mode/i)).toBeVisible(); + await page.getByRole("button",{name:/Preview/i}).click(); + await expect(page.locator(".preview-workspace video")).toBeVisible(); + await page.getByRole("button",{name:/Open editor/i}).click(); + await expect(page.locator(".editor-workspace")).toBeVisible(); + await page.getByRole("button",{name:"Close editor"}).click(); + await page.getByRole("button",{name:/Share sample/i}).click(); + await expect(page.getByRole("status").filter({hasText:/Sharing needs an internet connection/i})).toBeVisible(); + await page.context().setOffline(false); +}); +test("new frontend contains no legacy stylesheet or legacy app script requests",async({page})=>{ + const requested:string[]=[],fontRequests:string[]=[]; + page.on("request",request=>{const url=request.url();requested.push(new URL(url).pathname);if(/fonts\.googleapis\.com|fonts\.gstatic\.com/i.test(url))fontRequests.push(url)}); + await page.goto("/"); + await expect(page.getByRole("heading",{level:1})).toBeVisible(); + expect(requested).not.toContain("/style.css"); + expect(requested).not.toContain("/app.js"); + expect(requested).toContain("/src/main.tsx"); + expect(fontRequests,"the private workspace must not request third-party fonts").toEqual([]); +}); + + +test("temporary share viewer and privacy route use the independent responsive design",async({page})=>{ + const token="a".repeat(40); + await page.route(`**/api/share/${token}`,route=>route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({title:"A product walkthrough",mimeType:"video/webm",size:2048,duration:38,expiresAt:Math.floor(Date.now()/1000)+86400,passwordRequired:false})})); + await page.route(`**/api/share/${token}/comments`,route=>route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({comments:[{id:"visual-comment-1",parentId:null,viewerLabel:"Guest reviewer",body:"Please clarify this frame.",time:0,createdAt:100,resolved:0,deletedAt:null,isMine:true,anchorX:null,anchorY:null},{id:"visual-comment-deleted",parentId:null,viewerLabel:"Guest reviewer",body:"deleted private feedback must not leak",time:3,createdAt:102,resolved:0,deletedAt:110,isMine:true,anchorX:null,anchorY:null}]})})); + let savedReview:any=null; + await page.route("**/api/share/"+token+"/reviews",async route=>{ + if(route.request().method()==="POST"){savedReview=route.request().postDataJSON();await route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({saved:true})});return;} + const mine=savedReview?{reviewerLabel:savedReview.reviewerLabel||"Guest",decision:savedReview.decision,comment:savedReview.comment,time:savedReview.time,createdAt:100,updatedAt:101}:null; + await route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({reviews:mine?[mine]:[],myReview:mine})}); + }); + let selectedReaction=""; + await page.route("**/api/share/"+token+"/reactions",async route=>{ + if(route.request().method()==="POST")selectedReaction=route.request().postDataJSON().reaction||""; + const counts={like:selectedReaction==="like"?1:0,thanks:selectedReaction==="thanks"?1:0,idea:selectedReaction==="idea"?1:0}; + await route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({counts,myReaction:selectedReaction})}); + }); + const ownerKey="a".repeat(64); + await page.addInitScript(({token,ownerKey})=>localStorage.setItem("screennote-recovery-"+token,ownerKey),{token,ownerKey}); + let currentDetails:any={ + captions:[{start:1,end:2,text:"The first step"}], + annotations:[{kind:"rectangle",x:.1,y:.1,w:.2,h:.2,time:10,duration:4},{kind:"redact",x:.3,y:.3,w:.2,h:.2}], + chapters:[{time:1,title:"Introduction"}], + report:{steps:"Open the menu",expected:"Menu opens",actual:"Menu remains closed",url:"",environment:""}, + reviewBrief:{purpose:"Review the checkout flow",focus:"Inspect the payment confirmation",expectedOutcome:"A receipt is shown",requestedAction:"approve"}, + reviewStatus:"approved",reviewVersion:{number:2,publishedAt:1764158400000} + }; + await page.route("**/api/share/"+token+"/details",async route=>{ + if(route.request().method()==="PUT"){currentDetails=route.request().postDataJSON().details;await route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({saved:true})});return;} + await route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({details:currentDetails})}); + }); + await page.goto("/s/"+token+"?campaign=private#review"); + await expect(page.getByRole("heading",{name:"A product walkthrough"})).toBeVisible(); + await expect(page.locator(".share-version-badge")).toHaveText("Version 2"); + await assertTextContrast(page,"guest share light"); + await page.evaluate(()=>document.documentElement.setAttribute("data-theme","dark")); + await assertTextContrast(page,"guest share dark"); + await page.evaluate(()=>document.documentElement.setAttribute("data-theme","light")); + await assertNamedControls(page); + await expect(page.getByText("Approved",{exact:true})).toBeVisible(); + await expect(page.getByRole("region",{name:"Review brief"})).toContainText("Review the checkout flow"); + await expect(page.getByRole("region",{name:"Review brief"})).toContainText("A receipt is shown"); + const reviewPanel=page.getByRole("region",{name:"Review decision"}); + await expect(reviewPanel).toBeVisible(); + await reviewPanel.getByRole("button",{name:"Needs changes"}).click(); + await page.getByLabel("Reviewer display name").fill("Luke"); + await page.getByLabel("Review note").fill("Please adjust the payment state."); + await reviewPanel.getByRole("button",{name:"Save decision"}).click(); + await expect(reviewPanel.getByRole("status")).toContainText("saved"); + await expect(reviewPanel).toContainText("Please adjust the payment state."); + await page.getByRole("button",{name:/Thanks/i}).click(); + await expect(page.getByRole("button",{name:/Thanks/i})).toHaveAttribute("aria-pressed","true"); + await reviewPanel.getByRole("button",{name:"Reopen review"}).click(); + await expect(page.getByText("Needs feedback",{exact:true})).toBeVisible(); + await reviewPanel.getByRole("button",{name:"Mark changes requested"}).click(); + await expect(page.getByText("Changes requested",{exact:true})).toBeVisible(); + const packetDownloadPromise=page.waitForEvent("download"); + await reviewPanel.getByRole("button",{name:"Download review packet"}).click(); + const packetDownload=await packetDownloadPromise; + expect(packetDownload.suggestedFilename()).toBe("screennote-review-packet.md"); + const jsonDownloadPromise=page.waitForEvent("download"); + await page.getByRole("button",{name:"Export JSON"}).click(); + const jsonDownload=await jsonDownloadPromise; + expect(jsonDownload.suggestedFilename()).toBe("screennote-review-packet.json"); + const jsonPath=await jsonDownload.path();if(!jsonPath)throw new Error("Review packet JSON download did not produce a file."); + const packet=JSON.parse(await readFile(jsonPath,"utf8")); + expect(packet.schema).toBe("screennote.review-packet"); + expect(packet.shareUrl).toContain("/s/"+token); + expect(packet.shareUrl).not.toContain("campaign=private"); + expect(packet.shareUrl).not.toContain("#review"); + expect(packet.guestDecisions).toContainEqual(expect.objectContaining({decision:"changes-requested",comment:"Please adjust the payment state.",reviewerLabel:"Luke"})); + expect(packet.discussion).toContainEqual(expect.objectContaining({id:"visual-comment-deleted",text:"[Comment deleted]",deleted:true})); + expect(JSON.stringify(packet)).not.toContain("deleted private feedback must not leak"); + const markdownDownloadPromise=page.waitForEvent("download"); + await page.getByRole("button",{name:"Export Markdown"}).click(); + const markdownDownload=await markdownDownloadPromise; + expect(markdownDownload.suggestedFilename()).toBe("screennote-review-packet.md"); + const markdownPath=await markdownDownload.path();if(!markdownPath)throw new Error("Review packet Markdown download did not produce a file."); + const markdown=await readFile(markdownPath,"utf8"); + expect(markdown).toContain("Review packet — A product walkthrough"); + expect(markdown).toContain("Review the checkout flow"); + expect(markdown).toContain("Please adjust the payment state."); + expect(markdown).toContain("[Comment deleted]"); + expect(markdown).not.toContain("deleted private feedback must not leak"); + await expect(page.locator(".share-video-wrap")).toBeVisible(); + await expect(page.locator(".shared-annotation-overlay .shared-mark")).toHaveCount(1); // Only the untimed legacy mark is active at 0s. + await expect(page.locator(".share-discussion")).toBeVisible(); + await expect(page.locator(".discussion-title h2")).toHaveText("1 comment"); + await expect(page.locator(".share-comment-actions")).toHaveCSS("display","flex"); + await expect(page.locator(".share-comment-actions button")).toHaveCount(4); + await page.setViewportSize({width:320,height:900}); + const commentActionHeights=await page.locator(".share-comment-actions button").evaluateAll(nodes=>nodes.map(node=>node.getBoundingClientRect().height)); + expect(commentActionHeights.every(height=>height>=44),"comment actions must have mobile-sized touch targets").toBe(true); + const shareHeaderActionHeights=await page.locator(".share-header-actions .text-action").evaluateAll(nodes=>nodes.map(node=>node.getBoundingClientRect().height)); + expect(shareHeaderActionHeights.length).toBeGreaterThanOrEqual(2); + expect(shareHeaderActionHeights.every(height=>height>=44),"share header actions must have mobile-sized touch targets").toBe(true); + const timestampHeight=await page.locator(".share-comment-meta .timestamp-link").first().evaluate(node=>node.getBoundingClientRect().height); + expect(timestampHeight,"timestamp seek target must be comfortably tappable on mobile").toBeGreaterThanOrEqual(44); + await expect(page.locator(".share-comment-meta .timestamp-link").first()).toHaveCSS("background-color","rgba(0, 0, 0, 0)"); + await expect(page.locator(".share-comment-actions button").nth(0)).toHaveText("Reply"); + await expect(page.locator(".share-comment-actions button").nth(1)).toHaveText("Edit"); + await expect(page.locator(".share-comment-actions button").nth(2)).toHaveText("Delete"); + await expect(page.locator(".share-comment-actions button").nth(3)).toHaveText("Resolve"); + await expect(page.getByRole("button",{name:/Introduction/i})).toBeVisible(); + await expect(page.getByText(/SEARCH THE TRANSCRIPT/i)).toBeVisible(); + await expect(page.getByText(/Open the menu/i)).toBeVisible(); + for(const width of [320,375,768,1120,1440]){ + await page.setViewportSize({width,height:900}); + await contained(page,width); + if([320,1440].includes(width))await page.screenshot({path:`test-results/screenshots/share-${width}.png`,fullPage:true}); + } + await page.goto("/privacy"); + await expect(page.getByRole("heading",{name:"Your original stays with you."})).toBeVisible(); + await expect(page.locator(".privacy-document")).toBeVisible(); + for(const width of [320,1440]){await page.setViewportSize({width,height:900});await page.screenshot({path:`test-results/screenshots/privacy-${width}.png`,fullPage:true});} +}); + +test("password-protected share keeps the gate closed until correct unlock and remains responsive",async({page})=>{ + const token="d".repeat(40);let unlocked=false; + await page.route("**/api/share/"+token,route=>route.fulfill({status:unlocked?200:401,contentType:"application/json",body:JSON.stringify(unlocked?{title:"Protected walkthrough",mimeType:"video/webm",size:2048,duration:12,expiresAt:Math.floor(Date.now()/1000)+86400,passwordRequired:true}:{error:"Enter the sharing password."})})); + await page.route("**/api/share/"+token+"/access",async route=>{ + const password=route.request().postDataJSON()?.password; + if(password!=="correct-share-password"){await route.fulfill({status:401,contentType:"application/json",body:JSON.stringify({error:"That password isn't correct."})});return;} + unlocked=true;await route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({access:true})}); + }); + await page.route("**/api/share/"+token+"/comments",route=>route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({comments:[]})})); + await page.route("**/api/share/"+token+"/details",route=>route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({details:{}})})); + await page.route("**/api/share/"+token+"/reactions",route=>route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({counts:{like:0,thanks:0,idea:0},myReaction:""})})); + await page.route("**/api/share/"+token+"/reviews",route=>route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({reviews:[],myReview:null})})); + await page.route("**/api/share/"+token+"/media",route=>route.fulfill({status:200,headers:{"content-type":"video/webm"},body:Buffer.from([0x1a,0x45,0xdf,0xa3])})); + await page.goto("/s/"+token); + await expect(page.getByRole("heading",{name:"This ScreenNote is private."})).toBeVisible(); + await assertNamedControls(page); + for(const width of [320,375,768,1440]){await page.setViewportSize({width,height:900});await contained(page,width);} + for(const v of [{width:320,height:480},{width:568,height:320},{width:844,height:390}]){await page.setViewportSize(v);await contained(page,v.width);await expect(page.getByLabel("Password")).toBeVisible();} + await page.getByLabel("Password").fill("wrong-password"); + await page.getByRole("button",{name:"Unlock video"}).click(); + await expect(page.locator(".share-error")).toContainText("That password isn't correct."); + await expect(page.getByRole("heading",{name:"This ScreenNote is private."})).toBeVisible(); + await page.getByLabel("Password").fill("correct-share-password"); + await page.getByRole("button",{name:"Unlock video"}).click(); + await expect(page.getByRole("heading",{name:"Protected walkthrough"})).toBeVisible(); + await expect(page.locator(".password-gate")).toHaveCount(0); + for(const width of [320,375,768,1440]){await page.setViewportSize({width,height:900});await contained(page,width);} + for(const v of [{width:320,height:480},{width:568,height:320},{width:844,height:390}]){await page.setViewportSize(v);await contained(page,v.width);await expect(page.getByRole("heading",{name:"Protected walkthrough"})).toBeVisible();} +}); + +test("publishing new versions retains links only by consent and stop-sharing revokes all versions",async({page})=>{ + test.setTimeout(90000); + let reservations=0,publishes=0;const tokens=["v1"+"a".repeat(38),"v2"+"b".repeat(38),"v3"+"c".repeat(38)];const revoked:string[]=[]; + await page.route("**/api/session",route=>route.fulfill({status:200,contentType:"application/json",body:"{}"})); + await page.route("**/api/recordings",async route=>{ + if(route.request().method()!=="POST"){await route.continue();return;} + reservations++;await route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({id:"reservation-"+reservations,chunkBytes:2097152})}); + }); + await page.route("**/api/recordings/*/upload-state",route=>route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({status:"ready",parts:[],chunkBytes:2097152})})); + await page.route("**/api/recordings/*/publish",route=>{ + const index=publishes++;const token=tokens[index]; + return route.fulfill({status:200,contentType:"application/json",body:JSON.stringify({id:"share-id-"+(index+1),token,url:"/s/"+token,expiresAt:Math.floor(Date.now()/1000)+86400,passwordProtected:false})}); + }); + await page.route("**/api/share/*/details",route=>route.request().method()==="PUT"?route.fulfill({status:200,contentType:"application/json",body:"{}"}):route.continue()); + await page.route("**/api/share/*/manage",async route=>{ + if(route.request().method()!=="DELETE"){await route.continue();return;} + const token=new URL(route.request().url()).pathname.split("/")[3];revoked.push(token); + await route.fulfill({status:200,contentType:"application/json",body:"{}"}); + }); + await page.goto("/"); + await page.locator('input[type="file"]').first().setInputFiles(path.resolve("legacy/public/sample.webm")); + await expect(page.getByRole("heading",{name:"sample"})).toBeVisible({timeout:15000}); + await page.getByRole("button",{name:/Preview/i}).click(); + await page.getByRole("button",{name:"Share temporarily"}).click(); + await assertTextContrast(page,"publish first version dialog light"); + await page.getByRole("button",{name:"Publish temporary link"}).click(); + await expect(page.getByText("Version 1 link ready")).toBeVisible({timeout:20000}); + await page.getByRole("button",{name:"Dismiss"}).click(); + await page.getByRole("button",{name:"Publish new version"}).click(); + await assertTextContrast(page,"publish version dialog light"); + await page.evaluate(()=>document.documentElement.setAttribute("data-theme","dark")); + await assertTextContrast(page,"publish version dialog dark"); + await page.evaluate(()=>document.documentElement.setAttribute("data-theme","light")); + await page.getByRole("checkbox",{name:/Keep previous share as a version/i}).check(); + await page.getByRole("button",{name:"Publish new version"}).last().click(); + await expect(page.getByText("Version 2 link ready")).toBeVisible({timeout:20000}); + await page.getByRole("button",{name:"Dismiss"}).click(); + const history=page.getByRole("region",{name:"Previous share versions"}); + await expect(history).toContainText("Version 1"); + await assertTextContrast(page,"version history light"); + await page.evaluate(()=>document.documentElement.setAttribute("data-theme","dark")); + await assertTextContrast(page,"version history dark"); + await page.evaluate(()=>document.documentElement.setAttribute("data-theme","light")); + await expect(history.getByRole("link",{name:/Open/i})).toHaveAttribute("href","/s/"+tokens[0]); + expect(revoked).not.toContain(tokens[0]); + page.once("dialog",dialog=>dialog.accept()); + await page.getByRole("button",{name:"Revoke share version 1"}).click(); + await expect(history).toHaveCount(0); + expect(revoked).toContain(tokens[0]); + await page.getByRole("button",{name:"Publish new version"}).click(); + await page.getByRole("checkbox",{name:/Keep previous share as a version/i}).check(); + await page.getByRole("button",{name:"Publish new version"}).last().click(); + await expect(page.getByText("Version 3 link ready")).toBeVisible({timeout:20000}); + await page.getByRole("button",{name:"Dismiss"}).click(); + await expect(page.getByRole("region",{name:"Previous share versions"})).toContainText("Version 2"); + await assertTextContrast(page,"version history after republish"); + await page.getByRole("button",{name:"Close preview"}).click(); + await page.getByRole("button",{name:"Stop sharing sample"}).click(); + await expect(page.getByRole("status").filter({hasText:/All shared versions/i})).toBeVisible(); + expect(new Set(revoked)).toEqual(new Set(tokens)); + await expect(page.getByRole("heading",{name:"sample"})).toBeVisible(); +}); + +test("light and dark text tokens meet WCAG AA contrast",async({page})=>{ + await page.goto("/"); + const readRatios=()=>page.evaluate(()=>{ + const style=getComputedStyle(document.documentElement); + const hex=(name:string)=>style.getPropertyValue(name).trim().replace("#",""); + const rgb=(value:string)=>{const h=value.length===3?value.split("").map(x=>x+x).join(""):value;return [0,2,4].map(i=>parseInt(h.slice(i,i+2),16)/255)}; + const lum=(value:string)=>rgb(value).map(x=>x<=.04045?x/12.92:Math.pow((x+.055)/1.055,2.4)).reduce((sum,x,i)=>sum+x*[.2126,.7152,.0722][i],0); + const ratio=(a:string,b:string)=>{const values=[lum(a),lum(b)].sort((x,y)=>y-x);return (values[0]+.05)/(values[1]+.05)}; + const ink=hex("--ink"),muted=hex("--muted"),rust=hex("--rust"),paper=hex("--paper"),panel=hex("--panel"),acid=hex("--acid"),acidInk=hex("--acid-ink"); + return [ratio(ink,paper),ratio(muted,paper),ratio(muted,panel),ratio(rust,paper),ratio(rust,panel),ratio(acidInk,acid)]; + }); + for(const theme of ["light","dark"]){ + if(theme==="dark")await page.getByRole("button",{name:"Toggle appearance"}).click(); + const ratios=await readRatios(); + for(const value of ratios)expect(value,theme+" contrast ratio").toBeGreaterThanOrEqual(4.5); + } +}); + + +test("transient share and alert surfaces keep readable contrast in both themes",async({page})=>{ + await page.goto("/"); + await page.evaluate(()=>document.body.insertAdjacentHTML("beforeend",` + + + Changes requested +
+
Saved
+
Offline
+
Capture unavailable
+ + 0:45 + `)); + const contrast=async(selector:string)=>page.locator(selector).evaluate(el=>{ + const rgb=(value:string)=>value.match(/[\d.]+/g)!.slice(0,3).map(Number).map(v=>{v/=255;return v<=.04045?v/12.92:((v+.055)/1.055)**2.4}); + const lum=(v:number[])=>.2126*v[0]+.7152*v[1]+.0722*v[2]; + const style=getComputedStyle(el),fg=lum(rgb(style.color));let bgColor=style.backgroundColor; + if(bgColor==="transparent"||bgColor==="rgba(0, 0, 0, 0)"){let parent=el.parentElement;while(parent){const candidate=getComputedStyle(parent).backgroundColor;if(candidate!=="transparent"&&candidate!=="rgba(0, 0, 0, 0)"){bgColor=candidate;break;}parent=parent.parentElement;}} + const bg=lum(rgb(bgColor));return (Math.max(fg,bg)+.05)/(Math.min(fg,bg)+.05); + }); + for(const theme of ["light","dark"]){ + if(theme==="dark")await page.getByRole("button",{name:"Toggle appearance"}).click(); + for(const selector of [".share-link-toast",".share-link-toast span",".share-link-toast button",".share-error",".shared-review-status.changes-requested",".review-decision-options button[aria-pressed=true]",".editor-status",".offline-banner",".capture-unavailable",".button.danger",".duration",".capture-panel",".capture-panel .button.primary",".capture-panel .capture-advanced summary",".toggle-option",".button.danger",".duration"]){ + expect(await contrast(selector),selector+" contrast in "+theme).toBeGreaterThanOrEqual(4.5); + } + } +}); diff --git a/rebuild/extension/README.md b/rebuild/extension/README.md new file mode 100644 index 0000000..7637efd --- /dev/null +++ b/rebuild/extension/README.md @@ -0,0 +1,32 @@ +# ScreenNote Repro Capsule (Chrome / Edge) + +A small Manifest V3 extension that captures an explicit, local interaction outline for a ScreenNote bug report. + +## Install + +1. Open `chrome://extensions` in Chrome or `edge://extensions` in Edge. +2. Enable **Developer mode**. +3. Choose **Load unpacked** and select this `rebuild/extension` directory. +4. Open the web page you want to reproduce. +5. Click the extension, choose **Start capture**, perform the steps, then reopen the extension and choose **Stop & review**. +6. Review/edit the JSON, remove anything sensitive, and download it. +7. In ScreenNote, open a recording → **Edit** → **Captions & context** → **Bug report** → **Import Repro Capsule**. Review the imported URL, steps and environment, then save context only when you choose. + +## Exactly what it captures + +- The page URL with username/password, query string and fragment removed. +- Page title, browser user-agent string and viewport dimensions. +- Up to 500 click outlines (interactive target tag/role and a short accessible/button label). +- Navigation keys only: Enter, Escape, Tab, arrows and Space. No typed characters or field values. +- Relative timestamps and capture duration. + +## Privacy and limitations + +- Capture starts only after the user clicks **Start capture** and stops only after **Stop & review**. +- The extension has no host permissions, background listeners, analytics or network code. It uses the temporary `activeTab` permission and injected listeners in the selected tab. +- It does not capture screenshots, page body text, cookies, form values, clipboard, network requests, console logs or credentials. +- A clicked button/link label or the URL path can still contain personal information. Review and redact the JSON before export; ScreenNote removes URL credentials/query/hash again on import. +- The JSON is not uploaded by the extension. Importing into ScreenNote fills the local bug-report editor; publishing the share sends the saved context to the temporary share and makes it visible to link viewers. +- This is a user-approved interaction outline, not a complete automated reproduction or telemetry trace. It cannot observe server state or reproduce every browser/device condition. + +No dependencies or paid services are required. diff --git a/rebuild/extension/capture.js b/rebuild/extension/capture.js new file mode 100644 index 0000000..320df42 --- /dev/null +++ b/rebuild/extension/capture.js @@ -0,0 +1,20 @@ +(()=> { + if(window.__screennoteReproCapsule)return; + let active=false,startedAt=0,packet=null; + const allowedKeys=new Set(["Enter","Escape","Tab","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"," "]); + function safePageUrl(){try{const u=new URL(location.href);u.username="";u.password="";u.search="";u.hash="";return u.href}catch{return location.origin}} + function targetInfo(node){ + const el=node instanceof Element?node:null;if(!el)return{tag:"UNKNOWN"}; + const tag=el.tagName.toUpperCase(),role=(el.getAttribute("role")||"").slice(0,64); + const isControl=/^(BUTTON|A)$/.test(tag)||role==="button"||role==="link"; + const label=(el.getAttribute("aria-label")||el.getAttribute("title")||(isControl?el.textContent:"")||"").replace(/\\s+/g," ").trim().slice(0,80); + return{tag,role,label}; + } + function ignoreTarget(node){const el=node instanceof Element?node:null;return !el||Boolean(el.closest("input,textarea,select,[contenteditable=true],[contenteditable='']"))} + function push(step){if(packet&&packet.steps.length<500)packet.steps.push(step)} + function click(event){if(!active||ignoreTarget(event.target))return;const el=event.target instanceof Element?event.target.closest("button,a,[role=button],[role=link],input,select,textarea,[tabindex]")||event.target:event.target;push({atMs:Math.max(0,Math.round(performance.now()-startedAt)),action:"click",target:targetInfo(el)})} + function key(event){if(!active||event.repeat||ignoreTarget(event.target))return;const key=event.key===" "?"Space":event.key;if(!allowedKeys.has(event.key))return;push({atMs:Math.max(0,Math.round(performance.now()-startedAt)),action:"key",key,target:targetInfo(event.target)})} + function start(){if(active)return{started:false};packet={schema:"screennote.repro-capsule",version:1,createdAt:new Date().toISOString(),durationMs:0,page:{url:safePageUrl(),title:(document.title||"").slice(0,200),userAgent:navigator.userAgent.slice(0,300),viewport:{width:innerWidth,height:innerHeight}},steps:[]};startedAt=performance.now();active=true;document.addEventListener("click",click,true);document.addEventListener("keydown",key,true);return{started:true}} + function stop(){if(!packet)return null;if(active){active=false;document.removeEventListener("click",click,true);document.removeEventListener("keydown",key,true);packet.durationMs=Math.max(0,Math.round(performance.now()-startedAt))}return packet} + window.__screennoteReproCapsule={start,stop,isActive:()=>active}; +})(); \ No newline at end of file diff --git a/rebuild/extension/manifest.json b/rebuild/extension/manifest.json new file mode 100644 index 0000000..c0b2212 --- /dev/null +++ b/rebuild/extension/manifest.json @@ -0,0 +1,11 @@ +{ + "manifest_version": 3, + "name": "ScreenNote Repro Capsule", + "version": "1.0.0", + "description": "Capture a user-approved interaction outline locally and export a reviewable ScreenNote Repro Capsule.", + "permissions": ["activeTab", "scripting"], + "action": { + "default_title": "ScreenNote Repro Capsule", + "default_popup": "popup.html" + } +} \ No newline at end of file diff --git a/rebuild/extension/popup.css b/rebuild/extension/popup.css new file mode 100644 index 0000000..c03322a --- /dev/null +++ b/rebuild/extension/popup.css @@ -0,0 +1 @@ +:root{color-scheme:light;font:14px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#f4f2ec;color:#202a24}*{box-sizing:border-box}body{margin:0;padding:18px;width:360px;max-width:100vw}header{display:flex;align-items:center;gap:12px;padding-bottom:14px;border-bottom:1px solid #d9ddd4}.mark{width:38px;height:38px;display:grid;place-items:center;background:#315b45;color:#fffdf8;font-size:12px;font-weight:800;letter-spacing:-.05em;border-radius:7px}.eyebrow{margin:0;color:#626c63;font:600 10px/1.4 ui-monospace,monospace;letter-spacing:.12em}h1{margin:2px 0 0;font-size:21px;line-height:1.2;letter-spacing:-.04em}.intro{color:#626c63;line-height:1.6;margin:14px 0}.privacy{padding:12px;border:1px solid #d9ddd4;background:#fbfaf6;border-radius:7px}.privacy strong{font-size:12px}.privacy p{margin:5px 0 0;color:#626c63;font-size:12px;line-height:1.55}#status{min-height:42px;margin:14px 0;color:#315b45;font-size:12px}button{width:100%;min-height:44px;border-radius:7px;border:1px solid #315b45;padding:10px 14px;font:650 13px system-ui,sans-serif;cursor:pointer;margin:5px 0}button:focus-visible,textarea:focus-visible{outline:3px solid #315b45;outline-offset:3px}.primary{background:#315b45;color:#fffdf8}.secondary{background:transparent;color:#202a24;border-color:#bcc5b9}section{margin-top:14px}label{display:block;font-size:12px;font-weight:650;margin-bottom:7px}textarea{width:100%;min-width:0;border:1px solid #bcc5b9;border-radius:7px;background:#fffefa;color:#202a24;padding:10px;font:11px/1.5 ui-monospace,monospace;resize:vertical;overflow-wrap:anywhere}footer{border-top:1px solid #d9ddd4;margin-top:14px;padding-top:10px;color:#626c63;font:10px/1.5 ui-monospace,monospace} [hidden]{display:none!important} \ No newline at end of file diff --git a/rebuild/extension/popup.html b/rebuild/extension/popup.html new file mode 100644 index 0000000..5f37e61 --- /dev/null +++ b/rebuild/extension/popup.html @@ -0,0 +1,25 @@ + + + + + + ScreenNote Repro Capsule + + + +

SCREENNOTE TOOL

Repro Capsule

+

Capture a short interaction outline for a bug report. It stays in this tab until you review and export it.

+
Local capture only

No upload, keystroke values, form contents, cookies, network logs or page body. Click labels and navigation keys may be recorded. Review the page path and every step before export.

+

Ready. Start only when you intend to capture this tab.

+ + + +
Max 500 steps · No background capture · You choose what to export
+ + + \ No newline at end of file diff --git a/rebuild/extension/popup.js b/rebuild/extension/popup.js new file mode 100644 index 0000000..f5f0a70 --- /dev/null +++ b/rebuild/extension/popup.js @@ -0,0 +1,11 @@ +const $=id=>document.getElementById(id); +const status=$("status"),start=$("start"),stop=$("stop"),review=$("review"),packetField=$("packet"),download=$("download"),clear=$("clear"); +let tabId=null; +async function activeTab(){const tabs=await chrome.tabs.query({active:true,currentWindow:true});if(!tabs[0]?.id)throw new Error("Open a normal web page first.");tabId=tabs[0].id;return tabs[0];} +async function activeCapture(){if(tabId===null)return false;try{const r=await chrome.scripting.executeScript({target:{tabId},func:()=>Boolean(window.__screennoteReproCapsule?.isActive?.())});return Boolean(r[0]?.result)}catch{return false}} +async function sync(){try{await activeTab();const active=await activeCapture();start.hidden=active;stop.hidden=!active;status.textContent=active?"Capture is active in this tab. Reopen this popup to stop and review.":"Ready. Start only when you intend to capture this tab."}catch(e){start.disabled=true;status.textContent=e.message}} +start.addEventListener("click",async()=>{try{await activeTab();await chrome.scripting.executeScript({target:{tabId},files:["capture.js"]});const r=await chrome.scripting.executeScript({target:{tabId},func:()=>window.__screennoteReproCapsule?.start?.()});if(!r[0]?.result?.started)throw new Error("Could not start capture in this tab.");start.hidden=true;stop.hidden=false;status.textContent="Capturing clicks and navigation keys locally. Reopen this popup and choose Stop & review when finished."}catch(e){status.textContent=e.message||"Capture could not start. This page may not allow extension injection."}}); +stop.addEventListener("click",async()=>{try{await activeTab();const r=await chrome.scripting.executeScript({target:{tabId},func:()=>window.__screennoteReproCapsule?.stop?.()});const data=r[0]?.result;if(!data)throw new Error("No capture was found in this tab.");packetField.value=JSON.stringify(data,null,2);review.hidden=false;start.hidden=true;stop.hidden=true;status.textContent="Stopped. Review and redact the capsule JSON before downloading. Nothing has been uploaded."}catch(e){status.textContent=e.message||"Could not stop capture in this tab."}}); +download.addEventListener("click",()=>{try{const parsed=JSON.parse(packetField.value);if(parsed.schema!=="screennote.repro-capsule"||parsed.version!==1)throw new Error("Unsupported capsule schema.");const blob=new Blob([JSON.stringify(parsed,null,2)],{type:"application/json"});const url=URL.createObjectURL(blob);const a=document.createElement("a");a.href=url;a.download="screennote-repro-capsule.json";a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);status.textContent="Capsule exported. Import it in ScreenNote's Bug Report panel and review it again before sharing."}catch(e){status.textContent=e.message||"Fix the JSON before export."}}); +clear.addEventListener("click",()=>{packetField.value="";review.hidden=true;status.textContent="Capsule discarded from this popup. No file was exported."}); +void sync(); \ No newline at end of file diff --git a/rebuild/index.html b/rebuild/index.html new file mode 100644 index 0000000..4c19366 --- /dev/null +++ b/rebuild/index.html @@ -0,0 +1,16 @@ + + + + + + + + + + ScreenNote — Make it clear. + + +

Opening your workspace…

+ + + diff --git a/rebuild/legacy/lib/access.js b/rebuild/legacy/lib/access.js new file mode 100644 index 0000000..bbc989d --- /dev/null +++ b/rebuild/legacy/lib/access.js @@ -0,0 +1,5 @@ +import {scrypt,randomBytes,timingSafeEqual} from 'node:crypto'; +import {promisify} from 'node:util'; +const derive=promisify(scrypt); +export async function passwordRecord(password){if(password===undefined||password==='')return{};if(typeof password!=='string'||password.length<8||password.length>128)throw Error('Use a sharing password of 8–128 characters.');const passwordSalt=randomBytes(16).toString('hex'),passwordHash=(await derive(password,passwordSalt,32)).toString('hex');return{passwordSalt,passwordHash}} +export async function checkPassword(c,password){if(!c.passwordHash)return true;if(typeof password!=='string'||password.length>128)return false;const computed=await derive(password,c.passwordSalt,32);return timingSafeEqual(computed,Buffer.from(c.passwordHash,'hex'))} diff --git a/rebuild/legacy/lib/capacity.js b/rebuild/legacy/lib/capacity.js new file mode 100644 index 0000000..f0ff7ad --- /dev/null +++ b/rebuild/legacy/lib/capacity.js @@ -0,0 +1,35 @@ +import {MAX_BYTES, MAX_SHARED, STORAGE_BUDGET_BYTES} from './rules.js'; +import {RETENTION_GRACE} from './retention.js'; + +// Two copies may coexist while chunks are assembled. Release that extra +// allocation only after part cleanup succeeds. All updates use the same CAS. +export const defaultCapacityLimits = {maxBytes: STORAGE_BUDGET_BYTES, maxClips: MAX_SHARED}; +export function capacityBytes(capacity) { + return (capacity?.ids || []).reduce((sum,id) => sum + (capacity.allocations?.[id] ?? 2 * MAX_BYTES), 0); +} +export function hasCapacity(capacity, bytes, limits = defaultCapacityLimits) { + return (capacity?.ids?.length || 0) < limits.maxClips && capacityBytes(capacity) + bytes <= limits.maxBytes; +} +export function reserveCapacity(capacity, id, size, limits = defaultCapacityLimits) { + if (capacity.ids.includes(id)) throw Object.assign(Error('This reservation is being prepared. Try publishing again.'), {status:409}); + if (!hasCapacity(capacity, 2 * size, limits)) throw Object.assign(Error('Shared storage is full. Download locally, delete an upload you own, or try again after expired uploads are reclaimed.'), {status:429}); + capacity.ids.push(id); + (capacity.allocations ||= {})[id] = 2 * size; + (capacity.deadlines ||= {})[id] = Date.now() + 600000 + RETENTION_GRACE; +} +export function releaseCapacity(capacity, id) { + capacity.ids = capacity.ids.filter(value => value !== id); + if (capacity.allocations) delete capacity.allocations[id]; + if (capacity.deadlines) delete capacity.deadlines[id]; + if (capacity.orphanSince) delete capacity.orphanSince[id]; +} +export function finalizeCapacity(capacity, id, size, expiresAt) { + if (capacity.ids.includes(id)) { + (capacity.allocations ||= {})[id] = size; + (capacity.deadlines ||= {})[id] = expiresAt + RETENTION_GRACE; + } +} +export function capacitySummary(capacity, limits = defaultCapacityLimits) { + const reservedBytes=capacityBytes(capacity); + return {maxStorageBytes:limits.maxBytes,reservedBytes,availableBytes:Math.max(0,limits.maxBytes-reservedBytes),reservedRecordings:capacity?.ids?.length||0}; +} diff --git a/rebuild/legacy/lib/comment-actions.js b/rebuild/legacy/lib/comment-actions.js new file mode 100644 index 0000000..11394dc --- /dev/null +++ b/rebuild/legacy/lib/comment-actions.js @@ -0,0 +1,42 @@ +import {createHash,timingSafeEqual} from 'node:crypto'; +import {validId,commentInput,text,publicClip} from './rules.js'; +const fail=(message,status=400)=>Object.assign(Error(message),{status}); +const digest=v=>createHash('sha256').update(v).digest('hex'); +function matches(value,expected){if(typeof value!=='string'||value.length<40||value.length>100||typeof expected!=='string')return false;const a=Buffer.from(digest(value)),b=Buffer.from(expected);return a.length===b.length&&timingSafeEqual(a,b)} +function rootOf(comments,c){const seen=new Set();while(c.parentId){if(seen.has(c.id))throw fail('This thread is unavailable.',409);seen.add(c.id);const p=comments.find(x=>x.id===c.parentId);if(!p)break;c=p}return c} +export const commentOperations=['comment','edit-comment','delete-comment','resolve-thread']; +// Called inside the recording's compare-and-swap transaction. No author capability is public. +export function applyCommentAction(d,op,body,now=Date.now()){ + if(d.status!=='published'||d.expiresAtx.id===eventId))return publicClip(d); + if(d.comments.length>=100)throw fail('This clip has reached 100 comments and replies.'); + if(comment.parentId){const parent=d.comments.find(x=>x.id===comment.parentId);if(!parent||parent.deleted)throw fail('This reply is no longer available. Refresh the conversation.',409);comment.time=parent.time;rootOf(d.comments,parent).resolved=false} + d.comments.push({...comment,id:eventId,createdAt:now,creator,...(body.authorKey?{authorHash:digest(body.authorKey)}:{})}); + }else{ + if(!validId(body.commentId))throw fail('Choose an existing comment.'); + const c=d.comments.find(x=>x.id===body.commentId);if(!c)throw fail('Comment not found.',404); + const author=matches(body.authorKey,c.authorHash); + if(op==='resolve-thread'){ + const root=rootOf(d.comments,c); + if(!creator&&!matches(body.authorKey,root.authorHash))throw fail('Only the thread author or video creator can resolve this thread.',403); + if(typeof body.resolved!=='boolean')throw fail('Choose whether this thread is resolved.'); + root.resolved=body.resolved; + }else{ + if(!author&&!(creator&&op==='delete-comment'))throw fail('This browser cannot change this comment.',403); + if(op==='delete-comment'){c.deleted=true;c.text='';c.name='Deleted comment';c.editedAt=now} + else if(op==='edit-comment'){ + if(c.deleted)throw fail('This comment was deleted.',409); + if(body.expectedVersion!==(c.editedAt||c.createdAt))throw fail('This comment changed. Refresh before editing again.',409); + c.text=text(body.text,500,true);c.editedAt=Math.max(now,(c.editedAt||c.createdAt)+1); + } + } + } + d.discussionRevision=(d.discussionRevision||0)+1; + return publicClip(d); +} diff --git a/rebuild/legacy/lib/discussion.js b/rebuild/legacy/lib/discussion.js new file mode 100644 index 0000000..cc7a02f --- /dev/null +++ b/rebuild/legacy/lib/discussion.js @@ -0,0 +1,20 @@ +// Shared presentation rules: legacy flat comments remain independent threads. +export function discussionThreads(comments=[]){ + const byId=new Map(comments.map(c=>[c.id,c])),groups=new Map(); + for(const comment of comments){ + let root=comment;const seen=new Set([root.id]); + while(root.parentId&&byId.has(root.parentId)&&!seen.has(root.parentId)){root=byId.get(root.parentId);seen.add(root.id)} + if(!groups.has(root.id))groups.set(root.id,{root,items:[]}); + groups.get(root.id).items.push(comment); + } + return [...groups.values()].map(t=>({...t,items:t.items.sort((a,b)=>a.createdAt-b.createdAt)})).sort((a,b)=>(a.root.time-b.root.time)||(a.root.createdAt-b.root.createdAt)); +} +export function bubbleThreads(comments,time,window=5){return discussionThreads(comments).filter(t=>!t.root.deleted&&!t.root.resolved&&time>=t.root.time&&time!t.root.deleted)){ + const ratio=Math.max(0,Math.min(1,(t.root.time-start)/Math.max(.25,end-start))),bin=Math.min(bins-1,Math.floor(ratio*bins)); + if(!groups.has(bin))groups.set(bin,{ratio:(bin+.5)/bins,threads:[]});groups.get(bin).threads.push(t); + }return [...groups.values()]; +} +// A slower reaction/refresh response must not overwrite a newer conversation. +export function mergeDiscussion(current,next){return {...current,...next,...((next.discussionRevision||0)<(current.discussionRevision||0)?{comments:current.comments,discussionRevision:current.discussionRevision}:{})}} diff --git a/rebuild/legacy/lib/draft-writer.js b/rebuild/legacy/lib/draft-writer.js new file mode 100644 index 0000000..ba945ce --- /dev/null +++ b/rebuild/legacy/lib/draft-writer.js @@ -0,0 +1,14 @@ +// Recovery is best effort; losing it must never take away in-memory recording controls. +export function createDraftWriter(save, warn) { + let chain=Promise.resolve(), failed=false; + return { + save(snapshot) { + if(failed)return chain; + chain=chain.then(()=>{if(!failed)return save(snapshot)}).catch(()=>{ + if(!failed){failed=true;warn()} + }); + return chain; + }, + flush(){return chain} + }; +} diff --git a/rebuild/legacy/lib/enrichment.js b/rebuild/legacy/lib/enrichment.js new file mode 100644 index 0000000..780297b --- /dev/null +++ b/rebuild/legacy/lib/enrichment.js @@ -0,0 +1,10 @@ +// Bounded, portable metadata. Caption text is always treated as plain text. +const clean=(v,max)=>{if(typeof v!=='string'||v.length>max)throw Error('Text is too long or has an invalid format.');return v.trim()}; +export function timestamp(v){const p=String(v).trim().replace(',','.').split(':');if(p.length<2||p.length>3||p.some(n=>!/^\d+(\.\d+)?$/.test(n)))throw Error('Use a timestamp such as 0:30 or 00:00:30.000.');if(Number(p.at(-1))>=60||p.length===3&&Number(p[1])>=60)throw Error('Invalid timestamp.');return p.reduce((n,s)=>n*60+Number(s),0)} +export function parseCaptions(raw,duration){if(typeof raw!=='string'||raw.length>20000)throw Error('Use captions smaller than 20 KB.');const blocks=raw.replace(/^\uFEFF/,'').replace(/\r/g,'').trim().split(/\n\s*\n/),cues=[];for(const block of blocks){if(/^WEBVTT(?:\s|$)/.test(block)||/^NOTE(?:\s|$)/.test(block))continue;const lines=block.split('\n'),i=lines.findIndex(l=>l.includes('-->'));if(i<0)throw Error('Use an SRT or WebVTT caption file.');const parts=lines[i].split('-->');const start=timestamp(parts[0]),end=timestamp(parts[1].trim().split(/\s/)[0]);const text=lines.slice(i+1).join('\n').replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');cues.push({start,end,text})}return validateExtras({captions:cues},duration).captions} +export function parseChapters(raw,duration){if(!raw.trim())return[];return validateExtras({chapters:raw.trim().split('\n').map(line=>{const m=line.match(/^(\S+)\s+(.+)$/);if(!m)throw Error('Use one chapter per line: 0:30 Chapter title');return{time:timestamp(m[1]),title:m[2]}})},duration).chapters} +export function validateExtras(v={},duration){const captions=v.captions??[],chapters=v.chapters??[];if(!Array.isArray(captions)||captions.length>100||!Array.isArray(chapters)||chapters.length>20)throw Error('Use at most 100 captions and 20 chapters.');let last=-1,total=0;const cues=captions.map(c=>{if(!c||!Number.isFinite(c.start)||!Number.isFinite(c.end)||c.start<0||c.startduration+.05||c.end<=c.start)throw Error('Caption times must be ordered and inside the video.');last=c.start;const text=clean(c.text,500);total+=text.length;if(!text||total>12000)throw Error('Keep captions within 12,000 characters.');return{start:c.start,end:c.end,text}});last=-1;const marks=chapters.map(c=>{if(!c||!Number.isFinite(c.time)||c.time<0||c.time<=last||c.time>=duration)throw Error('Chapter times must increase and stay inside the video.');last=c.time;const title=clean(c.title,80);if(!title)throw Error('Add a chapter title.');return{time:c.time,title}});let report=null;if(v.report){const r=v.report;if(typeof r!=='object'||Array.isArray(r))throw Error('Invalid bug report.');report={url:clean(r.url||'',500),steps:clean(r.steps||'',2000),expected:clean(r.expected||'',1000),actual:clean(r.actual||'',1000),environment:clean(r.environment||'',300)};if(report.url&&!/^https?:\/\//i.test(report.url))throw Error('Use a full http or https page URL.');if(report.url){const u=new URL(report.url);if(u.username||u.password)throw Error('Remove credentials from the page URL.')}if(!Object.values(report).some(Boolean))report=null}return{captions:cues,chapters:marks,report}} +const stamp=n=>{const ms=Math.round(n*1000),h=Math.floor(ms/3600000),m=Math.floor(ms/60000)%60,s=Math.floor(ms/1000)%60;return`${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}.${String(ms%1000).padStart(3,'0')}`}; +export const captionsVTT=cues=>'WEBVTT\n\n'+cues.map(c=>`${stamp(c.start)} --> ${stamp(c.end)}\n${c.text.replace(/&/g,'&').replace(//g,'>')}\n`).join('\n'); +export function trimExtras(v,start,end){return{report:v.report||null,captions:(v.captions||[]).filter(c=>c.end>start&&c.start({...c,start:Math.max(0,c.start-start),end:Math.min(end,c.end)-start})),chapters:(v.chapters||[]).filter(c=>c.time>=start&&c.time({...c,time:c.time-start}))}} +export function reportMarkdown(c,origin){const r=c.report||{};return`# ${c.title}\n\n${c.shared?`Video: ${origin}/v/${c.id}\n\n`:''}Page: ${r.url||'Not supplied'}\n\n## Reproduction steps\n${r.steps||'Not supplied'}\n\n## Expected\n${r.expected||'Not supplied'}\n\n## Actual\n${r.actual||'Not supplied'}\n\n## Environment (owner supplied)\n${r.environment||'Not supplied'}\n\n## Chapters\n${(c.chapters||[]).map(x=>`${stamp(x.time)} ${x.title}`).join('\n')||'None'}\n`} diff --git a/rebuild/legacy/lib/feedback.js b/rebuild/legacy/lib/feedback.js new file mode 100644 index 0000000..3eb238c --- /dev/null +++ b/rebuild/legacy/lib/feedback.js @@ -0,0 +1,56 @@ +// Feedback-at-a-glance derivation from an owner-gated manage/view payload. +// Pure and testable; no network, no polling. Mirrors DESIGN_SYSTEM §6.3. +import {discussionThreads} from './discussion.js'; + +export function formatAgo(ts, now = Date.now()) { + if (!ts || !Number.isFinite(ts)) return ''; + const s = Math.max(0, Math.floor((now - ts) / 1000)); + if (s < 60) return 'just now'; + if (s < 3600) return `${Math.floor(s / 60)} min ago`; + if (s < 86400) return `${Math.floor(s / 3600)} h ago`; + return `${Math.floor(s / 86400)} d ago`; +} + +export function feedbackSummary(clip = {}, {now = Date.now(), seenAt = 0} = {}) { + const comments = Array.isArray(clip.comments) ? clip.comments : []; + const threads = discussionThreads(comments); + const liveThreads = threads.filter(t => !t.root.deleted); + const openThreads = liveThreads.filter(t => !t.root.resolved).length; + const liveComments = comments.filter(c => !c.deleted); + const lastReplyAt = liveComments.length ? Math.max(...liveComments.map(c => c.createdAt || 0)) || 0 : 0; + const reactions = clip.reactions || {}; + const reactionTotal = Object.values(reactions).reduce((n, v) => n + (Number(v) || 0), 0); + const newReplies = seenAt ? liveComments.filter(c => (c.createdAt || 0) > seenAt).length : 0; + return { + openThreads, + totalThreads: liveThreads.length, + hasDiscussion: liveComments.length > 0, + allResolved: liveThreads.length > 0 && openThreads === 0, + lastReplyAt, + lastReplyAgo: lastReplyAt ? formatAgo(lastReplyAt, now) : '', + reactions, + reactionTotal, + newReplies, + discussionRevision: clip.discussionRevision || 0, + }; +} + +export function feedbackLine(summary) { + if (!summary || !summary.hasDiscussion) return ''; + if (summary.newReplies > 0) return `● ${summary.newReplies} new ${summary.newReplies === 1 ? 'reply' : 'replies'}`; + if (summary.openThreads > 0) { + const base = `● ${summary.openThreads} open ${summary.openThreads === 1 ? 'thread' : 'threads'}`; + return summary.lastReplyAgo ? `${base} · last reply ${summary.lastReplyAgo}` : base; + } + if (summary.allResolved) return '✓ All threads resolved'; + return ''; +} + +export function seenKey(clipId) { return `screennote-seen-${clipId}`; } +export function readSeen(clipId) { + try { const v = JSON.parse(localStorage.getItem(seenKey(clipId))); return v && Number.isFinite(v.seenAt) ? v : {seenAt: 0, discussionRevision: 0}; } catch { return {seenAt: 0, discussionRevision: 0}; } +} +export function writeSeen(clipId, revision) { + try { localStorage.setItem(seenKey(clipId), JSON.stringify({seenAt: Date.now(), discussionRevision: revision || 0})); } catch {} +} +export function clearSeen(clipId) { try { localStorage.removeItem(seenKey(clipId)); } catch {} } diff --git a/rebuild/legacy/lib/import-media.js b/rebuild/legacy/lib/import-media.js new file mode 100644 index 0000000..fe51bad --- /dev/null +++ b/rebuild/legacy/lib/import-media.js @@ -0,0 +1,11 @@ +import {LOCAL_MAX_BYTES,isVideo} from './rules.js'; +// Some device file providers omit MIME or use application/octet-stream. +// Infer only supported extensions, verify their container header, then let the browser decode. +export async function importMedia(file){ + if(file.size>LOCAL_MAX_BYTES)throw Error('Choose a video up to 250 MB for local editing. Your file has not been uploaded.'); + const declared=String(file.type||'').split(';')[0].toLowerCase(); + const type=['video/mp4','video/webm'].includes(declared)?declared:(!declared||declared==='application/octet-stream')?(/\.mp4$/i.test(file.name)?'video/mp4':/\.webm$/i.test(file.name)?'video/webm':''):''; + if(!type)throw Error('Choose an MP4 or WebM video.'); + if(!isVideo(new Uint8Array(await file.slice(0,16).arrayBuffer()),type))throw Error('This file is not a valid MP4 or WebM video. Nothing was uploaded.'); + return{blob:new Blob([file],{type}),type}; +} diff --git a/rebuild/legacy/lib/library-backup.js b/rebuild/legacy/lib/library-backup.js new file mode 100644 index 0000000..1fb6e64 --- /dev/null +++ b/rebuild/legacy/lib/library-backup.js @@ -0,0 +1,69 @@ +import { Zip, ZipPassThrough, unzipSync, strToU8, strFromU8 } from "fflate"; +// @ts-ignore - shared browser-safe id and media validation helpers +import { validId, isVideo } from "./rules.js"; +const MAX_ARCHIVE=260*1024*1024,MAX_VIDEO_TOTAL=250*1024*1024,MAX_CLIPS=500,MAX_CLIP_BYTES=50_000_000; +const bytesView=(b)=>new DataView(b.buffer,b.byteOffset,b.byteLength); +function inspectStoredZip(bytes){ + if(bytes.length>MAX_ARCHIVE||bytes.length<22)throw Error("Choose a ScreenNote backup smaller than 260 MB."); + const view=bytesView(bytes);let end=-1;for(let i=bytes.length-22;i>=Math.max(0,bytes.length-65557);i--){if(view.getUint32(i,true)===0x06054b50){end=i;break}} + if(end<0)throw Error("This is not a complete ScreenNote ZIP backup."); + const count=view.getUint16(end+10,true),centralSize=view.getUint32(end+12,true),centralOffset=view.getUint32(end+16,true); + if(!count||count>MAX_CLIPS+1||centralOffset+centralSize>end)throw Error("The backup directory is invalid."); + let cursor=centralOffset,total=0;const names=new Set(); + for(let n=0;nbytes.length||view.getUint32(cursor,true)!==0x02014b50)throw Error("The backup directory is damaged."); + const flags=view.getUint16(cursor+8,true),method=view.getUint16(cursor+10,true),compressed=view.getUint32(cursor+20,true),size=view.getUint32(cursor+24,true),nameLen=view.getUint16(cursor+28,true),extraLen=view.getUint16(cursor+30,true),commentLen=view.getUint16(cursor+32,true); + if(flags&1||method!==0||compressed!==size||size===0xffffffff||compressed===0xffffffff)throw Error("Only uncompressed, private ScreenNote backup archives are supported."); + const name=strFromU8(bytes.subarray(cursor+46,cursor+46+nameLen)); + if(name.startsWith("/")||name.includes("..")||name.includes("\\")||!(name==="manifest.json"||/^videos\/[0-9a-f-]{36}\.(mp4|webm)$/.test(name))||names.has(name))throw Error("The backup contains an unexpected or duplicate file."); + if(name==="manifest.json"&&size>20*1024*1024)throw Error("The backup manifest is too large."); + if(name.startsWith("videos/")&&size>MAX_CLIP_BYTES)throw Error("A video in the backup exceeds 50 MB."); + names.add(name);total+=size;if(total>MAX_VIDEO_TOTAL+20*1024*1024)throw Error("The backup expands beyond the supported size."); + cursor+=46+nameLen+extraLen+commentLen; + } + if(!names.has("manifest.json"))throw Error("The backup manifest is missing."); + return{names,total}; +} +export async function makeLibraryBackup(clips,onProgress=()=>{}){ + if(!Array.isArray(clips)||!clips.length)throw Error("There are no local recordings to back up yet."); + if(clips.length>MAX_CLIPS)throw Error("Back up no more than 500 recordings at once."); + const total=clips.reduce((sum,c)=>sum+(c.blob?.size||0),0);if(total>MAX_VIDEO_TOTAL)throw Error("This library is larger than the 250 MB backup limit. Export large videos individually, then back up the remaining library."); + let copied=0; + const entries=clips.map(c=>{if(!validId(c.id))throw Error("A local recording has an invalid identity.");if(c.owner&&!/^[a-f0-9]{64}$/.test(c.owner))throw Error("A local recovery key is invalid.");const {blob,...metadata}=c;const type=blob?.type||c.type||"";const ext=blob?(type.split(";")[0]==="video/mp4"?"mp4":type.split(";")[0]==="video/webm"?"webm":null):null;if(blob&&(!ext||blob.size>MAX_CLIP_BYTES))throw Error("A local video has an unsupported type or exceeds 50 MB.");const videoPath=blob?`videos/${c.id}.${ext}`:null;return{metadata,videoPath,videoSize:blob?.size||0,videoType:type}}); + const manifest={format:"screennote-library-backup",version:1,origin:globalThis.location?.origin||"local",createdAt:new Date().toISOString(),clipCount:entries.length,totalVideoBytes:total,clips:entries}; + const output=[];let resolveDone,rejectDone;const done=new Promise((resolve,reject)=>{resolveDone=resolve;rejectDone=reject}); + const zip=new Zip((error,chunk,final)=>{if(error){rejectDone(error);return}if(chunk?.length)output.push(chunk);if(final)resolveDone()}); + const manifestFile=new ZipPassThrough("manifest.json");zip.add(manifestFile);manifestFile.push(strToU8(JSON.stringify(manifest)),true); + for(const entry of entries){ + const clip=clips.find(x=>x.id===entry.metadata.id);if(!clip?.blob)continue; + const file=new ZipPassThrough(entry.videoPath);zip.add(file); + if(clip.blob.stream){const reader=clip.blob.stream().getReader();for(;;){const {done,value}=await reader.read();if(done)break;file.push(value,false);copied+=value.length;onProgress(total?Math.floor(copied/total*100):100)}} + else{const data=new Uint8Array(await clip.blob.arrayBuffer());file.push(data,false);copied+=data.length;onProgress(total?Math.floor(copied/total*100):100)} + file.push(new Uint8Array(0),true); + } + zip.end();await done;const blob=new Blob(output,{type:"application/zip"});if(blob.size>MAX_ARCHIVE)throw Error("The backup archive exceeds 260 MB. Export large videos individually.");return blob; +} +export async function readLibraryBackup(file,existingIds=new Set()){ + if(!file||file.size>MAX_ARCHIVE)throw Error("Choose a ScreenNote backup smaller than 260 MB."); + const bytes=new Uint8Array(await file.arrayBuffer()),envelope=inspectStoredZip(bytes),files=unzipSync(bytes); + let manifest;try{manifest=JSON.parse(strFromU8(files["manifest.json"]))}catch{throw Error("The backup manifest could not be read.");} + if(!manifest||manifest.format!=="screennote-library-backup"||manifest.version!==1||!Array.isArray(manifest.clips)||manifest.clips.length>MAX_CLIPS||manifest.clipCount!==manifest.clips.length)throw Error("This is not a supported ScreenNote library backup."); + const records=[],ids=new Set();let totalVideoBytes=0,duplicates=0; + for(const entry of manifest.clips){ + if(!entry||typeof entry!=="object"||!entry.metadata||!validId(entry.metadata.id)||ids.has(entry.metadata.id))throw Error("The backup contains an invalid or duplicate recording."); + const metadata={...entry.metadata};ids.add(metadata.id);const videoPath=entry.videoPath,videoSize=Number(entry.videoSize)||0,videoType=entry.videoType;delete metadata.blob; + if(metadata.owner!==undefined&&metadata.owner!==null&&!/^[a-f0-9]{64}$/.test(metadata.owner))throw Error("A recovery key in this backup is invalid."); + if((metadata.shared||metadata.revoked||metadata.uploadAttempted)&&!metadata.owner)throw Error("A shared recording is missing its management key."); + if(videoPath){ + const ext=String(videoType||"").split(";")[0]==="video/mp4"?"mp4":String(videoType||"").split(";")[0]==="video/webm"?"webm":null; + if(!ext||videoPath!==`videos/${metadata.id}.${ext}`||videoSize<=0||videoSize>MAX_CLIP_BYTES)throw Error("A backup video entry is invalid."); + const data=files[videoPath];if(!data||data.length!==videoSize||!isVideo(data,String(videoType).split(";")[0]))throw Error("A video in this backup is damaged or does not match its manifest."); + metadata.blob=new Blob([data],{type:videoType});metadata.type=String(videoType).split(";")[0];totalVideoBytes+=data.length; + }else if(videoSize!==0)throw Error("A backup video is missing."); + if(!Number.isFinite(metadata.duration)||metadata.duration<=0||metadata.duration>1800||!Number.isFinite(metadata.createdAt))throw Error("A recording's metadata is invalid."); + if(existingIds.has(metadata.id)){duplicates++;continue}records.push(metadata); + } + if(totalVideoBytes>MAX_VIDEO_TOTAL||Number(manifest.totalVideoBytes)!==totalVideoBytes)throw Error("The backup video total does not match its manifest."); + for(const name of envelope.names)if(name!=="manifest.json"&&!manifest.clips.some(e=>e.videoPath===name))throw Error("The backup contains an unlisted file."); + return{clips:records,duplicates,totalVideoBytes,sourceOrigin:typeof manifest.origin==="string"?manifest.origin.slice(0,2048):"",clipCount:manifest.clips.length}; +} diff --git a/rebuild/legacy/lib/library.js b/rebuild/legacy/lib/library.js new file mode 100644 index 0000000..9ba367c --- /dev/null +++ b/rebuild/legacy/lib/library.js @@ -0,0 +1,7 @@ +export const REVIEW_STATES=['needs-feedback','changes-requested','approved']; +export const reviewLabel=s=>({'needs-feedback':'Needs feedback','changes-requested':'Changes requested',approved:'Approved'}[s]||'Needs feedback'); +export function filterRecordings(clips,{query='',status='all',sort='newest',feedbackById={}}={}){ + const q=query.trim().toLocaleLowerCase(); + const result=clips.filter(c=>(!q||String(c.title).toLocaleLowerCase().includes(q))&&(status==='all'||status==='shared'&&c.shared&&!c.revoked&&!c.cloudDeleted&&c.expiresAt>Date.now()||status==='local'&&!!c.blob&&(!c.shared||c.revoked||c.cloudDeleted||c.expiresAt<=Date.now())||status==='open-threads'&&(feedbackById[c.id]?.openThreads||0)>0||status!=='open-threads'&&status===(c.reviewStatus||'needs-feedback'))); + return result.sort((a,b)=>sort==='title'?String(a.title).localeCompare(String(b.title)):sort==='oldest'?a.createdAt-b.createdAt:b.createdAt-a.createdAt); +} diff --git a/rebuild/legacy/lib/media-validation.js b/rebuild/legacy/lib/media-validation.js new file mode 100644 index 0000000..2aa9333 --- /dev/null +++ b/rebuild/legacy/lib/media-validation.js @@ -0,0 +1,61 @@ +import {Input, BufferSource, MP4, WEBM, EncodedPacketSink} from 'mediabunny'; +import {MAX_BYTES, MAX_SECONDS} from './rules.js'; + +const invalid = () => Object.assign(Error('This upload does not contain a valid video. Re-export it as MP4 or WebM and try again. Your local copy is safe.'), {status: 400}); + +// Read complete packet payloads, not just the filename, MIME or magic bytes. +// This is bounded container/track validation, not a universal codec decoder. +export async function inspectMedia(bytes, expected) { + if (!bytes.length || bytes.length > MAX_BYTES || bytes.length !== expected.size) throw invalid(); + const input = new Input({source: new BufferSource(bytes), formats: [expected.type === 'video/mp4' ? MP4 : WEBM]}); + try { + const tracks = await input.getTracks(); + if (!tracks.length || tracks.length > 8) throw invalid(); + const video = await input.getPrimaryVideoTrack(); + if (!video || !video.codec || !video.displayWidth || !video.displayHeight + || video.displayWidth > 16384 || video.displayHeight > 16384) throw invalid(); + let videoPackets = 0, packets = 0, duration = 0; + const deadline = Date.now() + 8000; + for (const track of tracks) { + for await (const packet of new EncodedPacketSink(track).packets()) { + if (++packets > 100000 || Date.now() > deadline || !packet.data.length + || !Number.isFinite(packet.timestamp) || !Number.isFinite(packet.duration)) throw invalid(); + if (track === video) videoPackets++; + duration = Math.max(duration, packet.timestamp + packet.duration); + if (duration > MAX_SECONDS + 1) throw invalid(); + } + } + if (!videoPackets || duration <= 0 || Math.abs(duration - expected.duration) > 1) throw invalid(); + return {width: video.displayWidth, height: video.displayHeight, duration}; + } catch (error) { + if (error.status) throw error; + throw invalid(); + } finally { + input.dispose(); + } +} + +export async function validatePublishedMedia(url, expected, fetcher = fetch) { + let response;try{response=await fetcher(url,{signal:AbortSignal.timeout(20000)})}catch{throw Object.assign(Error('Could not verify this upload. Keep your local copy and retry.'),{status:503})} + if (!response.ok || !response.body) throw Object.assign(Error('Could not verify this upload. Keep your local copy and retry.'), {status: 503}); + const reader = response.body.getReader(), chunks = []; + let size = 0; + try { + for (;;) { + const {done, value} = await reader.read(); + if (done) break; + size += value.length; + if (size > expected.size || size > MAX_BYTES) throw invalid(); + chunks.push(value); + } + } catch (error) { + if (error.status) throw error; + throw Object.assign(Error('Could not verify this upload. Keep your local copy and retry.'), {status: 503}); + } finally { + await reader.cancel().catch(() => {}); + } + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } + return inspectMedia(bytes, expected); +} diff --git a/rebuild/legacy/lib/metadata-store.js b/rebuild/legacy/lib/metadata-store.js new file mode 100644 index 0000000..c66dad9 --- /dev/null +++ b/rebuild/legacy/lib/metadata-store.js @@ -0,0 +1,8 @@ +// Metadata must use a strong storage revision, not a compressed response's weak ETag. +const contention=()=>Object.assign(Error('Recording metadata changed. Please try again.'),{status:409}); +export function createMetadataStore({get,head,put,isConflict,delay=ms=>new Promise(r=>setTimeout(r,ms))}){ + async function read(path){for(let attempt=0;attempt<3;attempt++){const r=await get(path,{access:'private',useCache:false,headers:{'Accept-Encoding':'identity'}});if(!r)return null;const data=await new Response(r.stream).json();let etag=r.blob.etag;if(etag?.startsWith('W/')&&head){const canonical=await head(path);if(canonical.etag&&!canonical.etag.startsWith('W/')&&etag.slice(2)===canonical.etag)etag=canonical.etag;else{if(attempt<2)await delay(100*2**attempt);continue}}if(!etag||etag.startsWith('W/'))throw contention();return{data,etag}}throw contention()} + async function write(path,data,etag){if(etag?.startsWith('W/'))throw contention();return put(path,JSON.stringify(data),{access:'private',addRandomSuffix:false,allowOverwrite:!!etag,contentType:'application/json',...(etag?{ifMatch:etag}:{}),cacheControlMaxAge:0})} + async function mutate(path,change,initial){for(let attempt=0;attempt<5;attempt++){const r=await read(path),data=r?structuredClone(r.data):initial?.();if(!data)throw Object.assign(Error('Clip not found.'),{status:404});const result=change(data);try{await write(path,data,r?.etag);return result??data}catch(e){if(!isConflict(e)&&!String(e.message).includes('already exists'))throw e;console.warn('ScreenNote metadata contention',JSON.stringify({attempt:attempt+1,name:e.name}));if(attempt<4)await delay(100*2**attempt)}}throw contention()} + return{read,write,mutate}; +} diff --git a/rebuild/legacy/lib/recording-policy.js b/rebuild/legacy/lib/recording-policy.js new file mode 100644 index 0000000..b6fd1ba --- /dev/null +++ b/rebuild/legacy/lib/recording-policy.js @@ -0,0 +1,20 @@ +import {MAX_BYTES,MAX_SECONDS,LOCAL_MAX_BYTES,LOCAL_MAX_SECONDS} from './rules.js'; +export const PROFILES = { + saver: {label:'Data saver',width:960,fps:15,video:350000,audio:48000}, + balanced: {label:'Balanced',width:1280,fps:24,video:600000,audio:64000}, + clear: {label:'Clear text',width:1920,fps:24,video:1600000,audio:64000} +}; +export const profileFor = name => PROFILES[name] || PROFILES.balanced; +export function recordingStats(bytes,seconds,profile='balanced') { + const rate=seconds>2&&bytes>0?bytes/seconds:(profileFor(profile).video+profileFor(profile).audio)/8; + return {bytes,seconds,remaining:Math.max(0,Math.min(LOCAL_MAX_SECONDS-seconds,(LOCAL_MAX_BYTES-bytes)/rate)), + shareRemaining:Math.max(0,Math.min(MAX_SECONDS-seconds,(MAX_BYTES-bytes)/rate)), + shareable:bytes<=MAX_BYTES&&seconds<=MAX_SECONDS,rate}; +} +export function sharingProblem(clip) { + const size=clip.blob?.size??clip.size??0; + if(clip.duration>MAX_SECONDS)return 'This video is longer than 10 minutes. Trim a shorter copy to share; your original stays here.'; + if(size>MAX_BYTES)return 'This video is larger than 50 MB. Make a smaller copy to share; your original stays here.'; + return ''; +} +export const stopMessage = reason => ({size:'Saved: the 250 MB local recording limit was reached.',duration:'Saved: the 30-minute local recording limit was reached.',source:'Saved: screen sharing ended.',error:'Recording stopped unexpectedly. The captured video is saved.',user:'Recording saved.'}[reason]||'Recording saved.'); diff --git a/rebuild/legacy/lib/recovery.js b/rebuild/legacy/lib/recovery.js new file mode 100644 index 0000000..12f3d82 --- /dev/null +++ b/rebuild/legacy/lib/recovery.js @@ -0,0 +1,20 @@ +import {validId} from './rules.js'; +export function recoveryDocument(clips, origin) { + const keys = clips.filter(c => (c.shared || c.revoked || c.uploadAttempted) && !c.cloudDeleted) + .map(c => ({id:c.id, owner:c.owner})); + return JSON.stringify({format:'screennote-recovery',version:1,origin,keys},null,2); +} +export function recoveryKeys(raw, origin) { + if (typeof raw !== 'string' || raw.length > 524288) throw Error('Use a ScreenNote recovery file smaller than 512 KB.'); + let data;try {data=JSON.parse(raw)} catch {throw Error('This is not valid recovery JSON. Paste the complete recovery file.');} + const trustedOrigins=['https://screennote-woad.vercel.app','https://screennote-7hlckmmie-butters-projects-ad226a08.vercel.app','https://screennote-dev.buttercoder-dev.workers.dev']; + const destinationHost=new URL(origin).hostname; + const trustedDestination=trustedOrigins.includes(origin)||destinationHost==='screennote.online'||destinationHost.endsWith('.screennote.online')||destinationHost==='screennote.app'||destinationHost.endsWith('.screennote.app'); + if (!data || data.format!=='screennote-recovery' || data.version!==1 || data.origin!==origin&&!(trustedOrigins.includes(data.origin)&&trustedDestination) || !Array.isArray(data.keys) || !data.keys.length || data.keys.length>128) + throw Error('Use a recovery file from this ScreenNote address or an official ScreenNote/Vercel address when migrating.'); + const ids=new Set();return data.keys.map(k=>{ + if (!k || !validId(k.id) || typeof k.owner!=='string' || !/^[a-f0-9]{64}$/.test(k.owner) || ids.has(k.id)) + throw Error('The recovery file contains an invalid or duplicate key.'); + ids.add(k.id);return {id:k.id,owner:k.owner}; + }); +} diff --git a/rebuild/legacy/lib/retention.js b/rebuild/legacy/lib/retention.js new file mode 100644 index 0000000..19c2cce --- /dev/null +++ b/rebuild/legacy/lib/retention.js @@ -0,0 +1,8 @@ +export const RETENTION_GRACE = 24 * 60 * 60 * 1000; +export function reclaimable(clip, now = Date.now()) { + if (clip.status === 'expired' || clip.status === 'deleted') return true; + const deadline = clip.status === 'pending' + ? (clip.uploadUntil || clip.createdAt + 600000) + : clip.expiresAt; + return Number.isFinite(deadline) && deadline + RETENTION_GRACE <= now; +} diff --git a/rebuild/legacy/lib/rules.js b/rebuild/legacy/lib/rules.js new file mode 100644 index 0000000..dcc618f --- /dev/null +++ b/rebuild/legacy/lib/rules.js @@ -0,0 +1,15 @@ +import {REVIEW_STATES} from './library.js'; +import {validateExtras} from './enrichment.js'; +export const MAX_BYTES=50_000_000,MAX_SECONDS=600,LOCAL_MAX_BYTES=250_000_000,LOCAL_MAX_SECONDS=1800,MAX_SHARED=10000,STORAGE_BUDGET_BYTES=1_000_000_000; +export const TYPES=['video/webm','video/mp4']; +export const validId=v=>typeof v==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(v); +export function text(v,max,required=false){if(typeof v!=='string'||v.trim().length>max||required&&!v.trim())throw Error('Please check the text fields.');return v.trim()} +export function clipInput(v){const title=text(v.title,100,true),type=TYPES.find(t=>String(v.type).split(';')[0].trim()===t);if(!type||!Number.isFinite(v.duration)||v.duration<=0||v.duration>MAX_SECONDS+1||!Number.isInteger(v.size)||v.size<1||v.size>MAX_BYTES)throw Error('Use a playable WebM or MP4, up to ten minutes and 50 MB.');const start=Number(v.start),end=Number(v.end);if(!Number.isFinite(start)||!Number.isFinite(end)||start<0||end>v.duration+.05||end-start<.25)throw Error('Choose a valid start and end, at least a quarter-second apart.');const linkDays=v.linkDays??7;if(![1,3,7].includes(linkDays))throw Error('Choose a link expiry of 1, 3 or 7 days.');const reviewStatus=v.reviewStatus??'needs-feedback';if(!REVIEW_STATES.includes(reviewStatus))throw Error('Choose a valid review status.');return{reviewStatus,title,type,duration:v.duration,size:v.size,start,end,linkDays,...validateExtras(v,v.duration)}} +export function commentInput(v,clip){const body=text(v.text,500,true),name=text(typeof v.name==='string'?(v.name.trim()||'Guest'):(v.name||'Guest'),40,true),time=Number(v.time),parentId=v.parentId||null;if(parentId&&!validId(parentId))throw Error('Choose an existing reply.');if(!Number.isFinite(time)||timeclip.end+.1)throw Error('Choose a timestamp inside this clip.');return{text:body,name,time:Math.max(clip.start,Math.min(time,clip.end)),parentId}} +export function publicClip(c){return{id:c.id,title:c.title,reviewStatus:c.reviewStatus||'needs-feedback',width:c.width,height:c.height,start:c.start,end:c.end,duration:c.duration,createdAt:c.createdAt,expiresAt:c.expiresAt,passwordProtected:!!c.passwordHash,discussionRevision:c.discussionRevision||0,captions:c.captions||[],chapters:c.chapters||[],report:c.report||null,comments:(c.comments||[]).map(({id,name,text,time,createdAt,parentId=null,editedAt,deleted=false,resolved=false,creator=false})=>({id,name:deleted?'Deleted comment':name,text:deleted?'':text,time,createdAt,parentId,editedAt,deleted,resolved,creator})),reactions:Object.fromEntries(['like','thanks','idea'].map(k=>[k,Object.values(c.votes||{}).filter(v=>v===k).length]))}} +export function formatTime(n){n=Math.max(0,Math.floor(Number(n)||0));return `${Math.floor(n/60)}:${String(n%60).padStart(2,'0')}`} +export function isVideo(bytes,type){return type==='video/webm'?bytes[0]===26&&bytes[1]===69&&bytes[2]===223&&bytes[3]===163:String.fromCharCode(...bytes.slice(4,8))==='ftyp'} + +export function randomId(){if(globalThis.crypto?.randomUUID)return crypto.randomUUID();const b=crypto.getRandomValues(new Uint8Array(16));b[6]=(b[6]&15)|64;b[8]=(b[8]&63)|128;const h=[...b].map(n=>n.toString(16).padStart(2,'0')).join('');return `${h.slice(0,8)}-${h.slice(8,12)}-${h.slice(12,16)}-${h.slice(16,20)}-${h.slice(20)}`} + +export const CHUNK_BYTES=2*1024*1024; diff --git a/rebuild/legacy/lib/share-options.js b/rebuild/legacy/lib/share-options.js new file mode 100644 index 0000000..6587c50 --- /dev/null +++ b/rebuild/legacy/lib/share-options.js @@ -0,0 +1,7 @@ +export function newShareIdentity(c,now=Date.now()){return!!(c.revoked||c.cloudDeleted||c.shared&&c.expiresAt<=now)} +export function shareOptions(c,linkDays,password=''){ + if(![1,3,7].includes(linkDays))throw Error('Choose an expiry of 1, 3 or 7 days.'); + if(typeof password!=='string'||password&& (password.length<8||password.length>128))throw Error('Use a sharing password of 8–128 characters.'); + if(c.passwordProtected&&!password)throw Error('Enter the sharing password before retrying or republishing this protected video. For a pending upload, use its original password.'); + return{linkDays,password,newIdentity:newShareIdentity(c)}; +} diff --git a/rebuild/legacy/lib/store.js b/rebuild/legacy/lib/store.js new file mode 100644 index 0000000..7fee999 --- /dev/null +++ b/rebuild/legacy/lib/store.js @@ -0,0 +1,11 @@ +import * as legacy from './vercel-store.js'; +import {createSupabaseStore} from './supabase-store.js'; +export const key=legacy.key,media=legacy.media; +// Explicit Supabase configuration takes precedence; never silently fall back to +// a different store after a write failure or split one recording across stores. +const backend=process.env.SUPABASE_URL||process.env.SCREENNOTE_STORAGE_KEY + ?createSupabaseStore({url:process.env.SUPABASE_URL,secret:process.env.SCREENNOTE_STORAGE_KEY}) + :legacy; +export const {configured,read,write,mutate,mediaInfo,mediaMagic,mediaURL,removeMedia,uploadSmall,uploadPart,assemble,clearParts}=backend; +export const uploadedParts=backend.uploadedParts||(()=>Promise.resolve([])); +export const usingSupabase=backend!==legacy; diff --git a/rebuild/legacy/lib/supabase-store.js b/rebuild/legacy/lib/supabase-store.js new file mode 100644 index 0000000..7022e51 --- /dev/null +++ b/rebuild/legacy/lib/supabase-store.js @@ -0,0 +1,25 @@ +import {createMetadataStore} from './metadata-store.js'; +export function createSupabaseStore({url,secret,fetcher=fetch}){ + const ready=()=>/^https:\/\/[a-z0-9-]+\.supabase\.co$/.test(url||'')&&/^[a-f0-9]{64}$/.test(secret||''); + async function request(op,body={}){ + if(!ready())throw Error('Supabase sharing is not configured.'); + const r=await fetcher(url+'/functions/v1/screennote-store',{method:'POST',headers:{'Content-Type':'application/json','x-screennote-key':secret},body:JSON.stringify({op,...body}),signal:AbortSignal.timeout(55000)}); + const data=await r.json();if(!r.ok)throw Object.assign(Error(data.error||'Sharing storage is unavailable.'),{status:r.status>=500?undefined:r.status,statusCode:r.status,conflict:r.status===409});return data.data; + } + const metadata=createMetadataStore({ + get:async path=>{const record=await request('read',{path});return record?{stream:JSON.stringify(record.data),blob:{etag:record.etag}}:null}, + put:async(path,raw,options)=>request('write',{path,data:JSON.parse(raw),revision:options.ifMatch??null}), + isConflict:e=>e.conflict + }); + return{ + configured:ready,...metadata, + mediaInfo:id=>request('info',{id}), + mediaMagic:async id=>Uint8Array.from(await request('magic',{id})), + mediaURL:id=>request('sign',{id}),removeMedia:id=>request('remove',{id}), + uploadedParts:c=>request('partsStatus',{id:c.id,size:c.size}), + uploadSmall:(id,bytes,type)=>request('uploadSmall',{id,bytes:Buffer.from(bytes).toString('base64'),type}), + uploadPart:(id,part,bytes)=>request('uploadPart',{id,part,bytes:Buffer.from(bytes).toString('base64')}), + assemble:c=>request('assemble',{id:c.id,size:c.size,type:c.type}), + clearParts:c=>request('clearParts',{id:c.id,size:c.size}) + }; +} diff --git a/rebuild/legacy/lib/titles.js b/rebuild/legacy/lib/titles.js new file mode 100644 index 0000000..b98f8a6 --- /dev/null +++ b/rebuild/legacy/lib/titles.js @@ -0,0 +1,15 @@ +// File names are metadata, not necessarily a useful message title. +export function isGeneratedTitle(value = '') { + const name = String(value).replace(/\.(mp4|webm)$/i, '').trim(); + return !name || /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(?:[-_][a-z0-9_-]*)?$/i.test(name) + || /^[a-f0-9]{24,}(?:[_-].*)?$/i.test(name); +} +export function importTitle(filename, supplied) { + const name = String(supplied || filename || '').replace(/\.(mp4|webm)$/i, '').trim(); + return isGeneratedTitle(name) ? 'Untitled recording' : name.slice(0, 100); +} +export function validTitle(value) { + if (typeof value !== 'string' || !value.trim() || value.trim().length > 100) + throw Error('Add a video title of 1–100 characters.'); + return value.trim(); +} diff --git a/rebuild/legacy/lib/transfer.js b/rebuild/legacy/lib/transfer.js new file mode 100644 index 0000000..6df8e17 --- /dev/null +++ b/rebuild/legacy/lib/transfer.js @@ -0,0 +1 @@ +export async function retryTransfer(send,onRetry=()=>{},delay=ms=>new Promise(r=>setTimeout(r,ms))){for(let attempt=0;;attempt++){try{return await send()}catch(e){if(e.name==='AbortError'||e.code==='STORAGE_ACCESS_UNAVAILABLE'||attempt>=3||e.status&&e.status<500&&e.status!==429)throw e;onRetry(attempt+1);await delay(500*2**attempt)}}} diff --git a/rebuild/legacy/lib/unsaved.js b/rebuild/legacy/lib/unsaved.js new file mode 100644 index 0000000..e2176d9 --- /dev/null +++ b/rebuild/legacy/lib/unsaved.js @@ -0,0 +1,19 @@ +// Unsaved-work registry (DESIGN_SYSTEM §6.1, scoped): pure dirty-source logic. +// The share password is a flag only — its value is never stored anywhere. +export const DIRTY_ORDER = ['title', 'reviewStatus', 'extras', 'trim', 'marks', 'password']; +export const DIRTY_LABELS = { + title: 'title', + reviewStatus: 'review status', + extras: 'video context (captions, chapters, bug report)', + trim: 'trim range', + marks: 'drawn marks', + password: 'share password (not saved)', +}; +export function dirtyLabels(flags = {}) { + return DIRTY_ORDER.filter(k => !!flags[k]).map(k => DIRTY_LABELS[k]); +} +export function isDirty(flags = {}) { return DIRTY_ORDER.some(k => !!flags[k]); } +export function guardCopy(labels) { + const list = labels.length > 1 ? `${labels.slice(0, -1).join(', ')} and ${labels.at(-1)}` : labels[0]; + return `You have unsaved changes: ${list}. Leave anyway? Your saved video stays on this device.`; +} diff --git a/rebuild/legacy/lib/vercel-store.js b/rebuild/legacy/lib/vercel-store.js new file mode 100644 index 0000000..8cc531c --- /dev/null +++ b/rebuild/legacy/lib/vercel-store.js @@ -0,0 +1,18 @@ +import {createMetadataStore} from './metadata-store.js'; +import{Readable}from'node:stream'; +import{CHUNK_BYTES}from'./rules.js'; +import{get,put,head,del,issueSignedToken,presignUrl,BlobPreconditionFailedError}from'@vercel/blob'; +export const key=id=>`screennote/${id}/record.json`,media=id=>`screennote/${id}/video`; +export const configured=()=>!!(process.env.BLOB_READ_WRITE_TOKEN||process.env.BLOB_STORE_ID); +export const {read,write,mutate}=createMetadataStore({get,head,put,isConflict:e=>e instanceof BlobPreconditionFailedError}); +export async function mediaInfo(id){return head(media(id))} +export async function mediaMagic(id){const r=await get(media(id),{access:'private'});if(!r)throw Error('Upload is missing.');const reader=r.stream.getReader();try{const{value}=await reader.read();return value||new Uint8Array()}finally{await reader.cancel()}} +export async function mediaURL(id){const pathname=media(id),validUntil=Date.now()+300000,signed=await issueSignedToken({pathname,operations:['get'],validUntil});return(await presignUrl(signed,{operation:'get',pathname,access:'private',validUntil})).presignedUrl} +export const removeMedia=id=>del(media(id)); + +export const uploadSmall=(id,bytes,type)=>put(media(id),bytes,{access:'private',addRandomSuffix:false,contentType:type}); + +export const partKey=(id,n)=>`screennote/${id}/parts/${n}`; +export const uploadPart=(id,n,bytes)=>put(partKey(id,n),bytes,{access:'private',addRandomSuffix:false,contentType:'application/octet-stream'}); +export async function assemble(c){const count=Math.ceil(c.size/CHUNK_BYTES);async function*chunks(){for(let n=0;ndel(Array.from({length:Math.ceil(c.size/CHUNK_BYTES)},(_,n)=>partKey(c.id,n))); diff --git a/rebuild/legacy/package.json b/rebuild/legacy/package.json new file mode 100644 index 0000000..6fe9917 --- /dev/null +++ b/rebuild/legacy/package.json @@ -0,0 +1,21 @@ +{ + "name": "screennote", + "version": "0.5.0", + "type": "module", + "private": true, + "scripts": { + "build": "node scripts/build.mjs", + "test": "node --test tests/*.test.js", + "qa:prepare": "node scripts/prepare-qa.mjs" + }, + "dependencies": { + "@vercel/blob": "2.8.2", + "c8": "^12.0.0", + "esbuild": "0.28.2", + "fix-webm-duration": "1.0.6", + "mediabunny": "1.62.1" + }, + "overrides": { + "zod": "4.6.7" + } +} \ No newline at end of file diff --git a/rebuild/legacy/public/app.js b/rebuild/legacy/public/app.js new file mode 100644 index 0000000..3775952 --- /dev/null +++ b/rebuild/legacy/public/app.js @@ -0,0 +1,215 @@ +import {PROFILES,sharingProblem,stopMessage} from '../lib/recording-policy.js'; +import {filterRecordings,reviewLabel} from '../lib/library.js'; +import {discussionMarkup,mountDiscussion} from './discussion-ui.js'; +import {importTitle,isGeneratedTitle,validTitle} from '../lib/titles.js'; +import {version as APP_VERSION} from '../package.json'; +import {importMedia} from '../lib/import-media.js'; +import {shareOptions,newShareIdentity} from '../lib/share-options.js'; +import {retryTransfer} from '../lib/transfer.js'; +import {extrasPanel,mountExtras,mountViewerContext,viewerContext} from './extras-ui.js'; +import {bindMarkup} from './markup.js'; +import {trimExtras,captionsVTT} from '../lib/enrichment.js'; +import {feedbackSummary,feedbackLine,readSeen,writeSeen,clearSeen} from '../lib/feedback.js'; +import {dirtyLabels,guardCopy} from '../lib/unsaved.js'; +import {createDraftWriter} from '../lib/draft-writer.js'; +import {recoveryDocument,recoveryKeys} from '../lib/recovery.js'; +import {makeLibraryBackup,readLibraryBackup} from '../lib/library-backup.js'; +import fixDuration from'fix-webm-duration'; +import{Capture,trimVideo}from'./capture.js';import*as db from'./db.js';import{CHUNK_BYTES,randomId,formatTime,MAX_BYTES,MAX_SECONDS,LOCAL_MAX_BYTES,LOCAL_MAX_SECONDS}from'../lib/rules.js'; +const $=s=>document.querySelector(s),esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); +const formatBytes=n=>{if(!Number.isFinite(n)||n<0)return'0 B';const units=['B','KB','MB','GB'];let value=n,index=0;while(value>=1024&&index',grid:'',screen:'',mic:'',sound:'',play:'',arrow:'',plus:'',download:'',shield:'',moon:'',pause:'',stop:'',back:''}; +const icon=k=>``; +const brand=()=>''; +let libraryFilters={query:'',status:'all',sort:'newest'},uploadController=null,cameraBubble={x:.76,y:.72,size:.28}; +let clips=[],selected=null,objectURL=null,capture=null,recording=false,paused=false,busy=false,health=false,healthChecked=false,healthChecking=false,sharingIssue='',libraryReady=false,draft=null,viewData=null,viewer=randomId(),vote='',discussionUI=null,viewerOwner='',noticeTimer,markupUI=null,recordMarkup=[],countdownTimer=null,viewerPassword='',emergencyBlob=null,emergencyURL=null; +try{document.documentElement.dataset.theme=localStorage.getItem('screennote-theme')||'light';viewer=localStorage.getItem('screennote-viewer')||viewer;localStorage.setItem('screennote-viewer',viewer)}catch{} +const app=$('#app'),modal=$('#modal'); +function updateConnection(){const b=$('#connection-state');if(b){b.textContent=navigator.onLine?'':'Offline · local work is still available';b.hidden=navigator.onLine}} +window.addEventListener('offline',updateConnection);window.addEventListener('online',()=>{updateConnection();if(libraryReady)checkSharing()}); +let renderedView=null,feedbackById={},encodeController=null,editorMarks=null,feedbackChecking=false; +function notify(message){clearTimeout(noticeTimer);$('#notice').textContent=message;$('#notice').style.display='block';noticeTimer=setTimeout(()=>$('#notice').style.display='none',7000)} +function error(e){console.error(e);const box=$('#error');if(box){box.textContent=e.message||String(e);box.scrollIntoView({block:'nearest'})}else notify(e.message||String(e))} +async function checkSharing(){if(healthChecking)return;healthChecking=true;const retry=$('[data-action=check-sharing]');if(retry)retry.disabled=true;const status=$('#sharing-status');if(status)status.textContent='Checking sharing connection…';try{const result=await retryTransfer(()=>api('health'));health=!!result.configured;sharingIssue=health?'':'Online sharing is unavailable. Local editing and downloads still work.'}catch(e){health=false;sharingIssue=e.code==='STORAGE_ACCESS_UNAVAILABLE'?e.message:'Sharing connection failed. Your local copy is safe; retry when connected.'}finally{healthChecked=true;healthChecking=false;const banner=$('#service-status');if(banner){banner.textContent=sharingIssue;banner.hidden=health}const publish=$('[data-action=publish]');if(publish)publish.disabled=!health||!selected?.blob||!!sharingProblem(selected);const message=$('#sharing-status');if(message)message.textContent=health?'':sharingIssue;const button=$('[data-action=check-sharing]');if(button){button.hidden=health;button.disabled=false}}} +async function api(op,data,id){const signal=uploadController?AbortSignal.any([uploadController.signal,AbortSignal.timeout(65000)]):AbortSignal.timeout(65000);const r=await fetch('/api/clip?op='+op+(id?'&id='+encodeURIComponent(id):''),data?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data),signal}:{signal});let v;try{v=await r.json()}catch(e){if(e.name==='AbortError')throw e;throw Error('The sharing service did not respond. Your local copy is safe.')}if(!r.ok)throw Object.assign(Error(v.error||'Sharing failed. Keep your local copy and retry.'),{status:r.status,code:v.code});return v} +function shell(content,page='My recordings',view=page){discussionUI?.destroy();discussionUI=null;const navigated=renderedView!==view;renderedView=view;markupUI?.destroy();markupUI=null;app.innerHTML=`
Your space ${page}${brand()}
Early access · local first

${navigator.onLine?'':'Offline · local work is still available'}

${esc(sharingIssue)}
${emergencyBlob?``:''}${content}
ScreenNote · A little more human.Your recordings stay here until you choose to publish.
`;if(navigated){window.scrollTo({top:0,left:0,behavior:'instant'});$('#main').focus({preventScroll:true})}} +const isShared=c=>!!c.shared&&!c.revoked&&c.expiresAt>Date.now(); +function unsavedChanges(){if(!selected)return[];const flags={};const tf=$('#recording-title-input');if(tf&&tf.value!==(isGeneratedTitle(selected.title)?'Untitled recording':selected.title))flags.title=true;const rs=$('#review-status');if(rs&&rs.value!==(selected.reviewStatus||'needs-feedback'))flags.reviewStatus=true;const pw=$('#share-password');if(pw&&pw.value)flags.password=true;const cap=$('#captions-text'),chap=$('#chapters-text');if(cap||chap){const cur=[cap?.value||'',chap?.value||'', $('#report-url')?.value||'', $('#report-steps')?.value||'', $('#report-expected')?.value||'', $('#report-actual')?.value||'', $('#report-environment')?.value||''].join('\n');const saved=[selected.captions?.length?captionsVTT(selected.captions):'',(selected.chapters||[]).map(x=>`${formatTime(x.time)} ${x.title}`).join('\n'),selected.report?.url||'',selected.report?.steps||'',selected.report?.expected||'',selected.report?.actual||'',selected.report?.environment||''].join('\n');if(cur!==saved)flags.extras=true}const ts=$('#trim-start'),te=$('#trim-end');if(ts&&te&&(Math.abs(Number(ts.value))>1e-9||Math.abs(Number(te.value)-selected.duration)>0.051))flags.trim=true;if(editorMarks&&editorMarks.length)flags.marks=true;return dirtyLabels(flags)} +function unsavedTitle(){return unsavedChanges().includes('title')} +function showUnsavedGuard(labels){return new Promise(resolve=>{const opener=document.activeElement;modal.onclose=()=>{const target=opener?.isConnected?opener:$('#main');target?.focus({preventScroll:true})};modal.innerHTML=`

Unsaved changes

${guardCopy(labels)}

Your saved video stays on this device.${labels.some(l=>l.includes('password'))?' The sharing password is not saved.':''}

`;modal.oncancel=e=>{e.preventDefault();modal.close();resolve(false)};$('#guard-keep').focus();$('#guard-form').onsubmit=e=>{e.preventDefault();modal.close();resolve(false)};$('#guard-leave').onclick=()=>{const pw=$('#share-password');if(pw)pw.value='';modal.close();resolve(true)};modal.showModal()})} +async function confirmEditorLeave(){const labels=unsavedChanges();if(!labels.length)return true;return showUnsavedGuard(labels)} +function home(){ + if(recording||busy)return; + const canRecord=globalThis.isSecureContext&&!!navigator.mediaDevices?.getDisplayMedia&&!!globalThis.MediaRecorder; + selected=null;resetURL(); + const returning=clips.length>0; + shell(`
SCREENNOTE / YOUR WORKSPACE

Show it. Do not explain it twice.

Capture the detail, add context, and share one clear link. Your recordings stay on this device until you decide otherwise.

+
Local until you publish · No account needed to watch
+ ${returning?libraryMarkup():''} +
${canRecord||window.__ANDROID_APP__?'Record something new':'Import a device recording'}
A LITTLE CONTEXT GOES A LONG WAY

${canRecord?'Ready to record?':'Bring your recording.'}

${canRecord?'Choose your screen next. Review before you share.':'Use your phone’s screen recorder, then import the video here.'}

${icon('screen')}
+ + ${!canRecord?'

'+(window.__ANDROID_APP__?'Use Record screen below to capture, then bring the recording in here.':'This browser does not offer screen capture. MP4 and WebM imports work here.')+'

':''} +
${option('mic','Microphone','Include your voice','mic',canRecord)}
+
Camera, audio & microphone source${option('video','Camera bubble','Move and resize it in the preview','camera',canRecord)}${option('sound','Shared-screen audio','When your browser offers it','system',canRecord)}
+

Local: 30 min / 250 MB · Share: 10 min / 50 MB

+
+ ${returning?'':libraryMarkup()}`); + $('#import-video').onchange=e=>{const file=e.target.files[0];if(file)run(async()=>{const status=$('#import-status');status.textContent='Checking your video…';e.target.disabled=true;try{await importVideo(file)}finally{e.target.value='';e.target.disabled=false;if(status.isConnected)status.textContent=''}})}; + const backupInput=$('#restore-library-backup');if(backupInput)backupInput.onchange=e=>run(async()=>{const file=e.target.files[0];e.target.value='';if(!file)return;const parsed=await readLibraryBackup(file,new Set(clips.map(c=>c.id)));if(!parsed.clips.length){notify('Nothing new to restore · '+parsed.duplicates+' duplicate recordings were left unchanged.');return}dialog('Restore your ScreenNote library',`

This backup contains ${parsed.clips.length} recordings and ${formatBytes(parsed.totalVideoBytes)} of local video from ${esc(parsed.sourceOrigin||'another ScreenNote address')}.

Privacy: the backup includes local video files and sharing-management keys. Anyone with it can manage links in the backup. Existing recordings with matching IDs will be skipped, never overwritten.

Restore all selected records to this device? Your current library will remain intact.

`,async()=>{busy=true;try{await db.putMany(parsed.clips);clips=await db.all()}finally{busy=false}home();notify('Restored '+parsed.clips.length+' recordings · '+parsed.duplicates+' duplicates skipped.')},'Restore backup')}); + + for(const name of ['library-search','library-status','library-sort'])$('#'+name).addEventListener(name==='library-search'?'input':'change',renderLibrary); + renderLibrary(); + checkFeedback(); +} +function libraryMarkup(){return `

Your library ${clips.length}

On this device
Move or protect your library

Back up local videos and recovery keys, then restore them on another device or ScreenNote address.

`} +function renderLibrary(){ + libraryFilters={query:$('#library-search').value,status:$('#library-status').value,sort:$('#library-sort').value}; + const visible=filterRecordings(clips,{...libraryFilters,feedbackById});$('#library-count').textContent=clips.length?`${visible.length} of ${clips.length} recordings`:''; + $('#library-grid').innerHTML=visible.length?visible.map(c=>`
${isShared(c)?'Shared':'Local'}${reviewLabel(c.reviewStatus)}

${esc(isGeneratedTitle(c.title)?'Untitled recording':c.title)}

${c.cloudDeleted?'Upload deleted':isShared(c)?'Link expires '+new Date(c.expiresAt).toLocaleDateString():c.revoked?'Sharing stopped':c.shared?'Link expired':c.managementOnly?'Management access only':c.sample?'Sample walkthrough':'Saved on this device'} · ${new Date(c.createdAt).toLocaleDateString()}
${isShared(c)?'Checking…':''}
`).join(''):`

${clips.length?'No matching recordings.':'Your first clear explanation starts here.'}

${clips.length?'Try another title or filter.':'Record a message or explore a sample walkthrough.'}

${clips.length?'':''}
`; +} +async function fetchFeedbackFor(c){ + try{ + if(!isShared(c)||!c.owner)return null; + const state=await api('manage',{id:c.id,owner:c.owner}); + if(!state||state.status!=='published')return null; + const seen=readSeen(c.id); + const summary=feedbackSummary(state,{seenAt:seen.seenAt}); + feedbackById[c.id]=summary; + const line=feedbackLine(summary); + const reactions=summary.reactionTotal?` · ${Object.entries(summary.reactions).filter(([,v])=>v).map(([k,v])=>`${({like:'👍',thanks:'🙌',idea:'💡'})[k]||k} ${v}`).join(' · ')}`:''; + const el=document.querySelector(`[data-feedback="${c.id}"]`); + if(el)el.textContent=line+reactions; + const art=document.querySelector(`[data-open="${c.id}"]`); + if(art&&line)art.setAttribute('aria-label',`Open ${c.title}, ${line}`); + const ef=$('#editor-feedback'); + if(ef&&selected&&selected.id===c.id)ef.textContent=line+reactions; + return summary; + }catch{return null} +} +async function checkFeedback(){ + if(feedbackChecking)return;feedbackChecking=true; + const status=$('#library-feedback-status');if(status)status.textContent='Checking…'; + const shared=clips.filter(c=>isShared(c)); + let ok=0; + for(let i=0;ifetchFeedbackFor(c))); + ok+=results.filter(Boolean).length; + } + if(status)status.textContent=shared.length?(ok?'Up to date.':'Couldn\'t check for replies. Your recordings are safe.'):'No shared recordings to check.'; + if(libraryFilters.status==='open-threads'&&$('#library-grid'))renderLibrary(); + feedbackChecking=false; +} +function option(i,title,copy,id,enabled=true){return ``} +function resetURL(){if(objectURL)URL.revokeObjectURL(objectURL);objectURL=null} +function fitPlayer(video){if(!video)return;const fit=()=>{if(video.videoWidth&&video.videoHeight){video.style.aspectRatio=video.videoWidth+'/'+video.videoHeight;video.parentElement.style.setProperty('--media-ratio',video.videoWidth/video.videoHeight)}};video.addEventListener('loadedmetadata',fit);video.addEventListener('resize',fit);fit()} +function localVideo(){resetURL();if(!selected.blob)return '
Management access restored. The video file is not stored on this device. Use the shared viewer while the link is active.
';objectURL=URL.createObjectURL(selected.blob);return ``} +function editor(c){selected=c;editorMarks=null;const shareLocked=c.uploadAttempted&&!newShareIdentity(c),shared=isShared(c),cloud=!!(c.shared||c.revoked||c.uploadAttempted)&&!c.cloudDeleted&&!c.cloudMissing;shell(`

Review & share

${c.blob?'Saved on this device. Review your video before sharing.':'Manage your shared video.'}

${localVideo()}
More actions${c.originalFilename?`
Original filename${esc(c.originalFilename)}
`:''}
${c.blob?`
Trim video

Trim a new copy on this device. Trimming runs in real time — a 10-minute section takes about 10 minutes. You can cancel any time; the original is never modified. If you close the tab, no copy is saved.

`:''}${extrasPanel(c)}${c.sample?'
EXAMPLE FEEDBACK

One moment. A useful conversation.

Illustrative comments for this walkthrough.

Alex · Could the checkout button be clearer?

Sam · Yes — increase the contrast and keep the label short.

Alex · That works. Ready for another review.

':''}${c.blob?markupEditor():''}
`,'Recording','recording:'+c.id);fitPlayer($('#player'));$('#review-status').onchange=()=>run(async()=>{const field=$('#review-status'),next=field.value,old=c.reviewStatus||'needs-feedback';field.disabled=true;try{if((c.shared||c.uploadAttempted)&&!c.cloudDeleted&&!c.cloudMissing)await api('review-status',{id:c.id,owner:c.owner,reviewStatus:next});c.reviewStatus=next;await db.put(c);clips=await db.all();$('#review-status-message').textContent='Status saved.'}catch(e){field.value=old;throw e}finally{field.disabled=false}});if(isShared(c))fetchFeedbackFor(c); +mountExtras(c,{save:async extras=>{busy=true;try{if(c.shared&&!c.cloudDeleted)await api('details',{id:c.id,owner:c.owner,...extras});Object.assign(c,extras);await db.put(c);clips=await db.all()}finally{busy=false}},download:saveFile,error});if(c.blob)mountMarkupEditor(c);for(const b of document.querySelectorAll('[data-sample-time]'))b.onclick=()=>{$('#player').currentTime=Number(b.dataset.sampleTime);$('#player').play().catch(()=>{})};} +async function fixed(blob,seconds){return blob.type.startsWith('video/webm')?await new Promise(resolve=>fixDuration(blob,seconds*1000,resolve,{logger:false})):blob} +async function metadata(blob,knownDuration){const v=document.createElement('video'),url=URL.createObjectURL(blob);v.muted=true;v.preload='metadata';v.src=url;try{await new Promise((resolve,reject)=>{const t=setTimeout(()=>reject(Error('Could not read this video. Try another MP4 or WebM.')),10000);v.onloadedmetadata=()=>{clearTimeout(t);resolve()};v.onerror=()=>{clearTimeout(t);reject(Error('This file is not a playable video in this browser.'))}});let duration=knownDuration||v.duration;if(!Number.isFinite(duration))throw Error('This video has no readable duration. Re-export it as MP4 or WebM, then import again.');if(!v.videoWidth||!v.videoHeight)throw Error('This file does not contain a playable video track.');if(duration<=0||duration>LOCAL_MAX_SECONDS+1)throw Error('Choose a local video up to 30 minutes long.');v.currentTime=Math.min(.2,duration/2);await new Promise(resolve=>{v.onseeked=resolve;setTimeout(resolve,1200)});const canvas=document.createElement('canvas');canvas.width=480;canvas.height=Math.round(480*v.videoHeight/v.videoWidth);canvas.getContext('2d').drawImage(v,0,0,canvas.width,canvas.height);return{duration,thumbnail:canvas.toDataURL('image/jpeg',.6)}}finally{URL.revokeObjectURL(url)}} +async function importVideo(file,{sample=false,title}={}){if(busy||recording)return;busy=true;try{const media=await importMedia(file);const info=await metadata(media.blob),c={id:randomId(),owner:secret(),title:importTitle(file.name,title),originalFilename:file.name,blob:media.blob,type:media.type,createdAt:Date.now(),sample,...info};await db.put(c);clips=await db.all();editor(c)}finally{busy=false}} +function secret(){return[...crypto.getRandomValues(new Uint8Array(32))].map(n=>n.toString(16).padStart(2,'0')).join('')} +function markupTools(){return `
0 marks
`} +function fitCaptureFrame(video){const update=()=>{if(video.videoWidth&&video.videoHeight)video.parentElement.style.setProperty('--capture-ratio',video.videoWidth/video.videoHeight)};video.addEventListener('loadedmetadata',update);video.addEventListener('resize',update);update()} +function mountTools(items){markupUI=bindMarkup($('#markup-canvas'),items,n=>$('#markup-count').textContent=n+' marks',$('#markup-video'));$('#markup-tool').onchange=e=>markupUI.setKind(e.target.value);$('#undo-markup').onclick=()=>markupUI.undo();$('#clear-markup').onclick=()=>markupUI.clear()} +function updateCaptureMetrics(stats){ + if(!$('#record-size'))return; + $('#record-size').textContent=(stats.bytes/1e6).toFixed(1)+' MB'; + $('#record-remaining').textContent=`About ${formatTime(stats.remaining)} local recording left${stats.paused?' · paused':''}`; + $('#mic-meter').value=stats.level||0; + const message=$('#record-share-warning');message.textContent=!stats.shareable?'Past the sharing limit. Your local recording continues; trim or make a smaller copy before publishing.':stats.shareRemaining<60?`About ${formatTime(stats.shareRemaining)} left within sharing limits. Local recording can continue.`:''; +} +function mountCameraHandle(enabled){ + if(!enabled)return;const frame=$('#live-preview').parentElement,handle=document.createElement('button'); + handle.type='button';handle.className='camera-handle';handle.setAttribute('aria-label','Move camera bubble (arrow keys or drag)');handle.textContent='Move camera';frame.append(handle); + const place=()=>{const width=frame.clientWidth,height=frame.clientHeight,size=Math.min(width,height)*cameraBubble.size;cameraBubble.x=Math.max(0,Math.min(cameraBubble.x,1-size/width));cameraBubble.y=Math.max(0,Math.min(cameraBubble.y,1-size/height));handle.style.left=(cameraBubble.x*100)+'%';handle.style.top=(cameraBubble.y*100)+'%';handle.style.width=size+'px';handle.style.height=size+'px'}; + let dragging=false,dx=0,dy=0; + handle.onpointerdown=e=>{dragging=true;const r=handle.getBoundingClientRect();dx=e.clientX-r.left;dy=e.clientY-r.top;handle.setPointerCapture(e.pointerId);e.preventDefault()}; + handle.onpointermove=e=>{if(!dragging)return;const r=frame.getBoundingClientRect();cameraBubble.x=(e.clientX-r.left-dx)/r.width;cameraBubble.y=(e.clientY-r.top-dy)/r.height;place()}; + handle.onpointerup=handle.onpointercancel=()=>dragging=false; + handle.onkeydown=e=>{const dirs={ArrowLeft:[-.03,0],ArrowRight:[.03,0],ArrowUp:[0,-.03],ArrowDown:[0,.03]};if(dirs[e.key]){e.preventDefault();cameraBubble.x+=dirs[e.key][0];cameraBubble.y+=dirs[e.key][1];place()}}; + $('#bubble-size').oninput=e=>{cameraBubble.size=Number(e.target.value)/100;place()}; + $('#live-preview').addEventListener('loadedmetadata',place);place(); +} +function cancelCapture(){clearInterval(countdownTimer);capture?.cancel();capture=null;recording=false;busy=false;home()} +function beginRecording(){if(busy||!capture)return;busy=true;let n=3;const button=$('[data-action=begin-recording]');button.disabled=true;$('#capture-countdown').textContent=`Starting in ${n}…`;countdownTimer=setInterval(()=>{n--;if(n){$('#capture-countdown').textContent=`Starting in ${n}…`;return}clearInterval(countdownTimer);run(async()=>{try{capture.begin();recording=true;busy=false;paused=false;$('#capture-countdown').textContent='';$('.recording')?.classList.add('is-live');$('#capture-heading').textContent='Show what you mean.';$('#capture-status').textContent='Your video stays local. Stop to review and publish.';$('#setup-actions').hidden=true;$('#live-actions').hidden=false;$('#recording-status').textContent='RECORDING IN PROGRESS'}catch(e){cancelCapture();throw e}})},1000)} +async function startRecording(){if(recording||busy)return;if(emergencyBlob)throw Error('Download the unsaved recording and choose I saved my copy before recording again.');busy=true;const options={mic:$('#mic').checked,camera:$('#camera').checked,system:$('#system').checked,micId:$('#mic-source')?.value||'',defer:true,quality:$('#record-quality')?.value||'balanced',bubble:cameraBubble={x:.76,y:.72,size:.28},markup:recordMarkup=[]};draft={id:randomId(),chunks:[],createdAt:Date.now(),seconds:0};const writer=createDraftWriter(d=>db.saveDraft(d),()=>notify('Recovery storage is unavailable. Keep this tab open and download your video after stopping.'));const session=capture=new Capture({setupEnded:()=>{cancelCapture();notify('Screen sharing ended before recording. Choose a source again.')},chunk:(blob,seconds)=>{draft.chunks.push(blob);draft.seconds=seconds;if(seconds-(draft.savedSeconds||0)>=5){draft.savedSeconds=seconds;writer.save(structuredClone(draft))}},status:s=>{if($('#record-time'))$('#record-time').textContent=formatTime(s)},metrics:updateCaptureMetrics,finished:async(blob,duration,e,diagnostics)=>{busy=true;recording=false;try{writer.save(structuredClone(draft));await writer.flush();if(!blob.size)throw Error('No video was captured. Try recording again.');blob=await fixed(blob,duration);const info=await metadata(blob,duration),c={id:randomId(),owner:secret(),title:'A quick walkthrough',blob,type:blob.type.split(';')[0],createdAt:Date.now(),diagnostics,...info};await db.finish(c,draft.id);clips=await db.all();busy=false;editor(c);notify(stopMessage(e?'error':diagnostics?.reason))}catch(err){busy=false;if(!blob.size){home();error(err);return}resetURL();emergencyBlob=blob;emergencyURL=URL.createObjectURL(blob);shell(`

Download your recording now.

The captured video is still in this tab, but could not be saved to the local library. Download it before leaving or closing this tab.

`,'Recording');}}});try{const prepared=session.start(options);shell(`
BROWSER PERMISSION

Choose what to share.

Waiting for your browser’s screen picker or device permission. Nothing is recording yet.

Select a screen, window or tab in the browser prompt. Requests time out after one minute. If the prompt blocks this page, dismiss it in your browser. You can then retry or import a device recording.

`,'Recording permissions');const stream=await prepared;if(capture!==session)return;busy=false;recording=true;paused=false;shell(`
CHOOSE WHAT TO SHOW

Prepare your recording.

Nothing is recording yet. Add masks and marks on the preview, then begin.

${options.camera?'
Drag the camera handle to move it.
':''}${markupTools()}

Drag on the preview to add a mark (up to 40). Opaque masks cover pixels; soft blur is a visual effect and may leave details readable. Masks stay at fixed frame positions, so keep sensitive content inside them. Only frames captured after a change include that change. For full-screen walkthroughs, return here to change marks, or mask the saved video before publishing.

0 MBRemaining time is estimated while recording

Keep this tab open. Local recording stops at 30 minutes or 250 MB. Shared clips are limited to 10 minutes / 50 MB. Shared audio depends on your browser and source. Shortcuts: Alt+Shift+P pauses/resumes; Alt+Shift+S stops.
`,'Recording');$('#live-preview').srcObject=stream;fitCaptureFrame($('#live-preview'));$('#live-preview').play().catch(()=>{});mountTools(recordMarkup);mountCameraHandle(options.camera);updateCaptureMetrics({bytes:0,remaining:LOCAL_MAX_SECONDS,shareRemaining:MAX_SECONDS,level:0,shareable:true})}catch(e){session.cancel();if(capture!==session)return;capture=null;busy=false;recording=false;home();throw Error(e.name==='NotAllowedError'?'Recording permission was declined. Nothing was uploaded. Try again or import a video.':e.message)}} +async function publish(){let c=selected?{...selected,title:validTitle($('#recording-title-input')?$('#recording-title-input').value:selected.title)}:null;if(!health||!c?.blob)throw Error('Sharing is not available yet.');const problem=sharingProblem(c);if(problem)throw Error(problem);const {linkDays,password,newIdentity}=shareOptions(c,Number($('#link-days')?.value||c.linkDays||7),$('#share-password')?.value||'');if(newIdentity){c={...c,id:randomId(),owner:secret(),revoked:false,shared:false,cloudDeleted:false,cloudMissing:false,uploadAttempted:false,passwordProtected:!!password};await db.put(c);selected=c;clips=await db.all()}c.linkDays=linkDays;c.passwordProtected=!!password||!!c.passwordProtected;let savedLocally=false;busy=true;uploadController=new AbortController();const button=$('[data-action=publish]');button.disabled=true;try{const input={id:c.id,owner:c.owner,title:c.title,type:c.type,duration:c.duration,width:c.width,height:c.height,size:c.blob.size,start:0,end:c.duration,linkDays,password,captions:c.captions||[],chapters:c.chapters||[],report:c.report||null,reviewStatus:c.reviewStatus||'needs-feedback'};$('#cancel-upload').hidden=false;$('#upload-meter').hidden=false;$('#upload-meter').value=0;$('#upload-progress').textContent='Preparing a private upload…';c.uploadAttempted=true;await db.put(c);selected=c;savedLocally=true;let reservation;try{reservation=await retryTransfer(()=>api('reserve',input),attempt=>$('#upload-progress').textContent=`Sharing service interrupted. Retrying upload setup (${attempt}/3)…`)}catch(e){if(e.status!==409)throw e;const state=await api('manage',{id:c.id,owner:c.owner});if(!['expired','deleted','revoked'].includes(state.status))throw e;c.revoked=true;await db.put(c);busy=false;uploadController=null;return await publish()}const uploaded=new Set(reservation.status==='published'?[]:(await retryTransfer(()=>api('upload-state',{id:c.id,owner:c.owner}))).parts||[]);$('#upload-progress').textContent=uploaded.size?'Resuming saved upload… Your local copy is safe.':'Uploading video… Your local copy is safe.';for(let part=0,offset=0;reservation.status!=='published'&&offset{const reader=new FileReader();reader.onload=()=>resolve(reader.result.split(',')[1]);reader.onerror=()=>reject(Error('Could not read the local video.'));reader.readAsDataURL(chunk)});await retryTransfer(()=>api('upload-chunk',{id:c.id,owner:c.owner,part,data}),attempt=>$('#upload-progress').textContent=`Connection interrupted. Retrying part ${part+1} (${attempt}/3)…`);$('#upload-meter').value=Math.round(Math.min(c.blob.size,offset+CHUNK_BYTES)/c.blob.size*100);$('#upload-progress').textContent=`Uploading ${Math.round(Math.min(c.blob.size,offset+CHUNK_BYTES)/c.blob.size*100)}% · your local copy is safe.`}$('#upload-progress').textContent='Finalizing your video…';const shared=await retryTransfer(()=>api('publish',{id:c.id,owner:c.owner}),attempt=>$('#upload-progress').textContent=`Sharing service interrupted. Retrying finalization (${attempt}/3)…`);c.shared=true;c.uploadPaused=false;c.passwordProtected=shared.passwordProtected;c.expiresAt=shared.expiresAt;await db.put(c);clips=await db.all();busy=false;editor(c);notify('Your link is ready. The local copy is still here.')}catch(e){busy=false;if(savedLocally){if(e.name==='AbortError')c.uploadPaused=true;await db.put(c);editor(c)}throw e}finally{uploadController=null;busy=false;button.disabled=false}} +function saveFile(blob,name){const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=name;document.body.append(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),60000)} +function download(){const a=document.createElement('a');a.href=objectURL||URL.createObjectURL(selected.blob);a.download=selected.title.replace(/[^\p{L}\p{N} _-]/gu,'').slice(0,80)+(selected.type==='video/mp4'?'.mp4':'.webm');document.body.append(a);a.click();a.remove()} +function privacy(){if(recording||busy)return;shell(`
CLEAR BY DEFAULT

Your screen.
Your call.

ScreenNote only uploads a video when you choose Publish. Recording and trimming happen in your browser.

Before you publish

Recordings and recovery chunks are stored in this browser. Download videos you want to keep. Clearing site data, private browsing or losing this device can remove your local library.

After you publish

Older links from the previous storage service may be unavailable. Their videos have not been copied while that service denies access. If you have the original local video, refresh its shared status and publish a replacement link. Keep your original recovery keys.

When you publish, a separate video copy is stored in a private Cloudflare R2 bucket. Share metadata and discussion are stored in Cloudflare D1. An unlisted link lets anyone who has it watch and reply without a ScreenNote account. Do not include passwords or information you do not want the recipient to see. Unlisted does not mean encrypted end to end.

Links expire after 1, 3 or 7 days, as chosen before publication. Optional sharing passwords are verified on the server; issued playback URLs are bearer links with a five-minute lifetime. Captions, chapters and bug-report text you save are shared with viewers. Stop sharing blocks new viewer requests; already issued playback URLs may work for up to five more minutes. A scheduled cleanup checks expired shares and abandoned media every 15 minutes. Unreferenced objects are retained for a grace period before deletion. A short cleanup delay may occur after a link expires.

Small, honest first release

Back up your recovery keys to restore management access after changing browsers or clearing site data. Keep them private: they authorize stopping sharing and deleting uploads. Videos are not included.

Clips are limited to ten minutes and 50 MB. Shared uploads use a 1 GB storage budget. Pending uploads reserve space for both chunks and the assembled video. Deleting an uploaded video frees its slot after cleanup succeeds. Old expired uploads are also reclaimed when capacity is full. Local recording and downloads remain usable when sharing is full. Hosting quotas may pause online sharing; no paid upgrade is enabled by this application.

Screen capture needs a supported desktop browser. On phones or browsers without screen capture, record with your device and import MP4 or WebM. Camera, microphone and shared-screen audio require your browser’s permissions. Online sharing uses Supabase private file storage and a database for recording details and feedback. The application is served by Cloudflare Workers. No AI analysis, advertising trackers or per-viewer charges are built in.

Replies and reactions

Replies are visible to everyone with the link. Names are self-entered, not verified identities. You can reply to any comment or reply. New replies reopen resolved threads. Comment authors can edit or remove their comments from the browser that posted them; the video creator can also remove comments and resolve threads. Clearing site data loses anonymous comment controls. Unsent drafts are kept in this tab’s session storage. Optional bubbles preview comments in the inline player; native fullscreen and picture in picture show the video only. Each clip supports 100 total comments and replies, including removed entries. Reactions use an anonymous browser identifier and are not verified unique-person counts.

`,'Privacy')} +function recovery(){if(recording||busy)return;shell(`
KEEP CONTROL

Take your keys with you.

A private recovery file restores the ability to stop sharing or delete your uploaded videos from another browser at this same ScreenNote address.

Back up management access

Keep this file private. Anyone with its keys can manage the uploads. It contains no video files: download videos separately.

Restore your keys

Choose a recovery file, or paste its complete JSON below. Keys are checked with the sharing service before saving. Existing local videos remain intact.

`,'Recovery');$('#recovery-file').onchange=e=>run(async()=>{const file=e.target.files[0];if(!file)return;if(file.size>524288)throw Error('Choose a recovery file smaller than 512 KB.');$('#recovery-json').value=await file.text()})} +async function restoreKeys(){const keys=recoveryKeys($('#recovery-json').value,location.origin);busy=true;const button=$('[data-action=restore-keys]');button.disabled=true;let restored=0,failed=0,videoFailed=0;try{for(const key of keys){$('#recovery-progress').textContent=`Checking key ${restored+failed+1} of ${keys.length}…`;try{const state=await api('manage',key),current=clips.find(c=>c.id===key.id);if(current&¤t.owner!==key.owner)throw Error('This recording belongs to another key.');const record={...current,...state,...key,shared:state.status==='published',revoked:['revoked','expired','deleted'].includes(state.status),uploadAttempted:true,cloudDeleted:state.cleanupComplete,managementOnly:!current?.blob};await db.put(record);clips=await db.all();if($('#restore-videos').checked&&state.status==='published'&&state.expiresAt>Date.now()&&!record.blob){try{const response=await fetch(await api('restore-media',key).then(v=>v.mediaUrl));if(!response.ok)throw Error('Video download failed.');const file=new File([await response.blob()],record.title+'.'+(record.type==='video/mp4'?'mp4':'webm'),{type:record.type});const media=await importMedia(file),info=await metadata(media.blob);record.blob=media.blob;Object.assign(record,info,{managementOnly:false})}catch{videoFailed++}}await db.put(record);clips=await db.all();restored++}catch{failed++}}$('#recovery-json').value='';$('#recovery-file').value='';$('#recovery-progress').textContent=`Restored ${restored} recording${restored===1?'':'s'}.${failed?' '+failed+' key(s) could not be verified. Keep your file and retry when sharing is available.':''} ${videoFailed?' '+videoFailed+' video download(s) could not finish; management keys were restored. Keep the recovery file to retry.':''} Open My recordings to manage them.`}finally{busy=false;button.disabled=false}} +function dialog(title,body,save,label='Save'){ + const opener=document.activeElement;modal.onclose=()=>{const target=opener?.isConnected?opener:$('#main');target?.focus({preventScroll:true})}; + let saving=false; + modal.innerHTML=`

${title}

${body}
`; + modal.oncancel=e=>{if(saving)e.preventDefault()}; + $('#cancel-dialog').onclick=()=>{if(!saving)modal.close()}; + $('#dialog-form').onsubmit=async e=>{ + e.preventDefault();if(saving)return;$('#dialog-error').textContent=''; + const data=new FormData(e.target),controls=[...e.target.querySelectorAll('button,input,textarea')].map(node=>({node,disabled:node.disabled})); + saving=true;busy=true;for(const {node} of controls)node.disabled=true; + try{await save(data);modal.close()}catch(err){$('#dialog-error').textContent=err.message} + finally{saving=false;busy=false;for(const {node,disabled} of controls)node.disabled=disabled} + };modal.showModal(); +} +async function run(fn){try{if($('#error'))$('#error').textContent='';await fn()}catch(e){error(e)}} +function encodeProgress(meterEl,statusEl,label){ + const started=performance.now();let lastDecile=-1; + return frac=>{ + const pct=Math.round(Math.min(1,Math.max(0,frac))*100); + if(meterEl){meterEl.hidden=false;meterEl.value=pct} + const decile=Math.floor(pct/10); + if(decile!==lastDecile){ + lastDecile=decile; + const elapsed=(performance.now()-started)/1000; + const eta=pct>=5&&pct<100?` · about ${formatTime(Math.max(0,elapsed/Math.max(frac,0.01)-elapsed))} left`:''; + if(statusEl)statusEl.textContent=`${label} · ${pct}%${eta} · original stays in your library.`; + } + }; +} +function showEncodeCancel(show=true){for(const id of ['cancel-trim','cancel-marked']){const b=document.getElementById(id);if(b)b.hidden=!show}} +const actions={'bug-report':()=>{const panel=$('.extra-panel');panel.open=true;panel.scrollIntoView({block:'nearest',behavior:'smooth'});$('#report-actual').focus()},'cancel-trim':()=>{encodeController?.abort()},'cancel-upload':()=>uploadController?.abort(Object.assign(Error('Upload paused. Your local copy is safe. Publish again to resume saved parts.'),{name:'AbortError'})),'new-recording':()=>{const setup=$('#record-setup');setup.open=true;setup.scrollIntoView({block:'nearest',behavior:'smooth'});(setup.querySelector('[data-action=record]:not(:disabled)')||$('#import-video')).focus()},'clear-filters':()=>{libraryFilters={query:'',status:'all',sort:'newest'};home()}, +'check-replies':()=>{checkFeedback()},help,'check-sharing':checkSharing,'list-mics':listMicrophones,'begin-recording':beginRecording,'cancel-capture':cancelCapture,recovery,'acknowledge-recovery':()=>{emergencyBlob=null;if(emergencyURL)URL.revokeObjectURL(emergencyURL);emergencyURL=null;home()},'refresh-share':async()=>{const c=selected;busy=true;try{const state=await api('manage',{id:c.id,owner:c.owner});Object.assign(c,state,{shared:state.status==='published',revoked:['revoked','expired','deleted'].includes(state.status),cloudDeleted:state.cleanupComplete});await db.put(c);clips=await db.all();busy=false;editor(c);notify('Shared status refreshed.')}catch(e){if(e.status!==404)throw e;c.shared=false;c.revoked=true;c.cloudMissing=true;await db.put(c);clips=await db.all();busy=false;editor(c);notify(c.blob?'The previous upload is unavailable. Your local video is safe; publish a replacement link.':'The previous upload is unavailable. Import the original video to publish a replacement link.')}finally{busy=false}},'backup-library':async()=>{if(!clips.length)throw Error('There are no local recordings to back up yet.');const status=$('#library-backup-status'),button=$('[data-action=backup-library]');button.disabled=true;try{const backup=await makeLibraryBackup(clips,p=>{if(status)status.textContent='Preparing secure backup · '+p+'%'});saveFile(backup,'screennote-library-'+new Date().toISOString().slice(0,10)+'.snbackup');if(status)status.textContent='Backup downloaded · '+clips.length+' recordings · '+formatBytes(backup.size);notify('Full library backup downloaded. Keep it private; it includes videos and management keys.')}finally{button.disabled=false}},'backup-keys':()=>{const raw=recoveryDocument(clips,location.origin);if(!JSON.parse(raw).keys.length)throw Error('No uploaded recordings need recovery keys yet.');saveFile(new Blob([raw],{type:'application/json'}),'screennote-recovery.json');notify('Recovery keys downloaded. Keep this file private; download videos separately.')},'restore-keys':restoreKeys,'delete-cloud':()=>dialog('Delete the uploaded video?',`

This permanently deletes the uploaded video and stops its shared link. ${selected.blob?'Your local file remains saved on this device.':'There is no local video file on this device.'}

`,async()=>{await api('delete',{id:selected.id,owner:selected.owner});selected.shared=false;selected.revoked=true;selected.cloudDeleted=true;await db.put(selected);clips=await db.all();editor(selected)},'Delete uploaded video'),home:()=>{if(location.pathname.startsWith('/v/'))location.assign('/');else home()},privacy,record:startRecording,stop:()=>{capture.stop();$('#record-time').textContent='Saving…';$('#pause-button').disabled=true;$('[data-action=stop]').disabled=true;},pause:()=>{paused=!paused;paused?capture.pause():capture.resume();$('#pause-button').innerHTML=icon(paused?'play':'pause')+(paused?'Resume':'Pause');$('#recording-status').textContent=paused?'PAUSED · NOT CAPTURING':'RECORDING IN PROGRESS';$('.recording')?.classList.toggle('is-paused',paused)},theme:()=>{const theme=document.documentElement.dataset.theme==='dark'?'light':'dark';document.documentElement.dataset.theme=theme;try{localStorage.setItem('screennote-theme',theme)}catch{}},compress:async()=>{const c=selected;if(!c?.blob||c.duration>MAX_SECONDS)throw Error('Trim a clip up to 10 minutes first.');busy=true;const b=$('[data-action=compress]');b.disabled=true;try{notify('Making a smaller copy at playback speed. Keep this tab visible.');encodeController=new AbortController();showEncodeCancel(true);const blob=await fixed(await trimVideo(c.blob,0,c.duration,encodeProgress($('#upload-meter'),$('#upload-progress'),'Making smaller copy'),[],'saver',{signal:encodeController.signal}),c.duration),info=await metadata(blob,c.duration);if(blob.size>=c.blob.size)throw Error('This copy would not be smaller. Try trimming a shorter section instead.');const copy={...c,id:randomId(),owner:secret(),title:c.title.slice(0,80)+' · smaller',blob,...info,shared:false,revoked:false,uploadAttempted:false,passwordProtected:false,cloudDeleted:false,cloudMissing:false,createdAt:Date.now()};await db.put(copy);clips=await db.all();busy=false;editor(copy);notify(sharingProblem(copy)||'Smaller copy saved. Your original stays in your library.')}catch(e){if(e.name==='AbortError'){notify('Smaller copy stopped. Your original is unchanged.');return}throw e}finally{encodeController=null;showEncodeCancel(false);busy=false;b.disabled=false}},sample:async()=>{const r=await fetch('/sample.webm');if(!r.ok)throw Error('Sample clip is unavailable. Import your own video.');await importVideo(new File([await r.blob()],'A little context goes a long way.webm',{type:'video/webm'}),{sample:true,title:'A clearer checkout · sample walkthrough'});Object.assign(selected,{captions:[{start:0,end:4,text:'Show the detail that needs attention.'},{start:4,end:9,text:'Add a timestamp so feedback points to the right moment.'},{start:9,end:15,text:'Reply, resolve and keep the work moving.'}],chapters:[{time:0,title:'Show the detail'},{time:5,title:'Pin the feedback'},{time:10,title:'Resolve the conversation'}]});await db.put(selected);editor(selected)},download,publish,'copy-link':async()=>{const link=location.origin+'/v/'+selected.id;try{await navigator.clipboard.writeText(link);notify('Link copied.')}catch{dialog('Your share link',`
`,async()=>{},'Done')}},'save-title':async()=>{const c=selected,title=validTitle($('#recording-title-input').value);busy=true;try{if((c.shared||c.uploadAttempted)&&!c.cloudDeleted&&!c.cloudMissing){try{await api('title',{id:c.id,owner:c.owner,title})}catch(e){if(e.status!==404||c.shared)throw e}}const saved={...c,title};await db.put(saved);selected=saved;clips=await db.all();$('#title-status').textContent='Title saved.'}finally{busy=false}},rename:()=>dialog('Give it a clear title',`
`,async f=>{const title=f.get('title').trim();if(!title)throw Error('Add a title.');selected.title=title;await db.put(selected);clips=await db.all();editor(selected)}),'remove-local':()=>dialog(selected.blob?'Remove this local copy?':'Remove recovery access?',`

${selected.blob?'This removes the video from this browser.':'This removes the saved management keys from this browser.'} ${(selected.shared||selected.revoked||selected.uploadAttempted)&&!selected.cloudDeleted?'This also removes this browser’s ability to manage the uploaded video. Delete the uploaded video first if you want to remove it from the web.':selected.blob?'Download it first if you want to keep it.':'Keep an exported recovery file if you need this access later.'}

`,async()=>{clearSeen(selected.id);await db.remove(selected.id);clips=await db.all();busy=false;home()},selected.blob?'Remove local copy':'Remove recovery access'),revoke:()=>dialog('Stop sharing this video?',`

New viewers will no longer be able to open it. Playback URLs already issued may work for up to five minutes. ${selected.blob?'Your local video stays here.':'Your recovered management keys stay here.'}

`,async()=>{await api('revoke',{id:selected.id,owner:selected.owner});selected.shared=false;selected.revoked=true;await db.put(selected);clips=await db.all();editor(selected)},'Stop sharing'),trim:async()=>{const c=selected,start=Number($('#trim-start').value),end=Number($('#trim-end').value);if(!Number.isFinite(start)||!Number.isFinite(end)||start<0||end>c.duration+.05||end-start<.25)throw Error('Choose a valid range of at least 0.25 seconds.');busy=true;$('[data-action=trim]').disabled=true;encodeController=new AbortController();showEncodeCancel(true);try{let blob=await trimVideo(c.blob,start,end,encodeProgress($('#trim-meter'),$('#trim-progress'),'Trimming locally'),[],'balanced',{signal:encodeController.signal});blob=await fixed(blob,end-start);const info=await metadata(blob,end-start),copy={id:randomId(),owner:secret(),title:c.title.slice(0,85)+' · trimmed',...trimExtras(c,start,end),blob,type:blob.type.split(';')[0],createdAt:Date.now(),...info};await db.put(copy);clips=await db.all();busy=false;editor(copy);notify('Trimmed copy saved. The original is still in your library.')}catch(e){if(e.name==='AbortError'){const s=$('#trim-progress');if(s)s.textContent='Trim stopped. Your original is unchanged.';const m=$('#trim-meter');if(m)m.hidden=true;showEncodeCancel(false);encodeController=null;busy=false;const bb=$('[data-action=trim]');if(bb)bb.disabled=false;return}throw e}finally{encodeController=null;showEncodeCancel(false);busy=false;const b=$('[data-action=trim]');if(b)b.disabled=false}}}; +app.addEventListener('click',async e=>{const b=e.target.closest('[data-action],[data-open],[data-rename]');if(!b||b.disabled||busy&&!['cancel-capture','cancel-upload','cancel-trim'].includes(b.dataset.action))return;if((b.dataset.open||['home','help','privacy','recovery','refresh-share'].includes(b.dataset.action))&&!(await confirmEditorLeave()))return;if(b.dataset.rename){const c=clips.find(c=>c.id===b.dataset.rename);dialog('Rename recording',`
`,async f=>{const title=validTitle(f.get('title'));if((c.shared||c.uploadAttempted)&&!c.cloudDeleted&&!c.cloudMissing)await api('title',{id:c.id,owner:c.owner,title});c.title=title;await db.put(c);clips=await db.all();renderLibrary()});return}if(b.dataset.open){editor(clips.find(c=>c.id===b.dataset.open));return}run(()=>actions[b.dataset.action]?.())}); +window.addEventListener('beforeunload',e=>{if(recording||busy||emergencyBlob||unsavedChanges().length){e.preventDefault();e.returnValue=''}}); +async function viewerPage(id){try{await db.open();const local=await db.get(id);viewerOwner=local?.owner||''}catch{viewerOwner=''}try{vote=localStorage.getItem('screennote-vote-'+id)||''}catch{}app.innerHTML=`
${brand()}Make your own video ${icon('arrow')}

Opening your message…

`;try{viewData=await api('view',viewerPassword?{id,accessPassword:viewerPassword}:null,id);renderViewer()}catch(e){if(e.status===401){$('#main').innerHTML=`

A password keeps this video private.

${viewerPassword?'Password not accepted. ':''}Ask the sender for the sharing password.

`;$('#unlock-form').onsubmit=e=>{e.preventDefault();viewerPassword=$('#viewer-password').value;run(()=>viewerPage(id))};return}$('#main').innerHTML=`

This message is unavailable.

The link may have expired, stopped sharing, or the hosting service may be unavailable.

Open ScreenNote`}} +function renderViewer(){ + discussionUI?.destroy();const c=viewData;writeSeen(c.id,c.discussionRevision||0); + $('#main').innerHTML=`
A LITTLE CONTEXT FOR YOU

${esc(isGeneratedTitle(c.title)?'Untitled recording':c.title)}

${reviewLabel(c.reviewStatus)}

${document.pictureInPictureEnabled?'':''}
${[['like','👍','Helpful'],['thanks','🙌','Thanks'],['idea','💡','Good idea']].map(([key,emoji,label])=>``).join('')}

${formatTime(c.end-c.start)} · Link expires ${new Date(c.expiresAt).toLocaleDateString()}
Anyone with this link can see replies. Guest names are not verified.

${viewerContext(c)}
`; + const p=$('#viewer-player');fitPlayer(p);mountViewerContext(c,p,saveFile); + $('#playback-speed').onchange=e=>p.playbackRate=Number(e.target.value); + if($('#picture-in-picture'))$('#picture-in-picture').onclick=()=>run(async()=>{if(document.pictureInPictureElement)await document.exitPictureInPicture();else await p.requestPictureInPicture()}); + p.onloadedmetadata=()=>p.currentTime=c.start; + p.onplay=()=>{if(p.currentTime>=c.end-.05)p.currentTime=c.start}; + p.ontimeupdate=()=>{if(p.currentTime>c.end){p.pause();p.currentTime=c.end}}; + p.onerror=()=>error(Error('This video could not play here. Refresh the conversation to renew playback access, or try desktop Chrome or Safari.')); + discussionUI=mountDiscussion({clip:c,player:p,panel:$('.reply-panel'),api,owner:viewerOwner,viewer,accessPassword:viewerPassword,update:next=>viewData=next,notify,error}); + $('#refresh-replies').onclick=()=>run(async()=>{ + const button=$('#refresh-replies');button.disabled=true;try{ + const next=await api('view',viewerPassword?{id:c.id,accessPassword:viewerPassword}:null,c.id);viewData=next;$('#viewer-review').textContent=reviewLabel(next.reviewStatus);$('#viewer-review').dataset.review=next.reviewStatus||'needs-feedback'; + $('#main h1').textContent=isGeneratedTitle(next.title)?'Untitled recording':next.title; + const time=p.currentTime,playing=!p.paused;p.onloadedmetadata=()=>{p.currentTime=Math.max(c.start,Math.min(c.end,time));if(playing)p.play().catch(()=>{})};p.src=next.mediaUrl; + discussionUI.update(next);for(const b of document.querySelectorAll('[data-reaction]'))b.querySelector('span').textContent=next.reactions[b.dataset.reaction];notify('Conversation and playback access refreshed. Your draft is kept.') + }finally{button.disabled=false} + }); + $('.reactions').onclick=e=>run(async()=>{const b=e.target.closest('[data-reaction]');if(!b||document.querySelector('.reactions button:disabled'))return;const buttons=[...document.querySelectorAll('[data-reaction]')];for(const button of buttons)button.disabled=true;const next=vote===b.dataset.reaction?'':b.dataset.reaction;try{const updated=await api('reaction',{id:c.id,accessPassword:viewerPassword,viewer,reaction:next});vote=next;try{localStorage.setItem('screennote-vote-'+c.id,vote)}catch{}viewData={...viewData,...updated};discussionUI.update(viewData);for(const button of buttons){button.setAttribute('aria-pressed',String(button.dataset.reaction===vote));button.querySelector('span').textContent=updated.reactions[button.dataset.reaction]}}finally{for(const button of buttons)button.disabled=false}}) +} +async function listMicrophones(){if(!navigator.mediaDevices?.enumerateDevices)throw Error('This browser chooses the microphone in its permission prompt.');const devices=await navigator.mediaDevices.enumerateDevices(),mics=devices.filter(d=>d.kind==='audioinput'&&d.deviceId);const select=$('#mic-source');select.innerHTML=''+mics.map((d,i)=>``).join('');notify(mics.length?'Choose your microphone source. Labels may appear only after permission is granted.':'No named inputs are available yet. Browser default will use its permission chooser.')} +function markupEditor(){return `
Annotate or hide sensitive areas

Create a new video with marks burned into every frame. Your original stays unchanged and must not be shared if it contains secrets. Pause the preview, then draw fixed masks or marks. Check the new copy before publishing.

${markupTools()}

`} +function mountMarkupEditor(c){const video=$('#markup-video');video.src=objectURL;fitCaptureFrame(video);const items=[];editorMarks=items;mountTools(items);$('#markup-toggle').onclick=()=>video.paused?video.play().catch(error):video.pause();$('#choose-thumbnail').onclick=()=>run(async()=>{if(video.readyState<2)throw Error('Wait for the video preview to load.');const canvas=document.createElement('canvas');canvas.width=480;canvas.height=Math.round(480*video.videoHeight/video.videoWidth);canvas.getContext('2d').drawImage(video,0,0,canvas.width,canvas.height);c.thumbnail=canvas.toDataURL('image/jpeg',.7);await db.put(c);clips=await db.all();notify('Library thumbnail updated on this device.')});$('#save-marked').onclick=()=>run(async()=>{if(!items.length)throw Error('Draw at least one mark on the preview.');busy=true;$('#save-marked').disabled=true;encodeController=new AbortController();showEncodeCancel(true);try{const blob=await fixed(await trimVideo(c.blob,0,c.duration,encodeProgress($('#marked-meter'),$('#marked-progress'),`Saving marked copy · ${items.length} marks`),structuredClone(items),'balanced',{signal:encodeController.signal}),c.duration),info=await metadata(blob,c.duration),copy={id:randomId(),owner:secret(),title:c.title.slice(0,80)+' · marked',...trimExtras(c,0,c.duration),blob,type:blob.type.split(';')[0],createdAt:Date.now(),...info};await db.put(copy);clips=await db.all();busy=false;editor(copy);notify('Marked copy saved. Review it before publishing. The original is still in your library.')}catch(e){if(e.name==='AbortError'){const s=$('#marked-progress');if(s)s.textContent='Marked copy stopped. Your original is unchanged.';return}throw e}finally{encodeController=null;showEncodeCancel(false);busy=false;const b=$('#save-marked');if(b)b.disabled=false}})} +function help(){if(recording||busy)return;shell(`
A CLEAR FIRST MESSAGE

Show the problem.
Share the moment.

Record or import a short video, review your local copy, then publish when ready. Viewers need no account. ScreenNote is a limited free beta; no payment or subscription is enabled.

Record with confidence

  1. Use a desktop browser with screen capture, or import a device recording on mobile.
  2. Choose microphone, camera and screen audio, then choose the source in your browser.
  3. Add fixed masks and marks in setup. Begin starts a three-second countdown.
  4. Stop and review the whole video, especially any sensitive areas. Download a backup.
  5. Add optional captions, chapters or a bug report. Publish explicitly.

ScreenNote cannot silently capture a screen. Permission is required each session. If your source or audio is unavailable, choose another source or import a video.

Keyboard & playback

While recording: Alt+Shift+P pauses/resumes; Alt+Shift+S stops. In a video view: K plays/pauses, J/L seek five seconds, M toggles mute. Shortcuts do not run while typing in a field.

Native video controls provide fullscreen and captions. The viewer also has playback speed and picture in picture when the browser supports it.

Private by choice

Anyone with an unlisted link can view it unless you set a sharing password. Send that password separately. Playback links already issued can work for up to five minutes after revocation. Export management keys and download videos separately.

Recording & sharing limits

Local recording and import: up to 30 minutes / 250 MB. Shared video: up to 10 minutes / 50 MB. Shared storage has a 1 GB budget across the app; smaller videos leave room for more recordings. Links expire after 1, 3 or 7 days. Capacity or hosting quotas can pause sharing; local tools remain available.

Captions are supplied by you in SRT/WebVTT format. No paid transcription service, AI analysis or advertising tracker runs here. Browser storage can be lost; keep downloads.

Help validate this beta

Try a short, non-sensitive recording. Check playback, audio, captions and feedback with your recipient. Download a local test report to share through your own channel. No personal information is required, and feedback is not sent automatically.

Real Android, iOS, Safari, tablet and native permission testing remains a release gate. This app does not promise universal browser support.

`,'Help')} +actions['beta-feedback']=()=>dialog('Report your test',`

Save this report locally. Nothing is sent automatically.

`,async f=>saveFile(new Blob([JSON.stringify({version:APP_VERSION,device:f.get('device'),task:f.get('task'),result:f.get('result')},null,2)],{type:'application/json'}),'screennote-beta-test.json'),'Download test report'); +document.addEventListener('keydown',e=>{if(e.target.closest('input,textarea,select,[contenteditable=true]')||modal.open)return;if(busy)return;if(e.altKey&&e.shiftKey){if(capture?.begun&&recording&&e.code==='KeyP'){e.preventDefault();actions.pause()}if(capture?.begun&&recording&&e.code==='KeyS'){e.preventDefault();actions.stop()}return}if(e.ctrlKey||e.metaKey||e.altKey)return;const p=$('#viewer-player')||$('#player');if(!p)return;if(e.code==='KeyK'){e.preventDefault();p.paused?p.play().catch(()=>{}):p.pause()}else if(e.code==='KeyJ'||e.code==='KeyL'){e.preventDefault();p.currentTime=Math.min(p.duration||0,Math.max(0,p.currentTime+(e.code==='KeyJ'?-5:5)))}else if(e.code==='KeyM'){e.preventDefault();p.muted=!p.muted}}); + +async function boot(){const match=location.pathname.match(/^\/v\/([a-f0-9-]{36})$/);if(match||location.pathname.startsWith('/v/')){await viewerPage(match?.[1]||location.pathname.slice(3));return}try{await db.open();libraryReady=true;clips=await db.all();home();checkSharing();const drafts=await db.all('drafts');if(drafts.some(d=>d.chunks.length)){dialog('A recording was interrupted',`

ScreenNote found saved recording chunks on this device. Recover the most recent partial recording? Some browsers may not be able to play an interrupted file.

`,async()=>{const d=drafts.filter(d=>d.chunks.length).sort((a,b)=>b.createdAt-a.createdAt)[0],blob=await fixed(new Blob(d.chunks,{type:d.chunks[0].type}),d.seconds);const info=await metadata(blob,d.seconds),c={id:randomId(),owner:secret(),title:'Recovered recording',blob,type:blob.type.split(';')[0],createdAt:Date.now(),...info};await db.finish(c,d.id);clips=await db.all();editor(c)},'Recover recording')}}catch(e){app.innerHTML=`

We couldn’t open your local library.

${esc(e.message)}

Use a regular browser with device storage enabled. Do not clear site data if you have recordings saved here.

`}} +boot().then(async()=>{if(!globalThis.AppHost)return;const id=new URLSearchParams(location.search).get('nativeRecording');if(!/^[a-f0-9-]{36}$/.test(id||''))return;try{const response=await fetch('/__native_recordings/'+id);if(!response.ok)throw Error('This native recording is unavailable. Open Recordings to choose it again.');const blob=await response.blob();await importVideo(new File([blob],'Screen recording.mp4',{type:'video/mp4'}));history.replaceState(null,'','/')}catch(e){error(e)}}); + +if(globalThis.AppHost)window.handleAndroidBack=()=>{if(busy||recording)return true;if(modal.open){modal.close();return true}if(selected){confirmEditorLeave().then(ok=>{if(ok)home()});return true}return false}; + +if(globalThis.AppHost)window.requestAndroidHome=()=>{if(!busy&&!recording)confirmEditorLeave().then(ok=>{if(ok)home()});return true}; + +if(globalThis.AppHost)window.confirmAndroidRecordingImport=()=>{if(busy||recording||emergencyBlob){notify("Finish the current operation and save any recovered video before importing a recording.");return false}confirmEditorLeave().then(ok=>{if(ok)home()});return true}; + diff --git a/rebuild/legacy/public/capture.js b/rebuild/legacy/public/capture.js new file mode 100644 index 0000000..23bcb38 --- /dev/null +++ b/rebuild/legacy/public/capture.js @@ -0,0 +1,35 @@ +import {profileFor,recordingStats} from '../lib/recording-policy.js'; +import {LOCAL_MAX_BYTES,LOCAL_MAX_SECONDS} from '../lib/rules.js'; +import {paintMarkup} from './markup.js'; +export function chooseMime(Recorder=globalThis.MediaRecorder){return['video/webm;codecs=vp8,opus','video/webm','video/mp4'].find(t=>Recorder?.isTypeSupported(t))||''} +export function release(streams){for(const s of streams)for(const t of s?.getTracks()||[])t.stop()} +export class Capture{ + constructor({chunk,finished,status,setupEnded,metrics=()=>{},permissionTimeoutMs=60000}){this.metrics=metrics;this.bytes=0;this.stopReason='user';this.permissionTimeoutMs=permissionTimeoutMs;this.permissionAbort=new AbortController();this.onSetupEnded=setupEnded;this.onchunk=chunk;this.finished=finished;this.status=status;this.streams=[];this.chunks=[];this.started=0;this.elapsed=0;this.stopping=false} + async start({camera=false,mic=true,system=false,micId='',defer=false,markup=null,quality='balanced',bubble={x:.8,y:.76,size:.18}}){try{this.quality=quality;this.profile=profileFor(quality);this.bubble=bubble;if(!navigator.mediaDevices?.getDisplayMedia||!globalThis.MediaRecorder)throw Error('Screen recording is not supported here. Use desktop Chrome or Edge, or import a video recorded on your device.');const Audio=globalThis.AudioContext||globalThis.webkitAudioContext;if((mic||system)&&Audio){this.audio=new Audio();this.audio.resume().catch(()=>{})}const screen=await this.requestMedia(()=>navigator.mediaDevices.getDisplayMedia({video:{frameRate:this.profile.fps,width:{ideal:this.profile.width},height:{ideal:Math.round(this.profile.width*9/16)}},audio:system}));this.streams.push(screen);this.checkCancelled();let devices;if(camera||mic){devices=await this.requestMedia(()=>navigator.mediaDevices.getUserMedia({video:camera?{width:320,height:240}:false,audio:mic?(micId?{deviceId:{exact:micId}}:true):false}));this.streams.push(devices);this.checkCancelled()}let track=screen.getVideoTracks()[0];if(!track||track.readyState==='ended')throw Error('Screen sharing ended before recording started. Choose your screen again.');if(camera||markup||track.getSettings?.().width>this.profile.width){const screenVideo=document.createElement('video'),cameraVideo=document.createElement('video');for(const[v,s]of[[screenVideo,screen],...(camera?[[cameraVideo,devices]]:[])]){v.muted=true;v.playsInline=true;v.srcObject=s;await v.play();this.checkCancelled()}const settings=track.getSettings(),canvas=document.createElement('canvas');canvas.width=Math.min(settings.width||this.profile.width,this.profile.width);canvas.height=Math.round(canvas.width*(settings.height||720)/(settings.width||1280));const ctx=canvas.getContext('2d');this.ticker=new Worker('./ticker.js');this.ticker.onmessage=()=>{ctx.drawImage(screenVideo,0,0,canvas.width,canvas.height);if(camera){const size=Math.round(Math.min(canvas.width,canvas.height)*this.bubble.size),x=Math.max(0,Math.min(canvas.width-size,canvas.width*this.bubble.x)),y=Math.max(0,Math.min(canvas.height-size,canvas.height*this.bubble.y));ctx.save();ctx.beginPath();ctx.arc(x+size/2,y+size/2,size/2,0,Math.PI*2);ctx.clip();const side=Math.min(cameraVideo.videoWidth,cameraVideo.videoHeight);if(side)ctx.drawImage(cameraVideo,(cameraVideo.videoWidth-side)/2,(cameraVideo.videoHeight-side)/2,side,side,x,y,size,size);ctx.restore()}if(markup)paintMarkup(ctx,canvas.width,canvas.height,markup)};this.ticker.onmessage();const composed=canvas.captureStream(this.profile.fps);this.streams.push(composed);track=composed.getVideoTracks()[0]} + const audio=this.streams.slice(0,2).flatMap(s=>s.getAudioTracks());let audioTracks=[];if(audio.length){this.audio=this.audio||new Audio();await this.audio.resume();this.checkCancelled();const dest=this.audio.createMediaStreamDestination();for(const t of audio)this.audio.createMediaStreamSource(new MediaStream([t])).connect(dest);audioTracks=dest.stream.getAudioTracks();this.streams.push(dest.stream)}if(mic&&devices?.getAudioTracks().length&&this.audio?.createAnalyser){this.analyser=this.audio.createAnalyser();this.analyser.fftSize=256;this.audio.createMediaStreamSource(new MediaStream(devices.getAudioTracks())).connect(this.analyser);this.levels=new Uint8Array(this.analyser.fftSize)}const output=new MediaStream([track,...audioTracks]);const mimeType=chooseMime();this.recorder=new MediaRecorder(output,{...(mimeType?{mimeType}:{}),videoBitsPerSecond:this.profile.video,audioBitsPerSecond:this.profile.audio});this.recorder.ondataavailable=e=>{if(e.data.size){this.chunks.push(e.data);this.bytes+=e.data.size;this.onchunk(e.data,this.seconds());this.report();if(this.bytes>=LOCAL_MAX_BYTES-1024*1024)this.stop('size')}};this.recorder.onerror=e=>{this.error=e.error||Error('Recording stopped unexpectedly.');this.stop('error')};this.recorder.onstop=async()=>{this.elapsed=this.seconds();this.started=0;this.cleanup();const blob=new Blob(this.chunks,{type:this.recorder.mimeType});await this.finished(blob,this.elapsed,this.error,{reason:this.stopReason,bytes:blob.size,requestedVideoBitrate:this.profile.video,actualVideoBitrate:this.recorder.videoBitsPerSecond||null,quality:this.quality})};this.screenTrack=screen.getVideoTracks()[0];this.screenTrack.onended=()=>{if(this.begun)this.stop('source');else{this.cleanup();this.onSetupEnded?.()}};if(!defer)this.begin();return output}catch(e){this.cleanup();throw e}} + begin(){this.checkCancelled();if(this.begun)return;if(this.screenTrack?.readyState==='ended')throw Error('Screen sharing ended. Choose your screen again.');this.begun=true;this.started=performance.now();this.recorder.start(1000);this.timer=setInterval(()=>{this.status(this.seconds());this.report();if(this.seconds()>=LOCAL_MAX_SECONDS)this.stop('duration')},250);this.status(0)} + checkCancelled(){if(this.cancelled)throw Object.assign(Error('Recording setup cancelled.'),{name:'AbortError'})} + // Invoke the native request synchronously to preserve the click's user activation. + // Browsers cannot dismiss every native picker programmatically. Reject our setup + // immediately on cancellation, and release any stream granted after it ends. + requestMedia(request){ + this.checkCancelled(); + return new Promise((resolve,reject)=>{ + const signal=this.permissionAbort.signal;let settled=false; + const finish=(callback,value)=>{if(settled)return;settled=true;clearTimeout(timer);signal.removeEventListener('abort',abort);callback(value)}; + const abort=()=>finish(reject,signal.reason); + const timer=setTimeout(()=>this.cancel(Object.assign(Error('Recording permission timed out. Dismiss any open browser prompt, then retry or import a video. Nothing was recorded.'),{name:'TimeoutError'})),this.permissionTimeoutMs); + signal.addEventListener('abort',abort,{once:true}); + try{Promise.resolve(request()).then(stream=>{if(settled){release([stream]);return}finish(resolve,stream)},error=>finish(reject,error))}catch(error){finish(reject,error)} + }); + } + cancel(reason=Object.assign(Error('Recording setup cancelled.'),{name:'AbortError'})){this.cancelled=true;this.permissionAbort.abort(reason);this.cleanup()} + seconds(){return this.elapsed+(this.started?(performance.now()-this.started)/1000:0)} + pause(){if(this.recorder?.state!=='recording')return;this.elapsed=this.seconds();this.started=0;this.recorder.pause()} + resume(){if(this.recorder?.state!=='paused')return;this.started=performance.now();this.recorder.resume()} + report(){let level=0;if(this.analyser&&this.levels&&this.recorder?.state!=='paused'){this.analyser.getByteTimeDomainData(this.levels);level=Math.min(1,Math.sqrt(this.levels.reduce((sum,n)=>sum+((n-128)/128)**2,0)/this.levels.length)*4)}this.metrics({...recordingStats(this.bytes,this.seconds(),this.quality),level,paused:this.recorder?.state==='paused'})} + stop(reason='user'){if(this.stopping)return;this.stopReason=reason;this.stopping=true;if(this.recorder&&this.recorder.state!=='inactive')this.recorder.stop();else this.cleanup()} + cleanup(){clearInterval(this.timer);this.ticker?.terminate();release(this.streams);this.audio?.close().catch(()=>{})} +} +export function cancelledError(){return Object.assign(Error('Trim stopped. Your original is unchanged.'),{name:'AbortError'})} +export async function trimVideo(blob,start,end,onProgress,markup=[],quality='balanced',options={}){const signal=options?.signal||null;const check=()=>{if(signal?.aborted)throw cancelledError()};const profile=profileFor(quality);const video=document.createElement('video'),url=URL.createObjectURL(blob);video.src=url;video.playsInline=true;video.muted=false;video.volume=1;let context,timer,watchdog,recorder,outputStreams=[];try{const Audio=globalThis.AudioContext||globalThis.webkitAudioContext;if(!Audio||!globalThis.MediaRecorder)throw Error('Local video processing is unavailable in this browser. Download the original or use a browser with MediaRecorder and Web Audio support.');context=new Audio();context.resume().catch(()=>{});await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>reject(Error('Timed out reading the video. Try importing it again.')),10000);video.onloadedmetadata=()=>{clearTimeout(timeout);resolve()};video.onerror=()=>{clearTimeout(timeout);reject(Error('This browser cannot decode the video.'))}});if(start>0){video.currentTime=start;await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>reject(Error('Could not seek to the trim start. Try another video.')),10000);video.onseeked=()=>{clearTimeout(timeout);resolve()}})}check();const canvas=document.createElement('canvas');canvas.width=Math.min(video.videoWidth,profile.width);canvas.height=Math.round(video.videoHeight*canvas.width/video.videoWidth);const ctx=canvas.getContext('2d'),stream=canvas.captureStream(profile.fps);outputStreams=[stream];await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>reject(Error('Audio processing could not start. Tap Save again with this tab visible. Your original is safe.')),10000);context.resume().then(()=>{clearTimeout(timeout);resolve()},e=>{clearTimeout(timeout);reject(e)})});const source=context.createMediaElementSource(video),dest=context.createMediaStreamDestination();source.connect(dest);outputStreams=[stream,dest.stream];const tracks=[...stream.getVideoTracks(),...dest.stream.getAudioTracks()],mimeType=chooseMime();recorder=new MediaRecorder(new MediaStream(tracks),{...(mimeType?{mimeType}:{}),videoBitsPerSecond:profile.video,audioBitsPerSecond:profile.audio});const chunks=[];return await new Promise((resolve,reject)=>{let done=false;let cancelled=false;const onAbort=()=>{cancelled=true;video.pause();if(recorder&&recorder.state!=='inactive')recorder.stop();reject(cancelledError())};if(signal?.aborted){onAbort();return}signal?.addEventListener('abort',onAbort,{once:true});let lastTime=start,lastProgress=performance.now();watchdog=setInterval(()=>{if(video.currentTime>lastTime+.01){lastTime=video.currentTime;lastProgress=performance.now()}if(performance.now()-lastProgress>15000){done=true;reject(Error('Trimming stalled. Your original is safe; keep this tab visible and try again.'))}},1000);const finish=()=>{if(done)return;done=true;video.pause();recorder.stop()};recorder.ondataavailable=e=>{if(e.data.size)chunks.push(e.data)};recorder.onstop=()=>{signal?.removeEventListener?.('abort',onAbort);release([stream,dest.stream]);if(!cancelled)resolve(new Blob(chunks,{type:recorder.mimeType}))};recorder.onerror=()=>reject(Error('Could not trim this video. Your original remains unchanged.'));video.onended=finish;timer=setInterval(()=>{ctx.drawImage(video,0,0,canvas.width,canvas.height);paintMarkup(ctx,canvas.width,canvas.height,markup);onProgress(Math.min(1,(video.currentTime-start)/(end-start)));if(video.currentTime>=end)finish()},40);recorder.start(250);video.play().catch(reject)})}finally{signal?.removeEventListener?.('abort',()=>{});clearInterval(timer);clearInterval(watchdog);video.pause();if(recorder&&recorder.state!=='inactive')recorder.stop();release(outputStreams);context?.close().catch(()=>{});URL.revokeObjectURL(url)}} diff --git a/rebuild/legacy/public/db.js b/rebuild/legacy/public/db.js new file mode 100644 index 0000000..58bac31 --- /dev/null +++ b/rebuild/legacy/public/db.js @@ -0,0 +1,12 @@ +let db; +export async function open(){db=await new Promise((resolve,reject)=>{const r=indexedDB.open('screennote',1);r.onupgradeneeded=()=>{r.result.createObjectStore('clips',{keyPath:'id'});r.result.createObjectStore('drafts',{keyPath:'id'})};r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(Error('Device storage is unavailable. Use a normal browser window.'))});return db} +export function transact(names,fn){return new Promise((resolve,reject)=>{const t=db.transaction(names,'readwrite');try{fn(t)}catch(e){t.abort();reject(e)}t.oncomplete=resolve;t.onerror=()=>reject(Error('Device storage is full or unavailable. Download your recording before closing.'));t.onabort=()=>reject(Error('Could not save to this device. Download your recording before closing.'))})} +export function all(name='clips'){return new Promise((resolve,reject)=>{const r=db.transaction(name).objectStore(name).getAll();r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error)})} +export const put=c=>transact(['clips'],t=>t.objectStore('clips').put(c)); +export const saveDraft=d=>transact(['drafts'],t=>t.objectStore('drafts').put(d)); +export const finish=(clip,draftId)=>transact(['clips','drafts'],t=>{t.objectStore('clips').put(clip);t.objectStore('drafts').delete(draftId)}); +export const remove=id=>transact(['clips'],t=>t.objectStore('clips').delete(id)); + +export function get(id){return new Promise((resolve,reject)=>{const r=db.transaction('clips').objectStore('clips').get(id);r.onsuccess=()=>resolve(r.result);r.onerror=()=>reject(r.error)})} + +export const putMany=clips=>transact(['clips'],t=>{const store=t.objectStore('clips');for(const clip of clips)store.put(clip)}); diff --git a/rebuild/legacy/public/discussion-ui.js b/rebuild/legacy/public/discussion-ui.js new file mode 100644 index 0000000..13ba38f --- /dev/null +++ b/rebuild/legacy/public/discussion-ui.js @@ -0,0 +1,81 @@ +import {randomId,formatTime} from '../lib/rules.js'; +import {discussionThreads,bubbleThreads,timelineGroups,mergeDiscussion} from '../lib/discussion.js'; +const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); +const short=(s,n=90)=>String(s||'').slice(0,n)+(String(s||'').length>n?'…':''); +export function discussionMarkup(){return `
THE CONVERSATION

Talk about this moment.

0

Reply to anyone. Every thread stays with its moment in the video.

The timestamp follows the playhead until you type. Typing pins it. You can keep watching while you write.

0 / 500

`} +export function mountDiscussion({clip,player,panel,api,owner='',viewer,accessPassword='',update,notify,error}){ + let c=clip,target=null,editing=null,savedDraft=null,posting=false,attempt=null,stamp=c.start,stampLocked=false,expanded=new Set(),focused=null,bubbleIndex=0,bubbleSet='',dismissed='',destroyed=false; + const $=s=>panel.querySelector(s),form=$('#reply-form'),input=$('#reply-text'),context=$('#reply-context'),status=$('#discussion-status'); + const storageKey='screennote-comments-'+c.id,draftKey='screennote-comment-draft-'+c.id; + let identity={key:randomId().replaceAll('-','')+randomId().replaceAll('-',''),ids:[]}; + try{const v=JSON.parse(localStorage.getItem(storageKey));if(/^[a-f0-9]{64}$/.test(v?.key)&&Array.isArray(v.ids))identity=v}catch{} + const persistIdentity=()=>{try{localStorage.setItem(storageKey,JSON.stringify(identity))}catch{status.textContent='Comment controls will remain available for this tab only.'}};persistIdentity(); + let bubbles=true;try{bubbles=localStorage.getItem('screennote-comment-bubbles')!=='off'}catch{} + const stage=player.closest('.video-panel');stage.classList.add('conversation-stage'); + const overlay=document.createElement('div');overlay.className='comment-overlay';stage.append(overlay); + const rail=document.createElement('div');rail.className='comment-timeline';rail.setAttribute('aria-label','Conversation moments');stage.after(rail); + const controls=document.createElement('div');controls.className='conversation-controls';controls.innerHTML=``;rail.after(controls); + const mine=x=>identity.ids.includes(x.id),relative=t=>formatTime(t-c.start),find=id=>c.comments.find(x=>x.id===id); + function saveDraft(){if(editing)return;try{sessionStorage.setItem(draftKey,JSON.stringify({text:input.value,name:$('#reply-name').value,parentId:target?.id||null,time:stamp}))}catch{}} + let draftRestored=false;try{const d=JSON.parse(sessionStorage.getItem(draftKey));if(d){draftRestored=!!d.text;input.value=String(d.text||'').slice(0,500);$('#reply-name').value=String(d.name||'').slice(0,40);target=find(d.parentId)||null;stamp=Math.min(c.end,Math.max(c.start,Number(d.time)||c.start));stampLocked=!!input.value}}catch{} + function composer(){ + context.hidden=!target&&!editing;$('#cancel-reply').hidden=!target&&!editing + const item=editing||target; + context.innerHTML=item?`${editing?'Editing your comment':'Replying to '+esc(item.name)}${esc(short(item.text,140))}`:''; + $('#reply-label').innerHTML=`${editing?'Edit comment':target?'Reply in thread at':'Comment at'} ${relative(target?.time??stamp)}`; + $('#post-comment').textContent=editing?'Save changes':target?'Post reply':'Post comment';$('#reply-count').textContent=`${input.value.length} / 500`; + const chip=$('#timestamp-chip');if(chip){const t=relative(target?.time??stamp);chip.textContent=editing?'editing · timestamp unchanged':target?`⏱ replying in thread · ${t}`:stampLocked?`⏱ pinned · ${t}`:`⏱ follows playhead · ${t}`;chip.setAttribute('aria-pressed',String(!stampLocked&&!target&&!editing));chip.disabled=!!editing} + const dn=$('#draft-notice');if(dn)dn.hidden=!draftRestored; + } + function chooseReply(id){if(posting)return;const item=find(id);if(!item||item.deleted)return;player.pause();if(editing){input.value=savedDraft?.text||'';editing=null;savedDraft=null}target=item;stampLocked=true;stamp=item.time;attempt=null;composer();saveDraft();form.scrollIntoView({block:'nearest',behavior:'auto'});input.focus({preventScroll:true})} + function reveal(id,seek=true){const item=find(id);if(!item)return;const thread=discussionThreads(c.comments).find(t=>t.items.some(x=>x.id===id));if(thread)expanded.add(thread.root.id);$('#thread-filter').value='all';focused=id;render();if(seek){player.pause();player.currentTime=item.time;syncBubble()}const article=$('#comment-'+id);article?.scrollIntoView({block:'nearest',behavior:'auto'});article?.focus({preventScroll:true});history.replaceState(null,'','#comment='+id)} + function card(item,root){const parent=find(item.parentId);return `
${esc(item.name)} ${item.creator&&!item.deleted?'Creator':''}${mine(item)&&!item.deleted?' · You':''}
${parent&&item.id!==root.id?``:''}

${item.deleted?'This comment was removed. Replies are kept below.':esc(item.text)}

${item.editedAt&&!item.deleted?'Edited':''}
${!item.deleted?``:''}${mine(item)&&!item.deleted?``:''}${(mine(item)||owner)&&!item.deleted?``:''}
`} + function render(){ + const threads=discussionThreads(c.comments),filter=$('#thread-filter').value;let visible=threads.filter(t=>filter==='all'||!!t.root.resolved===(filter==='resolved')); + if($('#thread-sort').value==='new')visible.sort((a,b)=>b.root.createdAt-a.root.createdAt); + $('#discussion-count').textContent=String(c.comments.filter(x=>!x.deleted).length); + $('#comments').innerHTML=visible.length?visible.map(({root,items})=>{const replies=items.filter(x=>x.id!==root.id),shown=expanded.has(root.id)?replies:replies.slice(0,2);return `
${root.resolved?'
✓ Resolved
':''}${card(root,root)}${shown.map(x=>card(x,root)).join('')}${replies.length>2?``:''}${mine(root)||owner?``:''}
`}).join(''):`

${filter==='all'?'Start the conversation at a moment that matters.':'No '+filter+' threads.'}

`; + rail.innerHTML=timelineGroups(c.comments,c.start,c.end,Math.max(1,Math.floor(rail.clientWidth/44))).map(g=>``).join(''); + rail.hidden=!threads.some(t=>!t.root.deleted);syncBubble(); + } + function syncBubble(){ + if(destroyed)return;if(overlay.contains(document.activeElement))return;const active=bubbleThreads(c.comments,player.currentTime),key=active.map(t=>t.root.id).join(',');if(key!==bubbleSet){bubbleSet=key;bubbleIndex=0} + const t=active[bubbleIndex%Math.max(1,active.length)];overlay.hidden=!bubbles||!t||dismissed===key||!!document.pictureInPictureElement; + if(overlay.hidden)return; + const note=[...t.items].reverse().find(x=>!x.deleted)||t.root,replyCount=t.items.filter(x=>x.id!==t.root.id&&!x.deleted).length; + const html=`
${active.length>1?``:''}
`; + if(overlay.innerHTML!==html)overlay.innerHTML=html; + } + function timeUpdate(){if(!stampLocked&&!target&&!editing){stamp=player.currentTime;$('#reply-time').textContent=relative(stamp)}syncBubble()} + player.addEventListener('timeupdate',timeUpdate);player.addEventListener('seeked',syncBubble);player.addEventListener('enterpictureinpicture',syncBubble);player.addEventListener('leavepictureinpicture',syncBubble); + controls.querySelector('#bubble-toggle').onclick=e=>{bubbles=!bubbles;e.currentTarget.setAttribute('aria-pressed',String(bubbles));e.currentTarget.textContent='Comment bubbles '+(bubbles?'on':'off');try{localStorage.setItem('screennote-comment-bubbles',bubbles?'on':'off')}catch{}syncBubble()}; + controls.querySelector('#add-moment').onclick=()=>{if(posting)return;player.pause();if(editing)return;target=null;stamp=player.currentTime;stampLocked=true;composer();saveDraft();form.scrollIntoView({block:'nearest'});input.focus({preventScroll:true})}; + overlay.onclick=e=>{const b=e.target.closest('[data-bubble]');if(b)reveal(b.dataset.bubble);else if(e.target.closest('.bubble-next')){bubbleIndex++;syncBubble()}else if(e.target.closest('.bubble-dismiss')){dismissed=bubbleSet;overlay.hidden=true}}; + rail.onclick=e=>{const b=e.target.closest('[data-moment]');if(b)reveal(b.dataset.moment)}; + input.oninput=()=>{attempt=null;if(!stampLocked&&!target&&!editing&&input.value.length){stamp=player.currentTime;stampLocked=true;status.textContent=`Timestamp pinned at ${relative(stamp)}.`}composer();saveDraft()};$('#reply-name').oninput=()=>{attempt=null;saveDraft()}; + const chip=$('#timestamp-chip');if(chip)chip.onclick=()=>{if(editing)return;if(stampLocked){stampLocked=false;stamp=player.currentTime;status.textContent='Timestamp now follows the playhead.'}else{stamp=player.currentTime;stampLocked=true;status.textContent=`Timestamp pinned at ${relative(stamp)}.`}composer();saveDraft()}; + $('#cancel-reply').onclick=()=>{if(editing){input.value=savedDraft?.text||'';target=savedDraft?.target||null;stamp=savedDraft?.stamp??player.currentTime;savedDraft=null}else target=null;editing=null;attempt=null;composer();saveDraft();input.focus()}; + const request=(op,body)=>api(op,{id:c.id,viewer,accessPassword,authorKey:identity.key,...(owner?{owner}:{}),...body}); + function accept(next){c=mergeDiscussion(c,next);update(c);render()} + form.onsubmit=async e=>{ + e.preventDefault();if(posting)return;posting=true;for(const node of form.querySelectorAll('input,textarea,button'))node.disabled=true;status.textContent='Saving…'; + try{ + if(editing){const next=await request('edit-comment',{commentId:editing.id,text:input.value,expectedVersion:editing.editedAt||editing.createdAt});editing=null;input.value=savedDraft?.text||'';target=savedDraft?.target||null;stamp=savedDraft?.stamp??player.currentTime;savedDraft=null;accept(next);status.textContent='Changes saved.'} + else{if(!attempt)attempt={eventId:randomId(),text:input.value,name:$('#reply-name').value||'Guest',time:target?.time??stamp,parentId:target?.id||null};const next=await request('comment',attempt);identity.ids.push(attempt.eventId);persistIdentity();const id=attempt.eventId;attempt=null;input.value='';target=null;stampLocked=false;draftRestored=false;accept(next);const thread=discussionThreads(c.comments).find(t=>t.items.some(x=>x.id===id));if(thread)expanded.add(thread.root.id);render();status.textContent='Comment posted.'} + composer();saveDraft(); + }catch(e){status.textContent='Not saved. Your text is still here.';error(e)}finally{posting=false;for(const node of form.querySelectorAll('input,textarea,button'))node.disabled=false} + }; + $('#thread-filter').onchange=render;$('#thread-sort').onchange=render; + $('#comments').onclick=async e=>{const b=e.target.closest('button');if(!b||b.disabled||posting)return;try{ + if(b.dataset.time!==undefined){player.currentTime=Number(b.dataset.time);player.play().catch(()=>{});return} + if(b.dataset.reply){chooseReply(b.dataset.reply);return} + if(b.dataset.show){reveal(b.dataset.show,false);return} + if(b.dataset.expand){expanded.has(b.dataset.expand)?expanded.delete(b.dataset.expand):expanded.add(b.dataset.expand);render();return} + if(b.dataset.link){const url=new URL(location.href);url.hash='comment='+b.dataset.link;try{await navigator.clipboard.writeText(url.href);notify('Link to comment copied.')}catch{const box=document.createElement('input');box.readOnly=true;box.value=url.href;box.className='comment-link';b.after(box);box.focus();box.select();status.textContent='Select and copy the comment link.'}return} + if(b.dataset.edit){if(!editing)savedDraft={text:input.value,target,stamp};editing=find(b.dataset.edit);input.value=editing.text;target=null;composer();input.focus();form.scrollIntoView({block:'nearest'});return} + if(b.dataset.remove){const item=find(b.dataset.remove);b.disabled=true;status.innerHTML=`Remove this comment? Replies will stay. `;$('#cancel-remove').onclick=()=>{status.textContent='';b.disabled=false};$('#confirm-remove').onclick=async()=>{try{accept(await request('delete-comment',{commentId:item.id}));status.textContent='Comment removed.'}catch(e){error(e);status.textContent='Could not remove comment.'}finally{b.disabled=false}};return} + if(b.dataset.resolve){b.disabled=true;const root=find(b.dataset.resolve);accept(await request('resolve-thread',{commentId:root.id,resolved:!root.resolved}));status.textContent=root.resolved?'Thread reopened.':'Thread resolved.'} + }catch(e){error(e)}finally{b.disabled=false}}; + composer();render();const resizeObserver=typeof ResizeObserver==='function'?new ResizeObserver(()=>render()):null;resizeObserver?.observe(stage);const match=location.hash.match(/^#comment=([a-f0-9-]{36})$/);if(match&&find(match[1])){reveal(match[1],false);player.addEventListener('loadedmetadata',()=>{player.currentTime=find(match[1])?.time??c.start},{once:true})} + return {update(next){if(destroyed)return;accept(next)},destroy(){destroyed=true;resizeObserver?.disconnect();saveDraft();player.removeEventListener('timeupdate',timeUpdate);player.removeEventListener('seeked',syncBubble);player.removeEventListener('enterpictureinpicture',syncBubble);player.removeEventListener('leavepictureinpicture',syncBubble);overlay.remove();rail.remove();controls.remove()}}; +} diff --git a/rebuild/legacy/public/extras-ui.js b/rebuild/legacy/public/extras-ui.js new file mode 100644 index 0000000..62c591f --- /dev/null +++ b/rebuild/legacy/public/extras-ui.js @@ -0,0 +1,8 @@ +import {parseCaptions,parseChapters,validateExtras,captionsVTT,reportMarkdown} from '../lib/enrichment.js'; +import {formatTime} from '../lib/rules.js'; +const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); +export function extrasPanel(c){const r=c.report||{};return`
Captions, chapters & bug report

Optional context, supplied by you. Saving shared context makes it visible to everyone with the video link. Check URLs and text for secrets.

Owner-supplied captions; automatic transcription is not enabled.

Bug report

${[['steps','Reproduction steps',2000],['expected','Expected result',1000],['actual','Actual result',1000]].map(([key,label,max])=>`
`).join('')}

No logs, cookies, browsing history or page contents are collected.

`} +export function mountExtras(c,{save,download,error}){const form=document.querySelector('#extras-form');if(!form)return;const $=s=>form.querySelector(s);$('#caption-file').onchange=async e=>{try{const f=e.target.files[0];if(!f)return;if(f.size>20000)throw Error('Use captions smaller than 20 KB.');const raw=await f.text();parseCaptions(raw,c.duration);$('#captions-text').value=raw;$('#extras-status').textContent='Captions loaded. Save video context to apply them.'}catch(e){error(e)}finally{e.target.value=''}};form.onsubmit=async e=>{e.preventDefault();const button=e.submitter;button.disabled=true;try{const raw=$('#captions-text').value;const report=Object.fromEntries(['url','steps','expected','actual','environment'].map(k=>[k,$('#report-'+k).value]));if($('#include-environment').checked)report.environment=navigator.userAgent.slice(0,300);const extras=validateExtras({captions:raw.trim()?parseCaptions(raw,c.duration):[],chapters:parseChapters($('#chapters-text').value,c.duration),report},c.duration);await save(extras);$('#report-environment').value=extras.report?.environment||'';$('#include-environment').checked=false;$('#export-captions').disabled=!extras.captions.length;$('#extras-status').textContent='Video context saved.';attachCaptions(document.querySelector('#player'),extras.captions)}catch(e){error(e)}finally{button.disabled=false}};$('#export-report').onclick=()=>download(new Blob([reportMarkdown(c,location.origin)],{type:'text/markdown'}),'screennote-bug-report.md');$('#export-captions').onclick=()=>download(new Blob([captionsVTT(c.captions||[])],{type:'text/vtt'}),'screennote-captions.vtt');attachCaptions(document.querySelector('#player'),c.captions||[])} +export function attachCaptions(video,cues){if(!video)return;let track=video._screennoteTrack;if(!track){track=video.addTextTrack('captions','Owner captions','en');video._screennoteTrack=track}for(const cue of [...(track.cues||[])])track.removeCue(cue);for(const c of cues)track.addCue(new VTTCue(c.start,c.end,c.text.replace(/&/g,'&').replace(//g,'>')));track.mode=cues.length?'showing':'disabled'} +export function viewerContext(c){return`${c.chapters?.length?`

Chapters

${c.chapters.map(x=>``).join('')}
`:''}${c.captions?.length?'

Transcript

':''}${c.report?`

Bug report

${[['url','Page'],['steps','Reproduction steps'],['expected','Expected'],['actual','Actual'],['environment','Environment (owner supplied)']].map(([k,label])=>c.report[k]?`

${label}

${esc(c.report[k])}

`:'').join('')}
`:''}`} +export function mountViewerContext(c,video,download){attachCaptions(video,c.captions||[]);const results=document.querySelector('#transcript-results'),search=document.querySelector('#transcript-search');if(search){const render=()=>{const q=search.value.toLocaleLowerCase(),matches=c.captions.filter(x=>x.text.toLocaleLowerCase().includes(q));results.innerHTML=matches.length?matches.map(x=>``).join(''):'

No matching captions.

'};search.oninput=render;render()}document.querySelectorAll('[data-seek]').forEach(b=>b.onclick=()=>{video.currentTime=Number(b.dataset.seek);video.play().catch(()=>{})});if(results)results.onclick=e=>{const b=e.target.closest('[data-seek]');if(b){video.currentTime=Number(b.dataset.seek);video.play().catch(()=>{})}};const exportButton=document.querySelector('#viewer-export-report');if(exportButton)exportButton.onclick=()=>download(new Blob([reportMarkdown({...c,shared:true},location.origin)],{type:'text/markdown'}),'screennote-bug-report.md')} diff --git a/rebuild/legacy/public/icon.svg b/rebuild/legacy/public/icon.svg new file mode 100644 index 0000000..436a24f --- /dev/null +++ b/rebuild/legacy/public/icon.svg @@ -0,0 +1 @@ + diff --git a/rebuild/legacy/public/index.html b/rebuild/legacy/public/index.html new file mode 100644 index 0000000..782439f --- /dev/null +++ b/rebuild/legacy/public/index.html @@ -0,0 +1 @@ +ScreenNote · Show what you mean.

Opening ScreenNote…

diff --git a/rebuild/legacy/public/manifest.webmanifest b/rebuild/legacy/public/manifest.webmanifest new file mode 100644 index 0000000..e5cc303 --- /dev/null +++ b/rebuild/legacy/public/manifest.webmanifest @@ -0,0 +1,11 @@ +{ + "name": "ScreenNote", + "short_name": "ScreenNote", + "description": "Clear screen recordings, thoughtful conversations.", + "start_url": "/", + "scope": "/", + "display": "standalone", + "background_color": "#f7f7f4", + "theme_color": "#f7f7f4", + "icons": [{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any maskable" }] +} \ No newline at end of file diff --git a/rebuild/legacy/public/markup.js b/rebuild/legacy/public/markup.js new file mode 100644 index 0000000..abc5a39 --- /dev/null +++ b/rebuild/legacy/public/markup.js @@ -0,0 +1,3 @@ +// Annotations are normalized to the captured frame, then burned into its pixels. +export function paintMarkup(ctx,width,height,items){for(const m of items){const x=m.x*width,y=m.y*height,w=m.w*width,h=m.h*height;ctx.save();ctx.lineWidth=Math.max(3,width/250);ctx.strokeStyle='#ff6b35';ctx.fillStyle='rgba(255,210,40,.32)';if(m.kind==='redact'){ctx.fillStyle='#161a17';ctx.fillRect(x,y,w,h)}else if(m.kind==='blur'){const pad=Math.max(16,width*.025);ctx.save();ctx.beginPath();ctx.rect(x,y,w,h);ctx.clip();ctx.filter=`blur(${pad}px)`;ctx.drawImage(ctx.canvas,0,0);ctx.restore();ctx.fillStyle='rgba(20,25,20,.25)';ctx.fillRect(x,y,w,h)}else if(m.kind==='highlight'){ctx.fillRect(x,y,w,h)}else if(m.kind==='arrow'){ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(x+w,y+h);const a=Math.atan2(h,w),s=Math.max(14,width*.02);ctx.moveTo(x+w-s*Math.cos(a-.5),y+h-s*Math.sin(a-.5));ctx.lineTo(x+w,y+h);ctx.lineTo(x+w-s*Math.cos(a+.5),y+h-s*Math.sin(a+.5));ctx.stroke()}else ctx.strokeRect(x,y,w,h);ctx.restore()}} +export function bindMarkup(canvas,items,onChange=()=>{},source=null){let kind='rectangle',down=null;const point=e=>{const r=canvas.getBoundingClientRect();return{x:Math.max(0,Math.min(1,(e.clientX-r.left)/r.width)),y:Math.max(0,Math.min(1,(e.clientY-r.top)/r.height))}};function render(preview){if(!canvas.clientWidth||!canvas.clientHeight)return;const ctx=canvas.getContext('2d');canvas.width=Math.round(canvas.clientWidth*devicePixelRatio)||960;canvas.height=Math.round(canvas.clientHeight*devicePixelRatio)||540;ctx.clearRect(0,0,canvas.width,canvas.height);if(source?.readyState>=2)ctx.drawImage(source,0,0,canvas.width,canvas.height);paintMarkup(ctx,canvas.width,canvas.height,[...items,...(preview?[preview]:[])])}function shape(p){return kind==='arrow'?{kind,x:down.x,y:down.y,w:p.x-down.x,h:p.y-down.y}:{kind,x:Math.min(down.x,p.x),y:Math.min(down.y,p.y),w:Math.abs(p.x-down.x),h:Math.abs(p.y-down.y)}}canvas.onpointerdown=e=>{if(e.button!==0)return;down=point(e);canvas.setPointerCapture(e.pointerId)};canvas.onpointermove=e=>{if(down)render(shape(point(e)))};canvas.onpointerup=e=>{if(!down)return;const m=shape(point(e));down=null;if((Math.abs(m.w)>.005||Math.abs(m.h)>.005)&&items.length<40)items.push(m);render();onChange(items.length)};canvas.onpointercancel=()=>{down=null;render()};const observer=new ResizeObserver(()=>render());observer.observe(canvas);const timer=source?setInterval(()=>{if(!down)render()},100):null;render();return{setKind:k=>{kind=k},undo:()=>{items.pop();render();onChange(items.length)},clear:()=>{items.length=0;render();onChange(0)},destroy:()=>{observer.disconnect();clearInterval(timer)}}} diff --git a/rebuild/legacy/public/privacy.html b/rebuild/legacy/public/privacy.html new file mode 100644 index 0000000..73587b6 --- /dev/null +++ b/rebuild/legacy/public/privacy.html @@ -0,0 +1,52 @@ + + + + + +Privacy policy | ScreenNote + + + +
+ +

Privacy policy

+

ScreenNote — record, review and optionally share short screen videos with timestamped discussion. Android package za.co.buttercode.screennote.

+

Effective 26 October 2026.

+ +

1. Recording

+

Screen video is captured only after you approve Android's screen-capture consent dialog, and recording does not restart without fresh consent. If you switch the microphone on, your voice is recorded with the video. The app declares RECORD_AUDIO, POST_NOTIFICATIONS, FOREGROUND_SERVICE, FOREGROUND_SERVICE_MEDIA_PROJECTION and FOREGROUND_SERVICE_MICROPHONE so that a recording can continue behind a visible notification you can stop from. System audio and camera overlays are not captured in this version.

+ +

2. What stays on your device

+

Recordings, drafts and your recording library stay in the app's private storage until you choose to publish. Android cloud backup is switched off for this app (allowBackup="false").

+ +

3. What is uploaded, and only when you publish

+

When you explicitly publish a link, the video file and the details needed to serve it are uploaded: title, duration, size, expiry, and any password you set. Viewers can watch, react, and leave comments or replies, which are stored with the clip. A clip is limited to 10 minutes and 50 MB, and the service runs on a shared 1 GB storage budget.

+ +

4. Names and access are not verified

+

Display names and reviewer identities used in discussions are not verified. Creator and author controls rely on private capability links held by whoever created the content, not on a verified account. A displayed name is not proof of identity.

+ +

5. Retention and deletion

+

Published clips expire after the window the creator chooses — 1, 3 or 7 days (7 days by default). When a creator stops sharing or deletes a published clip, media links already handed out may keep working for up to about ten minutes, because links are signed to be valid for that long. Deleting the local recording does not delete a published copy; stop sharing or delete the published clip to do that. Expired, deleted and unclaimed uploads are reclaimed by the service's retention process. The app runs on third-party hosting, which keeps ordinary request logs such as IP address and browser information for its own default retention period; the app does not add analytics of its own.

+ +

6. What you record, and content responsibility

+

You are responsible for what you record and publish, and for having the right to record and share it, including anything visible on your screen. Reviewers' comments are stored with the clip. This build has no in-app report button for a viewer; if content shows you and you want it removed, contact the person who shared the link, or raise it through the contact route in section 10.

+ +

7. Security

+

Uploaded content is stored in private cloud storage and served through time-limited signed links. Password protection for a shared link is optional and chosen by the creator.

+ +

8. Children

+

ScreenNote is a work and product-feedback tool and is not directed at children.

+ +

9. Your control

+

You can delete local recordings at any time, and stop sharing or delete a published clip to remove it from the server. Requests to remove content that shows you: see section 10.

+ +

10. Contact

+

Privacy questions or removal requests: open an issue at github.com/buttercode101/ScreenNote/issues, or use the developer contact address shown on the app's Google Play listing.

+ +

11. Changes

+

If these practices change, this page is updated and carries a new effective date.

+ +
ScreenNote · This is the privacy policy referenced by the Google Play listing.
+

Publisher and support

Published by TheRealButter. For app support, privacy questions or data requests, email buttercode101@gmail.com.

+ + diff --git a/rebuild/legacy/public/sample.webm b/rebuild/legacy/public/sample.webm new file mode 100644 index 0000000..7cf1fe1 Binary files /dev/null and b/rebuild/legacy/public/sample.webm differ diff --git a/rebuild/legacy/public/style.css b/rebuild/legacy/public/style.css new file mode 100644 index 0000000..99bdc50 --- /dev/null +++ b/rebuild/legacy/public/style.css @@ -0,0 +1,385 @@ +:root{--bg:#f7f6f2;--panel:#fff;--soft:#eeede7;--text:#292c29;--muted:#62685f;--line:#dedfd7;--accent:#b43b1f;--tint:#f7e7df;--dark:#242d28;--light:#f3f4ea;color:var(--text);background:var(--bg);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-synthesis:none;color-scheme:light}*{box-sizing:border-box}:root[data-theme=dark]{--bg:#141b18;--panel:#1b2520;--soft:#25332b;--text:#eef1e9;--muted:#adbaad;--line:#3b4b3e;--accent:#ffb29a;--tint:#3f2d26;--dark:#0c120f;--light:#eef4e9;color-scheme:dark}body{margin:0}button,input,textarea{font:inherit}button,a,input,textarea{touch-action:manipulation}button,a{cursor:pointer}button{color:inherit}button:disabled{opacity:.5;cursor:wait}button:focus-visible,a:focus-visible,input:focus-visible,textarea:focus-visible{outline:3px solid #dd8155;outline-offset:3px}button{min-height:44px}button svg{width:18px;height:18px}svg{width:21px;height:21px;flex:none}a{color:var(--accent)}h1,h2,h3,p{margin-top:0}h1{font-size:clamp(32px,4vw,50px);font-weight:550;letter-spacing:-1.9px;line-height:1.08;margin-bottom:17px}h2{font-size:21px;letter-spacing:-.6px;font-weight:550}h3{font-size:15px;font-weight:600}p{line-height:1.65}.muted{color:var(--muted)}.small{font-size:12px}.eyebrow{font-size:10px;letter-spacing:1.6px;font-weight:650;text-transform:uppercase;color:var(--accent);margin-bottom:15px}.shell{display:grid;grid-template-columns:220px minmax(0,1fr);min-height:100dvh}.sidebar{width:220px;position:fixed;inset:0 auto 0 0;padding:28px 18px;border-right:1px solid var(--line);background:var(--panel);display:flex;flex-direction:column;overflow-y:auto}.brand{background:none;border:0;display:flex;align-items:center;gap:9px;font-weight:650;font-size:21px;letter-spacing:-.8px;text-align:left;padding:0}.brand img{width:32px;height:32px}.nav-label{margin:50px 12px 12px;font-size:10px;font-weight:650;color:var(--muted);letter-spacing:1.3px}.nav{display:grid;gap:8px}.nav button{border:0;text-align:left;padding:13px 14px;border-radius:8px;background:none;display:flex;gap:10px;align-items:center;font-size:13px}.nav .active{background:var(--tint);color:var(--accent);font-weight:650}.side-note{margin-top:auto;padding:22px 12px 0;font-size:12px;line-height:1.7;color:var(--muted);border-top:1px solid var(--line)}.side-note strong{display:block;color:var(--text);margin-bottom:8px}.workspace{grid-column:2;min-width:0}.topbar{height:78px;display:flex;justify-content:space-between;align-items:center;gap:16px;padding:0 42px;border-bottom:1px solid var(--line)}.topbar .brand{display:none}.tag{font-size:10px;letter-spacing:1px;text-transform:uppercase;color:var(--muted)}.top-actions{display:flex;gap:12px;align-items:center}.icon-button{min-width:44px;min-height:44px;border:1px solid var(--line);border-radius:8px;background:var(--panel);display:inline-grid;place-items:center}.content{max-width:1400px;padding:42px;margin:auto}.heading{display:flex;gap:24px;justify-content:space-between;align-items:center;margin-bottom:27px}.heading p{font-size:14px;color:var(--muted);max-width:480px;margin-bottom:0}.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:44px;border:1px solid var(--line);border-radius:7px;padding:11px 16px;font-size:13px;font-weight:600;color:var(--text);background:var(--panel);text-decoration:none;white-space:nowrap}.btn:hover,.icon-button:hover{filter:brightness(.96)}.btn.primary{background:var(--accent);color:var(--panel);border-color:var(--accent)}:root[data-theme=dark] .btn.primary{color:#2f211b}.btn.dark{background:var(--text);color:var(--bg);border-color:var(--text)}.btn.danger{color:var(--accent)}.actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.record-grid{display:grid;grid-template-columns:minmax(0,1.6fr) minmax(250px,1fr);gap:24px}.stage{border-radius:13px;min-height:340px;background:var(--dark);position:relative;overflow:hidden;display:flex;align-items:center;justify-content:center;color:var(--light)}.stage:before{content:'';position:absolute;inset:0;background-image:radial-gradient(#8b9e8b32 .75px,transparent .75px);background-size:16px 16px;pointer-events:none}.stage-inner{position:relative;text-align:center;padding:32px}.screen-symbol{width:155px;height:102px;border:1px solid #a9b8a26b;border-radius:9px;margin:0 auto 30px;display:grid;place-items:center;position:relative;background:#354038}.screen-symbol:after{content:'';position:absolute;width:52px;height:4px;background:#859580;bottom:-14px;border-radius:2px}.play-disc{width:48px;height:48px;display:grid;place-items:center;background:#f2efdd;border-radius:50%;color:#344236}.stage h2{font-size:24px;letter-spacing:-.7px;margin-bottom:8px}.stage p{font-size:12px;color:#b6c3b1;margin:0}.stage video{width:100%;max-height:440px;display:block;position:relative}.stage-top{position:absolute;top:18px;left:20px;font-size:10px;letter-spacing:1px;border:1px solid #64755e;border-radius:20px;padding:6px 10px;z-index:1}.stage .live-dot{display:inline-block;background:#ef7759;border-radius:50%;width:7px;height:7px;margin-right:6px}.panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:25px;min-width:0}.panel h2{margin-bottom:8px}.panel p{font-size:12px;color:var(--muted)}.option{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:17px 0;border-bottom:1px solid var(--line)}.option>div{display:flex;gap:12px;align-items:center}.option strong{display:block;font-size:13px;font-weight:550}.option small{display:block;color:var(--muted);font-size:11px;margin-top:4px}.option input{width:36px;height:21px;accent-color:var(--accent);flex:none}.record-options .btn.primary{width:100%;margin-top:24px}.record-options .import-label{display:flex;justify-content:center;cursor:pointer;padding:12px 0;font-size:12px;color:var(--muted);font-weight:600}.file-input{width:100%;font-size:12px;margin-top:8px;color:var(--muted)}.meta-strip{display:flex;justify-content:space-between;gap:18px;font-size:11px;color:var(--muted);padding:15px 0 0;line-height:1.6}.section-head{display:flex;justify-content:space-between;align-items:center;gap:15px;margin:42px 0 20px}.section-head h2{margin:0}.clip-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px}.clip-card{border:1px solid var(--line);background:var(--panel);border-radius:10px;overflow:hidden;min-width:0}.clip-art{aspect-ratio:16/9;background:var(--soft);display:grid;place-items:center;position:relative}.clip-art img{width:100%;height:100%;object-fit:cover}.clip-art .duration{position:absolute;right:12px;bottom:12px;font-size:10px;border-radius:4px;padding:4px 6px;background:#17231edf;color:#fff}.clip-body{padding:17px}.clip-body h3{overflow-wrap:anywhere;margin-bottom:7px}.clip-body .btn{margin-top:14px;width:100%;font-size:12px}.clip-status{font-size:10px;color:var(--muted)}.empty{grid-column:1/-1;text-align:center;padding:37px;border:1px dashed var(--line);border-radius:12px;background:var(--soft)}.empty p{font-size:12px;color:var(--muted)}.empty h3{margin-bottom:7px}.empty .btn{margin-top:5px}.footer{display:flex;justify-content:space-between;gap:16px;font-size:11px;color:var(--muted);margin-top:40px;padding-top:22px;border-top:1px solid var(--line);line-height:1.7}.error-box{border:1px solid #d78c71;background:var(--tint);padding:14px 18px;border-radius:8px;margin-bottom:20px;font-size:13px;line-height:1.6;overflow-wrap:anywhere}.error-box:empty{display:none}.editor-grid{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:24px}.video-panel{background:var(--dark);border-radius:12px;overflow:hidden}.video-panel video{display:block;width:100%;aspect-ratio:16/9;max-height:65vh}.field{display:flex;flex-direction:column;gap:8px;margin-bottom:18px;min-width:0}.field label{font-size:12px;font-weight:600}.field input,.field textarea{width:100%;min-height:45px;border:1px solid var(--line);border-radius:6px;background:var(--panel);color:var(--text);padding:11px 12px;font-size:14px}.field textarea{resize:vertical;min-height:90px}.field-row{display:grid;grid-template-columns:1fr 1fr;gap:12px}.small-label{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--muted);margin:0 0 10px}.editor-actions{padding:18px 0;display:flex;gap:10px;flex-wrap:wrap}.notice{background:var(--soft);border-radius:8px;padding:14px 17px;font-size:12px;line-height:1.7;color:var(--muted);margin:18px 0}.share-link{word-break:break-all;display:block;padding:11px 12px;background:var(--soft);font-size:12px;border:1px solid var(--line);border-radius:6px;margin-bottom:12px;color:var(--accent)}.full{width:100%}.progress{height:5px;background:var(--soft);border-radius:3px;overflow:hidden;margin-top:16px}.progress>div{height:100%;background:var(--accent);transition:width .2s}.live-controls{display:flex;align-items:center;justify-content:center;gap:12px;margin-top:20px}.timer{font-size:30px;font-variant-numeric:tabular-nums;font-weight:500;min-width:100px}.recording .stage{border:2px solid #da6847}.reactions{display:flex;gap:10px;margin:20px 0;flex-wrap:wrap}.reactions button[aria-pressed=true]{border-color:var(--accent);background:var(--tint)}.comment{padding:17px 0;border-bottom:1px solid var(--line);font-size:13px}.comment-head{display:flex;align-items:center;gap:10px;margin-bottom:8px}.comment-head strong{font-size:12px}.timestamp{color:var(--accent);background:var(--tint);border:0;min-height:30px;font-size:11px;padding:4px 8px;border-radius:4px}.comment p{overflow-wrap:anywhere;margin-bottom:0;white-space:pre-wrap}.viewer-top{max-width:1200px;margin:auto;padding:23px 32px;display:flex;justify-content:space-between;gap:20px;border-bottom:1px solid var(--line)}.viewer{max-width:1200px;margin:auto;padding:36px 32px}.viewer h1{font-size:34px;line-height:1.25;overflow-wrap:anywhere}.viewer-grid{display:grid;grid-template-columns:minmax(0,1.6fr) minmax(270px,1fr);gap:26px}.reply-panel{max-height:800px;overflow:auto}.viewer .video-panel video{min-height:220px}.privacy{max-width:760px}.privacy h2{margin-top:30px}#notice{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);max-width:calc(100% - 30px);background:var(--text);color:var(--bg);font-size:13px;line-height:1.6;padding:13px 20px;border-radius:8px;z-index:50;display:none}.skip{position:fixed;left:10px;top:-80px;background:var(--panel);padding:12px;z-index:99}.skip:focus{top:10px}.loading{padding:40px}dialog{max-width:560px;width:calc(100% - 32px);max-height:calc(100dvh - 32px);border:1px solid var(--line);padding:25px;border-radius:12px;background:var(--panel);color:var(--text)}dialog::backdrop{background:#0e1a1377}.dialog-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:20px}.visually-hidden{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)} +@media(min-width:1600px){.content{padding-top:58px}}@media(max-width:1150px){.record-grid{grid-template-columns:minmax(0,1.3fr) minmax(240px,1fr)}.content{padding:30px}.topbar{padding:0 30px}.clip-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.editor-grid{grid-template-columns:minmax(0,1fr)}.editor-grid>aside{display:grid;grid-template-columns:1fr 1fr;gap:20px}.viewer-grid{grid-template-columns:minmax(0,1fr)}}@media(max-width:1024px){.shell{grid-template-columns:180px minmax(0,1fr)}.sidebar{width:180px;padding:25px 14px}.sidebar .brand{font-size:18px}.sidebar .brand img{width:28px;height:28px}.content{padding:28px 24px}.topbar{padding:0 24px}.record-grid{grid-template-columns:minmax(0,1fr)}.record-options .option{padding:13px 0}.record-options .btn.primary{margin-top:19px}.stage{min-height:310px}}@media(max-width:767px){.shell{display:block}.sidebar{display:none}.workspace{display:block}.topbar{height:70px;padding:0 20px}.topbar .brand{display:flex;font-size:19px}.breadcrumb{display:none}.tag{font-size:9px}.top-actions{gap:9px}.content{padding:28px 20px}.heading{align-items:start;gap:16px}.heading h1{font-size:36px}.heading p{font-size:13px}.heading .actions .btn{padding:10px 12px}.record-grid{gap:16px}.stage{min-height:280px}.stage h2{font-size:23px}.panel{padding:21px}.meta-strip{flex-wrap:wrap;gap:4px;font-size:11px}.section-head{margin-top:32px}.clip-grid{gap:14px}.clip-body{padding:14px}.clip-body h3{font-size:14px}.empty{padding:28px 20px}.footer{display:block}.footer span{display:block;margin-bottom:7px}.editor-grid>aside{display:block}.editor-grid>aside>.panel{margin-bottom:17px}.viewer-top{padding:18px 20px}.viewer-top .brand{font-size:18px}.viewer{padding:28px 20px}.viewer h1{font-size:27px;letter-spacing:-1px}.field input,.field textarea{font-size:16px}.viewer .video-panel video{min-height:0}.viewer-grid{gap:20px}.reply-panel{max-height:none}.editor-actions{gap:8px}.editor-actions .btn{font-size:12px}.timer{font-size:27px}}@media(max-width:480px){.clip-grid{grid-template-columns:minmax(0,1fr)}.topbar .tag{display:none}.heading{flex-wrap:wrap}.heading h1{font-size:35px}.screen-symbol{width:130px;height:90px}.record-grid .stage{min-height:265px}.content{padding:26px 17px}.field-row{gap:10px}.viewer-top>.btn{font-size:11px;padding:9px 11px}.stage-inner{padding:24px}.live-controls{flex-wrap:wrap}.reactions .btn{font-size:12px;padding:9px 11px}.clip-art{aspect-ratio:2/1}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}} + +.record-options .btn{white-space:normal}.file-input::file-selector-button{border:1px solid var(--line);border-radius:5px;background:var(--soft);color:var(--text);padding:8px 10px;margin-right:10px;font:inherit;cursor:pointer}button:disabled{cursor:not-allowed} + +/* Stable narrow layouts and readable interactive text. */ +.record-grid>*,.editor-grid>*,.viewer-grid>*{min-width:0}.option strong{font-size:14px}.option small{font-size:12px}.file-input{width:100%;min-width:0}.error-box:empty{display:none}.error-box{overflow-wrap:anywhere}.clip-status{line-height:1.6}.timestamp{min-height:44px;min-width:44px}.viewer-top{align-items:center}.viewer-top>.btn{white-space:normal;text-align:center}.reactions .btn{white-space:normal}.notice[role=status]{overflow-wrap:anywhere}@media(max-width:360px){.viewer-top{gap:12px;padding:16px}.viewer-top .brand{font-size:17px}.topbar{gap:8px;padding:0 16px}.top-actions{gap:6px}} + +/* Text must wrap inside components, including overflow toward the left. */ +h1,h2,h3,.panel p,.notice,.comment-head strong{overflow-wrap:anywhere} +.heading>div,.comment-head strong,.option>div,.footer>span{min-width:0} +.btn{max-width:100%;white-space:normal;text-align:center;overflow-wrap:anywhere} +.dialog-actions{flex-wrap:wrap}.dialog-actions .btn{flex:0 1 auto} +.comment-head{align-items:flex-start}.comment-head strong{flex:1}.comment-head .timestamp{flex:none} +.recording-title{font-size:clamp(27px,3vw,34px);line-height:1.2} + +[hidden]{display:none!important} +.panel p,.empty p,.stage p{font-size:14px}.notice,.small{font-size:13px}.clip-status,.footer,.meta-strip{font-size:12px} + +#notice{pointer-events:none;overflow-wrap:anywhere} + +/* Recording tools and portable context. */ +.extra-panel{margin-top:24px}.extra-panel summary{font-size:17px;font-weight:650;cursor:pointer;padding:8px 0;min-height:44px}.extra-panel[open] summary{margin-bottom:16px}.extra-panel textarea{width:100%;resize:vertical}.extra-panel input:not([type=checkbox]),.context-panel input{width:100%;max-width:100%;box-sizing:border-box}.consent{display:flex;gap:12px;align-items:flex-start;line-height:1.6}.consent input{flex:none;width:20px;height:20px}.context-panel{margin-top:24px}.pre-wrap{white-space:pre-wrap;overflow-wrap:anywhere}.chapter-list,.tool-controls{display:flex;gap:8px;flex-wrap:wrap}.transcript-cue{display:flex;gap:12px;width:100%;text-align:left;background:none;border:0;border-bottom:1px solid var(--line);padding:12px 0;min-height:44px;cursor:pointer;color:inherit;font:inherit}.transcript-cue span:first-child{flex:none;color:var(--accent)}.transcript-cue span:last-child{min-width:0;overflow-wrap:anywhere}.capture-frame{position:relative;line-height:0;background:#17251c;border-radius:12px;overflow:hidden}.capture-frame video{width:100%;height:auto;max-height:65vh;display:block;object-fit:contain}.capture-frame canvas{position:absolute;inset:0;width:100%;height:100%;touch-action:none;cursor:crosshair}.tool-controls{align-items:center;margin:16px 0}.tool-controls label{display:flex;gap:8px;align-items:center}.tool-controls select{max-width:100%;min-height:44px}.setup-note{margin:16px 0;line-height:1.7}.countdown{font-size:24px;font-weight:700;min-height:36px}.player-tools{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:12px 0}.player-tools label{display:flex;align-items:center;gap:8px}.player-tools select{min-height:44px}.record-options select{width:100%;margin:8px 0 16px}.help-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,280px),1fr));gap:24px}.beta-note{padding:14px 18px;border:1px solid var(--line);border-radius:10px;font-size:13px;line-height:1.6;margin-bottom:24px}.field select{width:100%;min-height:44px}.canvas-editor{margin-top:24px}.canvas-editor .capture-frame video{max-height:none}.context-panel h3{margin-top:18px}.context-panel input{margin:12px 0}.extra-panel .field small{display:block;margin-top:8px}.tool-controls>*{min-width:0}@media(max-width:480px){.player-tools,.tool-controls{gap:8px}.capture-frame video{max-height:none}.extra-panel{padding:18px}} +progress{width:100%;height:12px;margin-top:16px;accent-color:var(--accent)}select{font:inherit;color:var(--text);background:var(--panel);border:1px solid var(--line);border-radius:7px;padding:9px;min-width:0}select:focus-visible,summary:focus-visible{outline:3px solid #dd8155;outline-offset:3px} +.context-panel input{min-height:44px;padding:11px 12px;border:1px solid var(--line);border-radius:8px;background:var(--panel);color:var(--text);font:inherit}.canvas-editor summary{font-size:17px;font-weight:650;cursor:pointer;min-height:44px;padding:8px 0}.canvas-editor[open] summary{margin-bottom:16px} + +/* In stacked layouts, put the recording task before decorative artwork. */ + + +.import-only .option,.import-only .field,.import-only [data-action=record]{display:none} + +#main:focus{outline:none} + +/* Keep pointer coordinates aligned with captured pixels, including portrait sources. */ +.capture-frame{width:min(100%,calc(65vh * var(--capture-ratio,1.7777778)));aspect-ratio:var(--capture-ratio,1.7777778);margin-inline:auto} +.capture-frame video,.canvas-editor .capture-frame video{width:100%;height:auto;max-height:none} + +/* Review follows the task: title, preview, share, optional tools. */ +.heading h1.recording-title{font-size:clamp(24px,3vw,30px);line-height:1.2;letter-spacing:-.8px} +.editor-heading{margin-bottom:20px}.title-field{max-width:900px;margin-bottom:22px} +.title-controls{display:flex;gap:10px;align-items:stretch}.title-controls input{min-width:0;flex:1} +.title-controls .btn{flex:none}.title-field #title-status:empty{display:none} +.source-filename{font-size:12px;color:var(--muted)}.source-filename span{display:block;padding-top:8px;overflow-wrap:anywhere} +.source-filename summary,.local-options summary,.password-options summary{cursor:pointer;min-height:44px;display:flex;align-items:center} +.editor-preview{min-width:0}.editor-tools{grid-column:1/-1;display:grid;gap:12px;align-content:start} +.editor-tools .panel{margin:0;padding:16px 20px}.editor-tools summary{font-size:15px;font-weight:600;cursor:pointer;min-height:44px;padding:8px 0} +.editor-tools details[open] summary{margin-bottom:12px}.editor-tools details p{font-size:13px} +.video-panel{width:min(100%,calc(65dvh * var(--media-ratio,1.7777778)));margin-inline:auto} +.video-panel video{width:100%;height:auto;aspect-ratio:auto;max-height:none;object-fit:contain} +.viewer .video-panel video{min-height:0}.editor-actions{padding:12px 0;justify-content:space-between} +.local-options{position:relative;font-size:13px}.local-options[open] .btn{display:block;margin-top:8px} +.password-options{margin-bottom:14px;font-size:13px}.password-options .field{margin-top:8px} +.editor-grid>aside>.panel{padding:20px}.editor-grid>aside .eyebrow{margin-bottom:8px} +.editor-grid>aside .notice{font-size:12px;margin:12px 0;padding:12px} +.reply-panel{align-self:start}.viewer-grid{align-items:start} +@media(max-width:1150px){.editor-grid>aside{display:block}.editor-grid{gap:16px}} +@media(max-width:767px){.editor-heading p{font-size:13px}.title-field{margin-bottom:16px}.editor-tools .panel{padding:12px 16px}.viewer{padding-top:20px}.viewer h1{font-size:24px;line-height:1.25}.viewer .eyebrow{margin-bottom:10px}.reactions{margin:12px 0}.viewer-grid{gap:16px}.panel.reply-panel{padding:18px}.reply-panel h2{font-size:20px}} +@media(max-width:480px){.content{padding:20px 16px}.editor-heading{gap:12px;margin-bottom:16px}.heading h1.recording-title{font-size:26px}.editor-heading>div{flex:1 1 160px}.title-controls{gap:8px}.title-controls .btn{padding:10px 12px}.editor-grid>aside>.panel{padding:18px}.viewer{padding-inline:16px}.viewer h1{font-size:24px}.player-tools{font-size:13px}} +@media(max-width:767px){.editor-heading{display:grid;grid-template-columns:minmax(0,1fr);gap:10px}.editor-heading>.btn{order:-1;justify-self:start;min-height:36px;padding:6px 10px;font-size:12px}.editor-heading>div{width:100%}.editor-heading h1{margin-bottom:8px}.local-options .source-filename{max-width:260px}.local-options .source-filename summary{min-height:36px}} + +/* Conversation threads keep one readable reply level, regardless of ancestry. */ +.discussion-heading{display:flex;align-items:center;justify-content:space-between;gap:12px}.discussion-heading h2{font-size:23px;line-height:1.15}.discussion-heading .eyebrow{margin-bottom:8px}.count-pill{background:var(--soft);border:1px solid var(--line);border-radius:24px;min-width:36px;padding:8px;text-align:center;font-size:13px}.reply-panel{max-height:none;overflow:visible}.reply-panel #reply-form{padding:16px 0 20px}.reply-panel .field{margin-bottom:12px}.reply-panel .field textarea{min-height:100px}.compose-meta{display:flex;align-items:center;justify-content:space-between;gap:8px}.text-button{background:none;border:0;color:var(--accent);padding:8px 6px;min-height:44px;font-size:12px;font-weight:600;text-align:left;overflow-wrap:anywhere}.text-button:hover{text-decoration:underline}.reply-context{border-left:3px solid var(--accent);background:var(--tint);padding:10px 12px;margin:0 0 14px;font-size:12px;overflow-wrap:anywhere}.reply-context strong,.reply-context span{display:block}.reply-context span{margin-top:5px;line-height:1.5}.discussion-toolbar{display:flex;gap:8px;flex-wrap:wrap;border-top:1px solid var(--line);padding:16px 0}.discussion-toolbar select{font-size:12px;min-height:44px;flex:1}.discussion-thread{border:1px solid var(--line);border-radius:10px;margin:0 0 14px;padding:0 14px;background:var(--panel)}.discussion-thread .comment{padding:14px 0}.discussion-thread .thread-reply{margin-left:12px;padding-left:12px;border-left:2px solid var(--line);border-bottom:0}.discussion-thread .comment-head{align-items:center;gap:8px;margin-bottom:6px}.comment-avatar{display:grid;place-items:center;flex:none;width:28px;height:28px;border-radius:50%;background:var(--soft);font-size:12px;font-weight:650}.comment-head strong{font-size:12px;line-height:1.5}.comment-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:5px}.comment-actions .text-button{padding-inline:2px}.creator-badge{font-size:10px;color:var(--accent);border:1px solid var(--line);padding:2px 4px;border-radius:4px;display:inline-block}.parent-reference{display:block;font-size:11px;color:var(--muted);max-width:100%;line-height:1.5;padding:4px 0;min-height:32px}.resolve-thread{width:100%;border-top:1px solid var(--line);color:var(--muted)}.is-resolved{background:var(--soft)}.resolved-label{padding-top:12px;font-size:11px;color:var(--muted);font-weight:650}.comment-selected{background:var(--tint);outline:2px solid var(--accent);outline-offset:4px;border-radius:4px}.discussion-empty{font-size:14px;padding:20px 0}.comment-link{width:100%;padding:10px;min-width:0}.conversation-stage{position:relative}.comment-overlay{position:absolute;z-index:2;top:12px;left:12px;right:12px;pointer-events:none;display:flex;justify-content:flex-start}.moment-bubble{display:flex;align-items:flex-start;max-width:min(370px,90%);border:1px solid #ffffff55;border-radius:12px 12px 12px 3px;background:#18221def;color:#fff;box-shadow:0 4px 18px #0003;pointer-events:auto;overflow:hidden;backdrop-filter:blur(8px)}.bubble-main{display:flex;flex-direction:column;gap:5px;align-items:flex-start;background:none;color:inherit;border:0;text-align:left;padding:12px;min-width:0;min-height:44px;flex:1}.bubble-byline{font-size:11px;font-weight:650;overflow-wrap:anywhere;line-height:1.4}.bubble-byline>span{font-weight:400;color:#d1dace}.bubble-text{font-size:13px;line-height:1.45;overflow-wrap:anywhere;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden}.bubble-hint{font-size:10px;color:#d1dace}.bubble-side{display:flex;flex-direction:column;flex:none}.bubble-side button{border:0;background:none;color:#fff;min-width:44px;min-height:44px;font-size:13px}.bubble-dismiss{font-size:24px!important}.conversation-controls{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-top:12px}.conversation-controls .btn{font-size:12px}.conversation-controls [aria-pressed=true]{background:var(--tint);border-color:var(--accent)}.comment-timeline{position:relative;height:44px;border-bottom:2px solid var(--line);margin-top:2px}.comment-timeline:before{content:'';position:absolute;left:0;right:0;top:21px;border-top:2px solid var(--line)}.moment-marker{position:absolute;left:var(--moment);transform:translateX(-50%);min-width:44px;width:44px;min-height:44px;height:44px;padding:0;background:none;border:0;color:var(--accent);display:grid;place-items:center;z-index:1}.moment-marker>span{font-size:12px;border-radius:50%;width:20px;height:20px;display:grid;place-items:center;background:var(--tint);border:1px solid var(--accent)}.moment-marker:hover>span{background:var(--accent);color:var(--panel)}.viewer-media{min-width:0}.viewer-top .icon-button{flex:none} +@media(min-width:1151px){.viewer-grid{grid-template-columns:minmax(0,1.55fr) minmax(330px,1fr)}.viewer-media{position:sticky;top:20px}} +@media(max-width:480px){.moment-bubble{max-width:100%}.bubble-main{padding:9px 10px;gap:3px}.comment-overlay{top:8px;left:8px;right:8px}.bubble-text{font-size:12px}.bubble-byline{font-size:10px}.bubble-hint{display:none}.discussion-thread{padding-inline:10px}.discussion-thread .thread-reply{margin-left:5px;padding-left:9px}.discussion-heading h2{font-size:21px}.panel.reply-panel{padding:16px}.discussion-toolbar select{font-size:12px}.conversation-controls .btn{flex:1;padding:8px}.comment-head .timestamp{padding:4px}.comment-avatar{width:24px;height:24px}} + +/* A focused workspace, with motion that communicates state. */ +.library-heading h1{font-size:clamp(30px,3.6vw,44px);letter-spacing:-1.5px}.library-heading{align-items:center;margin-bottom:18px}.workspace-summary{display:flex;align-items:center;gap:10px;flex-wrap:wrap;font-size:12px;color:var(--muted);padding-bottom:24px}.workspace-summary .text-button{margin-left:auto}.status-dot{width:7px;height:7px;background:#518366;border-radius:50%}.library-section{margin-bottom:28px}.library-section .section-head{margin-top:18px}.library-filters{display:grid;grid-template-columns:minmax(0,1fr) 170px 150px;gap:12px}.library-filters .field{margin-bottom:0}.library-filters input,.library-filters select{min-height:44px;width:100%}.library-filters select,.record-defaults select,.advanced-recording select,.review-status-panel select{padding:10px 12px;border:1px solid var(--line);border-radius:7px;color:var(--text);background:var(--panel);font:inherit;min-width:0;max-width:100%}.library-filters+.small{margin:10px 0 16px}.record-setup{margin:20px 0 32px}.record-setup>summary{cursor:pointer;font-size:14px;font-weight:600;padding:16px 0;min-height:48px;border-top:1px solid var(--line)}.compact-recorder{grid-template-columns:minmax(0,1.25fr) minmax(240px,1fr);gap:24px}.recorder-intro{display:flex;justify-content:space-between;gap:15px;align-items:center}.recorder-intro>.svg,.recorder-intro>svg{width:32px;height:32px;color:var(--accent)}.recorder-intro .eyebrow{font-size:9px;margin-bottom:10px}.record-options .btn.primary{margin-top:8px;min-height:48px}.record-defaults{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:20px;margin-top:12px;align-items:center}.record-defaults .option{border:0}.record-defaults .field{margin:0}.record-defaults select{font-size:13px}.advanced-recording{border-top:1px solid var(--line);margin-top:14px}.advanced-recording>summary{min-height:48px;display:list-item;padding:16px 0;cursor:pointer;font-size:12px;color:var(--muted)}.advanced-recording .field{margin-top:14px}.record-limits{font-size:11px!important;margin:12px 0 0}.record-guide{border:1px solid var(--line);border-radius:12px;background:var(--soft);padding:28px}.guide-icon{display:grid;place-items:center;width:44px;height:44px;border-radius:50%;background:var(--dark);color:var(--light);margin-bottom:20px}.record-guide h2{font-size:25px}.record-guide ol{padding-left:20px;display:grid;gap:16px;color:var(--muted);font-size:13px;line-height:1.65;margin:20px 0}.record-guide li strong{color:var(--text)}.record-guide .btn{white-space:normal;width:100%}.clip-art{width:100%;padding:0;border:0;color:var(--text)}.card-play{position:absolute;display:grid;place-items:center;width:40px;height:40px;border-radius:50%;background:#fffdf2ed;color:#253c2d;opacity:0;transform:scale(.9);transition:opacity .18s,transform .18s}.clip-art:hover .card-play,.clip-art:focus-visible .card-play{opacity:1;transform:scale(1)}.card-badges{display:flex;gap:7px;flex-wrap:wrap;margin-bottom:12px}.clip-badge,.review-badge{font-size:10px;border-radius:5px;padding:4px 7px;background:var(--soft);color:var(--muted)}.clip-badge.shared{background:var(--tint);color:var(--accent)}.review-badge[data-review=approved]{background:#e2eee4;color:#285538}.review-badge[data-review=changes-requested]{background:#f4e5d4;color:#794619}.card-actions{display:flex;gap:8px;align-items:center;margin-top:14px}.card-actions>.btn{margin-top:0;flex:1;width:auto}.card-actions>.icon-button{flex:none}.review-status-panel{margin-top:14px}.review-status-panel label{display:block;font-size:12px;font-weight:600;margin-bottom:10px}.review-status-panel select{width:100%;font-size:13px}.review-status-panel p{margin-bottom:0}.recovery-note summary{cursor:pointer;font-weight:600}.recovery-note p{margin-bottom:0}.capture-metrics{display:grid;grid-template-columns:1fr auto;align-items:center;gap:12px;background:var(--soft);padding:16px;border-radius:10px;margin:16px 0}.capture-metrics strong{font-variant-numeric:tabular-nums;margin-right:12px}.capture-metrics span{font-size:12px;color:var(--muted)}.capture-metrics p{grid-column:1/-1;font-size:12px;margin:0}.capture-metrics p:empty{display:none}.mic-meter-label{font-size:12px;display:flex;align-items:center;gap:10px}.mic-meter-label meter{width:100px}.recording .capture-frame{max-height:58vh}.recording .capture-frame video{max-height:58vh;object-fit:contain}.live-controls{position:sticky;bottom:12px;z-index:8;background:var(--panel);padding:12px 20px;border:1px solid var(--line);border-radius:12px;box-shadow:0 8px 30px #14231c16;width:fit-content;margin:12px auto}.is-live #recording-status:before{content:'';display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--accent);margin-right:8px;animation:record-pulse 1.6s ease-in-out infinite}.is-paused #recording-status:before{animation:none;background:var(--muted)}.is-paused .timer{color:var(--muted)}.countdown:not(:empty){padding:16px;border-radius:10px;text-align:center;background:var(--tint);color:var(--accent);font-size:26px;font-weight:650;animation:count-in .3s ease-out}.camera-handle{position:absolute;z-index:6;background:#15231b22;border:2px dashed #fff;border-radius:50%;color:white;font-size:10px;min-height:0;touch-action:none;cursor:move;display:grid;place-items:center;text-shadow:0 1px 4px black}.camera-handle:hover,.camera-handle:focus-visible{background:#15231b88}.bubble-settings{display:flex;gap:20px;align-items:center;flex-wrap:wrap;font-size:12px;margin:12px 0}.bubble-settings label{display:flex;gap:12px;align-items:center}.sample-feedback blockquote{margin-left:18px;padding-left:14px;border-left:2px solid var(--line);font-size:13px}.sample-feedback p{font-size:13px}.share-problem .btn{margin-top:12px;width:100%;white-space:normal}.btn,.icon-button{transition:background-color .18s,border-color .18s,transform .18s,box-shadow .18s}.btn:active,.icon-button:active{transform:scale(.98)}.clip-card{transition:border-color .18s,box-shadow .18s;animation:surface-in .22s ease-out}.clip-card:hover{border-color:var(--muted);box-shadow:0 4px 14px #16241b0d}dialog[open]{animation:surface-in .18s ease-out}.moment-bubble{animation:bubble-in .2s ease-out}#notice{animation:toast-in .18s ease-out}progress{accent-color:var(--accent)} +@keyframes record-pulse{0%,100%{opacity:1;box-shadow:0 0 0 0 #c4472633}50%{opacity:.55;box-shadow:0 0 0 5px #c4472600}}@keyframes count-in{from{opacity:.3;transform:scale(.96)}to{opacity:1;transform:scale(1)}}@keyframes surface-in{from{opacity:0;transform:translateY(5px)}to{opacity:1;transform:translateY(0)}}@keyframes bubble-in{from{opacity:0;transform:translateY(6px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}@keyframes toast-in{from{opacity:0;margin-bottom:-5px}to{opacity:1;margin-bottom:0}} +@media(max-width:1024px){.compact-recorder{grid-template-columns:minmax(0,1fr)}.record-guide{display:none}.library-filters{grid-template-columns:minmax(0,1fr) 145px 135px}} +@media(max-width:767px){.library-heading{align-items:start}.library-heading .actions{width:100%}.library-heading .actions>.btn{flex:1}.library-heading h1{font-size:32px}.workspace-summary{font-size:11px;gap:7px;padding-bottom:8px}.workspace-summary .text-button{margin-left:0}.library-filters{grid-template-columns:1fr 1fr;gap:10px}.library-filters .field:first-child{grid-column:1/-1}.record-defaults{grid-template-columns:1fr;gap:0}.record-defaults .option{padding:14px 0}.record-defaults .field{margin-bottom:8px}.capture-metrics{grid-template-columns:1fr}.capture-metrics strong{display:block;margin-bottom:5px}.live-controls{bottom:8px;width:100%;padding:10px;gap:8px}.live-controls .btn{padding:10px}.live-controls .timer{font-size:24px;min-width:65px}.recording .capture-frame,.recording .capture-frame video{max-height:44vh}.card-play{opacity:1;transform:none;width:32px;height:32px}.review-status-panel{padding:18px}.record-setup{margin-top:12px}} +@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}} + +@media(max-width:360px){.library-filters{grid-template-columns:1fr}.library-filters .field:first-child{grid-column:auto}.library-heading .actions{flex-direction:column;align-items:stretch}.library-heading .actions>.btn{width:100%;min-height:44px}} +/* The import target stays accessible to its label without widening narrow pages. */ +.file-input.visually-hidden{position:fixed;width:1px;height:1px;left:0;top:0;padding:0;margin:0;clip-path:inset(50%);overflow:hidden} +.viewer-review{display:inline-block;margin:0 0 20px;font-size:12px} + + +.library-backup-tools{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:14px 16px;margin:12px 0;border:1px solid var(--line);border-radius:12px;background:var(--surface)} +.library-backup-tools p{margin:4px 0 0;max-width:54ch} +.library-backup-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap;flex-shrink:0} +.library-backup-actions .text-button{white-space:nowrap} +#library-backup-status{min-height:1.2em;margin:4px 0 10px} +@media(max-width:600px){.library-backup-tools{align-items:flex-start;flex-direction:column}.library-backup-actions{width:100%;justify-content:flex-start}.library-backup-actions .text-button{padding:8px 0}} + + +/* ScreenNote containment system — shared by legacy and React surfaces. */ +html,body,#root,#app,.app-shell,.main-content,.page-wrap,.share-page{width:100%;max-width:100%;min-width:0} +html,body{overflow-x:clip} +*,*::before,*::after{box-sizing:border-box}:where(.shell,.workspace,.content,.heading,.record-grid,.editor-grid,.clip-grid,.viewer-grid,.share-layout,.help-grid,.actions,.top-actions,.field-row,.comment-head,.dialog-actions)>*{min-width:0} +img,video,canvas,iframe,svg{max-width:100%} +p,h1,h2,h3,h4,h5,h6,small,strong,span,label,a,li,dd,dt,blockquote{overflow-wrap:anywhere;word-break:normal} +pre,code,kbd,samp{max-width:100%;white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word} +button,.button,.btn,[role="button"]{max-width:100%;min-width:0;white-space:normal;overflow-wrap:anywhere;line-height:1.35;text-align:center} +input,select,textarea{max-width:100%;min-width:0} +textarea{resize:vertical;overflow-wrap:anywhere} +fieldset{min-width:0;max-width:100%} +table{width:100%;max-width:100%;border-collapse:collapse} +.table-wrap,.table-scroll,.table-container,[data-table-scroll]{display:block;width:100%;max-width:100%;overflow-x:auto;overscroll-behavior-x:contain;-webkit-overflow-scrolling:touch} +table th,table td{overflow-wrap:anywhere;word-break:normal} +.flex,.row,.toolbar,.actions,.button-row,.form-row,.header-actions,.share-header-actions,.comment-composer-actions,.preview-actions,.capture-actions,.record-controls{min-width:0;max-width:100%;flex-wrap:wrap} +.grid,.clip-grid,.share-layout,.share-discussion,.share-main{min-width:0} +.grid{grid-template-columns:repeat(auto-fit,minmax(min(100%,15rem),1fr))} +.clip-grid{grid-template-columns:repeat(auto-fit,minmax(min(100%,14rem),1fr))} +.clip-card,.clip-info,.clip-info>div,.capture-copy,.capture-panel,.section-heading,.welcome-row,.topbar,.top-actions,.share-topbar,.share-layout,.share-main,.share-discussion,.discussion-list,.share-comment-form,.comment-composer-actions{min-width:0;max-width:100%} +.clip-info h3,.clip-info p,.share-heading h1,.share-heading p,.discussion-title,.share-comment-meta,.share-comment-meta strong,.share-comment p,.privacy-document,.privacy-document p,.privacy-document li{overflow-wrap:anywhere;word-break:normal} +.modal-backdrop,[role="dialog"],dialog,.modal,.preview-modal,.publish-modal{box-sizing:border-box;min-width:0;max-width:calc(100vw - 20px)} +.modal-backdrop{overflow-y:auto;overscroll-behavior:contain} +[role="dialog"],dialog,.modal,.preview-modal,.publish-modal{max-height:calc(100dvh - 20px);overflow:auto;overscroll-behavior:contain} +.share-layout{grid-template-columns:minmax(0,1.65fr) minmax(0,.85fr)} +.share-discussion{overflow-wrap:anywhere} +.share-video-wrap{min-width:0;max-width:100%} +.share-video-wrap video{max-width:100%} +.share-link-toast{max-width:calc(100vw - 24px);min-width:0} +.toast,.notice,.recovery-notice,.library-backup-tools,.bottom-note{min-width:0;max-width:100%;flex-wrap:wrap} +:focus-visible{outline-offset:3px} +@media(max-width:760px){ +.share-page{padding-inline:clamp(12px,4vw,20px)}.share-layout{grid-template-columns:minmax(0,1fr);gap:24px;margin-top:24px} +.share-topbar{height:auto;min-height:60px;flex-wrap:wrap;gap:10px;padding-block:12px} +.share-header-actions{display:flex;flex-wrap:wrap;gap:8px;min-width:0}.share-header-actions>*{max-width:100%} +.share-discussion{width:100%}.page-wrap{padding-inline:clamp(12px,4vw,24px)}.topbar{padding-inline:clamp(12px,4vw,24px)} +.capture-panel,.capture-actions,.record-controls{width:100%;min-width:0}.capture-actions>*{max-width:100%} +.library-tools{width:100%;min-width:0;flex-wrap:wrap}.search-box{min-width:0;max-width:100%} +.preview-actions,.comment-composer-actions{flex-wrap:wrap} +} +@media(max-width:420px){ +.clip-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.clip-info{gap:4px}.clip-actions{min-width:0;flex-wrap:wrap} +.button,.btn{padding-inline:10px}.share-comment-form textarea{width:100%;max-width:100%} +.share-video-meta{display:flex;flex-wrap:wrap;gap:6px 12px} +} +@media(max-width:340px){ +.clip-grid{grid-template-columns:minmax(0,1fr)}.welcome-row{flex-wrap:wrap}.welcome-art{max-width:42%;min-width:0} +.capture-actions,.record-controls{grid-template-columns:minmax(0,1fr)} +.capture-actions .button,.record-controls .button{width:100%;grid-column:auto} +} +@media(prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}} + + +/* Legacy share viewer containment: the shipped /v/:uuid route. */ +.viewer,.viewer-top,.viewer-grid,.viewer-media,.reply-panel,.video-panel,.player-tools,.reactions,.discussion-heading,.discussion-toolbar{min-width:0;max-width:100%} +.viewer-grid{grid-template-columns:minmax(0,1.55fr) minmax(0,1fr)} +.viewer-top{flex-wrap:wrap;align-items:center} +.viewer-top>*{min-width:0;max-width:100%} +.viewer .video-panel video{width:100%;max-width:100%;height:auto} +.reply-panel{overflow-wrap:anywhere} +.discussion-thread,.discussion-thread .comment,.comment-head,.comment-actions,.reply-context{min-width:0;max-width:100%;overflow-wrap:anywhere} +.discussion-thread .thread-reply{min-width:0;max-width:calc(100% - 8px)} +.discussion-heading,.comment-head,.compose-meta{flex-wrap:wrap} +@media(max-width:767px){.viewer-grid{grid-template-columns:minmax(0,1fr)}.viewer-top{gap:12px}.viewer-top>.btn{flex:0 1 auto}.viewer{padding-inline:clamp(12px,4vw,20px)}.reply-panel{max-height:none;overflow:visible}} +@media(max-width:420px){.viewer-top{padding-inline:12px}.viewer-top>.btn{width:auto}.viewer h1{overflow-wrap:anywhere}.reactions .btn{flex:1 1 100%;justify-content:flex-start}.discussion-toolbar>*{min-width:0;max-width:100%}} + + +/* Keep full-screen backdrops full-screen; constrain only the dialog surface. */ +.modal-backdrop{width:100vw;max-width:100vw;max-height:100dvh;inset:0} +.modal-backdrop>[role="dialog"],.modal-backdrop .modal,.modal-backdrop .preview-modal,.modal-backdrop .publish-modal{width:min(100%,920px);max-width:calc(100vw - 20px)} + + +/* Product-wide interaction, viewport and accessibility refinements. */ +html{scroll-padding-block:16px;scroll-behavior:smooth} +body{min-width:320px;overflow-wrap:normal} +button,a,input,select,textarea,[role="button"]{-webkit-tap-highlight-color:transparent} +a:not(.btn):not(.brand){text-decoration-thickness:1px;text-underline-offset:3px} +button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible,summary:focus-visible,[tabindex]:focus-visible{outline:3px solid #a9472b;outline-offset:3px} +:root[data-theme=dark] button:focus-visible,:root[data-theme=dark] a:focus-visible,:root[data-theme=dark] input:focus-visible,:root[data-theme=dark] select:focus-visible,:root[data-theme=dark] textarea:focus-visible,:root[data-theme=dark] summary:focus-visible,:root[data-theme=dark] [tabindex]:focus-visible{outline-color:#ffd0b9} +input,select,textarea{accent-color:var(--accent);color-scheme:inherit} +select{max-width:100%} +button:not(.timestamp),.btn,.icon-button,.nav button,.timestamp{touch-action:manipulation} +:where(.content,.viewer,.privacy,.workspace,.main-content){scroll-margin-top:16px} +:where(.sidebar,.viewer-top,.topbar){padding-top:max(12px,env(safe-area-inset-top))} +#notice{bottom:max(16px,env(safe-area-inset-bottom))} +dialog{overscroll-behavior:contain} +@media(hover:hover) and (pointer:fine){.btn:not(:disabled):hover,.icon-button:not(:disabled):hover{filter:brightness(.94);transform:translateY(-1px)}} +@media(hover:none){.btn:hover,.icon-button:hover{filter:none;transform:none}} +@media(orientation:landscape) and (max-height:520px){.sidebar{padding-top:max(12px,env(safe-area-inset-top));padding-bottom:max(12px,env(safe-area-inset-bottom))}.content,.viewer{padding-block:20px}.stage{min-height:240px}.reply-panel{max-height:60vh}} +@media(forced-colors:active){button,a,input,select,textarea,summary,[tabindex]:focus-visible{forced-color-adjust:auto}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible,summary:focus-visible{outline:2px solid Highlight}} +@media(prefers-reduced-motion:reduce){html{scroll-behavior:auto}.btn,.icon-button{transform:none!important}} + + +/* ScreenNote Studio — a distinct visual identity for the Cloudflare build. */ +:root{--bg:#f4f5f1;--panel:#fff;--soft:#e9ece5;--text:#171d19;--muted:#59645c;--line:#d5ddd4;--accent:#a6d936;--tint:#edf6d9;--dark:#111a15;--light:#f5f8ef;--surface:#fff;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-feature-settings:"ss01" on,"cv11" on} +:root[data-theme=dark]{--bg:#101512;--panel:#18211c;--soft:#222d25;--text:#edf3e9;--muted:#aab6aa;--line:#354239;--accent:#c1f36b;--tint:#293a20;--dark:#080d0a;--light:#eff8e5;--surface:#18211c;color-scheme:dark} +body{background:var(--bg);color:var(--text);font-size:14px;letter-spacing:-.01em} +.shell{grid-template-columns:248px minmax(0,1fr);background:var(--bg)} +.sidebar{width:248px;padding:30px 20px 24px;background:#111a15;color:#eef4e9;border:0} +.sidebar .brand{color:#f4f8ef;font-size:22px;letter-spacing:-1.1px}.sidebar .brand img{width:34px;height:34px} +.sidebar .nav-label{color:#91a095;margin:46px 12px 12px;font-size:9px;letter-spacing:1.8px} +.sidebar .nav{gap:5px}.sidebar .nav button{min-height:46px;border-radius:7px;color:#c7d1c7;padding:12px 13px;font-size:13px;transition:background .18s,color .18s} +.sidebar .nav button:hover{background:#26342b;color:#fff}.sidebar .nav .active{background:#c1f36b;color:#142015;font-weight:750} +.sidebar .side-note{border-color:#354239;color:#aab7aa}.sidebar .side-note strong{color:#f1f5eb} +.workspace{background:var(--bg)}.topbar{height:72px;padding-inline:clamp(20px,3.5vw,52px);border-color:var(--line);background:var(--panel)} +.topbar .tag{font-size:10px;letter-spacing:1.5px;font-weight:700}.content{max-width:1500px;padding:clamp(24px,3.6vw,54px)} +h1{font-size:clamp(34px,4.3vw,56px);font-weight:680;letter-spacing:-2.5px;line-height:1.02}h2{font-size:22px;font-weight:680;letter-spacing:-.9px}h3{font-size:15px;font-weight:700;letter-spacing:-.25px} +.eyebrow{font-size:9px;letter-spacing:2px;font-weight:800;color:#617d36}:root[data-theme=dark] .eyebrow{color:#c1f36b} +.heading{align-items:flex-end;margin-bottom:34px}.heading p{font-size:14px;line-height:1.7;max-width:520px} +.icon-button{border-radius:7px;background:var(--panel);border-color:var(--line)} +.btn{border-radius:6px;min-height:46px;padding:12px 17px;font-size:13px;font-weight:700;letter-spacing:-.01em;border-color:var(--line);box-shadow:0 1px 0 #101a1008} +.btn.primary{background:#b7ed4b;border-color:#b7ed4b;color:#152015}:root[data-theme=dark] .btn.primary{background:#c1f36b;border-color:#c1f36b;color:#111a15} +.btn.dark{background:#111a15;color:#f5f8ef;border-color:#111a15} +.panel{border-radius:8px;padding:25px;background:var(--panel);border-color:var(--line);box-shadow:0 2px 12px #17231908} +:root[data-theme=dark] .panel{box-shadow:0 2px 18px #00000014} +.record-grid{gap:20px}.stage{border-radius:8px;background:#111a15;min-height:360px;color:#eff8e5} +.stage:before{background-image:linear-gradient(#ffffff09 1px,transparent 1px),linear-gradient(90deg,#ffffff09 1px,transparent 1px);background-size:32px 32px} +.stage .screen-symbol{border-radius:5px;border-color:#a7c18a55;background:#1e3024}.stage .play-disc{background:#c1f36b;color:#142015} +.stage h2{font-size:26px;font-weight:700;letter-spacing:-1px}.stage p{color:#b8c7b7;font-size:13px} +.stage-top{border-radius:4px;border-color:#61745f;color:#e5efdf;letter-spacing:1.5px} +.record-options .option{padding:18px 0}.option strong{font-weight:700}.option input{accent-color:#91c62e} +.clip-grid{gap:16px}.clip-card{border-radius:7px;background:var(--panel);border-color:var(--line);box-shadow:0 2px 8px #15201608;animation:none} +.clip-card:hover{border-color:#9ab66d;box-shadow:0 7px 20px #15201612}.clip-art{background:var(--soft)}.clip-body{padding:18px} +.clip-body h3{font-size:14px;line-height:1.45}.empty{grid-column:1/-1;border-radius:7px;background:var(--soft);border-color:#aab9a6;padding:42px 28px} +.field input,.field textarea,.field select,select{border-radius:6px;border-color:var(--line);background:var(--panel)} +.field input:focus,.field textarea:focus,.field select:focus,select:focus{border-color:#8dbb38;box-shadow:0 0 0 3px #a6d9362b;outline:0} +.notice,.beta-note{border-radius:6px;background:var(--soft);border-color:var(--line)}.error-box{border-radius:6px} +.viewer-top{max-width:1320px;padding:22px clamp(18px,3vw,36px)}.viewer{max-width:1320px;padding:38px clamp(18px,3vw,36px)} +.viewer-grid{gap:22px}.viewer h1{font-size:clamp(28px,3.4vw,42px);letter-spacing:-1.7px} +.video-panel{border-radius:7px;background:#080d0a}.reply-panel{border-radius:7px}.comment{padding:18px 0} +.timestamp{background:var(--tint);color:var(--text);border-radius:4px} +.reactions button[aria-pressed=true]{background:var(--tint);border-color:#91c62e} +#notice{border-radius:6px;background:#111a15;color:#f3f8ed;box-shadow:0 8px 28px #0003} +dialog{border-radius:8px;box-shadow:0 22px 80px #0004}.footer{border-color:var(--line)} +:focus-visible{outline-color:#6d9e25!important;outline-offset:3px}:root[data-theme=dark] :focus-visible{outline-color:#c1f36b!important} +@media(max-width:1024px){.shell{grid-template-columns:190px minmax(0,1fr)}.sidebar{width:190px}.content{padding:28px 24px}} +@media(max-width:767px){.topbar{height:66px;padding-inline:18px}.content{padding:28px 18px}.heading{align-items:flex-start;margin-bottom:24px}.heading h1{font-size:clamp(32px,9vw,42px);letter-spacing:-1.7px}.panel{padding:20px}.stage{min-height:270px}.viewer{padding-block:26px}} +@media(max-width:420px){.content{padding-inline:15px}.topbar{padding-inline:15px}.heading h1{font-size:34px}.panel{padding:17px}.stage{min-height:250px}} + + +/* Cloudflare Studio surfaces mapped to the actual recording/editor markup. */ +.workspace-summary{padding:13px 0 25px;border-bottom:1px solid var(--line);margin-bottom:22px} +.workspace-summary .status-dot{background:#8cc63f;box-shadow:0 0 0 4px #8cc63f20} +.record-setup{border:1px solid var(--line);border-radius:8px;background:var(--panel);overflow:hidden} +.record-setup>summary{list-style:none;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:17px 21px;min-height:58px;font-size:13px;font-weight:700;cursor:pointer} +.record-setup>summary::-webkit-details-marker{display:none} +.record-setup>summary:after{content:'+';font-size:18px;color:#759d35} +.record-setup[open]>summary:after{content:'−'} +.record-setup[open]>summary{border-bottom:1px solid var(--line)} +.record-setup>.record-grid{padding:22px} +.compact-recorder{grid-template-columns:minmax(0,1.35fr) minmax(250px,.9fr);gap:18px} +.record-options{border:1px solid var(--line);border-radius:7px;background:var(--panel);padding:22px} +.recorder-intro{padding-bottom:16px;border-bottom:1px solid var(--line);margin-bottom:16px} +.recorder-intro>svg{color:#7ba52e} +.record-guide{border:0;border-radius:7px;background:#edf3e6;padding:25px;color:#1b281b} +:root[data-theme=dark] .record-guide{background:#202c23;color:#edf3e9} +.record-guide .guide-icon{border-radius:6px;background:#c1f36b;color:#142015} +.record-guide h2{font-size:24px;letter-spacing:-1px} +.record-guide ol{gap:13px} +.record-guide li strong{font-weight:750} +.record-guide .btn{border-color:#b8c7ac;background:transparent;color:inherit} +.capture-frame{border-radius:7px;border:1px solid #35473a;background:#0c140f;min-height:210px} +.capture-frame video{max-height:60vh} +.capture-frame canvas{border-radius:7px} +.recording{border:1px solid var(--line);border-radius:8px;padding:18px;background:var(--panel)} +.recording .capture-frame{margin-bottom:16px} +.recording .tool-controls{display:flex;flex-wrap:wrap;gap:10px} +.recording .tool-controls .btn{min-height:42px} +.setup-note{max-width:900px;color:var(--muted);font-size:12px} +.countdown{color:var(--text);font-variant-numeric:tabular-nums} +.library-section{padding-top:10px} +.library-heading .eyebrow{color:#718f38} +.clip-card{border-radius:7px} +.clip-art{background:linear-gradient(135deg,#dce6d2,#f0f2ec);color:#52674b} +:root[data-theme=dark] .clip-art{background:linear-gradient(135deg,#25352a,#1a241d);color:#c1f36b} +.clip-card:hover{transform:translateY(-2px);transition:transform .18s ease,border-color .18s ease,box-shadow .18s ease} +.clip-badge{border-radius:3px;letter-spacing:.5px} +.card-play{border-radius:5px} +.editor-grid{grid-template-columns:minmax(0,1.45fr) minmax(280px,.8fr)} +.editor-preview,.editor-tools,.trim-panel,.panel.reply-panel{border-radius:7px} +.video-panel{border-radius:7px} +.viewer-top{border-bottom:1px solid var(--line)} +.viewer{padding-top:32px} +.viewer .video-panel{box-shadow:0 12px 34px #07110920} +.reply-panel{border:1px solid var(--line);background:var(--panel)} +.privacy,.help-grid{max-width:880px} +@media(max-width:1024px){ + .compact-recorder{grid-template-columns:minmax(0,1fr) minmax(220px,.8fr)} + .editor-grid{grid-template-columns:minmax(0,1fr) 260px} + .clip-grid{grid-template-columns:repeat(2,minmax(0,1fr))} +} +@media(max-width:767px){ + .record-setup>.record-grid{padding:14px} + .compact-recorder,.editor-grid{grid-template-columns:minmax(0,1fr)} + .record-options,.record-guide{padding:18px} + .recording{padding:12px} + .capture-frame{min-height:160px} + .capture-frame video{max-height:48vh} + .record-guide{order:2} + .workspace-summary{font-size:11px;gap:8px} + .workspace-summary .text-button{margin-left:0} + .clip-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:11px} + .clip-body{padding:13px} + .viewer-grid{grid-template-columns:minmax(0,1fr)} + .viewer-media{position:static} +} +@media(max-width:420px){ + .clip-grid{grid-template-columns:minmax(0,1fr)} + .record-setup>summary{padding-inline:15px} + .record-setup>.record-grid{padding:10px} + .record-options,.record-guide{padding:15px} + .record-defaults{grid-template-columns:minmax(0,1fr)} + .editor-actions,.dialog-actions{flex-wrap:wrap} +} +@media(prefers-reduced-motion:reduce){.clip-card:hover{transform:none;transition:none}} + +/* ScreenNote Cloudflare redesign v2: horizontal studio shell, editorial dashboard, mobile task dock. */ +:root{--bg:#f7f4ee;--panel:#fffefa;--soft:#eee9df;--text:#201f1b;--muted:#706c63;--line:#ded8cd;--accent:#d34d2f;--tint:#f7e4dc;--dark:#201f1b;--light:#fffefa;--surface:#fffefa;color-scheme:light;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif} +:root[data-theme=dark]{--bg:#171714;--panel:#22221e;--soft:#2b2a25;--text:#f2eee5;--muted:#b7b0a3;--line:#414037;--accent:#ff9678;--tint:#3c2922;--dark:#11110f;--light:#f4eee2;--surface:#22221e;color-scheme:dark} +body{background:var(--bg);color:var(--text);font-size:14px} +.shell{display:block;min-height:100dvh;background:var(--bg)} +.sidebar{position:sticky;inset:0 0 auto;width:100%;height:76px;padding:0 clamp(20px,5vw,72px);border:0;border-bottom:1px solid var(--line);background:var(--panel);color:var(--text);display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:28px;overflow:visible;z-index:30} +.sidebar .brand{color:var(--text);font-size:22px;letter-spacing:-1.2px}.sidebar .brand img{width:30px;height:30px} +.sidebar .nav-label,.sidebar .side-note{display:none} +.sidebar .nav{height:100%;display:flex;align-items:center;gap:6px} +.sidebar .nav button{height:100%;padding:0 17px;border:0;border-bottom:2px solid transparent;border-radius:0;background:none;color:var(--muted);font-size:13px;font-weight:600;white-space:nowrap} +.sidebar .nav button.active{background:none;color:var(--text);border-bottom-color:var(--accent)} +.workspace{display:block;min-width:0} +.topbar{height:0;min-height:0;padding:0;border:0;overflow:visible;position:relative;z-index:31} +.topbar .breadcrumb,.topbar .brand{display:none} +.top-actions{position:absolute;right:clamp(20px,5vw,72px);top:-60px;gap:12px} +.top-actions .tag{display:none} +.icon-button{border-radius:3px;background:var(--panel);border-color:var(--line)} +.content{max-width:1440px;padding:34px clamp(20px,5vw,72px) 28px} +h1{font-family:Georgia,"Times New Roman",serif;font-size:clamp(42px,6vw,76px);font-weight:400;line-height:.99;letter-spacing:-2.8px} +h2{font-family:Georgia,serif;font-weight:400;letter-spacing:-.5px} +.eyebrow{color:var(--accent);font-size:10px;letter-spacing:2px;font-weight:700} +.heading.library-heading{display:grid;grid-template-columns:minmax(0,1fr) minmax(220px,310px);align-items:end;gap:42px;padding:32px 0 36px;border-bottom:1px solid var(--line);margin-bottom:0} +.library-heading>div:first-child{max-width:790px} +.library-heading h1{max-width:780px;font-size:clamp(42px,6vw,76px);margin-bottom:20px} +.library-heading p{font-size:16px;line-height:1.7;color:var(--muted);max-width:610px} +.library-heading .actions{display:flex;flex-direction:column;align-items:stretch;gap:10px;padding-bottom:4px} +.library-heading .actions .btn{width:100%;justify-content:center;min-height:50px;border-radius:3px} +.library-heading .actions .btn.primary,.btn.primary,.record-options .btn.primary{background:var(--accent);border-color:var(--accent);color:#fff} +.library-heading .actions:after{content:"NO ACCOUNT. NO VIEWER SEATS.";text-align:center;color:var(--muted);font-size:9px;letter-spacing:1.4px;margin-top:6px} +.workspace-summary{border:0;padding:14px 0 18px;margin:0;display:flex;align-items:center;gap:9px;color:var(--muted);font-size:12px} +.workspace-summary .status-dot{width:7px;height:7px;border-radius:50%;background:#5e9360;box-shadow:0 0 0 3px #5e93601b} +.workspace-summary .text-button{margin-left:auto} +.library-section{padding-top:22px}.section-head{margin:0 0 20px;padding-bottom:13px;border-bottom:1px solid var(--line)} +.section-head h2{font-size:26px}.library-backup-tools{background:transparent;border:0;border-top:1px solid var(--line);border-bottom:1px solid var(--line);border-radius:0;padding:14px 0;margin:0 0 20px} +.library-filters{display:grid;grid-template-columns:minmax(180px,1.5fr) repeat(2,minmax(130px,.65fr));gap:12px;align-items:end;margin:18px 0} +.field label{font-size:11px;color:var(--muted)}.field input,.field textarea,.field select,select{border-radius:3px;background:var(--panel);border-color:var(--line);min-height:46px} +.clip-grid{grid-template-columns:repeat(3,minmax(0,1fr));gap:18px}.clip-card{border-radius:3px;border:1px solid var(--line);box-shadow:none;background:var(--panel)} +.clip-card:hover{border-color:var(--accent);box-shadow:0 8px 24px #3c28100d;transform:translateY(-2px)} +.clip-art{border-radius:0;background:#e8e2d8;color:#6d6255}:root[data-theme=dark] .clip-art{background:#343129;color:#e5d5bf} +.clip-body{padding:17px}.clip-body h3{font-size:15px;font-weight:650}.card-actions{display:flex;gap:8px}.card-actions .btn{flex:1} +.btn{border-radius:3px;min-height:46px;font-weight:650}.panel{border-radius:3px;box-shadow:none} +.record-setup{margin-top:38px;border:0;border-top:1px solid var(--line);border-bottom:1px solid var(--line);border-radius:0;background:transparent} +.record-setup>summary{padding:20px 0;font-family:Georgia,serif;font-size:25px;font-weight:400}.record-setup>summary:after{color:var(--accent)} +.record-setup>.record-grid{padding:24px 0 28px}.compact-recorder{grid-template-columns:minmax(0,1.45fr) minmax(240px,.8fr);gap:22px} +.record-options{background:var(--panel);border:1px solid var(--line);border-radius:3px;padding:26px;box-shadow:none} +.recorder-intro h2{font-size:30px}.record-guide{background:#24231f;color:#f5f0e7;border-radius:3px;padding:28px} +.record-guide h2{font-size:29px;color:#fff}.record-guide li{color:#c9c2b7}.record-guide li strong{color:#fff}.record-guide .btn{border-color:#777065;color:#fff;background:transparent} +.capture-frame,.video-panel{border-radius:3px}.recording{border-radius:3px;background:var(--panel);border:1px solid var(--line)} +.editor-grid{grid-template-columns:minmax(0,1.5fr) minmax(280px,.75fr);gap:24px} +.viewer-top{background:var(--panel)}.privacy h1,.privacy h2{font-family:Georgia,serif;font-weight:400} +.footer{border-color:var(--line)}#notice{border-radius:3px;background:#24231f;color:#fff} +@media(max-width:900px){.sidebar{grid-template-columns:auto 1fr auto;padding-inline:24px;gap:16px}.sidebar .nav{justify-content:center}.sidebar .nav button{padding-inline:11px}.top-actions{right:24px}.clip-grid{grid-template-columns:repeat(2,minmax(0,1fr))}} +@media(max-width:680px){ +.sidebar{position:fixed;inset:auto 0 0;height:auto;min-height:68px;padding:7px 8px max(8px,env(safe-area-inset-bottom));display:block;background:var(--panel);border:0;border-top:1px solid var(--line);box-shadow:0 -8px 24px #201f1b0b} +.sidebar>.brand,.sidebar .nav-label,.sidebar .side-note{display:none} +.sidebar .nav{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));height:auto;gap:2px} +.sidebar .nav button{height:auto;min-height:54px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:3px;padding:5px;border:0;border-radius:3px;font-size:10px} +.sidebar .nav button svg{width:19px;height:19px}.sidebar .nav button.active{background:var(--tint);color:var(--accent)} +.topbar{height:64px;position:absolute;top:0;left:0;right:0;overflow:visible;border:0;background:var(--panel)} +.topbar .brand{display:flex;position:absolute;left:18px;top:14px;font-size:20px}.top-actions{top:10px;right:18px} +.content{padding:82px 18px calc(94px + env(safe-area-inset-bottom))} +.heading.library-heading{grid-template-columns:minmax(0,1fr);gap:22px;padding:23px 0 25px} +.library-heading h1{font-size:clamp(40px,11vw,58px);letter-spacing:-1.9px;line-height:1.01;margin-bottom:14px} +.library-heading p{font-size:14px;line-height:1.65}.library-heading .actions{display:grid;grid-template-columns:1fr 1fr;gap:9px} +.library-heading .actions .btn{min-height:48px;padding:10px 9px;font-size:12px}.library-heading .actions:after{grid-column:1/-1} +.workspace-summary{flex-wrap:wrap;font-size:11px;padding:13px 0}.workspace-summary .text-button{margin-left:0} +.library-section{padding-top:14px}.section-head{align-items:center;margin-bottom:15px}.section-head h2{font-size:24px} +.library-filters{grid-template-columns:1fr 1fr;gap:9px}.library-filters .field:first-child{grid-column:1/-1} +.clip-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.clip-body{padding:12px}.clip-body h3{font-size:13px} +.record-setup{margin-top:28px}.record-setup>summary{font-size:22px;padding:17px 0}.record-setup>.record-grid{padding:14px 0} +.compact-recorder,.editor-grid{grid-template-columns:minmax(0,1fr);gap:12px}.record-options,.record-guide{padding:18px}.editor-grid>aside{display:block} +.footer{display:block;margin-top:38px}.footer>span{display:block;margin:8px 0} +} +@media(max-width:390px){.content{padding-inline:14px}.library-heading h1{font-size:40px}.library-heading .actions{grid-template-columns:1fr}.library-heading .actions:after{grid-column:auto}.clip-grid,.library-filters{grid-template-columns:minmax(0,1fr)}.library-filters .field:first-child{grid-column:auto}.record-options{padding:15px}} +@media(prefers-reduced-motion:reduce){.clip-card:hover{transform:none}} + +/* Header action placement for the new horizontal shell. */ +@media(min-width:681px){.topbar{position:fixed;top:15px;right:clamp(20px,5vw,72px);width:auto;height:auto;min-height:0;z-index:35}.top-actions{position:static;gap:10px}} + +/* Keep the warm accent coherent in both themes; remove inherited lime-only controls. */ +:root[data-theme=dark] .btn.primary,:root[data-theme=dark] .record-options .btn.primary{background:var(--accent);border-color:var(--accent);color:#211b17} +:root[data-theme=dark] .dashboard-copy .eyebrow,:root[data-theme=dark] .recorder-intro>svg{color:var(--accent)} +:root[data-theme=dark] .record-guide .guide-icon{background:var(--accent);color:#211b17} +:root[data-theme=dark] .record-options input{accent-color:var(--accent)} diff --git a/rebuild/legacy/public/sw.js b/rebuild/legacy/public/sw.js new file mode 100644 index 0000000..4d4d549 --- /dev/null +++ b/rebuild/legacy/public/sw.js @@ -0,0 +1,45 @@ +const CACHE_NAME = "screennote-react-shell-v4"; +const APP_SHELL = ["/", "/manifest.webmanifest", "/icon.svg"]; + +self.addEventListener("install", (event) => { + event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL)).then(() => self.skipWaiting())); +}); + +self.addEventListener("activate", (event) => { + event.waitUntil( + caches.keys() + .then((keys) => Promise.all(keys.filter((key) => key.startsWith("screennote-shell-") && key !== CACHE_NAME).map((key) => caches.delete(key)))) + .then(() => self.clients.claim()) + ); +}); + +self.addEventListener("fetch", (event) => { + const request = event.request; + const url = new URL(request.url); + if (request.method !== "GET" || url.origin !== self.location.origin || url.pathname.startsWith("/api/") || request.headers.has("range")) return; + + if (request.mode === "navigate") { + event.respondWith( + fetch(request).then((response) => { + if (response.ok) { + const copy = response.clone(); + event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.put("/", copy))); + } + return response; + }).catch(async () => (await caches.match("/")) || (await caches.match("/index.html")) || new Response("ScreenNote is offline. Reconnect and try again.", { status: 503, headers: { "content-type": "text/plain; charset=utf-8" } })) + ); + return; + } + + if (url.pathname.startsWith("/assets/") || APP_SHELL.includes(url.pathname)) { + event.respondWith( + (async () => { + const cached = await caches.match(request); + if (cached) return cached; + const response = await fetch(request); + if (response.ok) await caches.open(CACHE_NAME).then((cache) => cache.put(request, response.clone())); + return response; + })() + ); + } +}); \ No newline at end of file diff --git a/rebuild/legacy/public/ticker.js b/rebuild/legacy/public/ticker.js new file mode 100644 index 0000000..1b9fd8e --- /dev/null +++ b/rebuild/legacy/public/ticker.js @@ -0,0 +1 @@ +setInterval(()=>postMessage('frame'),1000/24); diff --git a/rebuild/package.json b/rebuild/package.json new file mode 100644 index 0000000..2dd751d --- /dev/null +++ b/rebuild/package.json @@ -0,0 +1,38 @@ +{ + "name": "screennote-rebuild", + "private": true, + "version": "1.0.0", + "type": "module", + "scripts": { + "dev": "vite --host 0.0.0.0", + "build": "node scripts/prepare-public.mjs && cf build", + "typecheck": "tsc --noEmit", + "test": "vitest run tests", + "deploy": "cf deploy", + "e2e": "playwright test", + "perf:budget": "node scripts/performance-budget.mjs" + }, + "dependencies": { + "lucide-react": "^0.468.0", + "react": "^19.1.0", + "react-dom": "^19.1.0", + "fix-webm-duration": "1.0.6", + "mediabunny": "1.62.1", + "fflate": "0.8.2" + }, + "devDependencies": { + "@cloudflare/vite-plugin": "^2.0.0-rc.0", + "@cloudflare/workers-types": "^5.20261124.1", + "@types/react": "^19.1.0", + "@types/react-dom": "^19.1.0", + "@vitejs/plugin-react": "^5.0.0", + "cf": "^1.0.0-rc.4", + "typescript": "^5.9.0", + "vite": "^7.1.0", + "vitest": "^3.2.0", + "fake-indexeddb": "^6.2.0", + "@playwright/test": "^1.56.0", + "@types/node": "^24.0.0", + "esbuild": "0.28.2" + } +} diff --git a/rebuild/playwright.config.ts b/rebuild/playwright.config.ts new file mode 100644 index 0000000..7c54eb5 --- /dev/null +++ b/rebuild/playwright.config.ts @@ -0,0 +1,23 @@ +import { defineConfig } from "@playwright/test"; + +export default defineConfig({ + testDir: "./e2e", + fullyParallel: true, + reporter: [["list"]], + timeout: 45_000, + expect: { timeout: 8_000 }, + use: { + baseURL: "http://127.0.0.1:4173", + browserName: "chromium", + headless: true, + viewport: { width: 1440, height: 900 }, + screenshot: "only-on-failure" + }, + webServer: { + command: "npm run dev -- --port 4173", + url: "http://127.0.0.1:4173", + reuseExistingServer: !process.env.CI, + timeout: 120_000 + }, + outputDir: "test-results" +}); \ No newline at end of file diff --git a/rebuild/public/_headers b/rebuild/public/_headers new file mode 100644 index 0000000..4b7a883 --- /dev/null +++ b/rebuild/public/_headers @@ -0,0 +1,5 @@ +/index.html + Cache-Control: no-cache + +/sw.js + Cache-Control: no-cache diff --git a/rebuild/public/icon.svg b/rebuild/public/icon.svg new file mode 100644 index 0000000..cfa08bf --- /dev/null +++ b/rebuild/public/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/rebuild/public/manifest.webmanifest b/rebuild/public/manifest.webmanifest new file mode 100644 index 0000000..e5cc303 --- /dev/null +++ b/rebuild/public/manifest.webmanifest @@ -0,0 +1,11 @@ +{ + "name": "ScreenNote", + "short_name": "ScreenNote", + "description": "Clear screen recordings, thoughtful conversations.", + "start_url": "/", + "scope": "/", + "display": "standalone", + "background_color": "#f7f7f4", + "theme_color": "#f7f7f4", + "icons": [{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any maskable" }] +} \ No newline at end of file diff --git a/rebuild/public/sw.js b/rebuild/public/sw.js new file mode 100644 index 0000000..a651b41 --- /dev/null +++ b/rebuild/public/sw.js @@ -0,0 +1,45 @@ +const CACHE_NAME = "screennote-shell-v1"; +const APP_SHELL = ["/", "/manifest.webmanifest", "/icon.svg"]; + +self.addEventListener("install", (event) => { + event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL)).then(() => self.skipWaiting())); +}); + +self.addEventListener("activate", (event) => { + event.waitUntil( + caches.keys() + .then((keys) => Promise.all(keys.filter((key) => key.startsWith("screennote-shell-") && key !== CACHE_NAME).map((key) => caches.delete(key)))) + .then(() => self.clients.claim()) + ); +}); + +self.addEventListener("fetch", (event) => { + const request = event.request; + const url = new URL(request.url); + if (request.method !== "GET" || url.origin !== self.location.origin || url.pathname.startsWith("/api/") || request.headers.has("range")) return; + + if (request.mode === "navigate") { + event.respondWith( + fetch(request).then((response) => { + if (response.ok) { + const copy = response.clone(); + event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.put("/", copy))); + } + return response; + }).catch(async () => (await caches.match("/")) || (await caches.match("/index.html")) || new Response("ScreenNote is offline. Reconnect and try again.", { status: 503, headers: { "content-type": "text/plain; charset=utf-8" } })) + ); + return; + } + + if (url.pathname.startsWith("/assets/") || APP_SHELL.includes(url.pathname)) { + event.respondWith( + (async () => { + const cached = await caches.match(request); + if (cached) return cached; + const response = await fetch(request); + if (response.ok) await caches.open(CACHE_NAME).then((cache) => cache.put(request, response.clone())); + return response; + })() + ); + } +}); \ No newline at end of file diff --git a/rebuild/scripts/apply-migrations.mjs b/rebuild/scripts/apply-migrations.mjs new file mode 100644 index 0000000..f02a3c2 --- /dev/null +++ b/rebuild/scripts/apply-migrations.mjs @@ -0,0 +1,24 @@ +import { readFile } from "node:fs/promises"; +const accountId = process.env.CLOUDFLARE_ACCOUNT_ID; +const token = process.env.CLOUDFLARE_API_TOKEN; +const databaseId = "44a5859b-6411-4513-bd17-3302fbbc0575"; +if (!accountId || !token) throw new Error("Cloudflare account and API token are required to apply D1 migrations."); +for (const migrationFile of ["0001_initial.sql", "0002_temporary_sharing.sql", "0003_frame_annotations.sql", "0004_password_attempt_limits.sql", "0005_legacy_clip_api.sql", "0006_legacy_cleanup_cursor.sql", "0007_legacy_clip_tombstones.sql", "0008_share_details.sql", "0009_resumable_recording_uploads.sql", "0010_share_reactions.sql", "0011_share_reviews.sql", "0012_share_action_rate_limits.sql"]) { + const migration = await readFile(new URL("../worker/migrations/" + migrationFile, import.meta.url), "utf8"); + const statements = migration.split(";").map(statement => statement.trim()).filter(Boolean); + for (const sql of statements) { + const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${accountId}/d1/database/${databaseId}/query`, { + method: "POST", + headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + body: JSON.stringify({ sql }) + }); + const result = await response.json(); + const duplicateColumn = sql.startsWith("ALTER TABLE") + && (result.errors ?? []).some(error => String(error.message || "").toLowerCase().includes("duplicate column")); + if (duplicateColumn) continue; + if (!response.ok || !result.success || result.errors?.length) { + throw new Error(`D1 migration ${migrationFile} failed: ${JSON.stringify(result.errors ?? result)}`); + } + } + process.stdout.write("D1 migration applied: " + migrationFile + "\n"); +} diff --git a/rebuild/scripts/live-browser-smoke.mjs b/rebuild/scripts/live-browser-smoke.mjs new file mode 100644 index 0000000..e381719 --- /dev/null +++ b/rebuild/scripts/live-browser-smoke.mjs @@ -0,0 +1,147 @@ +import assert from "node:assert/strict"; +import { mkdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { chromium, expect } from "@playwright/test"; + +const base = process.env.SCREENNOTE_LIVE_URL || "https://screennote-dev.buttercoder-dev.workers.dev"; +const origin = new URL(base).origin; +const sample = fileURLToPath(new URL("../legacy/public/sample.webm", import.meta.url)); +const output = path.resolve("test-results/live-browser-smoke"); +const password = "LiveScreenNote2026"; +await mkdir(output, { recursive: true }); + +let browser, creatorContext, guestContext, recovery; +try { + browser = await chromium.launch({ headless: true }); + creatorContext = await browser.newContext({ viewport: { width: 1280, height: 900 }, acceptDownloads: true }); + const creator = await creatorContext.newPage(); + creator.on("console", message => { if (message.type() === "error") console.error("[live browser console]", message.text()); }); + creator.on("pageerror", error => console.error("[live browser page error]", error)); + creator.on("requestfailed", request => console.error("[live browser request failed]", request.url(), request.failure()?.errorText)); + creator.on("response", response => { if (response.status() >= 400 && new URL(response.url()).origin === origin) console.error("[live browser HTTP]", response.status(), response.url()); }); + await creator.goto(base, { waitUntil: "domcontentloaded" }); + await creator.getByRole("heading", { name: /Make it clear/i }).waitFor(); + await creator.locator('input[type="file"]').first().setInputFiles(sample); + const importedHeading = creator.locator(".clip-card h3").first(); + try { await importedHeading.waitFor({ timeout: 20000 }); } + catch (error) { + await creator.screenshot({ path: path.join(output, "creator-import-failure.png"), fullPage: true }); + console.error("[live browser import diagnostics]", JSON.stringify({ titles: await creator.locator(".clip-card h3").allTextContents(), statuses: await creator.locator("[role=status]").allTextContents(), body: (await creator.locator("body").innerText()).slice(0, 4000) })); + throw error; + } + const importedTitle = (await importedHeading.textContent() || "").replace(/\s+/g, " ").trim(); + assert.match(importedTitle, /sample/i, "the imported sample file should appear in the library"); + await creator.locator(".clip-thumb").waitFor(); + await creator.screenshot({ path: path.join(output, "creator-library.png"), fullPage: true }); + + await creator.getByRole("button", { name: /Preview/i }).click(); + await creator.locator(".preview-workspace video").waitFor(); + await creator.getByRole("button", { name: /Open editor/i }).click(); + await creator.locator(".editor-workspace").waitFor(); + await creator.getByRole("button", { name: "Close editor" }).click(); + + await creator.getByRole("button", { name: "Share " + importedTitle }).click(); + await creator.getByRole("heading", { name: "Make a temporary link" }).waitFor(); + await creator.locator(".publish-modal input[type=password]").fill(password); + await creator.locator(".review-brief-fields > summary").click(); + await creator.getByLabel("Review purpose").fill("Live browser acceptance"); + await creator.getByLabel("Review focus areas").fill("Verify guest feedback and creator controls"); + await creator.getByLabel("Expected outcome").fill("The shared clip is reviewed and can be revoked"); + await creator.getByLabel("Requested action").selectOption("approve"); + await creator.getByRole("button", { name: "Publish temporary link" }).click(); + await creator.locator(".share-link-toast").waitFor({ timeout: 60000 }); + const link = await creator.locator(".share-link-toast a").getAttribute("href"); + assert.ok(link, "publish flow must provide a real share URL"); + const shareUrl = new URL(link, base); + const token = shareUrl.pathname.split("/").filter(Boolean).at(-1); + assert.match(token || "", /^[A-Za-z0-9_-]{32,64}$/, "published URL must contain a valid share token"); + + const recoveryDownloadPromise = creator.waitForEvent("download"); + await creator.getByRole("button", { name: "Recovery key" }).click(); + const recoveryDownload = await recoveryDownloadPromise; + const recoveryPath = await recoveryDownload.path(); + assert.ok(recoveryPath, "creator recovery key must download"); + recovery = JSON.parse(await readFile(recoveryPath, "utf8")); + assert.equal(recovery.format, "screennote-share-recovery"); + assert.equal(recovery.shareToken, token); + assert.match(recovery.ownerKey, /^[a-f0-9]{64}$/); + await creator.screenshot({ path: path.join(output, "creator-published.png"), fullPage: true }); + + guestContext = await browser.newContext({ viewport: { width: 320, height: 640 }, acceptDownloads: true }); + const guest = await guestContext.newPage(); + await guest.goto(shareUrl.toString(), { waitUntil: "domcontentloaded" }); + await guest.getByRole("heading", { name: "This ScreenNote is private." }).waitFor(); + await guest.getByLabel("Password").fill("wrong-password"); + await guest.getByRole("button", { name: /Unlock video/i }).click(); + await guest.locator(".share-error").waitFor(); + await guest.getByLabel("Password").fill(password); + await guest.getByRole("button", { name: /Unlock video/i }).click(); + await guest.locator(".share-heading h1").waitFor({ timeout: 20000 }); + await guest.getByRole("heading", { name: "Live browser acceptance" }).waitFor(); + assert.equal(await guest.getByRole("button", { name: "Stop sharing" }).count(), 0, "guest must not receive creator controls"); + const dimensions = await guest.evaluate(() => ({ document: document.documentElement.scrollWidth, viewport: innerWidth })); + assert.ok(dimensions.document <= dimensions.viewport + 1, "live guest viewer must not overflow at 320px: " + JSON.stringify(dimensions)); + + const like = guest.getByRole("button", { name: /Like/ }).first(); + await like.click(); + await expect(like).toHaveAttribute("aria-pressed", "true", { timeout: 15000 }); + + await guest.getByLabel("Timestamped comment").fill("Live browser QA note"); + await guest.getByRole("button", { name: "Post comment" }).click(); + await guest.getByText("Live browser QA note", { exact: true }).waitFor({ timeout: 15000 }); + + await guest.getByRole("button", { name: "Looks good" }).click(); + await guest.getByLabel("Reviewer display name").fill("Live QA guest"); + await guest.getByLabel("Review note").fill("Reviewed through the deployed browser flow."); + await guest.getByRole("button", { name: "Save decision" }).click(); + await guest.getByText("Your review decision has been saved.", { exact: true }).waitFor({ timeout: 15000 }); + await guest.getByText("Live QA guest", { exact: true }).waitFor(); + await guest.screenshot({ path: path.join(output, "guest-review-320.png"), fullPage: true }); + + await creator.goto(shareUrl.toString(), { waitUntil: "domcontentloaded" }); + await creator.getByRole("heading", { name: "This ScreenNote is private." }).waitFor(); + await creator.getByLabel("Password").fill(password); + await creator.getByRole("button", { name: /Unlock video/i }).click(); + await creator.locator(".share-heading h1").waitFor({ timeout: 20000 }); + await creator.getByRole("button", { name: "Download review packet" }).waitFor(); + await creator.getByRole("button", { name: "Mark changes requested" }).waitFor(); + const packetPromise = creator.waitForEvent("download"); + await creator.getByRole("button", { name: "Download review packet" }).click(); + const packet = await packetPromise; + assert.match(packet.suggestedFilename(), /review-packet\.md$/); + + const resolveButton = creator.getByRole("button", { name: "Resolve" }).first(); + await resolveButton.waitFor(); + await resolveButton.click(); + await creator.getByText("Resolved", { exact: true }).waitFor(); + + await creator.getByRole("button", { name: "Mark changes requested" }).click(); + await creator.locator(".shared-review-status").getByText("Changes requested", { exact: true }).waitFor(); + await creator.getByRole("button", { name: "Mark complete" }).click(); + await creator.locator(".shared-review-status").getByText("Approved", { exact: true }).waitFor(); + await creator.screenshot({ path: path.join(output, "creator-review-1440.png"), fullPage: true }); + + creator.once("dialog", dialog => dialog.accept()); + await creator.getByRole("button", { name: "Stop sharing" }).click(); + await creator.getByText(/You stopped sharing/i).waitFor(); + await guest.reload(); + await guest.getByRole("heading", { name: "This moment has ended." }).waitFor({ timeout: 15000 }); + await guest.screenshot({ path: path.join(output, "guest-revoked-320.png"), fullPage: true }); + + console.log("Live browser acceptance passed: local import, preview/editor, real password-protected publish, isolated guest unlock/reaction/comment/review, creator moderation/status/packet and revocation."); +} finally { + if (recovery?.shareToken && recovery?.ownerKey) { + try { + const response = await fetch(origin + "/api/share/" + recovery.shareToken + "/manage", { + method: "DELETE", + headers: { origin, "content-type": "application/json" }, + body: JSON.stringify({ ownerKey: recovery.ownerKey }) + }); + assert.ok([200, 404].includes(response.status), "live smoke cleanup failed with " + response.status); + } catch (error) { console.error("Live browser smoke cleanup warning:", error); } + } + await guestContext?.close().catch(() => undefined); + await creatorContext?.close().catch(() => undefined); + await browser?.close().catch(() => undefined); +} diff --git a/rebuild/scripts/live-smoke.mjs b/rebuild/scripts/live-smoke.mjs new file mode 100644 index 0000000..a962a76 --- /dev/null +++ b/rebuild/scripts/live-smoke.mjs @@ -0,0 +1,294 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { Input, BufferSource, WEBM } from "mediabunny"; +import assert from "node:assert/strict"; + +const base = process.env.SCREENNOTE_LIVE_URL || "https://screennote-dev.buttercoder-dev.workers.dev"; +const origin = new URL(base).origin; +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +async function request(path, options = {}) { + const response = await fetch(origin + path, { redirect: "manual", ...options }); + return response; +} +async function json(response) { + const body = await response.json(); + assert.ok(response.ok, `${response.status} ${JSON.stringify(body)}`); + return body; +} +async function retryHealth() { + let last; + for (let i = 0; i < 30; i++) { + try { + const response = await request("/api/health"); + if (response.ok) return await json(response); + last = new Error(`health status ${response.status}`); + } catch (error) { last = error; } + await wait(2000); + } + throw last ?? new Error("Live health check did not become ready."); +} +const health = await retryHealth(); +assert.equal(health.status, "ok"); +const homeResponse = await fetch(origin + "/", { redirect: "follow" }); +assert.equal(homeResponse.headers.get("x-frame-options"), "DENY"); +assert.equal(homeResponse.headers.get("referrer-policy"), "strict-origin-when-cross-origin"); +assert.match(homeResponse.headers.get("content-security-policy") ?? "", /frame-ancestors 'none'/); +const page = await jsonText(homeResponse); +assert.match(page, / item.part), [0], "uploaded part is available for resume"); +const uploaded = await request(`/api/recordings/${recording.id}/complete`, { method:"POST", headers, body:"{}" }); +if (uploaded.status !== 200) { + await request("/api/recordings/" + recording.id, { method:"DELETE", headers, body:JSON.stringify({ ownerKey }) }).catch(() => undefined); +} +assert.equal(uploaded.status, 200, "resumable R2 upload assembles successfully"); +assert.equal((await json(uploaded)).status, "ready"); + +const publishResponse = await request(`/api/recordings/${recording.id}/publish`, { + method: "POST", headers, + body: JSON.stringify({ expiresInDays: 1, password: "live-check-password", ownerKey }) +}); +if (publishResponse.status !== 201) { + await request("/api/recordings/" + recording.id, { method:"DELETE", headers, body:JSON.stringify({ ownerKey }) }).catch(() => undefined); +} +const published = await json(publishResponse); +shareToken = published.token; +const token = shareToken; +assert.ok(token, "share token returned"); +const sharePath = `/api/share/${token}`; +assert.equal((await request(sharePath)).status, 401, "password protects share metadata"); +assert.equal((await request(sharePath + "/access", { + method: "POST", headers: { origin, "content-type": "application/json" }, + body: JSON.stringify({ password: "wrong-password" }) +})).status, 401, "wrong password rejected"); +const sharedDetails = { + annotations: [{ kind: "redact", x: .1, y: .1, w: .2, h: .2 }], + captions: [{ start: 1, end: 2, text: "Owner-supplied live caption" }], + chapters: [{ time: 1, title: "Live chapter" }], + report: { url: "https://example.com/checkout", steps: "Open checkout", expected: "Payment appears", actual: "Payment is missing", environment: "GitHub Actions" }, + reviewBrief: { purpose: "Review the checkout", focus: "Payment confirmation", expectedOutcome: "Receipt is shown", requestedAction: "approve" }, + reviewStatus: "changes-requested" +}; +const detailsSaved = await request(sharePath + "/details", { + method: "PUT", headers: { origin, "content-type": "application/json" }, + body: JSON.stringify({ ownerKey, details: sharedDetails }) +}); +assert.equal(detailsSaved.status, 200, "owner can save shared captions, chapters, annotations and bug report before viewer unlock"); +const accessResponse = await request(sharePath + "/access", { + method: "POST", headers: { origin, "content-type": "application/json" }, + body: JSON.stringify({ password: "live-check-password" }) +}); +assert.equal(accessResponse.status, 200, "correct password unlocks share"); +const accessCookie = accessResponse.headers.get("set-cookie")?.split(";")[0]; +assert.ok(accessCookie, "password access cookie is set"); +for (let i = 0; i < 5; i++) { + const failed = await request(sharePath + "/access", { + method:"POST", headers:{origin,"content-type":"application/json"}, + body:JSON.stringify({password:"wrong-password-again"}) + }); + assert.equal(failed.status, i === 4 ? 429 : 401, "password attempts are throttled after five failures"); +} +const lockedCorrect = await request(sharePath + "/access", { + method:"POST", headers:{origin,"content-type":"application/json"}, + body:JSON.stringify({password:"live-check-password"}) +}); +assert.equal(lockedCorrect.status, 429, "correct password is held during the temporary lockout"); +const viewerHeaders = { origin, cookie: accessCookie, "content-type": "application/json" }; +const share = await json(await request(sharePath, { headers: viewerHeaders })); +const contextResponse = await json(await request(sharePath + "/details", { headers: viewerHeaders })); +assert.deepEqual(contextResponse.details, sharedDetails, "authorized viewers receive the saved shared context"); +const reviewerKey = randomBytes(32).toString("hex"); +const reviewSaved = await request(sharePath + "/reviews", { method:"POST", headers:viewerHeaders, body:JSON.stringify({reviewerKey,reviewerLabel:"Live guest",decision:"changes-requested",comment:"Payment state needs correction",time:4}) }); +assert.equal(reviewSaved.status,200,"guest review decision is stored without an account"); +const reviewList = await json(await request(sharePath + "/reviews",{headers:{cookie:accessCookie,"x-reviewer-key":reviewerKey}})); +assert.equal(reviewList.myReview.decision,"changes-requested"); +assert.equal(reviewList.myReview.comment,"Payment state needs correction"); +const ownerStatusDetails={...sharedDetails,reviewStatus:"approved"}; +const ownerStatusSave=await request(sharePath+"/details",{method:"PUT",headers:{origin,"content-type":"application/json"},body:JSON.stringify({ownerKey,details:ownerStatusDetails})}); +assert.equal(ownerStatusSave.status,200,"creator can close the review after acting on guest feedback"); +const statusAfterReview=await json(await request(sharePath+"/details",{headers:{cookie:accessCookie}})); +assert.equal(statusAfterReview.details.reviewStatus,"approved","review completion status is persisted for the share page"); +const voterKey = randomBytes(32).toString("hex"); +const reaction = await json(await request(sharePath + "/reactions", { + method: "POST", headers: { origin, cookie: accessCookie, "content-type": "application/json" }, + body: JSON.stringify({ voterKey, reaction: "thanks" }) +})); +assert.equal(reaction.counts.thanks, 1, "anonymous viewer reaction is stored"); +const ownReaction = await json(await request(sharePath + "/reactions", { headers: { cookie: accessCookie, "x-voter-key": voterKey } })); +assert.equal(ownReaction.myReaction, "thanks", "the same browser can retrieve its reaction"); +assert.equal(share.title, "Live acceptance check"); +assert.equal(share.passwordRequired, true); +const media = await request(sharePath + "/media", { headers: { cookie: accessCookie, range: "bytes=2-7" } }); +assert.equal(media.status, 206, "R2 video supports range playback"); +assert.equal(media.headers.get("content-range"), "bytes 2-7/12"); +assert.equal((await media.arrayBuffer()).byteLength, 6); + +const authorKey = "b".repeat(48), replyKey = "c".repeat(48); +const commentsPath = sharePath + "/comments"; +const comment = await json(await request(commentsPath, { + method: "POST", headers: viewerHeaders, + body: JSON.stringify({ authorKey, text: "Live lifecycle comment", time: 4, anchorX: 0.3, anchorY: 0.6 }) +})); +assert.equal((await request(commentsPath, { headers: { cookie: accessCookie, "x-sn-author-key": authorKey } })).status, 200); +const reply = await json(await request(commentsPath, { + method: "POST", headers: viewerHeaders, + body: JSON.stringify({ authorKey: replyKey, parentId: comment.id, text: "Live threaded reply", time: 4 }) +})); +assert.ok(reply.id); +const resolved = await request(commentsPath + "/" + comment.id + "/resolve", { + method: "PATCH", headers: viewerHeaders, + body: JSON.stringify({ ownerKey, resolved: true }) +}); +assert.equal(resolved.status, 200, "owner can resolve a thread"); +const edited = await request(commentsPath + "/" + comment.id, { + method: "PATCH", headers: viewerHeaders, + body: JSON.stringify({ authorKey, text: "Edited live lifecycle comment" }) +}); +assert.equal(edited.status, 200, "comment author can edit"); +const deleted = await request(commentsPath + "/" + comment.id, { + method: "DELETE", headers: viewerHeaders, + body: JSON.stringify({ authorKey }) +}); +assert.equal(deleted.status, 200, "comment author can delete"); +for (let i = 0; i < 10; i++) { + const allowed = await request(commentsPath, { method:"POST", headers:viewerHeaders, body:JSON.stringify({authorKey:randomBytes(24).toString("hex"),text:"Live rate limit probe "+i,time:4,viewerLabel:"Live QA"}) }); + assert.equal(allowed.status, 201, "comment action remains available up to its configured limit"); +} +const throttledComment = await request(commentsPath, { method:"POST", headers:viewerHeaders, body:JSON.stringify({authorKey:randomBytes(24).toString("hex"),text:"Live rate limit overflow",time:4,viewerLabel:"Live QA"}) }); +assert.equal(throttledComment.status,429,"deployed share comment endpoint throttles excessive guest writes"); + +const stopped = await request(sharePath + "/manage", { + method: "DELETE", headers: { origin, "content-type": "application/json" }, + body: JSON.stringify({ ownerKey }) +}); +assert.equal(stopped.status, 200, "owner can stop share and delete shared object"); +assert.equal((await request(sharePath)).status, 404, "stopped share is no longer available"); +shareToken = null; +recordingId = null; +console.log("Live ScreenNote acceptance passed: assets, guest session, resumable D1/R2 upload, password gate and lockout, byte-range media, comments/replies/edit/delete, comment rate limiting, resolve, and stop-share deletion."); +} catch (error) { + if (shareToken) { + await request(`/api/share/${shareToken}/manage`, { method:"DELETE", headers:{origin,"content-type":"application/json"}, body:JSON.stringify({ownerKey}) }).catch(() => undefined); + } else if (recordingId) { + await request(`/api/recordings/${recordingId}`, { method:"DELETE", headers:{cookie:sessionCookie,origin,"content-type":"application/json"}, body:JSON.stringify({ownerKey}) }).catch(() => undefined); + } + throw error; +} + +// Full 0.5.0 API parity smoke against the deployed Cloudflare D1/R2 implementation. +const nativeHealth = await json(await request("/api/clip?op=health")); +assert.equal(nativeHealth.configured,true); +assert.equal(nativeHealth.maxBytes,50_000_000); +assert.equal(nativeHealth.maxSeconds,600); +const sampleResponse = await request("/sample.webm"); +assert.equal(sampleResponse.status,200,"original sample video is served by Cloudflare assets"); +const sampleBytes = new Uint8Array(await sampleResponse.arrayBuffer()); +assert.ok(sampleBytes.length>4 && sampleBytes.length<=50_000_000); +const sampleInput=new Input({source:new BufferSource(sampleBytes),formats:[WEBM]}); +const sampleVideo=await sampleInput.getPrimaryVideoTrack(),sampleDuration=await sampleInput.getDurationFromMetadata(); +assert.ok(sampleVideo&&sampleDuration&&sampleDuration>1&&sampleDuration<=600); +const sampleWidth=sampleVideo.displayWidth,sampleHeight=sampleVideo.displayHeight;sampleInput.dispose(); +const nativeId = randomUUID(); +const nativeOwner = randomBytes(32).toString("hex"); +const nativePassword = "cloudflare-native-live-check"; +let nativeReserved = false; +const nativeHeaders = {origin,"content-type":"application/json"}; +const nativeApi = (op,body={},id=nativeId)=>request("/api/clip?op="+op+(id?"&id="+encodeURIComponent(id):""),{method:"POST",headers:nativeHeaders,body:JSON.stringify(body)}); +try { + const reservation = await json(await nativeApi("reserve",{ + id:nativeId,owner:nativeOwner,title:"Native Cloudflare parity smoke",type:"video/webm",duration:sampleDuration,size:sampleBytes.length, + start:0,end:sampleDuration,linkDays:1,password:nativePassword,reviewStatus:"needs-feedback",width:sampleWidth,height:sampleHeight, + captions:[{start:0,end:Math.min(1,sampleDuration),text:"A live caption"}],chapters:[{time:Math.min(1,sampleDuration/2),title:"Live chapter"}], + report:{url:"https://example.com/live-smoke",steps:"Open the sample",expected:"Video loads",actual:"Video loads",environment:"GitHub Actions"} + })); + nativeReserved=true; + assert.equal(reservation.id,nativeId); + const partBytes=2*1024*1024; + for(let part=0,offset=0;offseti)); + const published=await json(await nativeApi("publish",{id:nativeId,owner:nativeOwner,width:sampleWidth,height:sampleHeight})); + assert.equal(published.passwordProtected,true); + assert.equal(published.title,"Native Cloudflare parity smoke"); + const noPassword=await request("/api/clip?op=view&id="+nativeId); + assert.equal(noPassword.status,401,"native share password gate is enforced"); + const wrong=await nativeApi("view",{id:nativeId,accessPassword:"wrong-password"}); + assert.equal(wrong.status,401,"wrong native share password is rejected"); + const view=await json(await nativeApi("view",{id:nativeId,accessPassword:nativePassword})); + assert.equal(view.passwordProtected,true); + assert.equal(view.captions[0].text,"A live caption"); + assert.equal(view.chapters[0].title,"Live chapter"); + assert.equal(view.report.steps,"Open the sample"); + const range=await fetch(view.mediaUrl,{headers:{range:"bytes=0-63"}}); + assert.equal(range.status,206,"native R2 media supports byte ranges"); + assert.equal(range.headers.get("content-range"),"bytes 0-63/"+sampleBytes.length); + assert.equal((await range.arrayBuffer()).byteLength,64); + const viewer=randomUUID(),authorKey=randomBytes(32).toString("hex"),eventId=randomUUID(); + const posted=await json(await nativeApi("comment",{id:nativeId,owner:nativeOwner,viewer,eventId,authorKey,name:"Live QA",text:"Native comment",time:2,accessPassword:nativePassword})); + const root=posted.comments.find(x=>x.id===eventId);assert.ok(root); + const replyId=randomUUID(); + const replied=await json(await nativeApi("comment",{id:nativeId,viewer:randomUUID(),eventId:replyId,authorKey:randomBytes(32).toString("hex"),name:"Guest",text:"Nested reply",time:2,parentId:eventId,accessPassword:nativePassword})); + assert.equal(replied.comments.find(x=>x.id===replyId).parentId,eventId); + await json(await nativeApi("edit-comment",{id:nativeId,viewer,authorKey,commentId:eventId,expectedVersion:root.createdAt,text:"Edited native comment",accessPassword:nativePassword})); + await json(await nativeApi("resolve-thread",{id:nativeId,viewer,owner:nativeOwner,commentId:eventId,resolved:true,accessPassword:nativePassword})); + await json(await nativeApi("reaction",{id:nativeId,viewer:randomUUID(),reaction:"thanks",accessPassword:nativePassword})); + const title=await json(await nativeApi("title",{id:nativeId,owner:nativeOwner,title:"Native parity verified"}));assert.equal(title.title,"Native parity verified"); + const status=await json(await nativeApi("review-status",{id:nativeId,owner:nativeOwner,reviewStatus:"approved"}));assert.equal(status.reviewStatus,"approved"); + const manage=await json(await nativeApi("manage",{id:nativeId,owner:nativeOwner}));assert.equal(manage.status,"published"); + const restored=await json(await nativeApi("restore-media",{id:nativeId,owner:nativeOwner}));assert.match(restored.mediaUrl,/op=media/); + await json(await nativeApi("delete-comment",{id:nativeId,viewer,authorKey,commentId:eventId,accessPassword:nativePassword})); + for(let attempt=0;attempt<5;attempt++)assert.equal((await nativeApi("view",{id:nativeId,accessPassword:"wrong-password-again"})).status,401); + assert.equal((await nativeApi("view",{id:nativeId,accessPassword:nativePassword})).status,429,"five failed attempts lock the native password gate"); + await json(await nativeApi("revoke",{id:nativeId,owner:nativeOwner})); + assert.equal((await request("/api/clip?op=view&id="+nativeId)).status,404,"revoked native share is unavailable"); + await json(await nativeApi("delete",{id:nativeId,owner:nativeOwner})); + const tombstone=await json(await nativeApi("manage",{id:nativeId,owner:nativeOwner}));assert.equal(tombstone.deleted,true);assert.equal(tombstone.status,"revoked","deleted records remain in the revoked state to prevent legacy-share resurrection"); + assert.equal((await nativeApi("view",{id:nativeId,accessPassword:nativePassword})).status,404,"deleted IDs cannot fall back to old Vercel shares"); + assert.equal((await nativeApi("delete",{id:nativeId,owner:nativeOwner})).status,200,"delete is idempotent"); + nativeReserved=false; + const capacity=await json(await request("/api/clip?op=health")); + assert.equal(capacity.reservedBytes,nativeHealth.reservedBytes,"native storage reservation is released after delete"); + assert.equal(capacity.reservedRecordings,nativeHealth.reservedRecordings,"native recording count is released after delete"); + console.log("Native Cloudflare acceptance passed: D1 reservation, chunk resume state, R2 publish/range, password lockout, captions/chapters/report, nested comments/edit/resolve/delete, reaction, owner metadata, revoke and cleanup."); +} catch(error) { + if(nativeReserved)await nativeApi("delete",{id:nativeId,owner:nativeOwner}).catch(()=>undefined); + throw error; +} + +async function jsonText(response) { + assert.equal(response.status, 200, "homepage responds"); + return await response.text(); +} diff --git a/rebuild/scripts/performance-budget.mjs b/rebuild/scripts/performance-budget.mjs new file mode 100644 index 0000000..f106140 --- /dev/null +++ b/rebuild/scripts/performance-budget.mjs @@ -0,0 +1,45 @@ +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { gzipSync } from "node:zlib"; + +const assetsDir = path.resolve(".cloudflare/output/v1/workers/default/assets/assets"); +const files = await readdir(assetsDir); +const jsFiles = files.filter((name) => /\.m?js$/.test(name) && name !== "sw.js"); +const cssFiles = files.filter((name) => /\.css$/.test(name)); + +if (jsFiles.length === 0 || cssFiles.length === 0) { + throw new Error(`Performance budget could not find built JS/CSS assets in ${assetsDir}`); +} + +async function measure(names) { + let raw = 0; + let gzip = 0; + for (const name of names) { + const file = path.join(assetsDir, name); + const buffer = await readFile(file); + raw += buffer.length; + gzip += gzipSync(buffer, { level: 9 }).length; + } + return { raw, gzip }; +} + +const js = await measure(jsFiles); +const css = await measure(cssFiles); +const budgets = { + "JavaScript (gzip)": { actual: js.gzip, max: 130 * 1024 }, + "CSS (gzip)": { actual: css.gzip, max: 16 * 1024 }, + "JavaScript (raw)": { actual: js.raw, max: 400 * 1024 }, + "CSS (raw)": { actual: css.raw, max: 80 * 1024 }, +}; + +console.log("ScreenNote client performance budget"); +console.log(`JS: ${(js.raw / 1024).toFixed(1)} KiB raw / ${(js.gzip / 1024).toFixed(1)} KiB gzip (${jsFiles.join(", ")})`); +console.log(`CSS: ${(css.raw / 1024).toFixed(1)} KiB raw / ${(css.gzip / 1024).toFixed(1)} KiB gzip (${cssFiles.join(", ")})`); + +let failed = false; +for (const [label, budget] of Object.entries(budgets)) { + const pass = budget.actual <= budget.max; + console.log(`${pass ? "PASS" : "FAIL"} ${label}: ${(budget.actual / 1024).toFixed(1)} / ${(budget.max / 1024).toFixed(1)} KiB`); + if (!pass) failed = true; +} +if (failed) process.exitCode = 1; diff --git a/rebuild/scripts/prepare-public.mjs b/rebuild/scripts/prepare-public.mjs new file mode 100644 index 0000000..3cdb74e --- /dev/null +++ b/rebuild/scripts/prepare-public.mjs @@ -0,0 +1,17 @@ +import { mkdir, cp, rm, writeFile } from "node:fs/promises"; + +// Keep only static assets needed by the new React app. Never copy legacy UI files. +const source = "legacy/public"; +const output = "public"; +await rm(output, { recursive: true, force: true }); +await mkdir(output, { recursive: true }); +await writeFile(`${output}/_headers`, `/index.html + Cache-Control: no-cache + +/sw.js + Cache-Control: no-cache +`); +for (const file of ["sw.js", "icon.svg", "manifest.webmanifest", "sample.webm"]) { + try { await cp(`${source}/${file}`, `${output}/${file}`); } catch { /* optional static asset */ } +} +console.log("Prepared isolated Cloudflare public assets; legacy HTML, CSS and JS are excluded."); diff --git a/rebuild/src/CameraBubblePosition.tsx b/rebuild/src/CameraBubblePosition.tsx new file mode 100644 index 0000000..ba434c0 --- /dev/null +++ b/rebuild/src/CameraBubblePosition.tsx @@ -0,0 +1,29 @@ +import React, { useRef } from "react"; +import { cameraBubbleFootprint } from "./recorder"; +type Props={size:number;x:number;y:number;disabled?:boolean;onChange:(x:number,y:number)=>void}; +export default function CameraBubblePosition({size,x,y,disabled=false,onChange}:Props){ + const stage=useRef(null),grab=useRef({x:0,y:0}); + const bounds=cameraBubbleFootprint(size); + const clamp=(value:number,max:number)=>Math.max(0,Math.min(max,value)); + const update=(clientX:number,clientY:number)=>{ + const rect=stage.current?.getBoundingClientRect();if(!rect||!rect.width||!rect.height)return; + const nextX=clamp((clientX-rect.left-grab.current.x)/rect.width,1-bounds.width); + const nextY=clamp((clientY-rect.top-grab.current.y)/rect.height,1-bounds.height); + onChange(Number(nextX.toFixed(3)),Number(nextY.toFixed(3))); + }; + const onPointerDown=(event:React.PointerEvent)=>{ + if(disabled||!stage.current)return;const rect=stage.current.getBoundingClientRect(); + grab.current={x:event.clientX-rect.left-x*rect.width,y:event.clientY-rect.top-y*rect.height}; + event.currentTarget.setPointerCapture(event.pointerId);event.preventDefault(); + }; + const onKeyDown=(event:React.KeyboardEvent)=>{ + if(disabled)return;const step=event.shiftKey?.05:.01; + let nextX=x,nextY=y; + if(event.key==="ArrowLeft")nextX-=step;else if(event.key==="ArrowRight")nextX+=step;else if(event.key==="ArrowUp")nextY-=step;else if(event.key==="ArrowDown")nextY+=step;else if(event.key==="Home"){nextX=0;nextY=0;}else if(event.key==="End"){nextX=1-bounds.width;nextY=1-bounds.height;}else return; + event.preventDefault();onChange(Number(clamp(nextX,1-bounds.width).toFixed(3)),Number(clamp(nextY,1-bounds.height).toFixed(3))); + }; + return
+ SCREEN +
{if(event.currentTarget.hasPointerCapture(event.pointerId))update(event.clientX,event.clientY)}} onPointerUp={event=>{if(event.currentTarget.hasPointerCapture(event.pointerId))event.currentTarget.releasePointerCapture(event.pointerId)}} onPointerCancel={event=>{if(event.currentTarget.hasPointerCapture(event.pointerId))event.currentTarget.releasePointerCapture(event.pointerId)}} onKeyDown={onKeyDown} style={{left:`${x*100}%`,top:`${y*100}%`,width:`${bounds.width*100}%`,height:`${bounds.height*100}%`}}>
+

Drag the camera bubble into place, or focus it and use the arrow keys. Shift + arrow moves farther.

; +} diff --git a/rebuild/src/ClipThumbnail.tsx b/rebuild/src/ClipThumbnail.tsx new file mode 100644 index 0000000..79d9642 --- /dev/null +++ b/rebuild/src/ClipThumbnail.tsx @@ -0,0 +1,8 @@ +import React,{useEffect,useState} from "react"; +import {Film} from "lucide-react"; +type Props={thumbnail?:Blob;title:string}; +export default function ClipThumbnail({thumbnail,title}:Props){ + const [src,setSrc]=useState(""); + useEffect(()=>{if(!thumbnail){setSrc("");return}const url=URL.createObjectURL(thumbnail);setSrc(url);return()=>URL.revokeObjectURL(url)},[thumbnail]); + return src?{title+":
SCREENNOTE
+} diff --git a/rebuild/src/EditorWorkspace.tsx b/rebuild/src/EditorWorkspace.tsx new file mode 100644 index 0000000..fbc2839 --- /dev/null +++ b/rebuild/src/EditorWorkspace.tsx @@ -0,0 +1,159 @@ +import React, { useEffect, useMemo, useRef, useState } from "react"; +import { ArrowDownToLine, ArrowLeft, ArrowRight, ArrowUpRight, Camera, Check, Download, Eraser, Highlighter, LockKeyhole, MessageSquareText, Pause, Play, RectangleHorizontal, Scissors, Share2, Trash2, Type, Undo2, X } from "lucide-react"; +import { saveClip, type Annotation, type BugReport, type CaptionCue, type Chapter, type Clip } from "./library"; +import { clampTrimRange, trimVideoElement } from "./trim"; +import { createVideoThumbnail } from "./media"; +import { trimAnnotations, visibleAnnotations } from "./annotationTiming"; +import { useDialogFocus } from "./useDialogFocus"; +import { formatReproCapsuleSteps, parseReproCapsule } from "./reproCapsule"; +// @ts-expect-error Shared browser-safe JavaScript enrichment module has no declaration file. +import { captionsVTT, parseCaptions, parseChapters, reportMarkdown, trimExtras, validateExtras } from "../legacy/lib/enrichment.js"; + +type Props = { + clip: Clip; + url: string; + onClose: () => void; + onUpdated: () => void; + onShare: () => void; + shareLabel?:string; + onDownload: () => void; + onDelete: () => void; +}; +const stamp=(n:number)=>{const m=Math.floor(n/60),s=Math.floor(n%60);return m+":"+String(s).padStart(2,"0")}; +const initialReport=():BugReport=>({url:"",steps:"",expected:"",actual:"",environment:""}); +const kinds: {kind:Annotation["kind"];label:string;icon:React.ReactNode}[]=[ + {kind:"rectangle",label:"Box",icon:}, + {kind:"arrow",label:"Arrow",icon:}, + {kind:"highlight",label:"Highlight",icon:}, + {kind:"blur",label:"Blur",icon:}, + {kind:"redact",label:"Redact",icon:} +]; +function paint(ctx:CanvasRenderingContext2D,w:number,h:number,items:Annotation[],scratch?:HTMLCanvasElement){ + for(const a of items){const x=a.x*w,y=a.y*h,bw=a.w*w,bh=a.h*h;ctx.save();ctx.lineWidth=Math.max(2,w/320);ctx.strokeStyle="#ff6b35";ctx.fillStyle="rgba(255,210,40,.34)"; + if(a.kind==="redact"){ctx.fillStyle="#161a17";ctx.fillRect(x,y,bw,bh)} + else if(a.kind==="blur"){const source=scratch||ctx.canvas;if(scratch){scratch.width=w;scratch.height=h;const copy=scratch.getContext("2d");copy?.drawImage(ctx.canvas,0,0)}ctx.save();ctx.beginPath();ctx.rect(x,y,bw,bh);ctx.clip();ctx.filter=`blur(${Math.max(8,w*.012)}px)`;ctx.drawImage(source,0,0);ctx.restore();ctx.fillStyle="rgba(20,25,20,.12)";ctx.fillRect(x,y,bw,bh)} + else if(a.kind==="highlight")ctx.fillRect(x,y,bw,bh); + else if(a.kind==="arrow"){ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(x+bw,y+bh);const angle=Math.atan2(bh,bw),s=Math.max(12,w*.018);ctx.moveTo(x+bw-s*Math.cos(angle-.5),y+bh-s*Math.sin(angle-.5));ctx.lineTo(x+bw,y+bh);ctx.lineTo(x+bw-s*Math.cos(angle+.5),y+bh-s*Math.sin(angle+.5));ctx.stroke()} + else ctx.strokeRect(x,y,bw,bh);ctx.restore(); + } +} +function EditorWorkspace({clip,url,onClose,onUpdated,onShare,shareLabel,onDownload,onDelete}:Props){ + const video=useRef(null),overlay=useRef(null),file=useRef(null),capsuleFile=useRef(null); + const [title,setTitle]=useState(clip.title),[activeTool,setActiveTool]=useState("rectangle"),[drawMode,setDrawMode]=useState(false); + const [marks,setMarks]=useState(clip.annotations||[]),[drawing,setDrawing]=useState(null),[tab,setTab]=useState<"edit"|"context">("edit"); + const [start,setStart]=useState(0),[end,setEnd]=useState(clip.duration),[busy,setBusy]=useState(false),[status,setStatus]=useState(""); + const [captionsText,setCaptionsText]=useState(()=>clip.captions?.length?captionsVTT(clip.captions):""); + const [savedCaptions,setSavedCaptions]=useState(clip.captions||[]); + const [pendingSeek,setPendingSeek]=useState(null); + const [chaptersText,setChaptersText]=useState(()=>clip.chapters?.map(c=>stamp(c.time)+" "+c.title).join("\n")||""); + const [report,setReport]=useState(clip.report||initialReport()); + const [reviewStatus,setReviewStatus]=useState>(clip.reviewStatus||"needs-feedback"); + const [captionSearch,setCaptionSearch]=useState(""); + const [currentTime,setCurrentTime]=useState(0); + const [trimPreview,setTrimPreview]=useState(false); + const [titleEditing,setTitleEditing]=useState(false); + const [playing,setPlaying]=useState(false); + const [exportProgress,setExportProgress]=useState(0); + const [showReport,setShowReport]=useState(false); + const canvasFrame=useRef(0); + const dialogRef=useRef(null); + useDialogFocus(dialogRef,true,onClose); + const visibleCues=useMemo(()=> savedCaptions.filter(c=>c.text.toLocaleLowerCase().includes(captionSearch.toLocaleLowerCase())),[savedCaptions,captionSearch]); + + useEffect(()=>{const el=video.current,canvas=overlay.current;if(!el||!canvas)return; + const render=()=>{const rect=canvas.getBoundingClientRect();const dpr=Math.min(window.devicePixelRatio||1,2);const w=Math.max(1,Math.round(rect.width*dpr)),h=Math.max(1,Math.round(rect.height*dpr));if(canvas.width!==w||canvas.height!==h){canvas.width=w;canvas.height=h;}const ctx=canvas.getContext("2d");if(ctx){ctx.clearRect(0,0,w,h);paint(ctx,w,h,[...visibleAnnotations(marks,currentTime),...(drawing?[drawing]:[])]);}canvasFrame.current=requestAnimationFrame(render)}; + canvasFrame.current=requestAnimationFrame(render);return()=>cancelAnimationFrame(canvasFrame.current); + },[marks,drawing,currentTime]); + useEffect(()=>{const key=(event:KeyboardEvent)=>{if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==="z"&&!(event.target instanceof HTMLElement&&/^(INPUT|TEXTAREA|SELECT)$/.test(event.target.tagName))){event.preventDefault();setMarks(old=>old.slice(0,-1))}};window.addEventListener("keydown",key);return()=>window.removeEventListener("keydown",key)},[]); + useEffect(()=>{const el=video.current;if(!el)return;const update=()=>setCurrentTime(el.currentTime);const play=()=>setPlaying(true),pause=()=>setPlaying(false);el.addEventListener("timeupdate",update);el.addEventListener("play",play);el.addEventListener("pause",pause);return()=>{el.removeEventListener("timeupdate",update);el.removeEventListener("play",play);el.removeEventListener("pause",pause)}},[]); + useEffect(()=>{if(tab!=="edit"||pendingSeek===null||!video.current)return;video.current.currentTime=pendingSeek;void video.current.play().catch(()=>{});setPendingSeek(null)},[tab,pendingSeek]); + async function importReproCapsule(file:File){ + if(file.size>256*1024){setStatus("Repro Capsules must be 256 KB or smaller.");return} + try{ + const capsule=parseReproCapsule(JSON.parse(await file.text())); + const environment=[capsule.page.userAgent,capsule.page.viewport.width+"×"+capsule.page.viewport.height+" viewport"].filter(Boolean).join("\n"); + setReport(old=>({...old,url:capsule.page.url,steps:formatReproCapsuleSteps(capsule),environment})); + setStatus("Repro Capsule imported locally. Review the URL, steps and environment; remove anything sensitive before saving or publishing."); + }catch(error){setStatus(error instanceof Error?error.message:"This Repro Capsule could not be imported.");} + finally{if(capsuleFile.current)capsuleFile.current.value="";} + } + function seekEditor(seconds:number){if(video.current){video.current.currentTime=seconds;void video.current.play().catch(()=>{})}else{setPendingSeek(seconds);setTab("edit")}} + function point(e:React.PointerEvent){const r=e.currentTarget.getBoundingClientRect();return{x:Math.max(0,Math.min(1,(e.clientX-r.left)/r.width)),y:Math.max(0,Math.min(1,(e.clientY-r.top)/r.height))}} + function beginMark(e:React.PointerEvent){if(!drawMode||e.button!==0)return;const p=point(e);setDrawing({kind:activeTool,x:p.x,y:p.y,w:0,h:0,time:Math.max(0,currentTime),duration:Math.max(0.1,Math.min(4,Math.max(0,(clip.duration||currentTime)-currentTime)))});e.currentTarget.setPointerCapture(e.pointerId)} + function moveMark(e:React.PointerEvent){if(!drawing)return;const p=point(e);setDrawing(d=>d?{...d,w:Math.abs(p.x-d.x),h:Math.abs(p.y-d.y),x:d.kind==="arrow"?d.x:Math.min(d.x,p.x),y:d.kind==="arrow"?d.y:Math.min(d.y,p.y)}:null)} + function endMark(e:React.PointerEvent){if(!drawing)return;const p=point(e);const next={...drawing,w:Math.abs(p.x-drawing.x),h:Math.abs(p.y-drawing.y),x:drawing.kind==="arrow"?drawing.x:Math.min(drawing.x,p.x),y:drawing.kind==="arrow"?drawing.y:Math.min(drawing.y,p.y)};if(next.w>.004||next.h>.004){setMarks(old=>old.length<40?[...old,next]:old);setStatus("Annotation added. Save changes to keep it.")}setDrawing(null)} + async function saveContext(){setBusy(true);setStatus("");try{const duration=clip.duration||video.current?.duration||0;const extras=validateExtras({captions:captionsText.trim()?parseCaptions(captionsText,duration):[],chapters:parseChapters(chaptersText,duration),report},duration);const next={...clip,title:title.trim()||"Untitled recording",annotations:marks,reviewStatus,...extras};await saveClip(next);setSavedCaptions(extras.captions);onUpdated();setStatus("Changes saved privately on this device.")}catch(e){setStatus(e instanceof Error?e.message:"Could not save your changes.")}finally{setBusy(false)}} + async function saveTrim(){if(!video.current)return;setBusy(true);setStatus("Creating a trimmed copy…");try{const range=clampTrimRange(start,end,clip.duration);const blob=await trimVideoElement(video.current,range);const extras=trimExtras({captions:clip.captions||[],chapters:clip.chapters||[],report:clip.report||null},range.start,range.end);const next:Clip={...clip,...extras,id:crypto.randomUUID(),title:(title.trim()||clip.title)+" — trimmed",createdAt:Date.now(),duration:Math.ceil(range.duration),size:blob.size,mimeType:blob.type,blob,annotations:trimAnnotations(marks,range.start,range.end),thumbnail:await createVideoThumbnail(blob)};await saveClip(next);onUpdated();setStatus("Trimmed copy saved. The original is unchanged.")}catch(e){setStatus(e instanceof Error?e.message:"Trim failed. Your original is unchanged.")}finally{setBusy(false)}} + async function captureAnnotatedFrame(){const source=video.current;if(!source||source.readyState<2||!source.videoWidth||!source.videoHeight){setStatus("Wait for a video frame to load, then capture it.");return}try{const width=Math.min(source.videoWidth,1920),height=Math.round(width*source.videoHeight/source.videoWidth);const canvas=document.createElement("canvas");canvas.width=width;canvas.height=height;const ctx=canvas.getContext("2d");if(!ctx)throw new Error("Frame capture is unavailable.");ctx.drawImage(source,0,0,width,height);paint(ctx,width,height,visibleAnnotations(marks,source.currentTime),document.createElement("canvas"));const blob=await new Promise((resolve,reject)=>canvas.toBlob(result=>result?resolve(result):reject(new Error("Could not encode this frame.")),"image/png"));const safe=(title||"screennote").replace(/[^a-z0-9-_]+/gi,"-").replace(/^-+|-+$/g,"").slice(0,60)||"screennote";const href=URL.createObjectURL(blob),anchor=document.createElement("a");anchor.href=href;anchor.download=`${safe}-frame-${Math.round(source.currentTime*1000)}ms.png`;anchor.click();window.setTimeout(()=>URL.revokeObjectURL(href),1000);setStatus("Annotated frame saved as PNG. Nothing was uploaded.")}catch(error){setStatus(error instanceof Error?error.message:"Could not capture this frame.")}} + async function saveMarkedCopy(){ + const source=video.current;if(!source||!marks.length)return; + setBusy(true);setExportProgress(0);setStatus("Preparing annotated copy…"); + const previousControls=source.controls,originalTime=source.currentTime,wasPaused=source.paused; + let raf=0,stream:MediaStream|undefined,sourceCapture:MediaStream|undefined,recorder:MediaRecorder|undefined,recorderDone:Promise|undefined,recorderStarted=false; + let sourceFailed=false; + const stopRecorder=()=>{if(recorder&&recorder.state!=="inactive"){try{recorder.stop()}catch{/* Recorder may already be stopping. */}}}; + const seekTo=(time:number)=>new Promise((resolve,reject)=>{ + if(Math.abs(source.currentTime-time)<.02)return resolve(); + let timer=0;const cleanup=()=>{window.clearTimeout(timer);source.removeEventListener("seeked",done);source.removeEventListener("error",fail)}; + const done=()=>{cleanup();resolve()},fail=()=>{cleanup();reject(new Error("Could not seek the source video."))}; + source.addEventListener("seeked",done,{once:true});source.addEventListener("error",fail,{once:true}); + timer=window.setTimeout(()=>{cleanup();reject(new Error("Seeking timed out. The original video is unchanged."))},8000); + try{source.currentTime=time}catch{cleanup();reject(new Error("Could not seek the source video."))} + }); + let onEnded=()=>stopRecorder(); + const onSourceError=()=>{sourceFailed=true;stopRecorder()}; + try{ + source.controls=false;source.pause(); + const captureSource=source as HTMLVideoElement&{captureStream?:()=>MediaStream;mozCaptureStream?:()=>MediaStream}; + const capture=captureSource.captureStream||captureSource.mozCaptureStream; + if(!capture)throw new Error("This browser cannot export an annotated video. Download the original and keep annotations in your local project."); + sourceCapture=capture.call(source); + if(Number.isFinite(originalTime)&&originalTime>.02)await seekTo(0); + const width=Math.min(source.videoWidth||1280,1920),height=Math.round(width*(source.videoHeight||720)/(source.videoWidth||1280)); + const canvas=document.createElement("canvas"),scratch=document.createElement("canvas");canvas.width=width;canvas.height=height; + const ctx=canvas.getContext("2d");if(!ctx)throw Error("Video rendering is unavailable."); + stream=canvas.captureStream(30);for(const track of sourceCapture.getAudioTracks())stream.addTrack(track); + const mime=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm"].find(type=>MediaRecorder.isTypeSupported(type)); + recorder=new MediaRecorder(stream,mime?{mimeType:mime}:undefined);const chunks:Blob[]=[]; + recorderDone=new Promise((resolve,reject)=>{ + recorder!.ondataavailable=event=>{if(event.data.size)chunks.push(event.data)}; + recorder!.onstop=()=>resolve(new Blob(chunks,{type:recorder!.mimeType||"video/webm"})); + recorder!.onerror=()=>reject(new Error("Annotated export failed.")); + }); + recorder.start(250);recorderStarted=true; + source.addEventListener("ended",onEnded,{once:true}); + source.addEventListener("error",onSourceError,{once:true}); + const draw=()=>{ + if(source.readyState>=2)ctx.drawImage(source,0,0,width,height);else{ctx.fillStyle="#111";ctx.fillRect(0,0,width,height)} + paint(ctx,width,height,visibleAnnotations(marks,source.currentTime),scratch); + setExportProgress(source.duration?Math.min(1,source.currentTime/source.duration):0); + if(source.ended)stopRecorder();else raf=requestAnimationFrame(draw); + }; + raf=requestAnimationFrame(draw);await source.play(); + const blob=await Promise.race([recorderDone,new Promise((_,reject)=>window.setTimeout(()=>reject(new Error("The annotated export timed out. The original remains unchanged.")),45000))]);if(sourceFailed)throw new Error("The source video failed during export. No incomplete copy was saved.");if(!blob.size)throw new Error("The annotated export was empty."); + const next:Clip={...clip,id:crypto.randomUUID(),title:(title.trim()||clip.title)+" — annotated",createdAt:Date.now(),size:blob.size,mimeType:blob.type,blob,annotations:marks,thumbnail:await createVideoThumbnail(blob)}; + await saveClip(next);onUpdated();setStatus("Annotated copy saved. The original remains unchanged."); + }catch(error){setStatus(error instanceof Error?error.message:"Could not export annotations. The original remains unchanged.")} + finally{ + cancelAnimationFrame(raf);source.removeEventListener("ended",onEnded);source.removeEventListener("error",onSourceError);stopRecorder(); + if(recorderStarted&&recorderDone)await Promise.race([recorderDone.then(()=>undefined,()=>undefined),new Promise(resolve=>window.setTimeout(resolve,2500))]); + stream?.getTracks().forEach(track=>track.stop());sourceCapture?.getTracks().forEach(track=>track.stop()); + source.controls=previousControls;source.pause(); + if(Number.isFinite(originalTime))await seekTo(Math.min(originalTime,Number.isFinite(source.duration)?source.duration:originalTime)).catch(()=>undefined); + if(!wasPaused&&!source.ended)await source.play().catch(()=>undefined);else source.pause(); + setBusy(false);setExportProgress(0); + } + } + function timestampSrt(seconds:number){const ms=Math.max(0,Math.round(seconds*1000)),hours=Math.floor(ms/3600000),minutes=Math.floor(ms%3600000/60000),secs=Math.floor(ms%60000/1000),millis=ms%1000;return `${String(hours).padStart(2,"0")}:${String(minutes).padStart(2,"0")}:${String(secs).padStart(2,"0")},${String(millis).padStart(3,"0")}`} + function downloadText(content:string,name:string,type:string){const a=document.createElement("a"),blob=new Blob([content],{type}),href=URL.createObjectURL(blob);a.href=href;a.download=name;a.click();window.setTimeout(()=>URL.revokeObjectURL(href),1000)} + function exportCaptions(format:"srt"|"vtt"){try{const cues:CaptionCue[]=parseCaptions(captionsText,clip.duration);if(!cues.length)throw new Error("Add valid captions before exporting.");const content=format==="vtt"?captionsVTT(cues):cues.map((cue,i)=>`${i+1}\n${timestampSrt(cue.start)} --> ${timestampSrt(cue.end)}\n${cue.text}`).join("\n\n");downloadText(content,(title||"screennote")+`.${format}`,format==="vtt"?"text/vtt":"application/x-subrip")}catch(error){setStatus(error instanceof Error?error.message:"Could not export captions.")}} + function exportChapters(){try{const chapters=parseChapters(chaptersText,clip.duration);if(!chapters.length)throw new Error("Add valid chapters before exporting.");downloadText(JSON.stringify(chapters,null,2),(title||"screennote")+"-chapters.json","application/json")}catch(error){setStatus(error instanceof Error?error.message:"Could not export chapters.")}} + function downloadReport(){try{const markdown=reportMarkdown({...clip,title,report,chapters:parseChapters(chaptersText,clip.duration),shared:false},location.origin);downloadText(markdown,"screennote-bug-report.md","text/markdown")}catch(error){setStatus(error instanceof Error?error.message:"Could not export the report.")}} + return
+
{titleEditing?setTitle(e.target.value)} onBlur={()=>setTitleEditing(false)} onKeyDown={e=>{if(e.key==="Enter")setTitleEditing(false)}} autoFocus/>:}{stamp(clip.duration)} · {(clip.size/1048576).toFixed(1)} MB · stored locally
+
+ {tab==="edit"?
{stamp(currentTime)}{if(video.current)video.current.currentTime=Number(e.target.value)}}/>{stamp(clip.duration)}
MARK UP{kinds.map(k=>)}

Draw at the current playhead. New marks appear for up to 4 seconds, then disappear; older untimed marks remain throughout. Redaction is opaque.

:
OWNER-SUPPLIED CAPTIONS

Make every moment understandable.

Import an SRT or WebVTT file, or paste caption text. Automatic transcription is not enabled.

{const f=e.target.files?.[0];if(!f)return;if(f.size>20000){setStatus("Caption files must be 20 KB or smaller.");return}try{const raw=await f.text();parseCaptions(raw,clip.duration);setCaptionsText(raw);setStatus("Captions loaded. Save changes to apply them.")}catch(err){setStatus(err instanceof Error?err.message:"Invalid captions.")}finally{e.currentTarget.value=""}}}/>