Merge branch 'main' into feat/customize-retention

This commit is contained in:
Tom Moor committed 2026-10-20 23:33:07 -04:00
commit 6ec6215760
1426 files changed
+50963 -28181

No files matched your search

+247
View File
@@ -0,0 +1,247 @@
---
name: verify-outline
description: Launch an isolated Outline instance (web UI + API, production build, own Postgres/Redis containers) from the current checkout and drive it in a headless browser to prove a user-facing change works, with screenshots, Playwright traces and database checks as evidence. Use when asked to verify, demo, reproduce or screenshot Outline behavior in the real app, rather than only in unit tests.
---
# Verify Outline
Outline is a team knowledge base. The primary surface is the **web app**: a
React SPA served by the Koa server. The other surfaces are the RPC API
(`POST /api/<resource>.<verb>`), the collaboration websocket (Y.js) that saves
editor content, and the MCP server. All of them run in the same server process
that this skill starts.
This skill **never** uses the developer's dev server
(`https://*.outline.dev:3000`, Vite on 3001) or the docker-compose
Postgres/Redis on 5432/6379. They hold the developer's real session and data.
Every run gets its own copy of the source, its own containers, a free port and
an empty database. Many runs can exist side by side.
All commands below run from the repo root. `$V` is this skill's directory:
```bash
V=.claude/skills/verify-outline
```
## Launch
```bash
$V/scripts/verify-outline.sh up my-run # run-id: [a-z0-9-]+, omit for a timestamped id
```
What it does (about 30s on an M-series Mac):
1. rsyncs the checkout (with uncommitted changes) to
`~/.cache/outline-verify/runs/<id>/src`. It does not copy `node_modules`,
`build`, `.git`, `.env*` or the local TLS certs. `node_modules` is symlinked
from the checkout. The record of what was snapshotted is in `source.txt`.
Then it checks that every `package.json` dependency is in
`node_modules`. If not, it stops with `node_modules in … does not match`.
This happens when Conductor has moved the checkout to another commit:
run `yarn install` there, or use a checkout that matches.
2. Starts `outline-verify-<id>-pg` (postgres:latest) and
`outline-verify-<id>-redis` (redis:latest) on random 127.0.0.1 ports.
It waits for a TCP query to succeed *inside* the container: the image's
init phase runs a socket-only server, so `pg_isready` passes too early.
3. `node build.js` (SWC server build) and `vite build` (frontend) into the
snapshot's `build/`.
4. `sequelize db:migrate` on the empty database, including the data
migrations in `server/scripts/`.
5. Starts `node build/server/index.js --services=web,websockets,collaboration,worker,cron`
with `NODE_ENV=production`, `URL=http://localhost:<port>`, `FORCE_HTTPS=false`,
`FILE_STORAGE=local` and random secrets. The repo's `.env` files are
**not read**, because they hold real S3/OAuth credentials. So uploads stay
in the run's `storage/` dir and no OAuth providers are enabled.
**Ready** = the script prints `READY http://localhost:<port> (run-id: <id>)`.
This line only prints when `/_health` returns 200 (DB + Redis) **and** `/`
serves the built SPA. The script then prints `info` (URL, evidence dir, log,
DATABASE_URL).
The database is empty. There is no seed data. The first journey must be
`setup-workspace.mjs` (see Drive). It creates the workspace and admin through
the real first-run screen, and saves the session cookie for later journeys.
To test new code, `down` the run and `up` a new one. The snapshot does not
follow later edits. A rebuild without a new DB is not supported.
Requirements: Docker running (colima here), `node_modules` installed in the
checkout, and Playwright's Chromium in `~/Library/Caches/ms-playwright`
(see Drive).
## Doctor
Run this first when anything looks wrong. It is read-only. Exit code 0
means the instance is worth driving.
```bash
$V/scripts/verify-outline.sh doctor my-run
```
It checks the following: the server pid is alive, the port is listened on by
*our* process tree, the server cwd is the snapshot, both containers are
running, `/_health` returns 200, `/` serves the SPA, and there are no pending
migrations. It also prints the team/user counts (0 teams means `/` shows
workspace setup) and the commit plus uncommitted paths in the snapshot.
Other read-only helpers:
```bash
$V/scripts/verify-outline.sh info my-run # URL, EVIDENCE, SERVER_LOG, DATABASE_URL
$V/scripts/verify-outline.sh logs my-run 200 # tail server log (JSON lines)
$V/scripts/verify-outline.sh psql my-run 'select title from documents' # read-only transaction
$V/scripts/verify-outline.sh list # runs + labelled containers
```
## Drive
The harness is `scripts/drive.mjs`. It runs one journey module in headless
Chromium:
```bash
node $V/scripts/drive.mjs <run-id> <journey.mjs> [--headed] [--fresh] [-- key=value ...]
```
- The journey modules are in `$V/journeys/`. Each default-exports
`async ({ page, context, url, step, click, psql, literal, args, log }) => value`.
`page` already has `baseURL` set, so `page.goto("/home")` works.
`step(name, page?)` saves a numbered screenshot. `click(locator)`
moves the pointer over the element, waits, then clicks (see the rules below). `psql(sql)` returns rows
(`a|b|c`). Put values into SQL with `literal(value)`, never raw. `value` is written to `result.json`.
- The session persists per run in `runs/<id>/browser-state.json`. `--fresh`
starts signed out.
- Browser lookup: `OUTLINE_VERIFY_PLAYWRIGHT` (path to a playwright-core
package), else `node_modules/playwright-core`, else the newest
`~/.npm/_npx/*/node_modules/playwright-core` (the Playwright MCP server's
copy). Chromium: `OUTLINE_VERIFY_CHROME`, else the newest
`ms-playwright/chromium-*` build. The playwright-core version and the cached
Chromium build do not need to match. The Playwright **MCP** tools are set
to use the `chrome` channel, which is not installed here, so they fail.
Use drive.mjs.
The journeys that ship with the skill (see `features/` for what each proves):
```bash
node $V/scripts/drive.mjs my-run $V/journeys/setup-workspace.mjs # always first
node $V/scripts/drive.mjs my-run $V/journeys/create-collection.mjs -- name="Proof"
node $V/scripts/drive.mjs my-run $V/journeys/create-document.mjs -- collection="Proof"
node $V/scripts/drive.mjs my-run $V/journeys/search.mjs -- query=<word> expect="<title>"
node $V/scripts/drive.mjs my-run $V/journeys/share-public.mjs -- doc=/doc/<slug> expect="<body text>"
```
`create-document` returns `title`, `body` (with a letters-only marker) and
`url` in `result.json`. Feed them into `search` and `share-public`:
```bash
R=$(ls -td ~/.cache/outline-verify/evidence/my-run/create-document-*/ | head -1)result.json
node $V/scripts/drive.mjs my-run $V/journeys/search.mjs -- query="$(jq -r '.value.title|split(" ")|last' $R)" expect="$(jq -r .value.title $R)"
node $V/scripts/drive.mjs my-run $V/journeys/share-public.mjs -- doc="$(jq -r .value.url $R | sed 's|^http://localhost:[0-9]*||')" expect="$(jq -r .value.body $R)"
```
To verify a change, write a new journey next to these (copy the closest one).
Use stable handles that exist in this app:
- ARIA names: `button "New collection"`, `dialog "Create a collection"`,
`textbox "Document title"`, `textbox "Editor content"`,
`button "Share"` → `dialog "Share"` → `switch "Publish to internet"`,
`searchbox "Search…"`, sidebar `link "Expand <collection>"`,
`link "Search"`, `main` → `link "New doc"` (scope it: the sidebar's
Personal section has another `button "New doc"`),
`button "Account"`, `button "Document options"`.
- Routes: `/home`, `/search`, `/drafts`, `/collection/<slug>-<urlId>`,
`/doc/<slug>-<urlId>`, `/s/<shareId>` (public), `/settings/*`.
- To find more handles, dump `await page.locator("body").ariaSnapshot()` in a
scratch journey. Do not rely on a `main` landmark: some pages, such as a
collection while it loads or search, do not have one.
Interaction rules that matter here:
- **Use `click(locator)`, not `locator.click()`**, for sidebar items, header
buttons and list rows. `SidebarLink` and document rows re-render on
`pointerenter` (deferred menus, selection checkbox). Playwright's instant
move-and-click then loses the first click: nothing opens and no error shows.
- Type into the editor with `page.keyboard.type` after you click the title
or editor. In the title, `Enter` moves the cursor to the body.
- The body saves over the collaboration websocket, not the API. Poll the DB
(`documents.content::text`) for up to ~30s instead of trusting the screen.
- API-only checks: `curl -s -X POST $URL/api/<method> -H 'Content-Type: application/json' -H "Authorization: Bearer <key>" -d '{}'`.
Create the key in the UI (`/settings/api-and-access`, "API & Access") so that the key also
comes from a real path.
## Evidence
Evidence goes to `~/.cache/outline-verify/evidence/<run-id>/`, which is
**outside** the run dir and survives `down`. Each journey writes
`<journey>-<timestamp>/` with:
- `01-*.png, 02-*.png …` numbered screenshots of the action and the resulting
state, and `FAILED.png` on failure
- `trace.zip`: the full Playwright trace (DOM snapshots + screenshots per
action). Open it with `npx playwright show-trace trace.zip`.
- `console.log`: page errors and console errors/warnings
- `network.log`: every failed `/api` call and every API POST with its status
- `result.json`: pass/fail, error stack, returned value, and the step list
The run-level files are `source.txt` (commit + uncommitted paths under test)
and `server.log`, which `down` copies.
Proof standards:
- Drive the real user path: click what a user clicks. Do not call internal
store setters, `developer.*` endpoints or test factories. `psql` is
read-only and only for asserting side effects.
- Capture the action and the result: a screenshot before the submit and
after it, plus the reload or the fresh context that shows persistence.
- Verify side effects, not only pixels: rows in Postgres (`psql`), files in
`runs/<id>/storage` for uploads, and `network.log` for API status codes.
For things that are visible to others (shares, permissions), check from a
second, signed-out or other-user browser context (see `share-public.mjs`).
- Read `console.log` and `network.log`. A green journey with a 500 or a
pageerror in the log is not a pass.
- No mocks: the instance is real end to end. External integrations (Slack,
Google, S3, SMTP) are not configured at all. A journey that needs one must
report that it cannot be verified here. It must not stub the integration.
- The rate limits are real (only the global per-IP limit is raised). Do not
disable the limits to make a journey pass.
- If a feature lists several entry points in `features/`, a proof that
drives only one of them is incomplete. Say which entry points you covered.
## Cleanup
```bash
$V/scripts/verify-outline.sh down my-run
```
This kills the server process tree recorded in `server.pid` (never by
name). It removes the two containers, copies `server.log` to the evidence
dir, and deletes `runs/<id>` (snapshot, DB, storage, cookies). It then lists
the evidence dir to show that the evidence is still there. If the port
still has a listener afterwards, it prints a warning. Inspect it with `lsof`
and do not kill it blindly. Run `down` after **every** run, including
failed `up` attempts (`up` writes state before the slow steps, so `down`
always works). `list` shows any runs that you left behind.
To delete the evidence itself, remove
`~/.cache/outline-verify/evidence/<run-id>`, but only when the user asks.
## Helpers
| Script | Invocation |
| --- | --- |
| `scripts/verify-outline.sh` | `up [id]`, `doctor <id>`, `info <id>`, `logs <id> [n]`, `psql <id> '<sql>'`, `down <id>`, `list` |
| `scripts/drive.mjs` | `node scripts/drive.mjs <id> <journey.mjs> [--headed] [--fresh] [-- k=v ...]` |
| `journeys/*.mjs` | see Drive; one file per user journey, args via `-- k=v` |
Environment overrides: `OUTLINE_VERIFY_ROOT` (default
`~/.cache/outline-verify`), `OUTLINE_REPO` (the checkout to snapshot; default
is the git toplevel of the cwd), `OUTLINE_VERIFY_PG_IMAGE`,
`OUTLINE_VERIFY_REDIS_IMAGE`, `OUTLINE_VERIFY_PLAYWRIGHT`,
`OUTLINE_VERIFY_CHROME`.
## Conductor caveat
`~/Projects/outline` is mirrored and reset by Conductor from other
worktrees. It can carry another agent's uncommitted diff, and untracked files
there can disappear. Run `up` from the worktree that has your change.
`source.txt` shows exactly what was snapshotted, so check it before you
claim that a run tested your change.
@@ -0,0 +1,24 @@
# Outline feature map
This is the maintained list of user-facing features that `verify-outline`
can drive. Each file covers what the feature is, how a user reaches it, how
to drive it with `scripts/drive.mjs`, and the observable end state that
proves it works.
The instance starts empty. Journeys build on each other in this order:
| Feature | File | Journey | Needs first |
| --- | --- | --- | --- |
| First-run workspace setup and sign-in | [workspace-setup.md](workspace-setup.md) | `journeys/setup-workspace.mjs` | fresh `up` |
| Collections | [collections.md](collections.md) | `journeys/create-collection.mjs` | setup |
| Documents (create, edit, persist) | [documents.md](documents.md) | `journeys/create-document.mjs` | a collection |
| Search | [search.md](search.md) | `journeys/search.mjs` | a document |
| Share to web (public link) | [sharing.md](sharing.md) | `journeys/share-public.mjs` | a document |
Not mapped yet (candidates in priority order): comments
(`button "Comment"` on a doc), inviting members and permissions
(`button "Invite people…"`, the `dialog "Share"` invite box), import/export
(`/settings/import`, `/settings/export`), API keys
(`/settings/api-and-access`), templates, and the archive and trash
(`/archive`, `/trash`). When you add one, add a row here and a file with
the same four sections.
@@ -0,0 +1,42 @@
# Collections
Collections are the top-level containers for documents. They also carry
the default permissions. They appear in the sidebar under "Collections".
## Sub-features
- Create (name, icon/color, default permission, advanced options)
- Open a collection page (`/collection/<slug>-<urlId>`) and expand it in the sidebar
- Edit, archive and delete through the collection menu (not mapped yet)
## How to get to it (user POV)
In the sidebar, under **Collections**, click **New collection**. A dialog
"Create a collection" opens. Type a name and click **Create**. The app
navigates to the new collection, and it appears in the sidebar. The command
bar (⌘K → "New collection") opens the same dialog.
## Driving it with drive.mjs
```bash
node $V/scripts/drive.mjs <id> $V/journeys/create-collection.mjs -- name="Proof"
```
The handles are `button "New collection"`, then
`dialog "Create a collection"`, then its only `textbox`, then
`button "Create"`. After that the URL matches `/collection/` and the sidebar
shows `link "Expand Proof"`.
The proof is `02-collection-page.png` plus exactly one row in `collections`
with that name and `deletedAt is null`.
## Gotchas
- The sidebar's "New collection" ignores an instant click (re-render on
`pointerenter`). Hover, wait 300ms, then click. The journey does this.
- The name input in the dialog has **no accessible name**
(`textbox` with no label). Select it as the only textbox in the dialog.
- `collections.create` has a per-endpoint rate limit. Many collections in a
few minutes on one run can return 429. Check `network.log`.
- The page has no `main` landmark until the collection loads. Wait for the
sidebar link instead.
@@ -0,0 +1,59 @@
# Documents
This is the core of the app: a collaborative ProseMirror editor. The title
saves over the API (`documents.update`). The body saves over the Y.js
collaboration websocket and is stored in `documents.content`.
## Sub-features
- New doc in a collection (it is published at once in the current UI)
- Title editing (`textbox "Document title"`)
- Body editing (`textbox "Editor content"`): typing, `/` block menu,
markdown shortcuts, uploads (`button "Upload file"`), find and replace
- Persistence across a reload, and real-time sync
- Header actions: Share, Star, `button "New child document"`, `button "Document options"`
## How to get to it (user POV)
Open a collection from the sidebar and click **New doc** (top right). An
empty doc opens at `/doc/untitled-<urlId>` with the cursor in the title.
Type a title, press Enter, then type the body. There is no Save button:
changes save on their own.
## Driving it with drive.mjs
```bash
node $V/scripts/drive.mjs <id> $V/journeys/create-document.mjs -- collection="Proof" [title=... body=...]
```
The journey opens the collection with `link "Expand <collection>"` and clicks
`main` → `link|button "New doc"`. It then clicks `textbox "Document title"`, uses
`keyboard.type(title)`, presses `Enter` and uses `keyboard.type(body)`.
The proof has three parts. (1) It polls the DB until the row
`title|published|content contains body` is `<title>|t|t`. (2) It reloads the
page and asserts that the title and body come back from the server. (3) It
takes the screenshots `01-typed.png` and `02-after-reload.png`.
`result.json` has `title`, `body` and `url` for the search and share
journeys.
## Gotchas
- New docs in a collection are **published at once** (`publishedAt` is set),
with an empty title until you type one. There is no "Publish" button in
this flow. The draft flow (`/drafts`, `link "New doc"` on Home →
`/doc/new`) is not mapped yet.
- The body is not saved by the API. Do not assert on `documents.update`
in `network.log`. Poll `content::text` for up to ~30s.
- Use letters-only unique markers. Postgres parses `verify-123` as a
negative-number token, so a numeric marker can never be found through
search.
- Scope "New doc" to `getByRole("main")`. Newer builds have a **Personal**
sidebar section with its own `button "New doc"`, which makes an inline
title input in the sidebar instead of opening the editor.
- Right after a reload, the body can be in the DOM twice for a moment (the
read-only editor and the collaborative editor during the hand-over).
Strict-mode locators then fail. Filter `{ visible: true }` and wait for one
copy. More than one visible copy after ~10s is a real bug.
- Use `page.keyboard.type` after you click. `locator.fill` on the
contenteditable bypasses ProseMirror's input handling.
@@ -0,0 +1,48 @@
# Search
This is full-text search over the documents the user can access
(Postgres `searchVector`), with filters and a "titles only" switch.
## Sub-features
- Query from the Search page (`/search`) or the header searchbox
`searchbox "Search documents ⌘K"` on Home
- Filters: `button "Any collection"`, `button "Any author"`,
`button "Published, Drafts"`, `button "All time"`,
`switch "Search titles only"`, sort `button "Relevance"`
- Open a result. Recent searches (`searches.list`).
## How to get to it (user POV)
Click **Search** in the sidebar, type a word in the big search box and press
Enter. The results list shows the title, the collection and the last update.
Clicking a result opens the doc.
## Driving it with drive.mjs
```bash
node $V/scripts/drive.mjs <id> $V/journeys/search.mjs -- query=<word> expect="<exact doc title>"
```
The handles are `link "Search"` (exact), then `searchbox "Search…"` with
fill and Enter. Then the journey waits for a result `link` whose name
contains the title, takes a screenshot, clicks it, and asserts that
`textbox "Document title"` equals `expect`.
The proof is `01-results.png` with the matching result, `02-opened-result.png`,
and `200 POST /api/documents.search` in `network.log`.
## Gotchas
- Use a letters-only word as the query (see documents.md). Numbers with a
leading hyphen are stored as negative numbers.
- The `searchVector` updates when the document saves. Search right after
`create-document` finished its DB poll, not mid-typing.
- The query is in the `?q=` URL param (`searchPath` in
`app/utils/routeHelpers.ts`), not `?query=`. Wait for the result, not for
the URL.
- The result rows switch to an interactive state (selection checkbox, star,
menu) on the first pointer event. Open a result with `click(locator)` from
drive.mjs. A bare `locator.click()` is swallowed.
- The result link name contains the title, and the sidebar has a link with
the same name. Take the `.last()` match, which is the result list.
@@ -0,0 +1,48 @@
# Sharing: publish to web
The Share dialog on a document controls member access and the public link.
"Publish to web" creates a `shares` row that anyone with the `/s/<shareId>`
link can open without signing in.
## Sub-features
- Publish to web (`switch "Publish to internet"`) and unpublish
- Copy the link (the link icon in the dialog). There are also share options
once published: indexing, child documents, and a custom URL.
- Invite people or groups (`textbox "Add or invite…"`) and change a
member's permission (`Can edit` and so on): not mapped yet
- Collection-level public access (Collection → Share): not mapped yet
## How to get to it (user POV)
Open a document and click **Share** (top right). A popover "Share" lists the
people with access and a "Publish to web" row with a toggle. Turn the toggle
on, then copy the link and open it in a private window.
## Driving it with drive.mjs
```bash
node $V/scripts/drive.mjs <id> $V/journeys/share-public.mjs -- doc=/doc/<slug-urlId> expect="<body text>"
```
The journey hovers and clicks `button "Share"` (exact), then clicks
`dialog "Share"` → `switch "Publish to internet"` and waits for
`aria-checked="true"`. It reads the share id from `shares`
(`published = t`, not revoked). It then opens `/s/<shareId>` in a **new
browser context with no cookies** and waits for the body text there.
The proof is `01-share-dialog-published.png` (toggle on),
`02-public-page-signed-out.png` (content visible while signed out), the
`db:` line with the share row, and `200 POST /api/shares.create`.
## Gotchas
- The journey refuses a doc that is already published. Use a fresh doc from
`create-document`.
- If the toggle does not turn on, look in `network.log` for a 429 on
`shares.create`. Before the skill raised the global per-IP limit, the
production build's static assets used up the default 1000 requests/minute
in a few page loads. The per-endpoint limit for shares still applies.
- The public page renders through the same SPA. A 404 there with a valid
share row usually means the team setting for public sharing is off
(`teams.sharing`).
@@ -0,0 +1,49 @@
# Workspace setup (first run)
On a self-hosted instance with no teams, `/` shows the **Create workspace**
form instead of a login screen. When the form is submitted, it POSTs
`/api/installation.create`. This creates the team and an admin user, sets the
`accessToken` cookie and redirects to `/home`. This is the only sign-in path
on a verification instance, because no OAuth or SMTP providers are configured.
## Sub-features
- Workspace creation (team row, subdomain from the name)
- Admin user creation (`users.role = 'admin'`)
- Sign-in by session cookie and the redirect to `/home`
- Guard: `installation.create` refuses when a team already exists
## How to get to it (user POV)
Open the instance URL on a brand-new install. The page has the heading
"Create workspace" and the fields "Workspace name", "Admin name" and "Admin
email", plus a "Continue →" button.
## Driving it with drive.mjs
```bash
node $V/scripts/drive.mjs <id> $V/journeys/setup-workspace.mjs [-- team="Acme" name="Ada" email=ada@acme.test]
```
The journey fills the three labelled inputs (`getByLabel`), clicks
`button /Continue/` and waits for `/home` and the sidebar navigation. It then
asserts exactly one `teams ⋈ users` row: `<team>|<email>|admin`.
The proof is `02-signed-in-home.png`: the sidebar shows the workspace name
and the admin. The `db:` log line shows the team and the admin row.
`browser-state.json` now holds the session for later journeys.
## Gotchas
- This runs only once per instance. The journey refuses when `teams` is not
empty. To repeat it, `down` and `up` a new run.
- The route is not mounted when `URL` is one of the cloud-hosted URLs
(`env.isCloudHosted`). The skill uses `http://localhost:<port>`, so it is
always self-hosted.
- These are expected in this journey's logs and are not failures:
`401 POST /api/auth.info` and a matching console error (the signed-out
probe before setup), an empty `[pageerror]` from that probe, and
`302 POST /api/installation.create` (the form redirect).
- To sign in as a second user, you need an invite. Email sign-in is
disabled in production without SMTP. A multi-user journey must report that
limit. It must not mint tokens.
@@ -0,0 +1,28 @@
// Create a collection from the sidebar "New collection" dialog.
// Args: name= (default "Verify Collection <time>").
export default async ({ page, click, step, psql, literal, args, log }) => {
const name = args.name ?? `Verify Collection ${Date.now()}`;
await page.goto("/home");
await page.waitForLoadState("networkidle");
const open = page.getByRole("button", { name: "New collection" });
await click(open);
const dialog = page.getByRole("dialog", { name: "Create a collection" });
await dialog.waitFor();
// The name input has no accessible label; it is the only textbox.
await dialog.getByRole("textbox").fill(name);
await step("create-collection-dialog");
await dialog.getByRole("button", { name: "Create" }).click();
await page.waitForURL(/\/collection\//);
await page.getByRole("link", { name: `Expand ${name}` }).waitFor();
await step("collection-page");
const rows = psql(`select name from collections where name = ${literal(name)} and "deletedAt" is null`);
log("db:", rows);
if (rows.length !== 1) {
throw new Error(`expected 1 collection row named ${name}, got ${rows.length}`);
}
return { name, url: page.url() };
};
@@ -0,0 +1,75 @@
// Create a document in a collection through the editor, then prove the title
// and body persisted (reload + database).
// Args: collection= (name of an existing collection, required), title=, body=.
// The editor applies input rules such as smart quotes to body=, so the checks
// use the text that the editor shows.
export default async ({ page, click, step, psql, literal, args, log }) => {
if (!args.collection) {
throw new Error("collection= is required; run create-collection.mjs first");
}
// Letters only: Postgres parses "verify-123" as a negative number token, so
// a numeric marker can never be found through search.
const marker = `verify${Array.from({ length: 8 }, () => "abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random() * 26)]).join("")}`;
const title = args.title ?? `Verify Doc ${marker}`;
const typed = args.body ?? `Body text ${marker}`;
await page.goto("/home");
await page.waitForLoadState("networkidle");
const coll = page.getByRole("link", { name: `Expand ${args.collection}` });
await click(coll);
await page.waitForURL(/\/collection\//);
// Scope to main: the sidebar has its own "New doc" for the Personal section.
const header = page.getByRole("main");
const newDoc = header.getByRole("link", { name: "New doc" }).or(header.getByRole("button", { name: "New doc" })).first();
await click(newDoc);
await page.waitForURL(/\/doc\//);
const titleBox = page.getByRole("textbox", { name: "Document title" });
await titleBox.click();
await page.keyboard.type(title);
await page.keyboard.press("Enter");
await page.keyboard.type(typed);
const body = (await page.getByRole("textbox", { name: "Editor content" }).locator("p").first().innerText()).trim();
if (body !== typed) {
log("editor changed body to:", body);
}
await step("typed");
// Title saves over the API, body over the collaboration websocket; poll the DB.
// jsonb text escapes strings as JSON does, so search for the escaped body.
const escapedBody = JSON.stringify(body).slice(1, -1);
let row = [];
for (let i = 0; i < 30; i++) {
row = psql(
`select title, "publishedAt" is not null, strpos(content::text, ${literal(escapedBody)}) > 0 from documents where title = ${literal(title)} and "deletedAt" is null`
);
if (row[0]?.endsWith("|t|t")) {
break;
}
await page.waitForTimeout(1000);
}
log("db:", row);
if (row[0] !== `${title}|t|t`) {
throw new Error(`document not persisted as published with body: ${JSON.stringify(row)}`);
}
const docUrl = page.url();
await page.reload();
// While loading, a read-only editor and the collaborative editor can both be
// in the DOM; wait for exactly one visible copy so real duplication fails.
const copies = page.getByRole("textbox", { name: "Editor content" }).getByText(body).filter({ visible: true });
await copies.first().waitFor();
for (let i = 0; i < 20 && (await copies.count()) !== 1; i++) {
await page.waitForTimeout(500);
}
if ((await copies.count()) !== 1) {
throw new Error(`body visible ${await copies.count()} times after reload`);
}
const shownTitle = await page.getByRole("textbox", { name: "Document title" }).innerText();
if (shownTitle.trim() !== title) {
throw new Error(`title after reload is ${JSON.stringify(shownTitle)}`);
}
await step("after-reload");
return { title, body, url: docUrl };
};
@@ -0,0 +1,31 @@
// Search for a word from the sidebar Search page and open the matching result.
// Args: query= (a letters-only word, required), expect= (title the results must
// include, required).
export default async ({ page, click, step, args, log }) => {
if (!args.query || !args.expect) {
throw new Error("query= and expect= are required");
}
await page.goto("/home");
await page.waitForLoadState("networkidle");
const nav = page.getByRole("link", { name: "Search", exact: true });
await click(nav);
await page.waitForURL(/\/search/);
const box = page.getByRole("searchbox", { name: "Search…" });
await box.fill(args.query);
await box.press("Enter");
const result = page.getByRole("link", { name: new RegExp(args.expect.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) }).last();
await result.waitFor({ timeout: 10000 });
await step("results");
log("results url:", page.url());
await click(result);
await page.waitForURL(/\/doc\//);
const title = await page.getByRole("textbox", { name: "Document title" }).innerText();
if (title.trim() !== args.expect) {
throw new Error(`opened ${JSON.stringify(title)} instead of ${args.expect}`);
}
await step("opened-result");
return { query: args.query, opened: page.url() };
};
@@ -0,0 +1,31 @@
// First-run workspace setup on an empty instance: the real self-hosted
// onboarding form that POSTs /api/installation.create and signs the admin in.
// Args: team=, name=, email= (defaults below).
export default async ({ page, step, psql, args, log }) => {
const team = args.team ?? "Verify Co";
const name = args.name ?? "Vera Admin";
const email = args.email ?? "admin@verify.test";
if (psql("select count(*) from teams")[0] !== "0") {
throw new Error("instance already has a team; setup only runs on a fresh instance");
}
await page.goto("/");
await page.getByLabel("Workspace name").fill(team);
await page.getByLabel("Admin name").fill(name);
await page.getByLabel("Admin email").fill(email);
await step("setup-form-filled");
await page.getByRole("button", { name: /Continue/ }).click();
await page.waitForURL(/\/home/, { timeout: 20000 });
await page.getByRole("navigation").first().waitFor();
await step("signed-in-home");
const rows = psql(
`select t.name, u.email, u.role from teams t join users u on u."teamId" = t.id`
);
log("db:", rows);
if (rows.length !== 1 || rows[0] !== `${team}|${email}|admin`) {
throw new Error(`unexpected team/user rows: ${JSON.stringify(rows)}`);
}
return { team, email, rows };
};
@@ -0,0 +1,51 @@
// Publish a document to the web from the Share dialog, then open the public
// link in a signed-out browser context and read the content.
// Args: doc= (document path such as /doc/slug-id, required), expect= (body text
// the public page must show, required).
export default async ({ page, click, context, step, psql, literal, args, log }) => {
if (!args.doc || !args.expect) {
throw new Error("doc= and expect= are required");
}
await page.goto(args.doc);
await page.waitForLoadState("networkidle");
const docId = args.doc.split("-").pop();
const share = page.getByRole("button", { name: "Share", exact: true });
await click(share);
const dialog = page.getByRole("dialog", { name: "Share" });
const toggle = dialog.getByRole("switch", { name: "Publish to internet" });
if ((await toggle.getAttribute("aria-checked")) === "true") {
throw new Error("document is already published to the web; use a fresh document");
}
await toggle.click();
await page.waitForFunction(
() => document.querySelector('[role=switch][aria-checked="true"]') !== null
);
await step("share-dialog-published");
const rows = psql(
`select s.id, s.published from shares s join documents d on d.id = s."documentId" where d."urlId" = ${literal(docId)} and s."revokedAt" is null`
);
log("db:", rows);
const [shareId, published] = (rows[0] ?? "").split("|");
if (published !== "t") {
throw new Error(`no published share row for ${docId}: ${JSON.stringify(rows)}`);
}
const anon = await context.browser().newContext({ baseURL: page.url() });
try {
const pub = await anon.newPage();
await pub.goto(`/s/${shareId}`);
// Scope to main: the server also renders a screen-reader-only copy.
await pub.getByRole("main").getByText(args.expect).first().waitFor({ timeout: 15000 });
const cookies = (await anon.cookies()).map((c) => c.name);
if (cookies.includes("accessToken")) {
throw new Error("anonymous context unexpectedly holds an accessToken");
}
await step("public-page-signed-out", pub);
log("public page url:", pub.url());
return { shareUrl: `/s/${shareId}`, publicUrl: pub.url() };
} finally {
await anon.close();
}
};
+203
View File
@@ -0,0 +1,203 @@
#!/usr/bin/env node
// Run a browser journey against a verify-outline instance and capture evidence.
//
// Usage:
// drive.mjs <run-id> <journey.mjs> [--headed] [--fresh] [-- key=value ...]
//
// The journey module default-exports
// `async ({ page, context, url, step, click, psql, literal, args, log }) => value`
// step(name, page?) saves a numbered screenshot, click(locator) hovers first, psql(sql) returns rows of
// read-only SQL, literal(value) quotes a string for that SQL, args holds the key=value pairs, value
// lands in result.json.
// Cookies persist per run in <run-dir>/browser-state.json, so a journey run
// after `setup-workspace.mjs` is already signed in. --fresh ignores them.
//
// Evidence goes to <evidence>/<journey>-<timestamp>/: numbered step
// screenshots, trace.zip (open with `npx playwright show-trace trace.zip`),
// console.log (page errors and console errors), network.log (failed /api
// calls and every POST to /api), result.json.
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const verifySh = path.join(here, "verify-outline.sh");
const root = process.env.OUTLINE_VERIFY_ROOT ?? path.join(os.homedir(), ".cache/outline-verify");
const argv = process.argv.slice(2);
const sep = argv.indexOf("--");
const flags = sep === -1 ? argv : argv.slice(0, sep);
const extra = sep === -1 ? [] : argv.slice(sep + 1);
const [runId, journeyPath] = flags.filter((a) => !a.startsWith("--"));
const headed = flags.includes("--headed");
const fresh = flags.includes("--fresh");
if (!runId || !journeyPath) {
console.error("usage: drive.mjs <run-id> <journey.mjs> [--headed] [--fresh] [-- key=value ...]");
process.exit(2);
}
const args = Object.fromEntries(extra.map((kv) => kv.split(/=(.*)/s).slice(0, 2)));
const runDir = path.join(root, "runs", runId);
const stateFile = path.join(runDir, "state.env");
if (!fs.existsSync(stateFile)) {
console.error(`no run '${runId}' (${stateFile}); start one with verify-outline.sh up`);
process.exit(2);
}
const state = Object.fromEntries(
fs
.readFileSync(stateFile, "utf8")
.split("\n")
.filter(Boolean)
.map((l) => l.split(/=(.*)/s).slice(0, 2))
);
const url = state.URL;
/** Newest directory entry matching a pattern, or undefined. */
function newest(dir, re) {
if (!fs.existsSync(dir)) {
return undefined;
}
return fs
.readdirSync(dir)
.filter((d) => re.test(d))
.map((d) => path.join(dir, d))
.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)[0];
}
function loadPlaywright() {
const candidates = [
process.env.OUTLINE_VERIFY_PLAYWRIGHT,
path.join(state.SRC ?? "", "node_modules/playwright-core"),
path.join(state.SRC ?? "", "node_modules/playwright"),
];
const npx = path.join(os.homedir(), ".npm/_npx");
if (fs.existsSync(npx)) {
for (const d of fs.readdirSync(npx)) {
candidates.push(path.join(npx, d, "node_modules/playwright-core"));
}
}
const require = createRequire(import.meta.url);
for (const c of candidates) {
if (c && fs.existsSync(path.join(c, "package.json"))) {
return { lib: require(c), from: c };
}
}
throw new Error(
"playwright-core not found; set OUTLINE_VERIFY_PLAYWRIGHT=/path/to/node_modules/playwright-core"
);
}
function findChrome() {
if (process.env.OUTLINE_VERIFY_CHROME) {
return process.env.OUTLINE_VERIFY_CHROME;
}
const cache =
process.platform === "darwin"
? path.join(os.homedir(), "Library/Caches/ms-playwright")
: path.join(os.homedir(), ".cache/ms-playwright");
const dir = newest(cache, /^chromium-\d+$/);
if (!dir) {
return undefined;
}
const options = [
"chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
"chrome-mac/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
"chrome-linux64/chrome",
"chrome-linux/chrome",
].map((p) => path.join(dir, p));
return options.find((p) => fs.existsSync(p));
}
const journeyName = path.basename(journeyPath).replace(/\.m?js$/, "");
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
const outDir = path.join(state.EVIDENCE, `${journeyName}-${stamp}`);
fs.mkdirSync(outDir, { recursive: true });
const { lib, from } = loadPlaywright();
const executablePath = findChrome();
const browser = await lib.chromium.launch({ headless: !headed, executablePath });
const storage = path.join(runDir, "browser-state.json");
const context = await browser.newContext({
baseURL: url,
viewport: { width: 1400, height: 900 },
storageState: !fresh && fs.existsSync(storage) ? storage : undefined,
});
await context.tracing.start({ screenshots: true, snapshots: true });
const page = await context.newPage();
const consoleLines = [];
const networkLines = [];
page.on("console", (m) => {
if (m.type() === "error" || m.type() === "warning") {
consoleLines.push(`[${m.type()}] ${m.text()}`);
}
});
page.on("pageerror", (e) => consoleLines.push(`[pageerror] ${e.stack ?? e.message}`));
page.on("response", (r) => {
const u = r.url();
if (!u.startsWith(url) || !u.includes("/api/")) {
return;
}
const method = r.request().method();
if (r.status() >= 400 || method === "POST") {
networkLines.push(`${r.status()} ${method} ${u.slice(url.length)}`);
}
});
let n = 0;
const steps = [];
/** Screenshot a page (default: the journey page) as a numbered evidence step. */
async function step(name, target = page) {
n += 1;
const file = `${String(n).padStart(2, "0")}-${name.replace(/[^a-z0-9-]+/gi, "-")}.png`;
await target.screenshot({ path: path.join(outDir, file) });
steps.push(file);
console.log(` step ${file}`);
}
/**
* Click like a person: hover, pause, click. Sidebar links and document rows
* re-render on pointerenter, which swallows an instant Playwright click.
*/
async function click(locator) {
await locator.hover();
await page.waitForTimeout(300);
await locator.click();
}
/** Run read-only SQL against the instance database, returning trimmed rows. */
function psql(sql) {
return execFileSync(verifySh, ["psql", runId, sql], { encoding: "utf8" })
.split("\n")
.filter(Boolean);
}
/** Quote a string as a SQL literal for psql(). */
function literal(value) {
return `'${String(value).replace(/'/g, "''")}'`;
}
const log = (...a) => console.log(" ", ...a);
const journey = (await import(pathToFileURL(path.resolve(journeyPath)).href)).default;
let result = { journey: journeyName, url, ok: false };
console.log(`drive ${journeyName} -> ${url} (playwright ${from}, chrome ${executablePath ?? "default"})`);
try {
const value = await journey({ page, context, url, step, click, psql, literal, args, log });
result = { ...result, ok: true, value: value ?? null };
} catch (err) {
result.error = String(err?.stack ?? err);
await page.screenshot({ path: path.join(outDir, "FAILED.png") }).catch(() => {});
} finally {
await context.storageState({ path: storage }).catch(() => {});
await context.tracing.stop({ path: path.join(outDir, "trace.zip") }).catch(() => {});
await browser.close();
result.steps = steps;
fs.writeFileSync(path.join(outDir, "console.log"), consoleLines.join("\n") + "\n");
fs.writeFileSync(path.join(outDir, "network.log"), networkLines.join("\n") + "\n");
fs.writeFileSync(path.join(outDir, "result.json"), JSON.stringify(result, null, 2) + "\n");
}
console.log(`${result.ok ? "PASS" : "FAIL"} ${journeyName}; evidence: ${outDir}`);
if (!result.ok) {
console.error(result.error);
process.exit(1);
}
+278
View File
@@ -0,0 +1,278 @@
#!/usr/bin/env bash
# Launch, check and tear down an isolated Outline instance for verification.
#
# Usage:
# verify-outline.sh up [run-id] snapshot the checkout, build, migrate, start
# verify-outline.sh doctor <run-id> read-only health check of that instance
# verify-outline.sh info <run-id> print URL, ports and paths for that instance
# verify-outline.sh logs <run-id> [n] tail the server log
# verify-outline.sh psql <run-id> <sql> run read-only SQL against the instance DB
# verify-outline.sh down <run-id> stop and remove what `up` created, keep evidence
# verify-outline.sh list list runs and their containers
#
# Each run gets its own source snapshot, Postgres + Redis containers, free
# port and file storage. It never touches the developer's dev server, the
# docker-compose databases, or the repo's .env files.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO="${OUTLINE_REPO:-$(git rev-parse --show-toplevel 2>/dev/null || (cd "$SCRIPT_DIR/../../../.." && pwd))}"
ROOT="${OUTLINE_VERIFY_ROOT:-$HOME/.cache/outline-verify}"
PG_IMAGE="${OUTLINE_VERIFY_PG_IMAGE:-postgres:latest}"
REDIS_IMAGE="${OUTLINE_VERIFY_REDIS_IMAGE:-redis:latest}"
die() { echo "error: $*" >&2; exit 1; }
log() { echo "[verify-outline] $*" >&2; }
run_dir() { echo "$ROOT/runs/$1"; }
evidence_dir() { echo "$ROOT/evidence/$1"; }
load_state() {
local id="${1:-}"
[[ -n "$id" ]] || die "run-id required (see: $0 list)"
local state
state="$(run_dir "$id")/state.env"
[[ -f "$state" ]] || die "no run '$id' at $state"
# shellcheck disable=SC1090
source "$state"
}
# Exec a command in the snapshot with only this instance's env. The repo's
# .env files are never read: they hold real S3 and OAuth credentials. The
# global rate limit is raised because every static asset of the production
# build counts against it; per-endpoint limits stay as in production. It
# replaces the current shell: call it as `(in_instance ...)` or with `&`.
in_instance() {
cd "$SRC"
exec env -i PATH="$PATH" HOME="$HOME" \
NODE_ENV=production PORT="$PORT" URL="$URL" FORCE_HTTPS=false \
DATABASE_URL="$DATABASE_URL" PGSSLMODE=disable REDIS_URL="$REDIS_URL" \
SECRET_KEY="$SECRET_KEY" UTILS_SECRET="$UTILS_SECRET" \
FILE_STORAGE=local FILE_STORAGE_LOCAL_ROOT_DIR="$RUN_DIR/storage" \
WEB_CONCURRENCY=1 TELEMETRY=false LOG_LEVEL=info \
RATE_LIMITER_REQUESTS=100000 \
"$@"
}
free_port() {
python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close()'
}
cmd_up() {
local id="${1:-v$(date +%Y%m%d-%H%M%S)}"
[[ "$id" =~ ^[a-z0-9-]+$ ]] || die "run-id must match [a-z0-9-]+"
local dir src ev
dir="$(run_dir "$id")"
src="$dir/src"
ev="$(evidence_dir "$id")"
[[ -e "$dir/state.env" ]] && die "run '$id' already exists; use doctor, or down it first"
[[ -d "$REPO/node_modules" ]] || die "$REPO/node_modules missing; run yarn install there"
docker info >/dev/null 2>&1 || die "docker is not running (colima start?)"
mkdir -p "$dir/storage" "$ev"
log "snapshot $REPO -> $src"
rsync -a --delete \
--exclude node_modules --exclude /build --exclude /.git --exclude /data \
--exclude '/.env*' --exclude /.claude --exclude /.cursor --exclude /.conductor \
--exclude /server/config/certs --exclude '.DS_Store' \
"$REPO/" "$src/"
ln -sfn "$REPO/node_modules" "$src/node_modules"
{
echo "repo: $REPO"
git -C "$REPO" rev-parse HEAD
git -C "$REPO" status --porcelain
} >"$dir/source.txt" 2>/dev/null || true
cp "$dir/source.txt" "$ev/source.txt"
# A checkout whose package.json is ahead of or behind its node_modules builds
# with confusing resolver errors; fail fast instead.
local missing
missing="$(cd "$src" && node -e '
const p = require("./package.json");
const deps = Object.keys({ ...p.dependencies, ...p.devDependencies });
const fs = require("fs");
console.log(deps.filter((d) => !fs.existsSync(`node_modules/${d}/package.json`)).join(" "));
')"
[[ -z "$missing" ]] || { rm -rf "$dir"; die "node_modules in $REPO does not match its package.json (missing: $missing); run yarn install there or use a checkout that matches"; }
# Write state before any container starts, so `down` can always clean up.
local pg="outline-verify-$id-pg" redis="outline-verify-$id-redis" port
port="$(free_port)"
cat >"$dir/state.env" <<EOF
RUN_ID=$id
RUN_DIR=$dir
SRC=$src
EVIDENCE=$ev
PORT=$port
URL=http://localhost:$port
PG_CONTAINER=$pg
REDIS_CONTAINER=$redis
SECRET_KEY=$(openssl rand -hex 32)
UTILS_SECRET=$(openssl rand -hex 32)
SERVER_LOG=$dir/server.log
PID_FILE=$dir/server.pid
EOF
docker run -d --name "$pg" --label outline-verify="$id" \
-e POSTGRES_USER=user -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=outline \
-p 127.0.0.1::5432 "$PG_IMAGE" >/dev/null
docker run -d --name "$redis" --label outline-verify="$id" \
-p 127.0.0.1::6379 "$REDIS_IMAGE" >/dev/null
log "started containers $pg, $redis"
local pg_port redis_port
pg_port="$(docker port "$pg" 5432/tcp | head -1 | sed 's/.*://')"
redis_port="$(docker port "$redis" 6379/tcp | head -1 | sed 's/.*://')"
cat >>"$dir/state.env" <<EOF
DATABASE_URL=postgres://user:pass@127.0.0.1:$pg_port/outline
REDIS_URL=redis://127.0.0.1:$redis_port
EOF
load_state "$id"
# The postgres image runs its init scripts on a socket-only server, so a
# TCP query only succeeds once the real server is up.
log "waiting for postgres and redis"
local i
for i in $(seq 1 60); do
docker exec "$PG_CONTAINER" psql -h 127.0.0.1 -U user -d outline -tAc 'select 1' >/dev/null 2>&1 && break
[[ $i == 60 ]] && die "postgres not ready after 60s"
sleep 1
done
for i in $(seq 1 30); do
docker exec "$REDIS_CONTAINER" redis-cli ping 2>/dev/null | grep -q PONG && break
[[ $i == 30 ]] && die "redis not ready after 30s"
sleep 1
done
log "building server (swc)"
(cd "$SRC" && node build.js) >"$RUN_DIR/build-server.log" 2>&1 ||
die "server build failed, see $RUN_DIR/build-server.log"
log "building frontend (vite)"
(cd "$SRC" && NODE_ENV=production node_modules/.bin/vite build) \
>"$RUN_DIR/build-app.log" 2>&1 || die "frontend build failed, see $RUN_DIR/build-app.log"
log "migrating database"
(in_instance node_modules/.bin/sequelize db:migrate --env production-ssl-disabled) \
>"$RUN_DIR/migrate.log" 2>&1 || die "migration failed, see $RUN_DIR/migrate.log"
log "starting server on $URL"
in_instance nohup node build/server/index.js \
--services=web,websockets,collaboration,worker,cron >"$SERVER_LOG" 2>&1 &
echo $! >"$PID_FILE"
for i in $(seq 1 90); do
if ! kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
tail -40 "$SERVER_LOG" >&2
die "server exited during startup, see $SERVER_LOG"
fi
if [[ "$(curl -s -o /dev/null -w '%{http_code}' "$URL/_health")" == 200 ]] &&
curl -s "$URL/" | grep -q '/static/assets/index\.'; then
log "READY $URL (run-id: $id)"
cmd_info "$id"
return 0
fi
sleep 1
done
die "server not ready after 90s, see $SERVER_LOG"
}
cmd_doctor() {
load_state "$1"
local rc=0 pid tmp
pid="$(cat "$PID_FILE" 2>/dev/null || echo none)"
tmp="$(mktemp)"
check() {
if eval "$2" >/dev/null 2>&1; then echo "ok $1"; else echo "FAIL $1"; rc=1; fi
}
check "server pid $pid alive" "[[ $pid =~ ^[1-9][0-9]*$ ]] && kill -0 $pid"
check "port $PORT listened on by our process tree" \
"lsof -nP -iTCP:$PORT -sTCP:LISTEN -t | grep -qxF \"\$(tree $pid)\""
check "server cwd is snapshot" "lsof -a -p $pid -d cwd -Fn | grep -qx 'n$SRC'"
check "postgres container running" "[ \"\$(docker inspect -f '{{.State.Running}}' $PG_CONTAINER)\" = true ]"
check "redis container running" "[ \"\$(docker inspect -f '{{.State.Running}}' $REDIS_CONTAINER)\" = true ]"
check "GET /_health = 200 (db + redis)" "[ \"\$(curl -s -o /dev/null -w '%{http_code}' $URL/_health)\" = 200 ]"
check "GET / serves the built SPA" "curl -s $URL/ | grep -q '/static/assets/index\.'"
check "no pending migrations" \
"(in_instance node_modules/.bin/sequelize db:migrate:status --env production-ssl-disabled) >$tmp && grep -q '^up ' $tmp && ! grep -q '^down ' $tmp"
rm -f "$tmp"
echo "info teams=$(cmd_psql "$1" 'select count(*) from teams' 2>/dev/null || echo '?') users=$(cmd_psql "$1" 'select count(*) from users' 2>/dev/null || echo '?') (teams=0: / shows workspace setup)"
if [[ "$(wc -l <"$RUN_DIR/source.txt")" -ge 2 ]]; then
echo "info snapshot: $(sed -n 2p "$RUN_DIR/source.txt") + $(($(wc -l <"$RUN_DIR/source.txt") - 2)) uncommitted paths from $(sed -n 1p "$RUN_DIR/source.txt" | cut -d' ' -f2)"
else
echo "info snapshot: $(sed -n 1p "$RUN_DIR/source.txt" | cut -d' ' -f2) (not a git checkout)"
fi
return $rc
}
cmd_info() {
load_state "$1"
cat <<EOF
RUN_ID=$RUN_ID
URL=$URL
EVIDENCE=$EVIDENCE
SERVER_LOG=$SERVER_LOG
STORAGE=$RUN_DIR/storage
DATABASE_URL=$DATABASE_URL
PG_CONTAINER=$PG_CONTAINER
EOF
}
cmd_logs() {
load_state "$1"
tail -n "${2:-100}" "$SERVER_LOG"
}
cmd_psql() {
load_state "$1"
[[ -n "${2:-}" ]] || die "sql required"
docker exec "$PG_CONTAINER" psql -h 127.0.0.1 -U user -d outline -v ON_ERROR_STOP=1 \
-c 'SET default_transaction_read_only = on' -tA -c "$2" | sed '/^SET$/d'
}
# Print a pid and all of its descendants.
tree() {
local p
echo "$1"
for p in $(pgrep -P "$1" || true); do tree "$p"; done
}
cmd_down() {
load_state "$1"
local pid pids
pid="$(cat "$PID_FILE" 2>/dev/null || true)"
if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
# throng forks a worker; stop the tree we started, never by process name.
pids="$(tree "$pid" | tr '\n' ' ')"
kill $pids 2>/dev/null || true
for _ in $(seq 1 10); do kill -0 $pids 2>/dev/null || break; sleep 1; done
kill -9 $pids 2>/dev/null || true
log "stopped server pids $pids"
fi
if lsof -nP -iTCP:"$PORT" -sTCP:LISTEN >/dev/null 2>&1; then
log "WARNING: port $PORT still has a listener; inspect with lsof before killing anything"
fi
docker rm -f "$PG_CONTAINER" "$REDIS_CONTAINER" >/dev/null 2>&1 || true
log "removed containers"
mkdir -p "$EVIDENCE"
cp "$SERVER_LOG" "$EVIDENCE/server.log" 2>/dev/null || true
rm -rf "$RUN_DIR"
log "removed $RUN_DIR; evidence kept at $EVIDENCE"
ls -la "$EVIDENCE"
}
cmd_list() {
echo "runs:"
ls -1 "$ROOT/runs" 2>/dev/null | sed 's/^/ /' || true
echo "containers:"
docker ps -a --filter label=outline-verify --format ' {{.Names}}\t{{.Status}}'
}
case "${1:-}" in
up) cmd_up "${2:-}" ;;
doctor) cmd_doctor "${2:-}" ;;
info) cmd_info "${2:-}" ;;
logs) cmd_logs "${2:-}" "${3:-}" ;;
psql) cmd_psql "${2:-}" "${3:-}" ;;
down) cmd_down "${2:-}" ;;
list) cmd_list ;;
*) sed -n '2,13p' "$0"; exit 1 ;;
esac
+2 -2
View File
@@ -6,10 +6,10 @@ runs:
- name: Enable Corepack
shell: bash
run: corepack enable
- name: Use Node.js 26.x
- name: Use a supported Node.js version
uses: actions/setup-node@v5
with:
node-version: 26.x
node-version-file: package.json
cache: "yarn"
- name: Install dependencies
shell: bash
+24 -27
View File
@@ -18,8 +18,11 @@ env:
jobs:
changes:
runs-on: ubuntu-latest
# Blacksmith runners are only available to the outline organization, and are
# not used for pull requests from forks.
runs-on: ${{ (github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }}
outputs:
runner: ${{ (github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }}
code: ${{ steps.filter.outputs.code }}
config: ${{ steps.filter.outputs.config }}
server: ${{ steps.filter.outputs.server }}
@@ -39,8 +42,8 @@ jobs:
- '!shared/i18n/locales/**'
config:
- '.github/**'
- 'vite.config.ts'
- 'vitest.config.ts'
- 'vite.config.mts'
- 'vitest.config.mts'
server:
- 'server/**'
- 'shared/**'
@@ -60,7 +63,7 @@ jobs:
lint:
needs: changes
if: ${{ needs.changes.outputs.code == 'true' }}
runs-on: ubuntu-latest
runs-on: ${{ needs.changes.outputs.runner }}
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/install
@@ -79,16 +82,17 @@ jobs:
types:
needs: changes
if: ${{ needs.changes.outputs.code == 'true' }}
runs-on: ubuntu-latest
runs-on: ${{ needs.changes.outputs.runner }}
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/install
- run: yarn tsc
# No tsc build cache persists between runs, so skip writing one.
- run: yarn tsc --incremental false
audit:
needs: changes
if: ${{ needs.changes.outputs.deps == 'true' }}
runs-on: ubuntu-latest
runs-on: ${{ needs.changes.outputs.runner }}
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/install
@@ -97,7 +101,7 @@ jobs:
test:
needs: changes
if: ${{ needs.changes.outputs.app == 'true' || needs.changes.outputs.config == 'true' }}
runs-on: ubuntu-latest
runs-on: ${{ needs.changes.outputs.runner }}
strategy:
matrix:
test-group: [app, shared]
@@ -109,37 +113,30 @@ jobs:
test-server:
needs: changes
if: ${{ needs.changes.outputs.server == 'true' || needs.changes.outputs.config == 'true' }}
runs-on: ubuntu-latest
services:
postgres:
image: postgres:14.2
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
POSTGRES_DB: outline_test
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
runs-on: ${{ needs.changes.outputs.runner }}
strategy:
matrix:
shard: [1, 2, 3, 4]
shard: [1, 2, 3, 4, 5, 6]
steps:
- uses: actions/checkout@v5
# The runner image ships with PostgreSQL preinstalled, starting it is much
# faster than pulling and initializing a service container.
- name: Start PostgreSQL
run: |
sudo systemctl start postgresql.service
until pg_isready -h localhost; do sleep 1; done
sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'password';"
sudo -u postgres createdb outline_test
- uses: ./.github/actions/install
- run: yarn sequelize db:migrate
- name: Run server tests
run: yarn test:server --maxWorkers=2 --shard=${{ matrix.shard }}/4
run: yarn test:server --maxWorkers=4 --shard=${{ matrix.shard }}/6
bundle-size:
needs: changes
if: ${{ (needs.changes.outputs.app == 'true' || needs.changes.outputs.config == 'true') && github.repository == 'outline/outline' }}
runs-on: ubuntu-latest
runs-on: ${{ needs.changes.outputs.runner }}
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/install
+1 -5
View File
@@ -70,11 +70,7 @@ jobs:
# .nvmrc
echo "$LATEST_MAJOR" > .nvmrc
# CI install action: step name and node-version
sed -i "s/Use Node.js ${CURRENT_MAJOR}.x/Use Node.js ${LATEST_MAJOR}.x/g" .github/actions/install/action.yml
sed -i "s/node-version: ${CURRENT_MAJOR}.x/node-version: ${LATEST_MAJOR}.x/g" .github/actions/install/action.yml
# package.json engines field: append new major version
# package.json engines field (also used by CI): append new major version
sed -i "s/\"node\": \"\(.*\)\"/\"node\": \"\1 || ${LATEST_MAJOR}\"/" package.json
fi
+52
View File
@@ -0,0 +1,52 @@
/**
* Local oxlint plugin with rules for code that ships in the minified client
* bundle.
*/
/** Returns true if the member expression accesses the given property name. */
function isProperty(node, name) {
if (node.type !== "MemberExpression") {
return false;
}
if (!node.computed) {
return node.property.type === "Identifier" && node.property.name === name;
}
return node.property.type === "Literal" && node.property.value === name;
}
const plugin = {
meta: {
name: "bundle",
},
rules: {
"no-constructor-name": {
meta: {
type: "problem",
docs: {
description:
"Disallow reading `constructor.name`. The minifier renames classes, and two classes in separate chunks can end up with the same name.",
},
messages: {
forbidden:
"Do not read `constructor.name`; minified builds rename classes and two classes can share a name. Key by the class itself (eg a WeakMap) or use a static property such as `modelName`.",
},
},
create(context) {
return {
MemberExpression(node) {
if (
isProperty(node, "name") &&
isProperty(node.object, "constructor")
) {
context.report({ node, messageId: "forbidden" });
}
},
};
},
},
},
};
export default plugin;
+133
View File
@@ -0,0 +1,133 @@
/**
* Local oxlint plugin with MobX-specific rules.
*/
/** Returns true if the decorator is `@observable` or `@observable.<modifier>`. */
function isObservableDecorator(decorator) {
const expression = decorator.expression;
if (expression.type === "Identifier") {
return expression.name === "observable";
}
if (expression.type === "MemberExpression") {
return (
expression.object.type === "Identifier" &&
expression.object.name === "observable"
);
}
return false;
}
/** Returns true if the expression is a `makeObservable(this, …)` call. */
function isMakeObservableCall(expression) {
return (
expression.type === "CallExpression" &&
expression.callee.type === "Identifier" &&
expression.callee.name === "makeObservable" &&
expression.arguments.length > 0 &&
expression.arguments[0].type === "ThisExpression"
);
}
/** Returns the property name if the expression is `this.<name> = …`, else null. */
function assignedThisProperty(expression) {
if (
expression.type !== "AssignmentExpression" ||
expression.left.type !== "MemberExpression" ||
expression.left.object.type !== "ThisExpression" ||
expression.left.property.type !== "Identifier"
) {
return null;
}
return expression.left.property.name;
}
/**
* Walks the constructor body and returns the set of `this.<name>` properties
* assigned before `makeObservable(this)` is called, or null if the constructor
* never calls it.
*/
function propertiesAssignedBeforeMakeObservable(classBody) {
const ctor = classBody.body.find(
(member) =>
member.type === "MethodDefinition" && member.kind === "constructor"
);
if (!ctor?.value?.body) {
return null;
}
const assigned = new Set();
for (const statement of ctor.value.body.body) {
if (statement.type !== "ExpressionStatement") {
continue;
}
if (isMakeObservableCall(statement.expression)) {
return assigned;
}
const name = assignedThisProperty(statement.expression);
if (name) {
assigned.add(name);
}
}
return null;
}
const plugin = {
meta: {
name: "mobx",
},
rules: {
"observable-needs-initializer": {
meta: {
type: "problem",
docs: {
description:
"Require an initializer on @observable class fields in classes that call makeObservable(this). A field that does not exist as an own property when makeObservable runs is silently skipped by MobX.",
},
messages: {
missing:
"@observable field '{{name}}' has no initializer, so makeObservable() will silently skip it. Add `= undefined` or another initial value.",
},
},
create(context) {
return {
ClassBody(node) {
const assigned = propertiesAssignedBeforeMakeObservable(node);
if (assigned === null) {
return;
}
for (const member of node.body) {
if (
member.type !== "PropertyDefinition" ||
member.value !== null ||
member.static ||
member.declare ||
member.key.type !== "Identifier" ||
assigned.has(member.key.name)
) {
continue;
}
const decorators = member.decorators ?? [];
if (!decorators.some(isObservableDecorator)) {
continue;
}
context.report({
node: member,
messageId: "missing",
data: { name: member.key.name },
});
}
},
};
},
},
},
};
export default plugin;
+14
View File
@@ -9,7 +9,9 @@
"patches/**",
"*.d.ts"
],
"jsPlugins": ["./.oxlint/mobx.mjs", "./.oxlint/bundle.mjs"],
"rules": {
"mobx/observable-needs-initializer": "error",
"for-direction": "error",
"no-async-promise-executor": "error",
"no-case-declarations": "error",
@@ -68,6 +70,18 @@
"valid-typeof": "error"
},
"overrides": [
{
"files": ["plugins/*/client/**/*.{js,jsx,ts,tsx}"],
"rules": {
"bundle/no-constructor-name": "error"
}
},
{
"files": ["**/*.{ts,tsx}"],
"rules": {
"no-redeclare": "off"
}
},
{
"files": ["**/*.{js,jsx,ts,tsx}"],
"rules": {
+1
View File
@@ -1,5 +1,6 @@
require("@dotenvx/dotenvx").config({
path: process.env.NODE_ENV === "test" ? ".env.test" : ".env",
quiet: true,
});
var path = require('path');
+1
View File
@@ -13,3 +13,4 @@ npmAuditIgnoreAdvisories:
- "1113517" # GHSA-mw96-cpmx-2vgc rollup <2.80.0 path traversal (workbox-build, build-time)
- "1113686" # GHSA-5c6j-r48x-rmvq serialize-javascript RCE (@rollup/plugin-terser, build-time)
- "1124334" # GHSA-mh99-v99m-4gvg brace-expansion DoS is a false positive
- "1240992" # GHSA-vfj7-8cjw-p6xm braces DoS, no patched release (patch-package, install-time)
+15
View File
@@ -32,6 +32,7 @@ You're an expert in the following areas:
- Critical – Do not create new markdown (.md) files.
- Use early returns for readability.
- Leave an empty line above every comment, unless the comment is the first line in a block.
- Emphasize type safety and static analysis.
- Follow consistent oxfmt formatting.
- Do not replace smart quotes ("") or ('') with simple quotes ("").
@@ -94,6 +95,10 @@ This keeps overrides scoped to the affected dependents and avoids forcing unrela
- Do not import React unless it is used directly.
- Use styled-components for component styling.
- Ensure high accessibility (a11y) standards using ARIA roles and semantic HTML.
- In components that stay mounted across navigation (layout, sidebar, command bar), do not use `useLocation`. Use `useLocationSelector` to select only the value you need, or read `history.location` in effects and handlers.
- Give stable props to memoized and `observer` components, especially list rows. Do not create new arrays, objects, or JSX on each render; use shared constants for empty arrays.
- Do not read `ref.current` during render to pass it to props or context. Keep the element in state with a callback ref.
- If the initial value of `useState` reads observables, use a lazy initializer. Otherwise the expression runs, and subscribes, on every render.
## MobX State Management
@@ -102,6 +107,10 @@ This keeps overrides scoped to the affected dependents and avoids forcing unrela
- Use `observable`, `action`, and `computed` decorators appropriately.
- Prefer computed values over manual calculations in render.
- Keep business logic in stores, not components.
- Do not read an observable during render only for an effect or a per-item check. Use `useComputed` to derive a narrow value (e.g. `isActive`) so only affected components re-render.
- Use `observable.map` rather than a set when observers check membership by key. `ObservableSet.has()` tracks the whole set, so any change re-renders every observer.
- Store lookups called for each row of a list must not scan a computed list such as `orderedData`, as this subscribes the component to every item in the store.
- A context value provided near the app root must not change on navigation. Expose frequently changing store values as getters read on access, not values read during render.
## Database & ORM
@@ -116,6 +125,8 @@ yarn sequelize migration:create --name=add-field-to-table
- Use transactions for multi-table operations.
- Add appropriate indexes for query performance.
- Always handle database errors gracefully.
- When updating Sequelize array or JSON attributes, replace the value instead of mutating it in place; reload the model in tests to verify persistence rather than trusting its in-memory state.
- Schedule optional background work that depends on a transaction from `afterCommit`, and use non-fatal scheduling so a queue failure does not fail the committed operation.
## API Design
@@ -133,12 +144,15 @@ yarn sequelize migration:create --name=add-field-to-table
- Use cancan-style ability checks.
- Use authenticated middleware for protected routes.
- Always verify user permissions before data access.
- Set account email and passkey management routes to `AuthenticationType.APP`; API-key authentication must not change login credentials or authenticators.
## Real-time Collaboration
- WebSocket connections for real-time updates.
- Use Y.js for collaborative editing.
- Handle connection state changes gracefully.
- For bulk deletions that drive authorization or WebSocket processing, load affected models in the transaction and delete each with request context so downstream processors receive the expected per-item events.
- Do not persist viewer-specific unfurls in shared document mentions; only store unfurls that map to a stable mention type.
## Documentation
@@ -168,6 +182,7 @@ yarn test:shared # All shared code tests
```
- Write unit tests for utilities and business logic in a collocated .test.ts file.
- Server tests share a module registry between files. A server test that uses `vi.mock` or `vi.resetModules` must start with `// @vitest-isolate true` so it runs isolated.
- Do not create new test directories
- Mock external dependencies appropriately in **mocks** folder.
- Aim for high code coverage but focus on critical paths.
-1
View File
@@ -1 +0,0 @@
AGENTS.md
+2 -2
View File
@@ -3,7 +3,7 @@ Business Source License 1.1
Parameters
Licensor: General Outline, Inc.
Licensed Work: Outline 1.10.0
Licensed Work: Outline 1.11.0
The Licensed Work is (c) 2026 General Outline, Inc.
Additional Use Grant: You may make use of the Licensed Work, provided that
you may not use the Licensed Work for a Document
@@ -15,7 +15,7 @@ Additional Use Grant: You may make use of the Licensed Work, provided that
Licensed Work by creating teams and documents
controlled by such third parties.
Change Date: 2030-09-01
Change Date: 2030-10-12
Change License: Apache License, Version 2.0
-20
View File
@@ -1,20 +0,0 @@
const storage = {};
export default {
setItem: function (key, value) {
storage[key] = value || "";
},
getItem: function (key) {
return key in storage ? storage[key] : null;
},
removeItem: function (key) {
delete storage[key];
},
get length() {
return Object.keys(storage).length;
},
key: function (i) {
var keys = Object.keys(storage);
return keys[i] || null;
},
};
+25
View File
@@ -0,0 +1,25 @@
const storage: Record<string, string> = {};
const localStorage: Storage = {
setItem(key: string, value: string) {
storage[key] = value || "";
},
getItem(key: string) {
return key in storage ? storage[key] : null;
},
removeItem(key: string) {
delete storage[key];
},
clear() {
Object.keys(storage).forEach((key) => delete storage[key]);
},
get length() {
return Object.keys(storage).length;
},
key(i: number) {
const keys = Object.keys(storage);
return keys[i] || null;
},
};
export default localStorage;
+7 -1
View File
@@ -4,8 +4,9 @@
"plugins": ["oxc", "eslint", "typescript", "react"],
"overrides": [
{
"files": ["**/*.{jsx,tsx}"],
"files": ["**/*.{js,jsx,ts,tsx}"],
"rules": {
"bundle/no-constructor-name": "error",
"no-restricted-globals": [
"error",
{
@@ -17,6 +18,11 @@
"error",
{
"paths": [
{
"name": "~/editor",
"allowTypeImports": true,
"message": "Import AsyncEditor from ~/components/AsyncEditor instead. A direct import pulls the editor into the importing chunk and bypasses the shared preload."
},
{
"name": "prosemirror-tables",
"importNames": [
+8 -4
View File
@@ -48,7 +48,7 @@ import {
import { ExportDialog } from "~/components/Export/ExportDialog";
import { isMobile } from "@shared/utils/browser";
import history from "~/utils/history";
import lazyWithRetry from "~/utils/lazyWithRetry";
import lazyWithRetry from "@shared/utils/lazyWithRetry";
import { openRouteInSplit } from "~/utils/splitView";
const ColorCollectionIcon = ({ collection }: { collection: Collection }) => (
@@ -65,13 +65,15 @@ export const openCollection = createActionWithChildren({
shortcut: ["o", "c"],
icon: <CollectionIcon />,
children: ({ stores }) => {
const collections = stores.collections.orderedData;
const collections = stores.collections.orderedData.filter(
(collection) => !collection.isPersonal
);
return collections.map((collection) =>
createInternalLinkAction({
// Note: using url which includes the slug rather than id here to bust
// cache if the collection is renamed
id: collection.path,
name: collection.name,
name: collection.displayName,
icon: <ColorCollectionIcon collection={collection} />,
section: CollectionSection,
to: collection.path,
@@ -125,7 +127,9 @@ export const editCollectionPermissions = createAction({
section: ActiveCollectionSection,
icon: <PadlockIcon />,
visible: ({ getActivePolicies }) =>
getActivePolicies(Collection).some((policy) => policy.abilities.update),
getActivePolicies(Collection).some(
(policy) => policy.abilities.manageUsers
),
perform: ({ t, getActiveModel, stores }) => {
const collection = getActiveModel(Collection);
if (!collection) {
+33 -25
View File
@@ -62,6 +62,7 @@ import DocumentPublish from "~/scenes/DocumentPublish";
import DeleteDocumentsInTrash from "~/scenes/Trash/components/DeleteDocumentsInTrash";
import ConfirmationDialog from "~/components/ConfirmationDialog";
import { DialogTitle } from "~/components/DialogTitle";
import { DocumentArchiveDialog } from "~/components/DocumentArchiveDialog";
import DocumentCopy from "~/components/DocumentExplorer/DocumentCopy";
import MarkdownIcon from "~/components/Icons/MarkdownIcon";
import { ImportDocumentDialog } from "~/components/ImportDocumentDialog";
@@ -111,13 +112,14 @@ import type {
ActionGroup,
ActionSeparator as TActionSeparator,
} from "~/types";
import lazyWithRetry from "~/utils/lazyWithRetry";
import lazyWithRetry from "@shared/utils/lazyWithRetry";
import env from "~/env";
import { isMac, isWindows } from "@shared/utils/browser";
import isCloudHosted from "~/utils/isCloudHosted";
import DocumentMove from "~/components/DocumentExplorer/DocumentMove";
const Insights = lazyWithRetry(
/** Lazy insights dialog, exported so that triggers can preload it. */
export const Insights = lazyWithRetry(
() => import("~/scenes/Document/components/Insights")
);
const SharePopover = lazyWithRetry(
@@ -490,7 +492,7 @@ export const starDocument = createAction({
(document) => document.star(),
(documents, succeeded, t) =>
documents.length > 1
? t("{{ count }} documents starred", { count: succeeded })
? t("{{ count }} document starred", { count: succeeded })
: undefined
);
setPersistedState(getHeaderExpandedKey("starred"), true);
@@ -518,7 +520,7 @@ export const unstarDocument = createAction({
(document) => document.unstar(),
(documents, succeeded, t) =>
documents.length > 1
? t("{{ count }} documents unstarred", { count: succeeded })
? t("{{ count }} document unstarred", { count: succeeded })
: undefined
),
});
@@ -586,7 +588,7 @@ export const unpublishDocument = createAction({
? t("Unpublished {{ documentName }}", {
documentName: documents[0].noun,
})
: t("{{ count }} documents unpublished", { count: succeeded })
: t("{{ count }} document unpublished", { count: succeeded })
),
});
@@ -719,10 +721,20 @@ export const shareDocument = createAction({
},
});
/**
* Shows a file extension in the shortcut slot of menu items only, the command
* bar would otherwise register it as a key sequence.
*/
const fileExtensionHint =
(extension: string) =>
({ isMenu }: ActionContext) =>
isMenu ? [extension] : undefined;
export const downloadDocumentAsMarkdown = createAction({
name: ({ t, isMenu }) => (isMenu ? t("Markdown") : t("Download as Markdown")),
analyticsName: "Download document as Markdown",
section: ActiveDocumentSection,
shortcut: fileExtensionHint(".md"),
keywords: "md markdown export download",
icon: <MarkdownIcon />,
iconInContextMenu: false,
@@ -744,6 +756,7 @@ export const downloadDocumentAsHTML = createAction({
name: ({ t, isMenu }) => (isMenu ? t("HTML") : t("Download as HTML")),
analyticsName: "Download document as HTML",
section: ActiveDocumentSection,
shortcut: fileExtensionHint(".html"),
keywords: "xml html export download",
icon: <CodeIcon />,
iconInContextMenu: false,
@@ -766,6 +779,7 @@ export const downloadDocumentAsTextBundle = createAction({
isMenu ? t("TextBundle") : t("Download as TextBundle"),
analyticsName: "Download document as TextBundle",
section: ActiveDocumentSection,
shortcut: fileExtensionHint(".textpack"),
keywords: "textbundle textpack bear ulysses export download",
icon: <ArchiveIcon />,
iconInContextMenu: false,
@@ -787,6 +801,7 @@ export const downloadDocumentAsPDF = createAction({
name: ({ t, isMenu }) => (isMenu ? t("PDF") : t("Download as PDF")),
analyticsName: "Download document as PDF",
section: ActiveDocumentSection,
shortcut: fileExtensionHint(".pdf"),
keywords: "pdf export download",
icon: <PDFIcon />,
iconInContextMenu: false,
@@ -975,7 +990,7 @@ export const pinDocumentToCollection = createAction({
(documents, succeeded, t) =>
documents.length === 1
? t("Pinned to collection")
: t("{{ count }} documents pinned", { count: succeeded })
: t("{{ count }} document pinned", { count: succeeded })
),
});
@@ -1036,7 +1051,7 @@ export const unpinDocument = createAction({
(documents, succeeded, t) =>
documents.length === 1
? t("Unpinned")
: t("{{ count }} documents unpinned", { count: succeeded })
: t("{{ count }} document unpinned", { count: succeeded })
),
});
@@ -1150,6 +1165,7 @@ export const printDocument = createAction({
name: ({ t, isMenu }) => (isMenu ? t("Print") : t("Print document")),
analyticsName: "Print document",
section: ActiveDocumentSection,
shortcut: ["Meta+P"],
icon: <PrintIcon />,
iconInContextMenu: false,
visible: ({ activeDocumentId }) => !!(activeDocumentId && window.print),
@@ -1358,7 +1374,7 @@ export const searchDocumentsForQueryActionFactory = (query: string) =>
createInternalLinkAction({
id: "search",
name: ({ t }) =>
t(`Search documents for "{{searchQuery}}"`, { searchQuery: query }),
t("Search documents for “{{ searchQuery }}”", { searchQuery: query }),
analyticsName: "Search documents",
section: SearchResultsSection,
priority: -1,
@@ -1450,29 +1466,21 @@ export const archiveDocument = createAction({
})
),
content: (
<ConfirmationDialog
onSubmit={async () => {
<DocumentArchiveDialog
count={documents.length}
onSubmit={async (reason) => {
const succeeded = await performBatch(documents, (document) =>
document.archive()
document.archive({ reason })
);
if (succeeded) {
toast.success(
documents.length === 1
? t("Document archived")
: t("{{ count }} documents archived", { count: succeeded })
: t("{{ count }} document archived", { count: succeeded })
);
}
}}
savingText={`${t("Archiving")}…`}
>
{documents.length === 1
? t(
"Archiving this document will remove it from the collection and search results."
)
: t(
"Archiving these documents will remove them from their collections and search results."
)}
</ConfirmationDialog>
/>
),
});
},
@@ -1501,7 +1509,7 @@ export const restoreDocument = createAction({
? t("{{ documentName }} restored", {
documentName: capitalize(documents[0].noun),
})
: t("{{ count }} documents restored", { count: succeeded })
: t("{{ count }} document restored", { count: succeeded })
),
});
@@ -1538,7 +1546,7 @@ export const restoreDocumentToCollection = createActionWithChildren({
const actions = collections.orderedData.map((collection) => {
const can = policies.abilities(collection.id);
return createAction({
name: collection.name,
name: collection.displayName,
section: ActiveDocumentSection,
icon: <CollectionIcon collection={collection} />,
visible: can.createDocument,
@@ -1611,7 +1619,7 @@ export const deleteDocument = createAction({
);
if (succeeded) {
toast.success(
t("{{ count }} documents moved to trash", { count: succeeded })
t("{{ count }} document moved to trash", { count: succeeded })
);
}
}}
+1 -1
View File
@@ -37,7 +37,7 @@ export const deleteEmojiActionFactory = (emoji: Emoji) =>
analyticsName: "Delete emoji",
section: EmojiSecion,
name: (t) => `${t("Delete")}…`,
title: (t) => t("Delete Emoji"),
title: (t) => t("Delete emoji"),
content: (onSubmit) => (
<EmojiDeleteDialog emoji={emoji} onSubmit={onSubmit} />
),
+1 -11
View File
@@ -10,7 +10,6 @@ import {
LogoutIcon,
ProfileIcon,
BrowserIcon,
ShapesIcon,
DraftsIcon,
BugIcon,
ImportIcon,
@@ -19,7 +18,7 @@ import { UrlHelper } from "@shared/utils/UrlHelper";
import { isMac } from "@shared/utils/browser";
import stores from "~/stores";
import type SearchQuery from "~/models/SearchQuery";
import KeyboardShortcuts from "~/scenes/KeyboardShortcuts";
import KeyboardShortcuts from "~/components/KeyboardShortcuts";
import {
createAction,
createExternalLinkAction,
@@ -140,15 +139,6 @@ export const navigateToProfileSettings = createInternalLinkAction({
to: settingsPath(),
});
export const navigateToTemplateSettings = createInternalLinkAction({
name: ({ t }) => t("Templates"),
analyticsName: "Navigate to template settings",
section: NavigationSection,
iconInContextMenu: false,
icon: <ShapesIcon />,
to: settingsPath("templates"),
});
export const navigateToNotificationSettings = createInternalLinkAction({
name: ({ t, isMenu }) =>
isMenu ? t("Notification settings") : t("Notifications"),
+2 -2
View File
@@ -78,8 +78,8 @@ export const createTeam = createAction({
export const desktopLoginTeam = dialogActionFactory({
analyticsName: "Login to workspace",
section: TeamSection,
name: (t) => t("Login to workspace"),
title: (t) => t("Login to workspace"),
name: (t) => t("Log in to workspace"),
title: (t) => t("Log in to workspace"),
content: () => <LoginDialog />,
icon: <ArrowIcon />,
keywords: "change switch workspace organization team",
+13 -2
View File
@@ -9,6 +9,7 @@ import {
PlusIcon,
PrintIcon,
PublishIcon,
SettingsIcon,
TrashIcon,
} from "outline-icons";
import { Trans } from "react-i18next";
@@ -52,6 +53,16 @@ export const createTemplate = createInternalLinkAction({
to: newTemplatePath(),
});
export const manageTemplates = createInternalLinkAction({
name: ({ t }) => t("Manage templates"),
analyticsName: "Manage templates",
section: TemplateSection,
icon: <SettingsIcon />,
visible: ({ currentTeamId, stores }) =>
!!stores.policies.abilities(currentTeamId!).readTemplate,
to: settingsPath("templates"),
});
export const deleteTemplate = dialogActionFactory({
analyticsName: "Delete template",
section: ActiveTemplateSection,
@@ -84,7 +95,7 @@ export const deleteTemplate = dialogActionFactory({
<Trans
defaults="Are you sure about that? Deleting the <em>{{ templateName }}</em> template is permanent."
values={{
templateName: templates[0].titleWithDefault,
templateName: templates[0].displayTitle,
}}
components={{
em: <strong />,
@@ -176,7 +187,7 @@ export const moveTemplateToWorkspace = createAction({
toast.success(t("Template moved"));
stores.dialogs.closeAllModals();
} catch (_err) {
toast.error(t("Couldn't move the template, try again?"));
toast.error(t("Couldn’t move the template, try again?"));
}
},
});
+7 -3
View File
@@ -25,12 +25,16 @@ export const getCurrentContext = createAction({
document: document
? {
id: document.id,
title: document.titleWithDefault,
title: document.displayTitle,
path: document.url,
}
: undefined,
collection: collection
? { id: collection.id, name: collection.name, path: collection.path }
? {
id: collection.id,
name: collection.displayName,
path: collection.path,
}
: undefined,
});
},
@@ -65,7 +69,7 @@ export const searchWorkspace = createAction({
return JSON.stringify(
results.map((result) => ({
id: result.document.id,
title: result.document.titleWithDefault,
title: result.document.displayTitle,
path: result.document.url,
context: result.context,
}))
+16 -19
View File
@@ -46,24 +46,7 @@ export function createAction(
...definition,
type: "action",
variant: "action",
perform: definition.perform
? (context) => {
// We must use the specific analytics name here as the action name is
// translated and potentially contains user strings.
if (definition.analyticsName) {
Analytics.track("perform_action", definition.analyticsName, {
context: context.isButton
? "button"
: context.isCommandBar
? "commandbar"
: context.isMCP
? "webmcp"
: "contextmenu",
});
}
return definition.perform(context);
}
: () => {},
perform: definition.perform ?? (() => {}),
id: definition.id ?? uuidv4(),
};
}
@@ -182,7 +165,7 @@ export function actionToMenuItem(
icon,
visible,
disabled,
tooltip: resolve<React.ReactChild>(action.tooltip, context),
tooltip: resolve<React.ReactNode>(action.tooltip, context),
selected: resolve<boolean>(action.selected, context),
dangerous: action.dangerous,
shortcut,
@@ -353,6 +336,20 @@ export async function performAction(
? () => history.push(resolve<LocationDescriptor>(action.to, context))
: () => window.open(action.url, action.target);
// We must use the specific analytics name here as the action name is
// translated and potentially contains user strings.
if (action.analyticsName) {
Analytics.track("perform_action", action.analyticsName, {
context: context.isButton
? "button"
: context.isCommandBar
? "commandbar"
: context.isMCP
? "webmcp"
: "contextmenu",
});
}
const result = perform();
if (result instanceof Promise) {
+3 -3
View File
@@ -6,7 +6,7 @@ export const CollectionsSection = ({ t }: ActionContext) => t("Collections");
export const ActiveCollectionSection = ({ t, stores }: ActionContext) => {
const activeCollection = stores.collections.active;
return `${t("Collection")} · ${activeCollection?.name}`;
return `${t("Collection")} · ${activeCollection?.displayName}`;
};
ActiveCollectionSection.priority = 0.8;
@@ -30,7 +30,7 @@ DocumentsSection.priority = 0.8;
export const ActiveDocumentSection = ({ t, stores }: ActionContext) => {
const activeDocument = stores.documents.active;
return `${t("Document")} · ${activeDocument?.titleWithDefault}`;
return `${t("Document")} · ${activeDocument?.displayTitle}`;
};
ActiveDocumentSection.priority = 0.9;
@@ -39,7 +39,7 @@ export const TemplateSection = ({ t }: ActionContext) => t("Template");
export const ActiveTemplateSection = ({ t, stores }: ActionContext) => {
const activeTemplate = stores.templates.active;
return `${t("Template")} · ${activeTemplate?.titleWithDefault}`;
return `${t("Template")} · ${activeTemplate?.displayTitle}`;
};
ActiveTemplateSection.priority = 0.9;
+59 -63
View File
@@ -1,10 +1,8 @@
/* oxlint-disable react/prop-types */
import { observer } from "mobx-react";
import * as React from "react";
import type { Props as TooltipProps } from "~/components/Tooltip";
import Tooltip from "~/components/Tooltip";
import { performAction, resolve } from "~/actions";
import useIsMounted from "~/hooks/useIsMounted";
import useActionContext from "~/hooks/useActionContext";
import type { ActionVariant, ActionWithChildren } from "~/types";
@@ -22,68 +20,66 @@ export type Props = React.HTMLAttributes<HTMLButtonElement> & {
/**
* Button that can be used to trigger an action definition.
*/
const ActionButton = React.forwardRef<HTMLButtonElement, Props>(
function ActionButton_(
{ action, tooltip, hideOnActionDisabled, ...rest }: Props,
ref: React.Ref<HTMLButtonElement>
) {
const actionContext = useActionContext({
isButton: true,
});
const isMounted = useIsMounted();
const [executing, setExecuting] = React.useState(false);
function ActionButton({
action,
tooltip,
hideOnActionDisabled,
ref,
...rest
}: Props & { ref?: React.Ref<HTMLButtonElement> }) {
const actionContext = useActionContext({
isButton: true,
});
const [executing, setExecuting] = React.useState(false);
if (!actionContext || !action) {
return <button {...rest} ref={ref} />;
}
const actionIsDisabled =
action.visible && !resolve<boolean>(action.visible, actionContext);
if (actionIsDisabled && hideOnActionDisabled) {
return null;
}
const disabled = rest.disabled || actionIsDisabled;
const label =
rest["aria-label"] ??
(typeof action.name === "function"
? action.name(actionContext)
: action.name);
const button = (
<button
{...rest}
aria-label={typeof label === "string" ? label : undefined}
disabled={disabled || executing}
ref={ref}
onClick={
actionContext
? (ev) => {
ev.preventDefault();
ev.stopPropagation();
const response = performAction(action, actionContext);
if (response?.finally) {
setExecuting(true);
void response.finally(
() => isMounted() && setExecuting(false)
);
}
}
: rest.onClick
}
>
{rest.children ?? label}
</button>
);
if (tooltip) {
return <Tooltip {...tooltip}>{button}</Tooltip>;
}
return button;
if (!actionContext || !action) {
return <button {...rest} ref={ref} />;
}
);
const actionIsDisabled =
action.visible && !resolve<boolean>(action.visible, actionContext);
if (actionIsDisabled && hideOnActionDisabled) {
return null;
}
const disabled = rest.disabled || actionIsDisabled;
const label =
rest["aria-label"] ??
(typeof action.name === "function"
? action.name(actionContext)
: action.name);
const button = (
<button
{...rest}
aria-label={typeof label === "string" ? label : undefined}
disabled={disabled || executing}
ref={ref}
onClick={
actionContext
? (ev) => {
ev.preventDefault();
ev.stopPropagation();
const response = performAction(action, actionContext);
if (response?.finally) {
setExecuting(true);
void response.finally(() => setExecuting(false));
}
}
: rest.onClick
}
>
{rest.children ?? label}
</button>
);
if (tooltip) {
return <Tooltip {...tooltip}>{button}</Tooltip>;
}
return button;
}
export default observer(ActionButton);
+5
View File
@@ -1,5 +1,6 @@
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { MOBILE_TOUCH_TARGET } from "@shared/constants";
import { s } from "@shared/styles";
import Flex from "~/components/Flex";
@@ -10,6 +11,10 @@ export const Action = styled(Flex)`
font-size: 15px;
flex-shrink: 0;
${breakpoint("mobile", "tablet")`
height: ${MOBILE_TOUCH_TARGET}px;
`};
&:empty {
display: none;
}
-1
View File
@@ -1,4 +1,3 @@
/* oxlint-disable prefer-rest-params */
/* global ga */
import { escape } from "es-toolkit/compat";
import * as React from "react";
+9 -5
View File
@@ -6,12 +6,16 @@ type Props = Omit<React.HTMLAttributes<HTMLDivElement>, "children"> & {
children: () => React.ReactNode;
onEscape?: (ev: React.KeyboardEvent<HTMLDivElement>) => void;
items: unknown[];
ref?: React.Ref<HTMLDivElement>;
};
function ArrowKeyNavigation(
{ children, onEscape, items, ...rest }: Props,
ref: React.RefObject<HTMLDivElement>
) {
function ArrowKeyNavigation({
children,
onEscape,
items,
ref,
...rest
}: Props) {
const handleKeyDown = React.useCallback(
(ev: React.KeyboardEvent<HTMLDivElement>) => {
if (onEscape) {
@@ -48,4 +52,4 @@ function ArrowKeyNavigation(
);
}
export default observer(React.forwardRef(ArrowKeyNavigation));
export default observer(ArrowKeyNavigation);
+13
View File
@@ -0,0 +1,13 @@
import lazyWithRetry from "@shared/utils/lazyWithRetry";
/**
* The editor core is the largest chunk in the app and is kept out of the
* initial bundle. This module stays light so routes can preload the chunk
* without pulling editor dependencies into their own chunk.
*/
const AsyncEditor = lazyWithRetry(
// oxlint-disable-next-line no-restricted-imports -- the one place the chunk is loaded
() => import("~/editor")
);
export default AsyncEditor;
+1 -1
View File
@@ -8,7 +8,7 @@ import { changeLanguage } from "~/utils/language";
import LoadingIndicator from "./LoadingIndicator";
type Props = {
children: JSX.Element;
children: React.JSX.Element;
};
const Authenticated = ({ children }: Props) => {
+10 -8
View File
@@ -1,7 +1,6 @@
import { observer } from "mobx-react";
import * as React from "react";
import { DndProvider } from "react-dnd";
import { useLocation } from "react-router-dom";
import { EditorAwareHTML5Backend } from "~/components/EditorAwareHTML5Backend";
import ErrorSuspended from "~/scenes/Errors/ErrorSuspended";
import Layout from "~/components/Layout";
@@ -14,10 +13,11 @@ import useKeyDown from "~/hooks/useKeyDown";
import useWebMCPActions from "~/hooks/useWebMCPActions";
import { usePostLoginPath } from "~/hooks/useLastVisitedPath";
import usePolicy from "~/hooks/usePolicy";
import { useLocationSelector } from "~/hooks/useLocationSelector";
import useStores from "~/hooks/useStores";
import Logger from "~/utils/Logger";
import history from "~/utils/history";
import lazyWithRetry from "~/utils/lazyWithRetry";
import lazyWithRetry from "@shared/utils/lazyWithRetry";
import {
searchPath,
newDocumentPath,
@@ -40,8 +40,12 @@ type Props = {
const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => {
const { ui, auth } = useStores();
const location = useLocation();
const layoutRef = React.useRef<HTMLDivElement>(null);
const isSettings = useLocationSelector((location) =>
location.pathname.startsWith(settingsPath())
);
// State rather than a ref, so that portals receive the element once mounted.
const [layoutElement, setLayoutElement] =
React.useState<HTMLDivElement | null>(null);
const canCollection = usePolicy(ui.activeCollectionId);
const team = useCurrentTeam();
const [spendPostLoginPath] = usePostLoginPath();
@@ -87,8 +91,6 @@ const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => {
return <ErrorSuspended />;
}
const isSettings = location.pathname.startsWith(settingsPath());
const sidebar = (
<Fade>
<React.Suspense fallback={null}>
@@ -103,13 +105,13 @@ const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => {
return (
<DocumentContextProvider>
<RightSidebarProvider>
<PortalContext.Provider value={layoutRef.current}>
<PortalContext.Provider value={layoutElement}>
<DndProvider backend={EditorAwareHTML5Backend}>
<Layout
title={team.name}
sidebar={sidebar}
sidebarCanCollapse={!isSettings}
ref={layoutRef}
ref={setLayoutElement}
>
<RegisterKeyDown trigger="n" handler={goToNewDocument} />
<RegisterKeyDown trigger="t" handler={goToSearch} />
+5 -5
View File
@@ -49,16 +49,16 @@ export type AvatarProps = {
showTooltip?: boolean;
/** Whether to show a profile card on hover for users, defaults to true */
showHoverCard?: boolean;
/** Ref to the outer element */
ref?: React.Ref<HTMLDivElement>;
} & Omit<
React.ComponentPropsWithoutRef<"div">,
"onClick" | "className" | "style"
>;
const Avatar = React.forwardRef(function Avatar_(
props: AvatarProps,
ref: React.Ref<HTMLDivElement>
) {
function Avatar(props: AvatarProps) {
const {
ref,
model,
style,
variant = AvatarVariant.Round,
@@ -111,7 +111,7 @@ const Avatar = React.forwardRef(function Avatar_(
) : (
content
);
});
}
const Relative = styled.div<{ $variant: AvatarVariant; $size: AvatarSize }>`
position: relative;
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
import * as React from "react";
import { UserHoverCard } from "~/components/UserHoverCard";
import User from "~/models/User";
import type { AvatarProps } from "./Avatar";
@@ -9,10 +8,12 @@ import Avatar from "./Avatar";
* An avatar that additionally displays a profile card on hover when the model
* it represents is a user.
*/
const AvatarWithHoverCard = React.forwardRef(function AvatarWithHoverCard_(
{ showTooltip, showHoverCard = true, ...props }: AvatarProps,
ref: React.Ref<HTMLDivElement>
) {
function AvatarWithHoverCard({
showTooltip,
showHoverCard = true,
ref,
...props
}: AvatarProps) {
const { model } = props;
if (!showHoverCard || !(model instanceof User)) {
@@ -24,6 +25,6 @@ const AvatarWithHoverCard = React.forwardRef(function AvatarWithHoverCard_(
<Avatar ref={ref} {...props} />
</UserHoverCard>
);
});
}
export default observer(AvatarWithHoverCard);
+1 -1
View File
@@ -82,7 +82,7 @@ function AvatarWithPresence({
// real user, there's no profile to show for it.
if (!(user instanceof User)) {
return (
<Tooltip content={<Centered>{name}</Centered>} placement="bottom">
<Tooltip content={<Centered>{name}</Centered>} side="bottom">
{avatar}
</Tooltip>
);
+39 -8
View File
@@ -1,6 +1,11 @@
import { observer } from "mobx-react";
import { GroupIcon } from "outline-icons";
import { useTheme } from "styled-components";
import Icon from "@shared/components/Icon";
import Squircle from "@shared/components/Squircle";
import { IconType } from "@shared/types";
import useContrastColor from "@shared/hooks/useContrastColor";
import { determineIconType } from "@shared/utils/icon";
import type Group from "~/models/Group";
import { AvatarSize } from "../Avatar/Avatar";
@@ -16,20 +21,46 @@ type Props = {
className?: string;
};
export function GroupAvatar({
export const GroupAvatar = observer(function GroupAvatar_({
group,
color,
backgroundColor,
size = AvatarSize.Medium,
className,
}: Props) {
const theme = useTheme();
const contrastColor = useContrastColor();
const iconType = determineIconType(group.icon);
const iconSize = size * 0.75;
if (group.icon && iconType !== IconType.SVG) {
return (
<Squircle
color={color ?? theme.backgroundSecondary}
size={size}
className={className}
>
<Icon value={group.icon} size={iconSize} initial={group.initial} />
</Squircle>
);
}
const groupColor = contrastColor(group.color, theme.text);
const foreground = backgroundColor ?? theme.background;
return (
<Squircle color={color ?? theme.text} size={size} className={className}>
<GroupIcon
data-fixed-color
color={backgroundColor ?? theme.background}
size={size * 0.75}
/>
<Squircle color={color ?? groupColor} size={size} className={className}>
{group.icon ? (
<Icon
value={group.icon}
color={foreground}
size={iconSize}
initial={group.initial}
forceColor
/>
) : (
<GroupIcon data-fixed-color color={foreground} size={iconSize} />
)}
</Squircle>
);
}
});
+33 -13
View File
@@ -2,7 +2,7 @@ import { GoToIcon } from "outline-icons";
import { observer } from "mobx-react";
import * as React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import styled, { css } from "styled-components";
import { s, ellipsis } from "@shared/styles";
import Flex from "~/components/Flex";
import BreadcrumbMenu from "~/menus/BreadcrumbMenu";
@@ -20,12 +20,16 @@ type Props = React.PropsWithChildren<{
actions: InternalLinkAction[];
max?: number;
highlightFirstItem?: boolean;
ref?: React.Ref<HTMLDivElement>;
}>;
function Breadcrumb(
{ actions, highlightFirstItem, children, max = 2 }: Props,
ref: React.RefObject<HTMLDivElement> | null
) {
function Breadcrumb({
actions,
highlightFirstItem,
children,
max = 2,
ref,
}: Props) {
const actionContext = useActionContext({ isMenu: true });
const visibleActions = useComputed(
@@ -71,13 +75,20 @@ function Breadcrumb(
}
const item = actionToMenuItem(action, actionContext) as MenuInternalLink;
const highlight = !!highlightFirstItem && index === 0;
// Items without a destination are shown as plain text.
if (!item.to) {
return (
<StaticItem $highlight={highlight}>
{item.icon}
<Title>{item.title}</Title>
</StaticItem>
);
}
return (
<Item
to={item.to}
onClick={handleClick}
$highlight={!!highlightFirstItem && index === 0}
>
<Item to={item.to} onClick={handleClick} $highlight={highlight}>
{item.icon}
<Title>{item.title}</Title>
</Item>
@@ -106,7 +117,7 @@ const Slash = styled(GoToIcon)`
fill: ${s("divider")};
`;
const Item = styled(Link)<{ $highlight: boolean }>`
const itemStyles = css<{ $highlight: boolean }>`
${undraggableOnDesktop()}
display: flex;
@@ -114,7 +125,6 @@ const Item = styled(Link)<{ $highlight: boolean }>`
gap: 4px;
flex-shrink: 1;
min-width: 0;
cursor: var(--pointer);
color: ${s("text")};
font-size: 15px;
height: 32px;
@@ -127,6 +137,11 @@ const Item = styled(Link)<{ $highlight: boolean }>`
margin-inline-start: 0;
}
max-width: 460px;
`;
const Item = styled(Link)<{ $highlight: boolean }>`
${itemStyles}
cursor: var(--pointer);
transition: background 100ms ease-in-out;
&:hover,
@@ -136,9 +151,14 @@ const Item = styled(Link)<{ $highlight: boolean }>`
}
`;
const StaticItem = styled.span<{ $highlight: boolean }>`
${itemStyles}
cursor: default;
`;
const Title = styled.span`
${ellipsis()}
min-width: 0;
`;
export default observer(React.forwardRef<HTMLDivElement, Props>(Breadcrumb));
export default observer(Breadcrumb);
+32 -8
View File
@@ -3,6 +3,8 @@ import { DisclosureIcon } from "outline-icons";
import { darken, lighten, transparentize } from "polished";
import * as React from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { MOBILE_TOUCH_TARGET } from "@shared/constants";
import { s } from "@shared/styles";
import type { Props as ActionButtonProps } from "~/components/ActionButton";
import ActionButton from "~/components/ActionButton";
@@ -36,6 +38,12 @@ const RealButton = styled(ActionButton)<RealProps>`
transition: background 200ms ease-out;
${undraggableOnDesktop()}
${breakpoint("mobile", "tablet")`
height: ${MOBILE_TOUCH_TARGET}px;
border-radius: ${MOBILE_TOUCH_TARGET / 2}px;
font-size: 16px;
`};
&::-moz-focus-inner {
padding: 0;
border: 0;
@@ -126,11 +134,13 @@ const Label = styled.span<{ hasIcon?: boolean }>`
${(props) => props.hasIcon && "padding-inline-start: 4px;"};
`;
export const Inner = styled.span<{
interface InnerProps {
disclosure?: boolean;
hasIcon?: boolean;
hasText?: boolean;
}>`
}
export const Inner = styled.span<InnerProps>`
display: flex;
padding: 0 8px;
padding-inline-end: ${(props) => (props.disclosure ? 2 : 8)}px;
@@ -141,6 +151,18 @@ export const Inner = styled.span<{
${(props) => props.hasIcon && props.hasText && "padding-inline-start: 4px;"};
${(props) => props.hasIcon && !props.hasText && "padding: 0 4px;"};
${breakpoint("mobile", "tablet")`
min-height: ${MOBILE_TOUCH_TARGET}px;
padding: 0 16px;
padding-inline-end: ${(props: InnerProps) => (props.disclosure ? 8 : 16)}px;
${(props: InnerProps) =>
props.hasIcon && props.hasText && "padding-inline-start: 12px;"};
${(props: InnerProps) =>
props.hasIcon &&
!props.hasText &&
`padding: 0 ${(MOBILE_TOUCH_TARGET - 24) / 2}px;`};
`};
`;
export type Props<T> = ActionButtonProps & {
@@ -158,13 +180,14 @@ export type Props<T> = ActionButtonProps & {
"data-on"?: string;
"data-event-category"?: string;
"data-event-action"?: string;
ref?: React.Ref<HTMLButtonElement>;
};
const Button = <T extends React.ElementType = "button">(
props: Props<T> & React.ComponentPropsWithoutRef<T>,
ref: React.Ref<HTMLButtonElement>
) => {
function Button<T extends React.ElementType = "button">(
props: Props<T> & React.ComponentPropsWithoutRef<T>
) {
const {
ref,
type,
children,
value,
@@ -191,6 +214,7 @@ const Button = <T extends React.ElementType = "button">(
$danger={danger}
$fullwidth={fullwidth}
$borderOnHover={borderOnHover}
data-variant={danger ? "danger" : neutral ? "neutral" : "primary"}
{...rest}
>
<Inner hasIcon={hasIcon} hasText={hasText} disclosure={disclosure}>
@@ -200,10 +224,10 @@ const Button = <T extends React.ElementType = "button">(
</Inner>
</RealButton>
);
};
}
const StyledDisclosureIcon = styled(DisclosureIcon)`
opacity: 0.8;
`;
export default React.forwardRef(Button);
export default Button;
+20 -5
View File
@@ -1,7 +1,9 @@
import { filter, isEqual, orderBy, uniq } from "es-toolkit/compat";
import { observer } from "mobx-react";
import styled from "styled-components";
import { useState, useMemo, useEffect, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { MOBILE_TOUCH_TARGET } from "@shared/constants";
import type Document from "~/models/Document";
import type User from "~/models/User";
import type { AvatarProps } from "~/components/Avatar";
@@ -15,8 +17,12 @@ import {
PopoverContent,
} from "~/components/primitives/Popover";
import useCurrentUser from "~/hooks/useCurrentUser";
import useMobile from "~/hooks/useMobile";
import useStores from "~/hooks/useStores";
/** Space after the avatars on mobile, matching the inset of a 24px icon in a touch target. */
const MobileIconInset = (MOBILE_TOUCH_TARGET - 24) / 2;
type Props = {
/** The document to display live collaborators for */
document: Document;
@@ -31,6 +37,8 @@ type Props = {
function Collaborators(props: Props) {
const { limit = 6 } = props;
const { t } = useTranslation();
const isMobile = useMobile();
const size = isMobile ? AvatarSize.XLarge : AvatarSize.Large;
const user = useCurrentUser();
const currentUserId = user?.id;
const [requestedUserIds, setRequestedUserIds] = useState<string[]>([]);
@@ -163,21 +171,23 @@ function Collaborators(props: Props) {
return null;
}
const facepileWidth = Math.min(collaborators.length, limit) * size;
return (
<Popover>
<PopoverTrigger>
<NudeButton
width={Math.min(collaborators.length, limit) * AvatarSize.Large}
height={AvatarSize.Large}
<FacepileButton
width={isMobile ? facepileWidth + MobileIconInset : facepileWidth}
height={isMobile ? MOBILE_TOUCH_TARGET : size}
>
<Facepile
size={AvatarSize.Large}
size={size}
limit={limit}
overflow={Math.max(0, collaborators.length - limit)}
users={collaborators}
renderAvatar={renderAvatar}
/>
</NudeButton>
</FacepileButton>
</PopoverTrigger>
<PopoverContent aria-label={t("Viewers")} side="bottom" align="end">
<DocumentViews document={document} />
@@ -186,4 +196,9 @@ function Collaborators(props: Props) {
);
}
const FacepileButton = styled(NudeButton)`
display: inline-flex;
align-items: center;
`;
export default observer(Collaborators);
+2 -2
View File
@@ -56,7 +56,7 @@ const useIconColor = (collection?: Collection) => {
: randomElement(colorPalette)),
// Deliberately only keyed on the collection color so the randomly picked
// fallback stays stable while the form is open.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[collection?.color]
);
return iconColor;
@@ -273,7 +273,7 @@ export const CollectionForm = observer(function CollectionForm_({
field.onChange(value === EmptySelectValue ? null : value);
}}
help={t(
"The default access for workspace members, you can share with more users or groups later."
"The default access for workspace members. You can share with more users or groups later."
)}
/>
)}
+1 -1
View File
@@ -25,7 +25,7 @@ export const CollectionBreadcrumb: React.FC<Props> = ({ collection }) => {
to: archivePath(),
}),
createInternalLinkAction({
name: collection.name,
name: collection.displayName,
section: ActiveCollectionSection,
icon: <CollectionIcon collection={collection} expanded />,
to: collectionPath(collection),
+2 -2
View File
@@ -44,7 +44,7 @@ function CollectionDeleteDialog({ collection, onSubmit }: Props) {
<Trans
defaults="Are you sure about that? Deleting the <em>{{collectionName}}</em> collection is permanent and cannot be restored, however all published documents within will be moved to the trash."
values={{
collectionName: collection.name,
collectionName: collection.displayName,
}}
components={{
em: <strong />,
@@ -56,7 +56,7 @@ function CollectionDeleteDialog({ collection, onSubmit }: Props) {
<Trans
defaults="Also, <em>{{collectionName}}</em> is being used as the start view – deleting it will reset the start view to the Home page."
values={{
collectionName: collection.name,
collectionName: collection.displayName,
}}
components={{
em: <strong />,
+11 -7
View File
@@ -10,13 +10,17 @@ type Props = React.HTMLAttributes<HTMLButtonElement> & {
active?: boolean;
/** The size of the button in pixels */
size?: number;
ref?: React.Ref<HTMLButtonElement>;
};
export const ColorButton = React.forwardRef(
(
{ color, active = false, size = 24, ...rest }: Props,
ref: React.Ref<HTMLButtonElement>
) => (
export function ColorButton({
color,
active = false,
size = 24,
ref,
...rest
}: Props) {
return (
<ColorButtonInternal
$active={active}
$size={size}
@@ -26,8 +30,8 @@ export const ColorButton = React.forwardRef(
>
<Selected />
</ColorButtonInternal>
)
);
);
}
/** Highlight for the hovered or selected swatch, falls back for the gradient. */
const ring = css`2px solid var(--color, ${s("textTertiary")})`;
+1 -1
View File
@@ -2,10 +2,10 @@ import { useKBar, KBarPositioner, KBarAnimator, KBarSearch } from "kbar";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { Portal } from "react-portal";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { depths, s } from "@shared/styles";
import { Portal } from "~/components/Portal";
import SearchActions from "~/components/SearchActions";
import rootActions from "~/actions/root";
import useCommandBarActions from "~/hooks/useCommandBarActions";
+3 -5
View File
@@ -14,6 +14,7 @@ type Props = {
action: CommandBarActionImpl;
active: boolean;
currentRootActionId: string | null | undefined;
ref?: React.Ref<HTMLDivElement>;
};
const SEARCH_RESULT_REGEX = /<b\b[^>]*>(.*?)<\/b>/gi;
@@ -24,10 +25,7 @@ function replaceResultMarks(tag: string) {
return tag.replace(/<b\b[^>]*>(.*?)<\/b>/gi, "$1");
}
function CommandBarItem(
{ action, active, currentRootActionId }: Props,
ref: React.RefObject<HTMLDivElement>
) {
function CommandBarItem({ action, active, currentRootActionId, ref }: Props) {
const theme = useTheme();
const ancestors = React.useMemo(() => {
if (!currentRootActionId || !action.ancestors) {
@@ -168,4 +166,4 @@ const ForwardIcon = styled(BackIcon)`
flex-shrink: 0;
`;
export default React.forwardRef<HTMLDivElement, Props>(CommandBarItem);
export default CommandBarItem;
@@ -255,6 +255,47 @@ describe("SearchIndex", () => {
expect(results[0]?.document.id).toBe("1");
});
it("weights heading matches above content matches", () => {
const index = new SearchIndex();
index.update([
{ id: "1", title: "Team", url: "/doc/1", text: "onboarding guide" },
{
id: "2",
title: "People",
url: "/doc/2",
text: "Onboarding\nhow new starters get set up in their first week",
headings: ["Onboarding"],
},
]);
const results = index.search("onboarding");
expect(results[0]?.document.id).toBe("2");
});
it("preserves previously indexed headings when a later update omits them", () => {
const index = new SearchIndex();
index.update([
{ id: "1", title: "Team", url: "/doc/1", headings: ["Onboarding"] },
]);
expect(index.update([{ id: "1", title: "Team", url: "/doc/1" }])).toBe(
false
);
expect(index.search("onboarding")[0]?.document.id).toBe("1");
});
it("reports a change when headings change", () => {
const index = new SearchIndex();
index.update([{ id: "1", title: "A", url: "/doc/1", headings: ["One"] }]);
expect(
index.update([{ id: "1", title: "A", url: "/doc/1", headings: ["One"] }])
).toBe(false);
expect(
index.update([{ id: "1", title: "A", url: "/doc/1", headings: ["Two"] }])
).toBe(true);
});
it("reports whether an update changed the collection", () => {
const index = new SearchIndex();
expect(index.update([{ id: "1", title: "A", url: "/doc/1" }])).toBe(true);
+9 -2
View File
@@ -1,4 +1,4 @@
import { escapeRegExp } from "es-toolkit/compat";
import { escapeRegExp, isEqual } from "es-toolkit/compat";
import Fuse, { type IFuseOptions } from "fuse.js";
/** A document as represented within the search index. */
@@ -8,6 +8,8 @@ export interface SearchIndexDocument {
title: string;
/** Plain text content of the document, may be absent until it has loaded. */
text?: string;
/** Plain text of each heading in the document, may be absent until it has loaded. */
headings?: string[];
url: string;
icon?: string | null;
color?: string | null;
@@ -36,7 +38,8 @@ enum TitleRanking {
const options: IFuseOptions<SearchIndexDocument> = {
keys: [
{ name: "title", weight: 2 },
{ name: "title", weight: 4 },
{ name: "headings", weight: 2 },
{ name: "text", weight: 1 },
],
includeScore: true,
@@ -197,11 +200,15 @@ export class SearchIndex {
if (incoming.text === undefined && existing?.text !== undefined) {
merged.text = existing.text;
}
if (incoming.headings === undefined && existing?.headings !== undefined) {
merged.headings = existing.headings;
}
if (
existing &&
existing.title === merged.title &&
existing.text === merged.text &&
isEqual(existing.headings, merged.headings) &&
existing.url === merged.url &&
existing.isArchived === merged.isArchived
) {
@@ -2,10 +2,10 @@ import { useKBar, KBarPositioner, KBarAnimator, KBarSearch } from "kbar";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { Portal } from "react-portal";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { depths, s } from "@shared/styles";
import { Portal } from "~/components/Portal";
import CommandBarResults from "./CommandBarResults";
import SharedSearchActions from "./SharedSearchActions";
@@ -43,7 +43,7 @@ const useRecentDocumentActions = (count = recentDocumentCount) => {
count
).map((item) =>
createInternalLinkAction({
name: item.titleWithDefault,
name: item.displayTitle,
analyticsName: "Recently viewed document",
section: RecentSection,
visible: ({ isMCP }) => !isMCP,
+31 -16
View File
@@ -1,6 +1,7 @@
import { useCallback, useMemo, useRef, useState } from "react";
import type Document from "~/models/Document";
import { LRUCache } from "@shared/utils/LRUCache";
import { ProsemirrorHelper as SharedProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
import { ProsemirrorHelper } from "~/models/helpers/ProsemirrorHelper";
import {
SearchIndex,
@@ -8,26 +9,37 @@ import {
type SearchIndexResult,
} from "./SearchIndex";
const plainTextCache = new LRUCache<{ updatedAt: string; text: string }>({
interface DocumentContent {
text: string;
headings: string[];
}
const contentCache = new LRUCache<{ updatedAt: string } & DocumentContent>({
max: 100,
storage: "memory",
});
/**
* Returns the plain text content of a document, memoized so that repeated
* indexing passes do not reparse unchanged ProseMirror data. The cache holds at
* most one entry per document, invalidated when the document is edited, and is
* bounded to the most recently used documents.
* Returns the plain text and heading texts of a document, memoized so that
* repeated indexing passes do not reparse unchanged ProseMirror data. The cache
* holds at most one entry per document, invalidated when the document is
* edited, and is bounded to the most recently used documents.
*/
function getPlainText(doc: Document): string {
function getContent(doc: Document): DocumentContent {
const updatedAt = String(doc.updatedAt ?? "");
const cached = plainTextCache.get(doc.id);
const cached = contentCache.get(doc.id);
if (cached?.updatedAt === updatedAt) {
return cached.text;
return cached;
}
const text = ProsemirrorHelper.toPlainText(doc);
plainTextCache.set(doc.id, { updatedAt, text });
return text;
const node = ProsemirrorHelper.toNode(doc);
const content = {
text: SharedProsemirrorHelper.toPlainText(node),
headings: SharedProsemirrorHelper.getHeadings(node).map(
(heading) => heading.title
),
};
contentCache.set(doc.id, { updatedAt, ...content });
return content;
}
/** Removes server-generated `<b>` highlight tags from a context snippet. */
@@ -47,11 +59,14 @@ export function toSearchRecord(
doc: Document,
context?: string
): SearchIndexDocument {
const content = doc.data ? getContent(doc) : undefined;
return {
id: doc.id,
title: doc.titleWithDefault,
title: doc.displayTitle,
url: doc.url,
text: doc.data ? getPlainText(doc) : stripHighlightTags(context),
text: content ? content.text : stripHighlightTags(context),
headings: content?.headings,
icon: doc.icon,
color: doc.color,
isArchived: doc.isArchived,
@@ -90,7 +105,7 @@ export interface UseSearchIndex {
* @returns the current results and functions to feed or reset the index.
*/
export function useSearchIndex(query: string): UseSearchIndex {
const indexRef = useRef<SearchIndex>();
const indexRef = useRef<SearchIndex | undefined>(undefined);
if (!indexRef.current) {
indexRef.current = new SearchIndex();
}
@@ -110,14 +125,14 @@ export function useSearchIndex(query: string): UseSearchIndex {
const reset = useCallback(() => {
index.clear();
plainTextCache.clear();
contentCache.clear();
setVersion((v) => v + 1);
}, [index]);
const results = useMemo<SearchIndexResult[]>(
() => (query ? index.search(query) : []),
// The index mutates in place, so `version` is what marks the memo stale.
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
[index, query, version]
);
@@ -1,3 +1,4 @@
import { useKBar } from "kbar";
import { NewDocumentIcon, ShapesIcon } from "outline-icons";
import { useEffect, useMemo } from "react";
import Icon from "@shared/components/Icon";
@@ -12,16 +13,22 @@ import { newDocumentPath } from "~/utils/routeHelpers";
const useTemplatesAction = () => {
const { templates } = useStores();
const { showing } = useKBar((state) => ({
showing: state.visualState !== "hidden",
}));
// Templates are only needed once the command bar is opened.
useEffect(() => {
void templates.fetchAll();
}, [templates]);
if (showing) {
void templates.fetchAllIfNeeded();
}
}, [showing, templates]);
const actions = useMemo(
() =>
templates.alphabetical.map((template) =>
createInternalLinkAction({
name: template.titleWithDefault,
name: template.displayTitle,
analyticsName: "New document",
section: template.isWorkspaceTemplate
? TeamSection
+3 -3
View File
@@ -46,7 +46,7 @@ function ConfirmMoveDialog({ collection, item, ...rest }: Props) {
"You do not have permission to move {{ documentName }} to the {{ collectionName }} collection",
{
documentName: item.title,
collectionName: collection.name,
collectionName: collection.displayName,
}
)
);
@@ -68,8 +68,8 @@ function ConfirmMoveDialog({ collection, item, ...rest }: Props) {
defaults="Moving the document <em>{{ title }}</em> to the {{ newCollectionName }} collection will change permission for all workspace members from <em>{{ prevPermission }}</em> to <em>{{ newPermission }}</em>."
values={{
title: item.title,
prevCollectionName: prevCollection?.name,
newCollectionName: collection.name,
prevCollectionName: prevCollection?.displayName,
newCollectionName: collection.displayName,
prevPermission: accessMapping[prevCollection?.permission || "null"],
newPermission: accessMapping[collection.permission || "null"],
}}
+115 -32
View File
@@ -1,7 +1,9 @@
import isPrintableKeyEvent from "is-printable-key-event";
import * as React from "react";
import { useMergeRefs } from "react-merge-refs";
import styled from "styled-components";
import { s } from "@shared/styles";
import { TextHelper } from "@shared/utils/TextHelper";
import useOnScreen from "~/hooks/useOnScreen";
type Props = Omit<React.HTMLAttributes<HTMLSpanElement>, "ref" | "onChange"> & {
@@ -13,11 +15,13 @@ type Props = Omit<React.HTMLAttributes<HTMLSpanElement>, "ref" | "onChange"> & {
onBlur?: React.FocusEventHandler<HTMLSpanElement> | undefined;
onInput?: React.FormEventHandler<HTMLSpanElement> | undefined;
onKeyDown?: React.KeyboardEventHandler<HTMLSpanElement> | undefined;
onCompositionEnd?: React.CompositionEventHandler<HTMLSpanElement> | undefined;
placeholder?: string;
maxLength?: number;
autoFocus?: boolean;
children?: React.ReactNode;
value: string;
ref?: React.Ref<RefHandle>;
};
export type RefHandle = {
@@ -31,29 +35,29 @@ export type RefHandle = {
* Defines a content editable component with the same interface as a native
* HTMLInputElement (or, as close as we can get).
*/
const ContentEditable = React.forwardRef(function ContentEditable_(
{
disabled,
onChange,
onInput,
onFocus,
onBlur,
onKeyDown,
value,
children,
className,
maxLength,
autoFocus,
placeholder,
readOnly,
dir,
onClick,
...rest
}: Props,
ref: React.RefObject<RefHandle>
) {
function ContentEditable({
disabled,
onChange,
onInput,
onFocus,
onBlur,
onKeyDown,
onCompositionEnd,
value,
children,
className,
maxLength,
autoFocus,
placeholder,
readOnly,
dir,
onClick,
ref,
...rest
}: Props) {
const contentRef = React.useRef<HTMLSpanElement>(null);
const [innerValue, setInnerValue] = React.useState<string>(value);
const [isEmpty, setIsEmpty] = React.useState(value.length === 0);
const lastValue = React.useRef(value);
React.useImperativeHandle(ref, () => ({
@@ -95,18 +99,33 @@ const ContentEditable = React.forwardRef(function ContentEditable_(
return;
}
const text = event.currentTarget.textContent || "";
let text = event.currentTarget.textContent || "";
setIsEmpty(text.length === 0);
const overLimit =
!!maxLength && TextHelper.codePointLength(text) > maxLength;
if (
maxLength &&
event.nativeEvent instanceof KeyboardEvent &&
isPrintableKeyEvent(event.nativeEvent) &&
text.length >= maxLength
TextHelper.codePointLength(text) >= maxLength
) {
event.preventDefault();
return;
}
// Paste, drop, IME and other non-keyboard input paths bypass the check
// above, so clamp whatever landed in the DOM. Editing the DOM would
// break an active IME session, so wait for composition end and do not
// publish the over-limit buffer in the meantime.
if (overLimit && maxLength) {
if (isComposing(event)) {
callback?.(event);
return;
}
text = truncateContent(event.currentTarget, maxLength);
}
if (text !== lastValue.current) {
lastValue.current = text;
onChange?.(text);
@@ -119,7 +138,8 @@ const ContentEditable = React.forwardRef(function ContentEditable_(
// case the component may be rendered with display: none. React 18 may solve
// this in the future by delaying useEffect hooks:
// https://github.com/facebook/react/issues/14536#issuecomment-861980492
const isVisible = useOnScreen(contentRef);
const [onScreenRef, isVisible] = useOnScreen();
const mergedRef = useMergeRefs([contentRef, onScreenRef]);
React.useEffect(() => {
if (autoFocus && isVisible && !disabled && !readOnly) {
@@ -128,8 +148,17 @@ const ContentEditable = React.forwardRef(function ContentEditable_(
}, [autoFocus, disabled, isVisible, readOnly, contentRef]);
React.useEffect(() => {
if (contentRef.current && value !== contentRef.current.textContent) {
if (document.activeElement === contentRef.current) {
if (!contentRef.current) {
return;
}
const isFocused = document.activeElement === contentRef.current;
setIsEmpty(
isFocused ? !contentRef.current.textContent : value.length === 0
);
if (value !== contentRef.current.textContent) {
if (isFocused) {
// Don't reset content while the user is actively editing. Update
// lastValue so that the next input or blur event will push the
// current DOM text back to the model via onChange.
@@ -146,10 +175,21 @@ const ContentEditable = React.forwardRef(function ContentEditable_(
const handlePaste = React.useCallback(
(event: React.ClipboardEvent<HTMLSpanElement>) => {
event.preventDefault();
const text = event.clipboardData.getData("text/plain");
let text = event.clipboardData.getData("text/plain");
if (maxLength) {
const current = event.currentTarget.textContent || "";
const selected = window.getSelection()?.toString() || "";
const remaining =
maxLength -
(TextHelper.codePointLength(current) -
TextHelper.codePointLength(selected));
text = TextHelper.truncate(text, remaining);
}
window.document.execCommand("insertText", false, text);
},
[]
[maxLength]
);
const contentEditable = !disabled && !readOnly;
@@ -157,14 +197,16 @@ const ContentEditable = React.forwardRef(function ContentEditable_(
<div className={className} dir={dir} onClick={onClick} tabIndex={-1}>
{children}
<Content
ref={contentRef}
ref={mergedRef}
contentEditable={contentEditable}
onInput={wrappedEvent(onInput)}
onFocus={wrappedEvent(onFocus)}
onBlur={wrappedEvent(onBlur)}
onKeyDown={wrappedEvent(onKeyDown)}
onCompositionEnd={wrappedEvent(onCompositionEnd)}
onPaste={handlePaste}
data-placeholder={placeholder}
data-empty={isEmpty}
suppressContentEditableWarning
role={contentEditable ? "textbox" : undefined}
{...rest}
@@ -173,7 +215,46 @@ const ContentEditable = React.forwardRef(function ContentEditable_(
</Content>
</div>
);
});
}
function isComposing(event: React.SyntheticEvent<HTMLSpanElement>) {
const native = event.nativeEvent;
return (
(native instanceof InputEvent || native instanceof KeyboardEvent) &&
native.isComposing
);
}
/**
* Truncates the text content of an element to the given number of code points
* while keeping the caret at its current position where possible.
*/
function truncateContent(element: HTMLElement, maxLength: number): string {
const selection = window.getSelection();
const range = selection?.rangeCount ? selection.getRangeAt(0) : undefined;
let offset = Number.MAX_SAFE_INTEGER;
if (range && element.contains(range.startContainer)) {
const before = range.cloneRange();
before.selectNodeContents(element);
before.setEnd(range.startContainer, range.startOffset);
offset = before.toString().length;
}
const text = TextHelper.truncate(element.textContent || "", maxLength);
element.textContent = text;
const textNode = element.firstChild;
if (textNode && selection) {
const caret = document.createRange();
caret.setStart(textNode, Math.min(offset, text.length));
caret.collapse(true);
selection.removeAllRanges();
selection.addRange(caret);
}
return text;
}
function placeCaret(element: HTMLElement, atStart: boolean) {
if (
@@ -198,12 +279,14 @@ const Content = styled.span`
cursor: text;
word-break: anywhere;
&:empty {
/* Browsers can leave line breaks behind after all text is deleted. */
&[data-empty="true"] {
display: inline-block;
}
&:empty::before {
&[data-empty="true"]::before {
display: inline-block;
float: inline-start;
color: ${s("placeholder")};
-webkit-text-fill-color: ${s("placeholder")};
content: attr(data-placeholder);
+15 -12
View File
@@ -3,15 +3,21 @@ import * as React from "react";
import { mergeRefs } from "react-merge-refs";
import env from "~/env";
type Props = {
text: string;
children?: React.ReactElement;
onClick?: React.MouseEventHandler<HTMLButtonElement>;
onCopy?: () => void;
type ChildProps = {
onClick?: React.MouseEventHandler<HTMLElement>;
ref?: React.Ref<HTMLElement>;
};
function CopyToClipboard(props: Props, ref: React.Ref<HTMLElement>) {
const { text, onCopy, children, ...rest } = props;
type Props = {
text: string;
children?: React.ReactElement<ChildProps>;
onClick?: React.MouseEventHandler<HTMLButtonElement>;
onCopy?: () => void;
ref?: React.Ref<HTMLElement>;
};
function CopyToClipboard(props: Props) {
const { text, onCopy, children, ref, ...rest } = props;
const onClick = React.useCallback(
(ev: React.MouseEvent<HTMLElement>) => {
@@ -45,12 +51,9 @@ function CopyToClipboard(props: Props, ref: React.Ref<HTMLElement>) {
return React.cloneElement(elem, {
...rest,
ref:
"ref" in elem
? mergeRefs([elem.ref as React.MutableRefObject<HTMLElement>, ref])
: ref,
ref: elem.props.ref ? mergeRefs([elem.props.ref, ref]) : ref,
onClick,
});
}
export default React.forwardRef(CopyToClipboard);
export default CopyToClipboard;
@@ -4,13 +4,13 @@ import {
PrivateCollectionIcon,
} from "outline-icons";
import { observer } from "mobx-react";
import { getLuminance } from "polished";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { toError } from "@shared/utils/error";
import Icon from "@shared/components/Icon";
import { colorPalette } from "@shared/constants";
import useContrastColor from "@shared/hooks/useContrastColor";
import type { Option } from "~/components/InputSelect";
import { InputSelect } from "~/components/InputSelect";
import useStores from "~/hooks/useStores";
@@ -26,7 +26,8 @@ const DefaultCollectionInputSelect = observer(
defaultCollectionId,
}: DefaultCollectionInputSelectProps) => {
const { t } = useTranslation();
const { collections, ui } = useStores();
const { collections } = useStores();
const contrastColor = useContrastColor();
const [fetching, setFetching] = useState(false);
const [fetchError, setFetchError] = useState<Error>();
@@ -55,36 +56,20 @@ const DefaultCollectionInputSelect = observer(
return null;
}
const isDark = ui.resolvedTheme === "dark";
// Eagerly resolve collection icon properties within this observer context
// to avoid MobX warnings when Radix Select clones elements for the trigger.
const options: Option[] = collections.nonPrivate.reduce(
(acc, collection) => {
const collectionIcon = collection.icon;
const rawColor = collection.color ?? colorPalette[0];
const color = contrastColor(collection.color ?? colorPalette[0]);
let icon: React.ReactElement;
if (!collectionIcon || collectionIcon === "collection") {
const color =
isDark && rawColor !== "currentColor"
? getLuminance(rawColor) > 0.09
? rawColor
: "currentColor"
: rawColor;
const Component = collection.isPrivate
? PrivateCollectionIcon
: CollectionIconComponent;
icon = <Component color={color} />;
} else {
let color = rawColor;
if (color !== "currentColor") {
if (isDark) {
color = getLuminance(color) > 0.09 ? color : "currentColor";
} else {
color = getLuminance(color) < 0.9 ? color : "currentColor";
}
}
icon = (
<Icon
value={collectionIcon}
@@ -99,7 +84,7 @@ const DefaultCollectionInputSelect = observer(
...acc,
{
type: "item" as const,
label: collection.name,
label: collection.displayName,
value: collection.id,
icon,
},
+1 -1
View File
@@ -2,7 +2,7 @@ import { useState, useEffect } from "react";
type Props = {
delay?: number;
children: JSX.Element;
children: React.JSX.Element;
};
export default function DelayedMount({ delay = 250, children }: Props) {
+93
View File
@@ -0,0 +1,93 @@
import { observer } from "mobx-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import styled from "styled-components";
import { DeprecationValidation } from "@shared/validations";
import type Collection from "~/models/Collection";
import type Document from "~/models/Document";
import ContentEditable from "~/components/ContentEditable";
import usePolicy from "~/hooks/usePolicy";
interface Props {
model: Document | Collection;
}
/**
* Displays an editable reason for archiving or deleting a document or collection.
*
* @param props the model to describe.
* @returns the reason field, in read-only mode for readers.
*/
export const DeprecatedReason = observer(function DeprecatedReason({
model,
}: Props) {
const { t } = useTranslation();
const can = usePolicy(model);
const readOnly = !can.updateDeprecatedReason;
const [draft, setDraft] = useState<string>();
const value = draft ?? model.deprecatedReason ?? "";
const handleSave = async () => {
if (readOnly || model.isSaving || draft === undefined) {
return;
}
const deprecatedReason = draft.trim() || null;
if (deprecatedReason === model.deprecatedReason) {
setDraft(undefined);
return;
}
try {
await model.save({ deprecatedReason });
setDraft(undefined);
toast.success(t("Reason saved"));
} catch {
toast.error(t("The reason could not be saved. Please try again."));
}
};
if (readOnly && !model.deprecatedReason) {
return null;
}
return (
<Input
aria-label={t("Reason for archiving or deleting")}
placeholder={readOnly ? undefined : `${t("Add a reason")}…`}
value={readOnly ? (model.deprecatedReason ?? "") : value}
readOnly={readOnly}
maxLength={DeprecationValidation.maxReasonLength}
disabled={model.isSaving}
onChange={setDraft}
onBlur={handleSave}
onKeyDown={(event) => {
if (
event.key === "Enter" &&
!event.shiftKey &&
!event.nativeEvent.isComposing
) {
event.preventDefault();
event.currentTarget.blur();
}
}}
/>
);
});
const Input = styled(ContentEditable)`
margin-top: 4px;
> span {
display: block;
background: transparent;
color: inherit;
-webkit-text-fill-color: currentColor;
white-space: pre-wrap;
&[data-empty="true"] {
display: block;
}
}
`;
+15
View File
@@ -0,0 +1,15 @@
import styled from "styled-components";
import { s } from "@shared/styles";
import Notice from "./Notice";
/** A deprecation notice with a focus border around its editable reason. */
export const DeprecationNotice = styled(Notice)`
&:has([contenteditable="true"]:focus) {
outline: 1px solid ${s("inputBorderFocused")};
}
> span > span {
flex: 1;
min-width: 0;
}
`;
+5 -2
View File
@@ -2,7 +2,8 @@ import { useRef, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import { toast } from "sonner";
import KeyboardShortcuts from "~/scenes/KeyboardShortcuts";
import KeyboardShortcuts from "~/components/KeyboardShortcuts";
import { showDownloadToast } from "~/components/DownloadToast";
import { useDesktopTitlebar } from "~/hooks/useDesktopTitlebar";
import useStores from "~/hooks/useStores";
import Desktop from "~/utils/Desktop";
@@ -29,7 +30,7 @@ export default function DesktopEventHandler() {
}
hasDisabledUpdateMessage.current = true;
toast.message("An update is ready to install.", {
toast.message(t("An update is ready to install."), {
duration: Infinity,
dismissible: true,
action: {
@@ -41,6 +42,8 @@ export default function DesktopEventHandler() {
});
});
Desktop.bridge?.onDownloadComplete?.(showDownloadToast);
Desktop.bridge?.focus(() => {
window.document.body.classList.remove("backgrounded");
});
+1 -1
View File
@@ -60,7 +60,7 @@ export const DialogTitle = observer(function DialogTitle_({
<Subject type="secondary" size="small">
{icon}
<Text type="secondary" ellipsis>
{isDocument ? model.titleWithDefault : model.name}
{isDocument ? model.displayTitle : model.displayName}
</Text>
</Subject>
</Wrapper>
+1 -1
View File
@@ -1,7 +1,7 @@
import { observer } from "mobx-react";
import { Suspense } from "react";
import useStores from "~/hooks/useStores";
import lazyWithRetry from "~/utils/lazyWithRetry";
import lazyWithRetry from "@shared/utils/lazyWithRetry";
import { DialogProvider } from "./DialogContext";
const Guide = lazyWithRetry(() => import("~/components/Guide"));
+53
View File
@@ -0,0 +1,53 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { DeprecationValidation } from "@shared/validations";
import ConfirmationDialog from "~/components/ConfirmationDialog";
import Flex from "~/components/Flex";
import Input from "~/components/Input";
interface Props {
count: number;
onSubmit: (reason?: string) => Promise<void>;
}
/**
* Confirms document archival with an optional reason.
*
* @param props the document count and archive callback.
* @returns the archive confirmation form.
*/
export function DocumentArchiveDialog({ count, onSubmit }: Props) {
const { t } = useTranslation();
const [reason, setReason] = useState("");
const handleSubmit = () => onSubmit(reason.trim() || undefined);
return (
<ConfirmationDialog
onSubmit={handleSubmit}
submitText={t("Archive")}
savingText={`${t("Archiving")}…`}
>
<Flex column gap={12}>
<div>
{count === 1
? t(
"Archiving this document will remove it from the collection and search results."
)
: t(
"Archiving these documents will remove them from their collections and search results."
)}
</div>
<Input
name="reason"
label={t("Reason (optional)")}
placeholder={`${t("Add a reason")}…`}
value={reason}
onChange={(event) => setReason(event.currentTarget.value)}
maxLength={DeprecationValidation.maxReasonLength}
margin={0}
/>
</Flex>
</ConfirmationDialog>
);
}
+23 -17
View File
@@ -37,9 +37,9 @@ export function documentBreadcrumbParts(
): { collection: string | undefined; ancestors: string[] } {
let collectionLabel: string | undefined;
if (document.isCollectionDeleted) {
collectionLabel = t("Deleted Collection");
} else if (document.collection?.name) {
collectionLabel = document.collection.name;
collectionLabel = t("Deleted collection");
} else if (document.collection?.displayName) {
collectionLabel = document.collection.displayName;
}
return {
@@ -52,7 +52,7 @@ export function documentBreadcrumbParts(
/**
* Returns the breadcrumb path leading up to a document as a plain text
* string. Includes the collection name (or "Deleted Collection" fallback)
* string. Includes the collection name (or "Deleted collection" fallback)
* and any ancestor document titles, slash-separated.
*
* @param document - the document to compute the breadcrumb for.
@@ -83,12 +83,16 @@ type Props = {
* ancestors are shown. If less than or equal to 0, no items are shown.
*/
maxDepth?: number;
ref?: React.Ref<HTMLDivElement>;
};
function DocumentBreadcrumb(
{ document, children, onlyText, maxDepth }: Props,
ref: React.RefObject<HTMLDivElement> | null
) {
function DocumentBreadcrumb({
document,
children,
onlyText,
maxDepth,
ref,
}: Props) {
const { collections } = useStores();
const { t } = useTranslation();
const sidebarContext = useLocationSidebarContext();
@@ -135,15 +139,17 @@ function DocumentBreadcrumb(
) : undefined,
section: ActiveDocumentSection,
visible: !!(collection && can.readDocument),
to: collection
? {
pathname: collection.path,
state: { sidebarContext },
}
: "",
// A personal collection has no page to link to.
to:
collection && !collection.isPersonal
? {
pathname: collection.path,
state: { sidebarContext },
}
: "",
}),
createInternalLinkAction({
name: t("Deleted Collection"),
name: t("Deleted collection"),
section: ActiveDocumentSection,
visible: document.isCollectionDeleted,
to: "",
@@ -258,7 +264,7 @@ const CollectionName = observer(function CollectionName_({
<ContextMenu action={menuAction} ariaLabel={t("Collection options")}>
<Name>
{icon}
<NameText>{collection.name}</NameText>
<NameText>{collection.displayName}</NameText>
</Name>
</ContextMenu>
</ActionContextProvider>
@@ -334,4 +340,4 @@ const SmallSlash = styled(GoToIcon)`
opacity: 0.5;
`;
export default observer(React.forwardRef(DocumentBreadcrumb));
export default observer(DocumentBreadcrumb);
+4 -4
View File
@@ -24,7 +24,7 @@ import { DocumentContextMenu } from "~/menus/DocumentContextMenu";
import CollectionIcon from "./Icons/CollectionIcon";
import Text from "./Text";
import Tooltip from "./Tooltip";
import lazyWithRetry from "~/utils/lazyWithRetry";
import lazyWithRetry from "@shared/utils/lazyWithRetry";
const ReadingTime = lazyWithRetry(() => import("./ReadingTime"));
@@ -127,7 +127,7 @@ function DocumentCard(props: Props) {
to={{
pathname: document.path,
state: {
title: document.titleWithDefault,
title: document.displayTitle,
},
}}
>
@@ -169,8 +169,8 @@ function DocumentCard(props: Props) {
<div>
<Heading dir={document.dir}>
{hasEmojiInTitle
? document.titleWithDefault.replace(document.icon!, "")
: document.titleWithDefault}
? document.displayTitle.replace(document.icon!, "")
: document.displayTitle}
</Heading>
<DocumentMeta size="xsmall">
{isRecentlyUpdated ? (
+1 -1
View File
@@ -34,7 +34,7 @@ export const DocumentChip = observer(function DocumentChip_({
const { icon, color } = document;
const canPin = usePolicy(pin);
const canDocument = usePolicy(document);
const title = document.titleWithDefault;
const title = document.displayTitle;
const isEmoji = determineIconType(icon) === IconType.Emoji;
// Pins in a collection are governed by the document policy, pins on home by
+43 -1
View File
@@ -8,13 +8,19 @@ import type { TextStats } from "~/hooks/useTextStats";
import { getTextStats } from "~/hooks/useTextStats";
import type Document from "~/models/Document";
import type { Editor } from "~/editor";
import type { ConnectionStatus } from "~/utils/multiplayer/CollaborationProvider";
class DocumentContext {
/** The current document */
document?: Document;
/** The editor instance for this document */
editor?: Editor;
@observable.ref
editor: Editor | undefined = undefined;
/** The total number of changes in the currently viewed revision diff */
@observable
totalChanges: number = 0;
/** The ID of the currently focused comment, or null if no comment is focused */
@observable
@@ -28,6 +34,22 @@ class DocumentContext {
@observable
headings: Heading[] = [];
/** The connection status of the collaboration provider */
@observable
multiplayerStatus: ConnectionStatus | undefined = undefined;
/** The close code of the collaboration connection, when it was closed with an error */
@observable
multiplayerErrorCode?: number = undefined;
/** Whether there are local edits the collaboration server has not confirmed */
@observable
hasUnsyncedChanges = false;
/** Whether edits are also stored in the browser, so they survive a reload */
@observable
hasLocalPersistence = true;
constructor() {
makeObservable(this);
}
@@ -67,11 +89,31 @@ class DocumentContext {
this.isEditorInitialized = initialized;
};
@action
setTotalChanges = (totalChanges: number) => {
this.totalChanges = totalChanges;
};
@action
setFocusedCommentId = (commentId: string | null) => {
this.focusedCommentId = commentId;
};
@action
setMultiplayerStatus = (status: ConnectionStatus, errorCode?: number) => {
this.multiplayerStatus = status;
this.multiplayerErrorCode = errorCode;
};
@action
setMultiplayerSyncState = (
hasUnsyncedChanges: boolean,
hasLocalPersistence: boolean
) => {
this.hasUnsyncedChanges = hasUnsyncedChanges;
this.hasLocalPersistence = hasLocalPersistence;
};
@action
updateState = () => {
this.editorDoc = this.editor?.view.state.doc;
@@ -45,13 +45,13 @@ type Props = {
const VERTICAL_PADDING = 6;
const HORIZONTAL_PADDING = 24;
const innerElementType = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(function innerElementType(
{ style, ...rest }: React.HTMLAttributes<HTMLDivElement>,
ref
) {
function innerElementType({
style,
ref,
...rest
}: React.HTMLAttributes<HTMLDivElement> & {
ref?: React.Ref<HTMLDivElement>;
}) {
return (
<div
ref={ref}
@@ -62,7 +62,7 @@ const innerElementType = React.forwardRef<
{...rest}
/>
);
});
}
function DocumentExplorer({
onSubmit,
@@ -77,6 +77,8 @@ function DocumentExplorer({
const theme = useTheme();
const [searchTerm, setSearchTerm] = React.useState<string>();
// Defer filtering so typing in the search input stays responsive.
const deferredSearchTerm = React.useDeferredValue(searchTerm);
const [selectedNode, selectNode] = React.useState<NavigationNode | null>(
() => {
if (!defaultValue) {
@@ -143,8 +145,8 @@ function DocumentExplorer({
: [item];
}
return searchTerm
? searchIndex.search(searchTerm)
return deferredSearchTerm
? searchIndex.search(deferredSearchTerm)
: items.flatMap(includeDescendants);
}
@@ -161,7 +163,7 @@ function DocumentExplorer({
setTimeout(() => listRef.current?.scrollToItem(index, "center"), 50);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [defaultValue]);
const baseDepth = nodes.reduce(
(min, node) => (node.depth ? Math.min(min, node.depth) : min),
@@ -307,7 +309,7 @@ function DocumentExplorer({
.join(" / ");
}
return searchTerm ? (
return deferredSearchTerm ? (
<DocumentExplorerSearchResult
selected={isSelected(index)}
active={activeNode === index}
@@ -381,13 +383,13 @@ function DocumentExplorer({
break;
}
case "ArrowLeft": {
if (!searchTerm && isExpanded(activeNode)) {
if (!deferredSearchTerm && isExpanded(activeNode)) {
toggleCollapse(activeNode);
}
break;
}
case "ArrowRight": {
if (!searchTerm) {
if (!deferredSearchTerm) {
toggleCollapse(activeNode);
// let the nodes re-render first and then scroll
setTimeout(() => scrollNodeIntoView(activeNode), 0);
@@ -33,25 +33,25 @@ type Props = {
onClick: (ev: React.MouseEvent) => void;
/** Fired when the node is double-clicked to submit the current selection. */
onDoubleClick: (ev: React.MouseEvent) => void;
/** Ref to the node element. */
ref?: React.Ref<HTMLSpanElement>;
};
function DocumentExplorerNode(
{
selected,
active,
style,
expanded,
icon,
title,
depth,
hasChildren,
onDisclosureClick,
onPointerMove,
onClick,
onDoubleClick,
}: Props,
ref: React.RefObject<HTMLSpanElement>
) {
function DocumentExplorerNode({
selected,
active,
style,
expanded,
icon,
title,
depth,
hasChildren,
onDisclosureClick,
onPointerMove,
onClick,
onDoubleClick,
ref,
}: Props) {
const { t } = useTranslation();
const DISCLOSURE = 24;
const width = (depth + 2) * DISCLOSURE;
@@ -148,4 +148,4 @@ export const Node = styled.span<{
`}
`;
export default observer(React.forwardRef(DocumentExplorerNode));
export default observer(DocumentExplorerNode);
+162 -130
View File
@@ -1,7 +1,3 @@
import {
useFocusEffect,
useRovingTabIndex,
} from "@getoutline/react-roving-tabindex";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
@@ -35,6 +31,7 @@ import { ActionContextProvider } from "~/hooks/useActionContext";
import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction";
import { ContextMenu } from "./Menu/ContextMenu";
import { useDocumentActiveModels } from "~/hooks/useDocumentActiveModels";
import { useRovingTabIndex } from "~/hooks/useRovingTabIndex";
type Props = {
document: Document;
@@ -45,6 +42,7 @@ type Props = {
showPublished?: boolean;
showDraft?: boolean;
showLastViewed?: boolean;
ref?: React.RefObject<HTMLAnchorElement | null>;
};
const SEARCH_RESULT_REGEX = /<b\b[^>]*>(.*?)<\/b>/gi;
@@ -54,27 +52,25 @@ function replaceResultMarks(tag: string) {
return tag.replace(new RegExp(SEARCH_RESULT_REGEX.source), "$1");
}
function DocumentListItem(
props: Props,
ref: React.RefObject<HTMLAnchorElement>
) {
function DocumentListItem(props: Props) {
const { t } = useTranslation();
const user = useCurrentUser();
const theme = useTheme();
const locationSidebarContext = useLocationSidebarContext();
const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean();
const [isInteractive, setIsInteractive] = React.useState(false);
const isMobile = useMobile();
const selection = useModelSelection();
const iconRef = React.useRef<HTMLDivElement>(null);
const restoreFocus = React.useRef(false);
let itemRef: React.Ref<HTMLAnchorElement> =
let itemRef: React.RefObject<HTMLAnchorElement | null> =
React.useRef<HTMLAnchorElement>(null);
if (ref) {
itemRef = ref;
if (props.ref) {
itemRef = props.ref;
}
const { focused, ...rovingTabIndex } = useRovingTabIndex(itemRef, false);
useFocusEffect(focused, itemRef);
const {
document,
@@ -85,6 +81,7 @@ function DocumentListItem(
showLastViewed = true,
highlight,
context,
ref: _ref,
...rest
} = props;
const queryIsInTitle =
@@ -137,7 +134,6 @@ function DocumentListItem(
document.asNavigationNode,
0,
document,
false,
false
);
@@ -150,125 +146,161 @@ function DocumentListItem(
[itemRef, draggableRef]
);
React.useLayoutEffect(() => {
if (isInteractive && restoreFocus.current) {
itemRef.current?.focus();
restoreFocus.current = false;
}
}, [isInteractive]);
const handleFocusCapture = (event: React.FocusEvent<HTMLAnchorElement>) => {
if (!isInteractive && event.target === event.currentTarget) {
restoreFocus.current = true;
setIsInteractive(true);
}
};
const link = (
<DocumentLink
ref={mergedRef}
dir={document.dir}
$isStarred={document.isStarred}
$isDragging={isDragging}
$menuOpen={menuOpen}
$selectable={selectable}
to={{
pathname: documentPath(document),
search: highlight ? `?q=${encodeURIComponent(highlight)}` : undefined,
state: {
title: document.displayTitle,
sidebarContext,
},
}}
{...rest}
{...rovingTabIndex}
onClick={handleLinkClick}
onMouseDown={handleLinkMouseDown}
onPointerEnter={() => setIsInteractive(true)}
onFocusCapture={handleFocusCapture}
>
<Flex gap={4} auto>
<IconWrapper ref={iconRef}>
{selectable && (
<SelectButton
role="checkbox"
aria-checked={isSelected}
aria-label={t("Select")}
$checked={isSelected}
$visible={isSelecting}
tabIndex={-1}
>
{isSelected && <CheckmarkIcon size={16} />}
</SelectButton>
)}
<DocumentIconWrapper $dimmed={isSelecting}>
{document.icon ? (
<Icon
value={document.icon}
color={document.color ?? undefined}
initial={document.initial}
/>
) : (
<DocumentIcon
outline={document.isDraft}
color={theme.textSecondary}
/>
)}
</DocumentIconWrapper>
</IconWrapper>
<Content>
<Heading dir={document.dir}>
<Title
text={document.displayTitle}
highlight={highlight}
dir={document.dir}
/>
{document.isBadgedNew && document.createdBy?.id !== user.id && (
<Badge yellow>{t("New")}</Badge>
)}
{document.isDraft &&
showDraft &&
(isInteractive ? (
<Tooltip content={t("Only visible to you")}>
<Badge>{t("Draft")}</Badge>
</Tooltip>
) : (
<Badge>{t("Draft")}</Badge>
))}
{canStar && !isMobile && (
<StarButton
document={document}
tooltipDisabled={!isInteractive}
/>
)}
</Heading>
{!queryIsInTitle && (
<ResultContext
text={context}
highlight={highlight ? SEARCH_RESULT_REGEX : undefined}
processResult={replaceResultMarks}
/>
)}
<DocumentMeta
document={document}
showCollection={showCollection}
showPublished={showPublished}
showParentDocuments={showParentDocuments}
showLastViewed={showLastViewed}
/>
</Content>
</Flex>
{document.destroysInDays !== undefined && (
<RetentionBadge>
{isInteractive ? (
<Tooltip
content={t(
"Will be permanently deleted in {{ count }} days unless restored",
{ count: document.destroysInDays }
)}
>
<Badge>
{t("{{ count }} days", { count: document.destroysInDays })}
</Badge>
</Tooltip>
) : (
<Badge>
{t("{{ count }} days", { count: document.destroysInDays })}
</Badge>
)}
</RetentionBadge>
)}
<Actions>
{isInteractive && (
<DocumentMenu
document={document}
onOpen={handleMenuOpen}
onClose={handleMenuClose}
/>
)}
</Actions>
</DocumentLink>
);
return (
<ActionContextProvider value={{ activeModels }}>
<ContextMenu
action={contextMenuAction}
ariaLabel={t("Document options")}
onOpen={handleMenuOpen}
onClose={handleMenuClose}
>
<DocumentLink
ref={mergedRef}
dir={document.dir}
$isStarred={document.isStarred}
$isDragging={isDragging}
$menuOpen={menuOpen}
$selectable={selectable}
to={{
pathname: documentPath(document),
search: highlight
? `?q=${encodeURIComponent(highlight)}`
: undefined,
state: {
title: document.titleWithDefault,
sidebarContext,
},
}}
{...rest}
{...rovingTabIndex}
onClick={handleLinkClick}
onMouseDown={handleLinkMouseDown}
{isInteractive ? (
<ContextMenu
action={contextMenuAction}
ariaLabel={t("Document options")}
onOpen={handleMenuOpen}
onClose={handleMenuClose}
>
<Flex gap={4} auto>
<IconWrapper ref={iconRef}>
{selectable && (
<SelectButton
role="checkbox"
aria-checked={isSelected}
aria-label={t("Select")}
$checked={isSelected}
$visible={isSelecting}
tabIndex={-1}
>
{isSelected && <CheckmarkIcon size={16} />}
</SelectButton>
)}
<DocumentIconWrapper $dimmed={isSelecting}>
{document.icon ? (
<Icon
value={document.icon}
color={document.color ?? undefined}
initial={document.initial}
/>
) : (
<DocumentIcon
outline={document.isDraft}
color={theme.textSecondary}
/>
)}
</DocumentIconWrapper>
</IconWrapper>
<Content>
<Heading dir={document.dir}>
<Title
text={document.titleWithDefault}
highlight={highlight}
dir={document.dir}
/>
{document.isBadgedNew && document.createdBy?.id !== user.id && (
<Badge yellow>{t("New")}</Badge>
)}
{document.isDraft && showDraft && (
<Tooltip content={t("Only visible to you")} placement="top">
<Badge>{t("Draft")}</Badge>
</Tooltip>
)}
{canStar && !isMobile && <StarButton document={document} />}
</Heading>
{!queryIsInTitle && (
<ResultContext
text={context}
highlight={highlight ? SEARCH_RESULT_REGEX : undefined}
processResult={replaceResultMarks}
/>
)}
<DocumentMeta
document={document}
showCollection={showCollection}
showPublished={showPublished}
showParentDocuments={showParentDocuments}
showLastViewed={showLastViewed}
/>
</Content>
</Flex>
{document.destroysInDays !== undefined && (
<RetentionBadge>
<Tooltip
content={t(
"Will be permanently deleted in {{ count }} days unless restored",
{ count: document.destroysInDays }
)}
placement="top"
>
<Badge>
{t("{{ count }} days", {
count: document.destroysInDays,
})}
</Badge>
</Tooltip>
</RetentionBadge>
)}
<Actions>
<DocumentMenu
document={document}
onOpen={handleMenuOpen}
onClose={handleMenuClose}
/>
</Actions>
</DocumentLink>
</ContextMenu>
{link}
</ContextMenu>
) : (
link
)}
</ActionContextProvider>
);
}
@@ -472,4 +504,4 @@ const ResultContext = styled(Highlight)`
overflow: hidden;
`;
export default observer(React.forwardRef(DocumentListItem));
export default observer(DocumentListItem);
+24 -2
View File
@@ -13,6 +13,7 @@ import DocumentTasks from "~/components/DocumentTasks";
import Flex from "~/components/Flex";
import { MetaButton, Separator, metaStyles } from "~/components/HeaderMeta";
import Time from "~/components/Time";
import useClickIntent from "~/hooks/useClickIntent";
import useCurrentUser from "~/hooks/useCurrentUser";
import useStores from "~/hooks/useStores";
@@ -37,6 +38,8 @@ type Props = {
to?: LocationDescriptor;
/** Called when the meta content is clicked, renders it as a button. Takes precedence over `to`. */
onClick?: () => void;
/** Called when the user is likely to click the meta content, used to preload. */
onClickIntent?: () => void;
};
const DocumentMeta: React.FC<Props> = ({
@@ -50,9 +53,15 @@ const DocumentMeta: React.FC<Props> = ({
replace,
to,
onClick,
onClickIntent,
...rest
}: Props) => {
const { t } = useTranslation();
const {
ref: intentRef,
handleMouseEnter,
handleMouseLeave,
} = useClickIntent(onClickIntent, { predict: !!onClickIntent });
const { collections } = useStores();
const user = useCurrentUser();
const {
@@ -194,9 +203,22 @@ const DocumentMeta: React.FC<Props> = ({
return (
<Container align="center" $rtl={document.dir === "rtl"} {...rest} dir="ltr">
{onClick ? (
<MetaButton onClick={onClick}>{content}</MetaButton>
<MetaButton
ref={intentRef}
onClick={onClick}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{content}
</MetaButton>
) : to ? (
<Link to={to} replace={replace}>
<Link
ref={intentRef}
to={to}
replace={replace}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{content}
</Link>
) : (
+71
View File
@@ -0,0 +1,71 @@
import { t } from "i18next";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import Button from "~/components/Button";
import Flex from "~/components/Flex";
import Desktop from "~/utils/Desktop";
type DownloadedFile = {
/** The user facing name of the downloaded file. */
fileName: string;
/** The absolute path the file was saved to. */
filePath: string;
};
/**
* Displays a toast notifying that a file finished downloading, with the file
* name and actions to open the file or reveal it in the file manager. Desktop
* app only.
*
* @param file the name and path of the downloaded file.
*/
export function showDownloadToast(file: DownloadedFile) {
const toastId = `download-${file.filePath}`;
toast.message(t("Download complete"), {
id: toastId,
description: <DownloadToastDescription file={file} toastId={toastId} />,
});
}
function DownloadToastDescription({
file,
toastId,
}: {
file: DownloadedFile;
toastId: string;
}) {
const { t } = useTranslation();
const handleOpen = useCallback(() => {
toast.dismiss(toastId);
void Desktop.bridge?.openDownload?.(file.filePath);
}, [file.filePath, toastId]);
const handleShowInFolder = useCallback(() => {
toast.dismiss(toastId);
void Desktop.bridge?.showDownloadInFolder?.(file.filePath);
}, [file.filePath, toastId]);
// The name given to the file manager differs by operating system.
const showInFolderLabel = Desktop.isMacApp()
? t("Show in Finder")
: Desktop.isWindowsApp()
? t("Show in Explorer")
: t("Show in folder");
return (
<Flex column gap={8}>
{file.fileName}
<Flex gap={4}>
<Button onClick={handleOpen} neutral>
{t("Open")}
</Button>
<Button onClick={handleShowInFolder} neutral>
{showInFolderLabel}
</Button>
</Flex>
</Flex>
);
}
+11 -5
View File
@@ -20,6 +20,7 @@ type Props = Omit<React.InputHTMLAttributes<HTMLInputElement>, "onSubmit"> & {
maxLength?: number;
/** The default editing state. */
isEditing?: boolean;
ref?: React.Ref<RefHandle>;
};
export type RefHandle = {
@@ -27,10 +28,15 @@ export type RefHandle = {
setIsEditing: (isEditing: boolean) => void;
};
function EditableTitle(
{ title, onSubmit, canUpdate, onEditing, onCancel, ...rest }: Props,
ref: React.RefObject<RefHandle>
) {
function EditableTitle({
title,
onSubmit,
canUpdate,
onEditing,
onCancel,
ref,
...rest
}: Props) {
const [isEditing, setIsEditing] = React.useState(rest.isEditing || false);
const [originalValue, setOriginalValue] = React.useState(title);
const [value, setValue] = React.useState(title);
@@ -190,4 +196,4 @@ const Input = styled.input`
}
`;
export default React.forwardRef(EditableTitle);
export default EditableTitle;
+20 -84
View File
@@ -1,13 +1,12 @@
import { difference } from "es-toolkit/compat";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { mergeRefs } from "react-merge-refs";
import type { Optional } from "utility-types";
import EditorContainer from "@shared/editor/components/Styles";
import { AttachmentPreset } from "@shared/types";
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
import { ProsemirrorHelper } from "~/models/helpers/ProsemirrorHelper";
import AsyncEditor from "~/components/AsyncEditor";
import ClickablePadding from "~/components/ClickablePadding";
import ErrorBoundary from "~/components/ErrorBoundary";
import PlaceholderDocument from "~/components/PlaceholderDocument";
@@ -17,11 +16,8 @@ import useEditorClickHandlers from "~/hooks/useEditorClickHandlers";
import useEmbeds from "~/hooks/useEmbeds";
import useStores from "~/hooks/useStores";
import { uploadFile, uploadFileFromUrl } from "~/utils/files";
import lazyWithRetry from "~/utils/lazyWithRetry";
import useShare from "@shared/hooks/useShare";
const LazyLoadedEditor = lazyWithRetry(() => import("~/editor"));
export type Props = Optional<
EditorProps,
"placeholder" | "defaultValue" | "onClickLink" | "embeds" | "extensions"
@@ -32,30 +28,14 @@ export type Props = Optional<
editorStyle?: React.CSSProperties;
};
function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
const {
id,
onChange,
onCreateCommentMark,
onDeleteCommentMark,
onFileUploadStart,
onFileUploadStop,
} = props;
function Editor({ ref, ...props }: Props & { ref?: React.Ref<SharedEditor> }) {
const { id, onChange, onCreateCommentMark, onDeleteCommentMark } = props;
const { comments } = useStores();
const { shareId } = useShare();
const { t } = useTranslation();
const embeds = useEmbeds(!shareId);
const localRef = React.useRef<SharedEditor>();
const localRef = React.useRef<SharedEditor | null>(null);
const preferences = useCurrentUser({ rejectOnEmpty: false })?.preferences;
const previousCommentIds = React.useRef<string[]>();
// Upload progress tracking for delayed toast
const progressMap = React.useMemo(() => new Map<string, number>(), []);
const uploadState = React.useRef<{
toastId?: string | number;
timeoutId?: ReturnType<typeof setTimeout>;
progress: Map<string, number>;
}>({ progress: progressMap });
const previousCommentIds = React.useRef<string[] | undefined>(undefined);
const handleUploadFile = React.useCallback(
async (
@@ -82,49 +62,6 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
const { handleClickLink } = useEditorClickHandlers({ shareId });
// Show toast only after uploads have been running for 2 seconds
const handleFileUploadStart = React.useCallback(() => {
uploadState.current.timeoutId = setTimeout(() => {
uploadState.current.toastId = toast.loading(
t("Uploading… {{ progress }}%", { progress: 0 })
);
}, 2000);
onFileUploadStart?.();
}, [onFileUploadStart, t]);
const handleFileUploadProgress = React.useCallback(
(fileId: string, fractionComplete: number) => {
uploadState.current.progress.set(fileId, fractionComplete);
// Calculate average progress across all files
const progressValues = Array.from(uploadState.current.progress.values());
const avgProgress =
progressValues.reduce((a, b) => a + b, 0) / progressValues.length;
const percent = Math.round(avgProgress * 100);
// Update toast if visible
if (uploadState.current.toastId) {
toast.loading(t("Uploading… {{ progress }}%", { progress: percent }), {
id: uploadState.current.toastId,
});
}
},
[t]
);
const handleFileUploadStop = React.useCallback(() => {
if (uploadState.current.timeoutId) {
clearTimeout(uploadState.current.timeoutId);
uploadState.current.timeoutId = undefined;
}
if (uploadState.current.toastId) {
toast.dismiss(uploadState.current.toastId);
uploadState.current.toastId = undefined;
}
uploadState.current.progress.clear();
onFileUploadStop?.();
}, [onFileUploadStop]);
const focusAtEnd = React.useCallback(() => {
localRef?.current?.focusAtEnd();
}, [localRef]);
@@ -202,9 +139,12 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
[updateComments]
);
const paragraphs = React.useMemo(() => {
// Read-only content that needs no node views or plugins is rendered from
// the schema alone, avoiding an editor view per instance.
const staticHTML = React.useMemo(() => {
if (props.readOnly && typeof props.value === "object") {
return ProsemirrorHelper.getPlainParagraphs(props.value);
const node = ProsemirrorHelper.toStaticNode(props.value);
return node ? ProsemirrorHelper.toHTML(node) : undefined;
}
return undefined;
}, [props.readOnly, props.value]);
@@ -212,22 +152,21 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
return (
<ErrorBoundary component="div" reloadOnChunkMissing>
<>
{paragraphs ? (
{staticHTML !== undefined ? (
<EditorContainer
$rtl={props.dir === "rtl"}
grow={props.grow}
style={props.style}
className={props.className}
editorStyle={props.editorStyle}
commenting={!!props.onClickCommentMark}
lang={props.lang}
readOnly
>
<div className="ProseMirror">
{paragraphs.map((paragraph, index) => (
<p key={index} dir="auto">
{paragraph.content?.map((content) => content.text)}
</p>
))}
</div>
<div
className="ProseMirror"
dangerouslySetInnerHTML={{ __html: staticHTML }}
/>
</EditorContainer>
) : (
// The boundary must live between the lazy editor and any ancestor
@@ -235,7 +174,7 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
// React 18 would hide mounted ancestors and destroy their effects,
// re-running provider setup and ref callbacks in a loop.
<React.Suspense fallback={<PlaceholderDocument delay={500} />}>
<LazyLoadedEditor
<AsyncEditor
key={props.extensions?.length || 0}
ref={mergeRefs([ref, localRef, handleRefChanged])}
uploadFile={handleUploadFile}
@@ -244,9 +183,6 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
{...props}
onClickLink={handleClickLink}
onChange={handleChange}
onFileUploadStart={handleFileUploadStart}
onFileUploadStop={handleFileUploadStop}
onFileUploadProgress={handleFileUploadProgress}
placeholder={props.placeholder || ""}
defaultValue={props.defaultValue || ""}
/>
@@ -265,4 +201,4 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
);
}
export default observer(React.forwardRef(Editor));
export default observer(Editor);
+5 -1
View File
@@ -9,6 +9,7 @@ import { bytesToHumanReadable } from "@shared/utils/files";
import { AttachmentValidation } from "@shared/validations";
import Text from "~/components/Text";
import { VStack } from "~/components/primitives/VStack";
import { toDropzoneAccept } from "~/utils/files";
interface UseEmojiFileUploadOptions {
/** Optional callback fired after a valid file is selected. */
@@ -75,9 +76,10 @@ export function useEmojiFileUpload(options?: UseEmojiFileUploadOptions) {
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDropAccepted: handleDrop,
accept: AttachmentValidation.emojiContentTypes,
accept: emojiAccept,
maxSize: AttachmentValidation.emojiMaxFileSize,
maxFiles: 1,
noPaste: true,
});
return { file, getRootProps, getInputProps, isDragActive };
@@ -139,6 +141,8 @@ export function EmojiImageDropZone({
);
}
const emojiAccept = toDropzoneAccept(AttachmentValidation.emojiContentTypes);
const DropZone = styled.div`
border: 2px dashed ${s("inputBorder")};
border-radius: 8px;
@@ -94,7 +94,7 @@ export function EmojiCreateDialog({ onSubmit }: Props) {
>
<Text as="p" type="secondary">
{t(
"Square images with transparent backgrounds work best. If your image is too large, we'll try to resize it for you."
"Square images with transparent backgrounds work best. If your image is too large, we’ll try to resize it for you."
)}
</Text>
@@ -116,7 +116,7 @@ export function EmojiCreateDialog({ onSubmit }: Props) {
error={
!isValidName
? t(
"name can only contain lowercase letters, numbers, and underscores."
"Name can only contain lowercase letters, numbers, and underscores."
)
: undefined
}
+4 -4
View File
@@ -14,7 +14,7 @@ import Text from "~/components/Text";
import env from "~/env";
import Logger from "~/utils/Logger";
import isCloudHosted from "~/utils/isCloudHosted";
import { isStaleChunkError } from "~/utils/lazyWithRetry";
import { isStaleChunkError } from "@shared/utils/lazyWithRetry";
import Storage from "@shared/utils/Storage";
import { deleteAllDatabases } from "~/utils/developer";
import Flex from "./Flex";
@@ -145,7 +145,7 @@ class ErrorBoundaryClass extends React.Component<Props> {
<>
<PageTitle title={t("Module failed to load")} />
<Heading>
<Trans>Loading Failed</Trans>
<Trans>Loading failed</Trans>
</Heading>
</>
)}
@@ -167,9 +167,9 @@ class ErrorBoundaryClass extends React.Component<Props> {
<Component>
{showTitle && (
<>
<PageTitle title={t("Something Unexpected Happened")} />
<PageTitle title={t("Something unexpected happened")} />
<Heading>
<Trans>Something Unexpected Happened</Trans>
<Trans>Something unexpected happened</Trans>
</Heading>
</>
)}
+1 -1
View File
@@ -104,7 +104,7 @@ export const ExportDialog = observer(({ collection, onSubmit }: Props) => {
<Text as="p">
{t("Exporting the collection may take some time.")}{" "}
{user.subscribedToEventType(NotificationEventType.ExportCompleted) &&
t("You will receive an email when it's complete.")}
t("You will receive an email when it’s complete.")}
</Text>
)}
<FileFormatSelector
+1 -1
View File
@@ -63,7 +63,7 @@ function Facepile({
model,
size,
style: {
marginRight: lastChild ? 0 : -4,
marginRight: lastChild ? 0 : -Math.round(size / 7),
...(lastChild || filtered.length === 1
? {}
: { clipPath: `url(#${clipPathId(size)})` }),
+1 -1
View File
@@ -12,7 +12,7 @@ const Fade = styled.span<{ timing?: number | string }>`
`;
type Props = {
children?: JSX.Element | null;
children?: React.JSX.Element | null;
/** If true, children will be animated. */
animate: boolean;
};
+18 -4
View File
@@ -3,6 +3,8 @@ import { CheckmarkIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { MOBILE_TOUCH_TARGET } from "@shared/constants";
import { s } from "@shared/styles";
import type { FetchPageParams } from "~/stores/base/Store";
import Button, { Inner } from "~/components/Button";
@@ -63,6 +65,8 @@ const FilterOptions = ({
selectedKeys.includes(option.key)
);
const [query, setQuery] = React.useState("");
// Defer filtering so typing in the search input stays responsive.
const deferredQuery = React.useDeferredValue(query);
const selectedLabel = selectedItems.length
? selectedItems.map((selected) => selected.label).join(", ")
@@ -118,9 +122,9 @@ const FilterOptions = ({
);
const filteredOptions = React.useMemo(() => {
const normalizedQuery = deburr(query.toLowerCase());
const normalizedQuery = deburr(deferredQuery.toLowerCase());
const filtered = query
const filtered = deferredQuery
? options.filter((option) =>
deburr(option.label).toLowerCase().includes(normalizedQuery)
)
@@ -140,7 +144,7 @@ const FilterOptions = ({
// If both have the same selection state and there's a query,
// sort options starting with query first
if (query) {
if (deferredQuery) {
const aStartsWith = deburr(a.label)
.toLowerCase()
.startsWith(normalizedQuery);
@@ -158,7 +162,7 @@ const FilterOptions = ({
return 0;
});
}, [options, query, selectedKeys]);
}, [options, deferredQuery, selectedKeys]);
const handleKeyDown = React.useCallback(
(ev: React.KeyboardEvent) => {
@@ -357,6 +361,16 @@ export const StyledButton = styled(Button)`
line-height: 28px;
min-height: auto;
}
${breakpoint("mobile", "tablet")`
&& {
height: ${MOBILE_TOUCH_TARGET}px;
}
&& ${Inner} {
min-height: ${MOBILE_TOUCH_TARGET}px;
}
`};
`;
export default FilterOptions;
+192 -18
View File
@@ -1,24 +1,28 @@
import { useDirection } from "@radix-ui/react-direction";
import { throttle } from "es-toolkit/compat";
import { observer } from "mobx-react";
import { CloseIcon, MenuIcon } from "outline-icons";
import { CloseIcon, MenuIcon, SidebarIcon } from "outline-icons";
import { transparentize } from "polished";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { mergeRefs } from "react-merge-refs";
import styled from "styled-components";
import styled, { css } from "styled-components";
import type { DefaultTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import useMeasure from "react-use-measure";
import { HEADER_HEIGHT } from "@shared/constants";
import { depths, s } from "@shared/styles";
import { supportsPassiveListener } from "@shared/utils/browser";
import { HEADER_HEIGHT, MOBILE_TOUCH_TARGET } from "@shared/constants";
import { depths, hover, s } from "@shared/styles";
import { metaDisplay } from "@shared/utils/keyboard";
import Button from "~/components/Button";
import Fade from "~/components/Fade";
import Flex from "~/components/Flex";
import { useSidebarCollapsed } from "~/components/SidebarCollapsedContext";
import { useSplitView } from "~/components/SplitView/context";
import Tooltip from "~/components/Tooltip";
import useEventListener from "~/hooks/useEventListener";
import useMobile from "~/hooks/useMobile";
import useStores from "~/hooks/useStores";
import useWindowScrollbarWidth from "~/hooks/useWindowScrollbarWidth";
import { draggableOnDesktop, fadeOnDesktopBackgrounded } from "~/styles";
import Desktop from "~/utils/Desktop";
import history from "~/utils/history";
@@ -35,18 +39,26 @@ type Props = {
| React.ReactNode;
hasSidebar?: boolean;
className?: string;
ref?: React.Ref<HTMLDivElement>;
};
function Header(
{ left, title, actions, hasSidebar, className }: Props,
ref: React.RefObject<HTMLDivElement> | null
) {
function Header({ left, title, actions, hasSidebar, className, ref }: Props) {
const { ui } = useStores();
const { t } = useTranslation();
const { pane, isSplitView } = useSplitView();
const isMobile = useMobile();
const sidebarCollapsed = useSidebarCollapsed();
const hasMobileSidebar = hasSidebar && isMobile;
const hasDesktopSidebar = hasSidebar && !isMobile;
const [internalMeasureRef, size] = useMeasure();
const scrollbarWidth = useWindowScrollbarWidth() ?? 0;
const direction = useDirection();
// The body spans the full viewport, so a header at the window end extends past the visible area.
const isAtWindowEnd =
size.width > 0 &&
(direction === "rtl"
? size.left <= 1
: size.right >= window.innerWidth - 1);
const [breadcrumbsMeasureRef, breadcrumbsSize] = useMeasure();
const passThrough = !actions && !left && !title && !isSplitView;
@@ -60,12 +72,7 @@ function Header(
[]
);
useEventListener(
"scroll",
handleScroll,
window,
supportsPassiveListener ? { passive: true } : { capture: false }
);
useEventListener("scroll", handleScroll, window, { passive: true });
const handleClickTitle = React.useCallback(() => {
window.scrollTo({
@@ -95,7 +102,30 @@ function Header(
className={className}
$passThrough={passThrough}
$insetTitleAdjust={ui.sidebarIsClosed && Desktop.hasInsetTitlebar()}
$scrollbarInset={isAtWindowEnd ? scrollbarWidth : undefined}
>
{hasDesktopSidebar && (
<SidebarToggle
$visible={sidebarCollapsed}
aria-hidden={!sidebarCollapsed}
>
<Tooltip
content={t("Toggle sidebar")}
shortcut={`${metaDisplay}+.`}
side="bottom"
>
<SidebarToggleButton
$visible={sidebarCollapsed}
aria-label={t("Expand sidebar")}
onClick={ui.toggleCollapsedSidebar}
icon={<SidebarIcon />}
tabIndex={sidebarCollapsed ? undefined : -1}
neutral
borderOnHover
/>
</Tooltip>
</SidebarToggle>
)}
{left || hasMobileSidebar ? (
<Breadcrumbs ref={setBreadcrumbRef}>
{hasMobileSidebar && (
@@ -135,6 +165,26 @@ function Header(
);
}
/** Height of the fade at the bottom of the mobile header background. */
const HeaderFadeHeight = 64;
/** Eased mask stops for the header fade, so it has no visible start or end. */
const headerFadeStops = [1, 0.85, 0.5, 0.15, 0]
.map(
(opacity, index, stops) =>
`rgb(0 0 0 / ${opacity}) calc(100% - ${HeaderFadeHeight * (1 - index / (stops.length - 1))}px)`
)
.join(", ");
/** Raised capsule that holds header buttons on mobile, like an iOS toolbar. */
const mobilePill = css`
background: ${s("menuBackground")};
box-shadow:
0 0 0 1px ${s("divider")},
0 4px 12px rgb(0 0 0 / 8%);
border-radius: ${MOBILE_TOUCH_TARGET / 2}px;
`;
const Breadcrumbs = styled("div")`
flex-grow: 1;
flex-basis: 0;
@@ -143,6 +193,20 @@ const Breadcrumbs = styled("div")`
padding-inline: 0 8px;
display: flex;
${breakpoint("mobile", "tablet")`
gap: 8px;
&& [data-variant] {
${mobilePill}
}
&& [data-variant]:${hover}:not(:disabled),
&& [data-variant][aria-expanded="true"] {
${mobilePill}
background: ${s("buttonNeutralBackground")};
}
`};
${breakpoint("tablet")`
min-width: auto;
`};
@@ -156,6 +220,45 @@ const Actions = styled(Flex)`
gap: 8px;
margin-inline-start: 8px;
${breakpoint("mobile", "tablet")`
flex: 0 0 auto;
gap: 0;
margin-inline-start: auto;
&:not(:empty) {
${mobilePill}
padding-inline: 10px;
}
/* Touch targets overlap so icons sit closer than their 44px hit areas. */
& > * {
margin-inline: -4px;
}
&& [data-variant] {
background: transparent;
box-shadow: none;
}
&& [data-variant="primary"] {
color: ${s("accent")};
}
&& [data-variant="primary"]:disabled {
color: ${s("textTertiary")};
svg {
fill: currentColor;
}
}
&& [data-variant]:${hover}:not(:disabled),
&& [data-variant][aria-expanded="true"] {
background: ${s("buttonNeutralBackground")};
box-shadow: none;
}
`};
${breakpoint("tablet")`
position: unset;
`};
@@ -164,8 +267,20 @@ const Actions = styled(Flex)`
type WrapperProps = {
$passThrough?: boolean;
$insetTitleAdjust?: boolean;
/** Width of the window scrollbar that the end of the header falls behind. */
$scrollbarInset?: number;
};
/**
* Padding for the end of the header that clears the window scrollbar. The
* removed-body-scroll-bar-size variable is set while a modal locks the page
* scroll, which keeps the padding constant as the scrollbar is removed.
*/
const endPadding = (base: number) => (props: WrapperProps) =>
props.$scrollbarInset === undefined
? `${base}px`
: `calc(${base}px + ${props.$scrollbarInset}px + var(--removed-body-scroll-bar-size, 0px))`;
const Wrapper = styled(Flex)<WrapperProps>`
top: 0;
z-index: ${depths.header};
@@ -183,7 +298,8 @@ const Wrapper = styled(Flex)<WrapperProps>`
backdrop-filter: blur(20px);
`};
padding: 12px 16px;
padding: 6px 16px;
padding-inline-end: ${endPadding(16)};
transform: translate3d(0, 0, 0);
min-height: ${HEADER_HEIGHT}px;
justify-content: flex-start;
@@ -207,8 +323,38 @@ const Wrapper = styled(Flex)<WrapperProps>`
display: none;
}
${breakpoint("mobile", "tablet")`
${(props: WrapperProps & { theme: DefaultTheme }) =>
!props.$passThrough &&
`
background: transparent;
backdrop-filter: none;
/* The blurred background extends past the header and fades out, so content blends under it. */
&::before {
content: "";
position: absolute;
inset: 0 0 -${HeaderFadeHeight / 2}px;
z-index: -1;
pointer-events: none;
background: ${transparentize(0.2, props.theme.background)};
backdrop-filter: blur(20px);
mask-image: linear-gradient(to bottom, ${headerFadeStops});
}
/* A stuck tab bar continues the header, so the header is solid above it. */
body:has([data-sticky-tabs][data-stuck]) &::before {
inset: 0;
background: ${props.theme.background};
backdrop-filter: none;
mask-image: none;
}
`}
`};
${breakpoint("tablet")`
padding: 12px;
padding-inline-end: ${endPadding(12)};
${(props: WrapperProps) => props.$insetTitleAdjust && `padding-left: 64px;`}
`};
`;
@@ -239,7 +385,6 @@ const Title = styled("div")`
`;
const MobileMenuButton = styled(Button)`
margin-right: 8px;
pointer-events: auto;
@media print {
@@ -247,8 +392,37 @@ const MobileMenuButton = styled(Button)`
}
`;
const SidebarToggle = styled("div")<{ $visible: boolean }>`
flex-shrink: 0;
overflow: hidden;
width: ${(props) => (props.$visible ? 32 : 0)}px;
margin-inline-end: ${(props) => (props.$visible ? 8 : 0)}px;
pointer-events: ${(props) => (props.$visible ? "auto" : "none")};
transition:
width 150ms ease-out,
margin 150ms ease-out;
@media print {
display: none;
}
`;
const SidebarToggleButton = styled(Button)<{ $visible: boolean }>`
color: ${s("textTertiary")};
opacity: ${(props) => (props.$visible ? 1 : 0)};
transition: opacity 150ms ease-out;
&:hover:not(:disabled) {
color: ${s("textSecondary")};
}
[dir="rtl"] & svg {
transform: scaleX(-1);
}
`;
const CloseSplitPaneButton = styled(Button)`
pointer-events: auto;
`;
export default observer(React.forwardRef(Header));
export default observer(Header);
+9 -1
View File
@@ -1,13 +1,21 @@
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { IconTitleWrapper } from "@shared/components/Icon";
const Heading = styled.h1<{ as?: string; centered?: boolean }>`
display: flex;
align-items: center;
user-select: none;
${(props) => (props.as ? "" : "margin-top: 8vh; font-weight: 600;")}
${(props) => (props.as ? "" : "margin-top: 16px; font-weight: 600;")}
${(props) => (props.centered ? "text-align: center;" : "")}
/* On mobile the title icon sits above the title, so leave room for it. */
${breakpoint("mobile", "tablet")`
&:has(> ${IconTitleWrapper}) {
margin-top: 60px;
}
`};
${breakpoint("tablet")`
${(props: { as?: string }) => (props.as ? "" : "margin-top: 6vh;")}
`};
+21 -4
View File
@@ -1,5 +1,4 @@
import { transparentize } from "polished";
import { Link } from "react-router-dom";
import styled, { css } from "styled-components";
import { s } from "@shared/styles";
import Text from "~/components/Text";
@@ -16,9 +15,8 @@ const StyledText = styled(Text)`
margin-bottom: 0;
`;
export const Preview = styled(Link)`
cursor: ${(props: { as?: string }) =>
props.as === "div" ? "default" : "var(--pointer)"};
export const Preview = styled.a`
cursor: ${(props) => (props.as === "div" ? "default" : "var(--pointer)")};
border-radius: 4px;
box-shadow:
0 30px 90px -20px rgba(0, 0, 0, 0.3),
@@ -133,3 +131,22 @@ export const Card = styled.div<{ fadeOut?: boolean; $borderRadius?: string }>`
}`
: ""}
`;
export const BreadcrumbContainer = styled.div`
font-size: 12px;
font-weight: 500;
color: ${(props) => props.theme.textTertiary};
margin-bottom: 4px;
display: flex;
align-items: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
/* Adds a subtle separator between path items */
span:not(:last-child)::after {
content: "/";
margin: 0 4px;
color: ${(props) => props.theme.divider};
}
`;
+7 -5
View File
@@ -1,10 +1,10 @@
import { m } from "framer-motion";
import { observer } from "mobx-react";
import * as React from "react";
import { Portal } from "react-portal";
import styled from "styled-components";
import { depths } from "@shared/styles";
import { UnfurlResourceType } from "@shared/types";
import { Portal } from "~/components/Portal";
import useEventListener from "~/hooks/useEventListener";
import useKeyDown from "~/hooks/useKeyDown";
import useMobile from "~/hooks/useMobile";
@@ -44,7 +44,9 @@ const HoverPreviewDesktop = observer(
({ element, unfurlId, dataLoading, onClose }: Props) => {
const { unfurls } = useStores();
const [isVisible, setVisible] = React.useState(false);
const timerClose = React.useRef<ReturnType<typeof setTimeout>>();
const timerClose = React.useRef<ReturnType<typeof setTimeout> | undefined>(
undefined
);
const cardRef = React.useRef<HTMLDivElement | null>(null);
const { cardLeft, cardTop, pointerLeft, pointerTop, pointerDir } =
useHoverPosition({
@@ -114,13 +116,13 @@ const HoverPreviewDesktop = observer(
}
return (
<Portal>
<Portal toBody>
<Position top={cardTop} left={cardLeft} aria-hidden>
{isVisible ? (
<Animate
initial={{
opacity: 0,
y: -20,
y: -8,
filter: "blur(5px)",
pointerEvents: "none",
}}
@@ -248,7 +250,7 @@ function useHoverPosition({
element,
isVisible,
}: {
cardRef: React.RefObject<HTMLDivElement>;
cardRef: React.RefObject<HTMLDivElement | null>;
element: HTMLElement | null;
isVisible: boolean;
}) {
@@ -1,9 +1,13 @@
import * as React from "react";
import { Link } from "react-router-dom";
import { richExtensions } from "@shared/editor/nodes";
import type { UnfurlResourceType, UnfurlResponse } from "@shared/types";
import Editor from "~/components/Editor";
import Flex from "~/components/Flex";
import ErrorBoundary from "../ErrorBoundary";
import useStores from "~/hooks/useStores";
import { observer } from "mobx-react";
import DocumentBreadcrumb from "~/components/DocumentBreadcrumb";
import {
Preview,
Title,
@@ -11,20 +15,40 @@ import {
Card,
CardContent,
Description,
BreadcrumbContainer,
} from "./Components";
type Props = Omit<UnfurlResponse[UnfurlResourceType.Document], "type">;
type Props = Omit<UnfurlResponse[UnfurlResourceType.Document], "type"> & {
ref?: React.Ref<HTMLDivElement>;
};
const HoverPreviewDocument = React.forwardRef(function HoverPreviewDocument_(
{ url, id, title, summary, lastActivityByViewer }: Props,
ref: React.Ref<HTMLDivElement>
) {
return (
<Preview to={url}>
const HoverPreviewDocument = observer(
({ url, id, title, summary, lastActivityByViewer, ref }: Props) => {
const parsedUrl = new URL(url, window.location.href);
const { documents } = useStores();
const document = documents.get(id);
// We only need to fetch the document.
// DocumentBreadcrumb handles loading the collection and relations internally.
React.useEffect(() => {
if (!document) {
void documents.fetch(id);
}
}, [id, document, documents]);
const content = (
<Card ref={ref}>
<CardContent>
<ErrorBoundary showTitle={false} reloadOnChunkMissing={false}>
<Flex column gap={2}>
{/* Wrap the built-in breadcrumb in your container for CSS spacing */}
{document && (
<BreadcrumbContainer>
<DocumentBreadcrumb document={document} onlyText />
</BreadcrumbContainer>
)}
<Title>{title}</Title>
{lastActivityByViewer && <Info>{lastActivityByViewer}</Info>}
<Description as="div">
@@ -42,8 +66,25 @@ const HoverPreviewDocument = React.forwardRef(function HoverPreviewDocument_(
</ErrorBoundary>
</CardContent>
</Card>
</Preview>
);
});
);
if (parsedUrl.origin !== window.location.origin) {
return (
<Preview as="a" href={url}>
{content}
</Preview>
);
}
return (
<Preview
as={Link}
to={`${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`}
>
{content}
</Preview>
);
}
);
export default HoverPreviewDocument;
@@ -15,12 +15,17 @@ import {
} from "./Components";
import ErrorBoundary from "../ErrorBoundary";
type Props = Omit<UnfurlResponse[UnfurlResourceType.Group], "type">;
type Props = Omit<UnfurlResponse[UnfurlResourceType.Group], "type"> & {
ref?: React.Ref<HTMLDivElement>;
};
const HoverPreviewGroup = React.forwardRef(function HoverPreviewGroup_(
{ name, description, memberCount, users }: Props,
ref: React.Ref<HTMLDivElement>
) {
function HoverPreviewGroup({
name,
description,
memberCount,
users,
ref,
}: Props) {
const { t } = useTranslation();
return (
@@ -65,6 +70,6 @@ const HoverPreviewGroup = React.forwardRef(function HoverPreviewGroup_(
</Card>
</Preview>
);
});
}
export default HoverPreviewGroup;
@@ -21,12 +21,21 @@ import {
Info,
} from "./Components";
type Props = Omit<UnfurlResponse[UnfurlResourceType.Issue], "type">;
type Props = Omit<UnfurlResponse[UnfurlResourceType.Issue], "type"> & {
ref?: React.Ref<HTMLDivElement>;
};
const HoverPreviewIssue = React.forwardRef(function HoverPreviewIssue_(
{ url, id, title, description, author, labels, state, createdAt }: Props,
ref: React.Ref<HTMLDivElement>
) {
function HoverPreviewIssue({
url,
id,
title,
description,
author,
labels,
state,
createdAt,
ref,
}: Props) {
const authorName = author.name;
const urlObj = new URL(url);
const service =
@@ -88,7 +97,7 @@ const HoverPreviewIssue = React.forwardRef(function HoverPreviewIssue_(
</Flex>
</Preview>
);
});
}
const StyledIssueStatusIcon = styled(IssueStatusIcon)`
margin-top: 2px;
@@ -18,12 +18,16 @@ type Props = {
thumbnailUrl: string;
/** Some description about the link provider */
description: string;
ref?: React.Ref<HTMLDivElement>;
};
const HoverPreviewLink = React.forwardRef(function HoverPreviewLink_(
{ url, thumbnailUrl, title, description }: Props,
ref: React.Ref<HTMLDivElement>
) {
function HoverPreviewLink({
url,
thumbnailUrl,
title,
description,
ref,
}: Props) {
return (
<Preview as="a" href={url} target="_blank" rel="noopener noreferrer">
<Flex column ref={ref}>
@@ -39,6 +43,6 @@ const HoverPreviewLink = React.forwardRef(function HoverPreviewLink_(
</Flex>
</Preview>
);
});
}
export default HoverPreviewLink;
Loaded 100 of 1426 files, more files were not shown because too many files have changed in this diff. Show more