Merge remote-tracking branch 'origin/main' into tommoor/new-permissions

# Conflicts:
#	app/components/Sharing/Collection/AccessControlList.tsx
#	app/components/Sharing/Document/AccessControlList.tsx
#	server/models/GroupMembership.ts
#	server/models/UserMembership.ts
#	server/policies/document.test.ts
#	server/policies/document.ts
#	server/routes/api/documents/schema.ts
#	shared/i18n/locales/en_US/translation.json
#	shared/types.ts
This commit is contained in:
Tom Moor committed 2026-11-13 14:33:22 -05:00
commit a42e9e221e
1570 files changed
+71727 -34884

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
# the cluster 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 -1
View File
@@ -60,7 +60,8 @@ DEFAULT_LANGUAGE=en_US
DATABASE_URL=postgres://user:pass@postgres:5432/outline
# The in-memory database pool per-process settings. Ensure that the pool size that will not exceed
# the maximum number of connections allowed by your database. Defaults to 0 and 5.
# the maximum number of connections allowed by your database. Defaults to 0 and 5, the maximum
# must be at least 2.
DATABASE_CONNECTION_POOL_MIN=
DATABASE_CONNECTION_POOL_MAX=
+3
View File
@@ -13,6 +13,9 @@ updates:
update-types: ["version-update:semver-major"]
schedule:
interval: "weekly"
cooldown:
semver-patch-days: 3
semver-minor-days: 7
groups:
babel:
patterns:
+22 -10
View File
@@ -18,10 +18,11 @@ env:
jobs:
changes:
# 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' }}
runs-on: ubuntu-latest
outputs:
# Blacksmith runners are only available to the outline organization, and are
# not used for pull requests from forks. They are reserved for the test jobs
# that set the wall time of a CI run.
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 }}
@@ -42,8 +43,8 @@ jobs:
- '!shared/i18n/locales/**'
config:
- '.github/**'
- 'vite.config.ts'
- 'vitest.config.ts'
- 'vite.config.mts'
- 'vitest.config.mts'
server:
- 'server/**'
- 'shared/**'
@@ -63,7 +64,7 @@ jobs:
lint:
needs: changes
if: ${{ needs.changes.outputs.code == 'true' }}
runs-on: ${{ needs.changes.outputs.runner }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/install
@@ -82,7 +83,7 @@ jobs:
types:
needs: changes
if: ${{ needs.changes.outputs.code == 'true' }}
runs-on: ${{ needs.changes.outputs.runner }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/install
@@ -92,11 +93,20 @@ jobs:
audit:
needs: changes
if: ${{ needs.changes.outputs.deps == 'true' }}
runs-on: ${{ needs.changes.outputs.runner }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/install
- run: yarn npm audit --severity high --recursive --environment production
# Pass when the audit service is unreachable, but still fail on vulnerabilities.
- run: |
set +e
yarn npm audit --severity high --recursive --environment production 2>&1 | tee audit.log
status=${PIPESTATUS[0]}
if [ "$status" -ne 0 ] && grep -qE "RequestError|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|Response Code: 5[0-9]{2}" audit.log; then
echo "::warning::yarn npm audit could not reach the audit service, skipping."
exit 0
fi
exit "$status"
test:
needs: changes
@@ -136,15 +146,17 @@ jobs:
bundle-size:
needs: changes
if: ${{ (needs.changes.outputs.app == 'true' || needs.changes.outputs.config == 'true') && github.repository == 'outline/outline' }}
runs-on: ${{ needs.changes.outputs.runner }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/install
- name: Set environment to production
run: echo "NODE_ENV=production" >> "$GITHUB_ENV"
- run: yarn vite:build
# RelativeCI is an external service, an outage should not block merging.
- name: Send bundle stats to RelativeCI
if: ${{ env.RELATIVE_CI_KEY != '' }}
continue-on-error: true
env:
RELATIVE_CI_KEY: ${{ secrets.RELATIVE_CI_KEY }}
uses: relative-ci/agent-action@38328454d6a23942175eba485fca4fbb807b1f03 # v2
@@ -0,0 +1,58 @@
name: Dependabot Auto-merge
on: pull_request
jobs:
auto-merge:
if: github.repository == 'outline/outline' && github.event.pull_request.user.login == 'dependabot[bot]'
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Fetch Dependabot metadata
id: metadata
uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3.1.0
# Patch bumps, and minor bumps from 1.0 or later, with no new publisher and
# that leave out packages the test suite does not cover well. The required
# "ci" check gates the merge.
- name: Enable auto-merge for eligible updates
env:
GH_TOKEN: ${{ github.token }}
PR_URL: ${{ github.event.pull_request.html_url }}
DEPENDENCIES: ${{ steps.metadata.outputs.updated-dependencies-json }}
run: |
# Turn off auto-merge from an earlier run, as Dependabot can refresh a PR in place.
skip() {
echo "$1"
if [ "$(gh pr view "$PR_URL" --json autoMergeRequest --jq '.autoMergeRequest != null')" = "true" ]; then
gh pr merge --disable-auto "$PR_URL"
fi
exit 0
}
if ! jq -e "length > 0" <<< "$DEPENDENCIES" > /dev/null; then
skip "No dependency metadata found, skipping auto-merge."
fi
ineligible=$(jq -r '
.[]
| select(
.maintainerChanges
or (.dependencyName | test("^(prosemirror-.*|yjs|y-.*|@hocuspocus/.*|sequelize.*|pg|pg-.*|react.*|mobx.*|koa.*|@koa/.*)$"))
or (
.updateType != "version-update:semver-patch"
and (.updateType != "version-update:semver-minor" or (.prevVersion // "" | test("^v?[1-9]") | not))
)
)
| "\(.dependencyName) \(.prevVersion) -> \(.newVersion) (\(.updateType)\(if .maintainerChanges then ", new publisher" else "" end))"
' <<< "$DEPENDENCIES")
if [ -n "$ineligible" ]; then
echo "Skipping auto-merge, these updates need review:"
skip "$ineligible"
fi
gh pr merge --auto --squash "$PR_URL"
+44
View File
@@ -0,0 +1,44 @@
name: Merge Translations
on:
schedule:
# 09:00 UTC every Monday
- cron: "0 9 * * 1"
workflow_dispatch:
jobs:
merge-translations:
if: github.repository == 'outline/outline'
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- name: Squash merge the Crowdin PR when required checks pass
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
run: |
pr=$(gh pr list \
--head translations-main \
--author outline-translations \
--state open \
--json number,headRefOid \
--jq '.[0] // empty')
if [ -z "$pr" ]; then
echo "No open translations PR."
exit 0
fi
number=$(jq -r '.number' <<< "$pr")
sha=$(jq -r '.headRefOid' <<< "$pr")
if ! gh pr checks "$number" --required; then
echo "::error::Required checks are not passing on #$number."
exit 1
fi
# Only merge the commit that the checks ran against.
gh pr merge "$number" --squash --match-head-commit "$sha"
+33
View File
@@ -0,0 +1,33 @@
name: Draft release
# Creates a draft GitHub release for each version tag pushed by `yarn release`,
# so the release is authored by github-actions rather than a maintainer. Edit
# the generated notes and publish the draft from the releases page.
on:
push:
tags:
- "v*"
permissions: {}
jobs:
draft:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Create draft release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
TAG: ${{ github.ref_name }}
run: |
args=(--draft --verify-tag --generate-notes --title "$TAG")
# Tags such as v1.9.2-0 are prereleases.
if [[ "$TAG" == *-* ]]; then
args+=(--prerelease)
fi
gh release create "$TAG" "${args[@]}"
+1 -4
View File
@@ -1,4 +1 @@
#!/usr/bin/env sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged
npx lint-staged
+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;
+38
View File
@@ -0,0 +1,38 @@
/**
* Local oxlint plugin with class style rules.
*/
const plugin = {
meta: {
name: "classes",
},
rules: {
"no-private-identifier": {
meta: {
type: "suggestion",
docs: {
description: "Disallow `#` private class members.",
},
messages: {
forbidden:
"Do not use `#` private members. Use the TypeScript `private` modifier instead.",
},
},
create(context) {
const check = (node) => {
if (node.key.type === "PrivateIdentifier") {
context.report({ node: node.key, messageId: "forbidden" });
}
};
return {
AccessorProperty: check,
MethodDefinition: check,
PropertyDefinition: check,
};
},
},
},
};
export default plugin;
+198
View File
@@ -0,0 +1,198 @@
/**
* Local oxlint plugin with ProseMirror editor-specific rules.
*/
/** Files that contain editor schema code. */
const EDITOR_FILE =
/(^|[\\/])(shared[\\/]editor|plugins[\\/][^\\/]+[\\/]shared)[\\/]/;
/** Module that exports the url sanitizers, matched by any alias or relative path. */
const SANITIZER_SOURCE = /(^|\/)utils\/urls$/;
/** Exported names that sanitize a url for use in the DOM. */
const SANITIZER_NAMES = new Set(["sanitizeUrl", "sanitizeImageSrc"]);
/** Attributes that the browser can follow or load as a url. */
const URL_ATTRIBUTES = new Set(["href", "src"]);
/** Returns the static name of a property key, or null if it is computed. */
function keyName(node, computed) {
if (!computed && node.type === "Identifier") {
return node.name;
}
if (node.type === "Literal" && typeof node.value === "string") {
return node.value;
}
return null;
}
/** Returns true if the function is a `toDOM` method or `toDOM:` property. */
function isToDOMFunction(node) {
const parent = node.parent;
if (!parent || parent.value !== node) {
return false;
}
if (parent.type !== "Property" && parent.type !== "MethodDefinition") {
return false;
}
return keyName(parent.key, parent.computed) === "toDOM";
}
/** Returns true if the node is inside the body of a `toDOM` function. */
function isInsideToDOM(node) {
for (let current = node.parent; current; current = current.parent) {
if (
(current.type === "FunctionExpression" ||
current.type === "ArrowFunctionExpression") &&
isToDOMFunction(current)
) {
return true;
}
}
return false;
}
/** Returns the variable that the identifier refers to, or null if it is not declared. */
function resolveVariable(scope, identifier) {
for (let current = scope; current; current = current.upper) {
const variable = current.set.get(identifier.name);
if (variable) {
return variable;
}
}
return null;
}
/**
* Returns true if the value cannot carry an unsafe url: a constant, an empty
* value, a direct sanitizer call, or a choice between such values.
*/
function isSafeValue(node, isSanitizer) {
switch (node.type) {
case "Literal":
return typeof node.value === "string" || node.value === null;
case "TemplateLiteral":
return node.expressions.length === 0;
case "Identifier":
return node.name === "undefined";
case "CallExpression":
return node.callee.type === "Identifier" && isSanitizer(node.callee);
case "ConditionalExpression":
return (
isSafeValue(node.consequent, isSanitizer) &&
isSafeValue(node.alternate, isSanitizer)
);
case "LogicalExpression":
return (
isSafeValue(node.left, isSanitizer) &&
isSafeValue(node.right, isSanitizer)
);
default:
return false;
}
}
const plugin = {
meta: {
name: "editor",
},
rules: {
"sanitize-url-in-to-dom": {
meta: {
type: "problem",
docs: {
description:
"Require `sanitizeUrl()` for `href` and `src` values in ProseMirror `toDOM` methods, which write raw DOM attributes.",
},
messages: {
unsanitized:
"Wrap the `{{name}}` value in `sanitizeUrl()` or `sanitizeImageSrc()` from `utils/urls`. `toDOM` writes raw DOM attributes, so a `javascript:` url in a node or mark attribute can run.",
},
},
create(context) {
if (!EDITOR_FILE.test(context.filename)) {
return {};
}
const sanitizerImports = new Set();
// Resolve by binding so a local function that shadows the import is not trusted.
const isSanitizer = (identifier) => {
const variable = resolveVariable(
context.sourceCode.getScope(identifier),
identifier
);
return (
!!variable &&
variable.defs.some((def) => sanitizerImports.has(def.node))
);
};
const check = (node, name, value) => {
if (!isSafeValue(value, isSanitizer)) {
context.report({
node,
messageId: "unsanitized",
data: { name },
});
}
};
return {
ImportDeclaration(node) {
if (!SANITIZER_SOURCE.test(node.source.value)) {
return;
}
for (const specifier of node.specifiers) {
if (
specifier.type === "ImportSpecifier" &&
SANITIZER_NAMES.has(keyName(specifier.imported, false))
) {
sanitizerImports.add(specifier);
}
}
},
Property(node) {
const name = keyName(node.key, node.computed);
if (
!URL_ATTRIBUTES.has(name) ||
node.parent.type !== "ObjectExpression" ||
!isInsideToDOM(node)
) {
return;
}
check(node, name, node.value);
},
CallExpression(node) {
const callee = node.callee;
if (
callee.type !== "MemberExpression" ||
keyName(callee.property, callee.computed) !== "setAttribute" ||
node.arguments.length < 2
) {
return;
}
const name = keyName(node.arguments[0], true);
if (!URL_ATTRIBUTES.has(name) || !isInsideToDOM(node)) {
return;
}
check(node, name, node.arguments[1]);
},
AssignmentExpression(node) {
const left = node.left;
if (left.type !== "MemberExpression") {
return;
}
const name = keyName(left.property, left.computed);
if (!URL_ATTRIBUTES.has(name) || !isInsideToDOM(node)) {
return;
}
check(node, name, node.right);
},
};
},
},
},
};
export default plugin;
+51
View File
@@ -0,0 +1,51 @@
/**
* Local oxlint plugin with Koa-specific rules.
*/
/** 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: "koa",
},
rules: {
"no-request-origin": {
meta: {
type: "problem",
docs: {
description:
"Disallow `request.origin`, which returns the Origin header rather than the URL origin.",
},
messages: {
forbidden:
"`request.origin` is the Origin request header and is null for same-origin requests. Use `request.URL.origin` instead.",
},
},
create(context) {
return {
MemberExpression(node) {
if (
isProperty(node, "origin") &&
isProperty(node.object, "request")
) {
context.report({ node, messageId: "forbidden" });
}
},
};
},
},
},
};
export default plugin;
+197
View File
@@ -0,0 +1,197 @@
/**
* Local oxlint plugin with React Router rules.
*/
const routerPackages = new Set(["react-router", "react-router-dom"]);
/** Hooks whose callback runs later, outside of render. */
const deferredHooks = new Set(["useCallback"]);
/** Returns true if the node is a function. */
function isFunction(node) {
return (
node.type === "ArrowFunctionExpression" ||
node.type === "FunctionExpression" ||
node.type === "FunctionDeclaration"
);
}
/** Returns the hook name if the node is a call to `useX(…)` or `React.useX(…)`. */
function hookName(node) {
if (node?.type !== "CallExpression") {
return null;
}
const callee = node.callee;
if (callee.type === "Identifier") {
return callee.name;
}
if (callee.type === "MemberExpression" && !callee.computed) {
return callee.property.name;
}
return null;
}
/** Returns true if the identifier is a reference rather than a property name. */
function isReference(node, parent) {
if (parent.type === "MemberExpression" && parent.property === node) {
return parent.computed;
}
if (
(parent.type === "Property" || parent.type === "MethodDefinition") &&
parent.key === node
) {
return parent.computed || parent.value === node;
}
return true;
}
/**
* Returns true if the function is known to run later, outside of render: a
* JSX event handler such as `onClick`, or a `useCallback` callback.
*/
function isDeferredFunction(node, parent, grandparent) {
if (parent.type === "JSXExpressionContainer" && parent.expression === node) {
return (
grandparent?.type === "JSXAttribute" &&
grandparent.name.type === "JSXIdentifier" &&
/^on[A-Z]/.test(grandparent.name.name)
);
}
return deferredHooks.has(hookName(parent)) && parent.arguments[0] === node;
}
/**
* Classifies a reference by where it is read: "deferred" when it is read in a
* function known to run later, null when it does not read the value (a
* `useCallback` dependency array), and "render" otherwise.
*/
function classify(ancestors, owner) {
const start = ancestors.indexOf(owner);
for (let i = start + 1; i < ancestors.length; i++) {
const node = ancestors[i];
const parent = ancestors[i - 1];
if (isFunction(node)) {
return isDeferredFunction(node, parent, ancestors[i - 2])
? "deferred"
: "render";
}
if (
node.type === "ArrayExpression" &&
deferredHooks.has(hookName(parent)) &&
parent.arguments[1] === node
) {
return null;
}
}
return "render";
}
const plugin = {
meta: {
name: "react-router",
},
rules: {
"no-deferred-use-location": {
meta: {
type: "problem",
docs: {
description:
"Disallow `useLocation` when the location is only read in callbacks.",
},
messages: {
forbidden:
"The location is only read in callbacks, but `useLocation` re-renders this component on every navigation. Read `history.location` in the callback instead.",
},
},
create(context) {
const useLocationNames = new Set();
const tracked = [];
return {
ImportDeclaration(node) {
if (!routerPackages.has(node.source.value)) {
return;
}
for (const specifier of node.specifiers) {
if (
specifier.type === "ImportSpecifier" &&
specifier.imported.name === "useLocation"
) {
useLocationNames.add(specifier.local.name);
}
}
},
VariableDeclarator(node) {
if (
node.id.type !== "Identifier" ||
node.init?.type !== "CallExpression" ||
node.init.callee.type !== "Identifier" ||
!useLocationNames.has(node.init.callee.name)
) {
return;
}
const owner = context.sourceCode
.getAncestors(node)
.findLast(isFunction);
if (owner) {
tracked.push({
node,
owner,
name: node.id.name,
render: false,
deferred: false,
});
}
},
Identifier(node) {
if (!tracked.length) {
return;
}
const ancestors = context.sourceCode.getAncestors(node);
const parent = ancestors[ancestors.length - 1];
if (!isReference(node, parent)) {
return;
}
for (const entry of tracked) {
if (
entry.name !== node.name ||
entry.node.id === node ||
!ancestors.includes(entry.owner)
) {
continue;
}
const kind = classify([...ancestors, node], entry.owner);
if (kind) {
entry[kind] = true;
}
}
},
"Program:exit"() {
for (const entry of tracked) {
if (entry.deferred && !entry.render) {
context.report({ node: entry.node, messageId: "forbidden" });
}
}
},
};
},
},
},
};
export default plugin;
+48
View File
@@ -0,0 +1,48 @@
/**
* Local oxlint plugin with Sequelize-specific rules.
*/
/** 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: "sequelize",
},
rules: {
"prefer-after-commit-helper": {
meta: {
type: "problem",
docs: {
description:
"Disallow calling `transaction.afterCommit` directly. Use the `afterCommit` helper from `@server/storage/transaction` instead.",
},
messages: {
forbidden:
"Use `afterCommit(transaction, callback)` from `@server/storage/transaction`. A nested transaction runs its hooks when the savepoint is released, before the commit, and the helper also runs the callback when there is no transaction.",
},
},
create(context) {
return {
CallExpression(node) {
if (isProperty(node.callee, "afterCommit")) {
context.report({ node: node.callee, messageId: "forbidden" });
}
},
};
},
},
},
};
export default plugin;
+76
View File
@@ -0,0 +1,76 @@
/**
* Local oxlint plugin with rules for Vitest test files.
*/
// Must match ISOLATED_MARKER and the header length checked in vitest.config.mts.
const ISOLATED_MARKER = "@vitest-isolate true";
const HEADER_LENGTH = 512;
const MODULE_METHODS = new Set(["mock", "doMock", "resetModules"]);
/** Returns true if the file runs in the server Vitest projects. */
function isServerTestFile(filename) {
return /(^|\/)(server|plugins)\/.*\.test\.tsx?$/.test(
filename.replace(/\\/g, "/")
);
}
/** Returns the method name if the callee is `vi.<method>`, else null. */
function viMethodName(callee) {
if (
callee.type !== "MemberExpression" ||
callee.computed ||
callee.object.type !== "Identifier" ||
callee.object.name !== "vi" ||
callee.property.type !== "Identifier"
) {
return null;
}
return callee.property.name;
}
const plugin = {
meta: {
name: "vitest-local",
},
rules: {
"require-isolate-directive": {
meta: {
type: "problem",
docs: {
description:
"Require the `// @vitest-isolate true` header in server test files that mock or reset modules. Server tests share a module registry between files, so a mock leaks into other files.",
},
messages: {
missing:
"`vi.{{method}}` changes the module registry that server test files share. Add `// @vitest-isolate true` as the first line of this file so it runs isolated.",
},
},
create(context) {
if (!isServerTestFile(context.filename)) {
return {};
}
const header = context.sourceCode.text.slice(0, HEADER_LENGTH);
if (header.includes(ISOLATED_MARKER)) {
return {};
}
return {
CallExpression(node) {
const method = viMethodName(node.callee);
if (method && MODULE_METHODS.has(method)) {
context.report({
node: node.callee,
messageId: "missing",
data: { method },
});
}
},
};
},
},
},
};
export default plugin;
+55 -1
View File
@@ -9,9 +9,38 @@
"patches/**",
"*.d.ts"
],
"jsPlugins": ["./.oxlint/mobx.mjs"],
"jsPlugins": [
"./.oxlint/mobx.mjs",
"./.oxlint/bundle.mjs",
"./.oxlint/sequelize.mjs",
"./.oxlint/vitest.mjs",
"./.oxlint/editor.mjs",
"./.oxlint/koa.mjs",
"./.oxlint/react-router.mjs",
"./.oxlint/classes.mjs"
],
"plugins": ["eslint", "typescript", "unicorn", "oxc", "vitest"],
"rules": {
"mobx/observable-needs-initializer": "error",
"sequelize/prefer-after-commit-helper": "error",
"vitest/consistent-test-it": [
"error",
{ "fn": "it", "withinDescribe": "it" }
],
"vitest/no-focused-tests": "error",
"vitest/no-disabled-tests": "error",
"vitest/no-identical-title": "error",
"vitest/expect-expect": "off",
"vitest/no-conditional-expect": "off",
"vitest/require-mock-type-parameters": "off",
"vitest/require-to-throw-message": "off",
"vitest/valid-expect": "off",
"vitest/valid-title": "off",
"vitest-local/require-isolate-directive": "error",
"editor/sanitize-url-in-to-dom": "error",
"koa/no-request-origin": "error",
"react-router/no-deferred-use-location": "error",
"classes/no-private-identifier": "error",
"for-direction": "error",
"no-async-promise-executor": "error",
"no-case-declarations": "error",
@@ -70,6 +99,24 @@
"valid-typeof": "error"
},
"overrides": [
{
"files": ["plugins/*/client/**/*.{js,jsx,ts,tsx}"],
"rules": {
"bundle/no-constructor-name": "error"
}
},
{
"files": ["plugins/*/server/**/*.{js,ts}"],
"rules": {
"no-restricted-properties": [
"error",
{
"property": "isBot",
"message": "Use `isbot` from the `isbot` package instead"
}
]
}
},
{
"files": ["**/*.{ts,tsx}"],
"rules": {
@@ -96,12 +143,19 @@
],
"message": "Use the wrappers from shared/editor/commands/table instead, which respect the target index and place the cursor in the inserted cell."
}
],
"patterns": [
{
"group": ["lodash", "lodash/*", "lodash.*", "lodash-es"],
"message": "Use es-toolkit instead."
}
]
}
],
"no-unused-expressions": "error",
"arrow-body-style": ["error", "as-needed"],
"react/react-in-jsx-scope": "off",
"react/button-has-type": "error",
"typescript/await-thenable": "error",
"typescript/no-duplicate-type-constituents": "error",
"typescript/no-meaningless-void-operator": "error",
+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');
+20
View File
@@ -32,10 +32,12 @@ 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 ("").
- Do not add translation strings manually; they will be extracted automatically from the codebase.
- UI strings use US English and full grammar. Do not join two sentences with a comma.
## Dependencies and Upgrading
@@ -94,6 +96,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 +108,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 +126,9 @@ 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.
- When changing persisted task input fields, keep readers compatible with queued inputs or migrate them before removing old fields.
## API Design
@@ -133,12 +146,18 @@ 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.
- When linking accounts by provider email, use exact case-insensitive equality within the workspace.
- 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.
- When persisting pasted attachment URLs, use `signedUrlToAttachmentUrl` to convert this instance’s signed URLs to stable attachment redirects. Cover HTML, Markdown, and single-URL pastes, including pasting over selected text; document nodes and link marks must not retain expiring local URLs, and external URLs must remain unchanged.
- Editor plugins that repair the document (assigning missing IDs, fixing invalid structure) must use `RepairPlugin` from `shared/editor/plugins/RepairPlugin.ts`. Other plugins that change the document in `appendTransaction` must only respond to local changes, guard with `isLocalDocChange` from `shared/editor/lib/multiplayer.ts`. Otherwise every connected client writes the change in response to remote edits and is attributed as an editor.
## Documentation
@@ -195,6 +214,7 @@ yarn test:shared # All shared code tests
- Implement pagination for large lists.
- Use database indexes effectively.
- Cache expensive computations.
- Use `Redis.ephemeralClient` for request-path caches, rate limits, and locks, including lock extension and release.
- Monitor performance with appropriate tools.
- Lazy load routes and components where appropriate.
+1 -1
View File
@@ -6,7 +6,7 @@ ARG APP_PATH
WORKDIR $APP_PATH
# ---
FROM node:26.3.0-slim AS runner
FROM node:26.13.1-slim AS runner
LABEL org.opencontainers.image.source="https://github.com/outline/outline"
+1 -1
View File
@@ -1,5 +1,5 @@
ARG APP_PATH=/opt/outline
FROM node:26.3.0 AS deps
FROM node:26.13.1 AS deps
ARG APP_PATH
WORKDIR $APP_PATH
+2 -2
View File
@@ -3,7 +3,7 @@ Business Source License 1.1
Parameters
Licensor: General Outline, Inc.
Licensed Work: Outline 1.10.1
Licensed Work: Outline 1.12.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-09
Change Date: 2030-10-23
Change License: Apache License, Version 2.0
-4
View File
@@ -104,10 +104,6 @@ Or, to run migrations on test database:
yarn db:migrate --env test
```
# Activity
![Alt](https://repobeats.axiom.co/api/embed/ff2e4e6918afff1acf9deb72d1ba6b071d586178.svg "Repobeats analytics image")
# License
Outline is [BSL 1.1 licensed](LICENSE).
-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;
+5
View File
@@ -6,6 +6,7 @@
{
"files": ["**/*.{js,jsx,ts,tsx}"],
"rules": {
"bundle/no-constructor-name": "error",
"no-restricted-globals": [
"error",
{
@@ -37,6 +38,10 @@
{
"group": ["mime-types"],
"message": "Do not use the mime-types package in the browser."
},
{
"group": ["lodash", "lodash/*", "lodash.*", "lodash-es"],
"message": "Use es-toolkit instead."
}
]
}
+10 -4
View File
@@ -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,
@@ -98,7 +100,8 @@ export const editCollection = createAction({
analyticsName: "Edit collection",
section: ActiveCollectionSection,
icon: <EditIcon />,
visible: ({ getActivePolicies }) =>
visible: ({ getActiveModel, getActivePolicies }) =>
!getActiveModel(Collection)?.isPersonal &&
getActivePolicies(Collection).some((policy) => policy.abilities.update),
perform: ({ t, getActiveModel, stores }) => {
const collection = getActiveModel(Collection);
@@ -125,7 +128,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) {
@@ -385,6 +390,7 @@ export const subscribeCollection = createAction({
return (
!!collection.isActive &&
!collection.isPersonal &&
!collection.isSubscribed &&
stores.policies.abilities(collection.id).subscribe
);
+49 -60
View File
@@ -7,7 +7,6 @@ import {
StarredIcon,
PrintIcon,
UnstarredIcon,
DocumentIcon,
NewDocumentIcon,
ShapesIcon,
ImportIcon,
@@ -42,6 +41,7 @@ import {
PDFIcon,
} from "outline-icons";
import { toast } from "sonner";
import { showPublicLinkCopiedToast } from "~/components/Sharing/components/toasts";
import Icon from "@shared/components/Icon";
import type { NavigationNode } from "@shared/types";
import {
@@ -117,8 +117,10 @@ import env from "~/env";
import { isMac, isWindows } from "@shared/utils/browser";
import isCloudHosted from "~/utils/isCloudHosted";
import DocumentMove from "~/components/DocumentExplorer/DocumentMove";
import { DocumentIcon } from "~/components/Icons/DocumentIcon";
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(
@@ -151,10 +153,11 @@ export const openDocument = createActionWithChildren({
.filter((item) => !recentIds.has(item.id))
.map((item) => {
const document = stores.documents.get(item.id);
const path = item instanceof Document ? item.path : item.url;
return createInternalLinkAction({
// Note: using url which includes the slug rather than id here to bust
// Note: using path which includes the slug rather than id here to bust
// cache if the document is renamed
id: item.url,
id: path,
name: item.title,
description: document
? documentBreadcrumbText(document, t)
@@ -166,10 +169,10 @@ export const openDocument = createActionWithChildren({
color={item.color ?? undefined}
/>
) : (
<DocumentIcon outline={item.isDraft} />
<DocumentIcon empty={document?.isEmpty} />
),
section: DocumentSection,
to: item.url,
to: path,
});
});
},
@@ -491,7 +494,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);
@@ -519,7 +522,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
),
});
@@ -587,7 +590,7 @@ export const unpublishDocument = createAction({
? t("Unpublished {{ documentName }}", {
documentName: documents[0].noun,
})
: t("{{ count }} documents unpublished", { count: succeeded })
: t("{{ count }} document unpublished", { count: succeeded })
),
});
@@ -720,20 +723,17 @@ 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.
*/
/** Shows a file extension at the end of menu items only. */
const fileExtensionHint =
(extension: string) =>
({ isMenu }: ActionContext) =>
isMenu ? [extension] : undefined;
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"),
badge: fileExtensionHint(".md"),
keywords: "md markdown export download",
icon: <MarkdownIcon />,
iconInContextMenu: false,
@@ -755,7 +755,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"),
badge: fileExtensionHint(".html"),
keywords: "xml html export download",
icon: <CodeIcon />,
iconInContextMenu: false,
@@ -778,7 +778,7 @@ export const downloadDocumentAsTextBundle = createAction({
isMenu ? t("TextBundle") : t("Download as TextBundle"),
analyticsName: "Download document as TextBundle",
section: ActiveDocumentSection,
shortcut: fileExtensionHint(".textpack"),
badge: fileExtensionHint(".textpack"),
keywords: "textbundle textpack bear ulysses export download",
icon: <ArchiveIcon />,
iconInContextMenu: false,
@@ -800,7 +800,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"),
badge: fileExtensionHint(".pdf"),
keywords: "pdf export download",
icon: <PDFIcon />,
iconInContextMenu: false,
@@ -872,7 +872,7 @@ export const copyDocumentShareLink = createAction({
iconInContextMenu: false,
visible: ({ activeDocumentId, stores }) =>
!!activeDocumentId &&
!!stores.shares.getByDocumentId(activeDocumentId)?.published,
!!stores.shares.getByDocumentId(activeDocumentId)?.isActive,
perform: ({ stores, activeDocumentId, t }) => {
if (!activeDocumentId) {
return;
@@ -880,7 +880,7 @@ export const copyDocumentShareLink = createAction({
const share = stores.shares.getByDocumentId(activeDocumentId);
if (share) {
copy(share.url);
toast.success(t("Link copied to clipboard"));
showPublicLinkCopiedToast(share, t);
}
},
});
@@ -989,7 +989,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 })
),
});
@@ -1050,7 +1050,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 })
),
});
@@ -1373,7 +1373,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,
@@ -1389,31 +1389,32 @@ export const moveDocumentToCollection = createAction({
section: ActiveDocumentSection,
icon: <MoveIcon />,
iconInContextMenu: false,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
visible: (context) =>
everyActiveModel(
context,
Document,
(document) => !!context.stores.policies.abilities(document.id).move
),
perform: ({ getActiveModels, stores, t }) => {
const documents = getActiveModels(Document);
if (!documents.length) {
return;
}
return !!stores.policies.abilities(activeDocumentId).move;
},
perform: ({ activeDocumentId, stores, t }) => {
if (activeDocumentId) {
const document = stores.documents.get(activeDocumentId);
if (!document) {
return;
}
stores.dialogs.openModal({
title: (
stores.dialogs.openModal({
title:
documents.length === 1 ? (
<DialogTitle
title={t("Move {{ documentType }}", {
documentType: document.noun,
documentType: documents[0].noun,
})}
model={document}
model={documents[0]}
/>
) : (
t("Move {{ count }} document", { count: documents.length })
),
content: <DocumentMove document={document} />,
});
}
content: <DocumentMove documents={documents} />,
});
},
});
@@ -1422,16 +1423,7 @@ export const moveDocument = createAction({
analyticsName: "Move document",
section: ActiveDocumentSection,
icon: <MoveIcon />,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
const document = stores.documents.get(activeDocumentId);
if (!document) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).move;
},
visible: moveDocumentToCollection.visible,
perform: moveDocumentToCollection.perform,
});
@@ -1475,7 +1467,7 @@ export const archiveDocument = createAction({
toast.success(
documents.length === 1
? t("Document archived")
: t("{{ count }} documents archived", { count: succeeded })
: t("{{ count }} document archived", { count: succeeded })
);
}
}}
@@ -1508,7 +1500,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 })
),
});
@@ -1545,7 +1537,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,
@@ -1618,7 +1610,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 })
);
}
}}
@@ -1824,12 +1816,9 @@ const headingPrefixNames: Record<HeadingPrefixStyle, (t: TFunction) => string> =
const changeHeadingPrefixFactory = (style: HeadingPrefixStyle) =>
createAction({
name: ({ t }) => headingPrefixNames[style](t),
// The example is displayed in the shortcut slot of menu items, but must
// not be set on the command bar action where shortcuts are registered as
// key sequences.
shortcut: ({ isMenu }) =>
badge: ({ isMenu }) =>
isMenu && headingPrefixExamples[style]
? [headingPrefixExamples[style]]
? headingPrefixExamples[style]
: undefined,
keywords: headingPrefixExamples[style],
analyticsName: "Change heading numbering",
+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"),
+1 -1
View File
@@ -80,7 +80,7 @@ export const restoreRevision = createInternalLinkAction({
}
return {
pathname: document.url,
pathname: document.path,
state: { restore: true, revisionId },
};
},
+92 -2
View File
@@ -1,15 +1,23 @@
import copy from "copy-to-clipboard";
import { addDays, endOfDay } from "date-fns";
import Share from "~/models/Share";
import { createAction, createInternalLinkAction } from "..";
import {
ActionSeparator,
createAction,
createActionWithChildren,
createInternalLinkAction,
} from "..";
import {
everyActiveModel,
performBatchOnActiveModels,
} from "~/actions/definitions/common";
import { ArrowIcon, CopyIcon, TrashIcon } from "outline-icons";
import { ArrowIcon, CalendarIcon, CopyIcon, TrashIcon } from "outline-icons";
import { ShareSection } from "../sections";
import type { ActionContext } from "~/types";
import env from "~/env";
import { toast } from "sonner";
import { errToString } from "@shared/utils/error";
import { ShareExpiryDialog } from "~/components/Sharing/components/ShareExpiryDialog";
export const copyShareUrl = createAction({
name: ({ t }) => t("Copy link"),
@@ -51,6 +59,70 @@ export const goToShareSource = createInternalLinkAction({
},
});
export const customShareExpiry = createAction({
name: ({ t }) => `${t("Custom")}…`,
analyticsName: "Set custom share expiry",
section: ShareSection,
perform: (context) => {
const share = singleActiveShare(context);
if (!share) {
return;
}
const { dialogs } = context.stores;
dialogs.openModal({
title: context.t("Set expiry"),
width: "600px",
content: (
<ShareExpiryDialog share={share} onSubmit={dialogs.closeAllModals} />
),
});
},
});
export const removeShareExpiry = createAction({
name: ({ t }) => t("Remove expiry"),
analyticsName: "Remove share expiry",
section: ShareSection,
visible: (context) => !!singleActiveShare(context)?.expiresAt,
perform: (context) =>
saveShareExpiry(context, null, context.t("Expiry removed")),
});
export const setShareExpiry = createActionWithChildren({
name: ({ t }) => t("Set expiry"),
analyticsName: "Set share expiry",
section: ShareSection,
icon: <CalendarIcon />,
visible: (context) => {
const { auth, policies } = context.stores;
const share = singleActiveShare(context);
return (
!!share &&
!!policies.abilities(auth.team?.id || "").share &&
!!policies.abilities(share.id).update
);
},
children: [
...[1, 7, 30].map((days) =>
createAction({
name: ({ t }) => t("{{ count }} days", { count: days }),
analyticsName: "Set share expiry preset",
section: ShareSection,
perform: (context) =>
saveShareExpiry(
context,
endOfDay(addDays(new Date(), days)),
context.t("Expiry updated")
),
})
),
customShareExpiry,
ActionSeparator,
removeShareExpiry,
],
});
export const revokeShare = createAction({
name: ({ t }) => t("Revoke link"),
analyticsName: "Revoke share",
@@ -86,6 +158,24 @@ export const revokeShare = createAction({
},
});
const saveShareExpiry = async (
context: ActionContext,
date: Date | null,
message: string
) => {
const share = singleActiveShare(context);
if (!share) {
return;
}
try {
await share.save({ expiresAt: date ? date.toISOString() : null });
toast.success(message);
} catch (err) {
toast.error(errToString(err));
}
};
const singleActiveShare = ({ getActiveModels }: ActionContext) => {
const shares = getActiveModels(Share);
return shares.length === 1 ? shares[0] : undefined;
+9 -2
View File
@@ -15,11 +15,18 @@ import Desktop from "~/utils/Desktop";
import { dialogActionFactory } from "./common";
import { TeamSection } from "../sections";
/**
* Builds workspace links, indicating which workspaces require login.
*
* @param context the stores containing available workspaces.
* @returns the workspace switching actions.
*/
export const switchTeamsList = ({ stores }: { stores: RootStore }) =>
stores.auth.availableTeams?.map<ExternalLinkAction>((session) =>
createExternalLinkAction({
id: `switch-${session.id}`,
name: session.name,
badge: ({ t }) => (session.isSignedIn ? undefined : t("Logged out")),
analyticsName: "Switch workspace",
section: TeamSection,
keywords: "change switch workspace organization team",
@@ -78,8 +85,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?"));
}
},
});
+9 -5
View File
@@ -25,12 +25,16 @@ export const getCurrentContext = createAction({
document: document
? {
id: document.id,
title: document.titleWithDefault,
path: document.url,
title: document.displayTitle,
path: document.path,
}
: undefined,
collection: collection
? { id: collection.id, name: collection.name, path: collection.path }
? {
id: collection.id,
name: collection.displayName,
path: collection.path,
}
: undefined,
});
},
@@ -65,8 +69,8 @@ export const searchWorkspace = createAction({
return JSON.stringify(
results.map((result) => ({
id: result.document.id,
title: result.document.titleWithDefault,
path: result.document.url,
title: result.document.displayTitle,
path: result.document.path,
context: result.context,
}))
);
+4
View File
@@ -152,6 +152,7 @@ export function actionToMenuItem(
const visible = resolve<boolean>(action.visible, context) ?? true;
const disabled = resolve<boolean>(action.disabled, context);
const shortcut = resolve<string[] | undefined>(action.shortcut, context);
const badge = resolve<React.ReactNode>(action.badge, context);
const icon =
!!action.icon && action.iconInContextMenu !== false
? resolve<React.ReactNode>(action.icon, context)
@@ -169,6 +170,7 @@ export function actionToMenuItem(
selected: resolve<boolean>(action.selected, context),
dangerous: action.dangerous,
shortcut,
badge,
onClick: () => performAction(action, context),
};
@@ -181,6 +183,7 @@ export function actionToMenuItem(
visible,
disabled,
shortcut,
badge,
to,
};
}
@@ -193,6 +196,7 @@ export function actionToMenuItem(
visible,
disabled,
shortcut,
badge,
href: action.target
? { url: action.url, target: action.target }
: action.url,
+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;
+7 -2
View File
@@ -1,4 +1,3 @@
/* oxlint-disable react/prop-types */
import { observer } from "mobx-react";
import * as React from "react";
import type { Props as TooltipProps } from "~/components/Tooltip";
@@ -16,6 +15,8 @@ export type Props = React.HTMLAttributes<HTMLButtonElement> & {
action?: Exclude<ActionVariant, ActionWithChildren>;
/** If tooltip props are provided the button will be wrapped in a tooltip */
tooltip?: Omit<TooltipProps, "children">;
/** The button type, defaults to "button" */
type?: "button" | "submit" | "reset";
};
/**
@@ -26,6 +27,7 @@ function ActionButton({
tooltip,
hideOnActionDisabled,
ref,
type = "button",
...rest
}: Props & { ref?: React.Ref<HTMLButtonElement> }) {
const actionContext = useActionContext({
@@ -34,7 +36,8 @@ function ActionButton({
const [executing, setExecuting] = React.useState(false);
if (!actionContext || !action) {
return <button {...rest} ref={ref} />;
// oxlint-disable-next-line react/button-has-type -- type defaults to "button"
return <button {...rest} type={type} ref={ref} />;
}
const actionIsDisabled =
@@ -55,6 +58,8 @@ function ActionButton({
const button = (
<button
{...rest}
// oxlint-disable-next-line react/button-has-type -- type defaults to "button"
type={type}
aria-label={typeof label === "string" ? label : undefined}
disabled={disabled || executing}
ref={ref}
+6 -1
View File
@@ -1,5 +1,6 @@
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/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";
+12 -11
View File
@@ -1,8 +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 { DragAndDropProvider } from "~/components/DragAndDrop";
import ErrorSuspended from "~/scenes/Errors/ErrorSuspended";
import Layout from "~/components/Layout";
import RegisterKeyDown from "~/components/RegisterKeyDown";
@@ -14,6 +12,7 @@ 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";
@@ -40,8 +39,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 +90,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 +104,13 @@ const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => {
return (
<DocumentContextProvider>
<RightSidebarProvider>
<PortalContext.Provider value={layoutRef.current}>
<DndProvider backend={EditorAwareHTML5Backend}>
<PortalContext.Provider value={layoutElement}>
<DragAndDropProvider>
<Layout
title={team.name}
sidebar={sidebar}
sidebarCanCollapse={!isSettings}
ref={layoutRef}
ref={setLayoutElement}
>
<RegisterKeyDown trigger="n" handler={goToNewDocument} />
<RegisterKeyDown trigger="t" handler={goToSearch} />
@@ -118,7 +119,7 @@ const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => {
<CommandBar />
<NotificationBadge />
</Layout>
</DndProvider>
</DragAndDropProvider>
</PortalContext.Provider>
</RightSidebarProvider>
</DocumentContextProvider>
+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>
);
}
});
+24 -8
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";
@@ -75,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>
@@ -110,7 +117,7 @@ const Slash = styled(GoToIcon)`
fill: ${s("divider")};
`;
const Item = styled(Link)<{ $highlight: boolean }>`
const itemStyles = css<{ $highlight: boolean }>`
${undraggableOnDesktop()}
display: flex;
@@ -118,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;
@@ -131,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,
@@ -140,6 +151,11 @@ const Item = styled(Link)<{ $highlight: boolean }>`
}
`;
const StaticItem = styled.span<{ $highlight: boolean }>`
${itemStyles}
cursor: default;
`;
const Title = styled.span`
${ellipsis()}
min-width: 0;
+25 -2
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 "@shared/styles/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 & {
@@ -192,6 +214,7 @@ function 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}>
+1 -1
View File
@@ -1,6 +1,6 @@
import * as React from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
type Props = {
+9 -14
View File
@@ -17,12 +17,12 @@ const Circle = ({
}) => {
const radius = offset * 0.7;
const circumference = 2 * Math.PI * radius;
let strokePercentage;
let strokeDashoffset = 0;
if (percentage) {
if (percentage !== undefined) {
// because the circle is so small, anything greater than 85% appears like 100%
percentage = percentage > 85 && percentage < 100 ? 85 : percentage;
strokePercentage = ((100 - percentage) * circumference) / 100;
const visible = percentage > 85 && percentage < 100 ? 85 : percentage;
strokeDashoffset = ((100 - visible) * circumference) / 100;
}
return (
@@ -31,13 +31,14 @@ const Circle = ({
cx={offset}
cy={offset}
fill="none"
stroke={strokePercentage !== circumference ? color : ""}
stroke={color}
strokeWidth={2.5}
strokeDasharray={circumference}
strokeDashoffset={percentage ? strokePercentage : 0}
strokeLinecap="round"
style={{
transition: "stroke-dashoffset 0.6s ease 0s",
strokeDashoffset: `${strokeDashoffset}px`,
opacity: percentage === 0 ? 0 : 1,
transition: "stroke-dashoffset 0.6s ease, opacity 0.6s ease",
}}
/>
);
@@ -76,13 +77,7 @@ const CircularProgressBar = ({
>
<g transform={`rotate(-90 ${offset} ${offset})`}>
<Circle color={theme.progressBarBackground} offset={offset} />
{percentage > 0 && (
<Circle
color={theme.accent}
percentage={percentage}
offset={offset}
/>
)}
<Circle color={theme.accent} percentage={percentage} offset={offset} />
</g>
</SVG>
);
+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),
+3 -3
View File
@@ -42,9 +42,9 @@ function CollectionDeleteDialog({ collection, onSubmit }: Props) {
<>
<Text as="p" type="secondary">
<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."
defaults="Are you sure about that? Deleting the <em>{{collectionName}}</em> collection is permanent and cannot be restored, but 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 />,
+1 -1
View File
@@ -3,7 +3,7 @@ import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { depths, s } from "@shared/styles";
import { Portal } from "~/components/Portal";
import SearchActions from "~/components/SearchActions";
@@ -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
) {
@@ -3,7 +3,7 @@ import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import { depths, s } from "@shared/styles";
import { Portal } from "~/components/Portal";
import CommandBarResults from "./CommandBarResults";
@@ -1,13 +1,13 @@
import { DocumentIcon } from "outline-icons";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import Icon from "@shared/components/Icon";
import { createInternalLinkAction } from "~/actions";
import { RecentSection } from "~/actions/sections";
import { documentBreadcrumbText } from "~/components/DocumentBreadcrumb";
import { useComputed } from "~/hooks/useComputed";
import useStores from "~/hooks/useStores";
import type Document from "~/models/Document";
import { documentPath } from "~/utils/routeHelpers";
import { DocumentIcon } from "~/components/Icons/DocumentIcon";
/** The number of documents listed under "Recently viewed" in the command bar. */
export const recentDocumentCount = 6;
@@ -35,7 +35,7 @@ const useRecentDocumentActions = (count = recentDocumentCount) => {
const { documents, ui } = useStores();
const { t } = useTranslation();
return useMemo(
return useComputed(
() =>
recentDocuments(
documents.recentlyViewed,
@@ -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,
@@ -55,12 +55,12 @@ const useRecentDocumentActions = (count = recentDocumentCount) => {
color={item.color ?? undefined}
/>
) : (
<DocumentIcon outline={item.isDraft} />
<DocumentIcon empty={item.isEmpty} />
),
to: documentPath(item),
})
),
[count, ui.activeDocumentId, documents.recentlyViewed, t]
[count, documents, ui, t]
);
};
+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,
url: doc.url,
text: doc.data ? getPlainText(doc) : stripHighlightTags(context),
title: doc.displayTitle,
url: doc.path,
text: content ? content.text : stripHighlightTags(context),
headings: content?.headings,
icon: doc.icon,
color: doc.color,
isArchived: doc.isArchived,
@@ -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]
);
@@ -28,7 +28,7 @@ const useTemplatesAction = () => {
() =>
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"],
}}
+1 -1
View File
@@ -1,8 +1,8 @@
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 { isPrintableKeyEvent } from "@shared/utils/keyboard";
import { TextHelper } from "@shared/utils/TextHelper";
import useOnScreen from "~/hooks/useOnScreen";
@@ -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>();
@@ -40,7 +41,7 @@ const DefaultCollectionInputSelect = observer(
});
} catch (error) {
toast.error(
t("Collections could not be loaded, please reload the app")
t("Collections could not be loaded – please reload the app")
);
setFetchError(toError(error));
} finally {
@@ -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,
},
+2 -2
View File
@@ -2,7 +2,7 @@ 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";
@@ -30,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: {
+3 -3
View File
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
import { DocumentIcon } from "outline-icons";
import type * as React from "react";
import styled from "styled-components";
import Icon from "@shared/components/Icon";
@@ -8,6 +7,7 @@ import Document from "~/models/Document";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import Text from "~/components/Text";
import useStores from "~/hooks/useStores";
import { DocumentIcon } from "~/components/Icons/DocumentIcon";
type Props = {
/** The title of the dialog. */
@@ -51,7 +51,7 @@ export const DialogTitle = observer(function DialogTitle_({
color={model.color ?? undefined}
/>
) : (
<DocumentIcon outline={model.isDraft} />
<DocumentIcon empty={model.isEmpty} />
);
return (
@@ -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>
+17 -1
View File
@@ -1,5 +1,6 @@
import { observer } from "mobx-react";
import { Suspense } from "react";
import { Suspense, useEffect } from "react";
import { useHistory } from "react-router-dom";
import useStores from "~/hooks/useStores";
import lazyWithRetry from "@shared/utils/lazyWithRetry";
import { DialogProvider } from "./DialogContext";
@@ -9,9 +10,24 @@ const Modal = lazyWithRetry(() => import("~/components/Modal"));
function Dialogs() {
const { dialogs } = useStores();
const history = useHistory();
const { guide, modalStack } = dialogs;
const modals = [...modalStack];
// Close open modals when navigating to another page.
useEffect(() => {
let pathname = history.location.pathname;
return history.listen((location) => {
if (location.pathname === pathname) {
return;
}
pathname = location.pathname;
dialogs.modalStack.forEach((modal) => modal.onClose?.());
dialogs.closeAllModals();
});
}, [dialogs, history]);
return (
<DialogProvider>
<Suspense fallback={null}>
+14 -12
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.
@@ -139,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: "",
@@ -262,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>
+6 -5
View File
@@ -3,7 +3,7 @@ import { CSS } from "@dnd-kit/utilities";
import { subDays } from "date-fns";
import { m } from "framer-motion";
import { observer } from "mobx-react";
import { CloseIcon, DocumentIcon, ClockIcon } from "outline-icons";
import { CloseIcon, ClockIcon } from "outline-icons";
import { useRef, useCallback, Suspense } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
@@ -21,6 +21,7 @@ import Time from "~/components/Time";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import { DocumentContextMenu } from "~/menus/DocumentContextMenu";
import { DocumentIcon } from "~/components/Icons/DocumentIcon";
import CollectionIcon from "./Icons/CollectionIcon";
import Text from "./Text";
import Tooltip from "./Tooltip";
@@ -127,7 +128,7 @@ function DocumentCard(props: Props) {
to={{
pathname: document.path,
state: {
title: document.titleWithDefault,
title: document.displayTitle,
},
}}
>
@@ -162,15 +163,15 @@ function DocumentCard(props: Props) {
pinnedToHome ? (
<CollectionIcon collection={collection} color="white" />
) : (
<DocumentIcon color="white" />
<DocumentIcon color="white" empty={document.isEmpty} />
)}
</Squircle>
)}
<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 ? (
+4 -3
View File
@@ -1,5 +1,5 @@
import { observer } from "mobx-react";
import { CloseIcon, DocumentIcon } from "outline-icons";
import { CloseIcon } from "outline-icons";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
@@ -14,6 +14,7 @@ import NudeButton from "~/components/NudeButton";
import Tooltip from "~/components/Tooltip";
import usePolicy from "~/hooks/usePolicy";
import { DocumentContextMenu } from "~/menus/DocumentContextMenu";
import { DocumentIcon } from "~/components/Icons/DocumentIcon";
type Props = {
/** The document to display */
@@ -34,7 +35,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
@@ -68,7 +69,7 @@ export const DocumentChip = observer(function DocumentChip_({
initial={document.initial}
/>
) : (
<DocumentIcon />
<DocumentIcon empty={document.isEmpty} />
)}
<Title>{isEmoji ? title.replace(icon!, "") : title}</Title>
{pin && canUnpin && (
@@ -59,7 +59,7 @@ function DocumentCopy({ document, onSubmit }: Props) {
toast.success(t("Document copied"));
onSubmit(result);
} catch (_err) {
toast.error(t("Couldn’t copy the document, try again?"));
toast.error(t("Couldn’t copy the document. Try again?"));
} finally {
setCopying(false);
}
@@ -3,19 +3,19 @@ import {
concat,
difference,
fill,
filter,
flatten,
includes,
map,
union,
} from "es-toolkit/compat";
import { observer } from "mobx-react";
import { StarredIcon, DocumentIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import AutoSizer from "react-virtualized-auto-sizer";
import { FixedSizeList as List } from "react-window";
import type { ListImperativeAPI, RowComponentProps } from "react-window";
import { List } from "react-window";
import styled, { useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import Icon from "@shared/components/Icon";
import type { NavigationNode } from "@shared/types";
import { isModKey } from "@shared/utils/keyboard";
@@ -40,36 +40,31 @@ type Props = {
defaultValue?: string;
/** Whether to show child documents */
showDocuments?: boolean;
/** Overrides the icon of a node, return undefined to keep the default. */
renderIcon?: (node: NavigationNode) => React.ReactNode;
};
const VERTICAL_PADDING = 6;
const HORIZONTAL_PADDING = 24;
function innerElementType({
style,
ref,
...rest
}: React.HTMLAttributes<HTMLDivElement> & {
ref?: React.Ref<HTMLDivElement>;
}) {
return (
<div
ref={ref}
style={{
...style,
height: `${parseFloat(style?.height + "") + VERTICAL_PADDING * 2}px`,
}}
{...rest}
/>
);
const expandableDescendantIds = (node: NavigationNode) =>
descendants(node)
.filter((des) => des.children.length > 0)
.map((des) => des.id);
interface RowProps {
data: NavigationNode[];
}
const rowKey = (index: number, { data }: RowProps) => data[index].id;
function DocumentExplorer({
onSubmit,
onSelect,
items,
defaultValue,
showDocuments,
renderIcon,
}: Props) {
const isMobile = useMobile();
const { collections, documents } = useStores();
@@ -103,6 +98,10 @@ function DocumentExplorer({
}
return [];
});
// Nodes expanded with alt-click, whose descendants stay expanded as they load.
const [deepExpandedNodes, setDeepExpandedNodes] = React.useState<string[]>(
[]
);
const [itemRefs, setItemRefs] = React.useState<
React.RefObject<HTMLSpanElement>[]
@@ -111,7 +110,7 @@ function DocumentExplorer({
const inputSearchRef = React.useRef<HTMLInputElement | HTMLTextAreaElement>(
null
);
const listRef = React.useRef<List<NavigationNode[]>>(null);
const listRef = React.useRef<ListImperativeAPI>(null);
const searchIndex = React.useMemo(
() =>
@@ -125,6 +124,7 @@ function DocumentExplorer({
if (searchTerm) {
selectNode(null);
setExpandedNodes([]);
setDeepExpandedNodes([]);
}
setActiveNode(0);
}, [searchTerm]);
@@ -160,10 +160,13 @@ function DocumentExplorer({
if (defaultValue && selectedNode && listRef) {
const index = nodes.findIndex((node) => node.id === selectedNode.id);
if (index > 0) {
setTimeout(() => listRef.current?.scrollToItem(index, "center"), 50);
setTimeout(
() => listRef.current?.scrollToRow({ index, align: "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),
@@ -173,7 +176,7 @@ function DocumentExplorer({
(baseDepth === Infinity ? 0 : baseDepth) + (showDocuments ? 0 : 1);
const scrollNodeIntoView = React.useCallback((node: number) => {
listRef.current?.scrollToItem(node, "smart");
listRef.current?.scrollToRow({ index: node, align: "smart" });
}, []);
const handleSearch = (ev: React.ChangeEvent<HTMLInputElement>) => {
@@ -182,38 +185,50 @@ function DocumentExplorer({
const isExpanded = (node: number) => includes(expandedNodes, nodes[node].id);
const preserveScrollOffset = (itemCount: number) => {
if (listRef.current) {
const { height, itemSize } = listRef.current.props;
const { scrollOffset } = listRef.current.state as {
scrollOffset: number;
};
const itemsHeight = itemCount * itemSize;
const offset = itemsHeight < Number(height) ? 0 : scrollOffset;
setTimeout(() => listRef.current?.scrollTo(offset), 0);
}
};
const collapse = (node: number) => {
const descendantIds = descendants(nodes[node]).map((des) => des.id);
const ancestorIds = ancestors(nodes[node]).map((anc) => anc.id);
setExpandedNodes(
difference(expandedNodes, [...descendantIds, nodes[node].id])
);
// remove children
const newNodes = filter(nodes, (n) => !includes(descendantIds, n.id));
preserveScrollOffset(newNodes.length);
setDeepExpandedNodes(
difference(deepExpandedNodes, [
...ancestorIds,
...descendantIds,
nodes[node].id,
])
);
};
const expand = (node: number) => {
setExpandedNodes(concat(expandedNodes, nodes[node].id));
// add children
const newNodes = nodes.slice();
newNodes.splice(node + 1, 0, ...descendants(nodes[node], 1));
preserveScrollOffset(newNodes.length);
const expand = (node: number, deep = false) => {
if (deep) {
setExpandedNodes(
union(expandedNodes, [
nodes[node].id,
...expandableDescendantIds(nodes[node]),
])
);
setDeepExpandedNodes(union(deepExpandedNodes, [nodes[node].id]));
} else {
setExpandedNodes(concat(expandedNodes, nodes[node].id));
}
};
// Expand descendants of alt-clicked nodes that load after the click.
React.useEffect(() => {
if (!deepExpandedNodes.length) {
return;
}
const ids = flatten(items.map(flattenTree))
.filter((item) => deepExpandedNodes.includes(item.id))
.flatMap(expandableDescendantIds);
setExpandedNodes((prev) => {
const missing = difference(ids, prev);
return missing.length ? concat(prev, missing) : prev;
});
}, [items, deepExpandedNodes]);
React.useEffect(() => {
collections.orderedData
.filter(
@@ -238,14 +253,14 @@ function DocumentExplorer({
nodes[node].children.length > 0 ||
(showDocuments !== false && nodes[node].type === "collection");
const toggleCollapse = (node: number) => {
const toggleCollapse = (node: number, deep = false) => {
if (!hasChildren(node)) {
return;
}
if (isExpanded(node)) {
collapse(node);
} else {
expand(node);
expand(node, deep);
}
};
@@ -265,15 +280,7 @@ function DocumentExplorer({
};
const ListItem = observer(
({
index,
data,
style,
}: {
index: number;
data: NavigationNode[];
style: React.CSSProperties;
}) => {
({ index, data, style }: RowComponentProps<RowProps>) => {
const node = data[index];
const isCollection = node.type === "collection";
let renderedIcon,
@@ -309,15 +316,17 @@ function DocumentExplorer({
.join(" / ");
}
renderedIcon = renderIcon?.(node) ?? renderedIcon;
return deferredSearchTerm ? (
<DocumentExplorerSearchResult
selected={isSelected(index)}
active={activeNode === index}
style={{
...style,
top: (style.top as number) + VERTICAL_PADDING,
left: (style.left as number) + HORIZONTAL_PADDING,
width: `calc(${style.width} - ${HORIZONTAL_PADDING * 2}px)`,
top: VERTICAL_PADDING,
left: HORIZONTAL_PADDING,
width: `calc(100% - ${HORIZONTAL_PADDING * 2}px)`,
}}
onPointerMove={() => setActiveNode(index)}
onClick={() => selectNode(nodes[index])}
@@ -330,16 +339,16 @@ function DocumentExplorer({
<DocumentExplorerNode
style={{
...style,
top: (style.top as number) + VERTICAL_PADDING,
left: (style.left as number) + HORIZONTAL_PADDING,
width: `calc(${style.width} - ${HORIZONTAL_PADDING * 2}px)`,
top: VERTICAL_PADDING,
left: HORIZONTAL_PADDING,
width: `calc(100% - ${HORIZONTAL_PADDING * 2}px)`,
}}
onPointerMove={() => setActiveNode(index)}
onClick={() => selectNode(nodes[index])}
onDoubleClick={() => submitNode(index)}
onDisclosureClick={(ev) => {
ev.stopPropagation();
toggleCollapse(index);
toggleCollapse(index, ev.altKey);
}}
selected={isSelected(index)}
active={activeNode === index}
@@ -421,24 +430,15 @@ function DocumentExplorer({
/>
<ListContainer>
{nodes.length ? (
<AutoSizer>
{({ width, height }: { width: number; height: number }) => (
<Flex role="listbox" column>
<List
ref={listRef}
width={width}
height={height}
itemData={nodes}
itemCount={nodes.length}
itemSize={isMobile ? 48 : 32}
innerElementType={innerElementType}
itemKey={(index, results) => results[index].id}
>
{ListItem}
</List>
</Flex>
)}
</AutoSizer>
<StyledList
role="listbox"
listRef={listRef}
rowCount={nodes.length}
rowHeight={isMobile ? 48 : 32}
rowComponent={ListItem}
rowProps={{ data: nodes }}
rowKey={rowKey}
/>
) : (
<FlexContainer>
<Text as="p" type="secondary">
@@ -465,6 +465,11 @@ const ListSearch = styled(InputSearch).attrs({ round: true })`
padding-right: 24px;
`;
// Rows are offset by the top padding, so the bottom needs room for both.
const StyledList = styled(List<RowProps>)`
padding-bottom: ${VERTICAL_PADDING * 2}px;
`;
const ListContainer = styled.div`
height: 65vh;
@@ -1,8 +1,9 @@
import { observer } from "mobx-react";
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 { breakpoint } from "@shared/styles/breakpoint";
import { s, ellipsis } from "@shared/styles";
import Flex from "~/components/Flex";
import Disclosure from "~/components/Sidebar/components/Disclosure";
@@ -79,10 +80,15 @@ function DocumentExplorerNode({
</Spacer>
{icon}
<Title>{title || t("Untitled")}</Title>
{selected && <SelectedIcon aria-hidden />}
</Node>
);
}
export const SelectedIcon = styled(CheckmarkIcon)`
margin-left: auto;
`;
const Title = styled(Text)`
${ellipsis()}
margin: 0 4px 0 4px;
@@ -3,7 +3,7 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { ellipsis } from "@shared/styles";
import { Node as SearchResult } from "./DocumentExplorerNode";
import { Node as SearchResult, SelectedIcon } from "./DocumentExplorerNode";
import Flex from "~/components/Flex";
import Text from "~/components/Text";
@@ -51,6 +51,7 @@ function DocumentExplorerSearchResult({
{path}
</Path>
</Flex>
{selected && <SelectedIcon aria-hidden />}
</SearchResult>
);
}
@@ -1,9 +1,10 @@
import { observer } from "mobx-react";
import { useState, useMemo } from "react";
import { useEffect, useState, useMemo } from "react";
import { useTranslation, Trans } from "react-i18next";
import { toast } from "sonner";
import type { NavigationNode } from "@shared/types";
import { descendants, flattenTree } from "@shared/utils/tree";
import { ancestors, descendants, flattenTree } from "@shared/utils/tree";
import { performBatch } from "~/actions/definitions/common";
import type Document from "~/models/Document";
import Button from "~/components/Button";
import Text from "~/components/Text";
@@ -13,39 +14,74 @@ import { FlexContainer, Footer } from "./Components";
import DocumentExplorer from "./DocumentExplorer";
type Props = {
document: Document;
/** The documents to move. */
documents: Document[];
};
function DocumentMove({ document }: Props) {
const { dialogs, policies } = useStores();
function DocumentMove({ documents }: Props) {
const { collections, dialogs, policies } = useStores();
const { t } = useTranslation();
const collectionTrees = useCollectionTrees();
const [moving, setMoving] = useState<boolean>(false);
const [selectedPath, selectPath] = useState<NavigationNode | null>(null);
const [treesFailed, setTreesFailed] = useState<boolean>(false);
const items = useMemo(() => {
// Collect the IDs of the document itself and all of its descendants so they
// can be excluded from the move targets (moving to self or a descendant
// would create a cycle; moving to the exact same location is a no-op).
const sourceCollectionIds = useMemo(
() =>
Array.from(
new Set(
documents
.map((document) => document.collectionId)
.filter((id): id is string => !!id)
)
),
[documents]
);
// The source trees are needed to exclude descendants and to keep nesting,
// so load any that have not been loaded yet.
useEffect(() => {
Promise.all(
sourceCollectionIds
.map((id) => collections.get(id))
.filter((collection) => !!collection)
.map((collection) => collection.fetchDocuments())
).catch(() => setTreesFailed(true));
}, [collections, sourceCollectionIds]);
const isLoadingTrees =
!treesFailed &&
sourceCollectionIds.some((id) => {
const collection = collections.get(id);
return !!collection && !collection.documents;
});
const { items, movableDocuments } = useMemo(() => {
const selectedIds = new Set(documents.map((document) => document.id));
const allNodes = collectionTrees.flatMap(flattenTree);
const sourceNode = allNodes.find((node) => node.id === document.id);
const excludedIds = new Set<string>([document.id]);
if (sourceNode) {
descendants(sourceNode).forEach((n) => excludedIds.add(n.id));
const nodesById = new Map(allNodes.map((node) => [node.id, node]));
// Exclude the documents and all of their descendants from the move targets
// (moving to self or a descendant would create a cycle).
const excludedIds = new Set(selectedIds);
for (const id of selectedIds) {
const sourceNode = nodesById.get(id);
if (sourceNode) {
descendants(sourceNode).forEach((n) => excludedIds.add(n.id));
}
}
// Recursively filter out the document itself and its descendants.
// The document's current parent is intentionally kept so that siblings
// remain visible as valid move targets.
const filterSourceDocument = (node: NavigationNode): NavigationNode => ({
// Recursively filter out the documents and their descendants. The current
// parents are intentionally kept so that siblings remain valid targets.
const filterSourceDocuments = (node: NavigationNode): NavigationNode => ({
...node,
children: node.children
?.filter((c) => !excludedIds.has(c.id))
.map(filterSourceDocument),
.map(filterSourceDocuments),
});
const nodes = collectionTrees
.map(filterSourceDocument)
.map(filterSourceDocuments)
// Filter out collections that we don't have permission to create documents in.
.filter((node) =>
node.collectionId
@@ -53,10 +89,29 @@ function DocumentMove({ document }: Props) {
: true
);
return nodes;
}, [policies, collectionTrees, document.id]);
// Documents nested under another selected document move along with it,
// so only the outermost documents are moved to keep the structure. They
// are moved in tree order to keep their relative order at the destination.
const positions = new Map(allNodes.map((node, index) => [node.id, index]));
const movable = documents
.filter(
(document) =>
!ancestors(nodesById.get(document.id)).some((node) =>
selectedIds.has(node.id)
)
)
.sort(
(a, b) =>
(positions.get(a.id) ?? Infinity) - (positions.get(b.id) ?? Infinity)
);
return { items: nodes, movableDocuments: movable };
}, [policies, collectionTrees, documents]);
const move = async (path = selectedPath) => {
if (isLoadingTrees) {
return;
}
if (!path) {
toast.message(t("Select a location to move"));
return;
@@ -67,18 +122,28 @@ function DocumentMove({ document }: Props) {
const { type, id: parentDocumentId } = path;
const collectionId = path.collectionId as string;
const options =
type === "document"
? { collectionId, parentDocumentId }
: { collectionId };
if (type === "document") {
await document.move({ collectionId, parentDocumentId });
if (movableDocuments.length === 1) {
await movableDocuments[0].move(options);
toast.success(t("Document moved"));
} else {
await document.move({ collectionId });
const succeeded = await performBatch(movableDocuments, (document) =>
document.move(options)
);
if (!succeeded) {
toast.error(t("Couldn’t move the document. Try again?"));
return;
}
toast.success(t("{{ count }} document moved", { count: succeeded }));
}
toast.success(t("Document moved"));
dialogs.closeAllModals();
} catch (_err) {
toast.error(t("Couldn’t move the document, try again?"));
toast.error(t("Couldn’t move the document. Try again?"));
} finally {
setMoving(false);
}
@@ -103,7 +168,10 @@ function DocumentMove({ document }: Props) {
t("Select a location to move")
)}
</Text>
<Button disabled={!selectedPath || moving} onClick={() => move()}>
<Button
disabled={!selectedPath || moving || isLoadingTrees}
onClick={() => move()}
>
{moving ? `${t("Moving")}…` : t("Move")}
</Button>
</Footer>
@@ -47,7 +47,7 @@ function TemplateMove({ template }: Props) {
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 -6
View File
@@ -3,9 +3,9 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import { mergeRefs } from "react-merge-refs";
import { Link } from "react-router-dom";
import { CheckmarkIcon, DocumentIcon } from "outline-icons";
import { CheckmarkIcon } from "outline-icons";
import styled, { css, useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { breakpoint } from "@shared/styles/breakpoint";
import EventBoundary from "@shared/components/EventBoundary";
import Icon from "@shared/components/Icon";
import { s, hover } from "@shared/styles";
@@ -32,6 +32,7 @@ import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction";
import { ContextMenu } from "./Menu/ContextMenu";
import { useDocumentActiveModels } from "~/hooks/useDocumentActiveModels";
import { useRovingTabIndex } from "~/hooks/useRovingTabIndex";
import { DocumentIcon } from "~/components/Icons/DocumentIcon";
type Props = {
document: Document;
@@ -170,7 +171,7 @@ function DocumentListItem(props: Props) {
pathname: documentPath(document),
search: highlight ? `?q=${encodeURIComponent(highlight)}` : undefined,
state: {
title: document.titleWithDefault,
title: document.displayTitle,
sidebarContext,
},
}}
@@ -204,7 +205,7 @@ function DocumentListItem(props: Props) {
/>
) : (
<DocumentIcon
outline={document.isDraft}
empty={document.isEmpty}
color={theme.textSecondary}
/>
)}
@@ -213,7 +214,7 @@ function DocumentListItem(props: Props) {
<Content>
<Heading dir={document.dir}>
<Title
text={document.titleWithDefault}
text={document.displayTitle}
highlight={highlight}
dir={document.dir}
/>
@@ -223,7 +224,7 @@ function DocumentListItem(props: Props) {
{document.isDraft &&
showDraft &&
(isInteractive ? (
<Tooltip content={t("Only visible to you")} placement="top">
<Tooltip content={t("Only visible to you")}>
<Badge>{t("Draft")}</Badge>
</Tooltip>
) : (
+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>
) : (
@@ -2,6 +2,7 @@ import { observer } from "mobx-react";
import {
archiveDocument,
deleteDocument,
moveDocument,
pinDocumentToCollection,
restoreDocument,
starDocument,
@@ -25,6 +26,7 @@ const toolbarActions: Action[] = [
unstarDocument,
pinDocumentToCollection,
unpinDocument,
moveDocument,
archiveDocument,
unpublishDocument,
restoreDocument,
@@ -0,0 +1,351 @@
import {
DndContext,
PointerSensor,
useDraggable,
useSensor,
useSensors,
type Announcements,
} from "@dnd-kit/core";
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
type RefObject,
} from "react";
import { useTranslation } from "react-i18next";
import {
DragDropManager,
type DragSource,
type Point,
} from "./DragDropManager";
import { DragDropManagerContext } from "./hooks";
interface Props {
children: ReactNode;
}
/**
* Provides drag and drop to the hooks in this module. dnd-kit detects and
* tracks the drag; the manager resolves the drop targets under the pointer.
*/
export function DragAndDropProvider({ children }: Props) {
const { t } = useTranslation();
const [manager] = useState(() => new DragDropManager());
const activatorRef = useRef<Activator | null>(null);
const pendingRef = useRef<{ source: DragSource; pointer: Point } | null>(
null
);
const sessionRef = useRef<(() => void) | null>(null);
const titleRef = useRef("");
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 5,
},
})
);
// A single dnd-kit draggable is moved to the source under the pointer, so
// that dnd-kit context changes do not re-render every source. DndContext
// does not wrap the children, as its context changes on every move.
useEffect(() => {
const handlePointerDown = (event: PointerEvent) => {
// Touch gestures scroll the sidebar and swipe it closed instead.
if (
event.pointerType === "touch" ||
!(event.target instanceof Element) ||
event.target.closest(EDITABLE_SELECTOR)
) {
return;
}
const found = manager.findSource(event.target);
if (!found || !activatorRef.current) {
return;
}
pendingRef.current = {
source: found.source,
pointer: { x: event.clientX, y: event.clientY },
};
activatorRef.current(found.node, event);
};
// Runs before the sensor, so the move that starts a drag is included.
const handlePendingMove = (event: PointerEvent) => {
if (pendingRef.current) {
pendingRef.current.pointer = { x: event.clientX, y: event.clientY };
}
};
document.addEventListener("pointerdown", handlePointerDown);
window.addEventListener("pointermove", handlePendingMove, {
capture: true,
passive: true,
});
return () => {
document.removeEventListener("pointerdown", handlePointerDown);
window.removeEventListener("pointermove", handlePendingMove, {
capture: true,
});
};
}, [manager]);
const handleDragStart = useCallback(() => {
const pending = pendingRef.current;
pendingRef.current = null;
if (!pending) {
return;
}
manager.beginDrag(pending.source);
titleRef.current = manager.layerMonitor.getItem()?.title ?? "";
sessionRef.current = startDragSession(manager, pending.pointer);
}, [manager]);
const endSession = useCallback(() => {
sessionRef.current?.();
sessionRef.current = null;
}, []);
const handleDragEnd = useCallback(() => {
endSession();
manager.drop();
}, [manager, endSession]);
const handleDragCancel = useCallback(() => {
endSession();
manager.endDrag();
}, [manager, endSession]);
const handleDragAbort = useCallback(() => {
pendingRef.current = null;
}, []);
useEffect(() => handleDragCancel, [handleDragCancel]);
const accessibility = useMemo(() => {
const announcements: Announcements = {
onDragStart: () =>
t("Picked up {{ title }}", { title: titleRef.current }),
onDragOver: () => undefined,
onDragEnd: () => t("Dropped {{ title }}", { title: titleRef.current }),
onDragCancel: () =>
t("Canceled dragging {{ title }}", { title: titleRef.current }),
};
return {
announcements,
screenReaderInstructions: { draggable: "" },
};
}, [t]);
return (
<DragDropManagerContext.Provider value={manager}>
<DndContext
sensors={sensors}
autoScroll={false}
accessibility={accessibility}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onDragCancel={handleDragCancel}
onDragAbort={handleDragAbort}
>
<DragActivator activatorRef={activatorRef} />
</DndContext>
{children}
</DragDropManagerContext.Provider>
);
}
type Activator = (node: HTMLElement, event: PointerEvent) => void;
const DRAGGABLE_ID = "drag-source";
// Drags must not start from controls where the pointer selects text.
const EDITABLE_SELECTOR =
"input, textarea, select, [contenteditable='true'], [role='textbox']";
const POINTER_EVENTS = ["pointermove", "pointerup"];
// Mouse hover and move handlers do not run during a drag, as with a native
// drag. The drag itself is tracked with pointer events.
const MOUSE_EVENTS = [
"pointerover",
"pointerout",
"mouseover",
"mouseout",
"mousemove",
];
// Distance from the edge of a scroll container where dragging scrolls it.
const SCROLL_EDGE = 48;
// Scroll distance of one wheel line.
const LINE_HEIGHT = 16;
// Maximum scroll distance per frame.
const SCROLL_SPEED = 14;
/**
* Hosts the dnd-kit draggable and exposes a function that starts the dnd-kit
* sensor for a source element.
*/
function DragActivator({
activatorRef,
}: {
activatorRef: RefObject<Activator | null>;
}) {
const { setNodeRef, listeners } = useDraggable({ id: DRAGGABLE_ID });
useEffect(() => {
activatorRef.current = (node, event) => {
setNodeRef(node);
listeners?.onPointerDown?.({ nativeEvent: event });
};
return () => {
activatorRef.current = null;
};
}, [activatorRef, listeners, setNodeRef]);
return null;
}
/**
* Tracks the pointer during a drag, updates the hovered targets, scrolls the
* container under the pointer near its edges, blocks hover styles and
* handlers, and swallows the click that follows the drop.
*
* @param manager The drag and drop manager.
* @param initialPointer The pointer position where the drag started.
* @returns a function that ends the session.
*/
function startDragSession(
manager: DragDropManager,
initialPointer: Point
): () => void {
let pointer = initialPointer;
let hovered: Element | null = null;
let scroller: HTMLElement | null = null;
let scrollerRect: DOMRect | undefined;
let frame = 0;
// A transparent layer takes the pointer so that no element shows a hover
// style, as with a native drag. Hit testing looks through it.
const overlay = document.createElement("div");
overlay.style.cssText =
"position: fixed; inset: 0; z-index: 2147483647; cursor: grabbing;";
document.body.appendChild(overlay);
const update = () => {
const element =
document
.elementsFromPoint(pointer.x, pointer.y)
.find((el) => el !== overlay) ?? null;
if (element !== hovered) {
hovered = element;
scroller = getScrollContainer(element);
scrollerRect = scroller?.getBoundingClientRect();
}
manager.hover(element, pointer);
};
const handlePointerMove = (event: PointerEvent) => {
pointer = { x: event.clientX, y: event.clientY };
update();
};
const handleClick = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
};
const stopPropagation = (event: Event) => event.stopPropagation();
const handleWheel = (event: WheelEvent) => {
if (!scroller) {
return;
}
event.preventDefault();
scroller.scrollTop +=
event.deltaMode === WheelEvent.DOM_DELTA_LINE
? event.deltaY * LINE_HEIGHT
: event.deltaY;
};
const scroll = () => {
frame = requestAnimationFrame(scroll);
if (!scroller || !scrollerRect) {
return;
}
const speed =
getScrollSpeed(scrollerRect.bottom - pointer.y) -
getScrollSpeed(pointer.y - scrollerRect.top);
if (speed) {
scroller.scrollTop += speed;
}
};
// The release position is checked too, before the sensor ends the drag.
for (const type of POINTER_EVENTS) {
window.addEventListener(type, handlePointerMove, {
capture: true,
passive: true,
});
}
window.addEventListener("scroll", update, { capture: true, passive: true });
window.addEventListener("click", handleClick, { capture: true });
for (const type of MOUSE_EVENTS) {
window.addEventListener(type, stopPropagation, { capture: true });
}
overlay.addEventListener("wheel", handleWheel, { passive: false });
update();
frame = requestAnimationFrame(scroll);
return () => {
for (const type of POINTER_EVENTS) {
window.removeEventListener(type, handlePointerMove, { capture: true });
}
window.removeEventListener("scroll", update, { capture: true });
for (const type of MOUSE_EVENTS) {
window.removeEventListener(type, stopPropagation, { capture: true });
}
cancelAnimationFrame(frame);
overlay.remove();
setTimeout(
() => window.removeEventListener("click", handleClick, { capture: true }),
50
);
};
}
/**
* Returns the nearest ancestor of the element that scrolls vertically.
*
* @param element The element to start from.
* @returns the scroll container, or null if there is none.
*/
function getScrollContainer(element: Element | null): HTMLElement | null {
let current = element;
while (current && current !== document.body) {
if (
current instanceof HTMLElement &&
current.scrollHeight > current.clientHeight &&
/(auto|scroll|overlay)/.test(getComputedStyle(current).overflowY)
) {
return current;
}
current = current.parentElement;
}
return null;
}
/**
* Returns the scroll distance for one frame.
*
* @param distance The distance from the pointer to the edge of the container.
* @returns the scroll distance, 0 when the pointer is not near the edge.
*/
function getScrollSpeed(distance: number): number {
return SCROLL_SPEED * Math.max(0, 1 - Math.max(distance, 0) / SCROLL_EDGE);
}
@@ -0,0 +1,334 @@
import type { ReactNode } from "react";
import shallowEqual from "@shared/utils/shallowEqual";
/** A position in viewport coordinates. */
export interface Point {
x: number;
y: number;
}
/** The data carried by a drag operation. */
export interface DragItem {
/** The id of the dragged model. */
id: string;
/** The title shown in the drag preview. */
title?: string;
/** The icon shown in the drag preview. */
icon?: ReactNode;
/** Whether the dragged model is a draft. */
isDraft?: boolean;
}
/** Reads the drag state for a drop target. */
export interface DropTargetMonitor {
/**
* Whether the pointer is over this target. With `shallow`, only when no
* nested target that accepts the item is between them.
*/
isOver(options?: { shallow?: boolean }): boolean;
/** Whether the dragged item can be dropped on this target. */
canDrop(): boolean;
/** Whether a nested target has already handled the current drop. */
didDrop(): boolean;
/** The type of the dragged item, or null when nothing is dragged. */
getItemType(): string | null;
}
/** Reads the global drag state. */
export interface DragLayerMonitor {
/** Whether an item is being dragged. */
isDragging(): boolean;
/** The dragged item, or null when nothing is dragged. */
getItem(): DragItem | null;
/** The pointer position, or null when nothing is dragged. */
getClientOffset(): Point | null;
}
/** Describes an element that can be dragged. */
export interface DragSourceSpec<Item extends DragItem> {
/** The type of the dragged item, matched against a target's `accept`. */
type: string;
/** Returns the item that drop targets receive. */
item(): Item;
/** Whether the source can be dragged now. */
canDrag?(): boolean;
}
/** Describes an element that dragged items can be dropped on. */
export interface DropTargetSpec<Item extends DragItem> {
/** The item types that the target accepts. */
accept: string | string[];
/** Whether the item can be dropped on the target. */
canDrop?(item: Item, monitor: DropTargetMonitor): boolean;
/** Called while an accepted item is over the target. */
hover?(item: Item, monitor: DropTargetMonitor): void;
/** Called when the item is dropped on the target. */
drop?(item: Item, monitor: DropTargetMonitor): unknown;
}
/** A registered drag source. */
export interface DragSource {
/** Returns the latest source specification. */
getSpec(): DragSourceSpec<DragItem>;
}
/** A registered drop target. */
export interface DropTarget {
/** Returns the latest target specification. */
getSpec(): DropTargetSpec<DragItem>;
}
interface DragOperation {
source: DragSource;
type: string;
item: DragItem;
}
const EMPTY_TARGETS: DropTarget[] = [];
/**
* Holds the connected drag sources and drop targets, and the state of the
* current drag operation. Nested drop targets are resolved from the DOM: all
* connected targets that contain the element under the pointer are hovered,
* and a drop is offered to each of them from the innermost outwards.
*/
export class DragDropManager {
/** A monitor for the global drag state. */
public readonly layerMonitor: DragLayerMonitor = {
isDragging: () => !!this.operation,
getItem: () => this.operation?.item ?? null,
getClientOffset: () => this.pointer,
};
/**
* Subscribes to changes in the drag operation and the hovered targets.
*
* @param listener Called after each change.
* @returns a function that removes the listener.
*/
public subscribe = (listener: () => void) => {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
};
/**
* Subscribes to changes in the pointer position.
*
* @param listener Called after each change.
* @returns a function that removes the listener.
*/
public subscribeToPointer = (listener: () => void) => {
this.pointerListeners.add(listener);
return () => {
this.pointerListeners.delete(listener);
};
};
/**
* Connects a drag source to its DOM element.
*
* @param node The element.
* @param source The source.
* @returns a function that disconnects the source.
*/
public connectSource(node: HTMLElement, source: DragSource): () => void {
this.sources.set(node, source);
return () => {
if (this.sources.get(node) === source) {
this.sources.delete(node);
}
};
}
/**
* Connects a drop target to its DOM element.
*
* @param node The element.
* @param target The target.
* @returns a function that disconnects the target.
*/
public connectTarget(node: Element, target: DropTarget): () => void {
const targets = this.targets.get(node) ?? new Set<DropTarget>();
targets.add(target);
this.targets.set(node, targets);
return () => {
targets.delete(target);
if (this.hovered.includes(target)) {
this.hovered = this.hovered.filter((t) => t !== target);
this.emit();
}
};
}
/**
* Returns the nearest source connected to the element or one of its
* ancestors that can be dragged now.
*
* @param element The element where the drag starts.
* @returns the source and its element, or undefined if none can be dragged.
*/
public findSource(
element: Element
): { source: DragSource; node: HTMLElement } | undefined {
for (let node: Element | null = element; node; node = node.parentElement) {
const source = this.sources.get(node);
if (
source &&
node instanceof HTMLElement &&
(source.getSpec().canDrag?.() ?? true)
) {
return { source, node };
}
}
return undefined;
}
/**
* Starts a drag operation.
*
* @param source The dragged source.
*/
public beginDrag(source: DragSource) {
const spec = source.getSpec();
this.operation = { source, type: spec.type, item: spec.item() };
this.hovered = EMPTY_TARGETS;
this.dropped = false;
this.emit();
}
/**
* Updates the pointer position and the hovered targets.
*
* @param element The element under the pointer.
* @param pointer The pointer position.
*/
public hover(element: Element | null, pointer: Point) {
const operation = this.operation;
if (!operation) {
return;
}
this.pointer = pointer;
this.pointerListeners.forEach((listener) => listener());
const hovered: DropTarget[] = [];
for (let node = element; node; node = node.parentElement) {
for (const target of this.targets.get(node) ?? EMPTY_TARGETS) {
if (accepts(target, operation.type)) {
hovered.push(target);
}
}
}
if (!shallowEqual(hovered, this.hovered)) {
this.hovered = hovered.length ? hovered : EMPTY_TARGETS;
this.emit();
}
for (const target of this.hovered) {
target.getSpec().hover?.(operation.item, this.getTargetMonitor(target));
}
}
/**
* Offers the dragged item to the hovered targets that can accept it, from
* the innermost outwards, then ends the drag.
*/
public drop() {
const operation = this.operation;
if (!operation) {
return;
}
try {
for (const target of this.hovered) {
if (this.canDrop(target)) {
const monitor = this.getTargetMonitor(target);
target.getSpec().drop?.(operation.item, monitor);
this.dropped = true;
}
}
} finally {
this.endDrag();
}
}
/** Ends the drag operation without a drop. */
public endDrag() {
if (!this.operation) {
return;
}
this.operation = null;
this.pointer = null;
this.hovered = EMPTY_TARGETS;
this.emit();
this.pointerListeners.forEach((listener) => listener());
}
/**
* Returns whether the source is being dragged.
*
* @param source The source.
* @returns true if the source is dragged.
*/
public isDragging(source: DragSource): boolean {
return this.operation?.source === source;
}
/**
* Returns a monitor for a drop target.
*
* @param target The target.
* @returns the monitor.
*/
public getTargetMonitor(target: DropTarget): DropTargetMonitor {
return {
isOver: (options) =>
options?.shallow
? this.hovered[0] === target
: this.hovered.includes(target),
canDrop: () => this.canDrop(target),
didDrop: () => this.dropped,
getItemType: () => this.operation?.type ?? null,
};
}
private canDrop(target: DropTarget): boolean {
const operation = this.operation;
if (!operation || !accepts(target, operation.type)) {
return false;
}
return (
target
.getSpec()
.canDrop?.(operation.item, this.getTargetMonitor(target)) ?? true
);
}
private emit() {
this.listeners.forEach((listener) => listener());
}
private operation: DragOperation | null = null;
private pointer: Point | null = null;
/** Hovered targets, from the innermost outwards. */
private hovered = EMPTY_TARGETS;
private dropped = false;
private sources = new WeakMap<Element, DragSource>();
private targets = new WeakMap<Element, Set<DropTarget>>();
private listeners = new Set<() => void>();
private pointerListeners = new Set<() => void>();
}
function accepts(target: DropTarget, type: string): boolean {
const { accept } = target.getSpec();
return Array.isArray(accept) ? accept.includes(type) : accept === type;
}
+183
View File
@@ -0,0 +1,183 @@
import {
createContext,
useCallback,
useContext,
useLayoutEffect,
useRef,
useState,
useSyncExternalStore,
type RefCallback,
} from "react";
import shallowEqual from "@shared/utils/shallowEqual";
import {
DragDropManager,
type DragItem,
type DragLayerMonitor,
type DragSource,
type DragSourceSpec,
type DropTarget,
type DropTargetMonitor,
type DropTargetSpec,
} from "./DragDropManager";
/** Options for a drop target, with a collector for the props it renders. */
export interface DropTargetHookSpec<
Item extends DragItem,
Collected extends object,
> extends DropTargetSpec<Item> {
/** Returns the props to render. The component re-renders when they change. */
collect(monitor: DropTargetMonitor): Collected;
}
/** Provides the drag and drop manager to the hooks. */
export const DragDropManagerContext = createContext<DragDropManager>(
new DragDropManager()
);
/**
* Makes an element draggable.
*
* @param spec The drag source specification.
* @returns a tuple of whether the element is being dragged and a ref callback for it.
*/
export function useDragRef<Item extends DragItem>(
spec: DragSourceSpec<Item>
): [boolean, RefCallback<HTMLElement>] {
const manager = useContext(DragDropManagerContext);
const specRef = useLatest(spec);
const [source] = useState<DragSource>(() => ({
getSpec: () => specRef.current,
}));
const ref = useCallback(
(node: HTMLElement | null) =>
node ? manager.connectSource(node, source) : undefined,
[manager, source]
);
const isDragging = useSyncExternalStore(manager.subscribe, () =>
manager.isDragging(source)
);
return [isDragging, ref];
}
/**
* Makes an element a drop target. Targets may be nested; a drop is offered to
* every hovered target that can accept it, from the innermost outwards.
*
* @param spec The drop target specification.
* @returns a tuple of the collected props and a ref callback for the element.
*/
export function useDropRef<Item extends DragItem, Collected extends object>(
spec: DropTargetHookSpec<Item, Collected>
): [Collected, RefCallback<HTMLElement>] {
const manager = useContext(DragDropManagerContext);
const specRef = useLatest(spec);
const [target] = useState<DropTarget>(() => ({
getSpec: () => specRef.current,
}));
const [monitor] = useState(() => manager.getTargetMonitor(target));
const ref = useCallback(
(node: HTMLElement | null) =>
node ? manager.connectTarget(node, target) : undefined,
[manager, target]
);
const collected = useCollected(manager.subscribe, () =>
spec.collect(monitor)
);
return [collected, ref];
}
/**
* Collects props from the global drag state.
*
* @param collect Returns the props to render. The component re-renders when they change.
* @returns the collected props.
*/
export function useDragLayer<Collected extends object>(
collect: (monitor: DragLayerMonitor) => Collected
): Collected {
const manager = useContext(DragDropManagerContext);
return useCollected(manager.subscribe, () => collect(manager.layerMonitor));
}
/**
* Returns a ref callback for an element that follows the pointer during a
* drag. The element is moved directly, without a render.
*
* @param offsetX The horizontal distance from the pointer.
* @param offsetY The vertical distance from the pointer.
* @returns a ref callback for the element.
*/
export function useDragFollower(
offsetX: number,
offsetY: number
): RefCallback<HTMLElement> {
const manager = useContext(DragDropManagerContext);
return useCallback(
(node: HTMLElement | null) => {
if (!node) {
return undefined;
}
const move = () => {
const pointer = manager.layerMonitor.getClientOffset();
if (pointer) {
node.style.transform = `translate(${pointer.x + offsetX}px, ${pointer.y + offsetY}px)`;
}
};
move();
return manager.subscribeToPointer(move);
},
[manager, offsetX, offsetY]
);
}
/**
* Returns a ref that always holds the latest value.
*
* @param value The value to hold.
* @returns the ref.
*/
function useLatest<T>(value: T): { readonly current: T } {
const ref = useRef(value);
useLayoutEffect(() => {
ref.current = value;
});
return ref;
}
/**
* Subscribes to a store and returns the collected value. The previous value is
* returned while the new one is shallowly equal, so the component only
* re-renders when a collected prop changes.
*
* @param subscribe Subscribes to changes in the store.
* @param collect Returns the collected value.
* @returns the collected value.
*/
function useCollected<T extends object>(
subscribe: (listener: () => void) => () => void,
collect: () => T
): T {
const cache = useRef<{ value: T } | null>(null);
const getSnapshot = () => {
const value = collect();
if (
cache.current &&
shallowEqual(Object.keys(cache.current.value), Object.keys(value)) &&
shallowEqual(Object.values(cache.current.value), Object.values(value))
) {
return cache.current.value;
}
cache.current = { value };
return value;
};
return useSyncExternalStore(subscribe, getSnapshot);
}
+3
View File
@@ -0,0 +1,3 @@
export { DragAndDropProvider } from "./DragAndDropProvider";
export { useDragFollower, useDragLayer, useDragRef, useDropRef } from "./hooks";
export type { Point } from "./DragDropManager";
+1 -65
View File
@@ -1,8 +1,6 @@
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";
@@ -31,30 +29,14 @@ export type Props = Optional<
};
function Editor({ ref, ...props }: Props & { ref?: React.Ref<SharedEditor> }) {
const {
id,
onChange,
onCreateCommentMark,
onDeleteCommentMark,
onFileUploadStart,
onFileUploadStop,
} = props;
const { id, onChange, onCreateCommentMark, onDeleteCommentMark } = props;
const { comments } = useStores();
const { shareId } = useShare();
const { t } = useTranslation();
const embeds = useEmbeds(!shareId);
const localRef = React.useRef<SharedEditor | null>(null);
const preferences = useCurrentUser({ rejectOnEmpty: false })?.preferences;
const previousCommentIds = React.useRef<string[] | undefined>(undefined);
// 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 handleUploadFile = React.useCallback(
async (
file: File | string,
@@ -80,49 +62,6 @@ function Editor({ ref, ...props }: Props & { ref?: React.Ref<SharedEditor> }) {
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]);
@@ -244,9 +183,6 @@ function Editor({ ref, ...props }: Props & { ref?: React.Ref<SharedEditor> }) {
{...props}
onClickLink={handleClickLink}
onChange={handleChange}
onFileUploadStart={handleFileUploadStart}
onFileUploadStop={handleFileUploadStop}
onFileUploadProgress={handleFileUploadProgress}
placeholder={props.placeholder || ""}
defaultValue={props.defaultValue || ""}
/>
-89
View File
@@ -1,89 +0,0 @@
import type { BackendFactory } from "dnd-core";
import { HTML5Backend } from "react-dnd-html5-backend";
/**
* react-dnd's HTML5 backend installs global drag listeners on `window` in both
* the capture and bubble phases. The bubble-phase `dragover` handler runs after
* ProseMirror's and, when react-dnd isn't tracking a drag, forces
* `dataTransfer.dropEffect = "none"` – which tells the browser the drop is
* disallowed and silently rejects images dragged into the editor.
*
* These handlers live on `window`, so a propagation-based guard can't stop
* react-dnd without also starving the editor of the event. Instead we wrap the
* backend and make all of its top-level handlers no-op for events that occur
* within the editor surface, leaving ProseMirror to handle them itself.
*/
const topHandlerNames = [
"handleTopDragStart",
"handleTopDragStartCapture",
"handleTopDragEnter",
"handleTopDragEnterCapture",
"handleTopDragLeaveCapture",
"handleTopDragOver",
"handleTopDragOverCapture",
"handleTopDrop",
"handleTopDropCapture",
"handleTopDragEndCapture",
] as const;
const isWithinEditor = (target: EventTarget | null): boolean =>
target instanceof Element && Boolean(target.closest(".ProseMirror"));
// A file dragged over an element marked `data-drop-area`, which accepts native
// file drops itself. react-dnd never tracks these drags, so its handlers would
// otherwise reject them.
const isFileOverDropArea = (event: DragEvent): boolean =>
Boolean(event.dataTransfer?.types.includes("Files")) &&
event.target instanceof Element &&
Boolean(event.target.closest("[data-drop-area]"));
/**
* An HTML5 drag-and-drop backend that ignores drag events originating within the
* rich text editor so that ProseMirror can handle them itself.
*
* @param manager The drag-and-drop manager.
* @param context The global context.
* @param options Backend options.
* @returns The wrapped HTML5 backend instance.
*/
export const EditorAwareHTML5Backend: BackendFactory = (
manager,
context,
options
) => {
const backend = HTML5Backend(manager, context, options);
const monitor = manager.getMonitor();
// The top-level handlers are private instance fields on the backend, so reach
// for them through an index signature view of the instance.
const handlers = backend as unknown as Record<
string,
(event: DragEvent) => void
>;
for (const name of topHandlerNames) {
const original = handlers[name];
if (typeof original === "function") {
handlers[name] = (event: DragEvent) => {
if (isWithinEditor(event.target) || isFileOverDropArea(event)) {
return;
}
// A drag that began or entered the page over the editor is never
// registered with react-dnd because those events are skipped above.
// The backend's drop handlers assume a registered drag and may call
// `actions.hover` unconditionally, which throws "Cannot call hover
// while not dragging" – so drops without a tracked drag must be
// ignored here.
if (
(name === "handleTopDrop" || name === "handleTopDropCapture") &&
!monitor.isDragging()
) {
return;
}
original.call(backend, event);
};
}
}
return backend;
};
+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
}
+5 -5
View File
@@ -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>
</>
)}
@@ -177,14 +177,14 @@ class ErrorBoundaryClass extends React.Component<Props> {
{this.isRepeatedError ? (
<Text as="p" type="secondary">
<Trans>
An error has occurred multiple times recently. If it continues
An error has occurred multiple times recently. If it continues,
please try clearing the cache or using a different browser.
</Trans>
</Text>
) : (
<Text as="p" type="secondary">
<Trans
defaults="Sorry, an unrecoverable error occurred{{notified}}. Please try reloading the page, it may have been a temporary glitch."
defaults="Sorry, an unrecoverable error occurred{{notified}}. Please try reloading the page – it may have been a temporary glitch."
values={{
notified: isReported
? ` – ${t("our engineers have been notified")}`
+119
View File
@@ -0,0 +1,119 @@
import { format as formatDate } from "date-fns";
import { CloseIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled, { useTheme } from "styled-components";
import { Calendar } from "@shared/components/Calendar";
import { dateLocale } from "@shared/utils/date";
import Button from "~/components/Button";
import ButtonSmall from "~/components/ButtonSmall";
import NudeButton from "~/components/NudeButton";
import Tooltip from "~/components/Tooltip";
import {
Popover,
PopoverTrigger,
PopoverContent,
} from "~/components/primitives/Popover";
import useUserLocale from "~/hooks/useUserLocale";
type Props = {
selectedDate?: Date;
onSelect: (date: Date) => void;
/** Called to remove the date, shows a remove button when a date is selected. */
onClear?: () => void;
/** The text to display when no date is selected. */
placeholder?: string;
/** Whether to display a smaller input. */
small?: boolean;
/** Applied to the outer element. */
className?: string;
};
const ExpiryDatePicker = ({
selectedDate,
onSelect,
onClear,
placeholder,
small,
className,
}: Props) => {
const { t } = useTranslation();
const theme = useTheme();
const [open, setOpen] = React.useState(false);
const userLocale = useUserLocale();
const locale = dateLocale(userLocale);
const PickerButton = small ? SmallPickerButton : LargePickerButton;
const clearSize = small ? 18 : 24;
const handleSelect = React.useCallback(
(date: Date) => {
setOpen(false);
onSelect(date);
},
[onSelect]
);
return (
<Wrapper className={className}>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger>
<PickerButton neutral>
{selectedDate
? formatDate(selectedDate, "MMM dd, yyyy", { locale })
: (placeholder ?? t("Choose a date"))}
</PickerButton>
</PopoverTrigger>
<PopoverContent
aria-label={t("Choose a date")}
width={280}
side="right"
shrink
>
<Calendar
required
mode="single"
selected={selectedDate}
onSelect={handleSelect}
locale={locale}
disabled={{ before: new Date() }}
/>
</PopoverContent>
</Popover>
{selectedDate && onClear && (
<Tooltip content={t("Remove expiration")}>
<ClearButton
type="button"
onClick={onClear}
aria-label={t("Remove expiration")}
size={clearSize}
>
<CloseIcon color={theme.placeholder} size={clearSize} />
</ClearButton>
</Tooltip>
)}
</Wrapper>
);
};
const Wrapper = styled.div`
position: relative;
display: inline-flex;
`;
const ClearButton = styled(NudeButton)`
position: absolute;
top: 50%;
right: 4px;
transform: translateY(-50%);
`;
const LargePickerButton = styled(Button)`
width: 150px;
`;
const SmallPickerButton = styled(ButtonSmall)`
width: 130px;
`;
export default ExpiryDatePicker;
+3 -3
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
@@ -126,7 +126,7 @@ export const ExportDialog = observer(({ collection, onSubmit }: Props) => {
{t("Include attachments")}
</Text>
<Text size="small" type="secondary">
{t("Including uploaded images and files in the exported data")}.
{t("Include uploaded images and files in the exported data")}.
</Text>
</div>
</Option>
@@ -144,7 +144,7 @@ export const ExportDialog = observer(({ collection, onSubmit }: Props) => {
</Text>
<Text size="small" type="secondary">
{t(
"As an admin you can export collections you are not currently a member of"
"As an admin, you can export collections you are not currently a member of"
)}
.
</Text>
+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)})` }),
Loaded 100 of 1570 files, more files were not shown because too many files have changed in this diff. Show more