diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ec52dad..578fe33 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -82,7 +82,7 @@ jobs: run: | docker run -d --name lienzo -p 3000:3000 -e ORIGIN=http://localhost:3000 lienzo:ci for i in $(seq 1 30); do curl -fsS http://localhost:3000/ >/dev/null 2>&1 && break; sleep 1; done - curl -fsS http://localhost:3000/ | grep -q "Create Beautiful Documents" + curl -fsS http://localhost:3000/ | grep -q "Design it. Export it. Edit it again." curl -fsS http://localhost:3000/sitemap.xml | grep -q "" curl -fsS http://localhost:3000/canvas >/dev/null - name: Container logs diff --git a/CHANGELOG.md b/CHANGELOG.md index ea333be..4c45fbb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,44 @@ All notable changes to this project are documented in this file. New entries are generated by the Prepare Release workflow from [Conventional Commits](https://www.conventionalcommits.org/), following [Semantic Versioning](https://semver.org/). +## [2.0.0](https://github.com/Deityhub/lienzo/compare/v1.1.0...v2.0.0) (2026-11-07) + +### Features + +- template gallery with 22 templates, a page for each, and sorting on the documents page +- tool palette that adds on click, and headers that collapse to icons instead of wrapping +- tidier property panel, a phone sheet and rulers with values ([#46](https://github.com/Deityhub/lienzo/pull/46)) +- new logo, favicons, app icons and social preview image +- one export dialog and a tidier editor header +- Studio home page ([#43](https://github.com/Deityhub/lienzo/pull/43)) +- Fluent 2 colours and a light and dark theme +- copy, cut, paste and duplicate elements, and paste pictures ([#41](https://github.com/Deityhub/lienzo/pull/41)) +- move elements and groups between pages ([#40](https://github.com/Deityhub/lienzo/pull/40)) +- select, group and resize multiple elements ([#39](https://github.com/Deityhub/lienzo/pull/39)) +- save documents automatically while editing +- export PDFs with real text and vector shapes +- import documents from Lienzo-exported PDFs +- add JSON import and export for documents +- add document schema versioning, migrations and IndexedDB tests + +### Bug Fixes + +- templates open in the editor exactly as designed +- root favicon, uncut favicon icon, and a System option for the theme switch +- scale text with the page on smaller screens + +### Refactors + +- slim down the canvas page +- move canvas drag and resize into controllers +- split CanvasElement into per-type views and extract shape geometry +- split PropertyPanel into per-element panels +- extract canvas geometry into tested utilities + +### Documentation + +- rewrite the README, add contributing, security, code of conduct and third-party notices, and fresh screenshots + ## [1.1.0](https://github.com/Deityhub/lienzo/compare/v1.0.0...v1.1.0) (2026-11-05) ### Features diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..3f0c38a --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,79 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or advances of any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [contact@deityhub.com](mailto:contact@deityhub.com). All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at . + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). + +For answers to common questions about this code of conduct, see the FAQ at . Translations are available at . + +[homepage]: https://www.contributor-covenant.org diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..06a8a1a --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,77 @@ +# Contributing to Lienzo + +Thanks for helping. Bug reports, ideas, documentation fixes and code are all welcome. By taking part you agree to follow the [Code of Conduct](CODE_OF_CONDUCT.md). For a security problem, please follow [SECURITY.md](SECURITY.md) instead of opening an issue. + +## Ways to help + +- **Report a bug or suggest something:** open a [GitHub issue](https://github.com/Deityhub/lienzo/issues). For a bug, say what you did, what you expected, what happened, and your browser. A screenshot or a `.lienzo.json` file that shows it helps. +- **Ask a question or share an idea:** use [GitHub Discussions](https://github.com/Deityhub/lienzo/discussions). +- **Send a change:** see below. For anything bigger than a small fix, please open an issue first so we can agree on the approach before you spend time on it. + +## Set up + +You need Node.js 22 (see `.nvmrc`) and Yarn 4 (`corepack enable` picks the pinned version). + +```bash +git clone https://github.com//lienzo.git +cd lienzo +yarn install +yarn dev # http://localhost:5173 +``` + +## Make a change + +1. Fork the repository and create a branch from `develop`, for example `feat/text-alignment` or `fix/resize-offset`. +2. Make the change, and add or update tests for it. +3. Run the same checks CI runs: + + ```bash + yarn lint # Prettier and ESLint + yarn check # types + yarn test:unit:run # unit and browser-component tests + yarn test:e2e # builds the app and runs the Playwright tests (Chromium) + ``` + + `yarn format` fixes formatting. The first time, run `yarn playwright install chromium`. + +4. Open a pull request into `develop` and fill in the template. + +### Pull request titles and commits + +Pull requests are squash-merged, and the PR title becomes the commit message, so it must follow [Conventional Commits](https://www.conventionalcommits.org/) (CI checks this): `feat: add text alignment`, `fix: resize handle offset`, `docs: explain backups`. `feat`, `fix`, `perf`, `refactor` and `docs` appear in the changelog; `chore`, `ci`, `test` and similar do not. + +### Code style + +- TypeScript and Svelte 5 with runes (`$state`, `$derived`, `$effect`). State shared between components lives in `.svelte.ts` files. +- Keep pure logic (geometry, sorting, file formats) in `src/lib/utils` as plain functions with unit tests, apart from the components. +- Colours, spacing and radii come from the theme tokens in `src/app.css`, so both the light and the dark theme work. Please check a change in both. +- Interfaces must work with the keyboard and a screen reader: real buttons, labels for icon-only controls, visible focus, and touch targets of at least 44px on phones. + +### Tests + +- **Unit tests** (`*.spec.ts`) run in Node. Tests that need a browser (`*.browser.spec.ts`) run in Chromium. +- **End-to-end tests** (`e2e/`) run against a production build on port 4173. To keep them reliable on any machine: + - wait for hydration (`waitForLoadState('networkidle')`) before the first click; + - assert on the saved data (read from IndexedDB, in page units) rather than on screen pixels; + - use `dragTo` for drags, and `hasTouch: true` for tap tests. + +## Documentation and generated files + +- Update the README and other docs when behaviour changes. +- If you add or remove a runtime dependency or a font, run `yarn notices` to refresh [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). +- If you add a font, also regenerate the PDF export fonts with `python3 scripts/generate-pdf-fonts.py` (needs `fonttools` and `brotli`). +- The icons and the social image are generated by `yarn brand:assets`; the screenshots in the README by `yarn docs:screenshots`. + +## Releases + +Lienzo follows [Semantic Versioning](https://semver.org/) and keeps a [CHANGELOG](CHANGELOG.md) generated from the commit titles. + +1. In GitHub, go to Actions, then **Prepare Release**, and run it on `develop` with `patch`, `minor` or `major`. It opens a `chore(release): vX.Y.Z` pull request that bumps `package.json` and the changelog. +2. Merge that pull request into `develop`. +3. Open a pull request from `develop` into `main` and merge it with a merge commit. The **Release** workflow tags the version and creates the GitHub release; the Docker image is published to GHCR and Docker Hub. + +To run CI on the release pull request, add a personal access token as the repository secret `RELEASE_TOKEN`. + +## License + +Lienzo is licensed under the [GNU GPLv3](LICENSE). By contributing you agree that your contribution is licensed under the same terms. diff --git a/README.md b/README.md index 11584fb..3bd69b3 100644 --- a/README.md +++ b/README.md @@ -1,325 +1,67 @@ # Lienzo -A modern, open-source document builder built with Svelte 5, TypeScript, and Tailwind CSS. Create professional documents (resumes, invoices, letters, and more) with an intuitive drag-and-drop canvas interface, featuring advanced ruler boundaries and real-time editing capabilities. +A free document builder for A4 pages. Place text, shapes and images, start from a template, and export a PDF that keeps real, selectable text and carries your editable document inside it. No account, and nothing leaves your browser. -![CI](https://github.com/Deityhub/lienzo/workflows/CI/badge.svg) -![PR Checks](https://github.com/Deityhub/lienzo/workflows/PR%20Checks/badge.svg) +[![CI](https://github.com/Deityhub/lienzo/actions/workflows/ci.yml/badge.svg)](https://github.com/Deityhub/lienzo/actions/workflows/ci.yml) +[![License: GPL v3](https://img.shields.io/badge/license-GPLv3-blue.svg)](LICENSE) -## πŸš€ Features +**Try it: ** -### Core Features + + + The Lienzo editor with an invoice template open + -- **Drag-and-Drop Interface**: Intuitive canvas-based document creation with real-time preview -- **Multiple Element Types**: Text, shapes, and images with full customization -- **Real-time Editing**: Live preview with instant updates and inline text editing -- **Multi-page Support**: Create documents with unlimited pages -- **Nested Elements**: Elements can contain other elements (hierarchical structure) -- **UUID-based IDs**: Cryptographically secure unique identifiers for all elements -- **Versatile Use Cases**: Perfect for resumes, invoices, letters, certificates, and more +## What you can do -### Advanced Canvas Tools +- **Design on a canvas.** Add text, shapes (rectangles, circles, triangles, lines, arrows and more) and images, then move, resize, layer and style them. Rulers set the margins of each page, and elements stay inside them. +- **Start from a template.** 22 ready-made layouts: resumes, letters, invoices, flyers, certificates, menus, planners and more. Each is a normal document, so you can change anything. +- **Work with several elements.** Select many at once, group them, copy, cut, paste and duplicate (also between documents and tabs), and move them to another page. Pictures can be pasted straight in. +- **Never lose work.** Documents save automatically in your browser a moment after each change. +- **Export a real PDF.** Text stays text and shapes stay vector, with fonts embedded. The editable document is stored inside the PDF, so importing that PDF later brings your design back. +- **Back up and move.** Export one document or all of them as `.lienzo.json` files, and import them in another browser or on another device. +- **Light, dark or system theme,** and a layout that works on a phone. The page you design is always white, so a document looks the same in every theme. +- **14 font families,** loaded only when a document uses them. -- **Professional Ruler System**: - - Horizontal and vertical rulers with tick marks (major, minor, tiny) - - Draggable triangle markers for boundary adjustment - - Real-time boundary visualization -- **Smart Element Positioning**: - - Snap-to-grid with 10px threshold - - Boundary enforcement (elements stay within defined areas) - - Dynamic sizing based on drop position - - Automatic element reparenting on drag + + + The template gallery + -- **Advanced Resize Tool**: - - 4 edge handles for width/height adjustment - - 4 corner handles for proportional resize - - Minimum size enforcement (20px) - - Visual feedback with hover states +## Run it yourself -### Element Management - -- **Text Elements**: - - Inline contenteditable text - - Font family, size, weight, and style customization - - Color picker - - Full typography control - -- **Shape Elements**: - - **Basic Shapes**: Rectangle, Circle, Ellipse, Triangle, Diamond, Hexagon, Pentagon - - **Lines & Arrows**: Horizontal, Vertical, and Directional Arrows (up, down, left, right) - - **Styling Options**: - - Custom stroke color and width - - Fill color with opacity control - - Stroke styles: solid, dashed, or dotted - - Corner radius for rectangles - - Rotation support - - **Use Cases**: - - Visual dividers and section breaks - - Decorative elements and icons - - Flow charts and diagrams - - Highlighting important content - -- **Image Elements**: - - URL-based image loading - - Alt text support - - Responsive sizing - -### Visual Feedback System - -- **Element Highlighting**: - - Blue ring: Selected element - - Yellow ring: Elements underneath (overlapping) - - Green ring: Element being hovered during drag - - Purple dashed outline: Drag preview -- **Drag Operations**: - - Real-time drag preview - - ESC key to cancel drag - - Automatic cleanup on drag leave - - Parent detection and highlighting - -### Property Panel - -- **Position & Size**: Precise X, Y, width, height controls -- **Typography**: Font family, size, weight, style, color -- **Shape Properties**: Type, stroke color, stroke width -- **Image Properties**: URL, alt text -- **Element Actions**: Delete button with confirmation - -## πŸ› οΈ Technology Stack - -- **Framework**: Svelte 5 (SvelteKit) -- **Language**: TypeScript -- **Styling**: Tailwind CSS -- **Build Tool**: Vite -- **Testing**: Vitest + Playwright -- **Code Quality**: ESLint + Prettier -- **Deployment**: Vercel, or Docker (GHCR and Docker Hub) - -## πŸ“‹ Prerequisites - -- **Node.js** 22 (see `.nvmrc`) -- **Yarn** 4 (run `corepack enable`; the version is pinned via `packageManager`) -- **Git** - -## πŸš€ Quick Start - -### Installation - -1. **Clone the repository** - - ```bash - git clone https://github.com/your-username/lienzo.git - cd lienzo - ``` - -2. **Install dependencies** - - ```bash - yarn install - ``` - -3. **Start development server** - - ```bash - yarn dev - ``` - -4. **Open your browser** - Navigate to `http://localhost:5173` - -### Build for Production - -```bash -# Build the application -yarn build - -# Preview production build -yarn preview -``` - -## 🎨 Key Components - -### Canvas - -The main canvas component that handles: - -- Element rendering with zIndex sorting -- Drag-and-drop with real-time preview -- Boundary enforcement and snapping -- Ruler integration and visualization -- Element reparenting on drag -- Nested element flattening for display - -### Ruler System - -Professional boundary controls featuring: - -- Horizontal and vertical rulers (Google Docs style) -- Draggable triangle markers (blue for start, red for end) -- Three-tier tick marks: - - Major ticks (12px) every 100px - - Minor ticks (8px) every 50px - - Tiny ticks (4px) every 10px -- Real-time boundary updates with reactive effects -- Coordinate scaling for accurate positioning - -### Property Panel - -Comprehensive styling interface for: - -- Position and dimensions (X, Y, width, height) -- Typography (7 font families, 12 font sizes) -- Font weight (normal, bold) and style (normal, italic) -- Color picker for text and shapes -- Element-specific properties -- Delete functionality - -### Resize Tool - -Advanced resize system with: - -- **4 Edge Handles**: 60px Γ— 4px bars for width/height -- **4 Corner Handles**: 12px circles for proportional resize -- **8 Resize Directions**: n, s, e, w, nw, ne, sw, se -- Visual feedback with hover states -- Boundary-aware resizing - -## πŸ”§ Development - -### Available Scripts +You need Node.js 22 (see `.nvmrc`) and Yarn 4 (`corepack enable` picks the pinned version). ```bash -# Development -yarn dev # Start development server -yarn dev -- --open # Open browser automatically - -# Building -yarn build # Production build -yarn preview # Preview production build - -# Code Quality -yarn lint # Run ESLint -yarn format # Format code with Prettier -yarn check # Type checking - -# Testing -yarn test # Run all tests -yarn test:unit # Unit tests only -yarn test:e2e # End-to-end tests +git clone https://github.com/Deityhub/lienzo.git +cd lienzo +yarn install +yarn dev # http://localhost:5173 ``` -### Code Style - -This project follows: - -- **Prettier** for code formatting -- **ESLint** for linting -- **TypeScript** for type safety -- **Svelte 5** syntax and patterns - -### Key Development Patterns - -1. **State Management**: Uses Svelte 5 runes (`$state`, `$derived`) -2. **Component Architecture**: Functional components with clear props -3. **TypeScript**: Full type safety across the application -4. **Responsive Design**: Mobile-first approach with Tailwind CSS - -## 🎯 Usage Guide - -### Creating a Document - -1. **Navigate to Builder**: Click "Start Building" from the homepage -2. **Add Elements**: Drag text, shapes, or images from the toolbar -3. **Customize Elements**: Select elements to edit properties in the panel -4. **Adjust Boundaries**: Drag ruler markers to set canvas boundaries -5. **Multi-page Support**: Add additional pages as needed -6. **Save & Export**: Save your document to locally or export as PDF - -### Element Manipulation - -- **Move**: Click and drag elements on the canvas -- **Resize**: Use corner handles on selected elements -- **Edit**: Select elements to modify properties in the panel -- **Delete**: Use the delete button in the property panel - -### Boundary System - -- **Set Boundaries**: Drag triangle markers on rulers -- **Snap-to-Grid**: Elements automatically align to boundaries -- **Boundary Enforcement**: Elements cannot move outside defined areas -- **Auto-constrain**: Elements automatically adjust when boundaries change - -## πŸ§ͺ Testing - -This project has comprehensive test coverage for most features. - -### Unit Tests - -```bash -yarn test:unit -``` - -**Test Coverage:** - -- βœ… Page Management (create, delete, UUID generation) -- βœ… Ruler Boundaries (initialization, updates, validation) -- βœ… Element Management (add, update, delete, UUID generation) -- βœ… Element Selection (select, deselect) -- βœ… Nested Elements (parent-child relationships, finding, moving) -- βœ… zIndex Management (automatic assignment) -- βœ… Store State Management (reactive updates) - -**Total Unit Tests**: 20+ tests covering all store functionality - -### End-to-End Tests - -```bash -yarn test:e2e -``` - -**Test Coverage:** - -- βœ… Navigation (home, create, about pages) -- βœ… Page Management (add pages, page counter) -- βœ… Drag and Drop (text, shape, image elements) -- βœ… Element Selection (select, deselect) -- βœ… Element Manipulation (resize handles, delete) -- βœ… Property Updates (font size, font family) -- βœ… UI Components (toolbar, canvas, property panel, rulers) -- βœ… Boundary Visualization (rulers, boundary box) -- βœ… Multi-element Workflows (adding multiple elements) - -**Total E2E Tests**: 14 comprehensive workflow tests - -### Run All Tests - -```bash -yarn test -``` - -This runs both unit and e2e tests sequentially. - -## πŸš€ Deployment - -### Vercel (Recommended) - -1. **Connect Repository**: Link your GitHub repository to Vercel -2. **Automatic Deployments**: Every push to main branch triggers deployment -3. **Environment Variables**: Configure any required environment variables +| Command | What it does | +| ----------------------- | ----------------------------------------------------------- | +| `yarn build` | Production build (targets Vercel) | +| `yarn preview` | Serve the production build | +| `yarn lint` | Prettier and ESLint checks | +| `yarn format` | Format the code | +| `yarn check` | Type check | +| `yarn test:unit:run` | Unit and browser-component tests (Vitest) | +| `yarn test:e2e` | End-to-end tests (Playwright; builds the app first) | +| `yarn test` | Both test suites | +| `yarn brand:assets` | Regenerate the favicons, app icons and social image | +| `yarn docs:screenshots` | Retake the screenshots in this README | +| `yarn notices` | Regenerate [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) | ### Docker -A multi-arch (amd64/arm64) image is published to GitHub Container Registry and Docker Hub on every release: +A multi-arch (amd64 and arm64) image is published to GitHub Container Registry and Docker Hub with every release. ```bash docker run -p 3000:3000 -e ORIGIN=http://localhost:3000 ghcr.io/deityhub/lienzo:latest ``` -The same image is on Docker Hub as `deityhub/lienzo`. Pin a version with a tag instead of `latest` (e.g. `ghcr.io/deityhub/lienzo:1.1.0`). To build it yourself: - -```bash -docker build -t lienzo . -docker compose up --build # http://localhost:3000 -``` +The same image is on Docker Hub as `deityhub/lienzo`. Use a version tag instead of `latest` to pin a release, for example `ghcr.io/deityhub/lienzo:1.1.0`. To build it yourself, run `docker compose up --build` (). | Variable | Default | Description | | -------- | ------------------------ | ------------------------------------------------------------------ | @@ -327,64 +69,40 @@ docker compose up --build # http://localhost:3000 | `PORT` | `3000` | Port the server listens on | | `HOST` | `0.0.0.0` | Interface the server binds to | -The image is built with `adapter-node` (`ADAPTER=node`); the default `yarn build` keeps targeting Vercel. Without Docker: `ADAPTER=node yarn build && node build`. - -## 🀝 Contributing - -We welcome contributions! Here's how to get involved: - -### Getting Started - -1. **Fork** the repository -2. **Clone** your fork -3. **Create** a feature branch: `git checkout -b feature/amazing-feature` -4. **Install** dependencies: `yarn install` -5. **Start** development: `yarn dev` - -### Contribution Guidelines +The image uses `adapter-node` (`ADAPTER=node`); the default build targets Vercel. Without Docker: `ADAPTER=node yarn build && node build`. -1. **Code Style**: Follow existing patterns and run `yarn format` -2. **Tests**: Add tests for new features -3. **Documentation**: Update README for significant changes -4. **Pull Requests**: Use a [Conventional Commits](https://www.conventionalcommits.org/) title (e.g. `feat: add text alignment`, `fix: resize handle offset`). It is checked in CI and drives versioning +## Your documents and your data -### Development Workflow +Documents are stored only in your browser (IndexedDB). There is no server-side storage and no account, so export your documents to keep a backup or to move them. On the **Documents** page: -1. Create a feature branch -2. Make your changes -3. Add tests if applicable -4. Run the test suite: `yarn test` -5. Format code: `yarn format` -6. Submit a pull request +- **Export** on a card downloads that document as `.lienzo.json`, and **Export all** downloads everything in one file. +- **Import** reads `.lienzo.json` files and PDFs exported from Lienzo. If a document with the same id already exists, you choose **Replace existing** or **Keep both**. Documents from older versions are upgraded automatically, and invalid ones are skipped and listed. +- In the editor, **Import** loads a single document as a new one, so saving never overwrites an existing document. -## 🏷️ Versioning & Releases +**About the PDF.** Every PDF exported from Lienzo has the editable document embedded as an attachment (`lienzo-document.json`), so the PDF you share is also a full backup. PDFs from other tools hold no such data and cannot be imported. Limits: characters outside Latin and Latin-extended show as `?`, images from sites that block downloads are left blank (you are told), image shadows are not drawn, and a PDF editor edits text line by line. -Lienzo follows [Semantic Versioning](https://semver.org/) and keeps a [CHANGELOG](CHANGELOG.md) generated from [Conventional Commits](https://www.conventionalcommits.org/). PRs are squash-merged into `develop` with a Conventional Commit title (`feat:`, `fix:`, `perf:`, `refactor:`, `docs:` appear in the changelog; `chore:`, `ci:`, `test:` etc. do not). +Images are kept inside the document when you paste a picture, and by address when you give a URL, in which case the address must stay reachable. -To cut a release: +## Built with -1. **Prepare:** In GitHub, go to Actions β†’ **Prepare Release** β†’ Run workflow on `develop` and choose `patch`, `minor` or `major`. It opens a `chore(release): vX.Y.Z` PR into `develop` that bumps `package.json` and updates `CHANGELOG.md`. -2. **Merge** that PR into `develop`. -3. **Publish:** Open a PR from `develop` into `main` and merge it (use a merge commit so branches stay aligned). The **Release** workflow tags `vX.Y.Z` and creates the GitHub Release with the changelog notes. +[Svelte 5](https://svelte.dev/) and [SvelteKit](https://svelte.dev/docs/kit), TypeScript, [Tailwind CSS](https://tailwindcss.com/) 4, Vite, [pdf-lib](https://github.com/cantoo-scribe/pdf-lib) for the PDF, and [Lucide](https://lucide.dev/) icons. Tested with Vitest and Playwright. Deployed on Vercel, or as a Docker image. The visual design follows [Fluent 2](https://fluent2.microsoft.design/). Everything that ships with the app, with its license, is listed in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). -The running version is shown in the landing page footer. To make CI run on the release PR, add a personal access token as the repo secret `RELEASE_TOKEN`. - -## πŸ“ License - -This project is open source and available under the [GNU GPLv3 License](LICENSE). - -## πŸ™ Acknowledgments +``` +src/lib/canvas editing behaviour: dragging, resizing, selection, autosave, clipboard +src/lib/pdf the PDF exporter +src/lib/stores app state and the IndexedDB layer, with migrations +src/lib/templates the template catalogue +src/lib/utils pure helpers: geometry, file formats, sorting +src/routes home, templates, documents and the editor +e2e end-to-end tests +``` -- Built with [Svelte 5](https://svelte.dev/) and [SvelteKit](https://svelte.dev/docs/kit) -- Styled with [Tailwind CSS](https://tailwindcss.com/) -- Icons from [Lucide Svelte](https://lucide.dev/) +## Contributing -## πŸ“ž Support +Contributions are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) first (it covers setup, checks, commit titles and releases) and follow the [Code of Conduct](CODE_OF_CONDUCT.md). To report a security problem, see [SECURITY.md](SECURITY.md). Changes are listed in the [CHANGELOG](CHANGELOG.md). -- **Issues**: Use GitHub Issues for bug reports and feature requests -- **Discussions**: Use GitHub Discussions for questions and ideas -- **Contributing**: See our contributing guidelines above +## License ---- +Lienzo is open source under the [GNU GPLv3](LICENSE). Third-party software and fonts keep their own licenses; see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). -**Made with ❀️ by [Deityhub](https://github.com/Deityhub) - Create beautiful documents with ease** +Made by [Chizoba Jude Ojini](https://judeojini.com). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..da65230 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,40 @@ +# Security policy + +## Reporting a vulnerability + +Please do not open a public issue for a security problem. + +Report it privately instead: + +- Use GitHub's [private vulnerability reporting](https://github.com/Deityhub/lienzo/security/advisories/new) for this repository, or +- Email [contact@deityhub.com](mailto:contact@deityhub.com) with "Lienzo security" in the subject. + +Please include what you found, the steps to reproduce it, the browser and version, and what an attacker could do with it. A small example file or a screen recording helps. + +What you can expect: + +- A reply within 5 working days to confirm that we have your report. +- A fix, or a plan for one, as soon as the problem is understood. We will keep you updated. +- Credit in the release notes when the fix ships, unless you would rather stay anonymous. + +Please give us a reasonable time to fix the problem before you share it publicly. + +## Supported versions + +Only the latest release gets security fixes. Lienzo is a web app, so the hosted site at is always the latest release. If you run your own copy (for example the Docker image), please keep it up to date. + +## What matters most here + +Lienzo has no accounts and no server-side storage. Documents live in the browser (IndexedDB) and are never uploaded. The areas where a bug would matter most are: + +- **Opening files.** Importing a `.lienzo.json` file or a PDF exported from Lienzo reads untrusted content. A crafted file should never run code, break out of the page or damage other saved documents. +- **Pasting and dropping.** Content from the clipboard or dragged in from elsewhere. +- **Images from a web address.** Image elements load a URL, and PDF export fetches it. +- **Saved data.** Anything that could let one site read or change the documents saved by another. +- **The Docker image and the Node server build,** including the headers and defaults they ship with. + +Out of scope: problems that need a user to already control their own browser (for example, running code in their own developer console), and findings in third-party services we link to. + +## Dependencies + +Dependencies are updated weekly by Dependabot, and every change goes through CI. The packages that ship with the app are listed in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..b5e0d87 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,145 @@ +# Third-party notices + +Lienzo itself is licensed under the [GNU GPLv3](LICENSE). It includes the open source software and fonts below, each under its own license. This file is generated by `yarn notices`; do not edit it by hand. + +## Software + +These packages are part of the app that runs in your browser or on the server. Tools used only to build and test Lienzo are not included, because they are not distributed with it. + +| Package | Version | License | Copyright | +| --------------------------- | ------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| @cantoo/fontkit | 2.0.12 | MIT | Copyright 2014-present Devon Govett | +| @cantoo/pdf-lib | 2.11.1 | MIT | Copyright 2019 Andrew Dillon | +| @jridgewell/gen-mapping | 0.3.13 | MIT | Copyright 2024 Justin Ridgewell | +| @jridgewell/remapping | 2.3.5 | MIT | Copyright 2024 Justin Ridgewell | +| @jridgewell/resolve-uri | 3.1.2 | MIT | Copyright 2019 Justin Ridgewell | +| @jridgewell/sourcemap-codec | 1.5.5 | MIT | Copyright 2024 Justin Ridgewell | +| @jridgewell/trace-mapping | 0.3.31 | MIT | Copyright 2024 Justin Ridgewell | +| @lucide/svelte | 0.548.0 | ISC | Copyright for portions of Lucide are held by Cole Bemis 2013-2023 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2025. | +| @polka/url | 1.0.0-next.29 | MIT | See the package | +| @standard-schema/spec | 1.0.0 | MIT | Copyright 2024 Colin McDonnell | +| @sveltejs/acorn-typescript | 1.0.5 | MIT | Copyright 2022 Tyreal Hu | +| @sveltejs/kit | 2.43.4 | MIT | Copyright 2020 these people | +| @types/cookie | 0.6.0 | MIT | See the package | +| @types/estree | 1.0.8 | MIT | See the package | +| acorn | 8.15.0 | MIT | Copyright 2012-2022 by various contributors (see AUTHORS) | +| aria-query | 5.3.0 | Apache-2.0 | Copyright 2020 A11yance | +| axobject-query | 4.1.0 | Apache-2.0 | Copyright 2020 A11yance | +| base64-js | 1.5.1 | MIT | Copyright 2014 Jameson Little | +| brotli | 1.3.3 | MIT | See the package | +| clsx | 2.1.1 | MIT | See the package | +| cookie | 0.6.0 | MIT | Copyright 2012-2014 Roman Shtylman | +| culori | 4.0.2 | MIT | Copyright 2018 Dan Burzo | +| dequal | 2.0.3 | MIT | See the package | +| devalue | 5.3.2 | MIT | Copyright 2018-19 these people | +| dfa | 1.2.0 | MIT | See the package | +| esm-env | 1.2.2 | MIT | Copyright 2022 Benjamin McCann | +| esrap | 2.1.0 | MIT | Copyright 2023-2025 these people | +| fflate | 0.8.3 | MIT | Copyright 2026 Arjun Barrett | +| html-entities | 2.6.0 | MIT | Copyright 2021 Dulin Marat | +| html-to-image | 1.11.13 | MIT | Copyright 2017-2025 W.Y. | +| is-reference | 1.2.1 | MIT | See the package | +| kleur | 4.1.5 | MIT | See the package | +| locate-character | 3.0.0 | MIT | See the package | +| magic-string | 0.30.19 | MIT | Copyright 2018 Rich Harris | +| mri | 1.2.0 | MIT | See the package | +| mrmime | 2.0.1 | MIT | See the package | +| node-html-better-parser | 1.5.9 | MIT | Copyright 2019 Tao Qiufeng | +| restructure | 3.0.2 | MIT | Copyright 2015-present Devon Govett | +| sade | 1.8.1 | MIT | See the package | +| set-cookie-parser | 2.7.1 | MIT | Copyright 2015 Nathan Friedly (http://nfriedly.com/) | +| sirv | 3.0.2 | MIT | See the package | +| svelte | 5.39.5 | MIT | Copyright 2016-2025 Svelte Contributors | +| totalist | 3.0.1 | MIT | See the package | +| tslib | 2.9.1 | 0BSD | See the package | +| zimmerframe | 1.1.4 | MIT | Copyright 2023 these people | + +## Fonts + +The fonts in `src/lib/fonts` and the static copies used for PDF export in `static/pdf-fonts` come from the projects below, as published on Google Fonts and by their authors. Roboto, Roboto Condensed and Roboto Slab have been published under both the Apache License 2.0 and the SIL Open Font License; the full text of the Apache License is at . + +| Font | Copyright holder | License | Source | +| ---------------- | ------------------------------------ | --------------------- | ---------------------------------------------------- | +| Inter | The Inter Project Authors | OFL-1.1 | | +| Lato | Łukasz Dziedzic | OFL-1.1 | | +| Merriweather | The Merriweather Project Authors | OFL-1.1 | | +| Montserrat | The Montserrat Project Authors | OFL-1.1 | | +| Nunito | The Nunito Project Authors | OFL-1.1 | | +| Open Sans | The Open Sans Project Authors | OFL-1.1 | | +| Oswald | The Oswald Project Authors | OFL-1.1 | | +| Playfair Display | The Playfair Project Authors | OFL-1.1 | | +| Poppins | Indian Type Foundry | OFL-1.1 | | +| Raleway | The Raleway Project Authors | OFL-1.1 | | +| Roboto | The Roboto Project Authors | Apache-2.0 or OFL-1.1 | | +| Roboto Condensed | The Roboto Condensed Project Authors | Apache-2.0 or OFL-1.1 | | +| Roboto Slab | The Roboto Slab Project Authors | Apache-2.0 or OFL-1.1 | | +| Source Code Pro | Adobe | OFL-1.1 | | + +Fonts that were made from the originals (subset to Latin and Latin-extended, converted to WOFF2 and, for PDF export, to static instances) are modified versions as the OFL describes. None of them is sold on its own. + +## Design + +The look of the app follows the public design guidance of [Fluent 2](https://fluent2.microsoft.design/) from Microsoft. No Microsoft code or assets are included. + +## License texts + +### MIT License + +Applies to the packages marked MIT. Each has its own copyright line, listed above. + +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +### ISC License + +Applies to `@lucide/svelte` (Lucide Contributors, and Cole Bemis for the parts derived from Feather). + +> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +### BSD Zero Clause License (0BSD) + +Applies to `tslib`. It permits use, copying, modification and distribution without conditions. + +### Apache License 2.0 + +Applies to `aria-query` and `axobject-query`. The full text is at . + +### SIL Open Font License 1.1 + +Applies to the fonts marked OFL-1.1. The text below is the license itself; each font's copyright holder is in the table above. + +> PREAMBLE +> The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. +> +> The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. +> +> DEFINITIONS +> "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. +> +> "Reserved Font Name" refers to any names specified as such after the copyright statement(s). +> +> "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). +> +> "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. +> +> "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. +> +> PERMISSION & CONDITIONS +> Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: +> +> 1. Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. +> 2. Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. +> 3. No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. +> 4. The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. +> 5. The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. +> +> TERMINATION +> This license becomes null and void if any of the above conditions are not met. +> +> DISCLAIMER +> THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/docs/screenshots/editor-dark.png b/docs/screenshots/editor-dark.png new file mode 100644 index 0000000..8f2bfaf Binary files /dev/null and b/docs/screenshots/editor-dark.png differ diff --git a/docs/screenshots/editor-light.png b/docs/screenshots/editor-light.png new file mode 100644 index 0000000..b8d746a Binary files /dev/null and b/docs/screenshots/editor-light.png differ diff --git a/docs/screenshots/home-dark.png b/docs/screenshots/home-dark.png new file mode 100644 index 0000000..5e4c124 Binary files /dev/null and b/docs/screenshots/home-dark.png differ diff --git a/docs/screenshots/home-light.png b/docs/screenshots/home-light.png new file mode 100644 index 0000000..d2fef98 Binary files /dev/null and b/docs/screenshots/home-light.png differ diff --git a/docs/screenshots/templates-dark.png b/docs/screenshots/templates-dark.png new file mode 100644 index 0000000..0f99113 Binary files /dev/null and b/docs/screenshots/templates-dark.png differ diff --git a/docs/screenshots/templates-light.png b/docs/screenshots/templates-light.png new file mode 100644 index 0000000..3bc159f Binary files /dev/null and b/docs/screenshots/templates-light.png differ diff --git a/e2e/autosave.test.ts b/e2e/autosave.test.ts new file mode 100644 index 0000000..8c92335 --- /dev/null +++ b/e2e/autosave.test.ts @@ -0,0 +1,126 @@ +import { expect, test, type Page } from '@playwright/test'; +import { seedDocument } from './helpers'; + +/** The stored documents, read straight from IndexedDB. */ +const storedDocuments = (page: Page) => + page.evaluate( + () => + new Promise< + Array<{ name: string; pages: Record }> }> + >((resolve, reject) => { + const open = indexedDB.open('lienzo-db'); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const all = open.result.transaction('documents').objectStore('documents').getAll(); + all.onsuccess = () => resolve(all.result); + all.onerror = () => reject(all.error); + }; + }) + ); + +test.describe('Autosave', () => { + test('a new document is saved as "Untitled document" on its first edit', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); + await expect(page.getByTestId('save-status')).toHaveText(''); + + await page.getByTestId('tool-text').dragTo(page.getByTestId('document-canvas'), { + targetPosition: { x: 60, y: 60 } + }); + + await expect(page.getByTestId('save-status')).toHaveText('Saving…', { timeout: 10000 }); + await expect(page.getByTestId('save-status')).toHaveText('Saved'); + const [stored] = await storedDocuments(page); + expect(stored.name).toBe('Untitled document'); + expect(Object.values(Object.values(stored.pages)[0].elements)).toHaveLength(1); + + await page.getByTestId('back-btn').click(); + await expect(page).toHaveURL(/\/documents/); + await expect(page.getByRole('heading', { name: 'Untitled document' })).toBeVisible(); + }); + + test('edits to a saved document are stored without pressing Save', async ({ page }) => { + await seedDocument(page, { + id: 'auto-1', + schemaVersion: 1, + name: 'My Resume', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { + id: 'p1', + boundaries: { horizontal: { start: 100, end: 700 }, vertical: { start: 100, end: 1000 } }, + elements: { + t1: { + id: 't1', + type: 'text', + pageId: 'p1', + zIndex: 0, + x: 120, + y: 140, + width: 400, + height: 80, + text: 'Before', + fontFamily: 'Inter', + fontSize: 24, + fontWeight: '400', + fontStyle: 'normal', + color: '#000000' + } + } + } + } + }); + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(page.locator('textarea')).toHaveValue('Before'); + + // Opening a document is not an edit + await page.waitForTimeout(2500); + expect((await storedDocuments(page))[0].pages.p1.elements).toMatchObject({ + t1: { text: 'Before' } + }); + + await page.locator('textarea').fill('After'); + await expect(page.getByTestId('save-status')).toHaveText('Saved', { timeout: 10000 }); + + const [stored] = await storedDocuments(page); + expect(stored.name).toBe('My Resume'); + expect(stored.pages.p1.elements).toMatchObject({ t1: { text: 'After' } }); + }); + + test('leaving right after an edit still saves it', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); + await page.getByTestId('add-page-btn').click(); + + await page.getByTestId('back-btn').click(); // well before the autosave delay + await expect(page).toHaveURL(/\/documents/); + + await expect(page.getByRole('heading', { name: 'Untitled document' })).toBeVisible(); + }); + + test('shows Saving… and Saved once per edit, not twice', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); + await page.evaluate(() => { + const w = window as unknown as { statuses: string[] }; + w.statuses = []; + const el = document.querySelector('[data-testid="save-status"]')!; + new MutationObserver(() => w.statuses.push(el.textContent?.trim() ?? '')).observe(el, { + childList: true, + subtree: true, + characterData: true + }); + }); + + await page.getByTestId('tool-text').dragTo(page.getByTestId('document-canvas'), { + targetPosition: { x: 60, y: 60 } + }); + await expect(page.getByTestId('save-status')).toHaveText('Saved', { timeout: 10000 }); + await page.waitForTimeout(3000); // long enough for a stray second save + + expect( + await page.evaluate(() => (window as unknown as { statuses: string[] }).statuses) + ).toEqual(['Saving…', 'Saved']); + }); +}); diff --git a/e2e/builder.test.ts b/e2e/builder.test.ts index 593059f..e325838 100644 --- a/e2e/builder.test.ts +++ b/e2e/builder.test.ts @@ -3,18 +3,19 @@ import { expect, test } from '@playwright/test'; test.describe('Document Builder E2E Tests', () => { test('home page loads correctly', async ({ page }) => { await page.goto('/'); - await expect(page.locator('h1')).toContainText('Create Beautiful Documents'); - await expect(page.getByRole('link', { name: 'Start Building' }).first()).toBeVisible(); + await expect(page.locator('h1')).toContainText('Design it. Export it. Edit it again.'); + await expect(page.getByRole('link', { name: 'Start designing' }).first()).toBeVisible(); }); test('navigate to create page', async ({ page }) => { await page.goto('/'); - await page.getByRole('link', { name: 'Start Building' }).first().click(); + await page.getByRole('link', { name: 'Start designing' }).first().click(); await expect(page).toHaveURL(/.*canvas/); }); test('create page has toolbar and canvas', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Check for toolbar await expect(page.getByTestId('toolbar')).toBeVisible(); @@ -25,6 +26,7 @@ test.describe('Document Builder E2E Tests', () => { test('add page button works', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Initially should have 1 page const pageCount = page.getByTestId('page-count'); @@ -39,6 +41,7 @@ test.describe('Document Builder E2E Tests', () => { test('drag and drop text element', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Get the text tool const textTool = page.getByTestId('tool-text'); @@ -57,6 +60,7 @@ test.describe('Document Builder E2E Tests', () => { test('element selection and deselection', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Add an element const textTool = page.getByTestId('tool-text'); @@ -77,6 +81,7 @@ test.describe('Document Builder E2E Tests', () => { test('resize handles appear on selected element', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Add an element const textTool = page.getByTestId('tool-text'); @@ -94,6 +99,7 @@ test.describe('Document Builder E2E Tests', () => { test('delete element', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Add an element const textTool = page.getByTestId('tool-text'); @@ -111,6 +117,7 @@ test.describe('Document Builder E2E Tests', () => { test('update text element properties', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Add text element const textTool = page.getByTestId('tool-text'); @@ -144,11 +151,8 @@ test.describe('Document Builder E2E Tests', () => { await fontWeightSelect.click(); // Test font style change - const fontStyleSelect = page.getByTestId('select-font-style'); - await fontStyleSelect.click(); - const fontStyleNormal = page.getByTestId('select-font-style-option-normal'); - await expect(fontStyleNormal).toBeVisible(); - await fontStyleSelect.click(); + await expect(page.getByTestId('select-font-style-option-normal')).toBeVisible(); + await expect(page.getByTestId('select-font-style-option-italic')).toBeVisible(); // Test color change const colorInput = page.getByTestId('input-color'); @@ -158,6 +162,7 @@ test.describe('Document Builder E2E Tests', () => { test('update position and size properties', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Add text element const textTool = page.getByTestId('tool-text'); @@ -189,6 +194,7 @@ test.describe('Document Builder E2E Tests', () => { test('update shape element properties', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Add shape element const shapeTool = page.getByTestId('tool-shape'); @@ -219,6 +225,7 @@ test.describe('Document Builder E2E Tests', () => { test('update image element properties', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Add image element const imageTool = page.getByTestId('tool-image'); @@ -238,6 +245,7 @@ test.describe('Document Builder E2E Tests', () => { test('rulers are visible', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Check for ruler elements const rulers = page.getByTestId(/ruler/); @@ -246,6 +254,7 @@ test.describe('Document Builder E2E Tests', () => { test('boundary visualization is visible', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // Check for boundary box (blue dashed border) const boundary = page.getByTestId(/boundary/); @@ -260,6 +269,7 @@ test.describe('Document Builder E2E Tests', () => { test('multiple element types can be added', async ({ page }) => { await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive const canvas = page.getByTestId('document-canvas'); diff --git a/e2e/canvas-interaction.test.ts b/e2e/canvas-interaction.test.ts new file mode 100644 index 0000000..46d5a15 --- /dev/null +++ b/e2e/canvas-interaction.test.ts @@ -0,0 +1,64 @@ +import { expect, test, type Page } from '@playwright/test'; + +async function addTextElement(page: Page) { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive + await page.getByTestId('tool-text').dragTo(page.getByTestId('document-canvas'), { + targetPosition: { x: 200, y: 200 } + }); + await expect(page.getByTestId('property-panel-title')).toContainText('Text Properties'); +} + +async function geometry(page: Page) { + const read = async (id: string) => Number(await page.getByTestId(id).inputValue()); + return { + x: await read('input-x'), + y: await read('input-y'), + width: await read('input-width'), + height: await read('input-height') + }; +} + +/** Press on the centre of `target`, move by (dx, dy) screen pixels, release. */ +async function dragBy(page: Page, target: ReturnType, dx: number, dy: number) { + const box = (await target.boundingBox())!; + const startX = box.x + box.width / 2; + const startY = box.y + box.height / 2; + await page.mouse.move(startX, startY); + await page.mouse.down(); + await page.mouse.move(startX + dx / 2, startY + dy / 2, { steps: 4 }); + await page.mouse.move(startX + dx, startY + dy, { steps: 4 }); + await page.mouse.up(); + await page.waitForTimeout(100); // let the last animation frame apply +} + +// Boundary clamping, snapping and resize maths are covered by unit tests in utils/geometry.spec.ts. +// These check that the pointer handling in Canvas.svelte is wired to them. +test.describe('Canvas interaction', () => { + test('dragging an element moves it without resizing it', async ({ page }) => { + await addTextElement(page); + const before = await geometry(page); + + await dragBy(page, page.locator('textarea'), 60, 40); + + const after = await geometry(page); + expect(after.x).toBeGreaterThan(before.x); + expect(after.y).toBeGreaterThan(before.y); + expect(after.width).toBe(before.width); + expect(after.height).toBe(before.height); + }); + + test('the north-west handle moves the origin and grows the element', async ({ page }) => { + await addTextElement(page); + await dragBy(page, page.locator('textarea'), 80, 80); // make room first + const before = await geometry(page); + + await dragBy(page, page.getByTestId('resize-handle-nw'), -30, -20); + + const after = await geometry(page); + expect(after.x).toBeLessThan(before.x); + expect(after.y).toBeLessThan(before.y); + expect(after.width).toBeGreaterThan(before.width); + expect(after.height).toBeGreaterThan(before.height); + }); +}); diff --git a/e2e/copy-paste.test.ts b/e2e/copy-paste.test.ts new file mode 100644 index 0000000..40362a4 --- /dev/null +++ b/e2e/copy-paste.test.ts @@ -0,0 +1,229 @@ +import { expect, test, type Page } from '@playwright/test'; +import { seedDocument } from './helpers'; + +const shape = (id: string, x: number, y: number) => ({ + id, + type: 'shape', + pageId: 'p1', + zIndex: 0, + x, + y, + width: 300, + height: 200, + shapeType: 'rectangle', + strokeColor: '#1d4ed8', + strokeWidth: 8, + fillColor: '#bfdbfe', + fillOpacity: 1 +}); + +const boundaries = { horizontal: { start: 100, end: 2380 }, vertical: { start: 100, end: 3408 } }; +const doc = (id = 'copy') => ({ + id, + schemaVersion: 1, + name: 'Copy', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { id: 'p1', boundaries, elements: { a: shape('a', 300, 300), b: shape('b', 900, 300) } }, + p2: { id: 'p2', boundaries, elements: {} } + } +}); + +async function openEditor(page: Page, document = doc()) { + await seedDocument(page, document); + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(page.getByTestId('document-canvas')).toHaveCount(2); +} + +const onPage = (page: Page, id: string) => + page.locator(`[data-page-id="${id}"] [data-testid="document-canvas"] > .cursor-move`); +const title = (page: Page) => page.getByTestId('property-panel-title'); + +/** The stored document's elements per page, once autosave has written it. */ +async function stored(page: Page) { + await expect(page.getByTestId('save-status')).toHaveText('Saved', { timeout: 10000 }); + return page.evaluate( + () => + new Promise>>>((resolve, reject) => { + const open = indexedDB.open('lienzo-db'); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const all = open.result.transaction('documents').objectStore('documents').getAll(); + all.onsuccess = () => + resolve( + Object.fromEntries( + Object.entries( + all.result[0].pages as Record< + string, + { elements: Record> } + > + ).map(([id, p]) => [id, p.elements]) + ) + ); + all.onerror = () => reject(all.error); + }; + }) + ); +} + +test.describe('Copy and paste', () => { + test('Ctrl+C and Ctrl+V paste a copy, a little to the side, and select it', async ({ page }) => { + await openEditor(page); + await onPage(page, 'p1').first().click(); + + await page.keyboard.press('ControlOrMeta+c'); + await page.keyboard.press('ControlOrMeta+v'); + + await expect(onPage(page, 'p1')).toHaveCount(3); + await expect(title(page)).toContainText('Shape Properties'); // the copy is selected + + await page.keyboard.press('ControlOrMeta+v'); // again: a further copy, further along + await expect(onPage(page, 'p1')).toHaveCount(4); + + const elements = Object.values((await stored(page)).p1); + const xs = elements.map((el) => el.x as number).sort((m, n) => m - n); + expect(xs).toEqual([300, 340, 380, 900]); // original, two pastes, the other element + }); + + test('Ctrl+X removes the elements and Ctrl+V puts them back where they were', async ({ + page + }) => { + await openEditor(page); + await onPage(page, 'p1').first().click(); + + await page.keyboard.press('ControlOrMeta+x'); + await expect(onPage(page, 'p1')).toHaveCount(1); + await page.keyboard.press('ControlOrMeta+v'); + + await expect(onPage(page, 'p1')).toHaveCount(2); + const xs = Object.values((await stored(page)).p1) + .map((el) => el.x as number) + .sort((m, n) => m - n); + expect(xs).toEqual([300, 900]); + }); + + test('a selection or group is pasted as a group', async ({ page }) => { + await openEditor(page); + await onPage(page, 'p1').nth(0).click(); + await onPage(page, 'p1') + .nth(1) + .click({ modifiers: ['Shift'] }); + await page.keyboard.press('ControlOrMeta+g'); + + await page.keyboard.press('ControlOrMeta+c'); + await page.keyboard.press('ControlOrMeta+v'); + + await expect(onPage(page, 'p1')).toHaveCount(4); + await expect(title(page)).toHaveText('Group of 2 elements'); // the pasted pair is a group of its own + const groups = Object.values((await stored(page)).p1).map((el) => el.groupId as string); + expect(new Set(groups).size).toBe(2); + }); + + test('pastes onto the page that was clicked last, in the same position', async ({ page }) => { + await openEditor(page); + await onPage(page, 'p1').first().click(); + await page.keyboard.press('ControlOrMeta+c'); + + await page.locator('[data-page-id="p2"] [data-testid="document-canvas"]').click(); + await page.keyboard.press('ControlOrMeta+v'); + + await expect(onPage(page, 'p2')).toHaveCount(1); + await expect(onPage(page, 'p1')).toHaveCount(2); + const { p2 } = await stored(page); + expect(Object.values(p2)[0]).toMatchObject({ x: 300, y: 300 }); + }); + + test('the Copy and Paste buttons and Duplicate work without the keyboard', async ({ page }) => { + await openEditor(page); + await onPage(page, 'p1').first().click(); + + await page.getByTestId('duplicate-btn').click(); + await expect(onPage(page, 'p1')).toHaveCount(3); + + await page.getByTestId('copy-btn').click(); + await page.locator('[data-page-id="p2"] [data-testid="document-canvas"]').click(); + await page.getByTestId('paste-btn').click(); + await expect(onPage(page, 'p2')).toHaveCount(1); + await expect(onPage(page, 'p1')).toHaveCount(3); + + await page.getByTestId('cut-btn').click(); + await expect(onPage(page, 'p2')).toHaveCount(0); + }); + + test('Ctrl+D duplicates the selection', async ({ page }) => { + await openEditor(page); + await onPage(page, 'p1').first().click(); + + await page.keyboard.press('ControlOrMeta+d'); + + await expect(onPage(page, 'p1')).toHaveCount(3); + }); + + test('copy and paste keep working as normal text editing inside a text box', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); + await page.getByTestId('tool-text').dragTo(page.getByTestId('document-canvas'), { + targetPosition: { x: 100, y: 100 } + }); + const textarea = page.locator('textarea'); + await textarea.fill('hello'); + await textarea.press('ControlOrMeta+a'); + await page.keyboard.press('ControlOrMeta+c'); + await page.keyboard.press('ControlOrMeta+v'); + await page.keyboard.press('ControlOrMeta+v'); + + await expect(textarea).toHaveValue('hellohello'); // text pasted into the text, not new elements + await expect(page.locator('[data-testid="document-canvas"] > .cursor-move')).toHaveCount(1); + }); + + test('a picture pasted from the clipboard becomes an image element', async ({ page }) => { + await openEditor(page); + await page.locator('[data-page-id="p2"] [data-testid="document-canvas"]').click(); + + await page.evaluate(async () => { + // A 300x150 picture, as a screenshot would be + const canvas = document.createElement('canvas'); + canvas.width = 300; + canvas.height = 150; + canvas.getContext('2d')!.fillRect(0, 0, 300, 150); + const blob = await new Promise((resolve) => + canvas.toBlob((b) => resolve(b!), 'image/png') + ); + const data = new DataTransfer(); + data.items.add(new File([blob], 'screenshot.png', { type: 'image/png' })); + document.dispatchEvent( + new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }) + ); + }); + + await expect(onPage(page, 'p2')).toHaveCount(1); + await expect(title(page)).toContainText('Image Properties'); + const { p2 } = await stored(page); + expect(Object.values(p2)[0]).toMatchObject({ + type: 'image', + alt: 'screenshot.png', + width: 300, + height: 150 + }); + expect(String(Object.values(p2)[0].src)).toMatch(/^data:image\/png;base64,/); + }); + + test('copied elements can be pasted into another document in a new tab', async ({ + page, + context + }) => { + await openEditor(page); + await onPage(page, 'p1').first().click(); + await page.keyboard.press('ControlOrMeta+c'); + + // A new tab with a new, empty document + const other = await context.newPage(); + await other.goto('/canvas'); + await other.waitForLoadState('networkidle'); + await other.getByTestId('document-canvas').click(); + await other.keyboard.press('ControlOrMeta+v'); + + await expect(other.locator('[data-testid="document-canvas"] > .cursor-move')).toHaveCount(1); + }); +}); diff --git a/e2e/documents-sort.test.ts b/e2e/documents-sort.test.ts new file mode 100644 index 0000000..73e411a --- /dev/null +++ b/e2e/documents-sort.test.ts @@ -0,0 +1,99 @@ +import { expect, test, type Page } from '@playwright/test'; + +const doc = (id: string, name: string, createdAt: number, updatedAt: number) => ({ + id, + schemaVersion: 1, + name, + createdAt, + updatedAt, + pages: { + p1: { + id: 'p1', + boundaries: { horizontal: { start: 100, end: 700 }, vertical: { start: 100, end: 1000 } }, + elements: {} + } + } +}); + +// Names are chosen so each sort order gives a different, easy to read list +const docs = [ + doc('a', 'Invoice 10', 100, 5000), + doc('b', 'invoice 2', 300, 9000), + doc('c', 'Zebra', 200, 1000), + doc('d', 'apple', 400, 7000) +]; + +async function seed(page: Page) { + await page.goto('/documents'); + await page.getByText('No documents').waitFor(); + await page.evaluate( + (records) => + new Promise((resolve, reject) => { + const open = indexedDB.open('lienzo-db', 1); + open.onsuccess = () => { + const tx = open.result.transaction('documents', 'readwrite'); + for (const record of records) tx.objectStore('documents').put(record); + tx.oncomplete = () => resolve(); + tx.onerror = () => reject(tx.error); + }; + open.onerror = () => reject(open.error); + }), + docs + ); + await page.reload(); + await page.waitForLoadState('networkidle'); +} + +const names = (page: Page) => page.locator('main h3').allTextContents(); + +test.describe('Documents sorting', () => { + test('starts with the most recently updated, and each option reorders the list', async ({ + page + }) => { + await seed(page); + const select = page.getByTestId('sort-select'); + await expect(select).toHaveValue('updated-desc'); + expect(await names(page)).toEqual(['invoice 2', 'apple', 'Invoice 10', 'Zebra']); + + await select.selectOption('updated-asc'); + expect(await names(page)).toEqual(['Zebra', 'Invoice 10', 'apple', 'invoice 2']); + + await select.selectOption('created-desc'); + expect(await names(page)).toEqual(['apple', 'invoice 2', 'Zebra', 'Invoice 10']); + + await select.selectOption('name-asc'); + expect(await names(page)).toEqual(['apple', 'invoice 2', 'Invoice 10', 'Zebra']); + + await select.selectOption('name-desc'); + expect(await names(page)).toEqual(['Zebra', 'Invoice 10', 'invoice 2', 'apple']); + }); + + test('the choice is remembered, and the search keeps the order', async ({ page }) => { + await seed(page); + await page.getByTestId('sort-select').selectOption('name-asc'); + + await page.reload(); + await page.waitForLoadState('networkidle'); + await expect(page.getByTestId('sort-select')).toHaveValue('name-asc'); + expect(await names(page)).toEqual(['apple', 'invoice 2', 'Invoice 10', 'Zebra']); + + await page.getByLabel('Search documents').fill('invoice'); + await expect.poll(() => names(page)).toEqual(['invoice 2', 'Invoice 10']); + }); + + test('on a phone the control sits on the right', async ({ browser }) => { + const context = await browser.newContext({ viewport: { width: 375, height: 812 } }); + const page = await context.newPage(); + await seed(page); + const box = await page.getByTestId('sort-select').boundingBox(); + expect(box).not.toBeNull(); + expect(box!.x + box!.width).toBeGreaterThan(375 - 24); // against the right edge, not the left + await context.close(); + }); + + test('an unknown saved choice falls back to the default', async ({ page }) => { + await page.addInitScript(() => localStorage.setItem('lienzo-documents-sort', 'sideways')); + await seed(page); + await expect(page.getByTestId('sort-select')).toHaveValue('updated-desc'); + }); +}); diff --git a/e2e/export-dialog.test.ts b/e2e/export-dialog.test.ts new file mode 100644 index 0000000..e1f36b4 --- /dev/null +++ b/e2e/export-dialog.test.ts @@ -0,0 +1,151 @@ +import { expect, test, type Page } from '@playwright/test'; +import { seedDocument } from './helpers'; + +const boundaries = { horizontal: { start: 100, end: 700 }, vertical: { start: 100, end: 1000 } }; +const doc = { + id: 'dlg', + schemaVersion: 1, + name: 'Quarterly report', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { + id: 'p1', + boundaries, + elements: { + t: { + id: 't', + type: 'text', + pageId: 'p1', + zIndex: 0, + x: 120, + y: 140, + width: 400, + height: 80, + text: 'Headline', + fontFamily: 'Inter', + fontSize: 24, + fontWeight: '400', + fontStyle: 'normal', + color: '#000000' + } + } + }, + p2: { id: 'p2', boundaries, elements: {} } + } +}; + +async function openDialog(page: Page, document: object = doc) { + await seedDocument(page, document); + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(page.getByTestId('document-canvas')).toHaveCount(2); + await page.getByTestId('export-btn').click(); + const dialog = page.getByRole('dialog'); + await expect(dialog).toBeVisible(); + return dialog; +} + +test.describe('Export dialog', () => { + test('previews every page and offers the document name as the file name', async ({ page }) => { + const dialog = await openDialog(page); + + await expect(dialog.getByRole('img', { name: 'Preview of page 1' })).toBeVisible(); + await expect(dialog.getByRole('img', { name: 'Preview of page 2' })).toBeVisible(); + await expect(dialog.getByTestId('export-file-name')).toHaveValue('Quarterly report'); + await expect(dialog).toContainText('lienzo-document.json is attached'); + await expect(dialog).toContainText('2 pages'); + await expect(dialog.getByRole('button', { name: 'Export PDF' })).toBeEnabled(); + }); + + test('downloads under the chosen file name, then shows the result in the dialog', async ({ + page + }) => { + const dialog = await openDialog(page); + await dialog.getByTestId('export-file-name').fill('Board pack: Q3/2026'); + + const download = page.waitForEvent('download'); + await dialog.getByRole('button', { name: 'Export PDF' }).click(); + + // characters systems do not accept in file names are replaced + expect((await download).suggestedFilename()).toBe('Board pack Q3 2026.pdf'); + await expect(dialog.getByTestId('export-done')).toContainText( + 'Board pack Q3 2026.pdf was saved' + ); + await expect(dialog.getByTestId('export-warning')).toHaveCount(0); + + // it can be exported again without reopening the dialog + const again = page.waitForEvent('download'); + await dialog.getByRole('button', { name: 'Export again' }).click(); + await again; + await dialog.getByRole('button', { name: 'Close' }).click(); + await expect(dialog).toHaveCount(0); + }); + + test('an empty file name is explained and nothing is exported', async ({ page }) => { + const dialog = await openDialog(page); + await dialog.getByTestId('export-file-name').fill(' '); + + await dialog.getByRole('button', { name: 'Export PDF' }).click(); + + await expect(dialog.getByRole('alert')).toHaveText('Enter a file name.'); + await expect(dialog.getByTestId('export-done')).toHaveCount(0); + await expect(dialog.getByTestId('export-file-name')).toHaveAttribute('aria-invalid', 'true'); + }); + + test('Cancel and Escape close it without exporting', async ({ page }) => { + let downloads = 0; + page.on('download', () => downloads++); + + const dialog = await openDialog(page); + await dialog.getByRole('button', { name: 'Cancel' }).click(); + await expect(dialog).toHaveCount(0); + + await page.getByTestId('export-btn').click(); + await expect(page.getByRole('dialog')).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(page.getByRole('dialog')).toHaveCount(0); + expect(downloads).toBe(0); + }); + + test('a document without a name is exported as Untitled document', async ({ page }) => { + const dialog = await openDialog(page, { ...doc, name: '' }); + await expect(dialog.getByTestId('export-file-name')).toHaveValue('Untitled document'); + }); + + test('the backdrop is dark in the dark theme, not a bright wash', async ({ browser }) => { + const context = await browser.newContext({ colorScheme: 'dark' }); + const page = await context.newPage(); + const dialog = await openDialog(page); + + const backdrop = await dialog.evaluate((el) => getComputedStyle(el).backgroundColor); + expect(backdrop).toMatch(/0 0 0 \/ 0\.6|rgba\(0, 0, 0, 0\.6/); // black at 60%, not a white wash + await context.close(); + }); +}); + +test.describe('Editor header', () => { + test('shows the document, its page count and the save status', async ({ page }) => { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + + await expect(page.getByTestId('document-title')).toHaveText('Quarterly report'); + await expect(page.getByTestId('page-count')).toContainText('2 Pages'); + await expect(page.getByTestId('back-btn')).toBeVisible(); + await expect(page.getByTestId('theme-toggle')).toBeVisible(); + }); + + test('a new document is called Untitled document until it is named', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive + await expect(page.getByTestId('document-title')).toHaveText('Untitled document'); + }); + + test('the select-multiple switch reports whether it is on', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive + const toggle = page.getByTestId('multi-select-toggle'); + await expect(toggle).toHaveAttribute('aria-pressed', 'false'); + await toggle.click(); + await expect(toggle).toHaveAttribute('aria-pressed', 'true'); + }); +}); diff --git a/e2e/header-responsive.test.ts b/e2e/header-responsive.test.ts new file mode 100644 index 0000000..35100d4 --- /dev/null +++ b/e2e/header-responsive.test.ts @@ -0,0 +1,105 @@ +import { expect, test, type Page } from '@playwright/test'; +import { seedDocument } from './helpers'; + +const doc = { + id: 'hdr', + schemaVersion: 1, + name: 'A fairly long document name for the header', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { + id: 'p1', + boundaries: { horizontal: { start: 100, end: 2380 }, vertical: { start: 100, end: 3408 } }, + elements: {} + } + } +}; + +const IDS = [ + 'add-page-btn', + 'multi-select-toggle', + 'paste-btn', + 'canvas-import-btn', + 'save-btn', + 'export-btn' +]; + +async function openAt(page: Page, width: number, name = doc.name) { + await page.setViewportSize({ width, height: 800 }); + await seedDocument(page, { ...doc, name }); + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(page.getByTestId('document-canvas')).toBeVisible(); + await page.waitForTimeout(300); +} + +/** The visible width of a button's text, 0 when it is only an icon */ +const labelWidth = (page: Page, id: string) => + page.getByTestId(id).evaluate((button) => { + const label = [...button.querySelectorAll('span')].find((s) => s.textContent?.trim()); + return label ? label.getBoundingClientRect().width : 0; + }); + +test.describe('Editor header at every width', () => { + for (const width of [1920, 1360, 1280, 1180, 1024, 900, 768]) { + test(`stays on one row at ${width}px`, async ({ page }) => { + await openAt(page, width); + + const header = (await page.locator('header').boundingBox())!; + expect(header.height).toBeLessThan(80); // a single row of 36px controls + const tops = await Promise.all( + IDS.map(async (id) => (await page.getByTestId(id).boundingBox())!.y) + ); + expect(Math.max(...tops) - Math.min(...tops)).toBeLessThan(8); // all on the same line + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth - document.documentElement.clientWidth + ); + expect(overflow).toBeLessThanOrEqual(0); + }); + } + + test('wide: every action shows its name', async ({ page }) => { + await openAt(page, 1360); + for (const id of IDS) expect(await labelWidth(page, id), id).toBeGreaterThan(10); + }); + + test('medium: the secondary actions become icons and Export keeps its name', async ({ page }) => { + await openAt(page, 1100); + for (const id of IDS.slice(0, 5)) expect(await labelWidth(page, id), id).toBeLessThan(2); + expect(await labelWidth(page, 'export-btn')).toBeGreaterThan(10); + }); + + test('narrow: everything is an icon', async ({ page }) => { + await openAt(page, 860); + for (const id of IDS) expect(await labelWidth(page, id), id).toBeLessThan(2); + }); + + test('the icons keep their names for screen readers and hover tooltips', async ({ page }) => { + await openAt(page, 860); + for (const name of ['Add page', 'Select multiple', 'Paste', 'Import', 'Save', 'Export PDF']) { + const button = page.getByRole('button', { name, exact: true }); + await expect(button).toBeVisible(); + await expect(button).toHaveAttribute('title', name); + } + }); + + test('the document title shortens instead of pushing the buttons away', async ({ page }) => { + await openAt( + page, + 768, + 'An extremely long document name that keeps going and going for a very long time indeed' + ); + const title = page.getByTestId('document-title'); + expect(await title.evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true); // cut with an ellipsis + expect((await page.getByTestId('export-btn').boundingBox())!.x).toBeGreaterThan(500); // still at the right + const header = (await page.locator('header').boundingBox())!; + expect(header.height).toBeLessThan(80); + }); + + test('on a phone the actions are Export and a menu', async ({ page }) => { + await openAt(page, 390); + await expect(page.getByTestId('export-btn-phone')).toBeVisible(); + await expect(page.getByTestId('more-menu-btn')).toBeVisible(); + await expect(page.getByTestId('export-btn')).toBeHidden(); + }); +}); diff --git a/e2e/helpers.ts b/e2e/helpers.ts new file mode 100644 index 0000000..9f4167d --- /dev/null +++ b/e2e/helpers.ts @@ -0,0 +1,22 @@ +import type { Page } from '@playwright/test'; + +/** Put a raw record into the app's IndexedDB (opening /documents first creates the database). */ +export async function seedDocument(page: Page, doc: unknown) { + await page.goto('/documents'); + await page.getByText('No documents').waitFor(); + await page.evaluate( + (record) => + new Promise((resolve, reject) => { + const open = indexedDB.open('lienzo-db', 1); + open.onsuccess = () => { + const tx = open.result.transaction('documents', 'readwrite'); + tx.objectStore('documents').put(record); + tx.oncomplete = () => resolve(); + tx.onerror = () => reject(tx.error); + }; + open.onerror = () => reject(open.error); + }), + doc + ); + await page.reload(); +} diff --git a/e2e/home.test.ts b/e2e/home.test.ts new file mode 100644 index 0000000..323f3c7 --- /dev/null +++ b/e2e/home.test.ts @@ -0,0 +1,69 @@ +import { expect, test } from '@playwright/test'; + +test.describe('Home page', () => { + test('has the search essentials: title, description, one h1, landmarks', async ({ page }) => { + await page.goto('/'); + + await expect(page).toHaveTitle(/Free Document Builder with Editable PDF Export/); + const description = await page.locator('meta[name="description"]').getAttribute('content'); + expect(description!.length).toBeGreaterThan(70); + expect(description!.length).toBeLessThanOrEqual(160); + await expect(page.locator('h1')).toHaveCount(1); + await expect(page.getByRole('banner')).toBeVisible(); + await expect(page.getByRole('main')).toBeVisible(); + await expect(page.getByRole('contentinfo')).toBeVisible(); + await expect(page.locator('link[rel="canonical"]')).toHaveAttribute( + 'href', + 'https://lienzo.deityhub.com/' + ); + }); + + test('describes the app and its questions as structured data', async ({ page }) => { + await page.goto('/'); + + const data = JSON.parse( + (await page.locator('script[type="application/ld+json"]').first().textContent())! + ); + const types = data['@graph'].map((item: { '@type': string }) => item['@type']); + expect(types).toEqual(['WebApplication', 'FAQPage']); + + // Every question in the structured data is on the page, word for word + for (const question of data['@graph'][1].mainEntity as Array<{ name: string }>) { + await expect(page.getByText(question.name, { exact: true })).toBeVisible(); + } + }); + + test('the questions open and close without JavaScript', async ({ page }) => { + await page.goto('/'); + const second = page.locator('details').nth(1); + + await expect(page.locator('details').first()).toHaveAttribute('open', ''); + await expect(second).not.toHaveAttribute('open', ''); + await second.locator('summary').click(); + await expect(second).toHaveAttribute('open', ''); + }); + + test('the editor can be opened from the header and the hero', async ({ page }) => { + await page.goto('/'); + await expect(page.getByRole('link', { name: 'Open the editor' }).first()).toHaveAttribute( + 'href', + '/canvas' + ); + await expect(page.getByRole('link', { name: 'Start designing' })).toHaveAttribute( + 'href', + '/canvas' + ); + }); + + test('fits a phone: nothing sideways, and the main actions are reachable', async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto('/'); + + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth - document.documentElement.clientWidth + ); + expect(overflow).toBeLessThanOrEqual(0); + await expect(page.getByRole('link', { name: 'Start designing' })).toBeVisible(); + await expect(page.getByTestId('theme-toggle')).toBeVisible(); + }); +}); diff --git a/e2e/import-export.test.ts b/e2e/import-export.test.ts new file mode 100644 index 0000000..e67d482 --- /dev/null +++ b/e2e/import-export.test.ts @@ -0,0 +1,220 @@ +import { expect, test } from '@playwright/test'; +import { readFile } from 'node:fs/promises'; +import { seedDocument } from './helpers'; + +const doc = { + id: 'doc-1', + schemaVersion: 1, + name: 'My Resume', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { + id: 'p1', + boundaries: { horizontal: { start: 100, end: 700 }, vertical: { start: 100, end: 1000 } }, + elements: {} + } + } +}; + +test.describe('Import / export', () => { + test('export all is disabled when there are no documents', async ({ page }) => { + await page.goto('/documents'); + await expect(page.getByTestId('export-all-btn')).toBeDisabled(); + }); + + test('exports a document and shows the file contents', async ({ page }) => { + await seedDocument(page, doc); + + const downloadPromise = page.waitForEvent('download'); + await page.getByTestId('export-document-btn').click(); + const download = await downloadPromise; + expect(download.suggestedFilename()).toBe('my-resume.lienzo.json'); + + const file = JSON.parse(await readFile(await download.path(), 'utf-8')); + expect(file).toMatchObject({ app: 'lienzo', formatVersion: 1 }); + expect(file.documents[0].name).toBe('My Resume'); + }); + + test('importing into an empty library restores the document without asking', async ({ page }) => { + await page.goto('/documents'); + await page.waitForLoadState('networkidle'); // the page must be interactive before a file is chosen + await page.getByTestId('import-input').setInputFiles({ + name: 'resume.lienzo.json', + mimeType: 'application/json', + buffer: Buffer.from(JSON.stringify({ app: 'lienzo', formatVersion: 1, documents: [doc] })) + }); + + await expect(page.getByTestId('import-notice')).toContainText('Imported 1 document'); + await expect(page.getByRole('heading', { name: 'My Resume' })).toBeVisible(); + await expect(page.getByTestId('import-keep-both-btn')).toBeHidden(); + }); + + test.describe('when an imported document already exists', () => { + const file = { + name: 'resume.lienzo.json', + mimeType: 'application/json', + buffer: Buffer.from( + JSON.stringify({ + app: 'lienzo', + formatVersion: 1, + documents: [{ ...doc, name: 'My Resume (edited)' }] + }) + ) + }; + + test('asks, and "Keep both" imports a separate copy', async ({ page }) => { + await seedDocument(page, doc); + await page.getByTestId('import-input').setInputFiles(file); + + await expect(page.getByTestId('conflict-list')).toContainText('My Resume (edited)'); + await page.getByTestId('import-keep-both-btn').click(); + + await expect(page.getByTestId('import-notice')).toContainText('Imported 1 document'); + await expect(page.getByRole('heading', { name: 'My Resume', exact: true })).toBeVisible(); + await expect(page.getByRole('heading', { name: 'My Resume (edited)' })).toBeVisible(); + }); + + test('"Replace existing" overwrites the saved document', async ({ page }) => { + await seedDocument(page, doc); + await page.getByTestId('import-input').setInputFiles(file); + await page.getByTestId('import-replace-btn').click(); + + await expect(page.getByRole('heading', { name: 'My Resume (edited)' })).toBeVisible(); + await expect(page.getByRole('heading', { name: 'My Resume', exact: true })).toHaveCount(0); + }); + + test('Cancel imports nothing', async ({ page }) => { + await seedDocument(page, doc); + await page.getByTestId('import-input').setInputFiles(file); + await page.getByRole('button', { name: 'Cancel' }).click(); + + await expect(page.getByTestId('import-notice')).toBeHidden(); + await expect(page.getByRole('heading', { name: 'My Resume', exact: true })).toBeVisible(); + await expect(page.getByRole('heading', { name: 'My Resume (edited)' })).toHaveCount(0); + }); + }); + + test('importing an invalid file shows an error and keeps existing documents', async ({ + page + }) => { + await seedDocument(page, doc); + + await page.getByTestId('import-input').setInputFiles({ + name: 'broken.json', + mimeType: 'application/json', + buffer: Buffer.from('{"not":"lienzo"}') + }); + + const notice = page.getByTestId('import-notice'); + await expect(notice).toContainText('Nothing was imported'); + await expect(notice).toContainText('broken.json – This is not a Lienzo document file.'); + await expect(page.getByRole('heading', { name: 'My Resume' })).toHaveCount(1); + }); + + test.describe('importing into the canvas', () => { + const twoPageDocument = { + ...doc, + id: 'canvas-doc', + name: 'Imported Doc', + pages: { + p1: { + id: 'p1', + boundaries: { horizontal: { start: 100, end: 700 }, vertical: { start: 100, end: 1000 } }, + elements: { + t1: { + id: 't1', + type: 'text', + pageId: 'p1', + zIndex: 0, + x: 120, + y: 140, + width: 400, + height: 80, + text: 'Imported headline', + fontFamily: 'Inter', + fontSize: 24, + fontWeight: '400', + fontStyle: 'normal', + color: '#000000' + } + } + }, + p2: { + id: 'p2', + boundaries: { horizontal: { start: 100, end: 700 }, vertical: { start: 100, end: 1000 } }, + elements: {} + } + } + }; + const fileOf = (documents: unknown[], name = 'doc.lienzo.json') => ({ + name, + mimeType: 'application/json', + buffer: Buffer.from(JSON.stringify({ app: 'lienzo', formatVersion: 1, documents })) + }); + + test('an empty canvas is replaced right away', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive + await page.getByTestId('canvas-import-input').setInputFiles(fileOf([twoPageDocument])); + + await expect(page.getByTestId('page-count')).toContainText('2 Pages'); + await expect(page.locator('textarea')).toHaveValue('Imported headline'); + await expect(page.getByTestId('canvas-import-confirm')).toBeHidden(); + }); + + test('a canvas with content asks before replacing it', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive + await page.getByTestId('tool-text').dragTo(page.getByTestId('document-canvas'), { + targetPosition: { x: 200, y: 200 } + }); + await expect(page.getByTestId('property-panel-title')).toContainText('Text Properties'); + + await page.getByTestId('canvas-import-input').setInputFiles(fileOf([twoPageDocument])); + await expect(page.getByTestId('canvas-import-confirm')).toContainText('Imported Doc'); + await expect(page.getByTestId('page-count')).toContainText('1 Page'); + + await page.getByRole('button', { name: 'Replace canvas' }).click(); + await expect(page.getByTestId('page-count')).toContainText('2 Pages'); + await expect(page.locator('textarea')).toHaveValue('Imported headline'); + }); + + test('cancelling keeps the current canvas', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive + await page.getByTestId('add-page-btn').click(); + + await page.getByTestId('canvas-import-input').setInputFiles(fileOf([twoPageDocument])); + await page.getByRole('dialog').getByRole('button', { name: 'Cancel' }).click(); + + await expect(page.getByTestId('page-count')).toContainText('2 Pages'); + await expect(page.locator('textarea')).toHaveCount(0); + }); + + test('a file with several documents is rejected', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive + await page + .getByTestId('canvas-import-input') + .setInputFiles(fileOf([twoPageDocument, { ...twoPageDocument, id: 'other' }])); + + await expect(page.getByTestId('canvas-import-error')).toContainText( + 'contains 2 documents. Import it from the Documents page instead.' + ); + await expect(page.getByTestId('page-count')).toContainText('1 Page'); + }); + + test('an invalid file shows an error', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive + await page.getByTestId('canvas-import-input').setInputFiles({ + name: 'bad.json', + mimeType: 'application/json', + buffer: Buffer.from('nope') + }); + + await expect(page.getByTestId('canvas-import-error')).toContainText('not valid JSON'); + }); + }); +}); diff --git a/e2e/move-between-pages.test.ts b/e2e/move-between-pages.test.ts new file mode 100644 index 0000000..5b90af2 --- /dev/null +++ b/e2e/move-between-pages.test.ts @@ -0,0 +1,212 @@ +import { expect, test, type Locator, type Page } from '@playwright/test'; +import { seedDocument } from './helpers'; + +const shape = (id: string, pageId: string, x: number, y: number, extra: object = {}) => ({ + id, + type: 'shape', + pageId, + zIndex: 0, + x, + y, + width: 300, + height: 200, + shapeType: 'rectangle', + strokeColor: '#1d4ed8', + strokeWidth: 8, + fillColor: '#bfdbfe', + fillOpacity: 1, + ...extra +}); + +const boundaries = { + horizontal: { start: 100, end: 2380 }, + vertical: { start: 100, end: 3408 } +}; + +const doc = { + id: 'pages', + schemaVersion: 1, + name: 'Pages', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { + id: 'p1', + boundaries, + elements: { a: shape('a', 'p1', 300, 300), b: shape('b', 'p1', 900, 300) } + }, + p2: { id: 'p2', boundaries, elements: {} } + } +}; + +async function openEditor(page: Page) { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(page.getByTestId('document-canvas')).toHaveCount(2); +} + +/** The element's box once the layout has stopped moving (panels slide, scroll bars appear). */ +async function settledBox(locator: Locator) { + let last = JSON.stringify(await locator.boundingBox()); + await expect + .poll(async () => { + await locator.page().waitForTimeout(150); + const now = JSON.stringify(await locator.boundingBox()); + const same = now === last; + last = now; + return same; + }) + .toBe(true); + return (await locator.boundingBox())!; +} + +const PAGE_WIDTH = 2480; + +const onPage = (page: Page, id: string) => + page.locator(`[data-page-id="${id}"] [data-testid="document-canvas"] > .cursor-move`); + +/** The stored copy of the document: autosave writes it after an edit. */ +const storedPages = (page: Page) => + page.evaluate( + () => + new Promise }>>((resolve, reject) => { + const open = indexedDB.open('lienzo-db'); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const all = open.result.transaction('documents').objectStore('documents').getAll(); + all.onsuccess = () => resolve(all.result[0].pages); + all.onerror = () => reject(all.error); + }; + }) + ); + +test.describe('Moving elements between pages', () => { + test('dragging an element onto the next page moves it there', async ({ page }) => { + await page.setViewportSize({ width: 1400, height: 2900 }); // both pages are on screen + await openEditor(page); + const nextPage = page.locator('[data-page-id="p2"] [data-testid="document-canvas"]'); + + // Playwright waits for the layout to settle and finds the positions itself + await onPage(page, 'p1') + .first() + .dragTo(nextPage, { sourcePosition: { x: 20, y: 20 }, targetPosition: { x: 150, y: 200 } }); + + await expect(onPage(page, 'p1')).toHaveCount(1); + await expect(onPage(page, 'p2')).toHaveCount(1); + await expect(page.getByTestId('page-drop-preview')).toHaveCount(0); + + // The change is saved, in page units: the element's corner is where the pointer was, minus the + // 20px it was grabbed at. Screen pixels become page pixels by the display scale, whatever the machine. + await expect(page.getByTestId('save-status')).toHaveText('Saved', { timeout: 10000 }); + const stored = await storedPages(page); + expect(Object.keys(stored.p1.elements)).toEqual(['b']); + expect(Object.keys(stored.p2.elements)).toEqual(['a']); + + const scale = (await nextPage.boundingBox())!.width / PAGE_WIDTH; + const landed = stored.p2.elements.a as { x: number; y: number }; + expect(Math.abs(landed.x - 130 / scale)).toBeLessThan(10); + expect(Math.abs(landed.y - 180 / scale)).toBeLessThan(10); + }); + + test('a selection or group moves together', async ({ page }) => { + await page.setViewportSize({ width: 1400, height: 2900 }); + await openEditor(page); + await onPage(page, 'p1').nth(0).click(); + await onPage(page, 'p1') + .nth(1) + .click({ modifiers: ['Shift'] }); + await page.getByTestId('group-btn').click(); + + await onPage(page, 'p1') + .first() + .dragTo(page.locator('[data-page-id="p2"] [data-testid="document-canvas"]'), { + sourcePosition: { x: 20, y: 20 }, + targetPosition: { x: 100, y: 100 } + }); + + await expect(onPage(page, 'p1')).toHaveCount(0); + await expect(onPage(page, 'p2')).toHaveCount(2); + await expect(page.getByTestId('property-panel-title')).toHaveText('Group of 2 elements'); + + // Still the same distance apart, in page units (300 and 900 on the page before) + await expect(page.getByTestId('save-status')).toHaveText('Saved', { timeout: 10000 }); + const { a, b } = (await storedPages(page)).p2.elements as Record; + expect(b.x - a.x).toBeCloseTo(600, 0); + }); + + test('dragging near the bottom edge scrolls to a page that is out of view', async ({ page }) => { + await openEditor(page); // the default window shows only the first page + const container = page.getByTestId('canvas-container'); + const from = await settledBox(onPage(page, 'p1').first()); + await page.mouse.move(from.x + 20, from.y + 20); + await page.mouse.down(); + + const window = page.viewportSize()!; + await page.mouse.move(from.x + 20, window.height - 20, { steps: 5 }); + await expect + .poll(() => container.evaluate((el) => el.scrollTop), { timeout: 10000 }) + .toBeGreaterThan(1000); + + // Stop scrolling by moving to the middle, then drop it on the second page, which has come into view + await page.mouse.move(from.x + 20, window.height / 2); + await expect // wait until the list has stopped scrolling + .poll(async () => { + const before = await container.evaluate((el) => el.scrollTop); + await page.waitForTimeout(100); + return before === (await container.evaluate((el) => el.scrollTop)); + }) + .toBe(true); + const target = await settledBox( + page.locator('[data-page-id="p2"] [data-testid="document-canvas"]') + ); + const y = Math.min(Math.max(target.y + 100, 250), window.height - 250); + await page.mouse.move(target.x + 200, y, { steps: 5 }); + await expect(page.getByTestId('page-drop-preview')).toBeVisible(); + await page.mouse.up(); + + await expect(onPage(page, 'p2')).toHaveCount(1); + }); + + test('Escape while dragging over another page cancels the move', async ({ page }) => { + await page.setViewportSize({ width: 1400, height: 2900 }); + await openEditor(page); + const from = await settledBox(onPage(page, 'p1').first()); + const target = await settledBox( + page.locator('[data-page-id="p2"] [data-testid="document-canvas"]') + ); + + await page.getByTestId('document-canvas').first().focus(); + await page.mouse.move(from.x + 20, from.y + 20); + await page.mouse.down(); + await page.mouse.move(target.x + 150, target.y + 200, { steps: 10 }); + await expect(page.getByTestId('page-drop-preview')).toBeVisible(); + await page.keyboard.press('Escape'); + await page.mouse.up(); + + await expect(page.getByTestId('page-drop-preview')).toHaveCount(0); + await expect(onPage(page, 'p1')).toHaveCount(2); + }); + + test('the Move to Page selector moves the selection without dragging', async ({ page }) => { + await openEditor(page); + await onPage(page, 'p1').first().click(); + + await page.getByTestId('move-to-page').click(); + await expect(page.getByTestId('move-to-page-option-p1')).toHaveCount(0); // not its own page + await page.getByTestId('move-to-page-option-p2').click(); + + await expect(onPage(page, 'p1')).toHaveCount(1); + await expect(onPage(page, 'p2')).toHaveCount(1); + await expect(page.getByTestId('property-panel-title')).toContainText('Shape Properties'); // still selected + }); + + test('there is nothing to choose with a single page', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive + await page.getByTestId('tool-shape').dragTo(page.getByTestId('document-canvas'), { + targetPosition: { x: 200, y: 200 } + }); + await expect(page.getByTestId('property-panel')).toBeVisible(); + await expect(page.getByTestId('move-to-page')).toHaveCount(0); + }); +}); diff --git a/e2e/multi-select.test.ts b/e2e/multi-select.test.ts new file mode 100644 index 0000000..5c760ea --- /dev/null +++ b/e2e/multi-select.test.ts @@ -0,0 +1,331 @@ +import { expect, test, type Page } from '@playwright/test'; +import { seedDocument } from './helpers'; + +const shape = (id: string, x: number, y: number) => ({ + id, + type: 'shape', + pageId: 'p1', + zIndex: 0, + x, + y, + width: 300, + height: 200, + shapeType: 'rectangle', + strokeColor: '#1d4ed8', + strokeWidth: 8, + fillColor: '#bfdbfe', + fillOpacity: 1 +}); + +const doc = { + id: 'multi', + schemaVersion: 1, + name: 'Multi', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { + id: 'p1', + boundaries: { horizontal: { start: 100, end: 2380 }, vertical: { start: 100, end: 3408 } }, + elements: { + a: shape('a', 300, 300), + b: shape('b', 900, 300), + c: shape('c', 300, 1200) + } + } + } +}; + +async function openEditor(page: Page) { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(page.getByTestId('document-canvas')).toBeVisible(); +} + +const elements = (page: Page) => page.locator('[data-testid="document-canvas"] > .cursor-move'); +const title = (page: Page) => page.getByTestId('property-panel-title'); + +/** Convert page pixels to screen coordinates on the first canvas. */ +async function pagePoint(page: Page, x: number, y: number) { + const box = (await page.getByTestId('document-canvas').boundingBox())!; + const k = box.width / 2480; + return { x: box.x + x * k, y: box.y + y * k }; +} + +test.describe('Selecting several elements', () => { + test('Shift-click adds to the selection and a drag moves them together', async ({ page }) => { + await openEditor(page); + await elements(page).nth(0).click(); + await expect(title(page)).toContainText('Shape Properties'); + + await elements(page) + .nth(1) + .click({ modifiers: ['Shift'] }); + await expect(title(page)).toHaveText('2 elements selected'); + await expect(page.getByTestId('selection-box')).toBeVisible(); + + const before = [ + await elements(page).nth(0).boundingBox(), + await elements(page).nth(1).boundingBox() + ]; + const start = { x: before[0]!.x + 20, y: before[0]!.y + 20 }; + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + await page.mouse.move(start.x + 40, start.y + 60, { steps: 5 }); + await page.mouse.up(); + + const after = [ + await elements(page).nth(0).boundingBox(), + await elements(page).nth(1).boundingBox() + ]; + for (const i of [0, 1]) { + expect(after[i]!.x - before[i]!.x).toBeCloseTo(40, 0); + expect(after[i]!.y - before[i]!.y).toBeCloseTo(60, 0); + } + await expect(title(page)).toHaveText('2 elements selected'); // still selected after the drag + expect(await elements(page).nth(2).boundingBox()).toMatchObject({ + x: (await elements(page).nth(2).boundingBox())!.x + }); + }); + + test('Shift-click on a selected element removes it from the selection', async ({ page }) => { + await openEditor(page); + await elements(page).nth(0).click(); + await elements(page) + .nth(1) + .click({ modifiers: ['Shift'] }); + await expect(title(page)).toHaveText('2 elements selected'); + + await elements(page) + .nth(1) + .click({ modifiers: ['Shift'] }); + + await expect(title(page)).toContainText('Shape Properties'); + }); + + test('dragging a box over the empty page selects what it touches', async ({ page }) => { + await openEditor(page); + const from = await pagePoint(page, 200, 200); + const to = await pagePoint(page, 1300, 600); // covers a and b, not c + + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(to.x, to.y, { steps: 8 }); + await expect(page.getByTestId('marquee')).toBeVisible(); + await page.mouse.up(); + + await expect(title(page)).toHaveText('2 elements selected'); + await expect(page.getByTestId('marquee')).toHaveCount(0); + + // Clicking the empty page clears it + const empty = await pagePoint(page, 1800, 2500); + await page.mouse.click(empty.x, empty.y); + await expect(page.getByTestId('property-panel')).toHaveCount(0); + }); + + test('Delete removes all selected elements, but not while typing', async ({ page }) => { + await openEditor(page); + await elements(page).nth(0).click(); + await elements(page) + .nth(2) + .click({ modifiers: ['Shift'] }); + await expect(title(page)).toHaveText('2 elements selected'); + + await page.keyboard.press('Delete'); + + await expect(elements(page)).toHaveCount(1); + await expect(page.getByTestId('property-panel')).toHaveCount(0); + }); + + test('the Delete button in the panel removes the selection', async ({ page }) => { + await openEditor(page); + await elements(page).nth(0).click(); + await elements(page) + .nth(1) + .click({ modifiers: ['Shift'] }); + + await page.getByTestId('delete-selected-btn').click(); + + await expect(elements(page)).toHaveCount(1); + }); + + test('the select-multiple toggle lets plain clicks (taps) add to the selection', async ({ + page + }) => { + await openEditor(page); + await page.getByTestId('multi-select-toggle').click(); + await expect(page.getByTestId('multi-select-toggle')).toHaveAttribute('aria-pressed', 'true'); + + await elements(page).nth(0).click(); + await elements(page).nth(1).click(); + await expect(title(page)).toHaveText('2 elements selected'); + + // Switching the mode off keeps the selection + await page.getByTestId('multi-select-toggle').click(); + await expect(title(page)).toHaveText('2 elements selected'); + + // Now a plain click selects just one again + await elements(page).nth(2).click(); + await expect(title(page)).toContainText('Shape Properties'); + }); + + test('Backspace while typing in a text element does not delete the selection', async ({ + page + }) => { + await openEditor(page); + await page.getByTestId('tool-text').dragTo(page.getByTestId('document-canvas'), { + targetPosition: { x: 200, y: 330 } + }); + const textarea = page.locator('textarea'); + await textarea.fill('abc'); + await textarea.focus(); + + await page.keyboard.press('Backspace'); + + await expect(textarea).toHaveValue('ab'); + await expect(elements(page)).toHaveCount(4); + }); +}); + +test.describe('Grouping', () => { + test('a group is selected and moved as one until it is ungrouped', async ({ page }) => { + await openEditor(page); + await elements(page).nth(0).click(); + await elements(page) + .nth(1) + .click({ modifiers: ['Shift'] }); + await page.getByTestId('group-btn').click(); + await expect(title(page)).toHaveText('Group of 2 elements'); + await expect(page.getByTestId('ungroup-btn')).toBeVisible(); + await expect(page.getByTestId('group-btn')).toHaveCount(0); + + // Click the empty page, then one member: the whole group is selected + const empty = await pagePoint(page, 1800, 2500); + await page.mouse.click(empty.x, empty.y); + await expect(page.getByTestId('property-panel')).toHaveCount(0); + await elements(page).nth(1).click(); + await expect(title(page)).toHaveText('Group of 2 elements'); + + // Dragging one member moves both (the panel is open, so the page does not shift meanwhile) + await page.waitForTimeout(500); + const before = [ + await elements(page).nth(0).boundingBox(), + await elements(page).nth(1).boundingBox() + ]; + const from = { x: before[1]!.x + 20, y: before[1]!.y + 20 }; + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(from.x + 30, from.y + 50, { steps: 5 }); + await page.mouse.up(); + const after = [ + await elements(page).nth(0).boundingBox(), + await elements(page).nth(1).boundingBox() + ]; + for (const i of [0, 1]) { + expect(after[i]!.x - before[i]!.x).toBeCloseTo(30, 0); + expect(after[i]!.y - before[i]!.y).toBeCloseTo(50, 0); + } + + await page.getByTestId('ungroup-btn').click(); + await page.mouse.click(empty.x, empty.y); + await elements(page).nth(0).click(); + await expect(title(page)).toContainText('Shape Properties'); // alone again + }); + + test('Ctrl+G groups and Ctrl+Shift+G ungroups', async ({ page }) => { + await openEditor(page); + await elements(page).nth(0).click(); + await elements(page) + .nth(2) + .click({ modifiers: ['Shift'] }); + + await page.keyboard.press('Control+g'); + await expect(title(page)).toHaveText('Group of 2 elements'); + + await page.keyboard.press('Control+Shift+G'); + await expect(title(page)).toHaveText('2 elements selected'); + }); + + test('a group is kept when the document is saved and opened again', async ({ page }) => { + await openEditor(page); + await elements(page).nth(0).click(); + await elements(page) + .nth(1) + .click({ modifiers: ['Shift'] }); + await page.getByTestId('group-btn').click(); + await expect(page.getByTestId('save-status')).toHaveText('Saved', { timeout: 10000 }); + + await page.getByTestId('back-btn').click(); + await page.getByRole('button', { name: 'Edit' }).click(); + await elements(page).nth(0).click(); + + await expect(title(page)).toHaveText('Group of 2 elements'); + }); +}); + +test('a group that sticks out of the page boundaries is moved in as one, keeping its layout', async ({ + page +}) => { + const grouped = (id: string, x: number) => ({ ...shape(id, x, 300), groupId: 'g' }); + await seedDocument(page, { + ...doc, + id: 'sticks-out', + pages: { + p1: { + id: 'p1', + // the right boundary is at 1500, but the group spans 1200..1700 + boundaries: { horizontal: { start: 100, end: 1500 }, vertical: { start: 100, end: 3408 } }, + elements: { a: grouped('a', 1200), b: grouped('b', 1400) } + } + } + }); + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(elements(page)).toHaveCount(2); + await page.waitForTimeout(500); + + const [a, b] = [ + await elements(page).nth(0).boundingBox(), + await elements(page).nth(1).boundingBox() + ]; + const canvas = (await page.getByTestId('document-canvas').boundingBox())!; + const k = canvas.width / 2480; + expect((b!.x - a!.x) / k).toBeCloseTo(200, 0); // still 200 page pixels apart, not squeezed together + expect((b!.x + b!.width - canvas.x) / k).toBeCloseTo(1500, 0); // the group's right edge is at the boundary +}); + +test('dragging a corner of the selection box resizes everything in it proportionally', async ({ + page +}) => { + await openEditor(page); + await elements(page).nth(0).click(); + await elements(page) + .nth(1) + .click({ modifiers: ['Shift'] }); + await page.waitForTimeout(500); + + const before = [ + await elements(page).nth(0).boundingBox(), + await elements(page).nth(1).boundingBox() + ]; + const handle = (await page.getByTestId('group-resize-handle-se').boundingBox())!; + const from = { x: handle.x + handle.width / 2, y: handle.y + handle.height / 2 }; + // the selection box is a and b: 900 wide (300..1200) and 200 tall (300..500) + const box = { width: before[1]!.x + before[1]!.width - before[0]!.x, height: before[0]!.height }; + + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(from.x + box.width / 2, from.y + box.height / 2, { steps: 6 }); // 1.5 times as big + await page.mouse.up(); + + const after = [ + await elements(page).nth(0).boundingBox(), + await elements(page).nth(1).boundingBox() + ]; + expect(after[0]!.width / before[0]!.width).toBeCloseTo(1.5, 1); + expect(after[0]!.height / before[0]!.height).toBeCloseTo(1.5, 1); + expect(after[1]!.width / before[1]!.width).toBeCloseTo(1.5, 1); + // the top-left corner stayed, and the gap between the elements grew by the same factor + expect(after[0]!.x).toBeCloseTo(before[0]!.x, 0); + expect(after[1]!.x - after[0]!.x).toBeCloseTo((before[1]!.x - before[0]!.x) * 1.5, 0); + await expect(title(page)).toHaveText('2 elements selected'); // still selected +}); diff --git a/e2e/panel-and-rulers.test.ts b/e2e/panel-and-rulers.test.ts new file mode 100644 index 0000000..4908542 --- /dev/null +++ b/e2e/panel-and-rulers.test.ts @@ -0,0 +1,271 @@ +import { expect, test, type Page } from '@playwright/test'; +import { seedDocument } from './helpers'; + +const boundaries = { horizontal: { start: 100, end: 2380 }, vertical: { start: 100, end: 3408 } }; +const doc = { + id: 'panel', + schemaVersion: 1, + name: 'Panel', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { + id: 'p1', + boundaries, + elements: { + t: { + id: 't', + type: 'text', + pageId: 'p1', + zIndex: 0, + x: 300, + y: 300, + width: 800, + height: 200, + text: 'Hello', + fontFamily: 'Inter', + fontSize: 40, + fontWeight: '400', + fontStyle: 'normal', + color: '#000000' + }, + s: { + id: 's', + type: 'shape', + pageId: 'p1', + zIndex: 1, + x: 300, + y: 800, + width: 400, + height: 300, + shapeType: 'rectangle', + strokeColor: '#1d4ed8', + strokeWidth: 8 + } + } + } + } +}; + +async function select(page: Page, index: number) { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + await page.locator('[data-testid="document-canvas"] > .cursor-move').nth(index).click(); + await expect(page.getByTestId('property-panel')).toBeVisible(); +} + +/** The stored element, once autosave has written it */ +async function stored(page: Page, id: string) { + await expect(page.getByTestId('save-status')).toHaveText('Saved', { timeout: 10000 }); + return page.evaluate( + (elementId) => + new Promise>((resolve, reject) => { + const open = indexedDB.open('lienzo-db'); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const all = open.result.transaction('documents').objectStore('documents').getAll(); + all.onsuccess = () => resolve(all.result[0].pages.p1.elements[elementId]); + }; + }), + id + ); +} + +test.describe('Property panel', () => { + test('groups the text properties into Font, Paragraph and Colour', async ({ page }) => { + await select(page, 0); + const panel = page.getByTestId('property-panel'); + + for (const title of [ + 'Position and size', + 'Layering', + 'Copy and paste', + 'Font', + 'Paragraph', + 'Colour' + ]) { + await expect(panel.getByRole('heading', { name: title, exact: true })).toBeVisible(); + } + }); + + test('alignment, style, decoration and capitalisation are buttons that show what is on', async ({ + page + }) => { + await select(page, 0); + const align = (value: string) => page.getByTestId(`select-text-alignment-option-${value}`); + + await expect(align('left')).toHaveAttribute('aria-pressed', 'true'); + await align('center').click(); + await expect(align('center')).toHaveAttribute('aria-pressed', 'true'); + await expect(align('left')).toHaveAttribute('aria-pressed', 'false'); + + await page.getByTestId('select-font-style-option-italic').click(); + await page.getByTestId('select-text-decoration-option-underline').click(); + await page.getByTestId('select-text-transform-option-uppercase').click(); + + const element = await stored(page, 't'); + expect(element).toMatchObject({ + textAlign: 'center', + fontStyle: 'italic', + textDecoration: 'underline', + textTransform: 'uppercase' + }); + }); + + test('the buttons are named for assistive technology', async ({ page }) => { + await select(page, 0); + await expect(page.getByRole('group', { name: 'Alignment' })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Underline', exact: true })).toHaveAttribute( + 'aria-pressed', + 'false' + ); + }); + + test('a shape has Shape, Stroke and Fill sections, with the stroke style as buttons', async ({ + page + }) => { + await select(page, 1); + const panel = page.getByTestId('property-panel'); + for (const title of ['Shape', 'Stroke', 'Fill']) { + await expect(panel.getByRole('heading', { name: title, exact: true })).toBeVisible(); + } + + await page.getByTestId('select-stroke-style-option-dashed').click(); + expect(await stored(page, 's')).toMatchObject({ strokeStyle: 'dashed' }); + }); +}); + +test.describe('Rulers', () => { + test('the markers are labelled and report their value', async ({ page }) => { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + + const start = page.getByTestId('ruler-marker-start').first(); + await expect(start).toHaveAttribute('aria-label', 'Left margin'); + await expect(start).toHaveAttribute('aria-valuenow', '100'); + await expect(page.getByTestId('ruler-marker-end').first()).toHaveAttribute( + 'aria-label', + 'Right margin' + ); + await expect(page.getByTestId('ruler-marker-start').nth(1)).toHaveAttribute( + 'aria-label', + 'Top margin' + ); + }); + + test('the arrow keys move a marker, and its value shows while it is focused', async ({ + page + }) => { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + const start = page.getByTestId('ruler-marker-start').first(); + + await start.focus(); + await expect(page.getByTestId('ruler-tooltip')).toHaveText('Left margin 100'); + await page.keyboard.press('ArrowRight'); + await expect(start).toHaveAttribute('aria-valuenow', '110'); + await page.keyboard.press('Shift+ArrowRight'); + await expect(start).toHaveAttribute('aria-valuenow', '160'); + await expect(page.getByTestId('ruler-tooltip')).toHaveText('Left margin 160'); + await page.keyboard.press('ArrowLeft'); + await expect(start).toHaveAttribute('aria-valuenow', '150'); + + await start.blur(); + await expect(page.getByTestId('ruler-tooltip')).toHaveCount(0); + }); + + test('dragging a marker shows its value, and it goes away on release', async ({ page }) => { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + const start = page.getByTestId('ruler-marker-start').first(); + const box = (await start.boundingBox())!; + + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + await page.mouse.move(box.x + 60, box.y + box.height / 2, { steps: 6 }); + await expect(page.getByTestId('ruler-tooltip')).toContainText('Left margin'); + const value = Number(await start.getAttribute('aria-valuenow')); + expect(value).toBeGreaterThan(100); + await page.mouse.up(); + + await expect(page.getByTestId('ruler-tooltip')).toHaveCount(0); + await expect(start).toHaveAttribute('aria-valuenow', String(value)); + }); + + test('the markers keep their minimum distance from each other', async ({ page }) => { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + const end = page.getByTestId('ruler-marker-end').first(); + await end.focus(); + + await page.keyboard.press('Home'); // not a ruler key: nothing happens + for (let i = 0; i < 60; i++) await page.keyboard.press('Shift+ArrowLeft'); + + // the start marker is at 100, so the end cannot go below 150 + await expect(end).toHaveAttribute('aria-valuenow', '150'); + }); +}); + +test.describe('Property panel on a phone', () => { + test.use({ viewport: { width: 390, height: 844 } }); + + test('is a bottom sheet that shows only its title until it is opened', async ({ page }) => { + await select(page, 0); + const panel = page.getByTestId('property-panel'); + const toggle = page.getByTestId('property-panel-toggle'); + + await expect(page.getByTestId('property-panel-title')).toHaveText('Text Properties'); + await expect(toggle).toHaveAttribute('aria-expanded', 'false'); + await expect(panel.getByRole('heading', { name: 'Font', exact: true })).toBeHidden(); + const closed = (await panel.boundingBox())!; + expect(closed.height).toBeLessThan(120); // a strip, not a wall over the page + expect(closed.y + closed.height).toBeCloseTo(844 - 64, 0); // sits right above the 64px tool bar + + await toggle.click(); + await expect(toggle).toHaveAttribute('aria-expanded', 'true'); + await expect(panel.getByRole('heading', { name: 'Font', exact: true })).toBeVisible(); + const open = (await panel.boundingBox())!; + expect(open.height).toBeGreaterThan(closed.height); + expect(open.height).toBeLessThanOrEqual(844 * 0.55 + 1); // never more than 55% of the screen + + await toggle.click(); + await expect(panel.getByRole('heading', { name: 'Font', exact: true })).toBeHidden(); + }); + + test('each group is a row of its own, and its controls scroll along it', async ({ page }) => { + await select(page, 0); + await page.getByTestId('property-panel-toggle').click(); + const panel = page.getByTestId('property-panel'); + + // Paragraph holds three controls, side by side in one row + const row = panel.locator('section', { hasText: 'Paragraph' }).locator('> div'); + const boxes = await Promise.all( + ['select-text-alignment', 'select-text-decoration', 'select-text-transform'].map( + async (id) => (await page.getByTestId(id).boundingBox())! + ) + ); + expect(boxes[0].y).toBeCloseTo(boxes[1].y, 0); + expect(boxes[1].y).toBeCloseTo(boxes[2].y, 0); + expect(boxes[1].x).toBeGreaterThan(boxes[0].x); + // more controls than the screen is wide: the row scrolls, the page does not + expect(await row.evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true); + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth - document.documentElement.clientWidth + ); + expect(overflow).toBeLessThanOrEqual(0); + }); + + test('a selection of several elements gets the same sheet', async ({ page }) => { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + await page.getByTestId('multi-select-bar-btn').click(); // the header has no room for it on a phone + const elements = page.locator('[data-testid="document-canvas"] > .cursor-move'); + await elements.nth(0).click(); + await elements.nth(1).click(); + + await expect(page.getByTestId('property-panel-title')).toHaveText('2 elements selected'); + await expect(page.getByTestId('group-btn')).toBeHidden(); + await page.getByTestId('property-panel-toggle').click(); + await expect(page.getByTestId('group-btn')).toBeVisible(); + }); +}); diff --git a/e2e/pdf-export.test.ts b/e2e/pdf-export.test.ts new file mode 100644 index 0000000..492a716 --- /dev/null +++ b/e2e/pdf-export.test.ts @@ -0,0 +1,177 @@ +import { expect, test } from '@playwright/test'; +import fs from 'node:fs'; +import * as pdfjs from 'pdfjs-dist/legacy/build/pdf.mjs'; +import { seedDocument } from './helpers'; + +// 2x2 PNG, red and blue +const PNG = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAE0lEQVR4nGO4o6ammvyaAYiBLAAkaAU3/SddMwAAAABJRU5ErkJggg=='; + +const base = (id: string, extra: object) => ({ + id, + pageId: 'p1', + x: 150, + y: 150, + width: 1100, + height: 200, + zIndex: 0, + ...extra +}); +const text = (id: string, extra: object) => + base(id, { + type: 'text', + text: 'The quick brown fox jumps over the lazy dog', + fontFamily: 'Inter', + fontSize: 34, + fontWeight: '400', + fontStyle: 'normal', + color: '#111111', + ...extra + }); +const shape = (id: string, extra: object) => + base(id, { + type: 'shape', + strokeColor: '#1d4ed8', + strokeWidth: 8, + width: 300, + height: 200, + ...extra + }); + +const doc = { + id: 'vector', + schemaVersion: 1, + name: 'Vector', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { + id: 'p1', + boundaries: { horizontal: { start: 100, end: 2380 }, vertical: { start: 100, end: 3408 } }, + elements: { + t1: text('t1', { text: 'Invoice #0042', fontWeight: '800', fontSize: 60, width: 1500 }), + t2: text('t2', { y: 330, fontFamily: 'Merriweather', fontWeight: '300' }), + t3: text('t3', { + y: 520, + fontFamily: 'Lato', + fontWeight: '700', + fontStyle: 'italic', + textAlign: 'center', + backgroundColor: '#ffe08a', + backgroundOpacity: 0.6 + }), + t4: text('t4', { + y: 710, + fontFamily: 'Poppins', + fontWeight: '600', + text: 'RΓ©sumΓ© uppercase', + textTransform: 'uppercase', + textDecoration: 'underline' + }), + t5: text('t5', { + y: 900, + fontFamily: 'Playfair Display', + fontWeight: '900', + textAlign: 'justify', + height: 300, + text: 'Justified text wraps over several lines so that the browser decides where each line breaks. '.repeat( + 3 + ) + }), + t6: text('t6', { y: 1250, fontFamily: 'Georgia', text: 'System font' }), + s1: shape('s1', { + x: 1300, + y: 150, + shapeType: 'rectangle', + cornerRadius: 20, + strokeStyle: 'dashed', + fillColor: '#bfdbfe', + fillOpacity: 0.5 + }), + s2: shape('s2', { + x: 1300, + y: 450, + shapeType: 'ellipse', + fillColor: '#fecaca', + fillOpacity: 1 + }), + s3: shape('s3', { x: 1300, y: 750, shapeType: 'triangle', rotation: 30 }), + s4: shape('s4', { x: 1300, y: 1050, shapeType: 'arrow-right', fillColor: '#bbf7d0' }), + s5: shape('s5', { x: 1300, y: 1350, shapeType: 'line-horizontal', height: 20 }), + i1: base('i1', { + type: 'image', + y: 1500, + x: 150, + src: PNG, + alt: 'red', + objectFit: 'fill', + width: 400, + height: 300, + borderWidth: 6, + borderColor: '#111111', + borderRadius: 10 + }) + } + } + } +}; + +test('exports a PDF with real text, vector shapes and a single image', async ({ page }) => { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(page.locator('textarea').first()).toBeVisible(); + + await page.getByTestId('export-btn').click(); + const download = page.waitForEvent('download'); + await page.getByRole('dialog').getByRole('button', { name: 'Export PDF' }).click(); + const file = await download; + const path = (await file.path())!; + if (process.env.KEEP_PDF) fs.copyFileSync(path, process.env.KEEP_PDF); + + const pdf = await pdfjs.getDocument({ + data: new Uint8Array(fs.readFileSync(path)), + standardFontDataUrl: 'node_modules/pdfjs-dist/standard_fonts/' + }).promise; + expect(pdf.numPages).toBe(1); + const pdfPage = await pdf.getPage(1); + const [, , width, height] = pdfPage.view; + expect(width).toBeCloseTo(595.2, 0); + expect(height).toBeCloseTo(841.9, 0); + + // Real, selectable text + const content = await pdfPage.getTextContent(); + const items = content.items.filter( + (i): i is (typeof content.items)[number] & { str: string } => 'str' in i && !!i.str.trim() + ); + const all = items.map((i) => i.str).join(' '); + expect(all).toContain('Invoice #0042'); + expect(all).toContain('RΓ‰SUMΓ‰ UPPERCASE'); // text-transform applied to the text itself + expect(all).toContain('System font'); + expect(new Set(items.map((i) => i.fontName)).size).toBeGreaterThanOrEqual(5); // one font per family/weight + + // The headline sits where the editor draws it: box left + 8px padding at the display scale + const headline = items.find((i) => i.str === 'Invoice #0042')!; + const pt = 595.2 / 2480; + expect(headline.transform[4]).toBeCloseTo(150 * pt + (8 / 0.35) * pt, 0); + + // Only the picture is an image, everything else is vector + const ops = await pdfPage.getOperatorList(); + expect(ops.fnArray.filter((fn) => fn === pdfjs.OPS.paintImageXObject)).toHaveLength(1); +}); + +test('tells the user when an image cannot be included, and still exports the rest', async ({ + page +}) => { + const broken = JSON.parse(JSON.stringify(doc)); + broken.pages.p1.elements.i1.src = 'data:image/png;base64,AAAA'; // not a real image + await seedDocument(page, broken); + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(page.locator('textarea').first()).toBeVisible(); + + await page.getByTestId('export-btn').click(); + const download = page.waitForEvent('download'); + await page.getByRole('dialog').getByRole('button', { name: 'Export PDF' }).click(); + await download; + + await expect(page.getByTestId('export-warning')).toContainText('could not be included'); +}); diff --git a/e2e/pdf-import.test.ts b/e2e/pdf-import.test.ts new file mode 100644 index 0000000..3a171f5 --- /dev/null +++ b/e2e/pdf-import.test.ts @@ -0,0 +1,93 @@ +import { expect, test, type Page } from '@playwright/test'; +import { seedDocument } from './helpers'; + +const doc = { + id: 'pdf-doc', + schemaVersion: 1, + name: 'PDF Resume', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { + id: 'p1', + boundaries: { horizontal: { start: 100, end: 700 }, vertical: { start: 100, end: 1000 } }, + elements: { + t1: { + id: 't1', + type: 'text', + pageId: 'p1', + zIndex: 0, + x: 120, + y: 140, + width: 400, + height: 80, + text: 'Editable headline', + fontFamily: 'Inter', + fontSize: 24, + fontWeight: '400', + fontStyle: 'normal', + color: '#000000' + } + } + } + } +}; + +/** Open the seeded document in the editor and export it as a PDF. Returns the downloaded file path. */ +async function exportPdf(page: Page): Promise { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(page.locator('textarea')).toHaveValue('Editable headline'); + + await page.getByTestId('export-btn').click(); + const download = page.waitForEvent('download'); + await page.getByRole('dialog').getByRole('button', { name: 'Export PDF' }).click(); + + const file = await download; + await expect(page.getByTestId('export-done')).toContainText('PDF Resume.pdf was saved'); + await page.getByRole('dialog').getByRole('button', { name: 'Close' }).click(); + expect(file.suggestedFilename()).toBe('PDF Resume.pdf'); + return (await file.path())!; +} + +test.describe('PDF import', () => { + test('a PDF exported from Lienzo can be imported on the Documents page', async ({ page }) => { + const pdfPath = await exportPdf(page); + + await page.getByTestId('back-btn').click(); + await expect(page).toHaveURL(/\/documents/); + await page.getByTestId('import-input').setInputFiles(pdfPath); + + // It is the same document id, so the user decides what to do + await expect(page.getByTestId('conflict-list')).toContainText('PDF Resume'); + await page.getByTestId('import-keep-both-btn').click(); + + await expect(page.getByTestId('import-notice')).toContainText('Imported 1 document'); + await expect(page.getByRole('heading', { name: 'PDF Resume (imported)' })).toBeVisible(); + }); + + test('a PDF exported from Lienzo can be imported into the editor, fully editable', async ({ + page + }) => { + const pdfPath = await exportPdf(page); + + await page.goto('/canvas'); + + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive // a fresh, empty canvas + await page.getByTestId('canvas-import-input').setInputFiles(pdfPath); + + await expect(page.locator('textarea')).toHaveValue('Editable headline'); + }); + + test('a PDF that did not come from Lienzo is rejected with an explanation', async ({ page }) => { + await page.goto('/canvas'); + await page.waitForLoadState('networkidle'); // clicks only work once the page is interactive + await page.getByTestId('canvas-import-input').setInputFiles({ + name: 'plain.pdf', + mimeType: 'application/pdf', + buffer: Buffer.from('%PDF-1.4\n%%EOF') + }); + + await expect(page.getByTestId('canvas-import-error')).toContainText('plain.pdf'); + }); +}); diff --git a/e2e/seo.test.ts b/e2e/seo.test.ts index 003cf38..04ef09d 100644 --- a/e2e/seo.test.ts +++ b/e2e/seo.test.ts @@ -26,9 +26,10 @@ test.describe('SEO', () => { const jsonLd = JSON.parse( (await page.locator('script[type="application/ld+json"]').textContent()) ?? '{}' ); - expect(jsonLd['@type']).toBe('WebApplication'); - expect(jsonLd.url).toBe(SITE); - expect(jsonLd.author).toMatchObject({ + const app = jsonLd['@graph'][0]; + expect(app['@type']).toBe('WebApplication'); + expect(app.url).toBe(SITE); + expect(app.author).toMatchObject({ '@type': 'Person', name: 'Chizoba Jude Ojini', url: 'https://judeojini.com' @@ -43,7 +44,7 @@ test.describe('SEO', () => { }); } - test('sitemap lists only the landing page', async ({ request }) => { + test('sitemap lists the landing page, not the private pages', async ({ request }) => { const res = await request.get('/sitemap.xml'); expect(res.ok()).toBe(true); const body = await res.text(); @@ -51,6 +52,48 @@ test.describe('SEO', () => { expect(body).not.toContain('/canvas'); }); + test('every template has its own indexable page, listed in the sitemap', async ({ + page, + request + }) => { + const body = await (await request.get('/sitemap.xml')).text(); + expect(body).toContain(`${SITE}/templates`); + expect(body).toContain(`${SITE}/templates/resume`); + const listed = body.match(/\/templates\/[a-z-]+ n['@type'])).toEqual([ + 'CreativeWork', + 'BreadcrumbList' + ]); + + // links in the prerendered page are absolute: relative ones pointed at /templates/templates + const hrefs = await page + .locator('main a') + .evaluateAll((all) => all.map((a) => a.getAttribute('href'))); + expect(hrefs.length).toBeGreaterThan(0); + expect(hrefs.every((h) => h?.startsWith('/'))).toBe(true); + + await page.getByTestId('use-this-template').click(); + await expect(page).toHaveURL(/\/canvas$/); + await expect(page.getByTestId('document-title')).toHaveText('Invoice'); + }); + + test('an unknown template is a 404', async ({ request }) => { + expect((await request.get('/templates/not-a-template')).status()).toBe(404); + }); + test('robots.txt points to the sitemap', async ({ request }) => { const res = await request.get('/robots.txt'); expect(await res.text()).toContain(`Sitemap: ${SITE}/sitemap.xml`); diff --git a/e2e/storage.test.ts b/e2e/storage.test.ts new file mode 100644 index 0000000..3a33c4f --- /dev/null +++ b/e2e/storage.test.ts @@ -0,0 +1,39 @@ +import { expect, test } from '@playwright/test'; +import { seedDocument } from './helpers'; + +// A document saved by an older app version (before schemaVersion existed) +const legacyDocument = { + id: 'legacy-1', + name: 'Legacy Resume', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { + id: 'p1', + boundaries: { horizontal: { start: 100, end: 700 }, vertical: { start: 100, end: 1000 } }, + elements: { + t1: { + id: 't1', + type: 'text', + pageId: 'p1', + zIndex: 0, + x: 120, + y: 140, + width: 300, + height: 60, + text: 'Hello from v1', + fontFamily: 'Inter', + fontSize: 24, + fontWeight: '400', + fontStyle: 'normal', + color: '#000000' + } + } + } + } +}; + +test('documents saved before schema versioning still appear in the list', async ({ page }) => { + await seedDocument(page, legacyDocument); + await expect(page.getByText('Legacy Resume')).toBeVisible(); +}); diff --git a/e2e/templates.test.ts b/e2e/templates.test.ts new file mode 100644 index 0000000..b03229a --- /dev/null +++ b/e2e/templates.test.ts @@ -0,0 +1,110 @@ +import { expect, test } from '@playwright/test'; + +test.describe('Template gallery', () => { + test('lists every template, and the blank document first', async ({ page }) => { + await page.goto('/templates'); + await expect(page.getByRole('heading', { level: 1 })).toHaveText('Start from a template'); + await expect(page.getByTestId('template-blank')).toBeVisible(); + expect(await page.getByTestId('template-card').count()).toBeGreaterThanOrEqual(22); + }); + + test('filters by category and by search', async ({ page }) => { + await page.goto('/templates'); + await page.waitForLoadState('networkidle'); + const cards = page.getByTestId('template-card'); + const all = await cards.count(); + + await page.getByTestId('category-Events').click(); + await expect(page.getByTestId('category-Events')).toHaveAttribute('aria-pressed', 'true'); + const events = await cards.count(); + expect(events).toBeGreaterThan(0); + expect(events).toBeLessThan(all); + await expect(page.getByTestId('use-resume')).toHaveCount(0); + + await page.getByTestId('category-All').click(); + await page.getByLabel('Search templates').fill('invoice'); + await expect(cards).toHaveCount(1); + await expect(page.getByTestId('use-invoice')).toBeVisible(); + + await page.getByLabel('Search templates').fill('zzzz'); + await expect(cards).toHaveCount(0); + await expect(page.getByRole('status')).toContainText('No templates match'); + }); + + test('a template opens in the editor as its own editable document', async ({ page }) => { + await page.goto('/templates'); + await page.waitForLoadState('networkidle'); + await page.getByTestId('use-resume').click(); + + await expect(page).toHaveURL(/\/canvas$/); + await expect(page.getByTestId('document-title')).toHaveText('Resume'); + const texts = page.locator('textarea'); + await expect(texts.first()).toBeVisible(); + expect(await texts.count()).toBeGreaterThan(8); + const values = await texts.evaluateAll((all) => + all.map((t) => (t as HTMLTextAreaElement).value) + ); + expect(values).toContain('Alex Morgan'); + }); + + test('each card links to the template’s own page', async ({ page }) => { + await page.goto('/templates'); + await page.getByRole('link', { name: 'Resume', exact: true }).click(); + await expect(page).toHaveURL(/\/templates\/resume$/); + await expect(page.getByRole('heading', { level: 1 })).toHaveText('Resume template'); + await expect(page.getByRole('navigation', { name: 'Breadcrumb' })).toContainText('Templates'); + }); + + test('the blank document starts empty', async ({ page }) => { + await page.goto('/templates'); + await page.waitForLoadState('networkidle'); + await page.getByTestId('template-blank').click(); + + await expect(page).toHaveURL(/\/canvas$/); + await expect(page.locator('textarea')).toHaveCount(0); + }); + + test('the home page shows a few of them, and links to all', async ({ page, request }) => { + await page.goto('/'); + await page.waitForLoadState('networkidle'); + await expect(page.getByRole('heading', { name: 'Start from a template' })).toBeVisible(); + await expect(page.getByTestId('featured-templates').getByRole('listitem')).toHaveCount(6); + await expect(page.getByTestId('browse-templates')).toHaveAttribute('href', '/templates'); + + const sitemap = await (await request.get('/sitemap.xml')).text(); + expect(sitemap).toContain('/templates'); + }); + + test('a template on the home page opens in the editor', async ({ page }) => { + await page.goto('/'); + await page.waitForLoadState('networkidle'); + await page.getByTestId('featured-invoice').click(); + + await expect(page).toHaveURL(/\/canvas$/); + await expect(page.getByTestId('document-title')).toHaveText('Invoice'); + }); + + test('fits a phone: no sideways scroll, and the previews stay white in the dark theme', async ({ + browser + }) => { + const context = await browser.newContext({ + viewport: { width: 375, height: 812 }, + colorScheme: 'dark' + }); + const page = await context.newPage(); + await page.goto('/templates'); + await page.waitForLoadState('networkidle'); + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth - document.documentElement.clientWidth + ); + expect(overflow).toBeLessThanOrEqual(0); + const paper = await page + .getByTestId('template-card') + .nth(1) + .locator('[aria-hidden="true"]') + .first() + .evaluate((el) => getComputedStyle(el).backgroundColor); + expect(paper).toBe('rgb(255, 255, 255)'); + await context.close(); + }); +}); diff --git a/e2e/theme.test.ts b/e2e/theme.test.ts new file mode 100644 index 0000000..9d5679c --- /dev/null +++ b/e2e/theme.test.ts @@ -0,0 +1,115 @@ +import { expect, test } from '@playwright/test'; +import { seedDocument } from './helpers'; + +const isDark = (page: import('@playwright/test').Page) => + page.evaluate(() => document.documentElement.classList.contains('dark')); + +test.describe('Theme', () => { + test('follows the system setting by default', async ({ browser }) => { + for (const [scheme, dark] of [ + ['dark', true], + ['light', false] + ] as const) { + const context = await browser.newContext({ colorScheme: scheme }); + const page = await context.newPage(); + await page.goto('/'); + expect(await isDark(page)).toBe(dark); + await context.close(); + } + }); + + test('one button cycles System, Light, Dark, and the choice survives a reload', async ({ + page + }) => { + await page.goto('/'); + await page.waitForLoadState('networkidle'); + const toggle = page.getByTestId('theme-toggle'); + await expect(toggle).toHaveAttribute('data-theme-preference', 'system'); + + await toggle.click(); + await expect(toggle).toHaveAttribute('data-theme-preference', 'light'); + expect(await isDark(page)).toBe(false); + + await toggle.click(); + await expect(toggle).toHaveAttribute('data-theme-preference', 'dark'); + expect(await isDark(page)).toBe(true); + + await page.reload(); + expect(await isDark(page)).toBe(true); // applied before the first paint, not after hydration + await expect(page.getByTestId('theme-toggle')).toHaveAttribute('data-theme-preference', 'dark'); + + await page.getByTestId('theme-toggle').click(); + await expect(page.getByTestId('theme-toggle')).toHaveAttribute( + 'data-theme-preference', + 'system' + ); + }); + + test('System follows the device, live', async ({ browser }) => { + const context = await browser.newContext({ colorScheme: 'dark' }); + await context.addInitScript(() => localStorage.setItem('lienzo-theme', 'light')); + const page = await context.newPage(); + await page.goto('/'); + await page.waitForLoadState('networkidle'); + expect(await isDark(page)).toBe(false); // the saved choice wins + + const toggle = page.getByTestId('theme-toggle'); + await toggle.click(); // light -> dark + await toggle.click(); // dark -> system + await expect(toggle).toHaveAttribute('data-theme-preference', 'system'); + expect(await isDark(page)).toBe(true); // the device is dark + + await page.emulateMedia({ colorScheme: 'light' }); + await expect.poll(() => isDark(page)).toBe(false); // and it keeps following it + await context.close(); + }); + + test('a saved choice wins over the system setting', async ({ browser }) => { + const context = await browser.newContext({ colorScheme: 'dark' }); + await context.addInitScript(() => localStorage.setItem('lienzo-theme', 'light')); + const page = await context.newPage(); + + await page.goto('/'); + + expect(await isDark(page)).toBe(false); + await context.close(); + }); + + test('the theme is on every page, and the page you design stays white in the dark theme', async ({ + browser + }) => { + const context = await browser.newContext({ colorScheme: 'dark' }); + const page = await context.newPage(); + await seedDocument(page, { + id: 'theme', + schemaVersion: 1, + name: 'Theme', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { + id: 'p1', + boundaries: { + horizontal: { start: 100, end: 2380 }, + vertical: { start: 100, end: 3408 } + }, + elements: {} + } + } + }); + await page.waitForLoadState('networkidle'); + await expect(page.getByTestId('theme-toggle')).toBeVisible(); // documents page + + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(page.getByTestId('theme-toggle')).toBeVisible(); // editor + expect(await isDark(page)).toBe(true); + + const colours = await page.getByTestId('document-canvas').evaluate((el) => { + const style = getComputedStyle(el); + return { paper: style.backgroundColor, app: getComputedStyle(document.body).color }; + }); + expect(colours.paper).toBe('rgb(255, 255, 255)'); + expect(colours.app).not.toBe('rgb(36, 36, 36)'); // the interface itself is light on dark + await context.close(); + }); +}); diff --git a/e2e/tool-palette.test.ts b/e2e/tool-palette.test.ts new file mode 100644 index 0000000..fd5842a --- /dev/null +++ b/e2e/tool-palette.test.ts @@ -0,0 +1,193 @@ +import { expect, test, type Page } from '@playwright/test'; +import { seedDocument } from './helpers'; + +const boundaries = { horizontal: { start: 100, end: 2380 }, vertical: { start: 100, end: 3408 } }; +const doc = { + id: 'tools', + schemaVersion: 1, + name: 'Tools', + createdAt: 1, + updatedAt: 2, + pages: { + p1: { id: 'p1', boundaries, elements: {} }, + p2: { id: 'p2', boundaries, elements: {} } + } +}; + +const onPage = (page: Page, id: string) => + page.locator(`[data-page-id="${id}"] [data-testid="document-canvas"] > .cursor-move`); + +async function open(page: Page) { + await seedDocument(page, doc); + await page.getByRole('button', { name: 'Edit' }).click(); + await expect(page.getByTestId('document-canvas')).toHaveCount(2); +} + +test.describe('Tool palette', () => { + test('each tool has an icon and a name, and is a real button', async ({ page }) => { + await open(page); + for (const name of ['Text', 'Shape', 'Image']) { + await expect(page.getByTestId('toolbar').getByRole('button', { name })).toBeVisible(); + } + await expect(page.getByRole('navigation', { name: 'Add to page' })).toBeVisible(); + }); + + test('clicking a tool adds the element to the page that was last clicked', async ({ page }) => { + await open(page); + await page.locator('[data-page-id="p2"] [data-testid="document-canvas"]').click(); + + await page.getByTestId('toolbar').getByRole('button', { name: 'Shape' }).click(); + + await expect(onPage(page, 'p2')).toHaveCount(1); + await expect(onPage(page, 'p1')).toHaveCount(0); + await expect(page.getByTestId('property-panel-title')).toHaveText('Shape Properties'); // selected + }); + + test('each added element sits a little lower, so they do not hide each other', async ({ + page + }) => { + await open(page); + const text = page.getByTestId('toolbar').getByRole('button', { name: 'Text' }); + + await text.click(); + await text.click(); + await text.click(); + + await expect(onPage(page, 'p1')).toHaveCount(3); + const tops = await onPage(page, 'p1').evaluateAll((els) => + els.map((el) => el.getBoundingClientRect().top).sort((a, b) => a - b) + ); + expect(tops[1]).toBeGreaterThan(tops[0] + 5); + expect(tops[2]).toBeGreaterThan(tops[1] + 5); + }); + + test('the keyboard can add a tool, and dragging still works', async ({ page }) => { + await open(page); + await page.getByTestId('toolbar').getByRole('button', { name: 'Text' }).focus(); + await page.keyboard.press('Enter'); + await expect(onPage(page, 'p1')).toHaveCount(1); + + await page + .getByTestId('tool-shape') + .dragTo(page.locator('[data-page-id="p2"] [data-testid="document-canvas"]'), { + targetPosition: { x: 100, y: 100 } + }); + await expect(onPage(page, 'p2')).toHaveCount(1); + }); +}); + +test.describe('Tool bar on a phone', () => { + test.use({ viewport: { width: 390, height: 844 }, hasTouch: true }); + + test('is a bar along the bottom with the tools, Select and Page', async ({ page }) => { + await open(page); + const bar = page.getByRole('navigation', { name: 'Add to page' }); + const box = (await bar.boundingBox())!; + + expect(box.y + box.height).toBeCloseTo(844, 0); + expect(box.width).toBeCloseTo(390, 0); + for (const name of ['Text', 'Shape', 'Image', 'Select', 'Page']) { + const button = bar.getByRole('button', { name }); + await expect(button).toBeVisible(); + expect((await button.boundingBox())!.height).toBeGreaterThanOrEqual(44); // a comfortable target + } + }); + + test('tapping a tool adds it, Page adds a page and Select switches to multiple selection', async ({ + page + }) => { + await open(page); + const bar = page.getByRole('navigation', { name: 'Add to page' }); + + await bar.getByRole('button', { name: 'Text' }).tap(); + await expect(onPage(page, 'p1')).toHaveCount(1); + + await bar.getByTestId('add-page-bar-btn').tap(); + await expect(page.getByTestId('document-canvas')).toHaveCount(3); + + const select = bar.getByTestId('multi-select-bar-btn'); + await expect(select).toHaveAttribute('aria-pressed', 'false'); + await select.tap(); + await expect(select).toHaveAttribute('aria-pressed', 'true'); + }); + + test('the header keeps to one row: Back, the title and Export, with the rest in a menu', async ({ + page + }) => { + await open(page); + const header = page.locator('header'); + await expect(header.getByTestId('document-title')).toBeVisible(); + await expect(header.getByTestId('export-btn-phone')).toBeVisible(); + await expect(header.getByTestId('add-page-btn')).toBeHidden(); // in the bar instead + expect((await header.boundingBox())!.height).toBeLessThan(90); + + const menuButton = header.getByTestId('more-menu-btn'); + await menuButton.click(); + const menu = page.getByRole('menu', { name: 'More actions' }); + for (const name of ['Paste', 'Import', 'Save']) { + await expect(menu.getByRole('menuitem', { name })).toBeVisible(); + } + await expect(menuButton).toHaveAttribute('aria-expanded', 'true'); + + await page.keyboard.press('Escape'); + await expect(menu).toHaveCount(0); + }); + + test('the menu switches the theme and closes when you tap elsewhere', async ({ page }) => { + await open(page); + await page.getByTestId('more-menu-btn').click(); + const themeItem = page.getByTestId('menu-theme'); + await expect(themeItem).toHaveAttribute('aria-checked', 'false'); + + await themeItem.click(); + expect(await page.evaluate(() => document.documentElement.classList.contains('dark'))).toBe( + true + ); + + await page.getByTestId('more-menu-btn').click(); + await page + .locator('[data-testid="document-canvas"]') + .first() + .click({ position: { x: 20, y: 200 } }); + await expect(page.getByRole('menu')).toHaveCount(0); + }); + + test('the property sheet sits above the tool bar, not behind it', async ({ page }) => { + await open(page); + await page + .getByRole('navigation', { name: 'Add to page' }) + .getByRole('button', { name: 'Text' }) + .tap(); + const sheet = (await page.getByTestId('property-panel').boundingBox())!; + const bar = (await page.getByRole('navigation', { name: 'Add to page' }).boundingBox())!; + + expect(sheet.y + sheet.height).toBeLessThanOrEqual(bar.y + 1); + }); +}); + +test.describe('Documents page on a phone', () => { + test.use({ viewport: { width: 390, height: 844 } }); + + test('the header fits without sideways scrolling, with the main action and the file actions in reach', async ({ + page + }) => { + await page.goto('/documents'); + await page.waitForLoadState('networkidle'); + + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth - document.documentElement.clientWidth + ); + expect(overflow).toBeLessThanOrEqual(0); + await expect(page.getByTestId('new-document-btn')).toBeVisible(); + await expect(page.getByRole('searchbox', { name: 'Search documents' })).toBeVisible(); + // icon buttons keep their names for screen readers and are comfortable to tap + for (const id of ['import-btn', 'export-all-btn']) { + const button = page.getByTestId(id); + await expect(button).toBeVisible(); + const box = (await button.boundingBox())!; + expect(box.width).toBeGreaterThanOrEqual(44); + expect(box.height).toBeGreaterThanOrEqual(44); + } + await expect(page.getByRole('button', { name: 'Import' })).toBeVisible(); + }); +}); diff --git a/package.json b/package.json index 2fe9737..16c14d2 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,10 @@ { "name": "lienzo", "private": true, - "version": "1.1.0", + "version": "2.0.0", "author": { "name": "Chizoba Jude Ojini", - "email": "contact@judeojini.com", + "email": "contact@deityhub.com", "url": "https://judeojini.com" }, "license": "GPL-3.0-only", @@ -14,8 +14,8 @@ }, "type": "module", "scripts": { - "dev": "vite dev", - "build": "vite build", + "dev": "svelte-kit sync && vite dev", + "build": "svelte-kit sync && vite build", "preview": "vite preview", "prepare": "svelte-kit sync || echo ''", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", @@ -23,13 +23,17 @@ "format": "prettier --write .", "format:check": "prettier --check .", "lint": "prettier --check . && eslint .", - "test:unit": "vitest", - "test:unit:run": "vitest --run", - "test:unit:coverage": "vitest --run --coverage", + "test:unit": "svelte-kit sync && vitest", + "test:unit:run": "svelte-kit sync && vitest --run", + "test:unit:coverage": "svelte-kit sync && vitest --run --coverage", "test": "yarn test:unit:run && yarn test:e2e", - "test:e2e": "playwright test" + "brand:assets": "node scripts/generate-brand-assets.mjs", + "test:e2e": "playwright test", + "notices": "node scripts/generate-notices.mjs", + "docs:screenshots": "yarn build && node scripts/generate-screenshots.mjs" }, "devDependencies": { + "@cantoo/pdf-lib": "^2.11.1", "@eslint/compat": "^1.2.5", "@eslint/js": "^9.22.0", "@lucide/svelte": "^0.548.0", @@ -47,7 +51,7 @@ "eslint-plugin-svelte": "^3.0.0", "globals": "^16.0.0", "html-to-image": "^1.11.13", - "jspdf": "^3.0.3", + "pdfjs-dist": "^6.5.438", "playwright": "^1.53.0", "prettier": "^3.4.2", "prettier-plugin-svelte": "^3.3.3", @@ -60,5 +64,8 @@ "vite": "^7.0.4", "vitest": "^3.2.3", "vitest-browser-svelte": "^0.1.0" + }, + "dependencies": { + "@cantoo/fontkit": "^2.0.12" } } diff --git a/scripts/brand-assets.spec.ts b/scripts/brand-assets.spec.ts new file mode 100644 index 0000000..ccc3c99 --- /dev/null +++ b/scripts/brand-assets.spec.ts @@ -0,0 +1,86 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +// Guards the generated brand assets (scripts/generate-brand-assets.mjs): they must exist at the sizes +// the page, the manifest and social networks expect. + +const png = (file: string) => { + const bytes = readFileSync(`static/${file}`); + expect(bytes.subarray(1, 4).toString()).toBe('PNG'); + return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20), bytes: bytes.length }; +}; + +describe('social preview image', () => { + it('is 1200x630, the size og:image declares, and small enough for every crawler', () => { + const { width, height, bytes } = png('og-image.png'); + expect([width, height]).toEqual([1200, 630]); + expect(bytes).toBeLessThan(600 * 1024); + }); + + it('is the size the page says it is', () => { + const seo = readFileSync('src/lib/components/Seo.svelte', 'utf-8'); + expect(seo).toContain('og:image:width" content="1200"'); + expect(seo).toContain('og:image:height" content="630"'); + }); +}); + +describe('app manifest', () => { + const manifest = JSON.parse(readFileSync('static/favicon/site.webmanifest', 'utf-8')); + + it('lists icons that exist, at the sizes it declares', () => { + expect(manifest.icons.length).toBeGreaterThanOrEqual(4); + for (const icon of manifest.icons) { + const { width, height } = png(icon.src.replace(/^\//, '')); + expect(`${width}x${height}`, icon.src).toBe(icon.sizes); + } + }); + + it('has separate "any" and "maskable" icons, never one image for both', () => { + const purposes = manifest.icons.map((i: { purpose: string }) => i.purpose); + expect(purposes).toContain('any'); + expect(purposes).toContain('maskable'); + const bySource = manifest.icons.map((i: { src: string }) => i.src); + expect(new Set(bySource).size).toBe(bySource.length); + }); + + it('uses the brand colour', () => { + expect(manifest.theme_color.toLowerCase()).toBe('#0f6cbd'); + const html = readFileSync('src/app.html', 'utf-8'); + expect(html).toContain('name="theme-color" content="#0f6cbd"'); + }); +}); + +describe('favicons', () => { + it('the touch icon is 180x180', () => { + const { width, height } = png('favicon/apple-touch-icon.png'); + expect([width, height]).toEqual([180, 180]); + }); + + it('the .ico holds 16, 32 and 48 pixel images', () => { + const ico = readFileSync('static/favicon/favicon.ico'); + expect(ico.readUInt16LE(2)).toBe(1); // an icon + const count = ico.readUInt16LE(4); + const sizes = Array.from({ length: count }, (_, i) => ico.readUInt8(6 + i * 16)).sort( + (a, b) => a - b + ); + expect(sizes).toEqual([16, 32, 48]); + }); + + it('the vector favicon is the layers alone: brand blue, white on a dark tab bar', () => { + const svg = readFileSync('static/favicon/favicon.svg', 'utf-8'); + expect(svg).toContain('#0f6cbd'); + expect(svg).toContain('prefers-color-scheme:dark'); + expect(svg).toContain('#ffffff'); + expect(svg).not.toContain(' { + const html = readFileSync('src/app.html', 'utf-8'); + for (const [, href] of html.matchAll( + /rel="(?:icon|apple-touch-icon|manifest)" href="([^"]+)"/g + )) { + expect(existsSync(`static${href}`), href).toBe(true); + } + }); +}); diff --git a/scripts/generate-brand-assets.mjs b/scripts/generate-brand-assets.mjs new file mode 100644 index 0000000..5121d5f --- /dev/null +++ b/scripts/generate-brand-assets.mjs @@ -0,0 +1,162 @@ +/** + * Draws the brand assets: the favicons, the app icons and the social preview image. + * + * node scripts/generate-brand-assets.mjs + * + * They all come from the same mark (the layers, see src/lib/icons/Logo.svelte), so + * changing the brand means changing this file and running it again. Needs the Playwright browser + * (`yarn playwright install chromium`). + */ +import { chromium } from '@playwright/test'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +const root = resolve(import.meta.dirname, '..'); +const BRAND = '#0f6cbd'; + +/** + * The layers on a 32-unit square. `scale` sizes them (they fill 22 of the 32 units at 1); `background` puts + * them on a tile, which only the icons that need an opaque or full-bleed image have. + */ +function mark({ color = BRAND, scale = 1.27, background = null, rx = 0 } = {}) { + return ` +${background ? `` : ''} + + + + +`; +} + +/** The browser-tab icon: blue on a light tab bar, white on a dark one */ +const faviconSvg = ` + + + + + + + +`; + +const ICONS = [ + // "any": just the layers, on a transparent background + { file: 'favicon/favicon-96x96.png', size: 96, svg: mark() }, + { file: 'favicon/web-app-manifest-192x192.png', size: 192, svg: mark() }, + { file: 'favicon/web-app-manifest-512x512.png', size: 512, svg: mark() }, + // "maskable": full bleed, with the layers inside the safe zone, because the system cuts its own shape + { + file: 'favicon/web-app-manifest-maskable-192x192.png', + size: 192, + svg: mark({ background: '#ffffff', scale: 0.85 }) + }, + { + file: 'favicon/web-app-manifest-maskable-512x512.png', + size: 512, + svg: mark({ background: '#ffffff', scale: 0.85 }) + }, + // iOS rounds the corners itself and does not like transparency + { + file: 'favicon/apple-touch-icon.png', + size: 180, + svg: mark({ background: '#ffffff', scale: 1 }) + } +]; +const ICO_SIZES = [16, 32, 48]; + +const font = pathToFileURL(join(root, 'src/lib/fonts/inter/Inter-Variable-latin.woff2')).href; + +const socialImage = ` +
+
+
${mark({ color: '#ffffff', scale: 1.1 }).replace('width="32" height="32"', 'width="64" height="64"')}Lienzo
+

Design it. Export it.
Edit it again.

+

A free A4 document builder. Your PDF keeps real text and carries your editable document inside.

+
+
lienzo.deityhub.com
+
+
Ada Lovelace
+
Analyst Β· London
+
+
+
+
+
+
Summer market
+
Saturday 14 June Β· Riverside
+
+
+
Reserve a stall
+
+`; + +/** An .ico holding PNG images, which every current browser reads */ +function ico(images) { + const header = Buffer.alloc(6 + images.length * 16); + header.writeUInt16LE(1, 2); // type: icon + header.writeUInt16LE(images.length, 4); + let offset = header.length; + images.forEach(({ size, data }, i) => { + const entry = 6 + i * 16; + header.writeUInt8(size, entry); // width and height (0 would mean 256) + header.writeUInt8(size, entry + 1); + header.writeUInt16LE(1, entry + 4); // colour planes + header.writeUInt16LE(32, entry + 6); // bits per pixel + header.writeUInt32LE(data.length, entry + 8); + header.writeUInt32LE(offset, entry + 12); + offset += data.length; + }); + return Buffer.concat([header, ...images.map((i) => i.data)]); +} + +const out = (file, data) => writeFileSync(join(root, 'static', file), data); + +const browser = await chromium.launch(); +const scratch = mkdtempSync(join(tmpdir(), 'lienzo-brand-')); +try { + const page = await browser.newPage(); + + /** Draw an SVG at a size, on a transparent background */ + async function png(svg, size) { + await page.setViewportSize({ width: size, height: size }); + await page.setContent( + `${svg.replace('width="32" height="32"', `width="${size}" height="${size}"`)}` + ); + return page.screenshot({ + omitBackground: true, + clip: { x: 0, y: 0, width: size, height: size } + }); + } + + out('favicon/favicon.svg', faviconSvg); + for (const { file, size, svg } of ICONS) out(file, await png(svg, size)); + out( + 'favicon/favicon.ico', + ico(await Promise.all(ICO_SIZES.map(async (size) => ({ size, data: await png(mark(), size) })))) + ); + + const html = join(scratch, 'social.html'); + writeFileSync(html, socialImage); + await page.setViewportSize({ width: 1200, height: 630 }); + await page.goto(pathToFileURL(html).href); + await page.evaluate(() => document.fonts.ready); + out('og-image.png', await page.screenshot()); +} finally { + await browser.close(); + rmSync(scratch, { recursive: true, force: true }); +} +process.stdout.write('Brand assets written to static/\n'); diff --git a/scripts/generate-notices.mjs b/scripts/generate-notices.mjs new file mode 100644 index 0000000..0daded6 --- /dev/null +++ b/scripts/generate-notices.mjs @@ -0,0 +1,218 @@ +// Writes THIRD_PARTY_NOTICES.md: the open source code and fonts that ship with the app. +// Run after changing runtime dependencies or fonts: yarn notices +import fs from 'node:fs'; +import path from 'node:path'; + +const root = path.resolve(import.meta.dirname, '..'); +// What the browser bundle and the server build contain. Build and test tools are not listed: they do not ship. +const ROOTS = [ + 'svelte', + '@sveltejs/kit', + '@lucide/svelte', + '@cantoo/pdf-lib', + '@cantoo/fontkit', + 'html-to-image' +]; + +const packages = new Map(); +function visit(name) { + if (packages.has(name)) return; + const dir = path.join(root, 'node_modules', name); + const file = path.join(dir, 'package.json'); + if (!fs.existsSync(file)) return; + const json = JSON.parse(fs.readFileSync(file, 'utf8')); + let copyright = ''; + for (const entry of fs.readdirSync(dir)) { + if (!/^(licen[cs]e|copying)/i.test(entry)) continue; + const line = fs + .readFileSync(path.join(dir, entry), 'utf8') + .split('\n') + .find((l) => /copyright/i.test(l) && /\d{4}/.test(l)); + if (line) { + copyright = line + .replace(/^[\s#*>-]+/, '') + .replace(/\(c\)\s*/i, '') + .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') // keep the words of a markdown link + .trim(); + break; + } + } + packages.set(name, { version: json.version, license: json.license, copyright }); + for (const dep of Object.keys(json.dependencies ?? {})) visit(dep); +} +ROOTS.forEach(visit); + +const rows = [...packages] + .sort(([a], [b]) => a.localeCompare(b)) + .map( + ([name, p]) => `| ${name} | ${p.version} | ${p.license} | ${p.copyright || 'See the package'} |` + ) + .join('\n'); + +const fonts = [ + ['Inter', 'The Inter Project Authors', 'https://github.com/rsms/inter', 'OFL-1.1'], + ['Lato', 'Łukasz Dziedzic', 'https://fonts.google.com/specimen/Lato', 'OFL-1.1'], + [ + 'Merriweather', + 'The Merriweather Project Authors', + 'https://fonts.google.com/specimen/Merriweather', + 'OFL-1.1' + ], + [ + 'Montserrat', + 'The Montserrat Project Authors', + 'https://fonts.google.com/specimen/Montserrat', + 'OFL-1.1' + ], + ['Nunito', 'The Nunito Project Authors', 'https://fonts.google.com/specimen/Nunito', 'OFL-1.1'], + [ + 'Open Sans', + 'The Open Sans Project Authors', + 'https://fonts.google.com/specimen/Open+Sans', + 'OFL-1.1' + ], + ['Oswald', 'The Oswald Project Authors', 'https://fonts.google.com/specimen/Oswald', 'OFL-1.1'], + [ + 'Playfair Display', + 'The Playfair Project Authors', + 'https://fonts.google.com/specimen/Playfair+Display', + 'OFL-1.1' + ], + ['Poppins', 'Indian Type Foundry', 'https://fonts.google.com/specimen/Poppins', 'OFL-1.1'], + [ + 'Raleway', + 'The Raleway Project Authors', + 'https://fonts.google.com/specimen/Raleway', + 'OFL-1.1' + ], + [ + 'Roboto', + 'The Roboto Project Authors', + 'https://fonts.google.com/specimen/Roboto', + 'Apache-2.0 or OFL-1.1' + ], + [ + 'Roboto Condensed', + 'The Roboto Condensed Project Authors', + 'https://fonts.google.com/specimen/Roboto+Condensed', + 'Apache-2.0 or OFL-1.1' + ], + [ + 'Roboto Slab', + 'The Roboto Slab Project Authors', + 'https://fonts.google.com/specimen/Roboto+Slab', + 'Apache-2.0 or OFL-1.1' + ], + ['Source Code Pro', 'Adobe', 'https://github.com/adobe-fonts/source-code-pro', 'OFL-1.1'] +] + .map(([n, c, u, l]) => `| ${n} | ${c} | ${l} | <${u}> |`) + .join('\n'); + +const MIT = `Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`; + +const ISC = `Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.`; + +const OFL = `PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the copyright statement(s). + +"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. + +5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.`; + +const quote = (text) => + text + .split('\n') + .map((l) => (l ? `> ${l}` : '>')) + .join('\n'); + +const out = `# Third-party notices + +Lienzo itself is licensed under the [GNU GPLv3](LICENSE). It includes the open source software and fonts below, each under its own license. This file is generated by \`yarn notices\`; do not edit it by hand. + +## Software + +These packages are part of the app that runs in your browser or on the server. Tools used only to build and test Lienzo are not included, because they are not distributed with it. + +| Package | Version | License | Copyright | +| ------- | ------- | ------- | --------- | +${rows} + +## Fonts + +The fonts in \`src/lib/fonts\` and the static copies used for PDF export in \`static/pdf-fonts\` come from the projects below, as published on Google Fonts and by their authors. Roboto, Roboto Condensed and Roboto Slab have been published under both the Apache License 2.0 and the SIL Open Font License; the full text of the Apache License is at . + +| Font | Copyright holder | License | Source | +| ---- | ---------------- | ------- | ------ | +${fonts} + +Fonts that were made from the originals (subset to Latin and Latin-extended, converted to WOFF2 and, for PDF export, to static instances) are modified versions as the OFL describes. None of them is sold on its own. + +## Design + +The look of the app follows the public design guidance of [Fluent 2](https://fluent2.microsoft.design/) from Microsoft. No Microsoft code or assets are included. + +## License texts + +### MIT License + +Applies to the packages marked MIT. Each has its own copyright line, listed above. + +${quote(MIT)} + +### ISC License + +Applies to \`@lucide/svelte\` (Lucide Contributors, and Cole Bemis for the parts derived from Feather). + +${quote(ISC)} + +### BSD Zero Clause License (0BSD) + +Applies to \`tslib\`. It permits use, copying, modification and distribution without conditions. + +### Apache License 2.0 + +Applies to \`aria-query\` and \`axobject-query\`. The full text is at . + +### SIL Open Font License 1.1 + +Applies to the fonts marked OFL-1.1. The text below is the license itself; each font's copyright holder is in the table above. + +${quote(OFL)} +`; + +fs.writeFileSync(path.join(root, 'THIRD_PARTY_NOTICES.md'), out); +process.stdout.write(`THIRD_PARTY_NOTICES.md: ${packages.size} packages, 14 font families\n`); diff --git a/scripts/generate-pdf-fonts.py b/scripts/generate-pdf-fonts.py new file mode 100644 index 0000000..4d292c7 --- /dev/null +++ b/scripts/generate-pdf-fonts.py @@ -0,0 +1,87 @@ +""" +Generate the static font instances used by PDF export (static/pdf-fonts). + +The editor uses variable WOFF2 fonts, but the PDF library can only embed static fonts, so every +weight of every family is instanced once here and committed. A manifest maps +family -> style -> weight -> file; the exporter downloads only the files a document uses. + +Requires: pip install fonttools brotli +Run: python3 scripts/generate-pdf-fonts.py +""" +import io +import json +import os +from fontTools.ttLib import TTFont +from fontTools.varLib import instancer + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SRC = os.path.join(ROOT, 'src/lib/fonts') +OUT = os.path.join(ROOT, 'static/pdf-fonts') +WEIGHTS = range(100, 1000, 100) +STATIC_WEIGHTS = { + 'Thin': 100, 'ExtraLight': 200, 'Light': 300, 'Regular': 400, 'Medium': 500, + 'SemiBold': 600, 'Bold': 700, 'ExtraBold': 800, 'Black': 900, +} + + +def save(font, name): + font.flavor = 'woff' + font.save(os.path.join(OUT, name)) + + +def static_weight(filename): + """Lato-BoldItalic.woff2 -> (700, 'italic'); Lato-Italic.woff2 -> (400, 'italic').""" + part = filename.removesuffix('.woff2').split('-', 1)[1] + italic = part.endswith('Italic') + word = part.removesuffix('Italic') or 'Regular' + return STATIC_WEIGHTS[word], 'italic' if italic else 'normal' + + +def main(): + os.makedirs(OUT, exist_ok=True) + for old in os.listdir(OUT): + os.remove(os.path.join(OUT, old)) + + manifest = {} + for directory in sorted(os.listdir(SRC)): + folder = os.path.join(SRC, directory) + if not os.path.isdir(folder): + continue + family = directory.replace('-', ' ').title() + styles = manifest.setdefault(family, {}) + + for filename in sorted(os.listdir(folder)): + # Only the latin file is used; characters outside it fall back to '?' in the PDF + if not filename.endswith('.woff2') or 'latin-ext' in filename: + continue + font = TTFont(os.path.join(folder, filename)) + font.flavor = None + + if 'fvar' not in font: + weight, style = static_weight(filename) + name = f'{directory}-{style}-{weight}.woff' + save(font, name) + styles.setdefault(style, {})[str(weight)] = name + continue + + style = 'italic' if 'Italic' in filename else 'normal' + axis = next(a for a in font['fvar'].axes if a.axisTag == 'wght') + buffer = io.BytesIO() + font.save(buffer) + for weight in WEIGHTS: + if not axis.minValue <= weight <= axis.maxValue: + continue + instance = instancer.instantiateVariableFont(TTFont(io.BytesIO(buffer.getvalue())), {'wght': weight}) + name = f'{directory}-{style}-{weight}.woff' + save(instance, name) + styles.setdefault(style, {})[str(weight)] = name + + with open(os.path.join(OUT, 'manifest.json'), 'w') as f: + json.dump(manifest, f, indent=1, sort_keys=True) + f.write('\n') + files = [n for n in os.listdir(OUT) if n.endswith('.woff')] + size = sum(os.path.getsize(os.path.join(OUT, n)) for n in files) + print(f'{len(files)} fonts, {size / 1e6:.1f} MB') + + +main() diff --git a/scripts/generate-screenshots.mjs b/scripts/generate-screenshots.mjs new file mode 100644 index 0000000..8b5fe3e --- /dev/null +++ b/scripts/generate-screenshots.mjs @@ -0,0 +1,90 @@ +/** + * Takes the screenshots used in the README (docs/screenshots), in the light and the dark theme. + * + * yarn docs:screenshots (builds the app first) + * + * It starts the production preview itself. Needs the Playwright browser (`yarn playwright install chromium`). + */ +import { chromium } from '@playwright/test'; +import { spawn } from 'node:child_process'; +import { mkdirSync } from 'node:fs'; +import { resolve } from 'node:path'; + +const root = resolve(import.meta.dirname, '..'); +const out = resolve(root, 'docs/screenshots'); +const PORT = 4174; // not 4173, so it does not clash with the end-to-end tests +const BASE = `http://localhost:${PORT}`; +mkdirSync(out, { recursive: true }); + +const server = spawn( + process.execPath, + ['node_modules/vite/bin/vite.js', 'preview', '--port', String(PORT), '--strictPort'], + { + cwd: root, + stdio: 'ignore' + } +); +const stop = () => server.kill(); +process.on('exit', stop); + +async function waitForServer() { + for (let i = 0; i < 60; i++) { + try { + if ((await fetch(BASE)).ok) return; + } catch { + // not up yet + } + await new Promise((r) => setTimeout(r, 500)); + } + throw new Error('The preview server did not start. Run `yarn build` first.'); +} + +const shots = [ + { + name: 'home', + run: async (page) => { + await page.goto(BASE); + } + }, + { + name: 'templates', + run: async (page) => { + await page.goto(`${BASE}/templates`); + } + }, + { + name: 'editor', + run: async (page) => { + await page.goto(`${BASE}/templates`); + await page.waitForLoadState('networkidle'); // hydrated: the button works + await page.getByTestId('use-invoice').click(); + await page.waitForURL('**/canvas'); + await page.locator('textarea').first().waitFor(); + } + } +]; + +const browser = await chromium.launch(); +try { + await waitForServer(); + for (const theme of ['light', 'dark']) { + const context = await browser.newContext({ + viewport: { width: 1440, height: 900 }, + colorScheme: theme + }); + await context.addInitScript((value) => localStorage.setItem('lienzo-theme', value), theme); + for (const shot of shots) { + const page = await context.newPage(); + await shot.run(page); + await page.waitForLoadState('networkidle'); + await page.evaluate(() => document.fonts.ready); + await page.screenshot({ path: resolve(out, `${shot.name}-${theme}.png`) }); + await page.close(); + process.stdout.write(`docs/screenshots/${shot.name}-${theme}.png\n`); + } + await context.close(); + } +} finally { + await browser.close(); + stop(); +} diff --git a/src/app.css b/src/app.css index 55a7fd8..040d3ad 100644 --- a/src/app.css +++ b/src/app.css @@ -5,113 +5,136 @@ @custom-variant dark (&:where(.dark, .dark *)); :root { + /* + * Fluent 2 (web) palette, as HSL channels. Communication blue brand, neutral greys, 4px controls. + * --primary is for fills; --primary-text is the same brand colour tuned for text and thin lines on the page. + */ + /* Base colors */ --background: 0 0% 100%; - --foreground: 222.2 84% 4.9%; - --border: 214.3 31.8% 91.4%; - --input: 214.3 31.8% 91.4%; - --ring: 221.2 83.2% 53.3%; - - /* Primary colors (indigo) */ - --primary: 243 75% 59%; + --foreground: 0 0% 14%; + --border: 0 0% 88%; + /* Borders of inputs and controls: 3:1 against the page, as WCAG asks of interface boundaries */ + --input: 0 0% 52%; + --ring: 208 85% 40%; + + /* The app backdrop, and the paper pages are drawn on (always white, in both themes) */ + --surface: 0 0% 98%; + --paper: 0 0% 100%; + --paper-foreground: 0 0% 14%; + + /* Primary colors (communication blue) */ + --primary: 208 85% 40%; --primary-foreground: 0 0% 100%; - --primary-light: 237 100% 96%; - --primary-dark: 243 75% 49%; + --primary-light: 212 74% 96%; + --primary-dark: 208 81% 35%; + --primary-text: 208 81% 35%; - /* Secondary colors (slate) */ - --secondary: 215 16% 47%; + /* Secondary colors (neutral) */ + --secondary: 0 0% 38%; --secondary-foreground: 0 0% 100%; - --secondary-light: 210 20% 98%; - --secondary-dark: 215 19% 35%; + --secondary-light: 0 0% 96%; + --secondary-dark: 0 0% 26%; /* Destructive colors (red) */ - --destructive: 0 84.2% 60.2%; + --destructive: 355 85% 37%; --destructive-foreground: 0 0% 100%; - --destructive-light: 0 100% 97%; - --destructive-dark: 0 84% 50%; + --destructive-light: 354 71% 97%; + --destructive-dark: 355 85% 30%; + --destructive-text: 355 85% 37%; - /* Success colors (emerald) */ - --success: 142.1 70.6% 45.3%; + /* Success colors (green) */ + --success: 120 77% 27%; --success-foreground: 0 0% 100%; - --success-light: 142.1 76% 97%; - --success-dark: 142.1 70% 35%; + --success-light: 120 47% 96%; + --success-dark: 120 78% 25%; - /* Warning colors (amber) */ - --warning: 38 92% 50%; + /* Warning colors (orange) */ + --warning: 24 91% 39%; --warning-foreground: 0 0% 100%; - --warning-light: 38 100% 96%; - --warning-dark: 38 92% 40%; + --warning-light: 24 100% 98%; + --warning-dark: 24 92% 32%; + + --info: 208 85% 40%; /* Muted colors */ - --muted: 210 20% 98%; - --muted-foreground: 215.4 16.3% 46.9%; + --muted: 0 0% 96%; + --muted-foreground: 0 0% 38%; /* Accent colors */ - --accent: 210 20% 98%; - --accent-foreground: 222.2 47.4% 11.2%; + --accent: 0 0% 96%; + --accent-foreground: 0 0% 14%; /* Card colors */ --card: 0 0% 100%; - --card-foreground: 222.2 84% 4.9%; + --card-foreground: 0 0% 14%; /* Popover colors */ --popover: 0 0% 100%; - --popover-foreground: 222.2 84% 4.9%; + --popover-foreground: 0 0% 14%; } .dark { /* Base colors */ - --background: 222.2 84% 4.9%; - --foreground: 210 20% 98%; - --border: 217.2 32.6% 17.5%; - --input: 217.2 32.6% 17.5%; - --ring: 224.3 76.3% 48%; - - /* Primary colors (indigo) - dark theme */ - --primary: 243 75% 65%; + --background: 0 0% 16%; + --foreground: 0 0% 100%; + --border: 0 0% 24%; + --input: 0 0% 50%; + --ring: 210 90% 62%; + + --surface: 0 0% 12%; + --paper: 0 0% 100%; + --paper-foreground: 0 0% 14%; + + /* Primary colors (communication blue) - dark theme */ + --primary: 208 81% 35%; --primary-foreground: 0 0% 100%; - --primary-light: 243 75% 20%; - --primary-dark: 243 75% 75%; + --primary-light: 206 77% 21%; + --primary-dark: 208 85% 40%; + --primary-text: 210 90% 62%; - /* Secondary colors (slate) - dark theme */ - --secondary: 215 25% 65%; + /* Secondary colors (neutral) - dark theme */ + --secondary: 0 0% 40%; --secondary-foreground: 0 0% 100%; - --secondary-light: 215 20% 20%; - --secondary-dark: 215 25% 75%; + --secondary-light: 0 0% 22%; + --secondary-dark: 0 0% 50%; /* Destructive colors (red) - dark theme */ - --destructive: 0 84.2% 65.2%; + --destructive: 357 62% 40%; --destructive-foreground: 0 0% 100%; - --destructive-light: 0 84% 20%; - --destructive-dark: 0 84% 75%; - - /* Success colors (emerald) - dark theme */ - --success: 142.1 70.6% 55.3%; - --success-foreground: 0 0% 100%; - --success-light: 142.1 70% 20%; - --success-dark: 142.1 70% 65%; - - /* Warning colors (amber) - dark theme */ - --warning: 38 92% 60%; + --destructive-light: 359 60% 15%; + --destructive-dark: 357 62% 34%; + --destructive-text: 355 82% 69%; + + /* Success colors (green) - dark theme */ + --success: 120 37% 51%; + --success-foreground: 0 0% 7%; + --success-light: 120 66% 14%; + --success-dark: 120 37% 60%; + + /* Warning colors (orange) - dark theme */ + --warning: 42 85% 67%; --warning-foreground: 0 0% 0%; - --warning-light: 38 92% 20%; - --warning-dark: 38 92% 70%; + --warning-light: 42 70% 13%; + --warning-dark: 42 85% 75%; + + --info: 210 90% 62%; /* Muted colors - dark theme */ - --muted: 217.2 32.6% 17.5%; - --muted-foreground: 215 20.2% 65.1%; + --muted: 0 0% 22%; + --muted-foreground: 0 0% 68%; /* Accent colors - dark theme */ - --accent: 217.2 32.6% 17.5%; - --accent-foreground: 210 20% 98%; + --accent: 0 0% 22%; + --accent-foreground: 0 0% 100%; /* Card colors - dark theme */ - --card: 222.2 84% 4.9%; - --card-foreground: 210 20% 98%; + --card: 0 0% 16%; + --card-foreground: 0 0% 100%; /* Popover colors - dark theme */ - --popover: 222.2 84% 4.9%; - --popover-foreground: 210 20% 98%; + --popover: 0 0% 16%; + --popover-foreground: 0 0% 100%; } /* Map your CSS variables to Tailwind utilities using @theme */ @@ -122,12 +145,16 @@ --color-border: hsl(var(--border)); --color-input: hsl(var(--input)); --color-ring: hsl(var(--ring)); + --color-surface: hsl(var(--surface)); + --color-paper: hsl(var(--paper)); + --color-paper-foreground: hsl(var(--paper-foreground)); /* Primary colors */ --color-primary: hsl(var(--primary)); --color-primary-foreground: hsl(var(--primary-foreground)); --color-primary-light: hsl(var(--primary-light)); --color-primary-dark: hsl(var(--primary-dark)); + --color-primary-text: hsl(var(--primary-text)); /* Secondary colors */ --color-secondary: hsl(var(--secondary)); @@ -140,6 +167,7 @@ --color-destructive-foreground: hsl(var(--destructive-foreground)); --color-destructive-light: hsl(var(--destructive-light)); --color-destructive-dark: hsl(var(--destructive-dark)); + --color-destructive-text: hsl(var(--destructive-text)); --color-success: hsl(var(--success)); --color-success-foreground: hsl(var(--success-foreground)); diff --git a/src/app.html b/src/app.html index 7ca3856..3efa5c8 100644 --- a/src/app.html +++ b/src/app.html @@ -10,7 +10,23 @@ - + + %sveltekit.head% diff --git a/src/lib/canvas/autosave.svelte.spec.ts b/src/lib/canvas/autosave.svelte.spec.ts new file mode 100644 index 0000000..432fe07 --- /dev/null +++ b/src/lib/canvas/autosave.svelte.spec.ts @@ -0,0 +1,150 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createAutosave, UNTITLED_NAME } from './autosave.svelte'; + +function setup(name = '', minSavingTime = 0) { + let revision = 0; + let currentName = name; + const save = vi.fn<(name: string) => Promise>(async () => null); + const autosave = createAutosave({ + getRevision: () => revision, + getName: () => currentName, + save, + delay: 1000, + minSavingTime + }); + /** Open a document, then edit it `edits` times */ + const edit = (documentId = 'a') => autosave.changed(documentId, ++revision); + autosave.changed('a', revision); // the document opened + return { autosave, save, edit, setName: (n: string) => (currentName = n) }; +} + +describe('createAutosave', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it('does not save a document that was only opened', async () => { + const { save } = setup(); + await vi.advanceTimersByTimeAsync(5000); + expect(save).not.toHaveBeenCalled(); + }); + + it('saves an unnamed document as Untitled on its first edit', async () => { + const { save, edit, autosave } = setup(); + edit(); + expect(autosave.hasUnsaved).toBe(true); + + await vi.advanceTimersByTimeAsync(1000); + + expect(save).toHaveBeenCalledExactlyOnceWith(UNTITLED_NAME); + expect(autosave.status).toBe('saved'); + expect(autosave.hasUnsaved).toBe(false); + }); + + it('keeps the name of a named document', async () => { + const { save, edit } = setup('My Resume'); + edit(); + await vi.advanceTimersByTimeAsync(1000); + expect(save).toHaveBeenCalledWith('My Resume'); + }); + + it('waits for edits to stop, saving once', async () => { + const { save, edit } = setup('Doc'); + edit(); + await vi.advanceTimersByTimeAsync(600); + edit(); + await vi.advanceTimersByTimeAsync(600); + expect(save).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(400); + expect(save).toHaveBeenCalledTimes(1); + }); + + it('saves edits made during a save right after it, never at the same time', async () => { + const { save, edit, autosave } = setup('Doc'); + let release!: () => void; + save.mockImplementationOnce(() => new Promise((resolve) => (release = () => resolve(null)))); + + edit(); + await vi.advanceTimersByTimeAsync(1000); // first save starts and is still running + edit(); + await vi.advanceTimersByTimeAsync(2000); + expect(save).toHaveBeenCalledTimes(1); + + release(); + await vi.advanceTimersByTimeAsync(1000); + expect(save).toHaveBeenCalledTimes(2); + expect(autosave.status).toBe('saved'); + }); + + it('reports a failure, keeps the changes unsaved and can retry', async () => { + const { save, edit, autosave } = setup('Doc'); + save.mockResolvedValueOnce('Storage is full'); + + edit(); + await vi.advanceTimersByTimeAsync(1000); + expect(autosave.status).toBe('error'); + expect(autosave.error).toBe('Storage is full'); + expect(autosave.hasUnsaved).toBe(true); + + await autosave.retry(); + expect(autosave.status).toBe('saved'); + expect(autosave.error).toBe(''); + expect(autosave.hasUnsaved).toBe(false); + }); + + it('starts over when another document is opened', async () => { + const { save, edit, autosave } = setup('Doc'); + edit(); + autosave.changed('b', 0); // another document, with its own revision + await vi.advanceTimersByTimeAsync(5000); + + expect(save).not.toHaveBeenCalled(); + expect(autosave.status).toBe('idle'); + }); + + it('flush saves right away and waits for it', async () => { + const { save, edit, autosave } = setup('Doc'); + edit(); + await autosave.flush(); + expect(save).toHaveBeenCalledTimes(1); + + await autosave.flush(); // nothing new + expect(save).toHaveBeenCalledTimes(1); + }); + + it('does not save again after the document was saved another way', async () => { + const { save, edit, autosave } = setup('Doc'); + edit(); + autosave.markSaved(); + await vi.advanceTimersByTimeAsync(5000); + expect(save).not.toHaveBeenCalled(); + expect(autosave.status).toBe('saved'); + }); + + it('shows "saving" for a moment even when the save is instant', async () => { + const { save, edit, autosave } = setup('Doc', 800); + edit(); + await vi.advanceTimersByTimeAsync(1000); // the save starts and finishes at once + expect(save).toHaveBeenCalledTimes(1); + expect(autosave.status).toBe('saving'); + expect(autosave.hasUnsaved).toBe(false); // it is already safe, only the label waits + + await vi.advanceTimersByTimeAsync(800); + expect(autosave.status).toBe('saved'); + }); + + it('does not save twice when it is told about the revision it is already saving', async () => { + const { save, edit, autosave } = setup('Doc'); + let release!: () => void; + save.mockImplementationOnce(() => new Promise((resolve) => (release = () => resolve(null)))); + + edit(); + await vi.advanceTimersByTimeAsync(1000); // saving + autosave.changed('a', 1); // e.g. the save renamed the document in the editor + release(); + await vi.advanceTimersByTimeAsync(5000); + + expect(save).toHaveBeenCalledTimes(1); + expect(autosave.hasUnsaved).toBe(false); + }); +}); diff --git a/src/lib/canvas/autosave.svelte.ts b/src/lib/canvas/autosave.svelte.ts new file mode 100644 index 0000000..43cb95b --- /dev/null +++ b/src/lib/canvas/autosave.svelte.ts @@ -0,0 +1,132 @@ +export type SaveStatus = 'idle' | 'saving' | 'saved' | 'error'; + +export const UNTITLED_NAME = 'Untitled document'; + +interface Options { + /** Changes whenever the document has something new to save */ + getRevision: () => number; + /** The document's name; empty until it is first saved */ + getName: () => string; + /** Save under a name. Returns an error message, or null on success. */ + save: (name: string) => Promise; + /** Wait this long after the last change before saving */ + delay?: number; + /** Keep showing "saving" at least this long, so a very fast save is still noticeable */ + minSavingTime?: number; +} + +/** + * Saves the document shortly after it changes. A document that was never named is saved as + * "Untitled document" on its first edit. Writes never overlap: edits made during a save + * are saved right after it. + */ +export function createAutosave(options: Options) { + const delay = options.delay ?? 1500; + const minSavingTime = options.minSavingTime ?? 800; + + let status = $state('idle'); + let error = $state(''); + let savedAt = $state(null); + + let trackedId: string | null = null; + let savedRevision = 0; + /** The revision being written right now */ + let writingRevision: number | null = null; + let timer: ReturnType | undefined; + let statusTimer: ReturnType | undefined; + let writing: Promise | null = null; + + const dirty = () => options.getRevision() !== savedRevision; + + async function write() { + clearTimeout(timer); + timer = undefined; + const revision = options.getRevision(); + writingRevision = revision; + const started = Date.now(); + clearTimeout(statusTimer); + status = 'saving'; + const message = await options.save(options.getName() || UNTITLED_NAME); + writingRevision = null; + + if (message) { + status = 'error'; + error = message; + return; // stays unsaved: the next change or a retry tries again + } + error = ''; + savedRevision = revision; + savedAt = Date.now(); + if (dirty()) { + schedule(); // edited while saving + return; // still "saving" until that is done + } + // Saving is often too quick to notice: show it for a moment + const remaining = minSavingTime - (Date.now() - started); + if (remaining > 0) statusTimer = setTimeout(() => (status = 'saved'), remaining); + else status = 'saved'; + } + + /** Start a write, or wait for the one in progress (which then picks up newer changes). */ + function run(): Promise { + writing ??= write().finally(() => (writing = null)); + return writing; + } + + function schedule() { + clearTimeout(timer); + timer = setTimeout(() => void run(), delay); + } + + return { + get status() { + return status; + }, + get error() { + return error; + }, + get savedAt() { + return savedAt; + }, + /** Unsaved changes: waiting to be saved, being saved, or failed to save */ + get hasUnsaved() { + return timer !== undefined || writing !== null || status === 'error'; + }, + + /** Tell the controller the document's current id and revision; call whenever either may have changed. */ + changed(documentId: string, revision: number) { + if (documentId !== trackedId) { + // A different document was opened or started: nothing to save until it is edited + trackedId = documentId; + savedRevision = revision; + clearTimeout(timer); + timer = undefined; + clearTimeout(statusTimer); + status = 'idle'; + error = ''; + return; + } + // The save itself touches the document (its name), which calls this again: ignore the revision being written + if (revision !== savedRevision && revision !== writingRevision) schedule(); + }, + + /** The document was saved some other way (the Save button) */ + markSaved() { + clearTimeout(timer); + timer = undefined; + clearTimeout(statusTimer); + savedRevision = options.getRevision(); + savedAt = Date.now(); + status = 'saved'; + error = ''; + }, + + /** Save now if there is anything unsaved, and wait until it is done. */ + async flush() { + if (writing) await writing; + if (dirty() && trackedId !== null) await run(); + }, + + retry: () => run() + }; +} diff --git a/src/lib/canvas/canvasImport.browser.spec.ts b/src/lib/canvas/canvasImport.browser.spec.ts new file mode 100644 index 0000000..e6c5050 --- /dev/null +++ b/src/lib/canvas/canvasImport.browser.spec.ts @@ -0,0 +1,75 @@ +// Runs in Chromium (File and IndexedDB), see the "client" project in vite.config.ts +import { beforeEach, describe, expect, it } from 'vitest'; +import { appStore } from '../stores/appStore.svelte.ts'; +import { serializeDocuments } from '../utils/documentFile'; +import { sampleDoc } from '../utils/testDocument'; +import { createCanvasImport } from './canvasImport.svelte'; + +const file = (name: string, content: string) => + new File([content], name, { type: 'application/json' }); +const docFile = (name = 'Imported') => + file('doc.lienzo.json', serializeDocuments([sampleDoc('src-id', name)])); + +describe('createCanvasImport', () => { + beforeEach(() => { + appStore.initNewDocument(); + }); + + it('replaces an empty canvas right away, as a new document', async () => { + const importer = createCanvasImport(() => false); + + await importer.importFile(docFile('Fresh')); + + expect(importer.pending).toBeNull(); + expect(importer.error).toBe(''); + expect(appStore.getCurrentDocument().name).toBe('Fresh'); + expect(appStore.getCurrentDocument().id).not.toBe('src-id'); + expect(appStore.getSelectedElement()).toBeNull(); + }); + + it('asks before replacing a canvas that has content, and only replaces on confirm', async () => { + const before = appStore.getCurrentDocument().id; + const importer = createCanvasImport(() => true); + + await importer.importFile(docFile('Asked')); + expect(importer.pending?.name).toBe('Asked'); + expect(appStore.getCurrentDocument().id).toBe(before); + + importer.confirm(); + expect(importer.pending).toBeNull(); + expect(appStore.getCurrentDocument().name).toBe('Asked'); + }); + + it('cancelling keeps the canvas as it is', async () => { + const before = appStore.getCurrentDocument().id; + const importer = createCanvasImport(() => true); + + await importer.importFile(docFile()); + importer.cancel(); + + expect(importer.pending).toBeNull(); + expect(appStore.getCurrentDocument().id).toBe(before); + }); + + it('reports unreadable files and can dismiss the message', async () => { + const before = appStore.getCurrentDocument().id; + const importer = createCanvasImport(() => false); + + await importer.importFile(file('bad.json', 'nope')); + expect(importer.error).toMatch(/not valid JSON/); + expect(appStore.getCurrentDocument().id).toBe(before); + + importer.dismissError(); + expect(importer.error).toBe(''); + }); + + it('asks the canvas state at import time, not at creation time', async () => { + let hasContent = false; + const importer = createCanvasImport(() => hasContent); + + hasContent = true; + await importer.importFile(docFile()); + + expect(importer.pending).not.toBeNull(); + }); +}); diff --git a/src/lib/canvas/canvasImport.svelte.ts b/src/lib/canvas/canvasImport.svelte.ts new file mode 100644 index 0000000..a394adb --- /dev/null +++ b/src/lib/canvas/canvasImport.svelte.ts @@ -0,0 +1,48 @@ +import { appStore } from '../stores/appStore.svelte.ts'; +import type { DocumentData } from '../types/canvas'; +import { readSingleDocument } from '../utils/documentFile'; +import { uuidv4 } from '../utils/uuid'; + +/** + * Importing a document file into the editor, replacing whatever is on the canvas. + * If the canvas has content the user is asked to confirm first. + */ +export function createCanvasImport(hasContent: () => boolean) { + let pending = $state(null); + let error = $state(''); + + function load(document: DocumentData) { + // New id: saving must not silently overwrite a saved document that has the same id + appStore.setCurrentDocument({ ...document, id: uuidv4() }); + appStore.selectElement(null); + pending = null; + } + + return { + /** A document waiting for the user to confirm replacing the canvas */ + get pending() { + return pending; + }, + get error() { + return error; + }, + async importFile(file: File) { + try { + const document = await readSingleDocument(file); + if (hasContent()) pending = document; + else load(document); + } catch (e) { + error = e instanceof Error ? e.message : 'The file could not be imported.'; + } + }, + confirm() { + if (pending) load(pending); + }, + cancel() { + pending = null; + }, + dismissError() { + error = ''; + } + }; +} diff --git a/src/lib/canvas/clipboard.browser.spec.ts b/src/lib/canvas/clipboard.browser.spec.ts new file mode 100644 index 0000000..ea425a6 --- /dev/null +++ b/src/lib/canvas/clipboard.browser.spec.ts @@ -0,0 +1,288 @@ +// Runs in Chromium: real clipboard events with a DataTransfer +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { appStore } from '../stores/appStore.svelte.ts'; +import { CLIPBOARD_TYPE } from '../utils/clipboard'; +import { clipboard } from './clipboard.svelte'; + +let pageId: string; +let detach: () => void; + +const shapeCount = () => Object.keys(appStore.getPages()[pageId].elements).length; +const ids = () => appStore.getSelectedElements().map((el) => el.id); + +function add(type: 'shape' | 'text', x: number, y: number) { + appStore.addElement({ type, x, y, pageId, width: 200, height: 100 }); + return appStore.getSelectedElement()!; +} + +/** Fire a clipboard event on the document, like the browser does for Ctrl+C / X / V. */ +function fire( + type: 'copy' | 'cut' | 'paste', + data = new DataTransfer(), + target: EventTarget = document.body +) { + const event = new ClipboardEvent(type, { clipboardData: data, bubbles: true, cancelable: true }); + target.dispatchEvent(event); + return { event, data }; +} + +const wait = (ms = 50) => new Promise((resolve) => setTimeout(resolve, ms)); + +beforeEach(() => { + appStore.initNewDocument(); + pageId = Object.keys(appStore.getPages())[0]; + appStore.setActivePage(null); + window.getSelection()?.removeAllRanges(); + detach = clipboard.attach(); +}); +afterEach(() => detach()); + +describe('copy, cut and paste', () => { + it('copy puts the elements on the clipboard and paste adds copies', () => { + const a = add('shape', 300, 300); + const { event, data } = fire('copy'); + + expect(event.defaultPrevented).toBe(true); + expect(data.getData(CLIPBOARD_TYPE)).toContain('"app":"lienzo"'); + expect(shapeCount()).toBe(1); + + const pasted = fire('paste', data); + expect(pasted.event.defaultPrevented).toBe(true); + expect(shapeCount()).toBe(2); + expect(ids()).toHaveLength(1); + expect(ids()[0]).not.toBe(a.id); // the copy is selected + expect(appStore.getSelectedElement()).toMatchObject({ x: 340, y: 340 }); // offset from the original + }); + + it('further pastes of the same copy move a little more each time', () => { + add('shape', 300, 300); + const { data } = fire('copy'); + + fire('paste', data); + const first = appStore.getSelectedElement()!; + fire('paste', data); + const second = appStore.getSelectedElement()!; + + expect([first.x, second.x]).toEqual([340, 380]); + expect(shapeCount()).toBe(3); + }); + + it('also puts readable text on the clipboard', () => { + const t = add('text', 300, 300); + appStore.updateElement({ elementId: t.id, updates: { text: 'Hello world' }, pageId }); + const { data } = fire('copy'); + expect(data.getData('text/plain')).toBe('Hello world'); + }); + + it('cut removes the elements and paste brings them back', () => { + add('shape', 300, 300); + const { data } = fire('cut'); + + expect(shapeCount()).toBe(0); + fire('paste', data); + expect(shapeCount()).toBe(1); + expect(appStore.getSelectedElement()).toMatchObject({ x: 300, y: 300 }); // back where it was, not offset + }); + + it('copies a group as a group, under a new group id', () => { + const a = add('shape', 300, 300); + const b = add('shape', 600, 300); + appStore.selectElements(pageId, [a.id, b.id]); + appStore.groupSelected(); + const original = appStore.findElement(pageId, a.id)!.groupId; + + const { data } = fire('copy'); + fire('paste', data); + + const pasted = appStore.getSelectedElements(); + expect(pasted).toHaveLength(2); + expect(pasted[0].groupId).toBeTruthy(); + expect(pasted[0].groupId).toBe(pasted[1].groupId); + expect(pasted[0].groupId).not.toBe(original); + expect(pasted[1].x - pasted[0].x).toBe(300); + }); + + it('pastes onto the page that was last clicked', () => { + add('shape', 300, 300); + const { data } = fire('copy'); + appStore.addPage(); + const other = Object.keys(appStore.getPages()).find((id) => id !== pageId)!; + + appStore.setActivePage(other); + fire('paste', data); + + expect(Object.keys(appStore.getPages()[other].elements)).toHaveLength(1); + expect(appStore.getSelectedElement()).toMatchObject({ pageId: other, x: 300, y: 300 }); // same spot on another page + }); + + it('pastes onto the first page when nothing was clicked and no page is on screen', () => { + add('shape', 300, 300); + const { data } = fire('copy'); + appStore.addPage(); + fire('paste', data); + expect(appStore.getSelectedElement()?.pageId).toBe(pageId); + }); + + it('works without the custom clipboard format, using the text left with it', () => { + const t = add('text', 300, 300); + appStore.updateElement({ elementId: t.id, updates: { text: 'Same text' }, pageId }); + const { data } = fire('copy'); + + const plainOnly = new DataTransfer(); + plainOnly.setData('text/plain', data.getData('text/plain')); // a browser that drops custom formats + fire('paste', plainOnly); + + expect(shapeCount()).toBe(2); + }); + + it('leaves other pastes alone', () => { + add('shape', 300, 300); + const other = new DataTransfer(); + other.setData('text/plain', 'something copied elsewhere'); + + const { event } = fire('paste', other); + + expect(event.defaultPrevented).toBe(false); + expect(shapeCount()).toBe(1); + }); + + it('ignores clipboard content that is not valid', () => { + const bad = new DataTransfer(); + bad.setData( + CLIPBOARD_TYPE, + '{"app":"lienzo","kind":"elements","version":1,"elements":[{"x":1}]}' + ); + const { event } = fire('paste', bad); + expect(event.defaultPrevented).toBe(false); + expect(shapeCount()).toBe(0); + }); + + it('does nothing with nothing selected', () => { + const { event, data } = fire('copy'); + expect(event.defaultPrevented).toBe(false); + expect(data.getData(CLIPBOARD_TYPE)).toBe(''); + }); + + it('leaves copy, cut and paste alone while typing in a field', () => { + add('shape', 300, 300); + const input = document.createElement('textarea'); + document.body.appendChild(input); + + const copy = fire('copy', new DataTransfer(), input); + const cut = fire('cut', new DataTransfer(), input); + const data = new DataTransfer(); + data.setData(CLIPBOARD_TYPE, '{}'); + const paste = fire('paste', data, input); + + expect([ + copy.event.defaultPrevented, + cut.event.defaultPrevented, + paste.event.defaultPrevented + ]).toEqual([false, false, false]); + expect(shapeCount()).toBe(1); + input.remove(); + }); + + it('is one change for autosave', () => { + add('shape', 300, 300); + const { data } = fire('copy'); + const before = appStore.getRevision(); + fire('paste', data); + expect(appStore.getRevision()).toBe(before + 1); + }); +}); + +describe('duplicate', () => { + it('copies the selection right away, a little to the side', () => { + const a = add('shape', 300, 300); + + clipboard.duplicate(); + + expect(shapeCount()).toBe(2); + expect(ids()[0]).not.toBe(a.id); + expect(appStore.getSelectedElement()).toMatchObject({ x: 340, y: 340 }); + + clipboard.duplicate(); // duplicating the copy moves on again + expect(appStore.getSelectedElement()).toMatchObject({ x: 380, y: 380 }); + }); + + it('does nothing with nothing selected', () => { + clipboard.duplicate(); + expect(shapeCount()).toBe(0); + }); +}); + +describe('the buttons', () => { + it('Copy then Paste works through the clipboard events the browser fires', async () => { + add('shape', 300, 300); + // the browser may refuse execCommand in a test: the copy is then kept for this tab + clipboard.copy(); + await clipboard.paste(); + expect(shapeCount()).toBe(2); + }); + + it('Cut removes the elements', () => { + add('shape', 300, 300); + clipboard.cut(); + expect(shapeCount()).toBe(0); + }); +}); + +describe('pasting pictures', () => { + async function pngFile(width = 40, height = 20) { + const canvas = new OffscreenCanvas(width, height); + const context = canvas.getContext('2d')!; + context.fillStyle = '#dc2626'; + context.fillRect(0, 0, width, height); + return new File([await canvas.convertToBlob({ type: 'image/png' })], 'shot.png', { + type: 'image/png' + }); + } + + it('a picture on the clipboard becomes an image element', async () => { + const data = new DataTransfer(); + data.items.add(await pngFile()); + + const { event } = fire('paste', data); + expect(event.defaultPrevented).toBe(true); + await vi.waitFor(() => expect(shapeCount()).toBe(1)); + + const image = appStore.getSelectedElement()!; + expect(image).toMatchObject({ type: 'image', alt: 'shot.png', width: 40, height: 20 }); + expect((image as { src: string }).src).toMatch(/^data:image\/png;base64,/); + }); + + it('several pictures become several elements, each a little further along', async () => { + const data = new DataTransfer(); + data.items.add(await pngFile()); + data.items.add(await pngFile(60, 30)); + fire('paste', data); + await vi.waitFor(() => expect(shapeCount()).toBe(2)); + + const [first, second] = appStore.getSelectedElements(); + expect(first.y).not.toBe(second.y); + }); + + it('a picture that cannot be read is reported, and nothing is added', async () => { + const alerts = vi.spyOn(window, 'alert').mockImplementation(() => {}); + const data = new DataTransfer(); + data.items.add(new File(['not a picture'], 'broken.png', { type: 'image/png' })); + + fire('paste', data); + await vi.waitFor(() => expect(alerts).toHaveBeenCalled()); + + expect(shapeCount()).toBe(0); + alerts.mockRestore(); + }); + + it('elements win when the clipboard has both elements and a picture', async () => { + add('shape', 300, 300); + const { data } = fire('copy'); + data.items.add(await pngFile()); + + fire('paste', data); + await wait(); + + expect(shapeCount()).toBe(2); // the copied element, not an extra picture + }); +}); diff --git a/src/lib/canvas/clipboard.svelte.ts b/src/lib/canvas/clipboard.svelte.ts new file mode 100644 index 0000000..952b7dc --- /dev/null +++ b/src/lib/canvas/clipboard.svelte.ts @@ -0,0 +1,176 @@ +import { appStore } from '../stores/appStore.svelte.ts'; +import type { ImageElement } from '../types/canvas'; +import { + CLIPBOARD_TYPE, + createPayload, + parsePayload, + pastedElements, + pastedImageRect, + plainText, + type ClipboardPayload +} from '../utils/clipboard'; +import { targetPageId } from './targetPage'; +import { readImageFile } from '../utils/imageFile'; +import { getDefaultProperties } from '../utils/properties'; + +const MAX_PICTURES = 10; + +/** The last thing copied in this tab: pasting works from it too, e.g. from a button, where the browser gives no clipboard. */ +let memory: { payload: ClipboardPayload; text: string } | null = null; +/** How often each copy was pasted, to move every paste a little further */ +const pasteCounts: Record = {}; +let pictureCount = 0; + +/** A field where typing, copying and pasting must keep working normally. */ +const isEditable = (target: EventTarget | null) => + target instanceof Element && + !!target.closest('input, textarea, select, [contenteditable="true"]'); + +/** Is some text selected on the page? Then copying means copying that. */ +const hasTextSelection = () => !!window.getSelection()?.toString(); + +function remember(cut = false) { + const selected = appStore.getSelectedElements(); + if (!selected.length) return null; + memory = { + payload: createPayload(selected, cut ? '' : selected[0].pageId), + text: plainText(selected) + }; + return memory; +} + +function pastePayload(payload: ClipboardPayload) { + const pageId = targetPageId(); + const page = pageId ? appStore.getPages()[pageId] : null; + if (!pageId || !page) return false; + + const index = pasteCounts[payload.copyId] ?? 0; + pasteCounts[payload.copyId] = index + 1; + appStore.addElements(pageId, pastedElements(payload, page, index)); + return true; +} + +/** Pictures from the clipboard (a screenshot, a copied image) become image elements. */ +async function pastePictures(files: File[]) { + const pageId = targetPageId(); + const page = pageId ? appStore.getPages()[pageId] : null; + if (!pageId || !page) return; + + const added: ImageElement[] = []; + for (const file of files.slice(0, MAX_PICTURES)) { + try { + const image = await readImageFile(file); + const rect = pastedImageRect(image, page, pictureCount++); + added.push({ + ...(getDefaultProperties({ type: 'image', pageId, ...rect }) as ImageElement), + src: image.src, + alt: file.name || 'Pasted image' + }); + } catch (error) { + console.error('Could not paste the picture: ', error); + alert(error instanceof Error ? error.message : 'The picture could not be pasted.'); + } + } + if (added.length) appStore.addElements(pageId, added); +} + +function onCopy(event: ClipboardEvent, cut = false) { + if (isEditable(event.target) || hasTextSelection() || !event.clipboardData) return; + const pageId = appStore.getSelectedElements()[0]?.pageId; + const copied = remember(cut); + if (!copied) return; + + event.clipboardData.setData(CLIPBOARD_TYPE, JSON.stringify(copied.payload)); + event.clipboardData.setData('text/plain', copied.text); + event.preventDefault(); + if (cut) { + appStore.deleteElements( + copied.payload.elements.map((el) => el.id), + pageId + ); + } +} + +function onPaste(event: ClipboardEvent) { + if (isEditable(event.target) || hasTextSelection() || !event.clipboardData) return; + const data = event.clipboardData; + + // Elements copied in Lienzo (maybe in another tab or document) + let payload = parsePayload(data.getData(CLIPBOARD_TYPE)); + // The browser may not hand over custom formats: the text we put alongside identifies our last copy + if (!payload && memory && data.getData('text/plain') === memory.text) payload = memory.payload; + if (payload) { + event.preventDefault(); + pastePayload(payload); + return; + } + + const pictures = Array.from(data.files).filter((file) => file.type.startsWith('image/')); + if (pictures.length) { + event.preventDefault(); + void pastePictures(pictures); + } +} + +/** Ask the browser to copy, so the system clipboard is filled too; works from a click. */ +function copyViaBrowser(cut: boolean) { + if (!appStore.getSelectedElements().length) return; + const handler = (event: ClipboardEvent) => onCopy(event, cut); + document.addEventListener('copy', handler, { once: true }); + if (!document.execCommand('copy')) { + document.removeEventListener('copy', handler); + remember(cut); // no system clipboard: keep it for pasting in this tab + if (cut) { + const selected = appStore.getSelectedElements(); + appStore.deleteElements( + selected.map((el) => el.id), + selected[0].pageId + ); + } + } +} + +export const clipboard = { + copy: () => copyViaBrowser(false), + cut: () => copyViaBrowser(true), + + /** Copy the selection and paste it right away, a little to the side. */ + duplicate() { + const selected = appStore.getSelectedElements(); + if (!selected.length) return; + const page = appStore.getPages()[selected[0].pageId]; + appStore.addElements(page.id, pastedElements(createPayload(selected, page.id), page, 0)); + }, + + /** Paste from this tab's last copy, or a picture on the system clipboard (the browser may ask first). */ + async paste() { + if (memory) { + pastePayload(memory.payload); + return; + } + try { + const files: File[] = []; + for (const item of await navigator.clipboard.read()) { + const type = item.types.find((t) => t.startsWith('image/')); + if (type) files.push(new File([await item.getType(type)], 'Pasted image', { type })); + } + await pastePictures(files); + } catch { + // no permission, or nothing there: nothing to paste + } + }, + + /** Listen for copy, cut and paste anywhere on the page. Returns a function that stops listening. */ + attach() { + const copy = (event: ClipboardEvent) => onCopy(event); + const cut = (event: ClipboardEvent) => onCopy(event, true); + document.addEventListener('copy', copy); + document.addEventListener('cut', cut); + document.addEventListener('paste', onPaste); + return () => { + document.removeEventListener('copy', copy); + document.removeEventListener('cut', cut); + document.removeEventListener('paste', onPaste); + }; + } +}; diff --git a/src/lib/canvas/elementDrag.svelte.ts b/src/lib/canvas/elementDrag.svelte.ts new file mode 100644 index 0000000..97afb27 --- /dev/null +++ b/src/lib/canvas/elementDrag.svelte.ts @@ -0,0 +1,293 @@ +import { appStore } from '../stores/appStore.svelte.ts'; +import type { DocumentPage, TCanvasElement } from '../types/canvas'; +import { placeOnPage } from '../utils/pageMove'; +import { pageDrop } from './pageDrop.svelte'; +import { + boundingRect, + dragPosition, + findElementAt, + pointInRect, + type Point, + type Size +} from '../utils/geometry'; +import { eventPoint, trackPointer } from './pointer'; + +interface Options { + getCanvas: () => HTMLElement | undefined; + getPage: () => DocumentPage; + /** The canvas size in page pixels (not screen pixels) */ + getSize: () => Size; + /** The element that would become the parent if dropped now, or null */ + onHover: (elementId: string | null) => void; +} + +/** Pointer movement (screen pixels) below which a press counts as a click, not a drag */ +const CLICK_SLOP = 3; + +interface Session { + elementId: string; + pageId: string; + /** Every element that moves: just the dragged one, or the whole selection */ + items: Array<{ id: string; origin: Point }>; + elements: TCanvasElement[]; // as they were when the drag started + origin: Point; // where the element (or the selection's bounding box) started, in page pixels + size: Size; + pointerStart: Point; // screen pixels + /** Where the pointer started on the page, in page pixels (survives scrolling, unlike screen pixels) */ + startInPage: Point; + pointer: Point; // latest screen pixels + /** Another page the pointer is over, and where the elements would land on it */ + crossing: { pageId: string; updates: Record> } | null; + frame: number | null; + scrollFrame: number | null; + stop: () => void; +} + +/** Scroll the page list while dragging near its top or bottom edge, so far pages can be reached. */ +const SCROLL_ZONE_TOP = 140; // the header covers the top of the list +const SCROLL_ZONE_BOTTOM = 100; +const MAX_SCROLL_SPEED = 24; + +/** + * Dragging an element with the mouse or a finger: moves it within the page boundaries, + * highlights the element it would be dropped into, and re-parents it on release. + */ +export function createElementDrag(options: Options) { + let isDragging = $state(false); + let session: Session | null = null; + let moved = false; + + /** A point on the screen as a point on a page canvas, in page pixels. */ + function toPage(point: Point, canvas: HTMLElement): Point { + const rect = canvas.getBoundingClientRect(); + const { width, height } = options.getSize(); + return { + x: (point.x - rect.left) * (width / rect.width), + y: (point.y - rect.top) * (height / rect.height) + }; + } + + /** Another page of the document under the pointer, if any. */ + function otherPageAt(point: Point): { pageId: string; canvas: HTMLElement } | null { + for (const id of Object.keys(appStore.getPages())) { + if (id === session?.pageId) continue; + const canvas = document.getElementById(`canvas-${id}`); + if (canvas && pointInRect(point, canvas.getBoundingClientRect())) + return { pageId: id, canvas }; + } + return null; + } + + /** Move the element to where the pointer is now. */ + function apply() { + const canvas = options.getCanvas(); + if (!session || !canvas) return; + + const page = options.getPage(); + + // Over another page: leave the elements where they were and show where they would land + const other = otherPageAt(session.pointer); + if (other) { + const grab = { + x: session.startInPage.x - session.origin.x, + y: session.startInPage.y - session.origin.y + }; + const pointer = toPage(session.pointer, other.canvas); + const { updates, rects } = placeOnPage( + session.elements, + { x: pointer.x - grab.x, y: pointer.y - grab.y }, + appStore.getPages()[other.pageId].boundaries + ); + if (!session.crossing) { + appStore.moveElements( + session.pageId, + Object.fromEntries(session.items.map((item) => [item.id, item.origin])) + ); + } + session.crossing = { pageId: other.pageId, updates }; + pageDrop.set(other.pageId, rects); + options.onHover(null); + return; + } + if (session.crossing) { + session.crossing = null; + pageDrop.clear(); + } + + const pointerInPage = toPage(session.pointer, canvas); + const delta = { + x: pointerInPage.x - session.startInPage.x, + y: pointerInPage.y - session.startInPage.y + }; + const position = dragPosition(session.origin, delta, session.size, page.boundaries); + + // A group moves as one box: no re-parenting + if (session.items.length > 1) { + const dx = position.x - session.origin.x; + const dy = position.y - session.origin.y; + options.onHover(null); + appStore.moveElements( + session.pageId, + Object.fromEntries( + session.items.map((item) => [item.id, { x: item.origin.x + dx, y: item.origin.y + dy }]) + ) + ); + return; + } + + // The element under the dragged element's centre is the future parent + const parent = findElementAt( + Object.values(page.elements), + { x: position.x + session.size.width / 2, y: position.y + session.size.height / 2 }, + session.elementId + ); + options.onHover(parent ? parent.id : null); + + appStore.updateElement({ + elementId: session.elementId, + updates: position, + pageId: session.pageId + }); + } + + /** Apply the latest pointer position at most once per animation frame. */ + function schedule() { + if (!session || session.frame !== null) return; + session.frame = requestAnimationFrame(() => { + if (session) session.frame = null; + apply(); + }); + } + + /** While the pointer is near the top or bottom of the page list, keep scrolling it. */ + function autoScroll() { + if (!session) return; + const container = document.querySelector('[data-testid="canvas-container"]'); + if (container) { + const bounds = container.getBoundingClientRect(); + const y = session.pointer.y; + let speed = 0; + if (y < bounds.top + SCROLL_ZONE_TOP) speed = -(bounds.top + SCROLL_ZONE_TOP - y) / 4; + else if (y > bounds.bottom - SCROLL_ZONE_BOTTOM) + speed = (y - (bounds.bottom - SCROLL_ZONE_BOTTOM)) / 4; + speed = Math.max(-MAX_SCROLL_SPEED, Math.min(MAX_SCROLL_SPEED, speed)); + + const before = container.scrollTop; + if (speed) container.scrollTop += speed; + if (container.scrollTop !== before) apply(); // the pages moved under the pointer + } + session.scrollFrame = requestAnimationFrame(autoScroll); + } + + function teardown() { + if (session?.frame != null) cancelAnimationFrame(session.frame); + if (session?.scrollFrame != null) cancelAnimationFrame(session.scrollFrame); + pageDrop.clear(); + session?.stop(); + session = null; + isDragging = false; + options.onHover(null); + document.body.style.userSelect = ''; + document.body.style.touchAction = ''; + } + + /** The pointer was released: land the element and make it a child of what is under it. */ + function finish() { + if (!session) return; + apply(); // the last move may not have had its animation frame yet + + // Dropped on another page: move the elements there + if (session.crossing) { + appStore.moveElementsToPage( + session.pageId, + session.crossing.pageId, + session.crossing.updates + ); + teardown(); + return; + } + + const { elementId, pageId } = session; + const latest = session.items.length === 1 ? appStore.findElement(pageId, elementId) : null; + if (latest) { + const parent = findElementAt( + Object.values(options.getPage().elements), + { x: latest.x + latest.width / 2, y: latest.y + latest.height / 2 }, + latest.id + ); + appStore.moveElement({ + pageId: latest.pageId, + elementId: latest.id, + newParentId: parent ? parent.id : null, + newX: latest.x, + newY: latest.y + }); + + const updated = appStore.findElement(latest.pageId, latest.id); + if (updated) appStore.selectElement(updated); + } + teardown(); + } + + function start(event: PointerEvent | TouchEvent, element: TCanvasElement) { + event.stopPropagation(); + if (session) teardown(); + + // Dragging a selected element moves the whole selection; any other element is selected first + // (with the rest of its group, if it has one) + if (!appStore.isSelected(element.id)) appStore.selectElement(element); + const selected = appStore.getSelectedElements(); + const moving = selected.length ? selected : [element]; + const box = boundingRect(moving)!; + + const pointer = eventPoint(event); + isDragging = true; + moved = false; + session = { + elementId: element.id, + pageId: element.pageId, + items: moving.map((el) => ({ id: el.id, origin: { x: el.x, y: el.y } })), + elements: moving, + origin: { x: box.x, y: box.y }, + size: { width: box.width, height: box.height }, + pointerStart: pointer, + startInPage: options.getCanvas() ? toPage(pointer, options.getCanvas()!) : { x: 0, y: 0 }, + pointer, + crossing: null, + frame: null, + scrollFrame: null, + stop: trackPointer({ + onMove: (point) => { + if (!session) return; + session.pointer = point; + if ( + Math.abs(point.x - session.pointerStart.x) > CLICK_SLOP || + Math.abs(point.y - session.pointerStart.y) > CLICK_SLOP + ) { + moved = true; + } + schedule(); + }, + onEnd: finish + }) + }; + document.body.style.userSelect = 'none'; + document.body.style.touchAction = 'none'; + session.scrollFrame = requestAnimationFrame(autoScroll); + } + + return { + get isDragging() { + return isDragging; + }, + start, + /** Was there a drag since the last call? The click that ends a drag must not change the selection. */ + consumeMoved() { + const wasMoved = moved; + moved = false; + return wasMoved; + }, + /** Abort the drag (Escape): the element stays where it is, without re-parenting. */ + cancel: teardown + }; +} diff --git a/src/lib/canvas/elementInteractions.browser.spec.ts b/src/lib/canvas/elementInteractions.browser.spec.ts new file mode 100644 index 0000000..66a8f35 --- /dev/null +++ b/src/lib/canvas/elementInteractions.browser.spec.ts @@ -0,0 +1,659 @@ +// Runs in Chromium (real DOM events), see the "client" project in vite.config.ts +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { appStore } from '../stores/appStore.svelte.ts'; +import type { ResizeDirection, TCanvasElement } from '../types/canvas'; +import { createElementDrag } from './elementDrag.svelte'; +import { createElementResize } from './elementResize.svelte'; +import { createGroupResize } from './groupResize.svelte'; +import { createMarquee } from './marquee.svelte'; +import { pageDrop } from './pageDrop.svelte'; + +// The canvas is 1000x1000 screen pixels showing a 2000x2000 page: every screen pixel is 2 page pixels. +const SIZE = { width: 2000, height: 2000 }; + +let canvas: HTMLDivElement; +let pageId: string; +let hovered: Array; + +const frame = () => new Promise((resolve) => requestAnimationFrame(() => resolve())); +const frames = async () => { + await frame(); + await frame(); +}; + +function pointerEvent(type: string, x: number, y: number) { + return new PointerEvent(type, { clientX: x, clientY: y, bubbles: true, cancelable: true }); +} +const move = (x: number, y: number) => document.dispatchEvent(pointerEvent('pointermove', x, y)); +const release = () => document.dispatchEvent(pointerEvent('pointerup', 0, 0)); + +function touchEvent(type: string, x: number, y: number) { + const touch = new Touch({ identifier: 1, target: document.body, clientX: x, clientY: y }); + const active = type === 'touchend' || type === 'touchcancel' ? [] : [touch]; + return new TouchEvent(type, { touches: active, changedTouches: [touch], bubbles: true }); +} + +/** Add a shape through the store and return it. */ +function addShape(x: number, y: number, width: number, height: number): TCanvasElement { + appStore.addElement({ type: 'shape', x, y, pageId, width, height }); + return appStore.getSelectedElement()!; +} +const current = (element: TCanvasElement) => appStore.findElement(pageId, element.id)!; + +const options = () => ({ + getCanvas: () => canvas, + getPage: () => appStore.getPages()[pageId], + getSize: () => SIZE +}); + +beforeEach(() => { + appStore.initNewDocument(); + pageId = Object.keys(appStore.getPages())[0]; + hovered = []; + + canvas = document.createElement('div'); + canvas.style.cssText = 'position:fixed;left:0;top:0;width:1000px;height:1000px'; + document.body.appendChild(canvas); +}); + +afterEach(() => { + canvas.remove(); + document.body.style.userSelect = ''; + document.body.style.touchAction = ''; +}); + +describe('createElementDrag', () => { + const makeDrag = () => createElementDrag({ ...options(), onHover: (id) => hovered.push(id) }); + + it('moves the element by the pointer movement, scaled to page pixels', async () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 50, 50), el); + move(100, 80); + await frames(); + + expect(current(el)).toMatchObject({ x: 400, y: 360 }); // +50*2, +30*2 + release(); + }); + + it('keeps the element inside the page boundaries', async () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + const { horizontal, vertical } = appStore.getPages()[pageId].boundaries; + + drag.start(pointerEvent('pointerdown', 0, 0), el); + move(100000, 100000); + await frames(); + expect(current(el).x).toBe(horizontal.end - 100); + expect(current(el).y).toBe(vertical.end - 100); + + move(-100000, -100000); + await frames(); + expect(current(el)).toMatchObject({ x: horizontal.start, y: vertical.start }); + release(); + }); + + it('applies the final position on release even before an animation frame ran', () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 0, 0), el); + move(50, 50); + release(); + + expect(current(el)).toMatchObject({ x: 400, y: 400 }); + }); + + it('tracks the drag state and locks text selection and touch scrolling meanwhile', () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + expect(drag.isDragging).toBe(false); + + drag.start(pointerEvent('pointerdown', 0, 0), el); + expect(drag.isDragging).toBe(true); + expect(document.body.style.userSelect).toBe('none'); + expect(document.body.style.touchAction).toBe('none'); + + release(); + expect(drag.isDragging).toBe(false); + expect(document.body.style.userSelect).toBe(''); + expect(document.body.style.touchAction).toBe(''); + }); + + it('stops listening after the release', async () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 0, 0), el); + release(); + const landed = { ...current(el) }; + move(500, 500); + await frames(); + + expect(current(el)).toMatchObject({ x: landed.x, y: landed.y }); + }); + + it('makes the element a child of the one under its centre, and highlights it while dragging', async () => { + const parent = addShape(1000, 1000, 400, 400); + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + // move the centre (350,350) to (1200,1200): +850 page px = 425 screen px + drag.start(pointerEvent('pointerdown', 0, 0), el); + move(425, 425); + await frames(); + expect(hovered).toContain(parent.id); + + release(); + expect(current(el).parentElementId).toBe(parent.id); + expect(hovered.at(-1)).toBeNull(); + expect(appStore.getSelectedElement()?.id).toBe(el.id); + }); + + it('leaves the element without a parent when dropped on empty space', () => { + addShape(1000, 1000, 400, 400); + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 0, 0), el); + move(10, 10); + release(); + + expect(current(el).parentElementId ?? null).toBeNull(); + }); + + it('cancel() aborts without re-parenting and ignores further movement', async () => { + const parent = addShape(1000, 1000, 400, 400); + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 0, 0), el); + move(425, 425); + await frames(); + const where = { x: current(el).x, y: current(el).y }; + + drag.cancel(); + move(0, 0); + release(); + await frames(); + + expect(drag.isDragging).toBe(false); + expect(current(el)).toMatchObject(where); + expect(current(el).parentElementId ?? null).toBeNull(); + expect(parent.id).not.toBe(current(el).parentElementId); + expect(document.body.style.userSelect).toBe(''); + }); + + it('works with touch', async () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(touchEvent('touchstart', 50, 50), el); + document.dispatchEvent(touchEvent('touchmove', 100, 80)); + await frames(); + expect(current(el)).toMatchObject({ x: 400, y: 360 }); + + document.dispatchEvent(touchEvent('touchend', 100, 80)); + expect(drag.isDragging).toBe(false); + }); + + it('ends the drag when the touch is cancelled', () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(touchEvent('touchstart', 0, 0), el); + document.dispatchEvent(touchEvent('touchcancel', 0, 0)); + + expect(drag.isDragging).toBe(false); + }); + + describe('with several elements selected', () => { + it('moves them all together by the same amount', async () => { + const a = addShape(300, 300, 100, 100); + const b = addShape(600, 500, 100, 100); + appStore.selectElements(pageId, [a.id, b.id]); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 0, 0), a); + move(50, 30); + await frames(); + + expect(current(a)).toMatchObject({ x: 400, y: 360 }); + expect(current(b)).toMatchObject({ x: 700, y: 560 }); + release(); + expect(appStore.getSelectedElements().map((el) => el.id)).toEqual([a.id, b.id]); + }); + + it('keeps the whole group inside the boundaries, preserving the distance between elements', async () => { + const a = addShape(300, 300, 100, 100); + const b = addShape(600, 500, 100, 100); + appStore.selectElements(pageId, [a.id, b.id]); + const { horizontal } = appStore.getPages()[pageId].boundaries; + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 0, 0), a); + move(100000, 0); + await frames(); + + expect(current(b).x).toBe(horizontal.end - 100); // the rightmost element reaches the edge + expect(current(b).x - current(a).x).toBe(300); + release(); + }); + + it('dragging a member of a group moves the whole group, even when it is not selected', async () => { + const a = addShape(300, 300, 100, 100); + const b = addShape(600, 500, 100, 100); + const c = addShape(900, 900, 100, 100); + appStore.selectElements(pageId, [a.id, b.id]); + appStore.groupSelected(); + appStore.selectElement(c); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 0, 0), a); + move(50, 30); + await frames(); + + expect(current(a)).toMatchObject({ x: 400, y: 360 }); + expect(current(b)).toMatchObject({ x: 700, y: 560 }); + expect(current(c)).toMatchObject({ x: 900, y: 900 }); + release(); + }); + + it('dragging an element outside the selection selects just that element', async () => { + const a = addShape(300, 300, 100, 100); + const b = addShape(600, 500, 100, 100); + const c = addShape(900, 900, 100, 100); + appStore.selectElements(pageId, [a.id, b.id]); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 0, 0), c); + move(10, 0); + await frames(); + + expect(current(c).x).toBe(920); + expect(current(a).x).toBe(300); + expect(appStore.getSelectedElements().map((el) => el.id)).toEqual([c.id]); + release(); + }); + }); + + it('tells a click from a drag', async () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 10, 10), el); + move(11, 11); + release(); + expect(drag.consumeMoved()).toBe(false); + + drag.start(pointerEvent('pointerdown', 10, 10), el); + move(40, 40); + release(); + expect(drag.consumeMoved()).toBe(true); + expect(drag.consumeMoved()).toBe(false); // read once + }); +}); + +describe('createElementResize', () => { + const rect = (el: TCanvasElement) => { + const { x, y, width, height } = current(el); + return { x, y, width, height }; + }; + const startResize = (el: TCanvasElement, direction: ResizeDirection, x = 0, y = 0) => { + const resize = createElementResize(options()); + resize.start(pointerEvent('pointerdown', x, y), el, direction); + return resize; + }; + + it('grows from the south-east handle by the scaled pointer movement', async () => { + const el = addShape(300, 300, 200, 200); + startResize(el, 'se'); + + move(25, 10); + await frames(); + + expect(rect(el)).toEqual({ x: 300, y: 300, width: 250, height: 220 }); + release(); + }); + + it('moves the origin with the north-west handle', async () => { + const el = addShape(300, 300, 200, 200); + startResize(el, 'nw'); + + move(-10, -5); + await frames(); + + expect(rect(el)).toEqual({ x: 280, y: 290, width: 220, height: 210 }); + release(); + }); + + it('never shrinks below the minimum size', async () => { + const el = addShape(300, 300, 200, 200); + startResize(el, 'se'); + + move(-5000, -5000); + await frames(); + + expect(rect(el)).toMatchObject({ width: 20, height: 20 }); + release(); + }); + + it('applies the final size on release even before an animation frame ran', () => { + const el = addShape(300, 300, 200, 200); + startResize(el, 'se'); + + move(50, 0); + release(); + + expect(rect(el).width).toBe(300); + }); + + it('tracks the resize state and restores the body styles it changed', () => { + document.body.style.userSelect = 'text'; + document.body.style.touchAction = 'pan-y'; + const el = addShape(300, 300, 200, 200); + + const resize = startResize(el, 'se'); + expect(resize.isResizing).toBe(true); + expect(document.body.style.touchAction).toBe('none'); + + release(); + expect(resize.isResizing).toBe(false); + expect(document.body.style.userSelect).toBe('text'); + expect(document.body.style.touchAction).toBe('pan-y'); + }); + + it('stops listening after the release', async () => { + const el = addShape(300, 300, 200, 200); + startResize(el, 'se'); + release(); + const done = rect(el); + + move(500, 500); + await frames(); + + expect(rect(el)).toEqual(done); + }); + + it('works with touch and ends when the touch is cancelled', async () => { + const el = addShape(300, 300, 200, 200); + const resize = createElementResize(options()); + + resize.start(touchEvent('touchstart', 0, 0), el, 'se'); + document.dispatchEvent(touchEvent('touchmove', 25, 25)); + await frames(); + expect(rect(el)).toMatchObject({ width: 250, height: 250 }); + + document.dispatchEvent(touchEvent('touchcancel', 25, 25)); + expect(resize.isResizing).toBe(false); + }); +}); + +describe('createMarquee', () => { + it('selects the elements the box touches while it grows', () => { + const a = addShape(200, 200, 100, 100); + const b = addShape(800, 800, 100, 100); + const far = addShape(1500, 1500, 100, 100); + appStore.selectElement(null); + const marquee = createMarquee(options()); + + marquee.start(pointerEvent('pointerdown', 50, 50), false); // page 100,100 + move(250, 250); // page 500,500 + expect(marquee.box).toEqual({ x: 100, y: 100, width: 400, height: 400 }); + expect(appStore.getSelectedElements().map((el) => el.id)).toEqual([a.id]); + + move(500, 500); // page 1000,1000 + expect(appStore.getSelectedElements().map((el) => el.id)).toEqual([a.id, b.id]); + expect(appStore.isSelected(far.id)).toBe(false); + + release(); + expect(marquee.box).toBeNull(); + expect(marquee.consumeMoved()).toBe(true); + }); + + it('selects a whole group when the box touches one of its members', () => { + const a = addShape(200, 200, 100, 100); + const b = addShape(1500, 1500, 100, 100); + appStore.selectElements(pageId, [a.id, b.id]); + appStore.groupSelected(); + appStore.selectElement(null); + const marquee = createMarquee(options()); + + marquee.start(pointerEvent('pointerdown', 50, 50), false); + move(200, 200); // only touches a + release(); + + expect( + appStore + .getSelectedElements() + .map((el) => el.id) + .sort() + ).toEqual([a.id, b.id].sort()); + }); + + it('adds to the current selection when additive', () => { + const a = addShape(200, 200, 100, 100); + const b = addShape(800, 800, 100, 100); + appStore.selectElement(a); + const marquee = createMarquee(options()); + + marquee.start(pointerEvent('pointerdown', 350, 350), true); + move(500, 500); + + expect( + appStore + .getSelectedElements() + .map((el) => el.id) + .sort() + ).toEqual([a.id, b.id].sort()); + release(); + }); + + it('a press without movement is a click and changes nothing', () => { + const a = addShape(200, 200, 100, 100); + appStore.selectElement(a); + const marquee = createMarquee(options()); + + marquee.start(pointerEvent('pointerdown', 700, 700), false); + move(701, 701); + release(); + + expect(marquee.consumeMoved()).toBe(false); + expect(appStore.getSelectedElements().map((el) => el.id)).toEqual([a.id]); + }); +}); + +describe('createGroupResize', () => { + function addText(x: number, y: number, width: number, height: number, fontSize: number) { + appStore.addElement({ type: 'text', x, y, pageId, width, height }); + const el = appStore.getSelectedElement()!; + appStore.updateElement({ elementId: el.id, updates: { fontSize }, pageId }); + return current(el); + } + + /** Two shapes and a text, 300x100 in total at page 300,300, all selected */ + function setup() { + const a = addShape(300, 300, 100, 100); + const b = addShape(500, 300, 100, 100); + const t = addText(300, 300, 100, 100, 20); + appStore.selectElements(pageId, [a.id, b.id, t.id]); + return { a, b, t, resize: createGroupResize(options()) }; + } + + it('scales positions, sizes and text sizes together from the opposite corner', async () => { + const { a, b, t, resize } = setup(); + + resize.start(pointerEvent('pointerdown', 0, 0), 'se'); + move(75, 25); // page 150, 50: the box (300x100) grows by 1.5 + await frames(); + + expect(current(a)).toMatchObject({ x: 300, y: 300, width: 150, height: 150 }); + expect(current(b)).toMatchObject({ x: 600, y: 300, width: 150, height: 150 }); + expect(current(t)).toMatchObject({ x: 300, y: 300, width: 150, height: 150 }); + expect((current(t) as { fontSize: number }).fontSize).toBe(30); + release(); + }); + + it('works from the top-left corner, keeping the bottom-right in place', async () => { + const { a, b, resize } = setup(); + + resize.start(pointerEvent('pointerdown', 0, 0), 'nw'); + move(-75, -25); + await frames(); + + // anchor is the bottom-right of the box (600, 400) + expect(current(b)).toMatchObject({ x: 450, y: 250, width: 150, height: 150 }); + expect(current(a).x).toBe(600 - 300 * 1.5); + release(); + }); + + it('is one change per move and applies the final position on release', () => { + const { a, resize } = setup(); + resize.start(pointerEvent('pointerdown', 0, 0), 'se'); + move(75, 25); + release(); + + expect(current(a).width).toBe(150); + expect(resize.isResizing).toBe(false); + }); + + it('stays inside the boundaries and above the minimum size', async () => { + const { a, b, resize } = setup(); + const { horizontal } = appStore.getPages()[pageId].boundaries; + + resize.start(pointerEvent('pointerdown', 0, 0), 'se'); + move(100000, 100000); + await frames(); + expect(current(b).x + current(b).width).toBeLessThanOrEqual(horizontal.end); + + move(-100000, -100000); + await frames(); + expect(current(a).width).toBeGreaterThanOrEqual(20); + release(); + }); + + it('does not drift: the result depends on where the pointer is, not on the path', async () => { + const { a, resize } = setup(); + + resize.start(pointerEvent('pointerdown', 0, 0), 'se'); + move(100, 100); + await frames(); + move(75, 25); + await frames(); + + expect(current(a).width).toBe(150); + release(); + }); +}); + +describe('dragging to another page', () => { + let second: HTMLDivElement; + let secondId: string; + + beforeEach(() => { + appStore.addPage(); + secondId = Object.keys(appStore.getPages()).find((id) => id !== pageId)!; + // A second canvas to the right of the first, with the same scale + second = document.createElement('div'); + second.id = `canvas-${secondId}`; + second.style.cssText = 'position:fixed;left:1100px;top:0;width:1000px;height:1000px'; + document.body.appendChild(second); + }); + afterEach(() => { + second.remove(); + pageDrop.clear(); + }); + + const makeDrag = () => createElementDrag({ ...options(), onHover: () => {} }); + + it('shows where the element would land and leaves it in place until it is dropped', async () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 160, 160), el); // grabs it 20 page pixels from its corner + move(1300, 300); + await frames(); + + expect(pageDrop.target?.pageId).toBe(secondId); + expect(pageDrop.target?.rects).toEqual([{ x: 380, y: 580, width: 100, height: 100 }]); + expect(current(el)).toMatchObject({ x: 300, y: 300 }); // still on the first page + release(); + }); + + it('moves the element to the other page when dropped there, and selects it', () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 160, 160), el); + move(1300, 300); + release(); + + expect(appStore.findElement(pageId, el.id)).toBeNull(); + expect(appStore.findElement(secondId, el.id)).toMatchObject({ + pageId: secondId, + x: 380, + y: 580 + }); + expect(appStore.getSelectedElement()).toMatchObject({ id: el.id, pageId: secondId }); + expect(pageDrop.target).toBeNull(); + }); + + it('moves a whole selection, keeping the layout between its elements', () => { + const a = addShape(300, 300, 100, 100); + const b = addShape(500, 400, 100, 100); + appStore.selectElements(pageId, [a.id, b.id]); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 160, 160), a); + move(1300, 300); + release(); + + expect(appStore.findElement(secondId, a.id)).toMatchObject({ x: 380, y: 580 }); + expect(appStore.findElement(secondId, b.id)).toMatchObject({ x: 580, y: 680 }); + }); + + it('dragging back to the first page cancels the move', async () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 160, 160), el); + move(1300, 300); + await frames(); + expect(pageDrop.target).not.toBeNull(); + + move(400, 400); + await frames(); + expect(pageDrop.target).toBeNull(); + release(); + + expect(current(el)).toMatchObject({ pageId, x: 780, y: 780 }); // moved within the first page + }); + + it('cancelling mid-drag leaves the element where it was and clears the preview', async () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 160, 160), el); + move(1300, 300); + await frames(); + drag.cancel(); + + expect(pageDrop.target).toBeNull(); + expect(current(el)).toMatchObject({ x: 300, y: 300 }); + }); + + it('puts the element back when it was moved on the first page before crossing', async () => { + const el = addShape(300, 300, 100, 100); + const drag = makeDrag(); + + drag.start(pointerEvent('pointerdown', 160, 160), el); + move(400, 400); + await frames(); + move(1300, 300); + await frames(); + + expect(current(el)).toMatchObject({ x: 300, y: 300 }); + release(); + }); +}); diff --git a/src/lib/canvas/elementResize.svelte.ts b/src/lib/canvas/elementResize.svelte.ts new file mode 100644 index 0000000..f7dd1f7 --- /dev/null +++ b/src/lib/canvas/elementResize.svelte.ts @@ -0,0 +1,116 @@ +import { appStore } from '../stores/appStore.svelte.ts'; +import type { DocumentPage, ResizeDirection, TCanvasElement } from '../types/canvas'; +import { resizeRect, type Point, type Rect, type Size } from '../utils/geometry'; +import { eventPoint, trackPointer } from './pointer'; + +interface Options { + getCanvas: () => HTMLElement | undefined; + getPage: () => DocumentPage; + /** The canvas size in page pixels (not screen pixels) */ + getSize: () => Size; +} + +interface Session { + element: TCanvasElement; + direction: ResizeDirection; + startRect: Rect; + pointerStart: Point; // screen pixels + pointer: Point; // latest screen pixels + scale: Point; // page pixels per screen pixel + frame: number | null; + stop: () => void; + restoreStyles: () => void; +} + +/** Resizing an element from one of its handles with the mouse or a finger. */ +export function createElementResize(options: Options) { + let isResizing = $state(false); + let session: Session | null = null; + + function apply() { + if (!session) return; + const next = resizeRect( + session.startRect, + session.direction, + { + x: (session.pointer.x - session.pointerStart.x) * session.scale.x, + y: (session.pointer.y - session.pointerStart.y) * session.scale.y + }, + options.getPage().boundaries + ); + appStore.updateElement({ + elementId: session.element.id, + updates: next, + pageId: session.element.pageId + }); + } + + function schedule() { + if (!session || session.frame !== null) return; + session.frame = requestAnimationFrame(() => { + if (session) session.frame = null; + apply(); + }); + } + + function finish() { + if (!session) return; + apply(); // the last move may not have had its animation frame yet + if (session.frame !== null) cancelAnimationFrame(session.frame); + session.stop(); + session.restoreStyles(); + session = null; + isResizing = false; + } + + function start( + event: MouseEvent | PointerEvent | TouchEvent, + element: TCanvasElement, + direction: ResizeDirection + ) { + event.stopPropagation(); + if (session) finish(); + + const canvas = options.getCanvas(); + if (!canvas) return; + + const originalUserSelect = document.body.style.userSelect; + const originalTouchAction = document.body.style.touchAction; + document.body.style.userSelect = ''; + document.body.style.touchAction = 'none'; // Prevent touch scrolling during resize + + const rect = canvas.getBoundingClientRect(); + const { width, height } = options.getSize(); + const pointer = eventPoint(event); + + isResizing = true; + session = { + element, + direction, + startRect: { x: element.x, y: element.y, width: element.width, height: element.height }, + pointerStart: pointer, + pointer, + scale: { x: width / rect.width, y: height / rect.height }, + frame: null, + stop: trackPointer({ + onMove: (point) => { + if (!session) return; + session.pointer = point; + schedule(); + }, + onEnd: finish + }), + restoreStyles: () => { + document.body.style.userSelect = originalUserSelect; + document.body.style.touchAction = originalTouchAction; + } + }; + } + + return { + get isResizing() { + return isResizing; + }, + start + }; +} diff --git a/src/lib/canvas/groupResize.svelte.ts b/src/lib/canvas/groupResize.svelte.ts new file mode 100644 index 0000000..db383c8 --- /dev/null +++ b/src/lib/canvas/groupResize.svelte.ts @@ -0,0 +1,142 @@ +import { appStore } from '../stores/appStore.svelte.ts'; +import type { DocumentPage, TCanvasElement } from '../types/canvas'; +import { + boundingRect, + groupScaleFactor, + minScaleFactor, + oppositeCorner, + scaleRects, + type Corner, + type Point, + type Rect, + type Size +} from '../utils/geometry'; +import { eventPoint, trackPointer } from './pointer'; + +interface Options { + getCanvas: () => HTMLElement | undefined; + getPage: () => DocumentPage; + /** The canvas size in page pixels (not screen pixels) */ + getSize: () => Size; +} + +interface Session { + elements: TCanvasElement[]; // as they were when the resize started + box: Rect; + corner: Corner; + minFactor: number; + pointerStart: Point; // screen pixels + pointer: Point; // latest screen pixels + scale: Point; // page pixels per screen pixel + frame: number | null; + stop: () => void; + restoreStyles: () => void; +} + +const round = (value: number) => Math.round(value * 100) / 100; + +/** + * Resizing the selected elements as one from a corner of their box: positions, sizes and text sizes all + * scale by the same factor, so the group keeps its proportions. + */ +export function createGroupResize(options: Options) { + let isResizing = $state(false); + let session: Session | null = null; + + function apply() { + if (!session) return; + const { elements, box, corner } = session; + const delta = { + x: (session.pointer.x - session.pointerStart.x) * session.scale.x, + y: (session.pointer.y - session.pointerStart.y) * session.scale.y + }; + const factor = groupScaleFactor( + box, + corner, + delta, + options.getPage().boundaries, + session.minFactor + ); + const rects = scaleRects(elements, oppositeCorner(box, corner), factor); + + const updates: Record> = {}; + elements.forEach((el, i) => { + updates[el.id] = { + x: round(rects[i].x), + y: round(rects[i].y), + width: round(rects[i].width), + height: round(rects[i].height), + ...(el.type === 'text' && { fontSize: Math.max(1, Math.round(el.fontSize * factor)) }) + }; + }); + appStore.updateElements(elements[0].pageId, updates); + } + + function schedule() { + if (!session || session.frame !== null) return; + session.frame = requestAnimationFrame(() => { + if (session) session.frame = null; + apply(); + }); + } + + function finish() { + if (!session) return; + apply(); // the last move may not have had its animation frame yet + if (session.frame !== null) cancelAnimationFrame(session.frame); + session.stop(); + session.restoreStyles(); + session = null; + isResizing = false; + } + + function start(event: MouseEvent | PointerEvent | TouchEvent, corner: Corner) { + event.stopPropagation(); + if (session) finish(); + + const canvas = options.getCanvas(); + const elements = appStore.getSelectedElements(); + const box = boundingRect(elements); + if (!canvas || !box) return; + + const originalUserSelect = document.body.style.userSelect; + const originalTouchAction = document.body.style.touchAction; + document.body.style.userSelect = 'none'; + document.body.style.touchAction = 'none'; // Prevent touch scrolling during resize + + const rect = canvas.getBoundingClientRect(); + const { width, height } = options.getSize(); + const pointer = eventPoint(event); + + isResizing = true; + session = { + elements, + box, + corner, + minFactor: minScaleFactor(elements), + pointerStart: pointer, + pointer, + scale: { x: width / rect.width, y: height / rect.height }, + frame: null, + stop: trackPointer({ + onMove: (point) => { + if (!session) return; + session.pointer = point; + schedule(); + }, + onEnd: finish + }), + restoreStyles: () => { + document.body.style.userSelect = originalUserSelect; + document.body.style.touchAction = originalTouchAction; + } + }; + } + + return { + get isResizing() { + return isResizing; + }, + start + }; +} diff --git a/src/lib/canvas/marquee.svelte.ts b/src/lib/canvas/marquee.svelte.ts new file mode 100644 index 0000000..f5c8cdc --- /dev/null +++ b/src/lib/canvas/marquee.svelte.ts @@ -0,0 +1,89 @@ +import { appStore } from '../stores/appStore.svelte.ts'; +import type { DocumentPage } from '../types/canvas'; +import { rectBetween, rectsOverlap, type Point, type Rect, type Size } from '../utils/geometry'; +import { trackPointer } from './pointer'; + +interface Options { + getCanvas: () => HTMLElement | undefined; + getPage: () => DocumentPage; + /** The canvas size in page pixels (not screen pixels) */ + getSize: () => Size; +} + +/** Pointer movement (screen pixels) below which a press on the empty page is a click, not a selection box */ +const CLICK_SLOP = 3; + +/** + * Selecting by dragging a box over the empty page: everything the box touches is selected as it grows. + * With `additive` (Shift or the select-multiple mode) the box adds to the current selection. + */ +export function createMarquee(options: Options) { + let box = $state(null); + let moved = false; + let stop: (() => void) | null = null; + + function toPage(point: Point): Point { + const rect = options.getCanvas()!.getBoundingClientRect(); + const { width, height } = options.getSize(); + return { + x: (point.x - rect.left) * (width / rect.width), + y: (point.y - rect.top) * (height / rect.height) + }; + } + + function start(event: PointerEvent, additive: boolean) { + if (event.button !== 0 || !options.getCanvas()) return; + stop?.(); + + const page = options.getPage(); + const origin = { x: event.clientX, y: event.clientY }; + const originInPage = toPage(origin); + const kept = + additive && appStore.getSelectedElements()[0]?.pageId === page.id + ? appStore.getSelectedElements().map((el) => el.id) + : []; + moved = false; + + stop = trackPointer({ + onMove: (point) => { + if ( + !moved && + Math.abs(point.x - origin.x) <= CLICK_SLOP && + Math.abs(point.y - origin.y) <= CLICK_SLOP + ) { + return; + } + moved = true; + box = rectBetween(originInPage, toPage(point)); + const touched = Object.values(options.getPage().elements) + .filter((el) => rectsOverlap(box!, el)) + .map((el) => el.id); + appStore.selectElements(page.id, [...kept, ...touched.filter((id) => !kept.includes(id))]); + }, + onEnd: () => { + stop?.(); + stop = null; + box = null; + } + }); + } + + return { + /** The selection box being dragged, in page pixels */ + get box() { + return box; + }, + start, + /** Was there a selection box since the last call? The click that ends it must not clear the selection. */ + consumeMoved() { + const wasMoved = moved; + moved = false; + return wasMoved; + }, + cancel() { + stop?.(); + stop = null; + box = null; + } + }; +} diff --git a/src/lib/canvas/pageDrop.svelte.ts b/src/lib/canvas/pageDrop.svelte.ts new file mode 100644 index 0000000..3486877 --- /dev/null +++ b/src/lib/canvas/pageDrop.svelte.ts @@ -0,0 +1,16 @@ +import type { Rect } from '../utils/geometry'; + +let target = $state<{ pageId: string; rects: Rect[] } | null>(null); + +/** The page an element is being dragged over, and where it would land there. */ +export const pageDrop = { + get target() { + return target; + }, + set(pageId: string, rects: Rect[]) { + target = { pageId, rects }; + }, + clear() { + target = null; + } +}; diff --git a/src/lib/canvas/pointer.ts b/src/lib/canvas/pointer.ts new file mode 100644 index 0000000..8db38ef --- /dev/null +++ b/src/lib/canvas/pointer.ts @@ -0,0 +1,35 @@ +import type { Point } from '../utils/geometry'; + +/** Screen position of a mouse, pointer or (first) touch event. */ +export function eventPoint(event: PointerEvent | MouseEvent | TouchEvent): Point { + const source = 'touches' in event ? event.touches[0] : event; + return { x: source.clientX, y: source.clientY }; +} + +/** + * Follow a pointer (mouse, pen or finger) across the whole document until it is released or cancelled. + * Returns a function that stops tracking; it is also safe to call after `onEnd`. + */ +export function trackPointer(handlers: { + onMove: (point: Point) => void; + onEnd: () => void; +}): () => void { + const onPointerMove = (e: PointerEvent) => handlers.onMove(eventPoint(e)); + const onTouchMove = (e: TouchEvent) => handlers.onMove(eventPoint(e)); + const onEnd = () => handlers.onEnd(); + const touchMoveOptions: AddEventListenerOptions = { passive: false }; + + document.addEventListener('pointermove', onPointerMove); + document.addEventListener('pointerup', onEnd, true); + document.addEventListener('touchmove', onTouchMove, touchMoveOptions); + document.addEventListener('touchend', onEnd, true); + document.addEventListener('touchcancel', onEnd, true); + + return () => { + document.removeEventListener('pointermove', onPointerMove); + document.removeEventListener('pointerup', onEnd, true); + document.removeEventListener('touchmove', onTouchMove, touchMoveOptions); + document.removeEventListener('touchend', onEnd, true); + document.removeEventListener('touchcancel', onEnd, true); + }; +} diff --git a/src/lib/canvas/saveDocument.browser.spec.ts b/src/lib/canvas/saveDocument.browser.spec.ts new file mode 100644 index 0000000..4cded38 --- /dev/null +++ b/src/lib/canvas/saveDocument.browser.spec.ts @@ -0,0 +1,45 @@ +// Runs in Chromium (real IndexedDB), see the "client" project in vite.config.ts +import { beforeEach, describe, expect, it } from 'vitest'; +import { appStore } from '../stores/appStore.svelte.ts'; +import { deleteDocument, getAllDocuments, getDocument } from '../stores/idb'; +import type { DocumentData } from '../types/canvas'; +import { saveCurrentDocument } from './saveDocument'; + +describe('saveCurrentDocument', () => { + beforeEach(async () => { + for (const doc of await getAllDocuments()) await deleteDocument(doc.id); + appStore.initNewDocument(); + }); + + it('saves the current document under the given name and updates the editor', async () => { + const id = appStore.getCurrentDocument().id; + + const error = await saveCurrentDocument('My Resume'); + + expect(error).toBeNull(); + expect(appStore.getCurrentDocument().name).toBe('My Resume'); + const stored = await getDocument(id); + expect(stored?.name).toBe('My Resume'); + expect(Object.keys(stored!.pages)).toEqual(Object.keys(appStore.getPages())); + }); + + it('saving again under another name renames the same document', async () => { + await saveCurrentDocument('First'); + await saveCurrentDocument('Second'); + + const all = await getAllDocuments(); + expect(all).toHaveLength(1); + expect(all[0].name).toBe('Second'); + }); + + it('returns a message instead of throwing when saving fails', async () => { + const circular: Record = {}; + circular.self = circular; // cannot be serialised + appStore.updateCurrentDocument({ circular } as unknown as Partial); + + const error = await saveCurrentDocument('Broken'); + + expect(error).toMatch(/^Failed to save\. Please try again: /); + expect(appStore.getCurrentDocument().name).toBe(''); + }); +}); diff --git a/src/lib/canvas/saveDocument.ts b/src/lib/canvas/saveDocument.ts new file mode 100644 index 0000000..af1e64e --- /dev/null +++ b/src/lib/canvas/saveDocument.ts @@ -0,0 +1,15 @@ +import { appStore } from '../stores/appStore.svelte.ts'; +import { saveDocument, StorageQuotaError } from '../stores/idb'; + +/** Save the document being edited under `name`. Returns an error message for the user, or null on success. */ +export async function saveCurrentDocument(name: string): Promise { + try { + await saveDocument({ ...appStore.getCurrentDocument(), name }); + appStore.updateCurrentDocument({ name }); + return null; + } catch (err) { + return err instanceof StorageQuotaError + ? err.message + : 'Failed to save. Please try again: ' + err; + } +} diff --git a/src/lib/canvas/targetPage.ts b/src/lib/canvas/targetPage.ts new file mode 100644 index 0000000..1a0d800 --- /dev/null +++ b/src/lib/canvas/targetPage.ts @@ -0,0 +1,24 @@ +import { appStore } from '../stores/appStore.svelte.ts'; + +/** Where pasted elements go: the page last clicked, else the one nearest the middle of the screen. */ +export function targetPageId(): string | null { + const active = appStore.getActivePageId(); + if (active) return active; + + const container = document.querySelector('[data-testid="canvas-container"]'); + const middle = container + ? container.getBoundingClientRect().top + container.getBoundingClientRect().height / 2 + : window.innerHeight / 2; + let best: { id: string; distance: number } | null = null; + for (const id of Object.keys(appStore.getPages())) { + const canvas = document.getElementById(`canvas-${id}`); + if (!canvas) continue; + const rect = canvas.getBoundingClientRect(); + // zero when the middle of the screen is on the page + const distance = Math.max(rect.top - middle, middle - rect.bottom, 0); + if (!best || distance < best.distance) best = { id, distance }; + } + return best?.id ?? Object.keys(appStore.getPages())[0] ?? null; +} + +/** After a cut the originals are gone, so the first paste may land exactly where they were (no source page). */ diff --git a/src/lib/components/Button.svelte b/src/lib/components/Button.svelte index b353405..584eb37 100644 --- a/src/lib/components/Button.svelte +++ b/src/lib/components/Button.svelte @@ -23,6 +23,8 @@ onClick?: (event: MouseEvent) => void; children?: Snippet; 'data-testid'?: string; + 'aria-pressed'?: boolean; + title?: string; }; const { @@ -40,17 +42,18 @@ ...restProps }: ButtonProps = $props(); - const baseClasses = `inline-flex items-center justify-center font-medium rounded-lg transition-colors ${variant !== 'text' && variant !== 'ghost' ? `focus:outline-none` : ''}`; + const baseClasses = `inline-flex items-center justify-center font-semibold rounded transition-colors ${variant !== 'text' && variant !== 'ghost' ? `focus:outline-none` : ''}`; const variantClasses: Record = { - primary: 'bg-primary text-primary-foreground hover:bg-primary-dark shadow-md hover:shadow-lg', - secondary: 'border-2 border-primary text-primary hover:bg-primary/10', - 'secondary-destructive': 'border-2 border-destructive text-destructive hover:bg-destructive/10', - destructive: - 'bg-destructive text-destructive-foreground hover:bg-destructive-dark shadow-md hover:shadow-lg', + primary: 'bg-primary text-primary-foreground hover:bg-primary-dark', + secondary: + 'border border-input text-foreground hover:bg-accent aria-pressed:border-primary aria-pressed:bg-primary-light aria-pressed:text-primary-text', + 'secondary-destructive': + 'border border-destructive text-destructive-text hover:bg-destructive/10', + destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive-dark', ghost: 'text-foreground hover:bg-accent hover:text-accent-foreground border border-transparent hover:border-border', - text: 'text-primary hover:bg-accent/50' + text: 'text-primary-text hover:bg-accent/50' }; const getSizeStyles = (size: ButtonSize) => { @@ -103,8 +106,8 @@ : variant === 'ghost' ? 'text-foreground' : variant === 'secondary-destructive' - ? 'text-destructive' - : 'text-primary'; + ? 'text-destructive-text' + : 'text-primary-text'; const isDisabled = $derived(disabled || pending); diff --git a/src/lib/components/ColorInput.svelte b/src/lib/components/ColorInput.svelte index 39a07e5..a3f4cbb 100644 --- a/src/lib/components/ColorInput.svelte +++ b/src/lib/components/ColorInput.svelte @@ -98,7 +98,7 @@ type="button" id={inputId} onclick={handleButtonClick} - class="h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-left text-sm shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground" + class="h-9 w-full rounded border border-input bg-background px-3 py-1 text-left text-sm shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground" style={`background-color: ${value}`} aria-label={label ? `Select ${label} color` : 'Select color'} > diff --git a/src/lib/components/Input.svelte b/src/lib/components/Input.svelte index ddd5368..0c4afc4 100644 --- a/src/lib/components/Input.svelte +++ b/src/lib/components/Input.svelte @@ -45,6 +45,6 @@ {disabled} oninput={handleInput} data-testid={testId} - class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:ring-1 focus:ring-ring focus:outline-none disabled:cursor-not-allowed disabled:opacity-50" + class="flex h-9 w-full rounded border border-input bg-transparent px-3 py-1 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:ring-1 focus:ring-ring focus:outline-none disabled:cursor-not-allowed disabled:opacity-50" /> diff --git a/src/lib/components/Modal.svelte b/src/lib/components/Modal.svelte index 6c06909..fe6d232 100644 --- a/src/lib/components/Modal.svelte +++ b/src/lib/components/Modal.svelte @@ -16,6 +16,8 @@ closeFromBackdrop?: boolean; children: Snippet; isPending?: boolean; + /** Dialog width: medium for a form, large for a preview */ + size?: 'md' | 'lg'; } const { @@ -31,9 +33,16 @@ showAcceptAction = true, closeFromBackdrop = false, children, - isPending = false + isPending = false, + size = 'md' }: Props = $props(); + const titleId = `modal-title-${Math.random().toString(36).slice(2, 9)}`; + + function handleKey(e: KeyboardEvent) { + if (open && e.key === 'Escape' && !disableActions && !isPending) onCancel?.(); + } + function handleBackdropClick(e: MouseEvent) { if (e.target === e.currentTarget && closeFromBackdrop) { onCancel?.(); @@ -41,20 +50,28 @@ } + + {#if open}