diff --git a/.claude/skills/verify-outline/SKILL.md b/.claude/skills/verify-outline/SKILL.md new file mode 100644 index 0000000000..2cef55ed85 --- /dev/null +++ b/.claude/skills/verify-outline/SKILL.md @@ -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/.`), 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//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--pg` (postgres:latest) and + `outline-verify--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:`, `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: (run-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 [--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//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= expect="" +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. diff --git a/.claude/skills/verify-outline/features/README.md b/.claude/skills/verify-outline/features/README.md new file mode 100644 index 0000000000..ce101c7a29 --- /dev/null +++ b/.claude/skills/verify-outline/features/README.md @@ -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. diff --git a/.claude/skills/verify-outline/features/collections.md b/.claude/skills/verify-outline/features/collections.md new file mode 100644 index 0000000000..49cc79e457 --- /dev/null +++ b/.claude/skills/verify-outline/features/collections.md @@ -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. diff --git a/.claude/skills/verify-outline/features/documents.md b/.claude/skills/verify-outline/features/documents.md new file mode 100644 index 0000000000..af023561d2 --- /dev/null +++ b/.claude/skills/verify-outline/features/documents.md @@ -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. diff --git a/.claude/skills/verify-outline/features/search.md b/.claude/skills/verify-outline/features/search.md new file mode 100644 index 0000000000..94b982d7ff --- /dev/null +++ b/.claude/skills/verify-outline/features/search.md @@ -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. diff --git a/.claude/skills/verify-outline/features/sharing.md b/.claude/skills/verify-outline/features/sharing.md new file mode 100644 index 0000000000..664794c81e --- /dev/null +++ b/.claude/skills/verify-outline/features/sharing.md @@ -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`). diff --git a/.claude/skills/verify-outline/features/workspace-setup.md b/.claude/skills/verify-outline/features/workspace-setup.md new file mode 100644 index 0000000000..d9ddd66229 --- /dev/null +++ b/.claude/skills/verify-outline/features/workspace-setup.md @@ -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. diff --git a/.claude/skills/verify-outline/journeys/create-collection.mjs b/.claude/skills/verify-outline/journeys/create-collection.mjs new file mode 100644 index 0000000000..14b050c8b7 --- /dev/null +++ b/.claude/skills/verify-outline/journeys/create-collection.mjs @@ -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() }; +}; diff --git a/.claude/skills/verify-outline/journeys/create-document.mjs b/.claude/skills/verify-outline/journeys/create-document.mjs new file mode 100644 index 0000000000..331ae665d2 --- /dev/null +++ b/.claude/skills/verify-outline/journeys/create-document.mjs @@ -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 }; +}; diff --git a/.claude/skills/verify-outline/journeys/search.mjs b/.claude/skills/verify-outline/journeys/search.mjs new file mode 100644 index 0000000000..a19bb1a1e9 --- /dev/null +++ b/.claude/skills/verify-outline/journeys/search.mjs @@ -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() }; +}; diff --git a/.claude/skills/verify-outline/journeys/setup-workspace.mjs b/.claude/skills/verify-outline/journeys/setup-workspace.mjs new file mode 100644 index 0000000000..1e9ec9f79b --- /dev/null +++ b/.claude/skills/verify-outline/journeys/setup-workspace.mjs @@ -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 }; +}; diff --git a/.claude/skills/verify-outline/journeys/share-public.mjs b/.claude/skills/verify-outline/journeys/share-public.mjs new file mode 100644 index 0000000000..d063bb6ed9 --- /dev/null +++ b/.claude/skills/verify-outline/journeys/share-public.mjs @@ -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(); + } +}; diff --git a/.claude/skills/verify-outline/scripts/drive.mjs b/.claude/skills/verify-outline/scripts/drive.mjs new file mode 100755 index 0000000000..25bf0d25d3 --- /dev/null +++ b/.claude/skills/verify-outline/scripts/drive.mjs @@ -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); +} diff --git a/.claude/skills/verify-outline/scripts/verify-outline.sh b/.claude/skills/verify-outline/scripts/verify-outline.sh new file mode 100755 index 0000000000..375380346c --- /dev/null +++ b/.claude/skills/verify-outline/scripts/verify-outline.sh @@ -0,0 +1,278 @@ +#!/usr/bin/env bash +# Launch, check and tear down an isolated Outline instance for verification. +# +# Usage: +# verify-outline.sh up [run-id] snapshot the checkout, build, migrate, start +# verify-outline.sh doctor <run-id> read-only health check of that instance +# verify-outline.sh info <run-id> print URL, ports and paths for that instance +# verify-outline.sh logs <run-id> [n] tail the server log +# verify-outline.sh psql <run-id> <sql> run read-only SQL against the instance DB +# verify-outline.sh down <run-id> stop and remove what `up` created, keep evidence +# verify-outline.sh list list runs and their containers +# +# Each run gets its own source snapshot, Postgres + Redis containers, free +# port and file storage. It never touches the developer's dev server, the +# docker-compose databases, or the repo's .env files. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO="${OUTLINE_REPO:-$(git rev-parse --show-toplevel 2>/dev/null || (cd "$SCRIPT_DIR/../../../.." && pwd))}" +ROOT="${OUTLINE_VERIFY_ROOT:-$HOME/.cache/outline-verify}" +PG_IMAGE="${OUTLINE_VERIFY_PG_IMAGE:-postgres:latest}" +REDIS_IMAGE="${OUTLINE_VERIFY_REDIS_IMAGE:-redis:latest}" + +die() { echo "error: $*" >&2; exit 1; } +log() { echo "[verify-outline] $*" >&2; } + +run_dir() { echo "$ROOT/runs/$1"; } +evidence_dir() { echo "$ROOT/evidence/$1"; } + +load_state() { + local id="${1:-}" + [[ -n "$id" ]] || die "run-id required (see: $0 list)" + local state + state="$(run_dir "$id")/state.env" + [[ -f "$state" ]] || die "no run '$id' at $state" + # shellcheck disable=SC1090 + source "$state" +} + +# Exec a command in the snapshot with only this instance's env. The repo's +# .env files are never read: they hold real S3 and OAuth credentials. The +# global rate limit is raised because every static asset of the production +# build counts against it; per-endpoint limits stay as in production. It +# replaces the current shell: call it as `(in_instance ...)` or with `&`. +in_instance() { + cd "$SRC" + exec env -i PATH="$PATH" HOME="$HOME" \ + NODE_ENV=production PORT="$PORT" URL="$URL" FORCE_HTTPS=false \ + DATABASE_URL="$DATABASE_URL" PGSSLMODE=disable REDIS_URL="$REDIS_URL" \ + SECRET_KEY="$SECRET_KEY" UTILS_SECRET="$UTILS_SECRET" \ + FILE_STORAGE=local FILE_STORAGE_LOCAL_ROOT_DIR="$RUN_DIR/storage" \ + WEB_CONCURRENCY=1 TELEMETRY=false LOG_LEVEL=info \ + RATE_LIMITER_REQUESTS=100000 \ + "$@" +} + +free_port() { + python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close()' +} + +cmd_up() { + local id="${1:-v$(date +%Y%m%d-%H%M%S)}" + [[ "$id" =~ ^[a-z0-9-]+$ ]] || die "run-id must match [a-z0-9-]+" + local dir src ev + dir="$(run_dir "$id")" + src="$dir/src" + ev="$(evidence_dir "$id")" + [[ -e "$dir/state.env" ]] && die "run '$id' already exists; use doctor, or down it first" + [[ -d "$REPO/node_modules" ]] || die "$REPO/node_modules missing; run yarn install there" + docker info >/dev/null 2>&1 || die "docker is not running (colima start?)" + mkdir -p "$dir/storage" "$ev" + + log "snapshot $REPO -> $src" + rsync -a --delete \ + --exclude node_modules --exclude /build --exclude /.git --exclude /data \ + --exclude '/.env*' --exclude /.claude --exclude /.cursor --exclude /.conductor \ + --exclude /server/config/certs --exclude '.DS_Store' \ + "$REPO/" "$src/" + ln -sfn "$REPO/node_modules" "$src/node_modules" + { + echo "repo: $REPO" + git -C "$REPO" rev-parse HEAD + git -C "$REPO" status --porcelain + } >"$dir/source.txt" 2>/dev/null || true + cp "$dir/source.txt" "$ev/source.txt" + + # A checkout whose package.json is ahead of or behind its node_modules builds + # with confusing resolver errors; fail fast instead. + local missing + missing="$(cd "$src" && node -e ' + const p = require("./package.json"); + const deps = Object.keys({ ...p.dependencies, ...p.devDependencies }); + const fs = require("fs"); + console.log(deps.filter((d) => !fs.existsSync(`node_modules/${d}/package.json`)).join(" ")); + ')" + [[ -z "$missing" ]] || { rm -rf "$dir"; die "node_modules in $REPO does not match its package.json (missing: $missing); run yarn install there or use a checkout that matches"; } + + # Write state before any container starts, so `down` can always clean up. + local pg="outline-verify-$id-pg" redis="outline-verify-$id-redis" port + port="$(free_port)" + cat >"$dir/state.env" <<EOF +RUN_ID=$id +RUN_DIR=$dir +SRC=$src +EVIDENCE=$ev +PORT=$port +URL=http://localhost:$port +PG_CONTAINER=$pg +REDIS_CONTAINER=$redis +SECRET_KEY=$(openssl rand -hex 32) +UTILS_SECRET=$(openssl rand -hex 32) +SERVER_LOG=$dir/server.log +PID_FILE=$dir/server.pid +EOF + + docker run -d --name "$pg" --label outline-verify="$id" \ + -e POSTGRES_USER=user -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=outline \ + -p 127.0.0.1::5432 "$PG_IMAGE" >/dev/null + docker run -d --name "$redis" --label outline-verify="$id" \ + -p 127.0.0.1::6379 "$REDIS_IMAGE" >/dev/null + log "started containers $pg, $redis" + local pg_port redis_port + pg_port="$(docker port "$pg" 5432/tcp | head -1 | sed 's/.*://')" + redis_port="$(docker port "$redis" 6379/tcp | head -1 | sed 's/.*://')" + cat >>"$dir/state.env" <<EOF +DATABASE_URL=postgres://user:pass@127.0.0.1:$pg_port/outline +REDIS_URL=redis://127.0.0.1:$redis_port +EOF + load_state "$id" + + # The postgres image runs its init scripts on a socket-only server, so a + # TCP query only succeeds once the real server is up. + log "waiting for postgres and redis" + local i + for i in $(seq 1 60); do + docker exec "$PG_CONTAINER" psql -h 127.0.0.1 -U user -d outline -tAc 'select 1' >/dev/null 2>&1 && break + [[ $i == 60 ]] && die "postgres not ready after 60s" + sleep 1 + done + for i in $(seq 1 30); do + docker exec "$REDIS_CONTAINER" redis-cli ping 2>/dev/null | grep -q PONG && break + [[ $i == 30 ]] && die "redis not ready after 30s" + sleep 1 + done + + log "building server (swc)" + (cd "$SRC" && node build.js) >"$RUN_DIR/build-server.log" 2>&1 || + die "server build failed, see $RUN_DIR/build-server.log" + log "building frontend (vite)" + (cd "$SRC" && NODE_ENV=production node_modules/.bin/vite build) \ + >"$RUN_DIR/build-app.log" 2>&1 || die "frontend build failed, see $RUN_DIR/build-app.log" + + log "migrating database" + (in_instance node_modules/.bin/sequelize db:migrate --env production-ssl-disabled) \ + >"$RUN_DIR/migrate.log" 2>&1 || die "migration failed, see $RUN_DIR/migrate.log" + + log "starting server on $URL" + in_instance nohup node build/server/index.js \ + --services=web,websockets,collaboration,worker,cron >"$SERVER_LOG" 2>&1 & + echo $! >"$PID_FILE" + + for i in $(seq 1 90); do + if ! kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then + tail -40 "$SERVER_LOG" >&2 + die "server exited during startup, see $SERVER_LOG" + fi + if [[ "$(curl -s -o /dev/null -w '%{http_code}' "$URL/_health")" == 200 ]] && + curl -s "$URL/" | grep -q '/static/assets/index\.'; then + log "READY $URL (run-id: $id)" + cmd_info "$id" + return 0 + fi + sleep 1 + done + die "server not ready after 90s, see $SERVER_LOG" +} + +cmd_doctor() { + load_state "$1" + local rc=0 pid tmp + pid="$(cat "$PID_FILE" 2>/dev/null || echo none)" + tmp="$(mktemp)" + check() { + if eval "$2" >/dev/null 2>&1; then echo "ok $1"; else echo "FAIL $1"; rc=1; fi + } + check "server pid $pid alive" "[[ $pid =~ ^[1-9][0-9]*$ ]] && kill -0 $pid" + check "port $PORT listened on by our process tree" \ + "lsof -nP -iTCP:$PORT -sTCP:LISTEN -t | grep -qxF \"\$(tree $pid)\"" + check "server cwd is snapshot" "lsof -a -p $pid -d cwd -Fn | grep -qx 'n$SRC'" + check "postgres container running" "[ \"\$(docker inspect -f '{{.State.Running}}' $PG_CONTAINER)\" = true ]" + check "redis container running" "[ \"\$(docker inspect -f '{{.State.Running}}' $REDIS_CONTAINER)\" = true ]" + check "GET /_health = 200 (db + redis)" "[ \"\$(curl -s -o /dev/null -w '%{http_code}' $URL/_health)\" = 200 ]" + check "GET / serves the built SPA" "curl -s $URL/ | grep -q '/static/assets/index\.'" + check "no pending migrations" \ + "(in_instance node_modules/.bin/sequelize db:migrate:status --env production-ssl-disabled) >$tmp && grep -q '^up ' $tmp && ! grep -q '^down ' $tmp" + rm -f "$tmp" + echo "info teams=$(cmd_psql "$1" 'select count(*) from teams' 2>/dev/null || echo '?') users=$(cmd_psql "$1" 'select count(*) from users' 2>/dev/null || echo '?') (teams=0: / shows workspace setup)" + if [[ "$(wc -l <"$RUN_DIR/source.txt")" -ge 2 ]]; then + echo "info snapshot: $(sed -n 2p "$RUN_DIR/source.txt") + $(($(wc -l <"$RUN_DIR/source.txt") - 2)) uncommitted paths from $(sed -n 1p "$RUN_DIR/source.txt" | cut -d' ' -f2)" + else + echo "info snapshot: $(sed -n 1p "$RUN_DIR/source.txt" | cut -d' ' -f2) (not a git checkout)" + fi + return $rc +} + +cmd_info() { + load_state "$1" + cat <<EOF +RUN_ID=$RUN_ID +URL=$URL +EVIDENCE=$EVIDENCE +SERVER_LOG=$SERVER_LOG +STORAGE=$RUN_DIR/storage +DATABASE_URL=$DATABASE_URL +PG_CONTAINER=$PG_CONTAINER +EOF +} + +cmd_logs() { + load_state "$1" + tail -n "${2:-100}" "$SERVER_LOG" +} + +cmd_psql() { + load_state "$1" + [[ -n "${2:-}" ]] || die "sql required" + docker exec "$PG_CONTAINER" psql -h 127.0.0.1 -U user -d outline -v ON_ERROR_STOP=1 \ + -c 'SET default_transaction_read_only = on' -tA -c "$2" | sed '/^SET$/d' +} + +# Print a pid and all of its descendants. +tree() { + local p + echo "$1" + for p in $(pgrep -P "$1" || true); do tree "$p"; done +} + +cmd_down() { + load_state "$1" + local pid pids + pid="$(cat "$PID_FILE" 2>/dev/null || true)" + if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then + # throng forks a worker; stop the tree we started, never by process name. + pids="$(tree "$pid" | tr '\n' ' ')" + kill $pids 2>/dev/null || true + for _ in $(seq 1 10); do kill -0 $pids 2>/dev/null || break; sleep 1; done + kill -9 $pids 2>/dev/null || true + log "stopped server pids $pids" + fi + if lsof -nP -iTCP:"$PORT" -sTCP:LISTEN >/dev/null 2>&1; then + log "WARNING: port $PORT still has a listener; inspect with lsof before killing anything" + fi + docker rm -f "$PG_CONTAINER" "$REDIS_CONTAINER" >/dev/null 2>&1 || true + log "removed containers" + mkdir -p "$EVIDENCE" + cp "$SERVER_LOG" "$EVIDENCE/server.log" 2>/dev/null || true + rm -rf "$RUN_DIR" + log "removed $RUN_DIR; evidence kept at $EVIDENCE" + ls -la "$EVIDENCE" +} + +cmd_list() { + echo "runs:" + ls -1 "$ROOT/runs" 2>/dev/null | sed 's/^/ /' || true + echo "containers:" + docker ps -a --filter label=outline-verify --format ' {{.Names}}\t{{.Status}}' +} + +case "${1:-}" in + up) cmd_up "${2:-}" ;; + doctor) cmd_doctor "${2:-}" ;; + info) cmd_info "${2:-}" ;; + logs) cmd_logs "${2:-}" "${3:-}" ;; + psql) cmd_psql "${2:-}" "${3:-}" ;; + down) cmd_down "${2:-}" ;; + list) cmd_list ;; + *) sed -n '2,13p' "$0"; exit 1 ;; +esac diff --git a/.github/actions/install/action.yml b/.github/actions/install/action.yml index 3cd311d501..c79ac0e04b 100644 --- a/.github/actions/install/action.yml +++ b/.github/actions/install/action.yml @@ -6,10 +6,10 @@ runs: - name: Enable Corepack shell: bash run: corepack enable - - name: Use Node.js 26.x + - name: Use a supported Node.js version uses: actions/setup-node@v5 with: - node-version: 26.x + node-version-file: package.json cache: "yarn" - name: Install dependencies shell: bash diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba95754024..83c88c620c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,8 +18,11 @@ env: jobs: changes: - runs-on: ubuntu-latest + # Blacksmith runners are only available to the outline organization, and are + # not used for pull requests from forks. + runs-on: ${{ (github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} outputs: + runner: ${{ (github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} code: ${{ steps.filter.outputs.code }} config: ${{ steps.filter.outputs.config }} server: ${{ steps.filter.outputs.server }} @@ -39,8 +42,8 @@ jobs: - '!shared/i18n/locales/**' config: - '.github/**' - - 'vite.config.ts' - - 'vitest.config.ts' + - 'vite.config.mts' + - 'vitest.config.mts' server: - 'server/**' - 'shared/**' @@ -60,7 +63,7 @@ jobs: lint: needs: changes if: ${{ needs.changes.outputs.code == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install @@ -79,16 +82,17 @@ jobs: types: needs: changes if: ${{ needs.changes.outputs.code == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install - - run: yarn tsc + # No tsc build cache persists between runs, so skip writing one. + - run: yarn tsc --incremental false audit: needs: changes if: ${{ needs.changes.outputs.deps == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install @@ -97,7 +101,7 @@ jobs: test: needs: changes if: ${{ needs.changes.outputs.app == 'true' || needs.changes.outputs.config == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} strategy: matrix: test-group: [app, shared] @@ -109,37 +113,30 @@ jobs: test-server: needs: changes if: ${{ needs.changes.outputs.server == 'true' || needs.changes.outputs.config == 'true' }} - runs-on: ubuntu-latest - services: - postgres: - image: postgres:14.2 - env: - POSTGRES_USER: postgres - POSTGRES_PASSWORD: password - POSTGRES_DB: outline_test - ports: - - 5432:5432 - options: >- - --health-cmd pg_isready - --health-interval 10s - --health-timeout 5s - --health-retries 5 - + runs-on: ${{ needs.changes.outputs.runner }} strategy: matrix: - shard: [1, 2, 3, 4] + shard: [1, 2, 3, 4, 5, 6] steps: - uses: actions/checkout@v5 + # The runner image ships with PostgreSQL preinstalled, starting it is much + # faster than pulling and initializing a service container. + - name: Start PostgreSQL + run: | + sudo systemctl start postgresql.service + until pg_isready -h localhost; do sleep 1; done + sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'password';" + sudo -u postgres createdb outline_test - uses: ./.github/actions/install - run: yarn sequelize db:migrate - name: Run server tests - run: yarn test:server --maxWorkers=2 --shard=${{ matrix.shard }}/4 + run: yarn test:server --maxWorkers=4 --shard=${{ matrix.shard }}/6 bundle-size: needs: changes if: ${{ (needs.changes.outputs.app == 'true' || needs.changes.outputs.config == 'true') && github.repository == 'outline/outline' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install diff --git a/.github/workflows/update-node.yml b/.github/workflows/update-node.yml index 8fa7974a26..6a3c200374 100644 --- a/.github/workflows/update-node.yml +++ b/.github/workflows/update-node.yml @@ -70,11 +70,7 @@ jobs: # .nvmrc echo "$LATEST_MAJOR" > .nvmrc - # CI install action: step name and node-version - sed -i "s/Use Node.js ${CURRENT_MAJOR}.x/Use Node.js ${LATEST_MAJOR}.x/g" .github/actions/install/action.yml - sed -i "s/node-version: ${CURRENT_MAJOR}.x/node-version: ${LATEST_MAJOR}.x/g" .github/actions/install/action.yml - - # package.json engines field: append new major version + # package.json engines field (also used by CI): append new major version sed -i "s/\"node\": \"\(.*\)\"/\"node\": \"\1 || ${LATEST_MAJOR}\"/" package.json fi diff --git a/.oxlint/bundle.mjs b/.oxlint/bundle.mjs new file mode 100644 index 0000000000..ac2470dff1 --- /dev/null +++ b/.oxlint/bundle.mjs @@ -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; diff --git a/.oxlint/mobx.mjs b/.oxlint/mobx.mjs new file mode 100644 index 0000000000..ae1dfd14ca --- /dev/null +++ b/.oxlint/mobx.mjs @@ -0,0 +1,133 @@ +/** + * Local oxlint plugin with MobX-specific rules. + */ + +/** Returns true if the decorator is `@observable` or `@observable.<modifier>`. */ +function isObservableDecorator(decorator) { + const expression = decorator.expression; + + if (expression.type === "Identifier") { + return expression.name === "observable"; + } + + if (expression.type === "MemberExpression") { + return ( + expression.object.type === "Identifier" && + expression.object.name === "observable" + ); + } + + return false; +} + +/** Returns true if the expression is a `makeObservable(this, …)` call. */ +function isMakeObservableCall(expression) { + return ( + expression.type === "CallExpression" && + expression.callee.type === "Identifier" && + expression.callee.name === "makeObservable" && + expression.arguments.length > 0 && + expression.arguments[0].type === "ThisExpression" + ); +} + +/** Returns the property name if the expression is `this.<name> = …`, else null. */ +function assignedThisProperty(expression) { + if ( + expression.type !== "AssignmentExpression" || + expression.left.type !== "MemberExpression" || + expression.left.object.type !== "ThisExpression" || + expression.left.property.type !== "Identifier" + ) { + return null; + } + return expression.left.property.name; +} + +/** + * Walks the constructor body and returns the set of `this.<name>` properties + * assigned before `makeObservable(this)` is called, or null if the constructor + * never calls it. + */ +function propertiesAssignedBeforeMakeObservable(classBody) { + const ctor = classBody.body.find( + (member) => + member.type === "MethodDefinition" && member.kind === "constructor" + ); + if (!ctor?.value?.body) { + return null; + } + + const assigned = new Set(); + for (const statement of ctor.value.body.body) { + if (statement.type !== "ExpressionStatement") { + continue; + } + if (isMakeObservableCall(statement.expression)) { + return assigned; + } + const name = assignedThisProperty(statement.expression); + if (name) { + assigned.add(name); + } + } + + return null; +} + +const plugin = { + meta: { + name: "mobx", + }, + rules: { + "observable-needs-initializer": { + meta: { + type: "problem", + docs: { + description: + "Require an initializer on @observable class fields in classes that call makeObservable(this). A field that does not exist as an own property when makeObservable runs is silently skipped by MobX.", + }, + messages: { + missing: + "@observable field '{{name}}' has no initializer, so makeObservable() will silently skip it. Add `= undefined` or another initial value.", + }, + }, + create(context) { + return { + ClassBody(node) { + const assigned = propertiesAssignedBeforeMakeObservable(node); + if (assigned === null) { + return; + } + + for (const member of node.body) { + if ( + member.type !== "PropertyDefinition" || + member.value !== null || + member.static || + member.declare || + member.key.type !== "Identifier" || + assigned.has(member.key.name) + ) { + continue; + } + + const decorators = member.decorators ?? []; + if (!decorators.some(isObservableDecorator)) { + continue; + } + + context.report({ + node: member, + messageId: "missing", + data: { name: member.key.name }, + }); + } + }, + }; + }, + }, + }, +}; + +export default plugin; diff --git a/.oxlintrc.json b/.oxlintrc.json index 7b2243a1a5..523e769193 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -9,7 +9,9 @@ "patches/**", "*.d.ts" ], + "jsPlugins": ["./.oxlint/mobx.mjs", "./.oxlint/bundle.mjs"], "rules": { + "mobx/observable-needs-initializer": "error", "for-direction": "error", "no-async-promise-executor": "error", "no-case-declarations": "error", @@ -68,6 +70,18 @@ "valid-typeof": "error" }, "overrides": [ + { + "files": ["plugins/*/client/**/*.{js,jsx,ts,tsx}"], + "rules": { + "bundle/no-constructor-name": "error" + } + }, + { + "files": ["**/*.{ts,tsx}"], + "rules": { + "no-redeclare": "off" + } + }, { "files": ["**/*.{js,jsx,ts,tsx}"], "rules": { diff --git a/.sequelizerc b/.sequelizerc index 8c9410fe24..b345c7a059 100644 --- a/.sequelizerc +++ b/.sequelizerc @@ -1,5 +1,6 @@ require("@dotenvx/dotenvx").config({ path: process.env.NODE_ENV === "test" ? ".env.test" : ".env", + quiet: true, }); var path = require('path'); diff --git a/.yarnrc.yml b/.yarnrc.yml index e2a8e04f87..94b28b2ee1 100644 --- a/.yarnrc.yml +++ b/.yarnrc.yml @@ -13,3 +13,4 @@ npmAuditIgnoreAdvisories: - "1113517" # GHSA-mw96-cpmx-2vgc rollup <2.80.0 path traversal (workbox-build, build-time) - "1113686" # GHSA-5c6j-r48x-rmvq serialize-javascript RCE (@rollup/plugin-terser, build-time) - "1124334" # GHSA-mh99-v99m-4gvg brace-expansion DoS is a false positive + - "1240992" # GHSA-vfj7-8cjw-p6xm braces DoS, no patched release (patch-package, install-time) diff --git a/AGENTS.md b/AGENTS.md index 7618999693..f0dffee0a6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,6 +32,7 @@ You're an expert in the following areas: - Critical – Do not create new markdown (.md) files. - Use early returns for readability. +- Leave an empty line above every comment, unless the comment is the first line in a block. - Emphasize type safety and static analysis. - Follow consistent oxfmt formatting. - Do not replace smart quotes ("") or ('') with simple quotes (""). @@ -94,6 +95,10 @@ This keeps overrides scoped to the affected dependents and avoids forcing unrela - Do not import React unless it is used directly. - Use styled-components for component styling. - Ensure high accessibility (a11y) standards using ARIA roles and semantic HTML. +- In components that stay mounted across navigation (layout, sidebar, command bar), do not use `useLocation`. Use `useLocationSelector` to select only the value you need, or read `history.location` in effects and handlers. +- Give stable props to memoized and `observer` components, especially list rows. Do not create new arrays, objects, or JSX on each render; use shared constants for empty arrays. +- Do not read `ref.current` during render to pass it to props or context. Keep the element in state with a callback ref. +- If the initial value of `useState` reads observables, use a lazy initializer. Otherwise the expression runs, and subscribes, on every render. ## MobX State Management @@ -102,6 +107,10 @@ This keeps overrides scoped to the affected dependents and avoids forcing unrela - Use `observable`, `action`, and `computed` decorators appropriately. - Prefer computed values over manual calculations in render. - Keep business logic in stores, not components. +- Do not read an observable during render only for an effect or a per-item check. Use `useComputed` to derive a narrow value (e.g. `isActive`) so only affected components re-render. +- Use `observable.map` rather than a set when observers check membership by key. `ObservableSet.has()` tracks the whole set, so any change re-renders every observer. +- Store lookups called for each row of a list must not scan a computed list such as `orderedData`, as this subscribes the component to every item in the store. +- A context value provided near the app root must not change on navigation. Expose frequently changing store values as getters read on access, not values read during render. ## Database & ORM @@ -116,6 +125,8 @@ yarn sequelize migration:create --name=add-field-to-table - Use transactions for multi-table operations. - Add appropriate indexes for query performance. - Always handle database errors gracefully. +- When updating Sequelize array or JSON attributes, replace the value instead of mutating it in place; reload the model in tests to verify persistence rather than trusting its in-memory state. +- Schedule optional background work that depends on a transaction from `afterCommit`, and use non-fatal scheduling so a queue failure does not fail the committed operation. ## API Design @@ -133,12 +144,15 @@ yarn sequelize migration:create --name=add-field-to-table - Use cancan-style ability checks. - Use authenticated middleware for protected routes. - Always verify user permissions before data access. +- Set account email and passkey management routes to `AuthenticationType.APP`; API-key authentication must not change login credentials or authenticators. ## Real-time Collaboration - WebSocket connections for real-time updates. - Use Y.js for collaborative editing. - Handle connection state changes gracefully. +- For bulk deletions that drive authorization or WebSocket processing, load affected models in the transaction and delete each with request context so downstream processors receive the expected per-item events. +- Do not persist viewer-specific unfurls in shared document mentions; only store unfurls that map to a stable mention type. ## Documentation @@ -168,6 +182,7 @@ yarn test:shared # All shared code tests ``` - Write unit tests for utilities and business logic in a collocated .test.ts file. +- Server tests share a module registry between files. A server test that uses `vi.mock` or `vi.resetModules` must start with `// @vitest-isolate true` so it runs isolated. - Do not create new test directories - Mock external dependencies appropriately in **mocks** folder. - Aim for high code coverage but focus on critical paths. diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 120000 index 47dc3e3d86..0000000000 --- a/CLAUDE.md +++ /dev/null @@ -1 +0,0 @@ -AGENTS.md \ No newline at end of file diff --git a/LICENSE b/LICENSE index 3ba5896f6a..b7b4cf76a8 100644 --- a/LICENSE +++ b/LICENSE @@ -3,7 +3,7 @@ Business Source License 1.1 Parameters Licensor: General Outline, Inc. -Licensed Work: Outline 1.10.0 +Licensed Work: Outline 1.11.0 The Licensed Work is (c) 2026 General Outline, Inc. Additional Use Grant: You may make use of the Licensed Work, provided that you may not use the Licensed Work for a Document @@ -15,7 +15,7 @@ Additional Use Grant: You may make use of the Licensed Work, provided that Licensed Work by creating teams and documents controlled by such third parties. -Change Date: 2030-09-01 +Change Date: 2030-10-12 Change License: Apache License, Version 2.0 diff --git a/__mocks__/localStorage.js b/__mocks__/localStorage.js deleted file mode 100644 index 19e47a4d3e..0000000000 --- a/__mocks__/localStorage.js +++ /dev/null @@ -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; - }, -}; diff --git a/__mocks__/localStorage.ts b/__mocks__/localStorage.ts new file mode 100644 index 0000000000..83226caf06 --- /dev/null +++ b/__mocks__/localStorage.ts @@ -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; diff --git a/app/.oxlintrc.json b/app/.oxlintrc.json index 9857c6171f..88f10d4b2a 100644 --- a/app/.oxlintrc.json +++ b/app/.oxlintrc.json @@ -4,8 +4,9 @@ "plugins": ["oxc", "eslint", "typescript", "react"], "overrides": [ { - "files": ["**/*.{jsx,tsx}"], + "files": ["**/*.{js,jsx,ts,tsx}"], "rules": { + "bundle/no-constructor-name": "error", "no-restricted-globals": [ "error", { @@ -17,6 +18,11 @@ "error", { "paths": [ + { + "name": "~/editor", + "allowTypeImports": true, + "message": "Import AsyncEditor from ~/components/AsyncEditor instead. A direct import pulls the editor into the importing chunk and bypasses the shared preload." + }, { "name": "prosemirror-tables", "importNames": [ diff --git a/app/actions/definitions/collections.tsx b/app/actions/definitions/collections.tsx index f57bf65083..6fad915895 100644 --- a/app/actions/definitions/collections.tsx +++ b/app/actions/definitions/collections.tsx @@ -48,7 +48,7 @@ import { import { ExportDialog } from "~/components/Export/ExportDialog"; import { isMobile } from "@shared/utils/browser"; import history from "~/utils/history"; -import lazyWithRetry from "~/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; import { openRouteInSplit } from "~/utils/splitView"; const ColorCollectionIcon = ({ collection }: { collection: Collection }) => ( @@ -65,13 +65,15 @@ export const openCollection = createActionWithChildren({ shortcut: ["o", "c"], icon: <CollectionIcon />, children: ({ stores }) => { - const collections = stores.collections.orderedData; + const collections = stores.collections.orderedData.filter( + (collection) => !collection.isPersonal + ); return collections.map((collection) => createInternalLinkAction({ // Note: using url which includes the slug rather than id here to bust // cache if the collection is renamed id: collection.path, - name: collection.name, + name: collection.displayName, icon: <ColorCollectionIcon collection={collection} />, section: CollectionSection, to: collection.path, @@ -125,7 +127,9 @@ export const editCollectionPermissions = createAction({ section: ActiveCollectionSection, icon: <PadlockIcon />, visible: ({ getActivePolicies }) => - getActivePolicies(Collection).some((policy) => policy.abilities.update), + getActivePolicies(Collection).some( + (policy) => policy.abilities.manageUsers + ), perform: ({ t, getActiveModel, stores }) => { const collection = getActiveModel(Collection); if (!collection) { diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index c411207a5e..f6a2c8cdf5 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -62,6 +62,7 @@ import DocumentPublish from "~/scenes/DocumentPublish"; import DeleteDocumentsInTrash from "~/scenes/Trash/components/DeleteDocumentsInTrash"; import ConfirmationDialog from "~/components/ConfirmationDialog"; import { DialogTitle } from "~/components/DialogTitle"; +import { DocumentArchiveDialog } from "~/components/DocumentArchiveDialog"; import DocumentCopy from "~/components/DocumentExplorer/DocumentCopy"; import MarkdownIcon from "~/components/Icons/MarkdownIcon"; import { ImportDocumentDialog } from "~/components/ImportDocumentDialog"; @@ -111,13 +112,14 @@ import type { ActionGroup, ActionSeparator as TActionSeparator, } from "~/types"; -import lazyWithRetry from "~/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; import env from "~/env"; import { isMac, isWindows } from "@shared/utils/browser"; import isCloudHosted from "~/utils/isCloudHosted"; import DocumentMove from "~/components/DocumentExplorer/DocumentMove"; -const Insights = lazyWithRetry( +/** Lazy insights dialog, exported so that triggers can preload it. */ +export const Insights = lazyWithRetry( () => import("~/scenes/Document/components/Insights") ); const SharePopover = lazyWithRetry( @@ -490,7 +492,7 @@ export const starDocument = createAction({ (document) => document.star(), (documents, succeeded, t) => documents.length > 1 - ? t("{{ count }} documents starred", { count: succeeded }) + ? t("{{ count }} document starred", { count: succeeded }) : undefined ); setPersistedState(getHeaderExpandedKey("starred"), true); @@ -518,7 +520,7 @@ export const unstarDocument = createAction({ (document) => document.unstar(), (documents, succeeded, t) => documents.length > 1 - ? t("{{ count }} documents unstarred", { count: succeeded }) + ? t("{{ count }} document unstarred", { count: succeeded }) : undefined ), }); @@ -586,7 +588,7 @@ export const unpublishDocument = createAction({ ? t("Unpublished {{ documentName }}", { documentName: documents[0].noun, }) - : t("{{ count }} documents unpublished", { count: succeeded }) + : t("{{ count }} document unpublished", { count: succeeded }) ), }); @@ -719,10 +721,20 @@ export const shareDocument = createAction({ }, }); +/** + * Shows a file extension in the shortcut slot of menu items only, the command + * bar would otherwise register it as a key sequence. + */ +const fileExtensionHint = + (extension: string) => + ({ isMenu }: ActionContext) => + isMenu ? [extension] : undefined; + export const downloadDocumentAsMarkdown = createAction({ name: ({ t, isMenu }) => (isMenu ? t("Markdown") : t("Download as Markdown")), analyticsName: "Download document as Markdown", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".md"), keywords: "md markdown export download", icon: <MarkdownIcon />, iconInContextMenu: false, @@ -744,6 +756,7 @@ export const downloadDocumentAsHTML = createAction({ name: ({ t, isMenu }) => (isMenu ? t("HTML") : t("Download as HTML")), analyticsName: "Download document as HTML", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".html"), keywords: "xml html export download", icon: <CodeIcon />, iconInContextMenu: false, @@ -766,6 +779,7 @@ export const downloadDocumentAsTextBundle = createAction({ isMenu ? t("TextBundle") : t("Download as TextBundle"), analyticsName: "Download document as TextBundle", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".textpack"), keywords: "textbundle textpack bear ulysses export download", icon: <ArchiveIcon />, iconInContextMenu: false, @@ -787,6 +801,7 @@ export const downloadDocumentAsPDF = createAction({ name: ({ t, isMenu }) => (isMenu ? t("PDF") : t("Download as PDF")), analyticsName: "Download document as PDF", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".pdf"), keywords: "pdf export download", icon: <PDFIcon />, iconInContextMenu: false, @@ -975,7 +990,7 @@ export const pinDocumentToCollection = createAction({ (documents, succeeded, t) => documents.length === 1 ? t("Pinned to collection") - : t("{{ count }} documents pinned", { count: succeeded }) + : t("{{ count }} document pinned", { count: succeeded }) ), }); @@ -1036,7 +1051,7 @@ export const unpinDocument = createAction({ (documents, succeeded, t) => documents.length === 1 ? t("Unpinned") - : t("{{ count }} documents unpinned", { count: succeeded }) + : t("{{ count }} document unpinned", { count: succeeded }) ), }); @@ -1150,6 +1165,7 @@ export const printDocument = createAction({ name: ({ t, isMenu }) => (isMenu ? t("Print") : t("Print document")), analyticsName: "Print document", section: ActiveDocumentSection, + shortcut: ["Meta+P"], icon: <PrintIcon />, iconInContextMenu: false, visible: ({ activeDocumentId }) => !!(activeDocumentId && window.print), @@ -1358,7 +1374,7 @@ export const searchDocumentsForQueryActionFactory = (query: string) => createInternalLinkAction({ id: "search", name: ({ t }) => - t(`Search documents for "{{searchQuery}}"`, { searchQuery: query }), + t("Search documents for “{{ searchQuery }}”", { searchQuery: query }), analyticsName: "Search documents", section: SearchResultsSection, priority: -1, @@ -1450,29 +1466,21 @@ export const archiveDocument = createAction({ }) ), content: ( - <ConfirmationDialog - onSubmit={async () => { + <DocumentArchiveDialog + count={documents.length} + onSubmit={async (reason) => { const succeeded = await performBatch(documents, (document) => - document.archive() + document.archive({ reason }) ); if (succeeded) { toast.success( documents.length === 1 ? t("Document archived") - : t("{{ count }} documents archived", { count: succeeded }) + : t("{{ count }} document archived", { count: succeeded }) ); } }} - savingText={`${t("Archiving")}…`} - > - {documents.length === 1 - ? t( - "Archiving this document will remove it from the collection and search results." - ) - : t( - "Archiving these documents will remove them from their collections and search results." - )} - </ConfirmationDialog> + /> ), }); }, @@ -1501,7 +1509,7 @@ export const restoreDocument = createAction({ ? t("{{ documentName }} restored", { documentName: capitalize(documents[0].noun), }) - : t("{{ count }} documents restored", { count: succeeded }) + : t("{{ count }} document restored", { count: succeeded }) ), }); @@ -1538,7 +1546,7 @@ export const restoreDocumentToCollection = createActionWithChildren({ const actions = collections.orderedData.map((collection) => { const can = policies.abilities(collection.id); return createAction({ - name: collection.name, + name: collection.displayName, section: ActiveDocumentSection, icon: <CollectionIcon collection={collection} />, visible: can.createDocument, @@ -1611,7 +1619,7 @@ export const deleteDocument = createAction({ ); if (succeeded) { toast.success( - t("{{ count }} documents moved to trash", { count: succeeded }) + t("{{ count }} document moved to trash", { count: succeeded }) ); } }} diff --git a/app/actions/definitions/emojis.tsx b/app/actions/definitions/emojis.tsx index 256dac7805..44f4debd43 100644 --- a/app/actions/definitions/emojis.tsx +++ b/app/actions/definitions/emojis.tsx @@ -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} /> ), diff --git a/app/actions/definitions/navigation.tsx b/app/actions/definitions/navigation.tsx index 5287365fc0..1f24fe9198 100644 --- a/app/actions/definitions/navigation.tsx +++ b/app/actions/definitions/navigation.tsx @@ -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"), diff --git a/app/actions/definitions/teams.tsx b/app/actions/definitions/teams.tsx index 4727228087..aecfc44a24 100644 --- a/app/actions/definitions/teams.tsx +++ b/app/actions/definitions/teams.tsx @@ -78,8 +78,8 @@ export const createTeam = createAction({ export const desktopLoginTeam = dialogActionFactory({ analyticsName: "Login to workspace", section: TeamSection, - name: (t) => t("Login to workspace"), - title: (t) => t("Login to workspace"), + name: (t) => t("Log in to workspace"), + title: (t) => t("Log in to workspace"), content: () => <LoginDialog />, icon: <ArrowIcon />, keywords: "change switch workspace organization team", diff --git a/app/actions/definitions/templates.tsx b/app/actions/definitions/templates.tsx index af157ae117..f5b06a7932 100644 --- a/app/actions/definitions/templates.tsx +++ b/app/actions/definitions/templates.tsx @@ -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?")); } }, }); diff --git a/app/actions/definitions/webmcp.ts b/app/actions/definitions/webmcp.ts index fad4d68214..4aa246d825 100644 --- a/app/actions/definitions/webmcp.ts +++ b/app/actions/definitions/webmcp.ts @@ -25,12 +25,16 @@ export const getCurrentContext = createAction({ document: document ? { id: document.id, - title: document.titleWithDefault, + title: document.displayTitle, path: document.url, } : undefined, collection: collection - ? { id: collection.id, name: collection.name, path: collection.path } + ? { + id: collection.id, + name: collection.displayName, + path: collection.path, + } : undefined, }); }, @@ -65,7 +69,7 @@ export const searchWorkspace = createAction({ return JSON.stringify( results.map((result) => ({ id: result.document.id, - title: result.document.titleWithDefault, + title: result.document.displayTitle, path: result.document.url, context: result.context, })) diff --git a/app/actions/index.ts b/app/actions/index.ts index 46decda4fb..37cbcca3e7 100644 --- a/app/actions/index.ts +++ b/app/actions/index.ts @@ -46,24 +46,7 @@ export function createAction( ...definition, type: "action", variant: "action", - perform: definition.perform - ? (context) => { - // We must use the specific analytics name here as the action name is - // translated and potentially contains user strings. - if (definition.analyticsName) { - Analytics.track("perform_action", definition.analyticsName, { - context: context.isButton - ? "button" - : context.isCommandBar - ? "commandbar" - : context.isMCP - ? "webmcp" - : "contextmenu", - }); - } - return definition.perform(context); - } - : () => {}, + perform: definition.perform ?? (() => {}), id: definition.id ?? uuidv4(), }; } @@ -182,7 +165,7 @@ export function actionToMenuItem( icon, visible, disabled, - tooltip: resolve<React.ReactChild>(action.tooltip, context), + tooltip: resolve<React.ReactNode>(action.tooltip, context), selected: resolve<boolean>(action.selected, context), dangerous: action.dangerous, shortcut, @@ -353,6 +336,20 @@ export async function performAction( ? () => history.push(resolve<LocationDescriptor>(action.to, context)) : () => window.open(action.url, action.target); + // We must use the specific analytics name here as the action name is + // translated and potentially contains user strings. + if (action.analyticsName) { + Analytics.track("perform_action", action.analyticsName, { + context: context.isButton + ? "button" + : context.isCommandBar + ? "commandbar" + : context.isMCP + ? "webmcp" + : "contextmenu", + }); + } + const result = perform(); if (result instanceof Promise) { diff --git a/app/actions/sections.ts b/app/actions/sections.ts index b3499b46c6..699771bbf2 100644 --- a/app/actions/sections.ts +++ b/app/actions/sections.ts @@ -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; diff --git a/app/components/ActionButton.tsx b/app/components/ActionButton.tsx index e42f45bfba..c553fccdd4 100644 --- a/app/components/ActionButton.tsx +++ b/app/components/ActionButton.tsx @@ -1,10 +1,8 @@ -/* oxlint-disable react/prop-types */ import { observer } from "mobx-react"; import * as React from "react"; import type { Props as TooltipProps } from "~/components/Tooltip"; import Tooltip from "~/components/Tooltip"; import { performAction, resolve } from "~/actions"; -import useIsMounted from "~/hooks/useIsMounted"; import useActionContext from "~/hooks/useActionContext"; import type { ActionVariant, ActionWithChildren } from "~/types"; @@ -22,68 +20,66 @@ export type Props = React.HTMLAttributes<HTMLButtonElement> & { /** * Button that can be used to trigger an action definition. */ -const ActionButton = React.forwardRef<HTMLButtonElement, Props>( - function ActionButton_( - { action, tooltip, hideOnActionDisabled, ...rest }: Props, - ref: React.Ref<HTMLButtonElement> - ) { - const actionContext = useActionContext({ - isButton: true, - }); - const isMounted = useIsMounted(); - const [executing, setExecuting] = React.useState(false); +function ActionButton({ + action, + tooltip, + hideOnActionDisabled, + ref, + ...rest +}: Props & { ref?: React.Ref<HTMLButtonElement> }) { + const actionContext = useActionContext({ + isButton: true, + }); + const [executing, setExecuting] = React.useState(false); - if (!actionContext || !action) { - return <button {...rest} ref={ref} />; - } - - const actionIsDisabled = - action.visible && !resolve<boolean>(action.visible, actionContext); - - if (actionIsDisabled && hideOnActionDisabled) { - return null; - } - - const disabled = rest.disabled || actionIsDisabled; - - const label = - rest["aria-label"] ?? - (typeof action.name === "function" - ? action.name(actionContext) - : action.name); - - const button = ( - <button - {...rest} - aria-label={typeof label === "string" ? label : undefined} - disabled={disabled || executing} - ref={ref} - onClick={ - actionContext - ? (ev) => { - ev.preventDefault(); - ev.stopPropagation(); - const response = performAction(action, actionContext); - if (response?.finally) { - setExecuting(true); - void response.finally( - () => isMounted() && setExecuting(false) - ); - } - } - : rest.onClick - } - > - {rest.children ?? label} - </button> - ); - - if (tooltip) { - return <Tooltip {...tooltip}>{button}</Tooltip>; - } - - return button; + if (!actionContext || !action) { + return <button {...rest} ref={ref} />; } -); + + const actionIsDisabled = + action.visible && !resolve<boolean>(action.visible, actionContext); + + if (actionIsDisabled && hideOnActionDisabled) { + return null; + } + + const disabled = rest.disabled || actionIsDisabled; + + const label = + rest["aria-label"] ?? + (typeof action.name === "function" + ? action.name(actionContext) + : action.name); + + const button = ( + <button + {...rest} + aria-label={typeof label === "string" ? label : undefined} + disabled={disabled || executing} + ref={ref} + onClick={ + actionContext + ? (ev) => { + ev.preventDefault(); + ev.stopPropagation(); + const response = performAction(action, actionContext); + if (response?.finally) { + setExecuting(true); + void response.finally(() => setExecuting(false)); + } + } + : rest.onClick + } + > + {rest.children ?? label} + </button> + ); + + if (tooltip) { + return <Tooltip {...tooltip}>{button}</Tooltip>; + } + + return button; +} export default observer(ActionButton); diff --git a/app/components/Actions.ts b/app/components/Actions.ts index aff0f693c8..44db046c99 100644 --- a/app/components/Actions.ts +++ b/app/components/Actions.ts @@ -1,5 +1,6 @@ import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; +import { MOBILE_TOUCH_TARGET } from "@shared/constants"; import { s } from "@shared/styles"; import Flex from "~/components/Flex"; @@ -10,6 +11,10 @@ export const Action = styled(Flex)` font-size: 15px; flex-shrink: 0; + ${breakpoint("mobile", "tablet")` + height: ${MOBILE_TOUCH_TARGET}px; + `}; + &:empty { display: none; } diff --git a/app/components/Analytics.tsx b/app/components/Analytics.tsx index 908540161b..cbb4abfacb 100644 --- a/app/components/Analytics.tsx +++ b/app/components/Analytics.tsx @@ -1,4 +1,3 @@ -/* oxlint-disable prefer-rest-params */ /* global ga */ import { escape } from "es-toolkit/compat"; import * as React from "react"; diff --git a/app/components/ArrowKeyNavigation.tsx b/app/components/ArrowKeyNavigation.tsx index 7834efd5aa..7e520998b3 100644 --- a/app/components/ArrowKeyNavigation.tsx +++ b/app/components/ArrowKeyNavigation.tsx @@ -6,12 +6,16 @@ type Props = Omit<React.HTMLAttributes<HTMLDivElement>, "children"> & { children: () => React.ReactNode; onEscape?: (ev: React.KeyboardEvent<HTMLDivElement>) => void; items: unknown[]; + ref?: React.Ref<HTMLDivElement>; }; -function ArrowKeyNavigation( - { children, onEscape, items, ...rest }: Props, - ref: React.RefObject<HTMLDivElement> -) { +function ArrowKeyNavigation({ + children, + onEscape, + items, + ref, + ...rest +}: Props) { const handleKeyDown = React.useCallback( (ev: React.KeyboardEvent<HTMLDivElement>) => { if (onEscape) { @@ -48,4 +52,4 @@ function ArrowKeyNavigation( ); } -export default observer(React.forwardRef(ArrowKeyNavigation)); +export default observer(ArrowKeyNavigation); diff --git a/app/components/AsyncEditor.ts b/app/components/AsyncEditor.ts new file mode 100644 index 0000000000..f3964e1187 --- /dev/null +++ b/app/components/AsyncEditor.ts @@ -0,0 +1,13 @@ +import lazyWithRetry from "@shared/utils/lazyWithRetry"; + +/** + * The editor core is the largest chunk in the app and is kept out of the + * initial bundle. This module stays light so routes can preload the chunk + * without pulling editor dependencies into their own chunk. + */ +const AsyncEditor = lazyWithRetry( + // oxlint-disable-next-line no-restricted-imports -- the one place the chunk is loaded + () => import("~/editor") +); + +export default AsyncEditor; diff --git a/app/components/Authenticated.tsx b/app/components/Authenticated.tsx index 9a50239400..734904f6ee 100644 --- a/app/components/Authenticated.tsx +++ b/app/components/Authenticated.tsx @@ -8,7 +8,7 @@ import { changeLanguage } from "~/utils/language"; import LoadingIndicator from "./LoadingIndicator"; type Props = { - children: JSX.Element; + children: React.JSX.Element; }; const Authenticated = ({ children }: Props) => { diff --git a/app/components/AuthenticatedLayout.tsx b/app/components/AuthenticatedLayout.tsx index ef2bcd1252..d1b3ef235e 100644 --- a/app/components/AuthenticatedLayout.tsx +++ b/app/components/AuthenticatedLayout.tsx @@ -1,7 +1,6 @@ import { observer } from "mobx-react"; import * as React from "react"; import { DndProvider } from "react-dnd"; -import { useLocation } from "react-router-dom"; import { EditorAwareHTML5Backend } from "~/components/EditorAwareHTML5Backend"; import ErrorSuspended from "~/scenes/Errors/ErrorSuspended"; import Layout from "~/components/Layout"; @@ -14,10 +13,11 @@ import useKeyDown from "~/hooks/useKeyDown"; import useWebMCPActions from "~/hooks/useWebMCPActions"; import { usePostLoginPath } from "~/hooks/useLastVisitedPath"; import usePolicy from "~/hooks/usePolicy"; +import { useLocationSelector } from "~/hooks/useLocationSelector"; import useStores from "~/hooks/useStores"; import Logger from "~/utils/Logger"; import history from "~/utils/history"; -import lazyWithRetry from "~/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; import { searchPath, newDocumentPath, @@ -40,8 +40,12 @@ type Props = { const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => { const { ui, auth } = useStores(); - const location = useLocation(); - const layoutRef = React.useRef<HTMLDivElement>(null); + const isSettings = useLocationSelector((location) => + location.pathname.startsWith(settingsPath()) + ); + // State rather than a ref, so that portals receive the element once mounted. + const [layoutElement, setLayoutElement] = + React.useState<HTMLDivElement | null>(null); const canCollection = usePolicy(ui.activeCollectionId); const team = useCurrentTeam(); const [spendPostLoginPath] = usePostLoginPath(); @@ -87,8 +91,6 @@ const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => { return <ErrorSuspended />; } - const isSettings = location.pathname.startsWith(settingsPath()); - const sidebar = ( <Fade> <React.Suspense fallback={null}> @@ -103,13 +105,13 @@ const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => { return ( <DocumentContextProvider> <RightSidebarProvider> - <PortalContext.Provider value={layoutRef.current}> + <PortalContext.Provider value={layoutElement}> <DndProvider backend={EditorAwareHTML5Backend}> <Layout title={team.name} sidebar={sidebar} sidebarCanCollapse={!isSettings} - ref={layoutRef} + ref={setLayoutElement} > <RegisterKeyDown trigger="n" handler={goToNewDocument} /> <RegisterKeyDown trigger="t" handler={goToSearch} /> diff --git a/app/components/Avatar/Avatar.tsx b/app/components/Avatar/Avatar.tsx index 18abcd4b9f..34edf124cd 100644 --- a/app/components/Avatar/Avatar.tsx +++ b/app/components/Avatar/Avatar.tsx @@ -49,16 +49,16 @@ export type AvatarProps = { showTooltip?: boolean; /** Whether to show a profile card on hover for users, defaults to true */ showHoverCard?: boolean; + /** Ref to the outer element */ + ref?: React.Ref<HTMLDivElement>; } & Omit< React.ComponentPropsWithoutRef<"div">, "onClick" | "className" | "style" >; -const Avatar = React.forwardRef(function Avatar_( - props: AvatarProps, - ref: React.Ref<HTMLDivElement> -) { +function Avatar(props: AvatarProps) { const { + ref, model, style, variant = AvatarVariant.Round, @@ -111,7 +111,7 @@ const Avatar = React.forwardRef(function Avatar_( ) : ( content ); -}); +} const Relative = styled.div<{ $variant: AvatarVariant; $size: AvatarSize }>` position: relative; diff --git a/app/components/Avatar/AvatarWithHoverCard.tsx b/app/components/Avatar/AvatarWithHoverCard.tsx index 64f8000bfc..8ffb3c3a70 100644 --- a/app/components/Avatar/AvatarWithHoverCard.tsx +++ b/app/components/Avatar/AvatarWithHoverCard.tsx @@ -1,5 +1,4 @@ import { observer } from "mobx-react"; -import * as React from "react"; import { UserHoverCard } from "~/components/UserHoverCard"; import User from "~/models/User"; import type { AvatarProps } from "./Avatar"; @@ -9,10 +8,12 @@ import Avatar from "./Avatar"; * An avatar that additionally displays a profile card on hover when the model * it represents is a user. */ -const AvatarWithHoverCard = React.forwardRef(function AvatarWithHoverCard_( - { showTooltip, showHoverCard = true, ...props }: AvatarProps, - ref: React.Ref<HTMLDivElement> -) { +function AvatarWithHoverCard({ + showTooltip, + showHoverCard = true, + ref, + ...props +}: AvatarProps) { const { model } = props; if (!showHoverCard || !(model instanceof User)) { @@ -24,6 +25,6 @@ const AvatarWithHoverCard = React.forwardRef(function AvatarWithHoverCard_( <Avatar ref={ref} {...props} /> </UserHoverCard> ); -}); +} export default observer(AvatarWithHoverCard); diff --git a/app/components/Avatar/AvatarWithPresence.tsx b/app/components/Avatar/AvatarWithPresence.tsx index 1b14986836..82d88a9a49 100644 --- a/app/components/Avatar/AvatarWithPresence.tsx +++ b/app/components/Avatar/AvatarWithPresence.tsx @@ -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> ); diff --git a/app/components/Avatar/GroupAvatar.tsx b/app/components/Avatar/GroupAvatar.tsx index 9c0b352d72..acf81711e9 100644 --- a/app/components/Avatar/GroupAvatar.tsx +++ b/app/components/Avatar/GroupAvatar.tsx @@ -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> ); -} +}); diff --git a/app/components/Breadcrumb.tsx b/app/components/Breadcrumb.tsx index 7a9296ddd3..072b724651 100644 --- a/app/components/Breadcrumb.tsx +++ b/app/components/Breadcrumb.tsx @@ -2,7 +2,7 @@ import { GoToIcon } from "outline-icons"; import { observer } from "mobx-react"; import * as React from "react"; import { Link } from "react-router-dom"; -import styled from "styled-components"; +import styled, { css } from "styled-components"; import { s, ellipsis } from "@shared/styles"; import Flex from "~/components/Flex"; import BreadcrumbMenu from "~/menus/BreadcrumbMenu"; @@ -20,12 +20,16 @@ type Props = React.PropsWithChildren<{ actions: InternalLinkAction[]; max?: number; highlightFirstItem?: boolean; + ref?: React.Ref<HTMLDivElement>; }>; -function Breadcrumb( - { actions, highlightFirstItem, children, max = 2 }: Props, - ref: React.RefObject<HTMLDivElement> | null -) { +function Breadcrumb({ + actions, + highlightFirstItem, + children, + max = 2, + ref, +}: Props) { const actionContext = useActionContext({ isMenu: true }); const visibleActions = useComputed( @@ -71,13 +75,20 @@ function Breadcrumb( } const item = actionToMenuItem(action, actionContext) as MenuInternalLink; + const highlight = !!highlightFirstItem && index === 0; + + // Items without a destination are shown as plain text. + if (!item.to) { + return ( + <StaticItem $highlight={highlight}> + {item.icon} + <Title>{item.title} + + ); + } return ( - + {item.icon} {item.title} @@ -106,7 +117,7 @@ const Slash = styled(GoToIcon)` fill: ${s("divider")}; `; -const Item = styled(Link)<{ $highlight: boolean }>` +const itemStyles = css<{ $highlight: boolean }>` ${undraggableOnDesktop()} display: flex; @@ -114,7 +125,6 @@ const Item = styled(Link)<{ $highlight: boolean }>` gap: 4px; flex-shrink: 1; min-width: 0; - cursor: var(--pointer); color: ${s("text")}; font-size: 15px; height: 32px; @@ -127,6 +137,11 @@ const Item = styled(Link)<{ $highlight: boolean }>` margin-inline-start: 0; } max-width: 460px; +`; + +const Item = styled(Link)<{ $highlight: boolean }>` + ${itemStyles} + cursor: var(--pointer); transition: background 100ms ease-in-out; &:hover, @@ -136,9 +151,14 @@ const Item = styled(Link)<{ $highlight: boolean }>` } `; +const StaticItem = styled.span<{ $highlight: boolean }>` + ${itemStyles} + cursor: default; +`; + const Title = styled.span` ${ellipsis()} min-width: 0; `; -export default observer(React.forwardRef(Breadcrumb)); +export default observer(Breadcrumb); diff --git a/app/components/Button.tsx b/app/components/Button.tsx index 75a2b0b622..ff7964948a 100644 --- a/app/components/Button.tsx +++ b/app/components/Button.tsx @@ -3,6 +3,8 @@ import { DisclosureIcon } from "outline-icons"; import { darken, lighten, transparentize } from "polished"; import * as React from "react"; import styled from "styled-components"; +import breakpoint from "styled-components-breakpoint"; +import { MOBILE_TOUCH_TARGET } from "@shared/constants"; import { s } from "@shared/styles"; import type { Props as ActionButtonProps } from "~/components/ActionButton"; import ActionButton from "~/components/ActionButton"; @@ -36,6 +38,12 @@ const RealButton = styled(ActionButton)` 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` 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 = ActionButtonProps & { @@ -158,13 +180,14 @@ export type Props = ActionButtonProps & { "data-on"?: string; "data-event-category"?: string; "data-event-action"?: string; + ref?: React.Ref; }; -const Button = ( - props: Props & React.ComponentPropsWithoutRef, - ref: React.Ref -) => { +function Button( + props: Props & React.ComponentPropsWithoutRef +) { const { + ref, type, children, value, @@ -191,6 +214,7 @@ const Button = ( $danger={danger} $fullwidth={fullwidth} $borderOnHover={borderOnHover} + data-variant={danger ? "danger" : neutral ? "neutral" : "primary"} {...rest} > @@ -200,10 +224,10 @@ const Button = ( ); -}; +} const StyledDisclosureIcon = styled(DisclosureIcon)` opacity: 0.8; `; -export default React.forwardRef(Button); +export default Button; diff --git a/app/components/Collaborators.tsx b/app/components/Collaborators.tsx index 2eaece4f7a..fc9dda40ca 100644 --- a/app/components/Collaborators.tsx +++ b/app/components/Collaborators.tsx @@ -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([]); @@ -163,21 +171,23 @@ function Collaborators(props: Props) { return null; } + const facepileWidth = Math.min(collaborators.length, limit) * size; + return ( - - + @@ -186,4 +196,9 @@ function Collaborators(props: Props) { ); } +const FacepileButton = styled(NudeButton)` + display: inline-flex; + align-items: center; +`; + export default observer(Collaborators); diff --git a/app/components/Collection/CollectionForm.tsx b/app/components/Collection/CollectionForm.tsx index 520e5544ed..4f933a559c 100644 --- a/app/components/Collection/CollectionForm.tsx +++ b/app/components/Collection/CollectionForm.tsx @@ -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." )} /> )} diff --git a/app/components/CollectionBreadcrumb.tsx b/app/components/CollectionBreadcrumb.tsx index c5ebf3f08e..c95b563a75 100644 --- a/app/components/CollectionBreadcrumb.tsx +++ b/app/components/CollectionBreadcrumb.tsx @@ -25,7 +25,7 @@ export const CollectionBreadcrumb: React.FC = ({ collection }) => { to: archivePath(), }), createInternalLinkAction({ - name: collection.name, + name: collection.displayName, section: ActiveCollectionSection, icon: , to: collectionPath(collection), diff --git a/app/components/CollectionDeleteDialog.tsx b/app/components/CollectionDeleteDialog.tsx index 337ccbde9a..e8d4d1a153 100644 --- a/app/components/CollectionDeleteDialog.tsx +++ b/app/components/CollectionDeleteDialog.tsx @@ -44,7 +44,7 @@ function CollectionDeleteDialog({ collection, onSubmit }: Props) { , @@ -56,7 +56,7 @@ function CollectionDeleteDialog({ collection, onSubmit }: Props) { , diff --git a/app/components/ColorButton.tsx b/app/components/ColorButton.tsx index 1c3b359a87..67b4f76d06 100644 --- a/app/components/ColorButton.tsx +++ b/app/components/ColorButton.tsx @@ -10,13 +10,17 @@ type Props = React.HTMLAttributes & { active?: boolean; /** The size of the button in pixels */ size?: number; + ref?: React.Ref; }; -export const ColorButton = React.forwardRef( - ( - { color, active = false, size = 24, ...rest }: Props, - ref: React.Ref - ) => ( +export function ColorButton({ + color, + active = false, + size = 24, + ref, + ...rest +}: Props) { + return ( - ) -); + ); +} /** Highlight for the hovered or selected swatch, falls back for the gradient. */ const ring = css`2px solid var(--color, ${s("textTertiary")})`; diff --git a/app/components/CommandBar/CommandBar.tsx b/app/components/CommandBar/CommandBar.tsx index 5b6680bd2b..9fdf606e9c 100644 --- a/app/components/CommandBar/CommandBar.tsx +++ b/app/components/CommandBar/CommandBar.tsx @@ -2,10 +2,10 @@ import { useKBar, KBarPositioner, KBarAnimator, KBarSearch } from "kbar"; import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; -import { Portal } from "react-portal"; import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; import { depths, s } from "@shared/styles"; +import { Portal } from "~/components/Portal"; import SearchActions from "~/components/SearchActions"; import rootActions from "~/actions/root"; import useCommandBarActions from "~/hooks/useCommandBarActions"; diff --git a/app/components/CommandBar/CommandBarItem.tsx b/app/components/CommandBar/CommandBarItem.tsx index edb163fb2c..5af103303e 100644 --- a/app/components/CommandBar/CommandBarItem.tsx +++ b/app/components/CommandBar/CommandBarItem.tsx @@ -14,6 +14,7 @@ type Props = { action: CommandBarActionImpl; active: boolean; currentRootActionId: string | null | undefined; + ref?: React.Ref; }; const SEARCH_RESULT_REGEX = /]*>(.*?)<\/b>/gi; @@ -24,10 +25,7 @@ function replaceResultMarks(tag: string) { return tag.replace(/]*>(.*?)<\/b>/gi, "$1"); } -function CommandBarItem( - { action, active, currentRootActionId }: Props, - ref: React.RefObject -) { +function CommandBarItem({ action, active, currentRootActionId, ref }: Props) { const theme = useTheme(); const ancestors = React.useMemo(() => { if (!currentRootActionId || !action.ancestors) { @@ -168,4 +166,4 @@ const ForwardIcon = styled(BackIcon)` flex-shrink: 0; `; -export default React.forwardRef(CommandBarItem); +export default CommandBarItem; diff --git a/app/components/CommandBar/SearchIndex.test.ts b/app/components/CommandBar/SearchIndex.test.ts index 8fd7640999..3268632d88 100644 --- a/app/components/CommandBar/SearchIndex.test.ts +++ b/app/components/CommandBar/SearchIndex.test.ts @@ -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); diff --git a/app/components/CommandBar/SearchIndex.ts b/app/components/CommandBar/SearchIndex.ts index 4af8e09d40..5e8648da36 100644 --- a/app/components/CommandBar/SearchIndex.ts +++ b/app/components/CommandBar/SearchIndex.ts @@ -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 = { 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 ) { diff --git a/app/components/CommandBar/SharedCommandBar.tsx b/app/components/CommandBar/SharedCommandBar.tsx index 1895ecb681..fe09861a77 100644 --- a/app/components/CommandBar/SharedCommandBar.tsx +++ b/app/components/CommandBar/SharedCommandBar.tsx @@ -2,10 +2,10 @@ import { useKBar, KBarPositioner, KBarAnimator, KBarSearch } from "kbar"; import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; -import { Portal } from "react-portal"; import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; import { depths, s } from "@shared/styles"; +import { Portal } from "~/components/Portal"; import CommandBarResults from "./CommandBarResults"; import SharedSearchActions from "./SharedSearchActions"; diff --git a/app/components/CommandBar/useRecentDocumentActions.tsx b/app/components/CommandBar/useRecentDocumentActions.tsx index 2d5545286c..0da9ea7f1d 100644 --- a/app/components/CommandBar/useRecentDocumentActions.tsx +++ b/app/components/CommandBar/useRecentDocumentActions.tsx @@ -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, diff --git a/app/components/CommandBar/useSearchIndex.ts b/app/components/CommandBar/useSearchIndex.ts index 7ca8ec263e..354b690731 100644 --- a/app/components/CommandBar/useSearchIndex.ts +++ b/app/components/CommandBar/useSearchIndex.ts @@ -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 `` highlight tags from a context snippet. */ @@ -47,11 +59,14 @@ export function toSearchRecord( doc: Document, context?: string ): SearchIndexDocument { + const content = doc.data ? getContent(doc) : undefined; + return { id: doc.id, - title: doc.titleWithDefault, + title: doc.displayTitle, url: doc.url, - text: doc.data ? getPlainText(doc) : stripHighlightTags(context), + text: content ? content.text : stripHighlightTags(context), + headings: content?.headings, icon: doc.icon, color: doc.color, isArchived: doc.isArchived, @@ -90,7 +105,7 @@ export interface UseSearchIndex { * @returns the current results and functions to feed or reset the index. */ export function useSearchIndex(query: string): UseSearchIndex { - const indexRef = useRef(); + const indexRef = useRef(undefined); if (!indexRef.current) { indexRef.current = new SearchIndex(); } @@ -110,14 +125,14 @@ export function useSearchIndex(query: string): UseSearchIndex { const reset = useCallback(() => { index.clear(); - plainTextCache.clear(); + contentCache.clear(); setVersion((v) => v + 1); }, [index]); const results = useMemo( () => (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] ); diff --git a/app/components/CommandBar/useTemplatesAction.tsx b/app/components/CommandBar/useTemplatesAction.tsx index c4ae42406c..8aa6f09716 100644 --- a/app/components/CommandBar/useTemplatesAction.tsx +++ b/app/components/CommandBar/useTemplatesAction.tsx @@ -1,3 +1,4 @@ +import { useKBar } from "kbar"; import { NewDocumentIcon, ShapesIcon } from "outline-icons"; import { useEffect, useMemo } from "react"; import Icon from "@shared/components/Icon"; @@ -12,16 +13,22 @@ import { newDocumentPath } from "~/utils/routeHelpers"; const useTemplatesAction = () => { const { templates } = useStores(); + const { showing } = useKBar((state) => ({ + showing: state.visualState !== "hidden", + })); + // Templates are only needed once the command bar is opened. useEffect(() => { - void templates.fetchAll(); - }, [templates]); + if (showing) { + void templates.fetchAllIfNeeded(); + } + }, [showing, templates]); const actions = useMemo( () => templates.alphabetical.map((template) => createInternalLinkAction({ - name: template.titleWithDefault, + name: template.displayTitle, analyticsName: "New document", section: template.isWorkspaceTemplate ? TeamSection diff --git a/app/components/ConfirmMoveDialog.tsx b/app/components/ConfirmMoveDialog.tsx index 55401670a8..c3d3f0d08d 100644 --- a/app/components/ConfirmMoveDialog.tsx +++ b/app/components/ConfirmMoveDialog.tsx @@ -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 {{ title }} to the {{ newCollectionName }} collection will change permission for all workspace members from {{ prevPermission }} to {{ newPermission }}." 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"], }} diff --git a/app/components/ContentEditable.tsx b/app/components/ContentEditable.tsx index 20b3948e81..dd714bc539 100644 --- a/app/components/ContentEditable.tsx +++ b/app/components/ContentEditable.tsx @@ -1,7 +1,9 @@ import isPrintableKeyEvent from "is-printable-key-event"; import * as React from "react"; +import { useMergeRefs } from "react-merge-refs"; import styled from "styled-components"; import { s } from "@shared/styles"; +import { TextHelper } from "@shared/utils/TextHelper"; import useOnScreen from "~/hooks/useOnScreen"; type Props = Omit, "ref" | "onChange"> & { @@ -13,11 +15,13 @@ type Props = Omit, "ref" | "onChange"> & { onBlur?: React.FocusEventHandler | undefined; onInput?: React.FormEventHandler | undefined; onKeyDown?: React.KeyboardEventHandler | undefined; + onCompositionEnd?: React.CompositionEventHandler | undefined; placeholder?: string; maxLength?: number; autoFocus?: boolean; children?: React.ReactNode; value: string; + ref?: React.Ref; }; export type RefHandle = { @@ -31,29 +35,29 @@ export type RefHandle = { * Defines a content editable component with the same interface as a native * HTMLInputElement (or, as close as we can get). */ -const ContentEditable = React.forwardRef(function ContentEditable_( - { - disabled, - onChange, - onInput, - onFocus, - onBlur, - onKeyDown, - value, - children, - className, - maxLength, - autoFocus, - placeholder, - readOnly, - dir, - onClick, - ...rest - }: Props, - ref: React.RefObject -) { +function ContentEditable({ + disabled, + onChange, + onInput, + onFocus, + onBlur, + onKeyDown, + onCompositionEnd, + value, + children, + className, + maxLength, + autoFocus, + placeholder, + readOnly, + dir, + onClick, + ref, + ...rest +}: Props) { const contentRef = React.useRef(null); const [innerValue, setInnerValue] = React.useState(value); + const [isEmpty, setIsEmpty] = React.useState(value.length === 0); const lastValue = React.useRef(value); React.useImperativeHandle(ref, () => ({ @@ -95,18 +99,33 @@ const ContentEditable = React.forwardRef(function ContentEditable_( return; } - const text = event.currentTarget.textContent || ""; + let text = event.currentTarget.textContent || ""; + setIsEmpty(text.length === 0); + const overLimit = + !!maxLength && TextHelper.codePointLength(text) > maxLength; if ( maxLength && event.nativeEvent instanceof KeyboardEvent && isPrintableKeyEvent(event.nativeEvent) && - text.length >= maxLength + TextHelper.codePointLength(text) >= maxLength ) { event.preventDefault(); return; } + // Paste, drop, IME and other non-keyboard input paths bypass the check + // above, so clamp whatever landed in the DOM. Editing the DOM would + // break an active IME session, so wait for composition end and do not + // publish the over-limit buffer in the meantime. + if (overLimit && maxLength) { + if (isComposing(event)) { + callback?.(event); + return; + } + text = truncateContent(event.currentTarget, maxLength); + } + if (text !== lastValue.current) { lastValue.current = text; onChange?.(text); @@ -119,7 +138,8 @@ const ContentEditable = React.forwardRef(function ContentEditable_( // case the component may be rendered with display: none. React 18 may solve // this in the future by delaying useEffect hooks: // https://github.com/facebook/react/issues/14536#issuecomment-861980492 - const isVisible = useOnScreen(contentRef); + const [onScreenRef, isVisible] = useOnScreen(); + const mergedRef = useMergeRefs([contentRef, onScreenRef]); React.useEffect(() => { if (autoFocus && isVisible && !disabled && !readOnly) { @@ -128,8 +148,17 @@ const ContentEditable = React.forwardRef(function ContentEditable_( }, [autoFocus, disabled, isVisible, readOnly, contentRef]); React.useEffect(() => { - if (contentRef.current && value !== contentRef.current.textContent) { - if (document.activeElement === contentRef.current) { + if (!contentRef.current) { + return; + } + + const isFocused = document.activeElement === contentRef.current; + setIsEmpty( + isFocused ? !contentRef.current.textContent : value.length === 0 + ); + + if (value !== contentRef.current.textContent) { + if (isFocused) { // Don't reset content while the user is actively editing. Update // lastValue so that the next input or blur event will push the // current DOM text back to the model via onChange. @@ -146,10 +175,21 @@ const ContentEditable = React.forwardRef(function ContentEditable_( const handlePaste = React.useCallback( (event: React.ClipboardEvent) => { event.preventDefault(); - const text = event.clipboardData.getData("text/plain"); + let text = event.clipboardData.getData("text/plain"); + + if (maxLength) { + const current = event.currentTarget.textContent || ""; + const selected = window.getSelection()?.toString() || ""; + const remaining = + maxLength - + (TextHelper.codePointLength(current) - + TextHelper.codePointLength(selected)); + text = TextHelper.truncate(text, remaining); + } + window.document.execCommand("insertText", false, text); }, - [] + [maxLength] ); const contentEditable = !disabled && !readOnly; @@ -157,14 +197,16 @@ const ContentEditable = React.forwardRef(function ContentEditable_(
{children}
); -}); +} + +function isComposing(event: React.SyntheticEvent) { + const native = event.nativeEvent; + return ( + (native instanceof InputEvent || native instanceof KeyboardEvent) && + native.isComposing + ); +} + +/** + * Truncates the text content of an element to the given number of code points + * while keeping the caret at its current position where possible. + */ +function truncateContent(element: HTMLElement, maxLength: number): string { + const selection = window.getSelection(); + const range = selection?.rangeCount ? selection.getRangeAt(0) : undefined; + let offset = Number.MAX_SAFE_INTEGER; + + if (range && element.contains(range.startContainer)) { + const before = range.cloneRange(); + before.selectNodeContents(element); + before.setEnd(range.startContainer, range.startOffset); + offset = before.toString().length; + } + + const text = TextHelper.truncate(element.textContent || "", maxLength); + element.textContent = text; + + const textNode = element.firstChild; + if (textNode && selection) { + const caret = document.createRange(); + caret.setStart(textNode, Math.min(offset, text.length)); + caret.collapse(true); + selection.removeAllRanges(); + selection.addRange(caret); + } + + return text; +} function placeCaret(element: HTMLElement, atStart: boolean) { if ( @@ -198,12 +279,14 @@ const Content = styled.span` cursor: text; word-break: anywhere; - &:empty { + /* Browsers can leave line breaks behind after all text is deleted. */ + &[data-empty="true"] { display: inline-block; } - &:empty::before { + &[data-empty="true"]::before { display: inline-block; + float: inline-start; color: ${s("placeholder")}; -webkit-text-fill-color: ${s("placeholder")}; content: attr(data-placeholder); diff --git a/app/components/CopyToClipboard.ts b/app/components/CopyToClipboard.ts index 5dc70b7cd4..92068f1cf1 100644 --- a/app/components/CopyToClipboard.ts +++ b/app/components/CopyToClipboard.ts @@ -3,15 +3,21 @@ import * as React from "react"; import { mergeRefs } from "react-merge-refs"; import env from "~/env"; -type Props = { - text: string; - children?: React.ReactElement; - onClick?: React.MouseEventHandler; - onCopy?: () => void; +type ChildProps = { + onClick?: React.MouseEventHandler; + ref?: React.Ref; }; -function CopyToClipboard(props: Props, ref: React.Ref) { - const { text, onCopy, children, ...rest } = props; +type Props = { + text: string; + children?: React.ReactElement; + onClick?: React.MouseEventHandler; + onCopy?: () => void; + ref?: React.Ref; +}; + +function CopyToClipboard(props: Props) { + const { text, onCopy, children, ref, ...rest } = props; const onClick = React.useCallback( (ev: React.MouseEvent) => { @@ -45,12 +51,9 @@ function CopyToClipboard(props: Props, ref: React.Ref) { return React.cloneElement(elem, { ...rest, - ref: - "ref" in elem - ? mergeRefs([elem.ref as React.MutableRefObject, ref]) - : ref, + ref: elem.props.ref ? mergeRefs([elem.props.ref, ref]) : ref, onClick, }); } -export default React.forwardRef(CopyToClipboard); +export default CopyToClipboard; diff --git a/app/components/DefaultCollectionInputSelect.tsx b/app/components/DefaultCollectionInputSelect.tsx index e87b5d814c..9016fc1ccb 100644 --- a/app/components/DefaultCollectionInputSelect.tsx +++ b/app/components/DefaultCollectionInputSelect.tsx @@ -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(); @@ -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 = ; } 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 = ( (); + const value = draft ?? model.deprecatedReason ?? ""; + + const handleSave = async () => { + if (readOnly || model.isSaving || draft === undefined) { + return; + } + + const deprecatedReason = draft.trim() || null; + if (deprecatedReason === model.deprecatedReason) { + setDraft(undefined); + return; + } + + try { + await model.save({ deprecatedReason }); + setDraft(undefined); + toast.success(t("Reason saved")); + } catch { + toast.error(t("The reason could not be saved. Please try again.")); + } + }; + + if (readOnly && !model.deprecatedReason) { + return null; + } + + return ( + { + if ( + event.key === "Enter" && + !event.shiftKey && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + event.currentTarget.blur(); + } + }} + /> + ); +}); + +const Input = styled(ContentEditable)` + margin-top: 4px; + + > span { + display: block; + background: transparent; + color: inherit; + -webkit-text-fill-color: currentColor; + white-space: pre-wrap; + + &[data-empty="true"] { + display: block; + } + } +`; diff --git a/app/components/DeprecationNotice.tsx b/app/components/DeprecationNotice.tsx new file mode 100644 index 0000000000..16cec7baad --- /dev/null +++ b/app/components/DeprecationNotice.tsx @@ -0,0 +1,15 @@ +import styled from "styled-components"; +import { s } from "@shared/styles"; +import Notice from "./Notice"; + +/** A deprecation notice with a focus border around its editable reason. */ +export const DeprecationNotice = styled(Notice)` + &:has([contenteditable="true"]:focus) { + outline: 1px solid ${s("inputBorderFocused")}; + } + + > span > span { + flex: 1; + min-width: 0; + } +`; diff --git a/app/components/DesktopEventHandler.tsx b/app/components/DesktopEventHandler.tsx index 28ca23249c..d3f5d9bce5 100644 --- a/app/components/DesktopEventHandler.tsx +++ b/app/components/DesktopEventHandler.tsx @@ -2,7 +2,8 @@ import { useRef, useEffect } from "react"; import { useTranslation } from "react-i18next"; import { useHistory } from "react-router-dom"; import { toast } from "sonner"; -import KeyboardShortcuts from "~/scenes/KeyboardShortcuts"; +import KeyboardShortcuts from "~/components/KeyboardShortcuts"; +import { showDownloadToast } from "~/components/DownloadToast"; import { useDesktopTitlebar } from "~/hooks/useDesktopTitlebar"; import useStores from "~/hooks/useStores"; import Desktop from "~/utils/Desktop"; @@ -29,7 +30,7 @@ export default function DesktopEventHandler() { } hasDisabledUpdateMessage.current = true; - toast.message("An update is ready to install.", { + toast.message(t("An update is ready to install."), { duration: Infinity, dismissible: true, action: { @@ -41,6 +42,8 @@ export default function DesktopEventHandler() { }); }); + Desktop.bridge?.onDownloadComplete?.(showDownloadToast); + Desktop.bridge?.focus(() => { window.document.body.classList.remove("backgrounded"); }); diff --git a/app/components/DialogTitle.tsx b/app/components/DialogTitle.tsx index 5e713a7a7f..1e1a561db8 100644 --- a/app/components/DialogTitle.tsx +++ b/app/components/DialogTitle.tsx @@ -60,7 +60,7 @@ export const DialogTitle = observer(function DialogTitle_({ {icon} - {isDocument ? model.titleWithDefault : model.name} + {isDocument ? model.displayTitle : model.displayName} diff --git a/app/components/Dialogs.tsx b/app/components/Dialogs.tsx index 9ba2071beb..ec0dc5aa90 100644 --- a/app/components/Dialogs.tsx +++ b/app/components/Dialogs.tsx @@ -1,7 +1,7 @@ import { observer } from "mobx-react"; import { Suspense } from "react"; import useStores from "~/hooks/useStores"; -import lazyWithRetry from "~/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; import { DialogProvider } from "./DialogContext"; const Guide = lazyWithRetry(() => import("~/components/Guide")); diff --git a/app/components/DocumentArchiveDialog.tsx b/app/components/DocumentArchiveDialog.tsx new file mode 100644 index 0000000000..a6d95d7b2f --- /dev/null +++ b/app/components/DocumentArchiveDialog.tsx @@ -0,0 +1,53 @@ +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { DeprecationValidation } from "@shared/validations"; +import ConfirmationDialog from "~/components/ConfirmationDialog"; +import Flex from "~/components/Flex"; +import Input from "~/components/Input"; + +interface Props { + count: number; + onSubmit: (reason?: string) => Promise; +} + +/** + * Confirms document archival with an optional reason. + * + * @param props the document count and archive callback. + * @returns the archive confirmation form. + */ +export function DocumentArchiveDialog({ count, onSubmit }: Props) { + const { t } = useTranslation(); + const [reason, setReason] = useState(""); + + const handleSubmit = () => onSubmit(reason.trim() || undefined); + + return ( + + +
+ {count === 1 + ? t( + "Archiving this document will remove it from the collection and search results." + ) + : t( + "Archiving these documents will remove them from their collections and search results." + )} +
+ setReason(event.currentTarget.value)} + maxLength={DeprecationValidation.maxReasonLength} + margin={0} + /> +
+
+ ); +} diff --git a/app/components/DocumentBreadcrumb.tsx b/app/components/DocumentBreadcrumb.tsx index a64161ae92..8d385580c1 100644 --- a/app/components/DocumentBreadcrumb.tsx +++ b/app/components/DocumentBreadcrumb.tsx @@ -37,9 +37,9 @@ export function documentBreadcrumbParts( ): { collection: string | undefined; ancestors: string[] } { let collectionLabel: string | undefined; if (document.isCollectionDeleted) { - collectionLabel = t("Deleted Collection"); - } else if (document.collection?.name) { - collectionLabel = document.collection.name; + collectionLabel = t("Deleted collection"); + } else if (document.collection?.displayName) { + collectionLabel = document.collection.displayName; } return { @@ -52,7 +52,7 @@ export function documentBreadcrumbParts( /** * Returns the breadcrumb path leading up to a document as a plain text - * string. Includes the collection name (or "Deleted Collection" fallback) + * string. Includes the collection name (or "Deleted collection" fallback) * and any ancestor document titles, slash-separated. * * @param document - the document to compute the breadcrumb for. @@ -83,12 +83,16 @@ type Props = { * ancestors are shown. If less than or equal to 0, no items are shown. */ maxDepth?: number; + ref?: React.Ref; }; -function DocumentBreadcrumb( - { document, children, onlyText, maxDepth }: Props, - ref: React.RefObject | null -) { +function DocumentBreadcrumb({ + document, + children, + onlyText, + maxDepth, + ref, +}: Props) { const { collections } = useStores(); const { t } = useTranslation(); const sidebarContext = useLocationSidebarContext(); @@ -135,15 +139,17 @@ function DocumentBreadcrumb( ) : undefined, section: ActiveDocumentSection, visible: !!(collection && can.readDocument), - to: collection - ? { - pathname: collection.path, - state: { sidebarContext }, - } - : "", + // A personal collection has no page to link to. + to: + collection && !collection.isPersonal + ? { + pathname: collection.path, + state: { sidebarContext }, + } + : "", }), createInternalLinkAction({ - name: t("Deleted Collection"), + name: t("Deleted collection"), section: ActiveDocumentSection, visible: document.isCollectionDeleted, to: "", @@ -258,7 +264,7 @@ const CollectionName = observer(function CollectionName_({ {icon} - {collection.name} + {collection.displayName} @@ -334,4 +340,4 @@ const SmallSlash = styled(GoToIcon)` opacity: 0.5; `; -export default observer(React.forwardRef(DocumentBreadcrumb)); +export default observer(DocumentBreadcrumb); diff --git a/app/components/DocumentCard.tsx b/app/components/DocumentCard.tsx index c0b4143640..b471db8121 100644 --- a/app/components/DocumentCard.tsx +++ b/app/components/DocumentCard.tsx @@ -24,7 +24,7 @@ import { DocumentContextMenu } from "~/menus/DocumentContextMenu"; import CollectionIcon from "./Icons/CollectionIcon"; import Text from "./Text"; import Tooltip from "./Tooltip"; -import lazyWithRetry from "~/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; const ReadingTime = lazyWithRetry(() => import("./ReadingTime")); @@ -127,7 +127,7 @@ function DocumentCard(props: Props) { to={{ pathname: document.path, state: { - title: document.titleWithDefault, + title: document.displayTitle, }, }} > @@ -169,8 +169,8 @@ function DocumentCard(props: Props) {
{hasEmojiInTitle - ? document.titleWithDefault.replace(document.icon!, "") - : document.titleWithDefault} + ? document.displayTitle.replace(document.icon!, "") + : document.displayTitle} {isRecentlyUpdated ? ( diff --git a/app/components/DocumentChip.tsx b/app/components/DocumentChip.tsx index 5c45fb46ae..c39eab42fe 100644 --- a/app/components/DocumentChip.tsx +++ b/app/components/DocumentChip.tsx @@ -34,7 +34,7 @@ export const DocumentChip = observer(function DocumentChip_({ const { icon, color } = document; const canPin = usePolicy(pin); const canDocument = usePolicy(document); - const title = document.titleWithDefault; + const title = document.displayTitle; const isEmoji = determineIconType(icon) === IconType.Emoji; // Pins in a collection are governed by the document policy, pins on home by diff --git a/app/components/DocumentContext.tsx b/app/components/DocumentContext.tsx index a5bd9ca81b..a69333b7a8 100644 --- a/app/components/DocumentContext.tsx +++ b/app/components/DocumentContext.tsx @@ -8,13 +8,19 @@ import type { TextStats } from "~/hooks/useTextStats"; import { getTextStats } from "~/hooks/useTextStats"; import type Document from "~/models/Document"; import type { Editor } from "~/editor"; +import type { ConnectionStatus } from "~/utils/multiplayer/CollaborationProvider"; class DocumentContext { /** The current document */ document?: Document; /** The editor instance for this document */ - editor?: Editor; + @observable.ref + editor: Editor | undefined = undefined; + + /** The total number of changes in the currently viewed revision diff */ + @observable + totalChanges: number = 0; /** The ID of the currently focused comment, or null if no comment is focused */ @observable @@ -28,6 +34,22 @@ class DocumentContext { @observable headings: Heading[] = []; + /** The connection status of the collaboration provider */ + @observable + multiplayerStatus: ConnectionStatus | undefined = undefined; + + /** The close code of the collaboration connection, when it was closed with an error */ + @observable + multiplayerErrorCode?: number = undefined; + + /** Whether there are local edits the collaboration server has not confirmed */ + @observable + hasUnsyncedChanges = false; + + /** Whether edits are also stored in the browser, so they survive a reload */ + @observable + hasLocalPersistence = true; + constructor() { makeObservable(this); } @@ -67,11 +89,31 @@ class DocumentContext { this.isEditorInitialized = initialized; }; + @action + setTotalChanges = (totalChanges: number) => { + this.totalChanges = totalChanges; + }; + @action setFocusedCommentId = (commentId: string | null) => { this.focusedCommentId = commentId; }; + @action + setMultiplayerStatus = (status: ConnectionStatus, errorCode?: number) => { + this.multiplayerStatus = status; + this.multiplayerErrorCode = errorCode; + }; + + @action + setMultiplayerSyncState = ( + hasUnsyncedChanges: boolean, + hasLocalPersistence: boolean + ) => { + this.hasUnsyncedChanges = hasUnsyncedChanges; + this.hasLocalPersistence = hasLocalPersistence; + }; + @action updateState = () => { this.editorDoc = this.editor?.view.state.doc; diff --git a/app/components/DocumentExplorer/DocumentExplorer.tsx b/app/components/DocumentExplorer/DocumentExplorer.tsx index daa6dccde1..90b659c2f1 100644 --- a/app/components/DocumentExplorer/DocumentExplorer.tsx +++ b/app/components/DocumentExplorer/DocumentExplorer.tsx @@ -45,13 +45,13 @@ type Props = { const VERTICAL_PADDING = 6; const HORIZONTAL_PADDING = 24; -const innerElementType = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(function innerElementType( - { style, ...rest }: React.HTMLAttributes, - ref -) { +function innerElementType({ + style, + ref, + ...rest +}: React.HTMLAttributes & { + ref?: React.Ref; +}) { return (
); -}); +} function DocumentExplorer({ onSubmit, @@ -77,6 +77,8 @@ function DocumentExplorer({ const theme = useTheme(); const [searchTerm, setSearchTerm] = React.useState(); + // Defer filtering so typing in the search input stays responsive. + const deferredSearchTerm = React.useDeferredValue(searchTerm); const [selectedNode, selectNode] = React.useState( () => { if (!defaultValue) { @@ -143,8 +145,8 @@ function DocumentExplorer({ : [item]; } - return searchTerm - ? searchIndex.search(searchTerm) + return deferredSearchTerm + ? searchIndex.search(deferredSearchTerm) : items.flatMap(includeDescendants); } @@ -161,7 +163,7 @@ function DocumentExplorer({ setTimeout(() => listRef.current?.scrollToItem(index, "center"), 50); } } - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [defaultValue]); const baseDepth = nodes.reduce( (min, node) => (node.depth ? Math.min(min, node.depth) : min), @@ -307,7 +309,7 @@ function DocumentExplorer({ .join(" / "); } - return searchTerm ? ( + return deferredSearchTerm ? ( scrollNodeIntoView(activeNode), 0); diff --git a/app/components/DocumentExplorer/DocumentExplorerNode.tsx b/app/components/DocumentExplorer/DocumentExplorerNode.tsx index a47984d48c..9dfc313e8d 100644 --- a/app/components/DocumentExplorer/DocumentExplorerNode.tsx +++ b/app/components/DocumentExplorer/DocumentExplorerNode.tsx @@ -33,25 +33,25 @@ type Props = { onClick: (ev: React.MouseEvent) => void; /** Fired when the node is double-clicked to submit the current selection. */ onDoubleClick: (ev: React.MouseEvent) => void; + /** Ref to the node element. */ + ref?: React.Ref; }; -function DocumentExplorerNode( - { - selected, - active, - style, - expanded, - icon, - title, - depth, - hasChildren, - onDisclosureClick, - onPointerMove, - onClick, - onDoubleClick, - }: Props, - ref: React.RefObject -) { +function DocumentExplorerNode({ + selected, + active, + style, + expanded, + icon, + title, + depth, + hasChildren, + onDisclosureClick, + onPointerMove, + onClick, + onDoubleClick, + ref, +}: Props) { const { t } = useTranslation(); const DISCLOSURE = 24; const width = (depth + 2) * DISCLOSURE; @@ -148,4 +148,4 @@ export const Node = styled.span<{ `} `; -export default observer(React.forwardRef(DocumentExplorerNode)); +export default observer(DocumentExplorerNode); diff --git a/app/components/DocumentListItem.tsx b/app/components/DocumentListItem.tsx index cb1e60360b..59288cad10 100644 --- a/app/components/DocumentListItem.tsx +++ b/app/components/DocumentListItem.tsx @@ -1,7 +1,3 @@ -import { - useFocusEffect, - useRovingTabIndex, -} from "@getoutline/react-roving-tabindex"; import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; @@ -35,6 +31,7 @@ import { ActionContextProvider } from "~/hooks/useActionContext"; import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction"; import { ContextMenu } from "./Menu/ContextMenu"; import { useDocumentActiveModels } from "~/hooks/useDocumentActiveModels"; +import { useRovingTabIndex } from "~/hooks/useRovingTabIndex"; type Props = { document: Document; @@ -45,6 +42,7 @@ type Props = { showPublished?: boolean; showDraft?: boolean; showLastViewed?: boolean; + ref?: React.RefObject; }; const SEARCH_RESULT_REGEX = /]*>(.*?)<\/b>/gi; @@ -54,27 +52,25 @@ function replaceResultMarks(tag: string) { return tag.replace(new RegExp(SEARCH_RESULT_REGEX.source), "$1"); } -function DocumentListItem( - props: Props, - ref: React.RefObject -) { +function DocumentListItem(props: Props) { const { t } = useTranslation(); const user = useCurrentUser(); const theme = useTheme(); const locationSidebarContext = useLocationSidebarContext(); const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean(); + const [isInteractive, setIsInteractive] = React.useState(false); const isMobile = useMobile(); const selection = useModelSelection(); const iconRef = React.useRef(null); + const restoreFocus = React.useRef(false); - let itemRef: React.Ref = + let itemRef: React.RefObject = React.useRef(null); - if (ref) { - itemRef = ref; + if (props.ref) { + itemRef = props.ref; } const { focused, ...rovingTabIndex } = useRovingTabIndex(itemRef, false); - useFocusEffect(focused, itemRef); const { document, @@ -85,6 +81,7 @@ function DocumentListItem( showLastViewed = true, highlight, context, + ref: _ref, ...rest } = props; const queryIsInTitle = @@ -137,7 +134,6 @@ function DocumentListItem( document.asNavigationNode, 0, document, - false, false ); @@ -150,125 +146,161 @@ function DocumentListItem( [itemRef, draggableRef] ); + React.useLayoutEffect(() => { + if (isInteractive && restoreFocus.current) { + itemRef.current?.focus(); + restoreFocus.current = false; + } + }, [isInteractive]); + + const handleFocusCapture = (event: React.FocusEvent) => { + if (!isInteractive && event.target === event.currentTarget) { + restoreFocus.current = true; + setIsInteractive(true); + } + }; + + const link = ( + setIsInteractive(true)} + onFocusCapture={handleFocusCapture} + > + + + {selectable && ( + + {isSelected && } + + )} + + {document.icon ? ( + + ) : ( + + )} + + + + + + {document.isBadgedNew && document.createdBy?.id !== user.id && ( + <Badge yellow>{t("New")}</Badge> + )} + {document.isDraft && + showDraft && + (isInteractive ? ( + <Tooltip content={t("Only visible to you")}> + <Badge>{t("Draft")}</Badge> + </Tooltip> + ) : ( + <Badge>{t("Draft")}</Badge> + ))} + {canStar && !isMobile && ( + <StarButton + document={document} + tooltipDisabled={!isInteractive} + /> + )} + </Heading> + + {!queryIsInTitle && ( + <ResultContext + text={context} + highlight={highlight ? SEARCH_RESULT_REGEX : undefined} + processResult={replaceResultMarks} + /> + )} + <DocumentMeta + document={document} + showCollection={showCollection} + showPublished={showPublished} + showParentDocuments={showParentDocuments} + showLastViewed={showLastViewed} + /> + </Content> + </Flex> + {document.destroysInDays !== undefined && ( + <RetentionBadge> + {isInteractive ? ( + <Tooltip + content={t( + "Will be permanently deleted in {{ count }} days unless restored", + { count: document.destroysInDays } + )} + > + <Badge> + {t("{{ count }} days", { count: document.destroysInDays })} + </Badge> + </Tooltip> + ) : ( + <Badge> + {t("{{ count }} days", { count: document.destroysInDays })} + </Badge> + )} + </RetentionBadge> + )} + <Actions> + {isInteractive && ( + <DocumentMenu + document={document} + onOpen={handleMenuOpen} + onClose={handleMenuClose} + /> + )} + </Actions> + </DocumentLink> + ); + return ( <ActionContextProvider value={{ activeModels }}> - <ContextMenu - action={contextMenuAction} - ariaLabel={t("Document options")} - onOpen={handleMenuOpen} - onClose={handleMenuClose} - > - <DocumentLink - ref={mergedRef} - dir={document.dir} - $isStarred={document.isStarred} - $isDragging={isDragging} - $menuOpen={menuOpen} - $selectable={selectable} - to={{ - pathname: documentPath(document), - search: highlight - ? `?q=${encodeURIComponent(highlight)}` - : undefined, - state: { - title: document.titleWithDefault, - sidebarContext, - }, - }} - {...rest} - {...rovingTabIndex} - onClick={handleLinkClick} - onMouseDown={handleLinkMouseDown} + {isInteractive ? ( + <ContextMenu + action={contextMenuAction} + ariaLabel={t("Document options")} + onOpen={handleMenuOpen} + onClose={handleMenuClose} > - <Flex gap={4} auto> - <IconWrapper ref={iconRef}> - {selectable && ( - <SelectButton - role="checkbox" - aria-checked={isSelected} - aria-label={t("Select")} - $checked={isSelected} - $visible={isSelecting} - tabIndex={-1} - > - {isSelected && <CheckmarkIcon size={16} />} - </SelectButton> - )} - <DocumentIconWrapper $dimmed={isSelecting}> - {document.icon ? ( - <Icon - value={document.icon} - color={document.color ?? undefined} - initial={document.initial} - /> - ) : ( - <DocumentIcon - outline={document.isDraft} - color={theme.textSecondary} - /> - )} - </DocumentIconWrapper> - </IconWrapper> - <Content> - <Heading dir={document.dir}> - <Title - text={document.titleWithDefault} - highlight={highlight} - dir={document.dir} - /> - {document.isBadgedNew && document.createdBy?.id !== user.id && ( - <Badge yellow>{t("New")}</Badge> - )} - {document.isDraft && showDraft && ( - <Tooltip content={t("Only visible to you")} placement="top"> - <Badge>{t("Draft")}</Badge> - </Tooltip> - )} - {canStar && !isMobile && <StarButton document={document} />} - </Heading> - - {!queryIsInTitle && ( - <ResultContext - text={context} - highlight={highlight ? SEARCH_RESULT_REGEX : undefined} - processResult={replaceResultMarks} - /> - )} - <DocumentMeta - document={document} - showCollection={showCollection} - showPublished={showPublished} - showParentDocuments={showParentDocuments} - showLastViewed={showLastViewed} - /> - </Content> - </Flex> - {document.destroysInDays !== undefined && ( - <RetentionBadge> - <Tooltip - content={t( - "Will be permanently deleted in {{ count }} days unless restored", - { count: document.destroysInDays } - )} - placement="top" - > - <Badge> - {t("{{ count }} days", { - count: document.destroysInDays, - })} - </Badge> - </Tooltip> - </RetentionBadge> - )} - <Actions> - <DocumentMenu - document={document} - onOpen={handleMenuOpen} - onClose={handleMenuClose} - /> - </Actions> - </DocumentLink> - </ContextMenu> + {link} + </ContextMenu> + ) : ( + link + )} </ActionContextProvider> ); } @@ -472,4 +504,4 @@ const ResultContext = styled(Highlight)` overflow: hidden; `; -export default observer(React.forwardRef(DocumentListItem)); +export default observer(DocumentListItem); diff --git a/app/components/DocumentMeta.tsx b/app/components/DocumentMeta.tsx index 8e0180938d..32103aa3d7 100644 --- a/app/components/DocumentMeta.tsx +++ b/app/components/DocumentMeta.tsx @@ -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> ) : ( diff --git a/app/components/DownloadToast.tsx b/app/components/DownloadToast.tsx new file mode 100644 index 0000000000..d13cf9b5d3 --- /dev/null +++ b/app/components/DownloadToast.tsx @@ -0,0 +1,71 @@ +import { t } from "i18next"; +import { useCallback } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; +import Button from "~/components/Button"; +import Flex from "~/components/Flex"; +import Desktop from "~/utils/Desktop"; + +type DownloadedFile = { + /** The user facing name of the downloaded file. */ + fileName: string; + /** The absolute path the file was saved to. */ + filePath: string; +}; + +/** + * Displays a toast notifying that a file finished downloading, with the file + * name and actions to open the file or reveal it in the file manager. Desktop + * app only. + * + * @param file the name and path of the downloaded file. + */ +export function showDownloadToast(file: DownloadedFile) { + const toastId = `download-${file.filePath}`; + + toast.message(t("Download complete"), { + id: toastId, + description: <DownloadToastDescription file={file} toastId={toastId} />, + }); +} + +function DownloadToastDescription({ + file, + toastId, +}: { + file: DownloadedFile; + toastId: string; +}) { + const { t } = useTranslation(); + + const handleOpen = useCallback(() => { + toast.dismiss(toastId); + void Desktop.bridge?.openDownload?.(file.filePath); + }, [file.filePath, toastId]); + + const handleShowInFolder = useCallback(() => { + toast.dismiss(toastId); + void Desktop.bridge?.showDownloadInFolder?.(file.filePath); + }, [file.filePath, toastId]); + + // The name given to the file manager differs by operating system. + const showInFolderLabel = Desktop.isMacApp() + ? t("Show in Finder") + : Desktop.isWindowsApp() + ? t("Show in Explorer") + : t("Show in folder"); + + return ( + <Flex column gap={8}> + {file.fileName} + <Flex gap={4}> + <Button onClick={handleOpen} neutral> + {t("Open")} + </Button> + <Button onClick={handleShowInFolder} neutral> + {showInFolderLabel} + </Button> + </Flex> + </Flex> + ); +} diff --git a/app/components/EditableTitle.tsx b/app/components/EditableTitle.tsx index 2a9bcfdce6..9709f3eead 100644 --- a/app/components/EditableTitle.tsx +++ b/app/components/EditableTitle.tsx @@ -20,6 +20,7 @@ type Props = Omit<React.InputHTMLAttributes<HTMLInputElement>, "onSubmit"> & { maxLength?: number; /** The default editing state. */ isEditing?: boolean; + ref?: React.Ref<RefHandle>; }; export type RefHandle = { @@ -27,10 +28,15 @@ export type RefHandle = { setIsEditing: (isEditing: boolean) => void; }; -function EditableTitle( - { title, onSubmit, canUpdate, onEditing, onCancel, ...rest }: Props, - ref: React.RefObject<RefHandle> -) { +function EditableTitle({ + title, + onSubmit, + canUpdate, + onEditing, + onCancel, + ref, + ...rest +}: Props) { const [isEditing, setIsEditing] = React.useState(rest.isEditing || false); const [originalValue, setOriginalValue] = React.useState(title); const [value, setValue] = React.useState(title); @@ -190,4 +196,4 @@ const Input = styled.input` } `; -export default React.forwardRef(EditableTitle); +export default EditableTitle; diff --git a/app/components/Editor.tsx b/app/components/Editor.tsx index fd127de3c3..8ca37e1b9a 100644 --- a/app/components/Editor.tsx +++ b/app/components/Editor.tsx @@ -1,13 +1,12 @@ import { difference } from "es-toolkit/compat"; import { observer } from "mobx-react"; import * as React from "react"; -import { useTranslation } from "react-i18next"; -import { toast } from "sonner"; import { mergeRefs } from "react-merge-refs"; import type { Optional } from "utility-types"; import EditorContainer from "@shared/editor/components/Styles"; import { AttachmentPreset } from "@shared/types"; -import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; +import { ProsemirrorHelper } from "~/models/helpers/ProsemirrorHelper"; +import AsyncEditor from "~/components/AsyncEditor"; import ClickablePadding from "~/components/ClickablePadding"; import ErrorBoundary from "~/components/ErrorBoundary"; import PlaceholderDocument from "~/components/PlaceholderDocument"; @@ -17,11 +16,8 @@ import useEditorClickHandlers from "~/hooks/useEditorClickHandlers"; import useEmbeds from "~/hooks/useEmbeds"; import useStores from "~/hooks/useStores"; import { uploadFile, uploadFileFromUrl } from "~/utils/files"; -import lazyWithRetry from "~/utils/lazyWithRetry"; import useShare from "@shared/hooks/useShare"; -const LazyLoadedEditor = lazyWithRetry(() => import("~/editor")); - export type Props = Optional< EditorProps, "placeholder" | "defaultValue" | "onClickLink" | "embeds" | "extensions" @@ -32,30 +28,14 @@ export type Props = Optional< editorStyle?: React.CSSProperties; }; -function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) { - const { - id, - onChange, - onCreateCommentMark, - onDeleteCommentMark, - onFileUploadStart, - onFileUploadStop, - } = props; +function Editor({ ref, ...props }: Props & { ref?: React.Ref<SharedEditor> }) { + const { id, onChange, onCreateCommentMark, onDeleteCommentMark } = props; const { comments } = useStores(); const { shareId } = useShare(); - const { t } = useTranslation(); const embeds = useEmbeds(!shareId); - const localRef = React.useRef<SharedEditor>(); + const localRef = React.useRef<SharedEditor | null>(null); const preferences = useCurrentUser({ rejectOnEmpty: false })?.preferences; - const previousCommentIds = React.useRef<string[]>(); - - // Upload progress tracking for delayed toast - const progressMap = React.useMemo(() => new Map<string, number>(), []); - const uploadState = React.useRef<{ - toastId?: string | number; - timeoutId?: ReturnType<typeof setTimeout>; - progress: Map<string, number>; - }>({ progress: progressMap }); + const previousCommentIds = React.useRef<string[] | undefined>(undefined); const handleUploadFile = React.useCallback( async ( @@ -82,49 +62,6 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) { const { handleClickLink } = useEditorClickHandlers({ shareId }); - // Show toast only after uploads have been running for 2 seconds - const handleFileUploadStart = React.useCallback(() => { - uploadState.current.timeoutId = setTimeout(() => { - uploadState.current.toastId = toast.loading( - t("Uploading… {{ progress }}%", { progress: 0 }) - ); - }, 2000); - onFileUploadStart?.(); - }, [onFileUploadStart, t]); - - const handleFileUploadProgress = React.useCallback( - (fileId: string, fractionComplete: number) => { - uploadState.current.progress.set(fileId, fractionComplete); - - // Calculate average progress across all files - const progressValues = Array.from(uploadState.current.progress.values()); - const avgProgress = - progressValues.reduce((a, b) => a + b, 0) / progressValues.length; - const percent = Math.round(avgProgress * 100); - - // Update toast if visible - if (uploadState.current.toastId) { - toast.loading(t("Uploading… {{ progress }}%", { progress: percent }), { - id: uploadState.current.toastId, - }); - } - }, - [t] - ); - - const handleFileUploadStop = React.useCallback(() => { - if (uploadState.current.timeoutId) { - clearTimeout(uploadState.current.timeoutId); - uploadState.current.timeoutId = undefined; - } - if (uploadState.current.toastId) { - toast.dismiss(uploadState.current.toastId); - uploadState.current.toastId = undefined; - } - uploadState.current.progress.clear(); - onFileUploadStop?.(); - }, [onFileUploadStop]); - const focusAtEnd = React.useCallback(() => { localRef?.current?.focusAtEnd(); }, [localRef]); @@ -202,9 +139,12 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) { [updateComments] ); - const paragraphs = React.useMemo(() => { + // Read-only content that needs no node views or plugins is rendered from + // the schema alone, avoiding an editor view per instance. + const staticHTML = React.useMemo(() => { if (props.readOnly && typeof props.value === "object") { - return ProsemirrorHelper.getPlainParagraphs(props.value); + const node = ProsemirrorHelper.toStaticNode(props.value); + return node ? ProsemirrorHelper.toHTML(node) : undefined; } return undefined; }, [props.readOnly, props.value]); @@ -212,22 +152,21 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) { return ( <ErrorBoundary component="div" reloadOnChunkMissing> <> - {paragraphs ? ( + {staticHTML !== undefined ? ( <EditorContainer $rtl={props.dir === "rtl"} grow={props.grow} style={props.style} + className={props.className} editorStyle={props.editorStyle} commenting={!!props.onClickCommentMark} lang={props.lang} + readOnly > - <div className="ProseMirror"> - {paragraphs.map((paragraph, index) => ( - <p key={index} dir="auto"> - {paragraph.content?.map((content) => content.text)} - </p> - ))} - </div> + <div + className="ProseMirror" + dangerouslySetInnerHTML={{ __html: staticHTML }} + /> </EditorContainer> ) : ( // The boundary must live between the lazy editor and any ancestor @@ -235,7 +174,7 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) { // React 18 would hide mounted ancestors and destroy their effects, // re-running provider setup and ref callbacks in a loop. <React.Suspense fallback={<PlaceholderDocument delay={500} />}> - <LazyLoadedEditor + <AsyncEditor key={props.extensions?.length || 0} ref={mergeRefs([ref, localRef, handleRefChanged])} uploadFile={handleUploadFile} @@ -244,9 +183,6 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) { {...props} onClickLink={handleClickLink} onChange={handleChange} - onFileUploadStart={handleFileUploadStart} - onFileUploadStop={handleFileUploadStop} - onFileUploadProgress={handleFileUploadProgress} placeholder={props.placeholder || ""} defaultValue={props.defaultValue || ""} /> @@ -265,4 +201,4 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) { ); } -export default observer(React.forwardRef(Editor)); +export default observer(Editor); diff --git a/app/components/EmojiDialog/Components.tsx b/app/components/EmojiDialog/Components.tsx index d26c940048..c39c5e8856 100644 --- a/app/components/EmojiDialog/Components.tsx +++ b/app/components/EmojiDialog/Components.tsx @@ -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; diff --git a/app/components/EmojiDialog/EmojiCreateDialog.tsx b/app/components/EmojiDialog/EmojiCreateDialog.tsx index eaa4fcc7ee..820a142ee8 100644 --- a/app/components/EmojiDialog/EmojiCreateDialog.tsx +++ b/app/components/EmojiDialog/EmojiCreateDialog.tsx @@ -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 } diff --git a/app/components/ErrorBoundary.tsx b/app/components/ErrorBoundary.tsx index 570d535deb..2d2160cbc6 100644 --- a/app/components/ErrorBoundary.tsx +++ b/app/components/ErrorBoundary.tsx @@ -14,7 +14,7 @@ import Text from "~/components/Text"; import env from "~/env"; import Logger from "~/utils/Logger"; import isCloudHosted from "~/utils/isCloudHosted"; -import { isStaleChunkError } from "~/utils/lazyWithRetry"; +import { isStaleChunkError } from "@shared/utils/lazyWithRetry"; import Storage from "@shared/utils/Storage"; import { deleteAllDatabases } from "~/utils/developer"; import Flex from "./Flex"; @@ -145,7 +145,7 @@ class ErrorBoundaryClass extends React.Component<Props> { <> <PageTitle title={t("Module failed to load")} /> <Heading> - <Trans>Loading Failed</Trans> + <Trans>Loading failed</Trans> </Heading> </> )} @@ -167,9 +167,9 @@ class ErrorBoundaryClass extends React.Component<Props> { <Component> {showTitle && ( <> - <PageTitle title={t("Something Unexpected Happened")} /> + <PageTitle title={t("Something unexpected happened")} /> <Heading> - <Trans>Something Unexpected Happened</Trans> + <Trans>Something unexpected happened</Trans> </Heading> </> )} diff --git a/app/components/Export/ExportDialog.tsx b/app/components/Export/ExportDialog.tsx index 80e1ea5dae..d1c299852d 100644 --- a/app/components/Export/ExportDialog.tsx +++ b/app/components/Export/ExportDialog.tsx @@ -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 diff --git a/app/components/Facepile.tsx b/app/components/Facepile.tsx index 62a36e09cc..e257f06670 100644 --- a/app/components/Facepile.tsx +++ b/app/components/Facepile.tsx @@ -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)})` }), diff --git a/app/components/Fade.tsx b/app/components/Fade.tsx index a3de3c4eb4..8e0aeccfd2 100644 --- a/app/components/Fade.tsx +++ b/app/components/Fade.tsx @@ -12,7 +12,7 @@ const Fade = styled.span<{ timing?: number | string }>` `; type Props = { - children?: JSX.Element | null; + children?: React.JSX.Element | null; /** If true, children will be animated. */ animate: boolean; }; diff --git a/app/components/FilterOptions.tsx b/app/components/FilterOptions.tsx index 03e0a4df13..1475749137 100644 --- a/app/components/FilterOptions.tsx +++ b/app/components/FilterOptions.tsx @@ -3,6 +3,8 @@ import { CheckmarkIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; +import breakpoint from "styled-components-breakpoint"; +import { MOBILE_TOUCH_TARGET } from "@shared/constants"; import { s } from "@shared/styles"; import type { FetchPageParams } from "~/stores/base/Store"; import Button, { Inner } from "~/components/Button"; @@ -63,6 +65,8 @@ const FilterOptions = ({ selectedKeys.includes(option.key) ); const [query, setQuery] = React.useState(""); + // Defer filtering so typing in the search input stays responsive. + const deferredQuery = React.useDeferredValue(query); const selectedLabel = selectedItems.length ? selectedItems.map((selected) => selected.label).join(", ") @@ -118,9 +122,9 @@ const FilterOptions = ({ ); const filteredOptions = React.useMemo(() => { - const normalizedQuery = deburr(query.toLowerCase()); + const normalizedQuery = deburr(deferredQuery.toLowerCase()); - const filtered = query + const filtered = deferredQuery ? options.filter((option) => deburr(option.label).toLowerCase().includes(normalizedQuery) ) @@ -140,7 +144,7 @@ const FilterOptions = ({ // If both have the same selection state and there's a query, // sort options starting with query first - if (query) { + if (deferredQuery) { const aStartsWith = deburr(a.label) .toLowerCase() .startsWith(normalizedQuery); @@ -158,7 +162,7 @@ const FilterOptions = ({ return 0; }); - }, [options, query, selectedKeys]); + }, [options, deferredQuery, selectedKeys]); const handleKeyDown = React.useCallback( (ev: React.KeyboardEvent) => { @@ -357,6 +361,16 @@ export const StyledButton = styled(Button)` line-height: 28px; min-height: auto; } + + ${breakpoint("mobile", "tablet")` + && { + height: ${MOBILE_TOUCH_TARGET}px; + } + + && ${Inner} { + min-height: ${MOBILE_TOUCH_TARGET}px; + } + `}; `; export default FilterOptions; diff --git a/app/components/Header.tsx b/app/components/Header.tsx index 1d7ad66ce8..b4548b65b4 100644 --- a/app/components/Header.tsx +++ b/app/components/Header.tsx @@ -1,24 +1,28 @@ +import { useDirection } from "@radix-ui/react-direction"; import { throttle } from "es-toolkit/compat"; import { observer } from "mobx-react"; -import { CloseIcon, MenuIcon } from "outline-icons"; +import { CloseIcon, MenuIcon, SidebarIcon } from "outline-icons"; import { transparentize } from "polished"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { mergeRefs } from "react-merge-refs"; -import styled from "styled-components"; +import styled, { css } from "styled-components"; +import type { DefaultTheme } from "styled-components"; import breakpoint from "styled-components-breakpoint"; import useMeasure from "react-use-measure"; -import { HEADER_HEIGHT } from "@shared/constants"; -import { depths, s } from "@shared/styles"; -import { supportsPassiveListener } from "@shared/utils/browser"; +import { HEADER_HEIGHT, MOBILE_TOUCH_TARGET } from "@shared/constants"; +import { depths, hover, s } from "@shared/styles"; +import { metaDisplay } from "@shared/utils/keyboard"; import Button from "~/components/Button"; import Fade from "~/components/Fade"; import Flex from "~/components/Flex"; +import { useSidebarCollapsed } from "~/components/SidebarCollapsedContext"; import { useSplitView } from "~/components/SplitView/context"; import Tooltip from "~/components/Tooltip"; import useEventListener from "~/hooks/useEventListener"; import useMobile from "~/hooks/useMobile"; import useStores from "~/hooks/useStores"; +import useWindowScrollbarWidth from "~/hooks/useWindowScrollbarWidth"; import { draggableOnDesktop, fadeOnDesktopBackgrounded } from "~/styles"; import Desktop from "~/utils/Desktop"; import history from "~/utils/history"; @@ -35,18 +39,26 @@ type Props = { | React.ReactNode; hasSidebar?: boolean; className?: string; + ref?: React.Ref<HTMLDivElement>; }; -function Header( - { left, title, actions, hasSidebar, className }: Props, - ref: React.RefObject<HTMLDivElement> | null -) { +function Header({ left, title, actions, hasSidebar, className, ref }: Props) { const { ui } = useStores(); const { t } = useTranslation(); const { pane, isSplitView } = useSplitView(); const isMobile = useMobile(); + const sidebarCollapsed = useSidebarCollapsed(); const hasMobileSidebar = hasSidebar && isMobile; + const hasDesktopSidebar = hasSidebar && !isMobile; const [internalMeasureRef, size] = useMeasure(); + const scrollbarWidth = useWindowScrollbarWidth() ?? 0; + const direction = useDirection(); + // The body spans the full viewport, so a header at the window end extends past the visible area. + const isAtWindowEnd = + size.width > 0 && + (direction === "rtl" + ? size.left <= 1 + : size.right >= window.innerWidth - 1); const [breadcrumbsMeasureRef, breadcrumbsSize] = useMeasure(); const passThrough = !actions && !left && !title && !isSplitView; @@ -60,12 +72,7 @@ function Header( [] ); - useEventListener( - "scroll", - handleScroll, - window, - supportsPassiveListener ? { passive: true } : { capture: false } - ); + useEventListener("scroll", handleScroll, window, { passive: true }); const handleClickTitle = React.useCallback(() => { window.scrollTo({ @@ -95,7 +102,30 @@ function Header( className={className} $passThrough={passThrough} $insetTitleAdjust={ui.sidebarIsClosed && Desktop.hasInsetTitlebar()} + $scrollbarInset={isAtWindowEnd ? scrollbarWidth : undefined} > + {hasDesktopSidebar && ( + <SidebarToggle + $visible={sidebarCollapsed} + aria-hidden={!sidebarCollapsed} + > + <Tooltip + content={t("Toggle sidebar")} + shortcut={`${metaDisplay}+.`} + side="bottom" + > + <SidebarToggleButton + $visible={sidebarCollapsed} + aria-label={t("Expand sidebar")} + onClick={ui.toggleCollapsedSidebar} + icon={<SidebarIcon />} + tabIndex={sidebarCollapsed ? undefined : -1} + neutral + borderOnHover + /> + </Tooltip> + </SidebarToggle> + )} {left || hasMobileSidebar ? ( <Breadcrumbs ref={setBreadcrumbRef}> {hasMobileSidebar && ( @@ -135,6 +165,26 @@ function Header( ); } +/** Height of the fade at the bottom of the mobile header background. */ +const HeaderFadeHeight = 64; + +/** Eased mask stops for the header fade, so it has no visible start or end. */ +const headerFadeStops = [1, 0.85, 0.5, 0.15, 0] + .map( + (opacity, index, stops) => + `rgb(0 0 0 / ${opacity}) calc(100% - ${HeaderFadeHeight * (1 - index / (stops.length - 1))}px)` + ) + .join(", "); + +/** Raised capsule that holds header buttons on mobile, like an iOS toolbar. */ +const mobilePill = css` + background: ${s("menuBackground")}; + box-shadow: + 0 0 0 1px ${s("divider")}, + 0 4px 12px rgb(0 0 0 / 8%); + border-radius: ${MOBILE_TOUCH_TARGET / 2}px; +`; + const Breadcrumbs = styled("div")` flex-grow: 1; flex-basis: 0; @@ -143,6 +193,20 @@ const Breadcrumbs = styled("div")` padding-inline: 0 8px; display: flex; + ${breakpoint("mobile", "tablet")` + gap: 8px; + + && [data-variant] { + ${mobilePill} + } + + && [data-variant]:${hover}:not(:disabled), + && [data-variant][aria-expanded="true"] { + ${mobilePill} + background: ${s("buttonNeutralBackground")}; + } + `}; + ${breakpoint("tablet")` min-width: auto; `}; @@ -156,6 +220,45 @@ const Actions = styled(Flex)` gap: 8px; margin-inline-start: 8px; + ${breakpoint("mobile", "tablet")` + flex: 0 0 auto; + gap: 0; + margin-inline-start: auto; + + &:not(:empty) { + ${mobilePill} + padding-inline: 10px; + } + + /* Touch targets overlap so icons sit closer than their 44px hit areas. */ + & > * { + margin-inline: -4px; + } + + && [data-variant] { + background: transparent; + box-shadow: none; + } + + && [data-variant="primary"] { + color: ${s("accent")}; + } + + && [data-variant="primary"]:disabled { + color: ${s("textTertiary")}; + + svg { + fill: currentColor; + } + } + + && [data-variant]:${hover}:not(:disabled), + && [data-variant][aria-expanded="true"] { + background: ${s("buttonNeutralBackground")}; + box-shadow: none; + } + `}; + ${breakpoint("tablet")` position: unset; `}; @@ -164,8 +267,20 @@ const Actions = styled(Flex)` type WrapperProps = { $passThrough?: boolean; $insetTitleAdjust?: boolean; + /** Width of the window scrollbar that the end of the header falls behind. */ + $scrollbarInset?: number; }; +/** + * Padding for the end of the header that clears the window scrollbar. The + * removed-body-scroll-bar-size variable is set while a modal locks the page + * scroll, which keeps the padding constant as the scrollbar is removed. + */ +const endPadding = (base: number) => (props: WrapperProps) => + props.$scrollbarInset === undefined + ? `${base}px` + : `calc(${base}px + ${props.$scrollbarInset}px + var(--removed-body-scroll-bar-size, 0px))`; + const Wrapper = styled(Flex)<WrapperProps>` top: 0; z-index: ${depths.header}; @@ -183,7 +298,8 @@ const Wrapper = styled(Flex)<WrapperProps>` backdrop-filter: blur(20px); `}; - padding: 12px 16px; + padding: 6px 16px; + padding-inline-end: ${endPadding(16)}; transform: translate3d(0, 0, 0); min-height: ${HEADER_HEIGHT}px; justify-content: flex-start; @@ -207,8 +323,38 @@ const Wrapper = styled(Flex)<WrapperProps>` display: none; } + ${breakpoint("mobile", "tablet")` + ${(props: WrapperProps & { theme: DefaultTheme }) => + !props.$passThrough && + ` + background: transparent; + backdrop-filter: none; + + /* The blurred background extends past the header and fades out, so content blends under it. */ + &::before { + content: ""; + position: absolute; + inset: 0 0 -${HeaderFadeHeight / 2}px; + z-index: -1; + pointer-events: none; + background: ${transparentize(0.2, props.theme.background)}; + backdrop-filter: blur(20px); + mask-image: linear-gradient(to bottom, ${headerFadeStops}); + } + + /* A stuck tab bar continues the header, so the header is solid above it. */ + body:has([data-sticky-tabs][data-stuck]) &::before { + inset: 0; + background: ${props.theme.background}; + backdrop-filter: none; + mask-image: none; + } + `} + `}; + ${breakpoint("tablet")` padding: 12px; + padding-inline-end: ${endPadding(12)}; ${(props: WrapperProps) => props.$insetTitleAdjust && `padding-left: 64px;`} `}; `; @@ -239,7 +385,6 @@ const Title = styled("div")` `; const MobileMenuButton = styled(Button)` - margin-right: 8px; pointer-events: auto; @media print { @@ -247,8 +392,37 @@ const MobileMenuButton = styled(Button)` } `; +const SidebarToggle = styled("div")<{ $visible: boolean }>` + flex-shrink: 0; + overflow: hidden; + width: ${(props) => (props.$visible ? 32 : 0)}px; + margin-inline-end: ${(props) => (props.$visible ? 8 : 0)}px; + pointer-events: ${(props) => (props.$visible ? "auto" : "none")}; + transition: + width 150ms ease-out, + margin 150ms ease-out; + + @media print { + display: none; + } +`; + +const SidebarToggleButton = styled(Button)<{ $visible: boolean }>` + color: ${s("textTertiary")}; + opacity: ${(props) => (props.$visible ? 1 : 0)}; + transition: opacity 150ms ease-out; + + &:hover:not(:disabled) { + color: ${s("textSecondary")}; + } + + [dir="rtl"] & svg { + transform: scaleX(-1); + } +`; + const CloseSplitPaneButton = styled(Button)` pointer-events: auto; `; -export default observer(React.forwardRef(Header)); +export default observer(Header); diff --git a/app/components/Heading.ts b/app/components/Heading.ts index 940df0a7da..7660c9afdd 100644 --- a/app/components/Heading.ts +++ b/app/components/Heading.ts @@ -1,13 +1,21 @@ import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; +import { IconTitleWrapper } from "@shared/components/Icon"; const Heading = styled.h1<{ as?: string; centered?: boolean }>` display: flex; align-items: center; user-select: none; - ${(props) => (props.as ? "" : "margin-top: 8vh; font-weight: 600;")} + ${(props) => (props.as ? "" : "margin-top: 16px; font-weight: 600;")} ${(props) => (props.centered ? "text-align: center;" : "")} + /* On mobile the title icon sits above the title, so leave room for it. */ + ${breakpoint("mobile", "tablet")` + &:has(> ${IconTitleWrapper}) { + margin-top: 60px; + } + `}; + ${breakpoint("tablet")` ${(props: { as?: string }) => (props.as ? "" : "margin-top: 6vh;")} `}; diff --git a/app/components/HoverPreview/Components.tsx b/app/components/HoverPreview/Components.tsx index 3701d0271a..f7632f14ca 100644 --- a/app/components/HoverPreview/Components.tsx +++ b/app/components/HoverPreview/Components.tsx @@ -1,5 +1,4 @@ import { transparentize } from "polished"; -import { Link } from "react-router-dom"; import styled, { css } from "styled-components"; import { s } from "@shared/styles"; import Text from "~/components/Text"; @@ -16,9 +15,8 @@ const StyledText = styled(Text)` margin-bottom: 0; `; -export const Preview = styled(Link)` - cursor: ${(props: { as?: string }) => - props.as === "div" ? "default" : "var(--pointer)"}; +export const Preview = styled.a` + cursor: ${(props) => (props.as === "div" ? "default" : "var(--pointer)")}; border-radius: 4px; box-shadow: 0 30px 90px -20px rgba(0, 0, 0, 0.3), @@ -133,3 +131,22 @@ export const Card = styled.div<{ fadeOut?: boolean; $borderRadius?: string }>` }` : ""} `; + +export const BreadcrumbContainer = styled.div` + font-size: 12px; + font-weight: 500; + color: ${(props) => props.theme.textTertiary}; + margin-bottom: 4px; + display: flex; + align-items: center; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + /* Adds a subtle separator between path items */ + span:not(:last-child)::after { + content: "/"; + margin: 0 4px; + color: ${(props) => props.theme.divider}; + } +`; diff --git a/app/components/HoverPreview/HoverPreview.tsx b/app/components/HoverPreview/HoverPreview.tsx index 00965d055c..2a392ae9ae 100644 --- a/app/components/HoverPreview/HoverPreview.tsx +++ b/app/components/HoverPreview/HoverPreview.tsx @@ -1,10 +1,10 @@ import { m } from "framer-motion"; import { observer } from "mobx-react"; import * as React from "react"; -import { Portal } from "react-portal"; import styled from "styled-components"; import { depths } from "@shared/styles"; import { UnfurlResourceType } from "@shared/types"; +import { Portal } from "~/components/Portal"; import useEventListener from "~/hooks/useEventListener"; import useKeyDown from "~/hooks/useKeyDown"; import useMobile from "~/hooks/useMobile"; @@ -44,7 +44,9 @@ const HoverPreviewDesktop = observer( ({ element, unfurlId, dataLoading, onClose }: Props) => { const { unfurls } = useStores(); const [isVisible, setVisible] = React.useState(false); - const timerClose = React.useRef<ReturnType<typeof setTimeout>>(); + const timerClose = React.useRef<ReturnType<typeof setTimeout> | undefined>( + undefined + ); const cardRef = React.useRef<HTMLDivElement | null>(null); const { cardLeft, cardTop, pointerLeft, pointerTop, pointerDir } = useHoverPosition({ @@ -114,13 +116,13 @@ const HoverPreviewDesktop = observer( } return ( - <Portal> + <Portal toBody> <Position top={cardTop} left={cardLeft} aria-hidden> {isVisible ? ( <Animate initial={{ opacity: 0, - y: -20, + y: -8, filter: "blur(5px)", pointerEvents: "none", }} @@ -248,7 +250,7 @@ function useHoverPosition({ element, isVisible, }: { - cardRef: React.RefObject<HTMLDivElement>; + cardRef: React.RefObject<HTMLDivElement | null>; element: HTMLElement | null; isVisible: boolean; }) { diff --git a/app/components/HoverPreview/HoverPreviewDocument.tsx b/app/components/HoverPreview/HoverPreviewDocument.tsx index 4f5d1de441..f55e78295a 100644 --- a/app/components/HoverPreview/HoverPreviewDocument.tsx +++ b/app/components/HoverPreview/HoverPreviewDocument.tsx @@ -1,9 +1,13 @@ import * as React from "react"; +import { Link } from "react-router-dom"; import { richExtensions } from "@shared/editor/nodes"; import type { UnfurlResourceType, UnfurlResponse } from "@shared/types"; import Editor from "~/components/Editor"; import Flex from "~/components/Flex"; import ErrorBoundary from "../ErrorBoundary"; +import useStores from "~/hooks/useStores"; +import { observer } from "mobx-react"; +import DocumentBreadcrumb from "~/components/DocumentBreadcrumb"; import { Preview, Title, @@ -11,20 +15,40 @@ import { Card, CardContent, Description, + BreadcrumbContainer, } from "./Components"; -type Props = Omit<UnfurlResponse[UnfurlResourceType.Document], "type">; +type Props = Omit<UnfurlResponse[UnfurlResourceType.Document], "type"> & { + ref?: React.Ref<HTMLDivElement>; +}; -const HoverPreviewDocument = React.forwardRef(function HoverPreviewDocument_( - { url, id, title, summary, lastActivityByViewer }: Props, - ref: React.Ref<HTMLDivElement> -) { - return ( - <Preview to={url}> +const HoverPreviewDocument = observer( + ({ url, id, title, summary, lastActivityByViewer, ref }: Props) => { + const parsedUrl = new URL(url, window.location.href); + + const { documents } = useStores(); + const document = documents.get(id); + + // We only need to fetch the document. + // DocumentBreadcrumb handles loading the collection and relations internally. + React.useEffect(() => { + if (!document) { + void documents.fetch(id); + } + }, [id, document, documents]); + + const content = ( <Card ref={ref}> <CardContent> <ErrorBoundary showTitle={false} reloadOnChunkMissing={false}> <Flex column gap={2}> + {/* Wrap the built-in breadcrumb in your container for CSS spacing */} + {document && ( + <BreadcrumbContainer> + <DocumentBreadcrumb document={document} onlyText /> + </BreadcrumbContainer> + )} + <Title>{title} {lastActivityByViewer && {lastActivityByViewer}} @@ -42,8 +66,25 @@ const HoverPreviewDocument = React.forwardRef(function HoverPreviewDocument_( - - ); -}); + ); + + if (parsedUrl.origin !== window.location.origin) { + return ( + + {content} + + ); + } + + return ( + + {content} + + ); + } +); export default HoverPreviewDocument; diff --git a/app/components/HoverPreview/HoverPreviewGroup.tsx b/app/components/HoverPreview/HoverPreviewGroup.tsx index 55177186e7..e056d34f7a 100644 --- a/app/components/HoverPreview/HoverPreviewGroup.tsx +++ b/app/components/HoverPreview/HoverPreviewGroup.tsx @@ -15,12 +15,17 @@ import { } from "./Components"; import ErrorBoundary from "../ErrorBoundary"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewGroup = React.forwardRef(function HoverPreviewGroup_( - { name, description, memberCount, users }: Props, - ref: React.Ref -) { +function HoverPreviewGroup({ + name, + description, + memberCount, + users, + ref, +}: Props) { const { t } = useTranslation(); return ( @@ -65,6 +70,6 @@ const HoverPreviewGroup = React.forwardRef(function HoverPreviewGroup_( ); -}); +} export default HoverPreviewGroup; diff --git a/app/components/HoverPreview/HoverPreviewIssue.tsx b/app/components/HoverPreview/HoverPreviewIssue.tsx index bc7baef6d0..2fd4ba3c9b 100644 --- a/app/components/HoverPreview/HoverPreviewIssue.tsx +++ b/app/components/HoverPreview/HoverPreviewIssue.tsx @@ -21,12 +21,21 @@ import { Info, } from "./Components"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewIssue = React.forwardRef(function HoverPreviewIssue_( - { url, id, title, description, author, labels, state, createdAt }: Props, - ref: React.Ref -) { +function HoverPreviewIssue({ + url, + id, + title, + description, + author, + labels, + state, + createdAt, + ref, +}: Props) { const authorName = author.name; const urlObj = new URL(url); const service = @@ -88,7 +97,7 @@ const HoverPreviewIssue = React.forwardRef(function HoverPreviewIssue_( ); -}); +} const StyledIssueStatusIcon = styled(IssueStatusIcon)` margin-top: 2px; diff --git a/app/components/HoverPreview/HoverPreviewLink.tsx b/app/components/HoverPreview/HoverPreviewLink.tsx index b5ef796948..868c4605a7 100644 --- a/app/components/HoverPreview/HoverPreviewLink.tsx +++ b/app/components/HoverPreview/HoverPreviewLink.tsx @@ -18,12 +18,16 @@ type Props = { thumbnailUrl: string; /** Some description about the link provider */ description: string; + ref?: React.Ref; }; -const HoverPreviewLink = React.forwardRef(function HoverPreviewLink_( - { url, thumbnailUrl, title, description }: Props, - ref: React.Ref -) { +function HoverPreviewLink({ + url, + thumbnailUrl, + title, + description, + ref, +}: Props) { return ( @@ -39,6 +43,6 @@ const HoverPreviewLink = React.forwardRef(function HoverPreviewLink_( ); -}); +} export default HoverPreviewLink; diff --git a/app/components/HoverPreview/HoverPreviewMention.tsx b/app/components/HoverPreview/HoverPreviewMention.tsx index e05ccbcbcc..2db4b88079 100644 --- a/app/components/HoverPreview/HoverPreviewMention.tsx +++ b/app/components/HoverPreview/HoverPreviewMention.tsx @@ -4,12 +4,17 @@ import { Avatar, AvatarSize } from "~/components/Avatar"; import Flex from "~/components/Flex"; import { Preview, Title, Info, Card, CardContent } from "./Components"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewMention = React.forwardRef(function HoverPreviewMention_( - { avatarUrl, name, lastActive, color }: Props, - ref: React.Ref -) { +function HoverPreviewMention({ + avatarUrl, + name, + lastActive, + color, + ref, +}: Props) { return ( @@ -32,6 +37,6 @@ const HoverPreviewMention = React.forwardRef(function HoverPreviewMention_( ); -}); +} export default HoverPreviewMention; diff --git a/app/components/HoverPreview/HoverPreviewProject.tsx b/app/components/HoverPreview/HoverPreviewProject.tsx index 9cfb43a83a..f45b6a6b97 100644 --- a/app/components/HoverPreview/HoverPreviewProject.tsx +++ b/app/components/HoverPreview/HoverPreviewProject.tsx @@ -30,12 +30,21 @@ type Props = Pick< | "state" | "targetDate" | "description" ->; +> & { + ref?: React.Ref; +}; -const HoverPreviewProject = React.forwardRef(function HoverPreviewProject_( - { url, name, color, lead, labels, state, description, targetDate }: Props, - ref: React.Ref -) { +function HoverPreviewProject({ + url, + name, + color, + lead, + labels, + state, + description, + targetDate, + ref, +}: Props) { const { t } = useTranslation(); return ( @@ -116,7 +125,7 @@ const HoverPreviewProject = React.forwardRef(function HoverPreviewProject_( ); -}); +} const StyledSquircle = styled(Squircle)` flex-shrink: 0; diff --git a/app/components/HoverPreview/HoverPreviewPullRequest.tsx b/app/components/HoverPreview/HoverPreviewPullRequest.tsx index e9a4f41eca..d0b11c5343 100644 --- a/app/components/HoverPreview/HoverPreviewPullRequest.tsx +++ b/app/components/HoverPreview/HoverPreviewPullRequest.tsx @@ -19,57 +19,63 @@ import { Info, } from "./Components"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewPullRequest = React.forwardRef( - function HoverPreviewPullRequest_( - { url, title, id, description, author, state, createdAt }: Props, - ref: React.Ref - ) { - const authorName = author.name; +function HoverPreviewPullRequest({ + url, + title, + id, + description, + author, + state, + createdAt, + ref, +}: Props) { + const authorName = author.name; - return ( - - - - - - - <StyledPullRequestIcon size={18} state={state} /> - <span> - <Backticks content={title} /> -  <Text type="tertiary">{id}</Text> - </span> - - - - - - {{ authorName }} opened{" "} - - - - {description && ( - - }> - - - - )} + return ( + + + + + + + <StyledPullRequestIcon size={18} state={state} /> + <span> + <Backticks content={title} /> +  <Text type="tertiary">{id}</Text> + </span> + + + + + + {{ authorName }} opened{" "} + + - - - - - ); - } -); + {description && ( + + }> + + + + )} + + + + + + ); +} const StyledPullRequestIcon = styled(PullRequestIcon)` margin-top: 2px; diff --git a/app/components/IconPicker/components/EmojiPanel.tsx b/app/components/IconPicker/components/EmojiPanel.tsx index 324a89c2f4..800d826db5 100644 --- a/app/components/IconPicker/components/EmojiPanel.tsx +++ b/app/components/IconPicker/components/EmojiPanel.tsx @@ -26,6 +26,7 @@ const GRID_HEIGHT = 410; type Props = { panelWidth: number; + icon?: string | null; query: string; panelActive: boolean; height?: number; @@ -35,6 +36,7 @@ type Props = { const EmojiPanel = ({ panelWidth, + icon, query, panelActive, onEmojiChange, @@ -134,15 +136,18 @@ const EmojiPanel = ({ } }, []); + // Defer the search so typing stays responsive while the grid re-derives. + const deferredQuery = React.useDeferredValue(query); + // Drop the preview when the grid contents change out from under it. React.useEffect(() => { setActiveEmoji(undefined); - }, [query, skinTone]); + }, [deferredQuery, skinTone]); - const isSearch = query !== ""; + const isSearch = deferredQuery !== ""; const templateData: DataNode[] = isSearch ? getSearchResults({ - query, + query: deferredQuery, skinTone, customEmojis, }) @@ -185,6 +190,7 @@ const EmojiPanel = ({ width={panelWidth} height={height - 48 - PREVIEW_HEIGHT} data={templateData} + selected={icon} onIconSelect={handleEmojiSelection} onIconActive={handleEmojiActive} onOverflowChange={setHasMoreBelow} diff --git a/app/components/IconPicker/components/Grid.tsx b/app/components/IconPicker/components/Grid.tsx index 9be2b95de9..b82ac48bfc 100644 --- a/app/components/IconPicker/components/Grid.tsx +++ b/app/components/IconPicker/components/Grid.tsx @@ -10,12 +10,18 @@ type Props = { columns: number; itemWidth: number; onOverflowChange?: (hasMoreBelow: boolean) => void; + ref?: React.Ref; }; -const Grid = ( - { width, height, data, columns, itemWidth, onOverflowChange }: Props, - ref: React.Ref -) => { +function Grid({ + width, + height, + data, + columns, + itemWidth, + onOverflowChange, + ref, +}: Props) { const offsetRef = React.useRef(0); const maxOffset = Math.max(0, data.length * itemWidth - height); @@ -47,7 +53,7 @@ const Grid = ( {Row} ); -}; +} type RowProps = { data: React.ReactNode[][]; @@ -82,4 +88,4 @@ const RowContainer = styled.div<{ columns: number }>` align-content: center; `; -export default React.forwardRef(Grid); +export default Grid; diff --git a/app/components/IconPicker/components/GridTemplate.tsx b/app/components/IconPicker/components/GridTemplate.tsx index 27f1df6ae0..486e41ca05 100644 --- a/app/components/IconPicker/components/GridTemplate.tsx +++ b/app/components/IconPicker/components/GridTemplate.tsx @@ -50,6 +50,8 @@ type Props = { height: number; /** Data to be displayed in the grid */ data: DataNode[]; + /** Value of the currently selected icon or emoji */ + selected?: string | null; /** Content to display when search results are empty */ empty?: React.ReactNode; /** Callback when an icon is selected */ @@ -58,26 +60,47 @@ type Props = { onIconActive?: (icon: IconNode) => void; /** Callback when whether the grid has content below the fold changes */ onOverflowChange?: (hasMoreBelow: boolean) => void; + /** Ref to the scrolling container */ + ref?: React.Ref; }; -const GridTemplate = ( - { - width, - height, - data, - empty, - onIconSelect, - onIconActive, - onOverflowChange, - }: Props, - ref: React.Ref -) => { +function GridTemplate({ + width, + height, + data, + selected, + empty, + onIconSelect, + onIconActive, + onOverflowChange, + ref, +}: Props) { const isMobile = useMobile(); const buttonSize = isMobile ? BUTTON_SIZE_MOBILE : BUTTON_SIZE_DESKTOP; const iconSize = isMobile ? ICON_SIZE_MOBILE : ICON_SIZE_DESKTOP; // 24px padding for the Grid Container const itemsPerRow = Math.max(1, Math.floor((width - 24) / buttonSize)); + const [lastClicked, setLastClicked] = React.useState<{ + category: DataNode["category"]; + value: string; + }>(); + + // Highlight the selection in only one category: the one it was clicked in, + // otherwise the first category that contains it. + const containsSelected = (node: DataNode) => + node.icons.some((icon) => valueOf(icon) === selected); + const selectedCategory = selected + ? ( + data.find( + (node) => + lastClicked?.value === selected && + node.category === lastClicked.category && + containsSelected(node) + ) ?? data.find(containsSelected) + )?.category + : undefined; + const gridItems = compact( data.flatMap((node) => { const category = ( @@ -100,12 +123,19 @@ const GridTemplate = ( const items = node.icons.map((item) => { const handleActive = () => onIconActive?.(item); + const handleSelect = (id: string, value: string) => { + setLastClicked({ category: node.category, value }); + onIconSelect({ id, value }); + }; + const isSelected = + node.category === selectedCategory && valueOf(item) === selected; if (item.type === IconType.SVG) { return ( onIconSelect({ id: item.name, value: item.name })} + onClick={() => handleSelect(item.name, item.name)} + aria-current={isSelected ? "true" : undefined} onMouseEnter={handleActive} onFocus={handleActive} style={{ "--delay": `${item.delay}ms` } as React.CSSProperties} @@ -124,7 +154,8 @@ const GridTemplate = ( return ( onIconSelect({ id: item.id, value: item.value })} + onClick={() => handleSelect(item.id, item.value)} + aria-current={isSelected ? "true" : undefined} onMouseEnter={handleActive} onFocus={handleActive} > @@ -159,7 +190,10 @@ const GridTemplate = ( onOverflowChange={onOverflowChange} /> ); -}; +} + +const valueOf = (icon: IconNode) => + icon.type === IconType.SVG ? icon.name : icon.value; const CategoryName = styled(Text)` grid-column: 1 / -1; @@ -173,4 +207,4 @@ const Icon = styled.svg` transition-delay: var(--delay); `; -export default React.forwardRef(GridTemplate); +export default GridTemplate; diff --git a/app/components/IconPicker/components/IconButton.tsx b/app/components/IconPicker/components/IconButton.tsx index 0f662f8724..666fdc8db9 100644 --- a/app/components/IconPicker/components/IconButton.tsx +++ b/app/components/IconPicker/components/IconButton.tsx @@ -11,6 +11,11 @@ export const IconButton = styled(NudeButton)<{ delay?: number }>` background: ${s("listItemHoverBackground")}; } + &[aria-current="true"] { + background: ${s("listItemHoverBackground")}; + box-shadow: inset 0 0 0 1px ${s("inputBorderFocused")}; + } + @media (max-width: ${breakpoints.tablet - 1}px) { width: 40px; height: 40px; diff --git a/app/components/IconPicker/components/IconPanel.tsx b/app/components/IconPicker/components/IconPanel.tsx index 78afc3ec37..f9eb4f78b6 100644 --- a/app/components/IconPicker/components/IconPanel.tsx +++ b/app/components/IconPicker/components/IconPanel.tsx @@ -24,6 +24,7 @@ const GRID_HEIGHT = 314 - PREVIEW_HEIGHT; type Props = { panelWidth: number; initial: string; + icon: string | null; color: string; query: string; panelActive: boolean; @@ -35,6 +36,7 @@ type Props = { const IconPanel = ({ panelWidth, initial, + icon, color, query, panelActive, @@ -51,12 +53,15 @@ const IconPanel = ({ const totalFrequentIcons = frequentIcons.length; + // Defer the search so typing stays responsive while the grid re-derives. + const deferredQuery = React.useDeferredValue(query); + const filteredIcons = React.useMemo( - () => IconLibrary.findIcons(query), - [query] + () => IconLibrary.findIcons(deferredQuery), + [deferredQuery] ); - const isSearch = query !== ""; + const isSearch = deferredQuery !== ""; const category = isSearch ? DisplayCategory.Search : DisplayCategory.All; const delayPerIcon = 250 / (TotalIcons + totalFrequentIcons); @@ -86,7 +91,7 @@ const IconPanel = ({ React.useEffect(() => { setActiveIcon(undefined); - }, [query]); + }, [deferredQuery]); // Preview the first icon shown in the grid until the user hovers another. const previewIcon = @@ -150,6 +155,7 @@ const IconPanel = ({ width={panelWidth} height={GRID_HEIGHT} data={templateData} + selected={icon} onIconSelect={handleIconSelection} onIconActive={handleIconActive} onOverflowChange={setHasMoreBelow} diff --git a/app/components/IconPicker/index.tsx b/app/components/IconPicker/index.tsx index 036424a56d..b3a22c741f 100644 --- a/app/components/IconPicker/index.tsx +++ b/app/components/IconPicker/index.tsx @@ -74,7 +74,9 @@ const IconPicker = ({ const iconType = determineIconType(icon); const defaultTab = React.useMemo( () => - iconType === IconType.Emoji ? TAB_NAMES["Emoji"] : TAB_NAMES["Icon"], + iconType === IconType.Emoji || iconType === IconType.Custom + ? TAB_NAMES["Emoji"] + : TAB_NAMES["Icon"], [iconType] ); @@ -153,6 +155,7 @@ const IconPicker = ({ { if (open) { - void emojis.fetchAll(); + void emojis.fetchAllIfNeeded(); } }, [open, emojis]); @@ -208,6 +211,7 @@ const IconPicker = ({ type ContentProps = { open: boolean; activeTab: TabName; + icon: string | null; query: string; iconColor: string; iconInitial: string; @@ -223,6 +227,7 @@ type ContentProps = { const Content = ({ open, activeTab, + icon, iconColor, iconInitial, query, @@ -267,6 +272,7 @@ const Content = ({ + + + ); + } if (!collection.icon || collection.icon === "collection") { - // If the chosen icon color is very dark then we invert it in dark mode - // otherwise it will be impossible to see against the dark background. - const collectionColor = collection.color ?? colorPalette[0]; const color = - inputColor || - (ui.resolvedTheme === "dark" && collectionColor !== "currentColor" - ? getLuminance(collectionColor) > 0.09 - ? collectionColor - : "currentColor" - : collectionColor); + inputColor || contrastColor(collection.color ?? colorPalette[0]); const Component = collection.isPrivate ? PrivateCollectionIcon @@ -64,4 +70,13 @@ function ResolvedCollectionIcon({ ); } +const AvatarWrapper = styled.span<{ $size: number }>` + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: ${(props) => props.$size}px; + height: ${(props) => props.$size}px; +`; + export default observer(ResolvedCollectionIcon); diff --git a/app/components/Icons/GmailIcon.tsx b/app/components/Icons/GmailIcon.tsx new file mode 100644 index 0000000000..f362c20b95 --- /dev/null +++ b/app/components/Icons/GmailIcon.tsx @@ -0,0 +1,30 @@ +interface GmailIconProps { + size?: number; + color?: string; +} + +/** + * Renders the Gmail logo as a decorative icon. + * + * @param props the icon size and color. + * @returns the Gmail logo. + * @see https://github.com/simple-icons/simple-icons/blob/12.4.0/icons/gmail.svg + */ +export function GmailIcon({ + size = 24, + color = "currentColor", +}: GmailIconProps) { + return ( + + ); +} diff --git a/app/components/Icons/GroupIcon.tsx b/app/components/Icons/GroupIcon.tsx new file mode 100644 index 0000000000..d737bef6b6 --- /dev/null +++ b/app/components/Icons/GroupIcon.tsx @@ -0,0 +1,48 @@ +import { observer } from "mobx-react"; +import { GroupIcon } from "outline-icons"; +import Icon from "@shared/components/Icon"; +import type Group from "~/models/Group"; +import useContrastColor from "@shared/hooks/useContrastColor"; + +type Props = { + /** The group to show an icon for. */ + group: Pick; + /** The size of the icon, 24px is default to match standard icons. */ + size?: number; + /** The color of the icon, defaults to the group color. */ + color?: string; + className?: string; +}; + +/** + * Renders the icon chosen for a group, or the default group icon. + */ +export const ResolvedGroupIcon = observer(function ResolvedGroupIcon_({ + group, + color, + size, + className, +}: Props) { + const contrastColor = useContrastColor(); + + if (!group.icon) { + return ( + + ); + } + + return ( + + ); +}); diff --git a/app/components/Icons/OutlookIcon.tsx b/app/components/Icons/OutlookIcon.tsx new file mode 100644 index 0000000000..bf2c83ae9a --- /dev/null +++ b/app/components/Icons/OutlookIcon.tsx @@ -0,0 +1,30 @@ +interface OutlookIconProps { + size?: number; + color?: string; +} + +/** + * Renders the Outlook logo as a decorative icon. + * + * @param props the icon size and color. + * @returns the Outlook logo. + * @see https://github.com/simple-icons/simple-icons/blob/12.4.0/icons/microsoftoutlook.svg + */ +export function OutlookIcon({ + size = 24, + color = "currentColor", +}: OutlookIconProps) { + return ( + + ); +} diff --git a/app/components/ImportDocumentDialog.tsx b/app/components/ImportDocumentDialog.tsx index 0cbcd0704d..440f5378fb 100644 --- a/app/components/ImportDocumentDialog.tsx +++ b/app/components/ImportDocumentDialog.tsx @@ -92,7 +92,7 @@ export const ImportDocumentDialog = observer(function ImportDocumentDialog({ return ( (props.$round ? "16px" : "4px")}; font-weight: normal; + + ${breakpoint("mobile", "tablet")` + ${(props: { $round?: boolean }) => + props.$round && `border-radius: ${MOBILE_TOUCH_TARGET / 2}px;`} + `}; align-items: center; overflow: hidden; background: ${s("background")}; @@ -192,10 +199,12 @@ export interface Props extends Omit< } function Input( - props: Props, - ref: React.RefObject + props: Props & { ref?: React.Ref } ) { - const internalRef = React.useRef(); + const internalRef = React.useRef< + HTMLInputElement | HTMLTextAreaElement | null + >(null); + const generatedId = React.useId(); const [focused, setFocused] = React.useState(false); const [charCount, setCharCount] = React.useState(() => { if (typeof props.value === "string") { @@ -282,6 +291,8 @@ function Input( onChange, onRequestSubmit, children, + ref, + id = generatedId, ...rest } = props; @@ -308,7 +319,7 @@ function Input( return ( - + ); +} MobileSelect.displayName = "InputSelect"; function Label({ diff --git a/app/components/InputSelectPermission.tsx b/app/components/InputSelectPermission.tsx index 9faa2eb098..eee4e89d74 100644 --- a/app/components/InputSelectPermission.tsx +++ b/app/components/InputSelectPermission.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; -import styled from "styled-components"; +import styled, { css } from "styled-components"; import { s } from "@shared/styles"; import { CollectionPermission } from "@shared/types"; import type { Option } from "~/components/InputSelect"; @@ -9,56 +9,58 @@ import { EmptySelectValue } from "~/types"; type Props = { shrink?: boolean; + ref?: React.Ref; } & Pick< React.ComponentProps, "value" | "onChange" | "disabled" | "labelHidden" | "nude" | "help" >; -export const InputSelectPermission = React.forwardRef( - (props, ref) => { - const { value, onChange, shrink, ...rest } = props; - const { t } = useTranslation(); +export function InputSelectPermission(props: Props) { + const { ref, value, onChange, shrink, ...rest } = props; + const { t } = useTranslation(); - const options = React.useMemo( - () => [ - { - type: "item", - label: t("View only"), - value: CollectionPermission.Read, - }, - { - type: "item", - label: t("Can edit"), - value: CollectionPermission.ReadWrite, - }, - { - type: "separator", - }, - { - type: "item", - label: t("No access"), - value: EmptySelectValue, - }, - ], - [t] - ); + const options = React.useMemo( + () => [ + { + type: "item", + label: t("View only"), + value: CollectionPermission.Read, + }, + { + type: "item", + label: t("Can edit"), + value: CollectionPermission.ReadWrite, + }, + { + type: "separator", + }, + { + type: "item", + label: t("No access"), + value: EmptySelectValue, + }, + ], + [t] + ); - return ( - + ); +} const Select = styled(InputSelect)<{ $shrink?: boolean }>` - color: ${s("textSecondary")}; + ${({ nude }) => + nude && + css` + color: ${s("textSecondary")}; + `} ${({ $shrink }) => !$shrink && "margin-bottom: 16px;"} `; diff --git a/app/scenes/KeyboardShortcuts.tsx b/app/components/KeyboardShortcuts.tsx similarity index 94% rename from app/scenes/KeyboardShortcuts.tsx rename to app/components/KeyboardShortcuts.tsx index 1f50d34484..5238b625c5 100644 --- a/app/scenes/KeyboardShortcuts.tsx +++ b/app/components/KeyboardShortcuts.tsx @@ -1,5 +1,12 @@ import type * as React from "react"; -import { useMemo, useState, useCallback, memo, Fragment } from "react"; +import { + useMemo, + useState, + useCallback, + useDeferredValue, + memo, + Fragment, +} from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import { s } from "@shared/styles"; @@ -40,6 +47,14 @@ function KeyboardShortcuts({ defaultQuery = "" }: Props) { ), label: t("Forward"), }, + { + shortcut: , + label: t("Previous document in sidebar"), + }, + { + shortcut: , + label: t("Next document in sidebar"), + }, { shortcut: , label: t("New document"), @@ -128,15 +143,15 @@ function KeyboardShortcuts({ defaultQuery = "" }: Props) { }, { shortcut: , - label: t("Large header"), + label: t("Big heading"), }, { shortcut: , - label: t("Medium header"), + label: t("Medium heading"), }, { shortcut: , - label: t("Small header"), + label: t("Small heading"), }, { shortcut: , @@ -266,13 +281,13 @@ function KeyboardShortcuts({ defaultQuery = "" }: Props) { shortcut: ( ), - label: t("Large header"), + label: t("Big heading"), }, { shortcut: ( ), - label: t("Medium header"), + label: t("Medium heading"), }, { shortcut: ( @@ -281,7 +296,7 @@ function KeyboardShortcuts({ defaultQuery = "" }: Props) { combination="sequence" /> ), - label: t("Small header"), + label: t("Small heading"), }, { shortcut: ( @@ -396,7 +411,9 @@ function KeyboardShortcuts({ defaultQuery = "" }: Props) { [t] ); const [searchTerm, setSearchTerm] = useState(defaultQuery); - const normalizedSearchTerm = searchTerm.toLocaleLowerCase(); + // Defer filtering so typing in the search input stays responsive. + const deferredSearchTerm = useDeferredValue(searchTerm); + const normalizedSearchTerm = deferredSearchTerm.toLocaleLowerCase(); const handleChange = useCallback( (event: React.ChangeEvent) => { setSearchTerm(event.target.value); @@ -429,7 +446,7 @@ function KeyboardShortcuts({ defaultQuery = "" }: Props) { const titleMatches = category.title .toLocaleLowerCase() .includes(normalizedSearchTerm); - const filtered = searchTerm + const filtered = deferredSearchTerm ? titleMatches ? category.items : category.items.filter((item) => diff --git a/app/components/LanguagePrompt.tsx b/app/components/LanguagePrompt.tsx index 03835dcfe3..a98bc8fa01 100644 --- a/app/components/LanguagePrompt.tsx +++ b/app/components/LanguagePrompt.tsx @@ -50,7 +50,7 @@ export default function LanguagePrompt() { await user.save({ language }); }} > - {t("Change Language")} + {t("Change language")} {" "} ·{" "} ui.set({ languagePromptDismissed: true })}> diff --git a/app/components/Layout.tsx b/app/components/Layout.tsx index 76a9bde771..ab806c8b31 100644 --- a/app/components/Layout.tsx +++ b/app/components/Layout.tsx @@ -1,14 +1,15 @@ import { AnimatePresence } from "framer-motion"; import { observer } from "mobx-react"; import * as React from "react"; -import { Helmet } from "react-helmet-async"; import type { DefaultTheme } from "styled-components"; import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; import { s } from "@shared/styles"; import Flex from "~/components/Flex"; import { LoadingIndicatorBar } from "~/components/LoadingIndicator"; +import { FallbackPageTitle } from "~/components/PageTitle"; import { useRightSidebarContent } from "~/components/RightSidebarContext"; +import { SidebarCollapsedProvider } from "~/components/SidebarCollapsedContext"; import SkipNavContent from "~/components/SkipNavContent"; import SkipNavLink from "~/components/SkipNavLink"; import env from "~/env"; @@ -23,12 +24,16 @@ type Props = { sidebar?: React.ReactNode; /** Whether the sidebar can be collapsed, defaults to true. */ sidebarCanCollapse?: boolean; + ref?: React.Ref; }; -const Layout = React.forwardRef(function Layout_( - { title, children, sidebar, sidebarCanCollapse = true }: Props, - ref: React.RefObject -) { +function Layout({ + title, + children, + sidebar, + sidebarCanCollapse = true, + ref, +}: Props) { const { ui } = useStores(); const showSidebar = !!sidebar && !ui.sidebarHidden; const sidebarCollapsed = @@ -36,42 +41,42 @@ const Layout = React.forwardRef(function Layout_( const sidebarRight = useRightSidebarContent(); return ( - - - {title ? title : env.APP_NAME} - + + + + - + {ui.progressBarVisible && } - {ui.progressBarVisible && } + + {showSidebar && sidebar} - - {showSidebar && sidebar} + + + {children} + - - - {children} - - - {sidebarRight} - - + {sidebarRight} + + + + ); -}); +} const Container = styled(Flex)` background: ${s("background")}; diff --git a/app/components/LazyLoad.ts b/app/components/LazyLoad.ts index 5edf87559a..6c76b8e6e9 100644 --- a/app/components/LazyLoad.ts +++ b/app/components/LazyLoad.ts @@ -1,9 +1,10 @@ import * as React from "react"; -import lazyWithRetry from "~/utils/lazyWithRetry"; +import type { LazyComponent as LazyComponentType } from "@shared/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; // oxlint-disable no-explicit-any -- ComponentType is the standard React pattern for generic component constraints export interface LazyComponent> { - Component: React.LazyExoticComponent; + Component: LazyComponentType; preload: () => Promise<{ default: T }>; } @@ -46,8 +47,7 @@ export function createLazyComponent>( })) : (factory as () => Promise<{ default: T }>); - return { - Component: lazyWithRetry(wrappedFactory, retries, interval), - preload: wrappedFactory, - }; + const Component = lazyWithRetry(wrappedFactory, retries, interval); + + return { Component, preload: Component.preload }; } diff --git a/app/components/LazyPolyfills.tsx b/app/components/LazyPolyfills.tsx index fc9fa182b5..eac9e89228 100644 --- a/app/components/LazyPolyfills.tsx +++ b/app/components/LazyPolyfills.tsx @@ -7,7 +7,7 @@ type Props = { }; /** - * Asyncronously load required polyfills. Should wrap the React tree. + * Asynchronously load required polyfills. Should wrap the React tree. */ export const LazyPolyfill: React.FC = ({ children }: Props) => { const [isLoaded, setIsLoaded] = React.useState(false); diff --git a/app/components/Lightbox.tsx b/app/components/Lightbox.tsx index 45580531b9..aded9ed79a 100644 --- a/app/components/Lightbox.tsx +++ b/app/components/Lightbox.tsx @@ -6,11 +6,11 @@ import type { ComponentProps, HTMLAttributes, ReactNode, + Ref, SyntheticEvent, } from "react"; import { createContext, - forwardRef, useCallback, useContext, useEffect, @@ -142,12 +142,16 @@ type ZoomablePannablePinchableProps = { panningDisabled: boolean; disabled: boolean; onClose?: () => void; + ref?: Ref; }; -const ZoomablePannablePinchable = forwardRef< - ReactZoomPanPinchRef, - ZoomablePannablePinchableProps ->(({ children, panningDisabled, disabled, onClose }, ref) => { +function ZoomablePannablePinchable({ + children, + panningDisabled, + disabled, + onClose, + ref, +}: ZoomablePannablePinchableProps) { const { isPanning, ...panningHandlers } = usePanning(); const wrapperRef = useRef(null); const scale = wrapperRef.current?.instance.transformState.scale ?? 1; @@ -208,7 +212,7 @@ const ZoomablePannablePinchable = forwardRef< ); -}); +} function usePanning() { const [isPanning, setPanning] = useState(false); @@ -616,12 +620,12 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { }, [status.image]); // Hide the inline image in the editor while the lightbox zoom transition is - // active, otherwise a duplicate is visible behind the fading overlay. + // active, otherwise a duplicate is visible behind the fading overlay. It stays + // hidden until unmount so the lightbox copy is the only one visible in any + // frame painted between the close animation ending and the teardown. useHideElement( activeImage.getElement(), - status.lightbox !== null && - status.lightbox !== LightboxStatus.READY_TO_OPEN && - status.lightbox !== LightboxStatus.CLOSED + status.lightbox !== null && status.lightbox !== LightboxStatus.READY_TO_OPEN ); const prev = () => { @@ -785,7 +789,7 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { animation={animation.current} $commentsOpen={canShowComments && commentsOpen} > - + - + - + - + + )} {canShowComments && ( - + setCommentsOpen((open) => !open)} @@ -884,7 +888,7 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { - + void; onZoom: () => void; onMaxZoom: () => void; + ref?: Ref; }; -const Image = forwardRef(function Image_( - { - src, - alt, - onLoading, - onLoad, - onError, - onSwipeRight, - onSwipeLeft, - onSwipeUp, - onSwipeDown, - status, - animation, - onMinZoom, - onZoom, - onMaxZoom, - }: ImageProps, - ref -) { +function Image({ + src, + alt, + onLoading, + onLoad, + onError, + onSwipeRight, + onSwipeLeft, + onSwipeUp, + onSwipeDown, + status, + animation, + onMinZoom, + onZoom, + onMaxZoom, + ref, +}: ImageProps) { const { t } = useTranslation(); const swipeHandlers = useSwipe({ @@ -1091,7 +1094,7 @@ const Image = forwardRef(function Image_( ); -}); +} const Figure = styled("figure")` width: 100%; @@ -1132,7 +1135,7 @@ const StyledOverlay = styled(Dialog.Overlay)<{ : props.animation.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1167,12 +1170,12 @@ const StyledImg = styled.img<{ : props.animation?.zoomOut ? css` animation: ${props.animation.zoomOut.apply()} - ${props.animation.zoomOut.duration}ms; + ${props.animation.zoomOut.duration}ms forwards; ` : props.animation?.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1220,7 +1223,7 @@ const Actions = styled(HStack)<{ : props.animation.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1248,7 +1251,7 @@ const CloseAction = styled.div<{ animation: Animation | null }>` : props.animation.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1282,7 +1285,7 @@ const Nav = styled.div<{ : props.animation.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1303,7 +1306,7 @@ const StyledError = styled(ImageError)<{ : props.animation.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; @@ -1324,7 +1327,7 @@ const CommentsSidebar = styled.div<{ props.animation?.fadeOut ? css` animation: ${props.animation.fadeOut.apply()} - ${props.animation.fadeOut.duration}ms; + ${props.animation.fadeOut.duration}ms forwards; ` : ""} `; diff --git a/app/components/List/Item.tsx b/app/components/List/Item.tsx index a0a09db26b..3d1e989dad 100644 --- a/app/components/List/Item.tsx +++ b/app/components/List/Item.tsx @@ -1,7 +1,3 @@ -import { - useFocusEffect, - useRovingTabIndex, -} from "@getoutline/react-roving-tabindex"; import type { LocationDescriptor } from "history"; import * as React from "react"; import scrollIntoView from "scroll-into-view-if-needed"; @@ -9,6 +5,7 @@ import styled, { useTheme } from "styled-components"; import { s, hover, ellipsis } from "@shared/styles"; import Flex from "~/components/Flex"; import NavLink from "~/components/NavLink"; +import { useRovingTabIndex } from "~/hooks/useRovingTabIndex"; export type Props = Omit, "title"> & { /** An icon or image to display to the left of the list item */ @@ -34,27 +31,27 @@ export type Props = Omit, "title"> & { /** Whether to enable keyboard navigation */ keyboardNavigation?: boolean; enableEllipsis?: boolean; + /** Ref to the anchor element */ + ref?: React.RefObject; }; -const ListItem = ( - { - image, - title, - subtitle, - actions, - small, - border, - to, - keyboardNavigation, - enableEllipsis, - ...rest - }: Props, - ref: React.RefObject -) => { +function ListItem({ + image, + title, + subtitle, + actions, + small, + border, + to, + keyboardNavigation, + enableEllipsis, + ref, + ...rest +}: Props) { const theme = useTheme(); const compact = !subtitle; - let itemRef: React.RefObject = + let itemRef: React.RefObject = React.useRef(null); if (ref) { itemRef = ref; @@ -64,7 +61,6 @@ const ListItem = ( itemRef, keyboardNavigation || to ? false : true ); - useFocusEffect(focused, itemRef); const handleFocus = React.useCallback(() => { if (itemRef.current) { @@ -165,7 +161,7 @@ const ListItem = ( {content(false)} ); -}; +} const Wrapper = styled.a<{ $small?: boolean; @@ -241,4 +237,4 @@ export const Actions = styled(Flex)<{ $selected?: boolean }>` color: ${s("textSecondary")}; `; -export default React.forwardRef(ListItem); +export default ListItem; diff --git a/app/components/LoadingIndicator/LoadingIndicatorBar.tsx b/app/components/LoadingIndicator/LoadingIndicatorBar.tsx index 2985bcc13d..e15d442183 100644 --- a/app/components/LoadingIndicator/LoadingIndicatorBar.tsx +++ b/app/components/LoadingIndicator/LoadingIndicatorBar.tsx @@ -8,8 +8,8 @@ const LoadingIndicatorBar = () => ( ); const loadingFrame = keyframes` - from { margin-left: -100%; } - to { margin-left: 100%; } + from { transform: translateX(-100%); } + to { transform: translateX(100%); } `; const Container = styled.div` @@ -19,7 +19,7 @@ const Container = styled.div` width: 100%; animation: ${loadingFrame} 4s ease-in-out infinite; animation-delay: 250ms; - margin-left: -100%; + transform: translateX(-100%); `; const Loader = styled.div` diff --git a/app/components/LocaleTime.tsx b/app/components/LocaleTime.tsx index 2fc713ca93..ed2b4be25d 100644 --- a/app/components/LocaleTime.tsx +++ b/app/components/LocaleTime.tsx @@ -10,15 +10,50 @@ export type Props = { shorten?: boolean; relative?: boolean; format?: Partial>; + /** Additional content shown below the date in the tooltip. */ + tooltipDetail?: React.ReactNode; }; -const LocaleTime: React.FC = ({ children, ...rest }: Props) => { +const LocaleTime: React.FC = ({ + children, + tooltipDetail, + ...rest +}: Props) => { const { tooltipContent, content } = useLocaleTime(rest); + const [isInteractive, setIsInteractive] = React.useState(false); + // Detail is only available in the tooltip, so it must be reachable by keyboard. + const hasDetail = !!tooltipDetail; - return ( - - + const time = ( + + ); + + return isInteractive || hasDetail ? ( + + {tooltipContent} +
+ {tooltipDetail} + + ) : ( + tooltipContent + ) + } + side="bottom" + > + {time}
+ ) : ( + time ); }; diff --git a/app/components/MeasuredContainer.tsx b/app/components/MeasuredContainer.tsx deleted file mode 100644 index 241059f590..0000000000 --- a/app/components/MeasuredContainer.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import * as React from "react"; -import useMeasure from "react-use-measure"; - -export const MeasuredContainer = ({ - as: As = "div", - name, - children, - ...rest -}: { - as: T; - name: string; - children?: React.ReactNode; -} & React.ComponentProps) => { - const [measureRef, rect] = useMeasure(); - - return ( - - {children} - - ); -}; diff --git a/app/components/Menu/DropdownMenu.tsx b/app/components/Menu/DropdownMenu.tsx index e248d912b5..313e1629b0 100644 --- a/app/components/Menu/DropdownMenu.tsx +++ b/app/components/Menu/DropdownMenu.tsx @@ -1,5 +1,4 @@ import * as React from "react"; -import type * as TooltipPrimitive from "@radix-ui/react-tooltip"; import styled from "styled-components"; import Scrollable from "~/components/Scrollable"; import { @@ -46,121 +45,113 @@ type Props = { onOpen?: () => void; /** Callback when menu is closed */ onClose?: () => void; - // TODO: Invert the dependency chain by forwarding dropdown ref and props to Tooltip component -} & React.ComponentPropsWithoutRef; +} & Omit, "children">; -export const DropdownMenu = observer( - React.forwardRef, Props>( - ( - { - action, - children, - align = "start", - ariaLabel, - modal = true, - append, - onOpen, - onClose, - ...rest - }, - ref - ) => { - const [open, setOpen] = React.useState(false); - const isMobile = useMobile(); - const contentRef = - React.useRef>(null); - const actionContext = useActionContext({ - isMenu: true, - }); +export const DropdownMenu = observer(function DropdownMenu({ + ref, + action, + children, + align = "start", + ariaLabel, + modal = true, + append, + onOpen, + onClose, + ...rest +}: Props) { + const [open, setOpen] = React.useState(false); + const isMobile = useMobile(); + const contentRef = React.useRef>(null); + const actionContext = useActionContext({ + isMenu: true, + }); - const menuItems = useComputed(() => { - if (!open) { - return []; - } - - const resolvedAction = typeof action === "function" ? action() : action; - - return (resolvedAction.children as ActionVariant[]).map((childAction) => - actionToMenuItem(childAction, actionContext) - ); - }, [open, action, actionContext]); - - // Only visibility is resolved while the menu is closed, the remainder of - // each item is resolved when it is opened. - const isEmpty = useComputed(() => { - const resolvedAction = typeof action === "function" ? action() : action; - - return !hasVisibleActions( - resolvedAction.children as ActionVariant[], - actionContext - ); - }, [action, actionContext]); - - const handleOpenChange = React.useCallback( - (open: boolean) => { - setOpen(open); - if (open) { - onOpen?.(); - } else { - onClose?.(); - } - }, - [onOpen, onClose] - ); - - const enablePointerEvents = React.useCallback(() => { - if (contentRef.current) { - contentRef.current.style.pointerEvents = "auto"; - } - }, []); - - const disablePointerEvents = React.useCallback(() => { - if (contentRef.current) { - contentRef.current.style.pointerEvents = "none"; - } - }, []); - - if (isEmpty && !append) { - return null; - } - - if (isMobile) { - return ( - - ); - } - - const content = toMenuItems(menuItems); - - return ( - - - - {children} - - - {content} - {append} - - - - ); + const menuItems = useComputed(() => { + if (!open) { + return []; } - ) -); + + const resolvedAction = typeof action === "function" ? action() : action; + + return (resolvedAction.children as ActionVariant[]).map((childAction) => + actionToMenuItem(childAction, actionContext) + ); + }, [open, action, actionContext]); + + // Only visibility is resolved while the menu is closed, the remainder of + // each item is resolved when it is opened. + const isEmpty = useComputed(() => { + const resolvedAction = typeof action === "function" ? action() : action; + + return !hasVisibleActions( + resolvedAction.children as ActionVariant[], + actionContext + ); + }, [action, actionContext]); + + const handleOpenChange = React.useCallback( + (open: boolean) => { + setOpen(open); + if (open) { + onOpen?.(); + } else { + onClose?.(); + } + }, + [onOpen, onClose] + ); + + const enablePointerEvents = React.useCallback(() => { + if (contentRef.current) { + contentRef.current.style.pointerEvents = "auto"; + } + }, []); + + const disablePointerEvents = React.useCallback(() => { + if (contentRef.current) { + contentRef.current.style.pointerEvents = "none"; + } + }, []); + + if (isEmpty && !append) { + return null; + } + + if (isMobile) { + return ( + + ); + } + + const content = toMenuItems(menuItems); + + return ( + + + + {children} + + + {content} + {append} + + + + ); +}); type MobileDropdownProps = { open: boolean; @@ -178,7 +169,8 @@ function MobileDropdown({ append, }: MobileDropdownProps) { const [submenuName, setSubmenuName] = React.useState(); - const contentRef = React.useRef>(null); + const contentRef = + React.useRef>(null); const enablePointerEvents = React.useCallback(() => { if (contentRef.current) { @@ -234,7 +226,7 @@ function MobileDropdown({ onAnimationStart={disablePointerEvents} onAnimationEnd={enablePointerEvents} > - {ariaLabel} + {content} {!submenuName ? append : null} diff --git a/app/components/Menu/OverflowMenuButton.tsx b/app/components/Menu/OverflowMenuButton.tsx index 1be524dc5e..10e55054cf 100644 --- a/app/components/Menu/OverflowMenuButton.tsx +++ b/app/components/Menu/OverflowMenuButton.tsx @@ -9,16 +9,20 @@ type Props = React.ComponentPropsWithoutRef< > & { neutral?: boolean; className?: string; + ref?: React.Ref; }; -export const OverflowMenuButton = React.forwardRef( - ({ neutral, className, ...rest }, ref) => - neutral ? ( -
@@ -246,7 +246,7 @@ export const AccessControlList = observer( } return true; }} - disabled={!can.update} + disabled={!can.manageUsers} value={membership.permission} />
diff --git a/app/components/Sharing/Collection/PublicAccess.tsx b/app/components/Sharing/Collection/PublicAccess.tsx index fcf2ffad50..6a570a33cf 100644 --- a/app/components/Sharing/Collection/PublicAccess.tsx +++ b/app/components/Sharing/Collection/PublicAccess.tsx @@ -31,12 +31,11 @@ type Props = { collection: Collection; /** The existing share model, if any. */ share: Share | null | undefined; + /** Ref to the container element. */ + ref?: React.Ref; }; -function InnerPublicAccess( - { collection, share }: Props, - ref: React.RefObject -) { +function InnerPublicAccess({ collection, share, ref }: Props) { const { t } = useTranslation(); const { shares } = useStores(); const theme = useTheme(); @@ -117,7 +116,7 @@ function InnerPublicAccess( }, [t]); const copyButton = ( - + @@ -185,4 +184,4 @@ function InnerPublicAccess( ); } -export const PublicAccess = observer(React.forwardRef(InnerPublicAccess)); +export const PublicAccess = observer(InnerPublicAccess); diff --git a/app/components/Sharing/Collection/SharePopover.tsx b/app/components/Sharing/Collection/SharePopover.tsx index 61f9648f09..d498ad498b 100644 --- a/app/components/Sharing/Collection/SharePopover.tsx +++ b/app/components/Sharing/Collection/SharePopover.tsx @@ -5,7 +5,7 @@ import { BackIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; -import { CollectionPermission } from "@shared/types"; +import { CollectionPermission, UserRole } from "@shared/types"; import type Collection from "~/models/Collection"; import Group from "~/models/Group"; import User from "~/models/User"; @@ -54,6 +54,8 @@ function SharePopover({ const loading = externalLoading ?? internalLoading; const { t } = useTranslation(); const can = usePolicy(collection); + const teamCan = usePolicy(team); + const inviteRole = teamCan.addGuest ? UserRole.Guest : team.defaultUserRole; const [query, setQuery] = React.useState(""); const [picker, showPicker, hidePicker] = useBoolean(); const [hasRendered, setHasRendered] = React.useState(visible); @@ -207,7 +209,7 @@ function SharePopover({ { email: idOrEmail, name: idOrEmail, - role: team.defaultUserRole, + role: inviteRole, }, ]); user = response[0]; @@ -295,7 +297,7 @@ function SharePopover({ pendingIds, permission, t, - team.defaultUserRole, + inviteRole, users, ] ); @@ -362,7 +364,7 @@ function SharePopover({ return ( - {can.update && ( + {can.manageUsers && ( { + if (ownerId && !owner) { + void users.fetch(ownerId); + } + }, [ownerId, owner, users]); const containerRef = React.useRef(null); const publicAccessRef = React.useRef(null); @@ -137,7 +145,7 @@ export const AccessControlList = observer( ) : usersInCollection ? ( } - title={collection.name} + title={collection.displayName} subtitle={t("Everyone in the collection")} actions={{t("Can view")}} /> @@ -146,7 +154,11 @@ export const AccessControlList = observer( image={} title={user.name} subtitle={t("You have full access")} - actions={{t("Can edit")}} + actions={ + collection.isPersonal ? undefined : ( + {t("Can edit")} + ) + } /> )} {showLoading ? ( @@ -160,6 +172,20 @@ export const AccessControlList = observer( ) : ( <> + {owner && ( + } + title={owner.name} + subtitle={t("Owner")} + actions={ + + {t("Can edit")} + + } + /> + )} {showLoading ? ( ) : ( @@ -168,22 +194,24 @@ export const AccessControlList = observer( invitedInSession={invitedInSession} /> )} - - - - } - title={t("Other people")} - subtitle={t("Other workspace members may have access")} - actions={ - - } - /> + {!ownerId && ( + + + + } + title={t("Other people")} + subtitle={t("Other workspace members may have access")} + actions={ + + } + /> + )} )} diff --git a/app/components/Sharing/Document/DocumentMemberList.tsx b/app/components/Sharing/Document/DocumentMemberList.tsx index 9996970425..7bd6d98b68 100644 --- a/app/components/Sharing/Document/DocumentMemberList.tsx +++ b/app/components/Sharing/Document/DocumentMemberList.tsx @@ -160,10 +160,7 @@ function DocumentMemberList({ document, invitedInSession }: Props) { membership.sourceId ? ( Has access through{" "} - + parent diff --git a/app/components/Sharing/Document/DocumentMemberListItem.tsx b/app/components/Sharing/Document/DocumentMemberListItem.tsx index 007e0faeb8..ed8753dd7b 100644 --- a/app/components/Sharing/Document/DocumentMemberListItem.tsx +++ b/app/components/Sharing/Document/DocumentMemberListItem.tsx @@ -86,10 +86,7 @@ const DocumentMemberListItem = ({ membership?.sourceId ? ( Has access through{" "} - + parent diff --git a/app/components/Sharing/Document/PublicAccess.tsx b/app/components/Sharing/Document/PublicAccess.tsx index e57a2fd3e9..376b71591d 100644 --- a/app/components/Sharing/Document/PublicAccess.tsx +++ b/app/components/Sharing/Document/PublicAccess.tsx @@ -41,12 +41,11 @@ type Props = { /** Ref to the Copy Link button */ copyButtonRef?: React.RefObject; onRequestClose?: () => void; + /** Ref to the container element. */ + ref?: React.Ref; }; -function PublicAccess( - { document, share, sharedParent }: Props, - ref: React.RefObject -) { +function PublicAccess({ document, share, sharedParent, ref }: Props) { const { t } = useTranslation(); const { shares } = useStores(); const theme = useTheme(); @@ -132,7 +131,7 @@ function PublicAccess( : (share?.url ?? ""); const copyButton = ( - + @@ -149,24 +148,27 @@ function PublicAccess( <> {sharedParent && !document.isDraft ? ( sharedParent.collectionId ? ( - - Anyone with the link can access because the containing - collection,{" "} - - {sharedParent.sourceTitle} - - , is shared - + + ), + }} + /> ) : ( - - Anyone with the link can access because the parent document,{" "} - - {sharedParent.sourceTitle} - - , is shared - + + ), + }} + /> ) ) : ( t("Allow anyone with the link to access") @@ -223,9 +225,8 @@ function PublicAccess( {t( - "Nested documents are not shared on the web. Toggle sharing to enable access, this will be the default behavior in the future" + "Nested documents are not shared on the web. Toggle sharing to enable access. This will be the default behavior in the future." )} - . ) : null} @@ -234,4 +235,4 @@ function PublicAccess( ); } -export default observer(React.forwardRef(PublicAccess)); +export default observer(PublicAccess); diff --git a/app/components/Sharing/Document/SharePopover.tsx b/app/components/Sharing/Document/SharePopover.tsx index f2f06462a6..e37162a420 100644 --- a/app/components/Sharing/Document/SharePopover.tsx +++ b/app/components/Sharing/Document/SharePopover.tsx @@ -5,7 +5,7 @@ import { BackIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; -import { DocumentPermission } from "@shared/types"; +import { DocumentPermission, UserRole } from "@shared/types"; import type Document from "~/models/Document"; import Group from "~/models/Group"; import User from "~/models/User"; @@ -49,6 +49,8 @@ function SharePopover({ const team = useCurrentTeam(); const { t } = useTranslation(); const can = usePolicy(document); + const teamCan = usePolicy(team); + const inviteRole = teamCan.addGuest ? UserRole.Guest : team.defaultUserRole; const { shares } = useStores(); const share = shares.getByDocumentId(document.id); const sharedParent = shares.getByDocumentParents(document); @@ -154,7 +156,7 @@ function SharePopover({ { email: idOrEmail, name: idOrEmail, - role: team.defaultUserRole, + role: inviteRole, }, ]); user = response[0]; @@ -247,7 +249,7 @@ function SharePopover({ pendingIds, permission, t, - team.defaultUserRole, + inviteRole, users, ] ); diff --git a/app/components/Sharing/Document/index.tsx b/app/components/Sharing/Document/index.tsx deleted file mode 100644 index 757dd58d66..0000000000 --- a/app/components/Sharing/Document/index.tsx +++ /dev/null @@ -1,3 +0,0 @@ -import SharePopover from "./SharePopover"; - -export default SharePopover; diff --git a/app/components/Sharing/components/Actions.tsx b/app/components/Sharing/components/Actions.tsx index e5e0df51f5..5a6802de21 100644 --- a/app/components/Sharing/components/Actions.tsx +++ b/app/components/Sharing/components/Actions.tsx @@ -30,7 +30,7 @@ export const AppearanceAction = observer(() => { content={ resolvedTheme === "light" ? t("Switch to dark") : t("Switch to light") } - placement="bottom" + side="bottom" > - + +

+ + {hasMenu && ( + + {primaryAction && ( + (primaryAction.name, actionContext), + }} + > + {resolve(primaryAction.icon, actionContext)} + + )} + + + + + )} +

+
{expanded && (firstRender ? children : {children})} ); @@ -79,7 +144,7 @@ const Button = styled.button` letter-spacing: 0.03em; margin: 0; padding-block: 4px; - padding-inline: 12px 2px; + padding-inline: 12px 32px; border: 0; background: none; border-radius: 4px; @@ -87,16 +152,9 @@ const Button = styled.button` transition: all 100ms ease; ${undraggableOnDesktop()} - &:not(:disabled):hover, - &:not(:disabled):active { - background: ${s("sidebarHoverBackground")}; + &:not(:disabled) { cursor: var(--pointer); - } - - @media (hover: hover) { - &:not(:disabled):hover { - color: ${s("text")}; - } + background: var(--background); } `; @@ -114,14 +172,26 @@ const Disclosure = styled(CollapsedIcon)<{ $expanded?: boolean }>` `; const H3 = styled.h3` + position: relative; margin: 0; + ${revealActionsOnHover} - &:hover, + ${hoveredOrMenuOpen}, &:focus-within { + --background: ${s("sidebarHoverBackground")}; + ${Disclosure} { opacity: 1; } } + + @media (hover: hover) { + ${hoveredOrMenuOpen} { + ${Button}:not(:disabled) { + color: ${s("text")}; + } + } + } `; export default Header; diff --git a/app/components/Sidebar/components/HistoryNavigation.tsx b/app/components/Sidebar/components/HistoryNavigation.tsx index ee9af46a63..49a0430489 100644 --- a/app/components/Sidebar/components/HistoryNavigation.tsx +++ b/app/components/Sidebar/components/HistoryNavigation.tsx @@ -92,7 +92,7 @@ function HistoryNavigation(props: React.ComponentProps) { const Navigation = styled(Flex)` position: absolute; inset-inline-end: 12px; - top: 20px; + top: 17px; button { cursor: default; diff --git a/app/components/Sidebar/components/NavLink.tsx b/app/components/Sidebar/components/NavLink.tsx index a7749de327..b19cbef993 100644 --- a/app/components/Sidebar/components/NavLink.tsx +++ b/app/components/Sidebar/components/NavLink.tsx @@ -168,7 +168,7 @@ const NavLink = observer(function NavLink({ // Whether the link was active when the click gesture began, so a fast click // is not also treated as a click on an already-active link. - const wasActiveAtMouseDown = React.useRef(); + const wasActiveAtMouseDown = React.useRef(undefined); const handleMouseDown = React.useCallback( (event: React.MouseEvent) => { @@ -188,7 +188,16 @@ const NavLink = observer(function NavLink({ // Wait a frame until following the link requestAnimationFrame(() => { - requestAnimationFrame(navigateTo); + requestAnimationFrame(() => { + navigateTo(); + + // A may block the navigation, in which case the location + // is unchanged and the pending target must be released. + const value = pendingNavigation.get(); + if (value && value.from === history.location) { + setPendingNavigation(null); + } + }); element.blur(); }); } diff --git a/app/components/Sidebar/components/PersonalDocs.tsx b/app/components/Sidebar/components/PersonalDocs.tsx new file mode 100644 index 0000000000..b6ca43a151 --- /dev/null +++ b/app/components/Sidebar/components/PersonalDocs.tsx @@ -0,0 +1,184 @@ +import { observer } from "mobx-react"; +import { DocumentIcon, PlusIcon } from "outline-icons"; +import { useCallback, useMemo, useRef } from "react"; +import { useTranslation } from "react-i18next"; +import { useHistory } from "react-router-dom"; +import { PersonalCollectionId } from "@shared/constants"; +import { UserPreference } from "@shared/types"; +import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper"; +import { DocumentValidation } from "@shared/validations"; +import { createAction } from "~/actions"; +import { sortCollection } from "~/actions/definitions/collections"; +import { DocumentSection } from "~/actions/sections"; +import EditableTitle, { type RefHandle } from "~/components/EditableTitle"; +import Flex from "~/components/Flex"; +import { ActionContextProvider } from "~/hooks/useActionContext"; +import useBoolean from "~/hooks/useBoolean"; +import useCurrentTeam from "~/hooks/useCurrentTeam"; +import useCurrentUser from "~/hooks/useCurrentUser"; +import usePolicy from "~/hooks/usePolicy"; +import useStores from "~/hooks/useStores"; +import { useSyncSidebarContext } from "~/hooks/useSyncSidebarContext"; +import { documentEditPath } from "~/utils/routeHelpers"; +import CollectionLinkChildren from "./CollectionLinkChildren"; +import Header from "./Header"; +import Relative from "./Relative"; +import SidebarAction from "./SidebarAction"; +import SidebarContext, { type SidebarContextType } from "./SidebarContext"; +import SidebarLink from "./SidebarLink"; + +/** + * The sidebar section that shows the documents in the personal collection of + * the current user. + */ +export const PersonalDocs = observer(function PersonalDocs() { + const { collections, documents } = useStores(); + const { t } = useTranslation(); + const history = useHistory(); + const user = useCurrentUser(); + const team = useCurrentTeam(); + const can = usePolicy(team); + const collection = collections.personal; + const canCollection = usePolicy(collection); + const canCreate = collection + ? !!canCollection.createDocument + : !!can.createPersonalCollection; + const [isAddingNew, setIsAddingNew, closeAddingNew] = useBoolean(); + const newTitleRef = useRef(null); + + // Opens a temporary row with an editable title, the document is only + // created once a title is submitted. + const newDocAction = useMemo( + () => + createAction({ + name: ({ t, isMenu }) => (isMenu ? t("New document") : t("New doc")), + analyticsName: "New personal document", + section: DocumentSection, + icon: , + keywords: "create personal private", + visible: canCreate, + perform: setIsAddingNew, + }), + [canCreate, setIsAddingNew] + ); + const hasCollection = !!collection; + const headerActions = useMemo( + () => (hasCollection ? [newDocAction, sortCollection] : [newDocAction]), + [hasCollection, newDocAction] + ); + const activeModels = useMemo( + () => (collection ? [collection] : undefined), + [collection] + ); + + const handleNewDoc = useCallback( + async (title: string) => { + // The personal collection is created with the first document. + const newDocument = await documents.create( + { + collectionId: collection?.id ?? PersonalCollectionId, + title, + fullWidth: user.getPreference(UserPreference.FullWidthDocuments), + data: ProsemirrorDataHelper.getEmpty(), + }, + { publish: true } + ); + if (newDocument.collectionId) { + const personal = + collection ?? (await collections.fetch(newDocument.collectionId)); + personal.addDocument(newDocument); + } + history.push({ + pathname: documentEditPath(newDocument), + state: { sidebarContext: "personal" }, + }); + }, + [collection, collections, documents, user, history] + ); + + const handleNewDocSubmit = useCallback( + async (value: string) => { + try { + newTitleRef.current?.setIsEditing(false); + await handleNewDoc(value); + closeAddingNew(); + } catch (_err) { + newTitleRef.current?.setIsEditing(true); + } + }, + [handleNewDoc, closeAddingNew] + ); + + const collectionId = collection?.id; + useSyncSidebarContext( + useCallback( + (context: NonNullable) => context === "personal", + [] + ), + useCallback( + (activeDocumentId: string) => + collectionId && + documents.get(activeDocumentId)?.collectionId === collectionId + ? "personal" + : undefined, + [documents, collectionId] + ) + ); + + if (!collection && !canCreate) { + return null; + } + + const newDocRow = + isAddingNew && canCreate ? ( + true} + depth={0} + icon={} + ellipsis={false} + label={ + + } + /> + ) : null; + + return ( + + + +
+ + {collection ? ( + + {newDocRow} + + ) : ( + newDocRow + )} + + +
+
+
+
+ ); +}); diff --git a/app/components/Sidebar/components/SharedDocumentLink.tsx b/app/components/Sidebar/components/SharedDocumentLink.tsx index 9018d3a193..47760bd581 100644 --- a/app/components/Sidebar/components/SharedDocumentLink.tsx +++ b/app/components/Sidebar/components/SharedDocumentLink.tsx @@ -21,21 +21,20 @@ type Props = { index: number; shareId: string; parentId?: string; + ref?: React.Ref; }; -function DocumentLink( - { - node, - collection, - activeDocument, - activeDocumentId, - prefetchDocument, - isDraft, - depth, - shareId, - }: Props, - ref: React.RefObject -) { +function DocumentLink({ + node, + collection, + activeDocument, + activeDocumentId, + prefetchDocument, + isDraft, + depth, + shareId, + ref, +}: Props) { const { documents } = useStores(); const { t } = useTranslation(); const expansion = useSidebarExpansion(); @@ -150,4 +149,4 @@ function DocumentLink( ); } -export const SharedDocumentLink = observer(React.forwardRef(DocumentLink)); +export const SharedDocumentLink = observer(DocumentLink); diff --git a/app/components/Sidebar/components/SharedWithMe.tsx b/app/components/Sidebar/components/SharedWithMe.tsx index d8d2724a8a..03c0b4f269 100644 --- a/app/components/Sidebar/components/SharedWithMe.tsx +++ b/app/components/Sidebar/components/SharedWithMe.tsx @@ -94,7 +94,7 @@ function SharedWithMe() { } // `history` is read imperatively, the sidebar context should only be // recalculated when the active document or memberships change. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [ ui.activeDocumentId, locationSidebarContext, diff --git a/app/components/Sidebar/components/SharedWithMeLink.tsx b/app/components/Sidebar/components/SharedWithMeLink.tsx index 116268e784..0aca26920e 100644 --- a/app/components/Sidebar/components/SharedWithMeLink.tsx +++ b/app/components/Sidebar/components/SharedWithMeLink.tsx @@ -9,6 +9,7 @@ import type GroupMembership from "~/models/GroupMembership"; import UserMembership from "~/models/UserMembership"; import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; import useBoolean from "~/hooks/useBoolean"; +import { useComputed } from "~/hooks/useComputed"; import useStores from "~/hooks/useStores"; import DocumentMenu from "~/menus/DocumentMenu"; import * as Scenes from "~/routes/scenes"; @@ -21,7 +22,7 @@ import SidebarExpansionContext, { useSidebarExpansionState, } from "./SidebarExpansionContext"; import { useSidebarLabelAndIcon } from "../hooks/useSidebarLabelAndIcon"; -import DocumentLink from "./DocumentLink"; +import { DocumentTree } from "./DocumentTree"; import DocumentRow from "./DocumentRow"; import DropCursor from "./DropCursor"; import Folder from "./Folder"; @@ -30,6 +31,7 @@ import SidebarDisclosureContext, { useSidebarDisclosureState, } from "./SidebarDisclosureContext"; import { useSidebarContext, type SidebarContextType } from "./SidebarContext"; +import { useSidebarNavigation } from "./SidebarNavigation"; type Props = { membership: UserMembership | GroupMembership; @@ -41,19 +43,23 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { const { fetchChildDocuments } = documents; const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean(); const { documentId } = membership; - const isActiveDocument = documentId === ui.activeDocumentId; + const isActiveDocument = useComputed( + () => documentId === ui.activeDocumentId, + [documentId, ui] + ); const activeSidebarContext = useActiveSidebarContext(); const sidebarContext = useSidebarContext(); const document = documentId ? documents.get(documentId) : undefined; const membershipDocuments = membership.documents; - const expansion = useSidebarExpansionState( - membershipDocuments, - ui.activeDocumentId + const expansion = useSidebarExpansionState(membershipDocuments); + const isActiveDocumentInPath = useComputed( + () => + ui.activeDocumentId + ? membership.pathToDocument(ui.activeDocumentId).length > 0 + : false, + [membership, ui] ); - const isActiveDocumentInPath = ui.activeDocumentId - ? membership.pathToDocument(ui.activeDocumentId).length > 0 - : false; const [expanded, setExpanded, setCollapsed] = useBoolean( isActiveDocumentInPath && activeSidebarContext === sidebarContext @@ -123,6 +129,7 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { ); const [{ isOverReparent }, dropToReparent] = useDropToReparentDocument( reparentableNode, + undefined, setExpanded, parentRef ); @@ -150,6 +157,25 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { const displayChildDocuments = expanded && !isDragging; + const getNavigationItems = React.useCallback( + () => + document + ? [ + { + id: document.id, + url: document.path, + title: document.title, + sidebarContext, + collapsedChildren: displayChildDocuments + ? undefined + : membershipDocuments, + }, + ] + : [], + [document, sidebarContext, displayChildDocuments, membershipDocuments] + ); + useSidebarNavigation(parentRef, getNavigationItems); + if (!document) { return null; } @@ -158,7 +184,7 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { const label = determineIconType(docIcon) === IconType.Emoji ? document.title.replace(docIcon!, "") - : document.titleWithDefault; + : document.displayTitle; const collection = document.collectionId ? collections.get(document.collectionId) : undefined; @@ -201,6 +227,14 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { parentRef={parentRef} dropToReparentRef={dropToReparent} isActiveDropTarget={isOverReparent} + cursorAfter={ + reorderProps.isDragging ? ( + + ) : undefined + } menu={menu} menuOpen={menuOpen} isActiveOverride={isActive} @@ -208,28 +242,19 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { - {childDocuments.map((childNode, index) => ( - - ))} + - {reorderProps.isDragging && ( - - )} ); } diff --git a/app/components/Sidebar/components/SidebarActions.tsx b/app/components/Sidebar/components/SidebarActions.tsx new file mode 100644 index 0000000000..aa305f6134 --- /dev/null +++ b/app/components/Sidebar/components/SidebarActions.tsx @@ -0,0 +1,76 @@ +import styled, { css } from "styled-components"; +import EventBoundary from "@shared/components/EventBoundary"; +import { s } from "@shared/styles"; +import NudeButton from "~/components/NudeButton"; + +/** + * Selector list matching a sidebar row that is hovered, pressed, or has one + * of its menus open. Radix marks the open trigger with `data-state="open"`: + * the row itself for a context menu, a descendant button for a dropdown. + */ +export const hoveredOrMenuOpen = `&:hover, &:active, &[data-state="open"], &:has([data-state="open"])`; + +/** + * Trailing action buttons for a sidebar row. Hidden until the row reveals + * them, see `revealActionsOnHover`. The parent must be positioned. + */ +export const SidebarActions = styled(EventBoundary)<{ + $showActions?: boolean; +}>` + display: inline-flex; + visibility: ${(props) => (props.$showActions ? "visible" : "hidden")}; + position: absolute; + inset-block: 0; + inset-inline-end: 4px; + margin-block: auto; + height: 24px; + color: ${s("textTertiary")}; + background: var(--background); + transition: opacity 50ms; + + [data-drag-active] & { + display: none; + } + + svg { + color: ${s("textSecondary")}; + fill: currentColor; + opacity: 0.5; + } + + &:hover { + visibility: visible; + + svg { + opacity: 0.75; + } + } + + ${NudeButton} { + background: transparent; + + &:hover, + &[aria-expanded="true"] { + background: ${s("sidebarControlHoverBackground")}; + } + } +`; + +/** + * Mixin for a sidebar row that reveals its `SidebarActions` while hovered, + * focused, or while one of its menus is open. + */ +export const revealActionsOnHover = css` + @media (hover: hover) { + ${hoveredOrMenuOpen}, + &:focus-within { + ${SidebarActions} { + visibility: visible; + + svg { + opacity: 0.75; + } + } + } + } +`; diff --git a/app/components/Sidebar/components/SidebarButton.tsx b/app/components/Sidebar/components/SidebarButton.tsx index c306b2b6c5..0e9b4e45a3 100644 --- a/app/components/Sidebar/components/SidebarButton.tsx +++ b/app/components/Sidebar/components/SidebarButton.tsx @@ -10,56 +10,54 @@ import { draggableOnDesktop, undraggableOnDesktop } from "~/styles"; import Desktop from "~/utils/Desktop"; import { HStack } from "~/components/primitives/HStack"; -export type SidebarButtonProps = React.ComponentProps & { +export type SidebarButtonProps = Omit< + React.ButtonHTMLAttributes, + "title" +> & { position?: "top" | "bottom"; - title: React.ReactNode; + title?: React.ReactNode; image: React.ReactNode; showMoreMenu?: boolean; - onClick: React.MouseEventHandler; + onClick?: React.MouseEventHandler; children?: React.ReactNode; + ref?: React.Ref; }; -const SidebarButton = observer( - React.forwardRef( - function SidebarButton_( - { - position = "top", - showMoreMenu, - image, - title, - children, - onClick, - ...rest - }: SidebarButtonProps, - ref - ) { - return ( - - - {children} - - ); - } - ) -); +const SidebarButton = observer(function SidebarButton({ + position = "top", + showMoreMenu, + image, + title, + children, + onClick, + ref, + ...rest +}: SidebarButtonProps) { + return ( + + + {children} + + ); +}); const StyledMoreIcon = styled(MoreIcon)` flex-shrink: 0; diff --git a/app/components/Sidebar/components/SidebarContext.ts b/app/components/Sidebar/components/SidebarContext.ts index edbde78173..1c08ae9ff4 100644 --- a/app/components/Sidebar/components/SidebarContext.ts +++ b/app/components/Sidebar/components/SidebarContext.ts @@ -5,6 +5,7 @@ import type User from "~/models/User"; export type SidebarContextType = | "collections" | "shared" + | "personal" | "archive" | `group-${string}` | `starred-${string}` @@ -20,6 +21,21 @@ export const groupSidebarContext = (groupId: string): SidebarContextType => export const starredSidebarContext = (modelId: string): SidebarContextType => `starred-${modelId}`; +/** + * Whether a sidebar context matches the active sidebar context. When no context + * is active, the collections context is treated as active. + * + * @param sidebarContext the context to check. + * @param activeSidebarContext the active context. + * @returns true if the context is active. + */ +export const isActiveSidebarContext = ( + sidebarContext: SidebarContextType, + activeSidebarContext: SidebarContextType +): boolean => + sidebarContext === activeSidebarContext || + (!activeSidebarContext && sidebarContext === "collections"); + export const determineSidebarContext = ({ document, user, @@ -42,7 +58,10 @@ export const determineSidebarContext = ({ } if (document.collection) { - return document.collection.isArchived ? "archive" : "collections"; + if (document.collection.isArchived) { + return "archive"; + } + return document.collection.isPersonal ? "personal" : "collections"; } else if ( user.documentMemberships.find((m) => m.documentId === document.id) ) { diff --git a/app/components/Sidebar/components/SidebarExpansionContext.test.ts b/app/components/Sidebar/components/SidebarExpansionContext.test.ts new file mode 100644 index 0000000000..3cb15fdd1d --- /dev/null +++ b/app/components/Sidebar/components/SidebarExpansionContext.test.ts @@ -0,0 +1,44 @@ +import { autorun } from "mobx"; +import { SidebarExpansionState } from "./SidebarExpansionContext"; + +describe("SidebarExpansionState", () => { + it("should only notify observers of the node that changed", () => { + const state = new SidebarExpansionState(); + let runs = 0; + const dispose = autorun(() => { + state.isExpanded("a"); + runs++; + }); + + state.expand("b"); + state.expandPath(["c", "d"]); + expect(runs).toBe(1); + + state.expand("a"); + expect(runs).toBe(2); + + state.collapse("a"); + expect(state.isExpanded("a")).toBe(false); + expect(runs).toBe(3); + + dispose(); + }); + + it("should expand and collapse descendants", () => { + const state = new SidebarExpansionState(); + const node = { + id: "a", + title: "A", + url: "/doc/a", + children: [{ id: "b", title: "B", url: "/doc/b", children: [] }], + }; + + state.expandDescendants(node); + expect(state.isExpanded("a")).toBe(true); + expect(state.isExpanded("b")).toBe(true); + + state.collapseDescendants(node); + expect(state.isExpanded("a")).toBe(false); + expect(state.isExpanded("b")).toBe(false); + }); +}); diff --git a/app/components/Sidebar/components/SidebarExpansionContext.ts b/app/components/Sidebar/components/SidebarExpansionContext.ts index cff34538ad..733a04cbcd 100644 --- a/app/components/Sidebar/components/SidebarExpansionContext.ts +++ b/app/components/Sidebar/components/SidebarExpansionContext.ts @@ -1,6 +1,7 @@ -import { action, makeObservable, observable } from "mobx"; +import { action, autorun, makeObservable, observable } from "mobx"; import { createContext, useContext, useEffect, useState } from "react"; import type { NavigationNode } from "@shared/types"; +import useStores from "~/hooks/useStores"; /** * Computes the set of node IDs along the path from any node in `roots` down @@ -38,13 +39,12 @@ function computeAncestorPath( /** * Manages the set of expanded node IDs for a sidebar document tree. * - * Uses a MobX ObservableSet so that individual `observer`-wrapped - * DocumentLinks only re-render when their own node's membership in the set - * changes, rather than on every expansion toggle anywhere in the tree. + * Uses a MobX ObservableMap, which tracks `has` per key, so that individual + * `observer`-wrapped DocumentLinks only re-render when their own node is + * expanded or collapsed, rather than on every expansion change in the tree. */ export class SidebarExpansionState { - @observable - expandedIds = new Set(); + expandedIds = observable.map(); constructor() { makeObservable(this); @@ -67,7 +67,7 @@ export class SidebarExpansionState { */ @action expand(nodeId: string): void { - this.expandedIds.add(nodeId); + this.expandedIds.set(nodeId, true); } /** @@ -88,7 +88,7 @@ export class SidebarExpansionState { @action expandDescendants(node: NavigationNode): void { const walk = (n: NavigationNode) => { - this.expandedIds.add(n.id); + this.expandedIds.set(n.id, true); for (const child of n.children) { walk(child); } @@ -120,7 +120,7 @@ export class SidebarExpansionState { @action expandPath(ids: Iterable): void { for (const id of ids) { - this.expandedIds.add(id); + this.expandedIds.set(id, true); } } @@ -133,7 +133,7 @@ export class SidebarExpansionState { expandAll(roots: NavigationNode[]): void { const walk = (nodes: NavigationNode[]) => { for (const node of nodes) { - this.expandedIds.add(node.id); + this.expandedIds.set(node.id, true); walk(node.children); } }; @@ -179,24 +179,31 @@ export function useSidebarExpansion(): SidebarExpansionState { * to be provided via SidebarExpansionContext.Provider. * * @param roots the top-level navigation nodes (e.g. collection documents). - * @param activeDocumentId the currently active document ID. * @returns the expansion state instance. */ export function useSidebarExpansionState( - roots: NavigationNode[] | undefined, - activeDocumentId: string | undefined + roots: NavigationNode[] | undefined ): SidebarExpansionState { + const { ui } = useStores(); const [state] = useState(() => new SidebarExpansionState()); + // The active document is read in a reaction rather than during render, so + // that the component does not re-render on every navigation. useEffect(() => { - if (!roots || !activeDocumentId) { + if (!roots) { return; } - const path = computeAncestorPath(roots, activeDocumentId); - if (path.length > 0) { - state.expandPath(path); - } - }, [state, roots, activeDocumentId]); + return autorun(() => { + const activeDocumentId = ui.activeDocumentId; + if (!activeDocumentId) { + return; + } + const path = computeAncestorPath(roots, activeDocumentId); + if (path.length > 0) { + state.expandPath(path); + } + }); + }, [state, roots, ui]); return state; } diff --git a/app/components/Sidebar/components/SidebarLink.tsx b/app/components/Sidebar/components/SidebarLink.tsx index 46d89cd5e7..3894a530dc 100644 --- a/app/components/Sidebar/components/SidebarLink.tsx +++ b/app/components/Sidebar/components/SidebarLink.tsx @@ -2,20 +2,45 @@ import type { LocationDescriptor } from "history"; import * as React from "react"; import styled, { useTheme, css } from "styled-components"; import breakpoint from "styled-components-breakpoint"; -import EventBoundary from "@shared/components/EventBoundary"; import { ellipsis, hover, s } from "@shared/styles"; import { isMobile } from "@shared/utils/browser"; -import NudeButton from "~/components/NudeButton"; import { UnreadBadge } from "~/components/UnreadBadge"; import useClickIntent from "~/hooks/useClickIntent"; import { undraggableOnDesktop } from "~/styles"; import Disclosure from "./Disclosure"; import type { Props as NavLinkProps } from "./NavLink"; import NavLink from "./NavLink"; +import { + SidebarActions, + hoveredOrMenuOpen, + revealActionsOnHover, +} from "./SidebarActions"; import type { ActionFactory, ActionWithChildren } from "~/types"; import { ContextMenu } from "~/components/Menu/ContextMenu"; import { useTranslation } from "react-i18next"; +/** + * Returns the inline-start offset in pixels of a sidebar row's content at the + * given nesting depth. + * + * @param depth The nesting depth of the row, 0-based. + * @returns the offset in pixels. + */ +export function indentForDepth(depth: number): number { + return depth * 16 + 12; +} + +/** + * Returns the nesting depth of the children of a sidebar row. A row at depth 0 + * shows an icon, so its children skip a level to start beyond the icon. + * + * @param depth The nesting depth of the row, 0-based. + * @returns the nesting depth of the children. + */ +export function childDepthFor(depth: number): number { + return depth === 0 ? 2 : depth + 1; +} + /** * Props for the SidebarLink component. * Extends NavLink props with additional sidebar-specific functionality. @@ -25,10 +50,12 @@ type Props = Omit & { to?: LocationDescriptor; /** Ref callback to access the underlying HTML element */ innerRef?: (ref: HTMLElement | null | undefined) => void; + /** Ref to the rendered link element */ + ref?: React.Ref; /** Callback fired when the link is clicked */ onClick?: React.MouseEventHandler; /** Callback when we expect the user to click on the link. Used for prefetching data. */ - onClickIntent?: React.MouseEventHandler; + onClickIntent?: () => void; /** Callback fired when the disclosure icon is clicked */ onDisclosureClick?: React.MouseEventHandler; /** Icon to display on the left side of the link */ @@ -72,39 +99,38 @@ const stopPropagation = (ev: React.MouseEvent) => { ev.stopPropagation(); }; -function SidebarLink( - { - icon, - onClick, - onClickIntent, - to, - label, - active, - isActiveDrop, - isDraft, - menu, - $showActions, - exact, - href, - depth, - className, - expanded, - onDisclosureClick, - disabled, - unreadBadge, - contextAction, - ellipsis = true, - ...rest - }: Props, - ref: React.RefObject -) { +function SidebarLink({ + icon, + onClick, + onClickIntent, + to, + label, + active, + isActiveDrop, + isDraft, + menu, + $showActions, + exact, + href, + depth, + className, + expanded, + onDisclosureClick, + disabled, + unreadBadge, + contextAction, + ellipsis = true, + ref, + ...rest +}: Props) { const hasDisclosure = expanded !== undefined; const { t } = useTranslation(); const theme = useTheme(); + const [isInteractive, setIsInteractive] = React.useState(false); const { handleMouseEnter, handleMouseLeave } = useClickIntent(onClickIntent); const style = React.useMemo( () => ({ - paddingInlineStart: `${(depth || 0) * 16 + (icon ? -8 : 12)}px`, + paddingInlineStart: `${indentForDepth(depth || 0) - (icon ? 20 : 0)}px`, paddingInlineEnd: unreadBadge ? "32px" : undefined, }), [depth, icon, unreadBadge] @@ -147,26 +173,42 @@ function SidebarLink( [onDisclosureClick, hasDisclosure] ); + const handleFocusCapture = (event: React.FocusEvent) => { + if (event.target === event.currentTarget) { + setIsInteractive(true); + } + }; + const DisclosureComponent = icon ? HiddenDisclosure : Disclosure; + const content = ( + + {hasDisclosure && ( + + )} + {icon && {icon}} + + {unreadBadge && } + + ); + const innerContent = ( <> - - - {hasDisclosure && ( - - )} - {icon && {icon}} - - {unreadBadge && } - - - {menu && {menu}} + {isInteractive ? ( + + {content} + + ) : ( + content + )} + {isInteractive && menu && ( + {menu} + )} ); @@ -180,6 +222,8 @@ function SidebarLink( style={active ? activeStyle : style} onClick={handleClick} onMouseEnter={handleMouseEnter} + onPointerEnter={() => setIsInteractive(true)} + onFocusCapture={handleFocusCapture} onMouseLeave={handleMouseLeave} onDragEnter={handleMouseEnter} href={href} @@ -194,6 +238,7 @@ function SidebarLink( return ( setIsInteractive(true)} + onFocusCapture={handleFocusCapture} onMouseLeave={handleMouseLeave} onDragEnter={handleMouseEnter} exact={exact !== false} to={to!} href={href} className={className} - // @ts-expect-error spread props cause overload mismatch with styled NavLink ref={ref} {...rest} > @@ -234,58 +280,24 @@ const Content = styled.span` min-width: 0; `; -const Actions = styled(EventBoundary)<{ $showActions?: boolean }>` - display: inline-flex; - visibility: ${(props) => (props.$showActions ? "visible" : "hidden")}; - - [data-drag-active] & { - display: none; - } - - position: absolute; - top: 3px; - inset-inline-end: 4px; - gap: 4px; - color: ${s("textTertiary")}; - transition: opacity 50ms; - height: 24px; - background: var(--background); - - svg { - color: ${s("textSecondary")}; - fill: currentColor; - opacity: 0.5; - } - - &:hover { - visibility: visible; - - svg { - opacity: 0.75; - } - } -`; - +// Stays over the icon while invisible so that a tap on the icon toggles, even +// on touch devices where there is no hover to reveal it first. const HiddenDisclosure = styled(Disclosure)` - position: inherit; inset-inline-start: initial; - display: none; + opacity: 0; margin-inline-start: -2px; - margin-inline-end: 6px; `; -const Link = styled(NavLink)<{ +const Link = styled.a<{ $isActiveDrop?: boolean; $isDraft?: boolean; $disabled?: boolean; }>` - &:hover, - &:active, - &:has([data-state="open"]) { + ${hoveredOrMenuOpen} { --background: ${s("sidebarHoverBackground")}; } - &[aria-current="page"] ${Actions} { + &[aria-current="page"] ${SidebarActions} { --background: ${s("sidebarActiveBackground")}; } @@ -338,12 +350,11 @@ const Link = styled(NavLink)<{ &: ${hover}, &:has([data-state="open"]) { ${HiddenDisclosure} { - display: block; + opacity: 1; } ${HiddenDisclosure} + ${IconWrapper} { visibility: hidden; opacity: 0; - width: 0; } } @@ -353,34 +364,14 @@ const Link = styled(NavLink)<{ font-size: 14px; `} + ${revealActionsOnHover} + @media (hover: hover) { - &:hover ${Actions}, - &:active ${Actions}, - &:has([data-state="open"]) ${Actions} { - visibility: visible; - - svg { - opacity: 0.75; - } - } - - &:hover, - &:has([data-state="open"]) { + ${hoveredOrMenuOpen} { color: ${(props) => props.$isActiveDrop ? props.theme.white : props.theme.text}; } } - - & ${Actions} { - ${NudeButton} { - background: transparent; - - &:hover, - &[aria-expanded="true"] { - background: ${s("sidebarControlHoverBackground")}; - } - } - } `; const Label = styled.div<{ $ellipsis: boolean }>` @@ -398,4 +389,4 @@ const Label = styled.div<{ $ellipsis: boolean }>` } `; -export default React.forwardRef(SidebarLink); +export default SidebarLink; diff --git a/app/components/Sidebar/components/SidebarNavigation.tsx b/app/components/Sidebar/components/SidebarNavigation.tsx new file mode 100644 index 0000000000..cb8a637fd9 --- /dev/null +++ b/app/components/Sidebar/components/SidebarNavigation.tsx @@ -0,0 +1,161 @@ +import { observer } from "mobx-react"; +import * as React from "react"; +import type { NavigationNode } from "@shared/types"; +import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; +import useKeyDown from "~/hooks/useKeyDown"; +import useStores from "~/hooks/useStores"; +import history from "~/utils/history"; +import { + isActiveSidebarContext, + type SidebarContextType, +} from "./SidebarContext"; + +/** A sidebar row that keyboard navigation can move to. */ +export interface SidebarNavigationItem { + /** Id of the document or collection that the row links to. */ + id: string; + /** Path that the row links to. */ + url: string; + /** Title of the row. */ + title: string; + /** Sidebar context that the row is rendered in. */ + sidebarContext: SidebarContextType; + /** Children hidden below the row, when it is collapsed. */ + collapsedChildren?: NavigationNode[]; +} + +/** + * Provides keyboard navigation between the rows of the sidebar. Alt+Up and + * Alt+Down move to the previous and next row, in the order they are shown. + */ +export const SidebarNavigationProvider = observer( + function SidebarNavigationProvider({ + children, + }: { + children: React.ReactNode; + }) { + const { ui } = useStores(); + const activeSidebarContext = useActiveSidebarContext(); + const [registry] = React.useState(() => new SidebarNavigationRegistry()); + + const handleNavigate = React.useCallback( + (event: KeyboardEvent) => { + const activeId = ui.activeDocumentId ?? ui.activeCollectionId; + if (!activeId) { + return; + } + const items = registry.getItems(); + const index = items.findIndex( + (item) => + item.id === activeId && + isActiveSidebarContext(item.sidebarContext, activeSidebarContext) + ); + if (index === -1) { + return; + } + const offset = event.key === "ArrowUp" ? -1 : 1; + const item = items[index + offset]; + if (!item) { + return; + } + + // Moving up into a collapsed row goes to its last descendant. + let target: Pick = item; + if (offset < 0 && item.collapsedChildren?.length) { + let node = item.collapsedChildren[item.collapsedChildren.length - 1]; + while (node.children.length) { + node = node.children[node.children.length - 1]; + } + target = node; + } + + event.preventDefault(); + history.push({ + pathname: target.url, + state: { title: target.title, sidebarContext: item.sidebarContext }, + }); + }, + [ui, registry, activeSidebarContext] + ); + useKeyDown(isAltArrow, handleNavigate, keyDownOptions); + + return ( + + {children} + + ); + } +); + +/** + * Registers sidebar rows for keyboard navigation. The rows are ordered by the + * position of the element in the sidebar. + * + * @param ref the element that contains the rows. + * @param getItems function that returns the rows, called when a key is pressed. + */ +export function useSidebarNavigation( + ref: React.RefObject, + getItems: () => SidebarNavigationItem[] +): void { + const registry = React.useContext(SidebarNavigationContext); + + React.useEffect(() => { + if (!registry) { + return; + } + const entry = { ref, getItems }; + registry.add(entry); + return () => registry.delete(entry); + }, [registry, ref, getItems]); +} + +interface RegistryEntry { + ref: React.RefObject; + getItems: () => SidebarNavigationItem[]; +} + +class SidebarNavigationRegistry { + public add(entry: RegistryEntry) { + this.entries.add(entry); + } + + public delete(entry: RegistryEntry) { + this.entries.delete(entry); + } + + /** + * Returns the registered rows in the order they are shown in the sidebar. + * + * @returns the rows. + */ + public getItems(): SidebarNavigationItem[] { + return [...this.entries] + .flatMap((entry) => + entry.ref.current ? [{ element: entry.ref.current, entry }] : [] + ) + .sort((a, b) => + a.element.compareDocumentPosition(b.element) & + Node.DOCUMENT_POSITION_FOLLOWING + ? -1 + : 1 + ) + .flatMap(({ entry }) => entry.getItems()); + } + + private entries = new Set(); +} + +const SidebarNavigationContext = + React.createContext(null); + +// Alt+Shift+Arrow selects text, so other modifiers must not be held. +const isAltArrow = (event: KeyboardEvent) => + (event.key === "ArrowUp" || event.key === "ArrowDown") && + event.altKey && + !event.shiftKey && + !event.metaKey && + !event.ctrlKey; + +// The shortcut also works while the document editor has focus. +const keyDownOptions = { allowInTextInput: true }; diff --git a/app/components/Sidebar/components/StarredLink.tsx b/app/components/Sidebar/components/StarredLink.tsx index d224b1d88f..6a48f7df56 100644 --- a/app/components/Sidebar/components/StarredLink.tsx +++ b/app/components/Sidebar/components/StarredLink.tsx @@ -15,6 +15,7 @@ import type { RefHandle } from "~/components/EditableTitle"; import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; import useBoolean from "~/hooks/useBoolean"; import { useCollectionMenuAction } from "~/hooks/useCollectionMenuAction"; +import { useComputed } from "~/hooks/useComputed"; import useCurrentUser from "~/hooks/useCurrentUser"; import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction"; import usePolicy from "~/hooks/usePolicy"; @@ -35,7 +36,7 @@ import SidebarExpansionContext, { } from "./SidebarExpansionContext"; import CollectionLinkChildren from "./CollectionLinkChildren"; import CollectionRow from "./CollectionRow"; -import DocumentLink from "./DocumentLink"; +import { DocumentTree } from "./DocumentTree"; import DocumentRow from "./DocumentRow"; import DropCursor from "./DropCursor"; import Folder from "./Folder"; @@ -46,6 +47,7 @@ import SidebarDisclosureContext, { useSidebarDisclosure, useSidebarDisclosureState, } from "./SidebarDisclosureContext"; +import { useSidebarNavigation } from "./SidebarNavigation"; type Props = { star: Star; @@ -109,10 +111,22 @@ const StarredDocumentLink = observer(function StarredDocumentLink({ : emptyChildDocuments; const hasChildDocuments = childDocuments.length > 0; const displayChildDocuments = expanded && !isDragging; - const expansion = useSidebarExpansionState( - childDocuments, - documents.active?.id + const parentRef = React.useRef(null); + + const getNavigationItems = React.useCallback( + () => [ + { + id: document.id, + url: document.path, + title: document.title, + sidebarContext, + collapsedChildren: displayChildDocuments ? undefined : childDocuments, + }, + ], + [document, sidebarContext, displayChildDocuments, childDocuments] ); + useSidebarNavigation(parentRef, getNavigationItems); + const expansion = useSidebarExpansionState(childDocuments); const handleCascadeExpand = React.useCallback(() => { if (childDocuments.length) { @@ -204,10 +218,11 @@ const StarredDocumentLink = observer(function StarredDocumentLink({ documentId={document.id} document={document} to={{ pathname: document.path, state: { sidebarContext } }} + parentRef={parentRef} depth={0} icon={icon} canEdit={can.update} - labelText={document.titleWithDefault} + labelText={document.displayTitle} onTitleChange={handleTitleChange} editableTitleRef={editableTitleRef} expanded={expanded} @@ -229,19 +244,13 @@ const StarredDocumentLink = observer(function StarredDocumentLink({ - {childDocuments.map((node, index) => ( - - ))} + {cursor} @@ -344,7 +353,7 @@ const StarredCollectionLink = observer(function StarredCollectionLink({ onExpand={handleExpand} onClickIntent={handlePrefetch} canEdit={can.update} - labelText={collection.name} + labelText={collection.displayName} onTitleChange={handleTitleChange} editableTitleRef={editableTitleRef} contextAction={contextMenuAction} @@ -356,11 +365,15 @@ const StarredCollectionLink = observer(function StarredCollectionLink({ dropRef={dropRef} isActiveDropTarget={isOver && canDrop} > - + {(newChild) => ( + + {newChild} + + )} {cursor} @@ -378,33 +391,39 @@ function StarredLink({ star }: Props) { const sidebarContext = starredSidebarContext( star.documentId ?? star.collectionId ?? "" ); + // Computed so that only the stars that become active or inactive re-render + // when navigating. + const isActive = useComputed( + () => + star.documentId + ? star.documentId === ui.activeDocumentId + : star.collectionId === ui.activeCollectionId, + [star, ui] + ); + const activeDocumentId = useComputed( + () => (isActive ? ui.activeDocumentId : undefined), + [isActive, ui] + ); const [expanded, setExpanded] = useState( - (star.documentId - ? star.documentId === ui.activeDocumentId - : star.collectionId === ui.activeCollectionId) && - sidebarContext === activeSidebarContext + isActive && sidebarContext === activeSidebarContext ); const { event: disclosureEvent, onDisclosureClick } = useSidebarDisclosureState(); + // The sidebar context is unique to the star, so a starred document also + // expands when one of its descendants is active in it. React.useEffect(() => { if ( - star.documentId === ui.activeDocumentId && - sidebarContext === activeSidebarContext - ) { - setExpanded(true); - } else if ( - star.collectionId === ui.activeCollectionId && + (isActive || star.documentId) && sidebarContext === activeSidebarContext ) { setExpanded(true); } }, [ + isActive, + activeDocumentId, star.documentId, - star.collectionId, - ui.activeDocumentId, - ui.activeCollectionId, sidebarContext, activeSidebarContext, ]); @@ -438,7 +457,7 @@ function StarredLink({ star }: Props) { const handlePrefetch = React.useCallback(() => { if (documentId) { - void Scenes.Document.preload(); + Scenes.preloadEditor(); void documents.prefetchDocument(documentId); const document = documents.get(documentId); const documentCollection = document?.collectionId @@ -456,21 +475,31 @@ function StarredLink({ star }: Props) { const [reorderStarProps, dropToReorderRef] = useDropToReorderStar(getIndex); const [createStarProps, dropToStarRef] = useDropToCreateStar(getIndex); - const cursor = ( - <> - {reorderStarProps.isDragging && ( - - )} - {createStarProps.isDragging && ( - - )} - + const cursor = React.useMemo( + () => ( + <> + {reorderStarProps.isDragging && ( + + )} + {createStarProps.isDragging && ( + + )} + + ), + [ + reorderStarProps.isDragging, + reorderStarProps.isOverCursor, + dropToReorderRef, + createStarProps.isDragging, + createStarProps.isOverCursor, + dropToStarRef, + ] ); if (document) { diff --git a/app/components/Sidebar/components/StaticLink.tsx b/app/components/Sidebar/components/StaticLink.tsx new file mode 100644 index 0000000000..83fb0249d1 --- /dev/null +++ b/app/components/Sidebar/components/StaticLink.tsx @@ -0,0 +1,21 @@ +import type * as React from "react"; + +interface Props extends React.HTMLAttributes { + /** Provided by react-router's Link and ignored. */ + href?: string; + /** Provided by react-router's Link and ignored. */ + navigate?: () => void; + /** Ref forwarded by react-router's Link. */ + innerRef?: React.Ref; +} + +/** + * A non-navigating replacement for a Link's anchor element, used while a + * sidebar row is being edited. + * + * @param props The props passed through by react-router's Link. + * @returns A div with the link's presentational props. + */ +export function StaticLink({ href, navigate, innerRef, ...rest }: Props) { + return
; +} diff --git a/app/components/Sidebar/components/TrashLink.tsx b/app/components/Sidebar/components/TrashLink.tsx index 26f90ff48d..77fc4e9286 100644 --- a/app/components/Sidebar/components/TrashLink.tsx +++ b/app/components/Sidebar/components/TrashLink.tsx @@ -1,20 +1,19 @@ import { observer } from "mobx-react"; import { TrashIcon } from "outline-icons"; -import { useDrop } from "react-dnd"; import { useTranslation } from "react-i18next"; import DocumentDelete from "~/scenes/DocumentDelete"; import { DialogTitle } from "~/components/DialogTitle"; import useStores from "~/hooks/useStores"; import * as Scenes from "~/routes/scenes"; import { trashPath } from "~/utils/routeHelpers"; -import type { DragObject } from "../hooks/useDragAndDrop"; +import { type DragObject, useDropRef } from "../hooks/useDragAndDrop"; import SidebarLink from "./SidebarLink"; function TrashLink() { const { policies, dialogs, documents } = useStores(); const { t } = useTranslation(); - const [{ isDocumentDropping }, dropToTrashRef] = useDrop({ + const [{ isDocumentDropping }, dropToTrashRef] = useDropRef({ accept: "document", drop: async (item: DragObject) => { const document = documents.get(item.id); diff --git a/app/components/Sidebar/hooks/useDragAndDrop.tsx b/app/components/Sidebar/hooks/useDragAndDrop.tsx index 6fce7a890e..d49291efa8 100644 --- a/app/components/Sidebar/hooks/useDragAndDrop.tsx +++ b/app/components/Sidebar/hooks/useDragAndDrop.tsx @@ -1,6 +1,13 @@ import fractionalIndex from "fractional-index"; import * as React from "react"; -import type { ConnectDragSource } from "react-dnd"; +import type { + ConnectDragPreview, + ConnectDragSource, + ConnectDropTarget, + DragSourceHookSpec, + DropTargetHookSpec, + FactoryOrInstance, +} from "react-dnd"; import { useDrag, useDrop } from "react-dnd"; import { getEmptyImage } from "react-dnd-html5-backend"; import { useTranslation } from "react-i18next"; @@ -27,19 +34,79 @@ import { useSidebarLabelAndIcon } from "./useSidebarLabelAndIcon"; export type DragObject = NavigationNode & { depth: number; collectionId: string; - /** - * Whether the drag ghost should stay tethered to the sidebar. Defaults to - * tethered when unset — the placeholder only lets the ghost follow the - * cursor when this is explicitly `false` (e.g. drags from a document list). - */ - constrainToSidebar?: boolean; }; +/** + * Adapts a react-dnd connector to a ref callback. Connectors return the + * connected node so that calls can be chained, which React does not permit + * from a ref. + * + * @param connect The connector to adapt. + * @returns a ref callback. + */ +function useConnectorRef( + connect: ConnectDragSource | ConnectDropTarget +): React.RefCallback { + return React.useCallback( + (node: HTMLElement | null) => void connect(node), + [connect] + ); +} + +/** + * Wrapper around react-dnd's `useDrag` that returns the connector as a ref + * callback. + * + * @param spec The drag source specification. + * @returns a tuple of the collected props, a ref callback and the drag preview + * connector. + */ +export function useDragRef< + DragObj = unknown, + DropResult = unknown, + CollectedProps = unknown, +>( + spec: FactoryOrInstance< + DragSourceHookSpec + > +): [CollectedProps, React.RefCallback, ConnectDragPreview] { + const [collected, connect, preview] = useDrag< + DragObj, + DropResult, + CollectedProps + >(spec); + return [collected, useConnectorRef(connect), preview]; +} + +/** + * Wrapper around react-dnd's `useDrop` that returns the connector as a ref + * callback. + * + * @param spec The drop target specification. + * @returns a tuple of the collected props and a ref callback. + */ +export function useDropRef< + DragObj = unknown, + DropResult = unknown, + CollectedProps = unknown, +>( + spec: FactoryOrInstance< + DropTargetHookSpec + > +): [CollectedProps, React.RefCallback] { + const [collected, connect] = useDrop( + spec + ); + return [collected, useConnectorRef(connect)]; +} + function useHover( - elementRef: React.RefObject, + elementRef: React.RefObject, callback: () => void ) { - const hoverTimeoutRef = React.useRef>(); + const hoverTimeoutRef = React.useRef< + ReturnType | undefined + >(undefined); const startHover = React.useCallback(() => { if (!hoverTimeoutRef.current) { @@ -75,11 +142,11 @@ function useHover( */ export function useDragStar( star: Star -): [{ isDragging: boolean }, ConnectDragSource] { +): [{ isDragging: boolean }, React.RefCallback] { const id = star.id; const { label: title, icon } = useSidebarLabelAndIcon(star); - const [{ isDragging }, draggableRef, preview] = useDrag({ + const [{ isDragging }, dragRef, preview] = useDragRef({ type: "star", item: () => ({ id, title, icon }), collect: (monitor) => ({ @@ -91,7 +158,7 @@ export function useDragStar( preview(getEmptyImage(), { captureDraggingState: true }); }, [preview]); - return [{ isDragging }, draggableRef]; + return [{ isDragging }, dragRef]; } /** @@ -109,7 +176,7 @@ export function useDropToCreateStar(getIndex?: () => string) { const { documents, stars, collections, userMemberships, groupMemberships } = useStores(); - return useDrop< + return useDropRef< DragObject, Promise, { isOverCursor: boolean; isDragging: boolean } @@ -153,7 +220,7 @@ export function useDropToCreateStar(getIndex?: () => string) { export function useDropToReorderStar(getIndex?: () => string) { const { stars } = useStores(); - return useDrop< + return useDropRef< DragObject, Promise, { isOverCursor: boolean; isDragging: boolean } @@ -182,8 +249,8 @@ export function useDropToReorderStar(getIndex?: () => string) { export function useDragSidebarSection( section: SidebarSection, title: string -): [{ isDragging: boolean }, ConnectDragSource] { - const [{ isDragging }, draggableRef, preview] = useDrag({ +): [{ isDragging: boolean }, React.RefCallback] { + const [{ isDragging }, dragRef, preview] = useDragRef({ type: "sidebarSection", item: () => ({ id: section, title }), collect: (monitor) => ({ @@ -195,7 +262,7 @@ export function useDragSidebarSection( preview(getEmptyImage(), { captureDraggingState: true }); }, [preview]); - return [{ isDragging }, draggableRef]; + return [{ isDragging }, dragRef]; } /** @@ -209,7 +276,7 @@ export function useDropToReorderSidebarSection( ) { const user = useCurrentUser(); - return useDrop< + return useDropRef< { id: SidebarSection; title: string }, void, { isOverCursor: boolean; isDragging: boolean } @@ -237,22 +304,18 @@ export function useDropToReorderSidebarSection( * @param depth The depth of the node in the sidebar. * @param document The related Document model. * @param isEditing Whether the sidebar item is currently being edited. - * @param constrainToSidebar Whether the drag ghost should stay tethered to the - * sidebar. Defaults to true; pass false when dragging from outside the sidebar - * (e.g. a document list) so the ghost follows the cursor. */ export function useDragDocument( node: NavigationNode, depth: number, document?: Document, - isEditing?: boolean, - constrainToSidebar = true + isEditing?: boolean ) { const icon = document?.icon || node.icon || node.emoji; const color = document?.color || node.color; const initial = document?.initial || node.title; - const [{ isDragging }, draggableRef, preview] = useDrag< + const [{ isDragging }, dragRef, preview] = useDragRef< DragObject, Promise, { isDragging: boolean } @@ -266,7 +329,6 @@ export function useDragDocument( ) : undefined, collectionId: document?.collectionId || "", - constrainToSidebar, }) as DragObject, canDrag: () => !!document?.isActive && !isEditing, collect: (monitor) => ({ @@ -278,20 +340,20 @@ export function useDragDocument( preview(getEmptyImage(), { captureDraggingState: true }); }, [preview]); - return [{ isDragging }, draggableRef] as const; + return [{ isDragging }, dragRef] as const; } export function useDropToChangeCollection( collection: Collection, expandNode: () => void, - parentRef: React.RefObject + parentRef: React.RefObject ) { const { t } = useTranslation(); const { documents, collections, dialogs, policies } = useStores(); const can = usePolicy(collection); const startHover = useHover(parentRef, expandNode); - return useDrop< + return useDropRef< DragObject, Promise, { isOver: boolean; canDrop: boolean } @@ -332,7 +394,7 @@ export function useDropToChangeCollection( "You do not have permission to move {{ documentName }} to the {{ collectionName }} collection", { documentName: item.title, - collectionName: collection.name, + collectionName: collection.displayName, } ) ); @@ -363,48 +425,48 @@ export function useDropToChangeCollection( * Hook for shared logic that allows dropping documents to reparent * * @param node The NavigationNode model to drop. + * @param collection The collection that contains the node, if known. * @param setExpanded A function to expand the parent node. * @param parentRef A ref to the parent element that will be used to detect when the user is no longer hovering.. */ export function useDropToReparentDocument( node: NavigationNode | undefined, + collection: Collection | undefined, setExpanded: () => void, - parentRef: React.RefObject + parentRef: React.RefObject ) { const { t } = useTranslation(); const { documents, collections, dialogs, policies } = useStores(); const hasChildDocuments = !!node?.children.length; const document = node ? documents.get(node.id) : undefined; - const pathToNode = React.useMemo( - () => document?.pathTo.map((item) => item.id), - [document] - ); const startHover = useHover(parentRef, setExpanded); - return useDrop, { isOverReparent: boolean }>({ + return useDropRef, { isOverReparent: boolean }>({ accept: "document", drop: async (item, monitor) => { if (monitor.didDrop() || !node) { return; } - const collection = node.collectionId - ? collections.get(node.collectionId) - : undefined; + const collectionId = + node.collectionId ?? documents.get(node.id)?.collectionId; + const targetCollection = + collection ?? + (collectionId ? collections.get(collectionId) : undefined); const prevCollection = collections.get(item.collectionId); if ( - collection && + targetCollection && prevCollection && - prevCollection.permission !== collection.permission + prevCollection.permission !== targetCollection.permission ) { dialogs.openModal({ title: t("Change permissions?"), content: ( ), @@ -442,7 +504,10 @@ export function useDropToReparentDocument( return true; // optimistic, in case the document is not loaded yet; server will check for permissions before performing the move. } - return document.isActive && !!pathToNode && !pathToNode.includes(item.id); + return ( + document.isActive && + !document.pathTo.some((ancestor) => ancestor.id === item.id) + ); }, hover: (_item, monitor) => { // Enables expansion of document children when hovering over the document @@ -490,19 +555,33 @@ export function useDropToReorderDocument( const document = documents.get(node.id); - return useDrop, { isOverReorder: boolean }>({ + return useDropRef, { isOverReorder: boolean }>({ accept: "document", canDrop: (item: DragObject) => { - if (item.id === node.id || (document && !document.isActive)) { + if ( + (document && !document.isActive) || + !policies.abilities(item.id).move + ) { return false; } - return !!policies.abilities(item.id).move; + if (item.id !== node.id) { + return true; + } + // A document can only be dropped on its own cursor when that moves it to + // a different parent, e.g. out of the end of an expanded subtree. + const params = getMoveParams(item); + return ( + !!params && + params.parentDocumentId !== item.id && + (params.parentDocumentId ?? null) !== + (document?.parentDocumentId ?? null) + ); }, drop: async (item) => { if (!collection?.isManualSort && item.collectionId === collection?.id) { toast.message( t( - "You can't reorder documents in an alphabetically sorted collection" + "You can’t reorder documents in an alphabetically sorted collection" ) ); return; @@ -565,7 +644,7 @@ export function useDragMembership( const id = membership.id; const { label: title, icon } = useSidebarLabelAndIcon(membership); - const [{ isDragging }, draggableRef, preview] = useDrag({ + const [{ isDragging }, dragRef, preview] = useDragRef({ type: membership instanceof UserMembership ? "userMembership" @@ -580,7 +659,7 @@ export function useDragMembership( preview(getEmptyImage(), { captureDraggingState: true }); }, [preview]); - return [{ isDragging }, draggableRef] as const; + return [{ isDragging }, dragRef] as const; } /** @@ -592,7 +671,7 @@ export function useDropToReorderUserMembership(getIndex?: () => string) { const { userMemberships } = useStores(); const user = useCurrentUser(); - return useDrop< + return useDropRef< DragObject, Promise, { isOverCursor: boolean; isDragging: boolean } @@ -621,7 +700,7 @@ export function useDropToArchive() { const { documents, collections, policies } = useStores(); const { t } = useTranslation(); - return useDrop< + return useDropRef< DragObject, Promise, { isOverArchiveSection: boolean; isDragging: boolean } @@ -658,7 +737,7 @@ export function useDropToUnpublish() { const { t } = useTranslation(); const { policies, documents } = useStores(); - return useDrop< + return useDropRef< DragObject, Promise, { isOver: boolean; canDrop: boolean } diff --git a/app/components/Sidebar/hooks/useScrollMargin.ts b/app/components/Sidebar/hooks/useScrollMargin.ts new file mode 100644 index 0000000000..36ce759081 --- /dev/null +++ b/app/components/Sidebar/hooks/useScrollMargin.ts @@ -0,0 +1,56 @@ +import type { RefObject } from "react"; +import { useLayoutEffect, useState } from "react"; + +/** + * Tracks the offset of an element from the top of the content of a scroll + * container, for use as the scroll margin of a virtualized list. The offset is + * measured again when a direct child of the scroll container is resized, added + * or removed, as these move the element without a scroll event. + * + * @param ref a ref to the element to measure. + * @param scrollElement the scroll container that holds the element. + * @returns the offset in pixels. + */ +export function useScrollMargin( + ref: RefObject, + scrollElement: HTMLElement | null +): number { + const [scrollMargin, setScrollMargin] = useState(0); + + useLayoutEffect(() => { + const element = ref.current; + if (!element || !scrollElement) { + return; + } + + const measure = () => { + setScrollMargin( + element.getBoundingClientRect().top - + scrollElement.getBoundingClientRect().top + + scrollElement.scrollTop + ); + }; + + const resizeObserver = new ResizeObserver(measure); + const observeChildren = () => { + for (const child of scrollElement.children) { + resizeObserver.observe(child); + } + }; + const mutationObserver = new MutationObserver(() => { + observeChildren(); + measure(); + }); + + measure(); + observeChildren(); + mutationObserver.observe(scrollElement, { childList: true }); + + return () => { + resizeObserver.disconnect(); + mutationObserver.disconnect(); + }; + }, [ref, scrollElement]); + + return scrollMargin; +} diff --git a/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx b/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx index 16f95d94b5..3b8cf5c4e5 100644 --- a/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx +++ b/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx @@ -10,44 +10,67 @@ interface SidebarItem { groupId?: string; } +/** + * Returns the label and icon for a sidebar item that references a document or + * collection. The result is memoized so that rows receive equal props between + * renders. + * + * @param item the ids of the document, collection, or group of the item. + * @returns the label and icon of the item. + */ export function useSidebarLabelAndIcon({ documentId, collectionId, groupId, }: SidebarItem) { const { collections, documents } = useStores(); - const icon = ; + const document = documentId ? documents.get(documentId) : undefined; + const collection = + !document && collectionId ? collections.get(collectionId) : undefined; - if (documentId) { - const document = documents.get(documentId); + const title = document?.displayTitle; + const documentIcon = document?.icon; + const initial = document?.initial; + const color = document?.color; + const isDraft = document?.isDraft; + const collectionName = collection?.displayName; + + return React.useMemo(() => { if (document) { return { - label: document.titleWithDefault, - icon: document.icon ? ( + label: title ?? "", + icon: documentIcon ? ( ) : groupId ? null : ( - + ), }; } - } - if (collectionId) { - const collection = collections.get(collectionId); if (collection) { return { - label: collection.name, + label: collectionName ?? "", icon: , }; } - } - return { - label: "", - icon, - }; + return { + label: "", + icon: , + }; + }, [ + document, + title, + documentIcon, + initial, + color, + isDraft, + groupId, + collection, + collectionName, + ]); } diff --git a/app/components/SidebarCollapsedContext.ts b/app/components/SidebarCollapsedContext.ts new file mode 100644 index 0000000000..8f0bbb914e --- /dev/null +++ b/app/components/SidebarCollapsedContext.ts @@ -0,0 +1,19 @@ +import { createContext, useContext } from "react"; + +const SidebarCollapsedContext = createContext(false); + +/** + * Provider that reports whether the main sidebar is currently collapsed, + * taking into account both user preference and whether the current layout + * allows the sidebar to collapse. + */ +export const SidebarCollapsedProvider = SidebarCollapsedContext.Provider; + +/** + * Returns whether the main sidebar is currently collapsed. + * + * @returns true if the sidebar is collapsed. + */ +export function useSidebarCollapsed(): boolean { + return useContext(SidebarCollapsedContext); +} diff --git a/app/components/SortableTable.tsx b/app/components/SortableTable.tsx index 11f6bc2cb7..89607a390b 100644 --- a/app/components/SortableTable.tsx +++ b/app/components/SortableTable.tsx @@ -1,7 +1,7 @@ import type { ColumnSort } from "@tanstack/react-table"; import { useCallback } from "react"; import { useHistory } from "react-router-dom"; -import lazyWithRetry from "~/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; import type { Props as TableProps, RowData } from "./Table"; const Table = lazyWithRetry(() => import("~/components/Table")); diff --git a/app/components/SplitView/index.tsx b/app/components/SplitView/index.tsx index 87db2970a3..f91954fcf0 100644 --- a/app/components/SplitView/index.tsx +++ b/app/components/SplitView/index.tsx @@ -4,7 +4,7 @@ import { useDirection } from "@radix-ui/react-direction"; import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; -import { Router, useLocation } from "react-router-dom"; +import { Router } from "react-router-dom"; import styled from "styled-components"; import { depths, s } from "@shared/styles"; import CenteredContent from "~/components/CenteredContent"; @@ -17,6 +17,7 @@ import { import ResizeBorder from "~/components/Sidebar/components/ResizeBorder"; import useMobile from "~/hooks/useMobile"; import { useResizeHandle } from "~/hooks/useResizeHandle"; +import { useLocationSelector } from "~/hooks/useLocationSelector"; import useStores from "~/hooks/useStores"; import history, { patchLocation, toLocationDescriptor } from "~/utils/history"; import type { SplitViewPane } from "~/utils/splitView"; @@ -42,11 +43,12 @@ type Props = { */ export const SplitView = observer(function SplitView({ children }: Props) { const { ui } = useStores(); - const location = useLocation(); const isMobile = useMobile(); const direction = useDirection(); const containerRef = React.useRef(null); - const splitPath = isMobile ? undefined : getSplitPath(location.search); + const splitPath = useLocationSelector((location) => + isMobile ? undefined : getSplitPath(location.search) + ); const focusedPane = getFocusedSplitPane(); // Return focus to the primary pane and reset the secondary pane's sidebar diff --git a/app/components/Star.tsx b/app/components/Star.tsx index 7e64bbd7d2..fcf33b1a13 100644 --- a/app/components/Star.tsx +++ b/app/components/Star.tsx @@ -22,9 +22,18 @@ type Props = { size?: number; /** Color override for the star */ color?: string; + /** Defer the tooltip until the containing row is interactive. */ + tooltipDisabled?: boolean; }; -function Star({ size, document, collection, color, ...rest }: Props) { +function Star({ + size, + document, + collection, + color, + tooltipDisabled, + ...rest +}: Props) { const { t } = useTranslation(); const theme = useTheme(); @@ -44,10 +53,15 @@ function Star({ size, document, collection, color, ...rest }: Props) { > void; inForm?: boolean; + ref?: React.Ref>; } -function Switch( - { - width = 32, - height = 18, - labelPosition = "left", - inForm = true, - label, - disabled, - className, - note, - checked, - onChange, - ...props - }: Props, - ref: React.Ref> -) { +function Switch({ + ref, + width = 32, + height = 18, + labelPosition = "left", + inForm = true, + label, + disabled, + className, + note, + checked, + onChange, + ...props +}: Props) { const handleCheckedChange = React.useCallback( (checkedState: boolean) => { if (onChange) { @@ -68,7 +68,7 @@ function Switch( className={label ? undefined : className} {...props} > - + ); @@ -129,15 +129,16 @@ const Label = styled.label<{ const HOVER_EXTRA = 3; -const StyledSwitchThumb = styled(RadixSwitch.Thumb)<{ - width: number; - height: number; -}>` +/** Minimum switch size on mobile, so that small switches stay usable by touch. */ +const MOBILE_MIN_WIDTH = 32; +const MOBILE_MIN_HEIGHT = 18; + +const StyledSwitchThumb = styled(RadixSwitch.Thumb)` display: block; - width: ${(props) => props.height - 8}px; - height: ${(props) => props.height - 8}px; + width: calc(var(--switch-height) - 8px); + height: calc(var(--switch-height) - 8px); background-color: white; - border-radius: ${(props) => (props.height - 8) / 2}px; + border-radius: calc((var(--switch-height) - 8px) / 2); transition: transform 0.2s, width 0.2s; @@ -145,11 +146,11 @@ const StyledSwitchThumb = styled(RadixSwitch.Thumb)<{ will-change: transform, width; &[data-state="checked"] { - transform: translateX(${(props) => props.width - props.height}px); + transform: translateX(calc(var(--switch-width) - var(--switch-height))); } [dir="rtl"] &[data-state="checked"] { - transform: translateX(${(props) => -(props.width - props.height)}px); + transform: translateX(calc(var(--switch-height) - var(--switch-width))); } `; @@ -157,17 +158,25 @@ const StyledSwitchRoot = styled(RadixSwitch.Root)<{ width: number; height: number; }>` + --switch-width: ${(props) => Math.max(props.width, MOBILE_MIN_WIDTH)}px; + --switch-height: ${(props) => Math.max(props.height, MOBILE_MIN_HEIGHT)}px; + position: relative; - width: ${(props) => props.width}px; - height: ${(props) => props.height}px; + width: var(--switch-width); + height: var(--switch-height); background-color: ${(props) => props.theme.slate}; - border-radius: ${(props) => props.height}px; + border-radius: var(--switch-height); border: none; cursor: var(--pointer); transition: background-color 0.2s; padding: 0 4px; flex-shrink: 0; + ${(props) => breakpoint("tablet")` + --switch-width: ${props.width}px; + --switch-height: ${props.height}px; + `} + &:focus { box-shadow: 0 0 1px ${s("accent")}; outline: none; @@ -191,22 +200,22 @@ const StyledSwitchRoot = styled(RadixSwitch.Root)<{ } &:hover:not(:disabled) ${StyledSwitchThumb} { - width: ${(props) => props.height - 8 + HOVER_EXTRA}px; + width: calc(var(--switch-height) - 8px + ${HOVER_EXTRA}px); } &:hover:not(:disabled)[data-state="checked"] ${StyledSwitchThumb} { transform: translateX( - ${(props) => props.width - props.height - HOVER_EXTRA}px + calc(var(--switch-width) - var(--switch-height) - ${HOVER_EXTRA}px) ); } [dir="rtl"] - &:hover:not(:disabled)[data-state="checked"] - ${StyledSwitchThumb} { + &:hover:not(:disabled)[data-state="checked"] + ${StyledSwitchThumb} { transform: translateX( - ${(props) => -(props.width - props.height - HOVER_EXTRA)}px + calc(var(--switch-height) - var(--switch-width) + ${HOVER_EXTRA}px) ); } `; -export default React.forwardRef(Switch); +export default Switch; diff --git a/app/components/Table.tsx b/app/components/Table.tsx index 7900ef2d89..47b8ae289c 100644 --- a/app/components/Table.tsx +++ b/app/components/Table.tsx @@ -19,6 +19,8 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { Waypoint } from "react-waypoint"; import styled from "styled-components"; +import breakpoint from "styled-components-breakpoint"; +import { HEADER_HEIGHT as APP_HEADER_HEIGHT } from "@shared/constants"; import { s } from "@shared/styles"; import DelayedMount from "~/components/DelayedMount"; import Empty from "~/components/Empty"; @@ -442,7 +444,7 @@ function TableViewInner({ bottomOffset={-rowHeight * 5} /> )} - {isEmpty && {t("No results")}} + {isEmpty && {t("No results")}} ); } @@ -521,7 +523,7 @@ function ColumnVisibilityButton(props: ColumnVisibilityProps) { return ( - + @@ -589,6 +591,10 @@ const SelectAllCheckbox = observer(function SelectAllCheckbox_({ }) { const checked = count > 0 && selection.size === count; + if (count === 0) { + return null; + } + const handleClick = (event: React.MouseEvent) => { event.stopPropagation(); if (selection.isActive) { @@ -644,6 +650,11 @@ function Placeholder({ ); } +const NoResults = styled(Empty)` + display: block; + margin-top: 8px; +`; + const DescSortIcon = styled(CollapsedIcon)` margin-left: -2px; @@ -708,6 +719,11 @@ const THead = styled.div<{ $topPos: number }>` border-bottom: 1px solid ${(props) => transparentize(0.3, props.theme.divider)}; background: ${s("background")}; + + ${breakpoint("mobile", "tablet")` + top: ${({ $topPos }: { $topPos: number }) => + `${Math.min($topPos, APP_HEADER_HEIGHT)}px`}; + `}; `; const TBody = styled.div<{ $height: number }>` diff --git a/app/components/Tabs/Tab.tsx b/app/components/Tabs/Tab.tsx index 381fc8ec0e..8cfb47d1bf 100644 --- a/app/components/Tabs/Tab.tsx +++ b/app/components/Tabs/Tab.tsx @@ -1,3 +1,4 @@ +import type { Transition } from "framer-motion"; import { m } from "framer-motion"; import type { LocationDescriptor } from "history"; import { isEqual } from "es-toolkit/compat"; @@ -5,6 +6,7 @@ import queryString from "query-string"; import * as React from "react"; import styled, { css, useTheme } from "styled-components"; import breakpoint from "styled-components-breakpoint"; +import { MOBILE_TOUCH_TARGET } from "@shared/constants"; import { s, hover } from "@shared/styles"; import NavLink from "~/components/NavLink"; @@ -19,6 +21,8 @@ interface BaseProps { */ exactQueryString?: boolean; children?: React.ReactNode; + /** Ref to the underlying button, only attached in button mode. */ + ref?: React.Ref; } interface LinkProps extends BaseProps { @@ -57,9 +61,11 @@ const tabStyles = css` cursor: var(--pointer); user-select: none; padding: 12px 0; + min-height: ${MOBILE_TOUCH_TARGET}px; ${breakpoint("tablet")` padding: 6px 0; + min-height: 0; `}; `; @@ -94,7 +100,7 @@ const Active = styled(m.div)` background: ${s("textSecondary")}; `; -const transition = { +const transition: Transition = { type: "spring", stiffness: 500, damping: 30, @@ -112,10 +118,7 @@ const horizontalOnly = (transform: Record, generated: string) => * matched against the current location, or as a button in controlled mode. * A forwarded ref is only attached in button mode. */ -export const Tab = React.forwardRef(function Tab( - props: Props, - ref -) { +export function Tab(props: Props) { const { children, exact, exactQueryString } = props; const theme = useTheme(); const activeStyle = { @@ -125,6 +128,7 @@ export const Tab = React.forwardRef(function Tab( // Button mode - controlled by onClick and active props (no `to` prop) if ("active" in props && !("to" in props)) { const { + ref, active, exact: _exact, exactQueryString: _exactQueryString, @@ -147,7 +151,7 @@ export const Tab = React.forwardRef(function Tab( } // Link mode - controlled by react-router - const { to, ...rest } = props as LinkProps; + const { to, ref: _ref, ...rest } = props as LinkProps; return ( (function Tab( )} ); -}); +} diff --git a/app/components/Tabs/Tabs.tsx b/app/components/Tabs/Tabs.tsx index 8175761e38..5b16d26d3a 100644 --- a/app/components/Tabs/Tabs.tsx +++ b/app/components/Tabs/Tabs.tsx @@ -44,9 +44,12 @@ const Nav = styled.nav<{ $shadowVisible?: boolean }>` // When sticky we need extra background coverage around the sides otherwise // items that scroll past can "stick out" the sides of the heading +/** Offset from the top of the viewport at which the tab bar sticks. */ +const StickyTop = 54; + const Sticky = styled.div` position: sticky; - top: 54px; + top: ${StickyTop}px; margin: 0 -8px; padding: 0 8px; background: ${s("background")}; @@ -76,6 +79,7 @@ export const TabsGroup: React.FC = ({ children }: Props) => { export const Tabs: React.FC = ({ children }: Props) => { const ref = React.useRef(null); + const stickyRef = React.useRef(null); const [shadowVisible, setShadow] = React.useState(false); const { width } = useWindowSize(); @@ -97,9 +101,29 @@ export const Tabs: React.FC = ({ children }: Props) => { updateShadows(); }, [width, updateShadows]); + // Mark the tab bar while it is stuck so the header above can style itself to match. + React.useEffect(() => { + const sticky = stickyRef.current; + if (!sticky) { + return; + } + const observer = new IntersectionObserver( + ([entry]) => { + sticky.toggleAttribute( + "data-stuck", + entry.intersectionRatio < 1 && + entry.boundingClientRect.top <= StickyTop + 1 + ); + }, + { threshold: 1, rootMargin: `-${StickyTop + 1}px 0px 0px 0px` } + ); + observer.observe(sticky); + return () => observer.disconnect(); + }, []); + return ( - + diff --git a/app/components/Template/TemplateForm.tsx b/app/components/Template/TemplateForm.tsx index a2cd1e2d61..0b1d7340c9 100644 --- a/app/components/Template/TemplateForm.tsx +++ b/app/components/Template/TemplateForm.tsx @@ -154,7 +154,7 @@ export const TemplateForm = observer(function TemplateForm_({ void saveRef.current(); } }, - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps [] ); @@ -194,7 +194,7 @@ export const TemplateForm = observer(function TemplateForm_({ onChange={handleChange} readOnly={readOnly} canUpdate={can.update} - autoFocus={template.createdAt === template.updatedAt} + autoFocus={template.isJustCreated} template /> diff --git a/app/components/TemplatizeDialog/SelectLocation.tsx b/app/components/TemplatizeDialog/SelectLocation.tsx index 1a293d3131..e3d5a17793 100644 --- a/app/components/TemplatizeDialog/SelectLocation.tsx +++ b/app/components/TemplatizeDialog/SelectLocation.tsx @@ -52,7 +52,7 @@ const SelectLocation = ({ defaultCollectionId, onSelect }: Props) => { if (canCollection.createTemplate) { memo.push({ type: "item", - label: collection.name, + label: collection.displayName, value: collection.id, icon: , }); diff --git a/app/components/TemplatizeDialog/index.tsx b/app/components/TemplatizeDialog/index.tsx index e31859fa36..0c08618507 100644 --- a/app/components/TemplatizeDialog/index.tsx +++ b/app/components/TemplatizeDialog/index.tsx @@ -48,7 +48,7 @@ function DocumentTemplatizeDialog({ documentId }: Props) {
{t( - "Creating a template is a non-destructive action – we'll make a copy of the document and turn it into a template that can be used as a starting point for new documents." + "Creating a template is a non-destructive action – we’ll make a copy of the document and turn it into a template that can be used as a starting point for new documents." )}
= ({ children }: Props) => { - const { auth, ui } = useStores(); + const { auth } = useStores(); const { i18n } = useTranslation(); const theme = useBuildTheme( auth.team?.getPreference(TeamPreference.CustomTheme) || @@ -23,47 +24,22 @@ const Theme: React.FC = ({ children }: Props) => { ); const direction = isRTLLanguage(i18n.language) ? "rtl" : "ltr"; - React.useEffect(() => { - window.dispatchEvent( - new CustomEvent("theme-changed", { - detail: { isDark: ui.resolvedTheme === "dark" }, - }) - ); - }, [ui.resolvedTheme]); - - // Some editor elements such as Mermaid diagrams rely on theme-changed event - // to render the correct color. - // Listen on the print media query, which fires consistently for both the - // print dialog and print preview. - React.useEffect(() => { - const mediaQuery = window.matchMedia("print"); - const handleChange = (event: MediaQueryListEvent) => { - window.dispatchEvent( - new CustomEvent("theme-changed", { - detail: { - isDark: event.matches ? false : ui.resolvedTheme === "dark", - }, - }) - ); - }; - - mediaQuery.addEventListener("change", handleChange); - return () => mediaQuery.removeEventListener("change", handleChange); - }, [ui.resolvedTheme]); - return ( - - <> - - {children} - - + + + <> + + {children} + + + ); }; diff --git a/app/components/Time.tsx b/app/components/Time.tsx index 3bd82f5b45..15578a7e85 100644 --- a/app/components/Time.tsx +++ b/app/components/Time.tsx @@ -1,7 +1,7 @@ import { Suspense } from "react"; import { dateToRelative } from "@shared/utils/date"; import type { Props as LocaleTimeProps } from "~/components/LocaleTime"; -import lazyWithRetry from "~/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; const LocaleTime = lazyWithRetry(() => import("~/components/LocaleTime")); diff --git a/app/components/Toasts.tsx b/app/components/Toasts.tsx index 238a45f023..bf589af251 100644 --- a/app/components/Toasts.tsx +++ b/app/components/Toasts.tsx @@ -1,5 +1,5 @@ import { observer } from "mobx-react"; -import { Toaster } from "sonner"; +import { Toaster, type ToasterProps } from "sonner"; import styled, { useTheme } from "styled-components"; import useStores from "~/hooks/useStores"; import type { ResolvedTheme } from "~/stores/UiStore"; @@ -10,8 +10,7 @@ function Toasts() { return ( & { resolvedTheme: ResolvedTheme }) { + return ; +} + +const StyledToaster = styled(ThemedToaster)` [data-close-button] { cursor: var(--pointer); opacity: 0; diff --git a/app/components/Tooltip.tsx b/app/components/Tooltip.tsx index f52d2522fd..8522cea7a6 100644 --- a/app/components/Tooltip.tsx +++ b/app/components/Tooltip.tsx @@ -9,7 +9,7 @@ import { useTooltipContext } from "./TooltipContext"; export type Props = { /** The content to display in the tooltip. */ - content?: React.ReactChild | React.ReactChild[]; + content?: React.ReactNode; /** A keyboard shortcut to display next to the content */ shortcut?: React.ReactNode; /** Whether to show the shortcut on a new line */ @@ -46,24 +46,6 @@ export type Props = { children?: React.ReactNode; /** Whether to disable the tooltip entirely */ disabled?: boolean; - /** Custom offset for the tooltip */ - offset?: [number, number]; - /** Placement prop for backward compatibility with Tippy */ - placement?: - | "top" - | "right" - | "bottom" - | "left" - | "top-start" - | "top-end" - | "right-start" - | "right-end" - | "bottom-start" - | "bottom-end" - | "left-start" - | "left-end"; - /** Delay prop for backward compatibility with Tippy */ - delay?: number | [number, number]; }; /** @@ -93,43 +75,11 @@ function Tooltip({ disableHoverableContent = false, children, disabled = false, - offset, - placement, - delay, ...rest }: Props): React.ReactElement | null { const isMobile = useMobile(); const isInProvider = useTooltipContext(); - // Handle backward compatibility with Tippy props - let finalSide = side; - let finalAlign = align; - let finalDelayDuration = delayDuration; - let finalSideOffset = sideOffset; - - // Convert placement prop to side/align for backward compatibility - if (placement) { - const [placementSide, placementAlign] = placement.split("-"); - finalSide = placementSide as "top" | "right" | "bottom" | "left"; - if (placementAlign) { - finalAlign = placementAlign as "start" | "center" | "end"; - } - } - - // Handle delay prop for backward compatibility - if (delay !== undefined) { - if (typeof delay === "number") { - finalDelayDuration = delay; - } else if (Array.isArray(delay)) { - finalDelayDuration = delay[0]; - } - } - - // Handle offset prop for backward compatibility - if (offset) { - finalSideOffset = offset[1] || sideOffset; - } - let content = <>{tooltip}; if (!tooltip || isMobile || disabled) { @@ -164,15 +114,15 @@ function Tooltip({ defaultOpen={defaultOpen} open={open} onOpenChange={onOpenChange} - delayDuration={isInProvider ? undefined : finalDelayDuration} + delayDuration={isInProvider ? undefined : delayDuration} disableHoverableContent={disableHoverableContent} > {children} {tooltipContent} diff --git a/app/components/TooltipContext.tsx b/app/components/TooltipContext.tsx index ef905beef9..3a0de0b307 100644 --- a/app/components/TooltipContext.tsx +++ b/app/components/TooltipContext.tsx @@ -15,11 +15,6 @@ type Props = { skipDelayDuration?: number; /** Prevents the tooltip from opening */ disableHoverableContent?: boolean; - /** Props to pass to the Tippy component - kept for backward compatibility */ - tippyProps?: { - delay?: number; - [key: string]: unknown; - }; }; /** @@ -30,14 +25,10 @@ export function TooltipProvider({ delayDuration = 500, skipDelayDuration = 300, disableHoverableContent = false, - tippyProps, }: Props) { - // Handle backward compatibility with tippyProps - const finalDelayDuration = tippyProps?.delay ?? delayDuration; - return ( diff --git a/app/components/UserDialogs.tsx b/app/components/UserDialogs.tsx index 8653f18129..9a1cf5d158 100644 --- a/app/components/UserDialogs.tsx +++ b/app/components/UserDialogs.tsx @@ -160,7 +160,7 @@ export function UserChangeNameDialog({ user, onSubmit }: Props) { name="name" label={t("New name")} onChange={handleChange} - error={!name ? t("Name can't be empty") : undefined} + error={!name ? t("Name can’t be empty") : undefined} value={name} maxLength={UserValidation.maxNameLength} showCharacterCount @@ -265,7 +265,7 @@ export function UserChangeEmailDialog({ user, onSubmit }: Props) { name="email" label={t("New email")} onChange={handleChange} - error={!email ? t("Email can't be empty") : error} + error={!email ? t("Email can’t be empty") : error} value={email} maxLength={UserValidation.maxEmailLength} showCharacterCount diff --git a/app/components/WebsocketProvider.tsx b/app/components/WebsocketProvider.tsx index 8aacc678b8..aa8076462f 100644 --- a/app/components/WebsocketProvider.tsx +++ b/app/components/WebsocketProvider.tsx @@ -311,7 +311,7 @@ function useDocumentHandlers() { }) => { const document = event.document; - // When document is detached as part of unpublishing, only the owner should be able to view it. + // Users that cannot see the draft only receive its ID, so it is removed. if ( !document.collectionId && document.createdBy?.id !== currentUserId @@ -961,7 +961,7 @@ function WebsocketProvider({ children }: React.PropsWithChildren) { } document.removeEventListener(getVisibilityListener(), checkConnection); }; - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, []); return ( diff --git a/app/components/primitives/Drawer.tsx b/app/components/primitives/Drawer.tsx index 8df6c76142..073e23a92c 100644 --- a/app/components/primitives/Drawer.tsx +++ b/app/components/primitives/Drawer.tsx @@ -21,11 +21,12 @@ const DrawerTrigger = DrawerPrimitive.Trigger; const DrawerHandle = DrawerPrimitive.Handle; /** Drawer's content - renders the overlay and the actual content. */ -const DrawerContent = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->((props, ref) => { - const { children, ...rest } = props; +function DrawerContent( + props: React.ComponentPropsWithoutRef & { + ref?: React.Ref>; + } +) { + const { ref, children, ...rest } = props; const [measureRef, bounds] = useMeasure(); return ( @@ -51,15 +52,16 @@ const DrawerContent = React.forwardRef< ); -}); +} DrawerContent.displayName = DrawerPrimitive.Content.displayName; /** Drawer's title shown in the center. */ -const DrawerTitle = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->((props, ref) => { - const { hidden, children, ...rest } = props; +function DrawerTitle( + props: React.ComponentPropsWithoutRef & { + ref?: React.Ref>; + } +) { + const { ref, hidden, children, ...rest } = props; const title = ( @@ -76,7 +78,7 @@ const DrawerTitle = React.forwardRef< )} ); -}); +} DrawerTitle.displayName = DrawerPrimitive.Title.displayName; const StyledText = styled(Text)` @@ -98,11 +100,17 @@ const StyledContent = styled(m.div)` ${borderRadius(8)} background: ${s("menuBackground")}; + + @media print { + display: none; + } `; const StyledInnerContent = styled(Flex)` padding: 6px; - padding-bottom: calc(6px + var(--sab, 0px)); + + /* The safe area inset is zero unless the viewport uses viewport-fit=cover. */ + padding-bottom: max(24px, calc(6px + var(--sab, 0px))); height: 100%; `; diff --git a/app/components/primitives/Form.tsx b/app/components/primitives/Form.tsx index 20d11b1cde..2209f1b544 100644 --- a/app/components/primitives/Form.tsx +++ b/app/components/primitives/Form.tsx @@ -14,7 +14,7 @@ export const Form = ({ const tokenRef = useRef(null); const handleSubmit = useCallback( - (event: React.FormEvent) => { + (event: React.SubmitEvent) => { if (tokenRef.current) { tokenRef.current.value = getCSRFToken(); } diff --git a/app/components/primitives/InputSelect.tsx b/app/components/primitives/InputSelect.tsx index 0cb5f1bb40..382fa6f64d 100644 --- a/app/components/primitives/InputSelect.tsx +++ b/app/components/primitives/InputSelect.tsx @@ -27,14 +27,13 @@ type InputSelectTriggerProps = { placeholder: string; /** When provided, overrides the selected value rendered inside the trigger. */ displayValue?: React.ReactNode; + ref?: React.Ref>; } & TriggerButtonProps & React.ComponentPropsWithoutRef; -const InputSelectTrigger = React.forwardRef< - React.ElementRef, - InputSelectTriggerProps ->((props, ref) => { - const { placeholder, children, nude, displayValue, ...buttonProps } = props; +function InputSelectTrigger(props: InputSelectTriggerProps) { + const { ref, placeholder, children, nude, displayValue, ...buttonProps } = + props; return ( @@ -47,20 +46,19 @@ const InputSelectTrigger = React.forwardRef< ); -}); +} InputSelectTrigger.displayName = InputSelectPrimitive.Trigger.displayName; /** InputSelect's content - renders the options in a scrollable element. */ type ContentProps = Omit< React.ComponentPropsWithoutRef, "position" ->; +> & { + ref?: React.Ref>; +}; -const InputSelectContent = React.forwardRef< - React.ElementRef, - ContentProps ->((props, ref) => { - const { children, ...rest } = props; +function InputSelectContent(props: ContentProps) { + const { ref, children, ...rest } = props; return ( @@ -71,15 +69,16 @@ const InputSelectContent = React.forwardRef< ); -}); +} InputSelectContent.displayName = InputSelectPrimitive.Content.displayName; /** Individual InputSelect option rendered in the menu. */ -const InputSelectItem = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->((props, ref) => { - const { children, ...rest } = props; +function InputSelectItem( + props: React.ComponentPropsWithoutRef & { + ref?: React.Ref>; + } +) { + const { ref, children, ...rest } = props; return ( @@ -93,18 +92,22 @@ const InputSelectItem = React.forwardRef< ); -}); +} InputSelectItem.displayName = InputSelectPrimitive.Item.displayName; /** Horizontal separator rendered between the options. */ -const InputSelectSeparator = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->((props, ref) => ( - - - -)); +function InputSelectSeparator({ + ref, + ...props +}: React.ComponentPropsWithoutRef & { + ref?: React.Ref>; +}) { + return ( + + + + ); +} InputSelectSeparator.displayName = InputSelectPrimitive.Separator.displayName; const Separator = styled.hr` @@ -112,16 +115,21 @@ const Separator = styled.hr` `; /** Non-selectable heading rendered to group options in the menu. */ -const InputSelectHeading = React.forwardRef< - HTMLSpanElement, - { children?: React.ReactNode } ->(({ children }, ref) => ( - - - {children} - - -)); +function InputSelectHeading({ + ref, + children, +}: { + children?: React.ReactNode; + ref?: React.Ref; +}) { + return ( + + + {children} + + + ); +} InputSelectHeading.displayName = "InputSelectHeading"; const Heading = styled(Text).attrs({ diff --git a/app/components/primitives/Menu/index.tsx b/app/components/primitives/Menu/index.tsx index 7677eea644..17b4f6ed1e 100644 --- a/app/components/primitives/Menu/index.tsx +++ b/app/components/primitives/Menu/index.tsx @@ -43,15 +43,16 @@ const SubMenu = ({ children, ...rest }: SubMenuProps) => { type TriggerProps = React.ComponentPropsWithoutRef< typeof DropdownMenuPrimitive.Trigger > & - React.ComponentPropsWithoutRef; + React.ComponentPropsWithoutRef & { + ref?: React.Ref< + | React.ComponentRef + | React.ComponentRef + >; + }; -const MenuTrigger = React.forwardRef< - | React.ElementRef - | React.ElementRef, - TriggerProps ->((props, ref) => { +function MenuTrigger(props: TriggerProps) { const { variant } = useMenuContext(); - const { children, ...rest } = props; + const { ref, children, ...rest } = props; const Trigger = variant === "dropdown" @@ -59,24 +60,29 @@ const MenuTrigger = React.forwardRef< : ContextMenuPrimitive.Trigger; return ( - + // The trigger element type depends on the variant, so the forwarded ref is + // a union that neither primitive accepts on its own. + } + {...rest} + asChild + > {children} ); -}); +} MenuTrigger.displayName = "MenuTrigger"; type ContentProps = React.ComponentPropsWithoutRef< typeof DropdownMenuPrimitive.Content > & - React.ComponentPropsWithoutRef; + React.ComponentPropsWithoutRef & { + ref?: React.Ref>; + }; -const MenuContent = React.forwardRef< - React.ElementRef, - ContentProps ->((props, ref) => { +function MenuContent(props: ContentProps) { const { variant } = useMenuContext(); - const { children, ...rest } = props; + const { ref, children, ...rest } = props; const Portal = variant === "dropdown" @@ -111,19 +117,20 @@ const MenuContent = React.forwardRef< ); -}); +} MenuContent.displayName = "MenuContent"; type SubMenuTriggerProps = BaseItemProps & React.ComponentPropsWithoutRef & - React.ComponentPropsWithoutRef; + React.ComponentPropsWithoutRef & { + ref?: React.Ref< + React.ComponentRef + >; + }; -const SubMenuTrigger = React.forwardRef< - React.ElementRef, - SubMenuTriggerProps ->((props, ref) => { +function SubMenuTrigger(props: SubMenuTriggerProps) { const { variant } = useMenuContext(); - const { label, icon, disabled, ...rest } = props; + const { ref, label, icon, disabled, ...rest } = props; const Trigger = variant === "dropdown" @@ -139,20 +146,21 @@ const SubMenuTrigger = React.forwardRef< ); -}); +} SubMenuTrigger.displayName = "SubMenuTrigger"; type SubMenuContentProps = React.ComponentPropsWithoutRef< typeof DropdownMenuPrimitive.SubContent > & - React.ComponentPropsWithoutRef; + React.ComponentPropsWithoutRef & { + ref?: React.Ref< + React.ComponentRef + >; + }; -const SubMenuContent = React.forwardRef< - React.ElementRef, - SubMenuContentProps ->((props, ref) => { +function SubMenuContent(props: SubMenuContentProps) { const { variant } = useMenuContext(); - const { children, ...rest } = props; + const { ref, children, ...rest } = props; const Portal = variant === "dropdown" @@ -184,7 +192,7 @@ const SubMenuContent = React.forwardRef< ); -}); +} SubMenuContent.displayName = "SubMenuContent"; type MenuGroupProps = { @@ -197,14 +205,13 @@ type MenuGroupProps = { Omit< React.ComponentPropsWithoutRef, "children" | "asChild" - >; + > & { + ref?: React.Ref>; + }; -const MenuGroup = React.forwardRef< - React.ElementRef, - MenuGroupProps ->((props, ref) => { +function MenuGroup(props: MenuGroupProps) { const { variant } = useMenuContext(); - const { label, items, ...rest } = props; + const { ref, label, items, ...rest } = props; const Group = variant === "dropdown" @@ -217,7 +224,7 @@ const MenuGroup = React.forwardRef< {items} ); -}); +} MenuGroup.displayName = "MenuGroup"; type BaseItemProps = { @@ -258,7 +265,7 @@ function MenuItemShortcut({ shortcut }: { shortcut?: string[] }) { type MenuButtonProps = BaseItemProps & { onClick: (event: React.MouseEvent) => void; - tooltip?: React.ReactChild; + tooltip?: React.ReactNode; selected?: boolean; dangerous?: boolean; } & Omit< @@ -268,14 +275,14 @@ type MenuButtonProps = BaseItemProps & { Omit< React.ComponentPropsWithoutRef, "children" | "asChild" | "onClick" - >; + > & { + ref?: React.Ref>; + }; -const MenuButton = React.forwardRef< - React.ElementRef, - MenuButtonProps ->((props, ref) => { +function MenuButton(props: MenuButtonProps) { const { variant } = useMenuContext(); const { + ref, label, icon, tooltip, @@ -312,13 +319,13 @@ const MenuButton = React.forwardRef< ); return tooltip ? ( - +
{button}
) : ( <>{button} ); -}); +} MenuButton.displayName = "MenuButton"; type MenuInternalLinkProps = BaseItemProps & { @@ -330,14 +337,13 @@ type MenuInternalLinkProps = BaseItemProps & { Omit< React.ComponentPropsWithoutRef, "children" | "asChild" | "onClick" - >; + > & { + ref?: React.Ref>; + }; -const MenuInternalLink = React.forwardRef< - React.ElementRef, - MenuInternalLinkProps ->((props, ref) => { +function MenuInternalLink(props: MenuInternalLinkProps) { const { variant } = useMenuContext(); - const { label, icon, disabled, shortcut, to, ...rest } = props; + const { ref, label, icon, disabled, shortcut, to, ...rest } = props; const Item = variant === "dropdown" @@ -353,7 +359,7 @@ const MenuInternalLink = React.forwardRef< ); -}); +} MenuInternalLink.displayName = "MenuInternalLink"; type MenuExternalLinkProps = BaseItemProps & { @@ -366,14 +372,13 @@ type MenuExternalLinkProps = BaseItemProps & { Omit< React.ComponentPropsWithoutRef, "children" | "asChild" | "onClick" - >; + > & { + ref?: React.Ref>; + }; -const MenuExternalLink = React.forwardRef< - React.ElementRef, - MenuExternalLinkProps ->((props, ref) => { +function MenuExternalLink(props: MenuExternalLinkProps) { const { variant } = useMenuContext(); - const { label, icon, disabled, shortcut, href, target, ...rest } = props; + const { ref, label, icon, disabled, shortcut, href, target, ...rest } = props; const Item = variant === "dropdown" @@ -393,19 +398,19 @@ const MenuExternalLink = React.forwardRef< ); -}); +} MenuExternalLink.displayName = "MenuExternalLink"; type MenuSeparatorProps = React.ComponentPropsWithoutRef< typeof DropdownMenuPrimitive.Separator > & - React.ComponentPropsWithoutRef; + React.ComponentPropsWithoutRef & { + ref?: React.Ref>; + }; -const MenuSeparator = React.forwardRef< - React.ElementRef, - MenuSeparatorProps ->((props, ref) => { +function MenuSeparator(props: MenuSeparatorProps) { const { variant } = useMenuContext(); + const { ref, ...rest } = props; const Separator = variant === "dropdown" @@ -413,24 +418,23 @@ const MenuSeparator = React.forwardRef< : ContextMenuPrimitive.Separator; return ( - + ); -}); +} MenuSeparator.displayName = "MenuSeparator"; type MenuLabelProps = React.ComponentPropsWithoutRef< typeof DropdownMenuPrimitive.Label > & - React.ComponentPropsWithoutRef; + React.ComponentPropsWithoutRef & { + ref?: React.Ref>; + }; -const MenuLabel = React.forwardRef< - React.ElementRef, - MenuLabelProps ->((props, ref) => { +function MenuLabel(props: MenuLabelProps) { const { variant } = useMenuContext(); - const { children, ...rest } = props; + const { ref, children, ...rest } = props; const Label = variant === "dropdown" @@ -442,7 +446,7 @@ const MenuLabel = React.forwardRef< {children} ); -}); +} MenuLabel.displayName = "MenuLabel"; export { diff --git a/app/components/primitives/Popover.tsx b/app/components/primitives/Popover.tsx index 634998ef02..7903aa9084 100644 --- a/app/components/primitives/Popover.tsx +++ b/app/components/primitives/Popover.tsx @@ -10,17 +10,18 @@ const Popover = PopoverPrimitive.Root; const PopoverAnchor = PopoverPrimitive.Anchor; -const PopoverTrigger = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->((props, ref) => { - const { children, ...rest } = props; +function PopoverTrigger( + props: React.ComponentPropsWithoutRef & { + ref?: React.Ref>; + } +) { + const { ref, children, ...rest } = props; return ( {children} ); -}); +} PopoverTrigger.displayName = PopoverPrimitive.Trigger.displayName; type ContentProps = { @@ -34,16 +35,17 @@ type ContentProps = { scrollable?: boolean; /** Shrink the padding of the popover */ shrink?: boolean; + ref?: React.Ref>; } & React.ComponentPropsWithoutRef; -const PopoverContent = React.forwardRef< - React.ElementRef, - ContentProps ->((props, forwardedRef) => { - const ref = React.useRef>(); - const timeoutRef = React.useRef(); +function PopoverContent(props: ContentProps) { + const ref = React.useRef | null>(null); + const timeoutRef = React.useRef(undefined); const container = usePortalContext(); const { + ref: forwardedRef, width, minWidth, minHeight, @@ -92,7 +94,7 @@ const PopoverContent = React.forwardRef< ); -}); +} PopoverContent.displayName = PopoverPrimitive.Content.displayName; type StyledContentProps = { diff --git a/app/components/primitives/components/InputSelect.tsx b/app/components/primitives/components/InputSelect.tsx index 9ec1afaf33..5655e5c8cc 100644 --- a/app/components/primitives/components/InputSelect.tsx +++ b/app/components/primitives/components/InputSelect.tsx @@ -3,7 +3,6 @@ */ import { CheckmarkIcon } from "outline-icons"; -import { forwardRef } from "react"; import styled, { css } from "styled-components"; import breakpoint from "styled-components-breakpoint"; import { s } from "@shared/styles"; @@ -12,11 +11,12 @@ import Flex from "~/components/Flex"; import Text from "~/components/Text"; import { transparentize } from "polished"; -export const SelectItem = forwardRef< - HTMLDivElement, - React.ComponentPropsWithoutRef<"div"> ->((props, ref) => { - const { children, ...rest } = props; +export function SelectItem( + props: React.ComponentPropsWithoutRef<"div"> & { + ref?: React.Ref; + } +) { + const { ref, children, ...rest } = props; return ( ); -}); -SelectItem.displayName = "SelectItem"; +} -export const SelectItemIndicator = forwardRef< - HTMLSpanElement, - React.ComponentPropsWithoutRef<"span"> ->((props, ref) => ( - - - -)); -SelectItemIndicator.displayName = "SelectItemIndicator"; +export function SelectItemIndicator({ + ref, + ...props +}: React.ComponentPropsWithoutRef<"span"> & { + ref?: React.Ref; +}) { + return ( + + + + ); +} const IconSpacer = styled.div` width: 24px; diff --git a/app/components/primitives/components/Menu.tsx b/app/components/primitives/components/Menu.tsx index 412178d5fb..4f8167e9d8 100644 --- a/app/components/primitives/components/Menu.tsx +++ b/app/components/primitives/components/Menu.tsx @@ -98,11 +98,11 @@ export const MenuButton = styled.button` ${BaseMenuItemCSS} `; -export const MenuInternalLink = styled(Link)` +export const MenuInternalLink = styled(Link)` ${BaseMenuItemCSS} `; -export const MenuExternalLink = styled.a` +export const MenuExternalLink = styled.a` ${BaseMenuItemCSS} `; diff --git a/app/components/primitives/components/Overlay.tsx b/app/components/primitives/components/Overlay.tsx index 4112c9ce2a..ca52d5daf4 100644 --- a/app/components/primitives/components/Overlay.tsx +++ b/app/components/primitives/components/Overlay.tsx @@ -12,4 +12,8 @@ export const Overlay = styled.div` &[data-state="open"] { opacity: 1; } + + @media print { + display: none; + } `; diff --git a/app/editor/components/BlockMenu.tsx b/app/editor/components/BlockMenu.tsx index 74b18d4b02..95ada775a6 100644 --- a/app/editor/components/BlockMenu.tsx +++ b/app/editor/components/BlockMenu.tsx @@ -1,7 +1,7 @@ import { DocumentIcon, ShapesIcon } from "outline-icons"; import { cloneDeep } from "es-toolkit/compat"; import { observer } from "mobx-react"; -import { useCallback, useMemo } from "react"; +import { useCallback, useEffect, useMemo } from "react"; import { useTranslation } from "react-i18next"; import Icon from "@shared/components/Icon"; import type { MenuItem } from "@shared/editor/types"; @@ -18,8 +18,10 @@ import SuggestionsMenuItem from "./SuggestionsMenuItem"; /** * Hook that returns a template menu item with children for inserting template * content into the editor, or undefined if no templates are available. + * + * @param isActive whether the block menu is open, templates load when it is. */ -function useTemplateMenuItem(): MenuItem | undefined { +function useTemplateMenuItem(isActive: boolean): MenuItem | undefined { const { t } = useTranslation(); const user = useCurrentUser({ rejectOnEmpty: false }); const { documents, templates: templatesStore } = useStores(); @@ -28,6 +30,12 @@ function useTemplateMenuItem(): MenuItem | undefined { const document = documentId ? documents.get(documentId) : undefined; const collectionId = document?.collectionId; + useEffect(() => { + if (isActive && user) { + void templatesStore.fetchAllIfNeeded(); + } + }, [isActive, user, templatesStore]); + return useMemo(() => { if (!user) { return undefined; @@ -47,10 +55,7 @@ function useTemplateMenuItem(): MenuItem | undefined { const toMenuItem = (template: (typeof allTemplates)[0]): MenuItem => ({ name: "noop", - title: TextHelper.replaceTemplateVariables( - template.titleWithDefault, - user - ), + title: TextHelper.replaceTemplateVariables(template.displayTitle, user), icon: template.icon ? ( ), - keywords: template.titleWithDefault, + keywords: template.displayTitle, onClick: () => { const data = cloneDeep(template.data); ProsemirrorHelper.replaceTemplateVariables(data, user); @@ -109,7 +114,7 @@ type Props = Omit & function BlockMenu(props: Props) { const { t } = useTranslation(); const { elementRef } = useEditor(); - const templateMenuItem = useTemplateMenuItem(); + const templateMenuItem = useTemplateMenuItem(props.isActive); const items = useMemo(() => { const baseItems = getMenuItems(t, elementRef); diff --git a/app/editor/components/ComponentView.tsx b/app/editor/components/ComponentView.tsx index e55a68fd15..fbc06112a2 100644 --- a/app/editor/components/ComponentView.tsx +++ b/app/editor/components/ComponentView.tsx @@ -15,13 +15,16 @@ type ComponentViewConstructor = { node: ProsemirrorNode; /** The editor view instance. */ view: EditorView; - /** A function that returns the current position of the node. */ - getPos: () => number; + /** A function that returns the current position of the node, or undefined once the view is destroyed. */ + getPos: () => number | undefined; /** The decorations applied to the node. */ decorations: Decoration[]; }; export default class ComponentView { + /** The class name applied to the editable content element of every node view. */ + static readonly contentClassName = "component-content"; + /** The React component to render. */ component: FunctionComponent; /** The editor instance. */ @@ -32,8 +35,8 @@ export default class ComponentView { node: ProsemirrorNode; /** The editor view instance. */ view: EditorView; - /** A function that returns the current position of the node. */ - getPos: () => number; + /** A function that returns the current position of the node, or undefined once the view is destroyed. */ + getPos: () => number | undefined; /** The decorations applied to the node. */ decorations: Decoration[]; /** The renderer instance. */ @@ -76,6 +79,10 @@ export default class ComponentView { this.contentDOM = document.createElement( node.type.spec.inline ? "span" : "div" ); + // Chrome unwraps an attribute-less div that is the only child of its + // parent when a deletion empties a block inside it, which orphans the + // content from ProseMirror. Any attribute prevents this. + this.contentDOM.className = ComponentView.contentClassName; } this.className = `component-${node.type.name}`; @@ -164,12 +171,15 @@ export default class ComponentView { */ handleContentRef = (element: HTMLElement | null) => { if ( - element && - this.contentDOM && - element !== this.contentDOM.parentElement + !element || + !this.contentDOM || + element === this.contentDOM.parentElement ) { - element.appendChild(this.contentDOM); + return; } + + element.appendChild(this.contentDOM); + this.syncSelection(); }; stopEvent(event: Event) { @@ -211,4 +221,29 @@ export default class ComponentView { contentRef: this.handleContentRef, } as ComponentProps; } + + /** + * Re-apply the editor selection to the DOM once the content is mounted. React + * mounts the content after ProseMirror has already synced the selection, so a + * selection inside a freshly created node lands on a detached element and the + * browser leaves the caret after the node instead. + */ + private syncSelection() { + const { view } = this; + if (!this.dom || !view.hasFocus()) { + return; + } + + const pos = this.getPos(); + if (pos === undefined) { + return; + } + + const { from, to } = view.state.selection; + if (from <= pos || to >= pos + this.node.nodeSize) { + return; + } + + view.focus(); + } } diff --git a/app/editor/components/DocumentMenu.tsx b/app/editor/components/DocumentMenu.tsx index 735bb623fe..7e23baf582 100644 --- a/app/editor/components/DocumentMenu.tsx +++ b/app/editor/components/DocumentMenu.tsx @@ -1,8 +1,8 @@ import { observer } from "mobx-react"; import { useCallback, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; -import { useLocation } from "react-router-dom"; import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; +import { useLocationSelector } from "~/hooks/useLocationSelector"; import useStores from "~/hooks/useStores"; import type { MentionMenuItem } from "~/editor/menus/mention"; import { @@ -31,8 +31,9 @@ function DocumentMenu({ search = "", isActive, ...rest }: Props) { const { auth, documents } = useStores(); const { props: editorProps } = useEditor(); const actorId = auth.currentUserId; - const location = useLocation(); - const documentId = parseDocumentSlug(location.pathname); + const documentId = useLocationSelector((location) => + parseDocumentSlug(location.pathname) + ); // Spaces are allowed in the search term, so it may have trailing whitespace. const query = search.trim(); diff --git a/app/editor/components/EmojiMenu.tsx b/app/editor/components/EmojiMenu.tsx index 7e295d57e5..09806946b0 100644 --- a/app/editor/components/EmojiMenu.tsx +++ b/app/editor/components/EmojiMenu.tsx @@ -37,7 +37,7 @@ const EmojiMenu = (props: Props) => { () => emojiSearch({ customEmojis: emojis.orderedData, query: search }) .map((item) => { - // We snake_case the shortcode for backwards compatability with gemoji to + // We snake_case the shortcode for backwards compatibility with gemoji to // avoid multiple formats being written into documents. const id = emojiMartToGemoji[item.id] || item.id; const type = determineIconType(id); diff --git a/app/editor/components/FindAndReplace.tsx b/app/editor/components/FindAndReplace.tsx index 244773c03c..c723f233e0 100644 --- a/app/editor/components/FindAndReplace.tsx +++ b/app/editor/components/FindAndReplace.tsx @@ -3,6 +3,7 @@ import { CaretDownIcon, CaretUpIcon, CaseSensitiveIcon, + CloseIcon, RegexIcon, ReplaceIcon, } from "outline-icons"; @@ -24,14 +25,16 @@ import { } from "~/components/primitives/Popover"; import { useClearSearchHighlight } from "~/hooks/useClearSearchHighlight"; import useKeyDown from "~/hooks/useKeyDown"; +import useMobile from "~/hooks/useMobile"; import Desktop from "~/utils/Desktop"; import { useEditor } from "./EditorContext"; import { HStack } from "~/components/primitives/HStack"; type KeyboardShortcutsProps = { open: boolean; - inputRef: React.RefObject; + inputRef: React.RefObject; handleOpen: ({ withReplace }: { withReplace: boolean }) => void; + handleClose: () => void; handleCaseSensitive: () => void; handleRegex: () => void; }; @@ -40,18 +43,24 @@ function useKeyboardShortcuts({ open, inputRef, handleOpen, + handleClose, handleCaseSensitive, handleRegex, }: KeyboardShortcutsProps) { - // Open popover + // Toggle popover useKeyDown( (ev) => isModKey(ev) && ev.code === "KeyF" && - (!open || ev.altKey || document.activeElement !== inputRef.current) && // Keyboard handler is through the AppMenu on Desktop v1.2.0+ !(Desktop.bridge && "onFindInPage" in Desktop.bridge), (ev) => { + // Close and fall through to the browser's find when already focused. + if (open && !ev.altKey && document.activeElement === inputRef.current) { + handleClose(); + return; + } + ev.preventDefault(); handleOpen({ withReplace: ev.altKey }); }, @@ -104,12 +113,13 @@ export default function FindAndReplace({ }: Props) { const editor = useEditor(); const [localOpen, setLocalOpen] = React.useState(open); - const selectionRef = React.useRef(); + const selectionRef = React.useRef(undefined); const inputRef = React.useRef(null); const inputReplaceRef = React.useRef(null); const { t } = useTranslation(); const theme = useTheme(); const clearSearchHighlight = useClearSearchHighlight(); + const isMobile = useMobile(); const [showReplace, setShowReplace] = React.useState(false); const [caseSensitive, setCaseSensitive] = React.useState(false); const [regexEnabled, setRegex] = React.useState(false); @@ -129,6 +139,10 @@ export default function FindAndReplace({ } if ("onFindInPage" in Desktop.bridge) { Desktop.bridge.onFindInPage(() => { + if (document.activeElement === inputRef.current) { + setLocalOpen(false); + return; + } selectionRef.current = window.getSelection()?.toString(); setLocalOpen(true); }); @@ -183,6 +197,8 @@ export default function FindAndReplace({ [localOpen, readOnly, selectInputText, selectInputReplaceText] ); + const handleClose = React.useCallback(() => setLocalOpen(false), []); + const handleMore = React.useCallback(() => { setShowReplace((state) => !state); setTimeout(() => inputReplaceRef.current?.focus(), 100); @@ -338,6 +354,7 @@ export default function FindAndReplace({ open: localOpen, inputRef, handleOpen, + handleClose, handleCaseSensitive, handleRegex, }); @@ -345,15 +362,20 @@ export default function FindAndReplace({ const style: React.CSSProperties = React.useMemo( () => ({ position: "fixed", - top: 0, - right: 0, + top: 60, + right: 16, zIndex: depths.popover, }), [] ); + // Tracks whether the controls were opened, as there is nothing to clear + // when the editor mounts with them closed. + const hasOpenedRef = React.useRef(false); + React.useEffect(() => { if (localOpen) { + hasOpenedRef.current = true; onOpen(); // The find controls take over highlighting from here. clearSearchHighlight(); @@ -372,7 +394,7 @@ export default function FindAndReplace({ if (selectionRef.current) { setSearchTerm(selectionRef.current); } - } else { + } else if (hasOpenedRef.current) { onClose(); setShowReplace(false); // Cancel any pending debounced find so it can't reactivate highlights @@ -384,12 +406,12 @@ export default function FindAndReplace({ }, [localOpen]); const disabled = totalResults === 0; - const navigation = ( + const controls = ( <> - + { @@ -414,6 +436,20 @@ export default function FindAndReplace({ + {!readOnly && ( + + + + + + )} + + {totalResults > 0 ? currentIndex + 1 : 0} / {totalResults} + ); @@ -429,12 +465,15 @@ export default function FindAndReplace({ ev.preventDefault()} onFocusOutside={(ev) => ev.preventDefault()} - style={{ marginRight: 16, marginTop: 60 }} + style={{ + width: isMobile ? "calc(100vw - 32px)" : undefined, + }} > @@ -450,7 +489,7 @@ export default function FindAndReplace({ - {navigation} - {!readOnly && ( - - - - - - )} - - {totalResults > 0 ? currentIndex + 1 : 0} / {totalResults} - + {!isMobile && controls} + {isMobile && ( + + {controls} + + + + + )} {showReplace && !readOnly && ( - + setReplaceTerm(ev.currentTarget.value)} /> - + @@ -520,7 +546,7 @@ export default function FindAndReplace({ @@ -80,7 +76,7 @@ function Actions({ collection, isEditing, sidebarContext }: Props) { )} {can.createDocument && ( - + diff --git a/app/scenes/Collection/index.tsx b/app/scenes/Collection/index.tsx index 6370b3681b..6d2751b9c8 100644 --- a/app/scenes/Collection/index.tsx +++ b/app/scenes/Collection/index.tsx @@ -98,7 +98,7 @@ const CollectionScene = observer(function CollectionScene_() { }, [collection, collection?.name, history, id, match.url]); useEffect(() => { - if (collection) { + if (collection && !collection.isPersonal) { ui.setActiveCollection(collection.id); } @@ -118,7 +118,7 @@ const CollectionScene = observer(function CollectionScene_() { void fetchData(); // Fetched once on mount, the slug in `id` also changes when the collection // is renamed which must not trigger a refetch. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { @@ -140,12 +140,17 @@ const CollectionScene = observer(function CollectionScene_() { return ; } + // A personal collection is only shown in the sidebar, it has no page. + if (collection.isPersonal) { + return ; + } + const showOverview = can.update || hasDescription; return ( @@ -161,12 +166,14 @@ const CollectionScene = observer(function CollectionScene_() { title={ <> -  {collection.name} +  {collection.displayName} } actions={ <> - + {!collection.isPersonal && ( + + )} diff --git a/app/scenes/DesktopRedirect.tsx b/app/scenes/DesktopRedirect.tsx index 9cdc2b6c5a..8d5c0dc9c5 100644 --- a/app/scenes/DesktopRedirect.tsx +++ b/app/scenes/DesktopRedirect.tsx @@ -2,6 +2,7 @@ import { useEffect } from "react"; import styled from "styled-components"; import Flex from "~/components/Flex"; import useQuery from "~/hooks/useQuery"; +import Desktop from "~/utils/Desktop"; import { SigningIn } from "./Login/components/SigningIn"; const DesktopRedirect = () => { @@ -11,11 +12,11 @@ const DesktopRedirect = () => { useEffect(() => { if (token) { window.open( - `outline://${window.location.host}/auth/redirect?token=${token}`, + `${Desktop.protocol}://${window.location.host}/auth/redirect?token=${token}`, "_self" ); - // Clean the url after a short delay so it's not possible to hit reload, re-using the transfer token + // Clean the url after a short delay so it's not possible to hit reload, reusing the transfer token // will not work and changing the location immediately cancels the window.open call in Safari. setTimeout(() => (window.location.search = ""), 500); } diff --git a/app/scenes/Document/components/AsyncMultiplayerEditor.ts b/app/scenes/Document/components/AsyncMultiplayerEditor.ts index 0da5ce9832..0d489b7486 100644 --- a/app/scenes/Document/components/AsyncMultiplayerEditor.ts +++ b/app/scenes/Document/components/AsyncMultiplayerEditor.ts @@ -1,4 +1,4 @@ -import lazyWithRetry from "~/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; const MultiplayerEditor = lazyWithRetry(() => import("./MultiplayerEditor")); diff --git a/app/scenes/Document/components/ChangesNavigation.tsx b/app/scenes/Document/components/ChangesNavigation.tsx index 6c568c6430..dee3c5638c 100644 --- a/app/scenes/Document/components/ChangesNavigation.tsx +++ b/app/scenes/Document/components/ChangesNavigation.tsx @@ -6,32 +6,24 @@ import { CaretDownIcon, CaretUpIcon } from "outline-icons"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import Button from "~/components/Button"; +import { useDocumentContext } from "~/components/DocumentContext"; import Tooltip from "~/components/Tooltip"; -import { type Editor } from "~/editor"; import useQuery from "~/hooks/useQuery"; -import type Revision from "~/models/Revision"; -type Props = { - revision: Revision; - editorRef: React.RefObject; -}; - -export const ChangesNavigation = observer(function ChangesNavigation_({ - editorRef, -}: Props) { +export const ChangesNavigation = observer(function ChangesNavigation_() { const { t } = useTranslation(); const query = useQuery(); - const showChanges = query.get("changes"); + const showChanges = query.has("changes"); + const { editor, totalChanges } = useDocumentContext(); if (!showChanges) { return null; } - const diffExtension = editorRef.current?.extensions.extensions.find( + const diffExtension = editor?.extensions.extensions.find( (ext) => ext instanceof Diff ) as Diff | undefined; const currentChangeIndex = diffExtension?.getCurrentChangeIndex() ?? -1; - const totalChanges = diffExtension?.getTotalChangesCount() ?? 0; return ( <> @@ -47,17 +39,19 @@ export const ChangesNavigation = observer(function ChangesNavigation_({ count: totalChanges, })} - + } - onClick={() => editorRef.current?.commands.prevChange()} + onClick={() => editor?.commands.prevChange()} + disabled={!diffExtension} aria-label={t("Previous change")} /> - + } - onClick={() => editorRef.current?.commands.nextChange()} + onClick={() => editor?.commands.nextChange()} + disabled={!diffExtension} aria-label={t("Next change")} /> diff --git a/app/scenes/Document/components/Comments/CommentEditor.tsx b/app/scenes/Document/components/Comments/CommentEditor.tsx index f4161ade2a..99ec0edf94 100644 --- a/app/scenes/Document/components/Comments/CommentEditor.tsx +++ b/app/scenes/Document/components/Comments/CommentEditor.tsx @@ -38,12 +38,10 @@ const extensions = [ type CommentEditorProps = EditorProps & { /** Callback when user presses up arrow at the start of the editor */ onUpArrowAtStart?: () => void; + ref?: React.Ref; }; -const CommentEditor = ( - props: CommentEditorProps, - ref: React.RefObject -) => { +const CommentEditor = ({ ref, ...props }: CommentEditorProps) => { const user = useCurrentUser({ rejectOnEmpty: false }); return ( @@ -51,4 +49,4 @@ const CommentEditor = ( ); }; -export default observer(React.forwardRef(CommentEditor)); +export default observer(CommentEditor); diff --git a/app/scenes/Document/components/Comments/CommentForm.tsx b/app/scenes/Document/components/Comments/CommentForm.tsx index 214491587c..8a36b85d4d 100644 --- a/app/scenes/Document/components/Comments/CommentForm.tsx +++ b/app/scenes/Document/components/Comments/CommentForm.tsx @@ -1,5 +1,6 @@ import * as VisuallyHidden from "@radix-ui/react-visually-hidden"; import { v4 as uuidv4 } from "uuid"; +import type { Transition } from "framer-motion"; import { m } from "framer-motion"; import { action } from "mobx"; import { observer } from "mobx-react"; @@ -25,7 +26,7 @@ import useOnClickOutside from "~/hooks/useOnClickOutside"; import useStores from "~/hooks/useStores"; import { Bubble } from "./CommentThreadItem"; import { HighlightedText } from "./HighlightText"; -import lazyWithRetry from "~/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; import { mergeRefs } from "react-merge-refs"; import { HStack } from "~/components/primitives/HStack"; @@ -326,7 +327,7 @@ function CommentForm({ transition: { duration: 0.2, ease: "easeOut", - }, + } satisfies Transition, }, exit: { opacity: 0, @@ -334,17 +335,17 @@ function CommentForm({ transition: { duration: 0.2, ease: "easeOut", - }, + } satisfies Transition, }, } : {}; return ( - + diff --git a/app/scenes/Document/components/Comments/CommentThread.tsx b/app/scenes/Document/components/Comments/CommentThread.tsx index 99ec741fd7..13be9d4be0 100644 --- a/app/scenes/Document/components/Comments/CommentThread.tsx +++ b/app/scenes/Document/components/Comments/CommentThread.tsx @@ -216,6 +216,7 @@ function CommentThread({ setTimeout( () => { + editor?.revealComment(thread.id); getCommentMarkElement()?.scrollIntoView({ behavior: "smooth", block: "center", @@ -224,7 +225,7 @@ function CommentThread({ isMarkVisible ? 0 : sidebarAppearDuration ); } - }, [focused, scrollOnMount, thread.id]); + }, [focused, scrollOnMount, thread.id, editor]); return ( import("./CommentEditor")); import { HighlightedText } from "./HighlightText"; @@ -317,7 +317,7 @@ const ResolveButton = ({ const { t } = useTranslation(); return ( - + diff --git a/app/scenes/Document/components/RevisionViewer.tsx b/app/scenes/Document/components/RevisionViewer.tsx index 961217f2c7..3d75b13b96 100644 --- a/app/scenes/Document/components/RevisionViewer.tsx +++ b/app/scenes/Document/components/RevisionViewer.tsx @@ -1,5 +1,6 @@ import { observer } from "mobx-react"; import * as React from "react"; +import { mergeRefs } from "react-merge-refs"; import { colorPalette } from "@shared/constants"; import type Document from "~/models/Document"; import type Revision from "~/models/Revision"; @@ -17,6 +18,7 @@ import useStores from "~/hooks/useStores"; import { type Editor as TEditor } from "~/editor"; import { ChangesetHelper } from "@shared/editor/lib/ChangesetHelper"; import CodeWordBreak from "@shared/editor/extensions/CodeWordBreak"; +import { useDocumentContext } from "~/components/DocumentContext"; type Props = Omit & { /** The ID of the revision */ @@ -28,6 +30,7 @@ type Props = Omit & { /** Whether to show changes from the previous revision */ showChanges?: boolean; children?: React.ReactNode; + ref?: React.Ref; }; /** @@ -39,9 +42,10 @@ type Props = Omit & { * * @param props - Component props including the revision to display and current document */ -function RevisionViewer(props: Props, ref: React.Ref) { - const { document, children, revision } = props; +function RevisionViewer(props: Props) { + const { document, children, revision, ref } = props; const { revisions } = useStores(); + const { setEditor, setTotalChanges } = useDocumentContext(); const query = useQuery(); const showChanges = props.showChanges ?? query.has("changes"); const compareToParam = query.get("compareTo"); @@ -77,31 +81,49 @@ function RevisionViewer(props: Props, ref: React.Ref) { /** * Create editor extensions with the Diff extension configured to render - * the calculated changes as decorations in the editor. + * the calculated changes as decorations in the editor. The change count is + * derived from the same changeset so the indicator can render before the + * editor and its Diff extension have finished mounting. */ - const extensions = React.useMemo(() => { + const { extensions, totalChanges } = React.useMemo(() => { const changeset = ChangesetHelper.getChangeset( revision.data, comparisonData ); - return [ - CodeWordBreak, - ...withComments(richExtensions), - ...(showChanges && changeset?.changes - ? [new Diff({ changes: changeset?.changes })] - : []), - ]; + return { + extensions: [ + CodeWordBreak, + ...withComments(richExtensions), + ...(showChanges && changeset?.changes + ? [new Diff({ changes: changeset?.changes })] + : []), + ], + totalChanges: showChanges + ? Diff.countChanges(changeset?.changes ?? null) + : 0, + }; }, [revision.data, comparisonData, showChanges]); + // Publish the change count so the header indicator can render immediately, + // without waiting for the lazily-loaded editor to mount. + React.useEffect(() => { + setTotalChanges(totalChanges); + }, [totalChanges, setTotalChanges]); + + // Reset the count on unmount so it does not linger on the live document. + React.useEffect(() => () => setTotalChanges(0), [setTotalChanges]); + // The editor builds its extensions once, on mount, so it has to be remounted // whenever the diff configuration changes. Revisions are listed without their // content, so the revision being compared against — and with it the Diff // extension — usually only arrives on a later render; without this neither // the highlights nor the change count would ever appear. const editorKey = [ + revision.id, showChanges ? "changes" : "no-changes", compareToRevisionId ?? revision.before?.id ?? "none", comparisonData ? "loaded" : "pending", + revision.data ? "loaded" : "pending", ].join("-"); return ( @@ -121,7 +143,7 @@ function RevisionViewer(props: Props, ref: React.Ref) { /> ) { ); } -export default observer(React.forwardRef(RevisionViewer)); +export default observer(RevisionViewer); diff --git a/app/scenes/Document/components/SearchHighlightChip.tsx b/app/scenes/Document/components/SearchHighlightChip.tsx index 866868ecfb..4de683bd97 100644 --- a/app/scenes/Document/components/SearchHighlightChip.tsx +++ b/app/scenes/Document/components/SearchHighlightChip.tsx @@ -1,20 +1,21 @@ import { CloseIcon } from "outline-icons"; import { useCallback } from "react"; import { useTranslation } from "react-i18next"; -import { useLocation } from "react-router-dom"; import styled from "styled-components"; import { ellipsis } from "@shared/styles"; import { useDocumentContext } from "~/components/DocumentContext"; import Tooltip from "~/components/Tooltip"; import { useClearSearchHighlight } from "~/hooks/useClearSearchHighlight"; +import { useLocationSelector } from "~/hooks/useLocationSelector"; import { undraggableOnDesktop } from "~/styles"; export function SearchHighlightChip() { const { t } = useTranslation(); const { editor } = useDocumentContext(); - const location = useLocation(); const clearSearchHighlight = useClearSearchHighlight(); - const searchHighlight = new URLSearchParams(location.search).get("q"); + const searchHighlight = useLocationSelector((location) => + new URLSearchParams(location.search).get("q") + ); const handleClick = useCallback(() => { editor?.commands.clearSearch(); @@ -26,11 +27,7 @@ export function SearchHighlightChip() { } return ( - + import("~/components/Sharing/Document") + () => import("~/components/Sharing/Document/SharePopover") ); type Props = { @@ -46,6 +47,16 @@ function ShareButton({ document }: Props) { [preload, reset] ); + const handleIntent = useCallback(() => { + preload(); + void SharePopover.preload(); + }, [preload]); + const { + ref: intentRef, + handleMouseEnter, + handleMouseLeave, + } = useClickIntent(handleIntent, { predict: true }); + const closePopover = useCallback(() => { handleOpenChange(false); }, [handleOpenChange]); @@ -59,7 +70,13 @@ function ShareButton({ document }: Props) { return ( - diff --git a/app/scenes/Document/components/SharedHeader.tsx b/app/scenes/Document/components/SharedHeader.tsx index 0b2bf372f3..4a0047d437 100644 --- a/app/scenes/Document/components/SharedHeader.tsx +++ b/app/scenes/Document/components/SharedHeader.tsx @@ -4,7 +4,6 @@ import { useCallback, useEffect } from "react"; import { useTranslation } from "react-i18next"; import useMeasure from "react-use-measure"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; import Icon from "@shared/components/Icon"; import { HEADER_HEIGHT } from "@shared/constants"; import useShare from "@shared/hooks/useShare"; @@ -29,7 +28,6 @@ import useEditingFocus from "~/hooks/useEditingFocus"; import useKeyDown from "~/hooks/useKeyDown"; import useMobile from "~/hooks/useMobile"; import useStores from "~/hooks/useStores"; -import useWindowScrollbarWidth from "~/hooks/useWindowScrollbarWidth"; import TableOfContentsMenu from "~/menus/TableOfContentsMenu"; import type Document from "~/models/Document"; import PublicBreadcrumb from "./PublicBreadcrumb"; @@ -55,7 +53,6 @@ function SharedDocumentHeader({ document }: Props) { const { hasHeadings } = useDocumentContext(); const [measureRef, size] = useMeasure(); - const scrollbarWidth = useWindowScrollbarWidth() ?? 0; const { shareId, sharedTree, allowSubscriptions } = useShare(); const share = shareId ? shares.get(shareId) : undefined; const team = useTeamContext() as PublicTeam | undefined; @@ -73,12 +70,6 @@ function SharedDocumentHeader({ document }: Props) { const showContents = ui.tocVisible !== false; - useEffect(() => { - if (isMobile && showContents) { - ui.set({ tocVisible: false }); - } - }, [isMobile, showContents, ui]); - useKeyDown( (event) => event.ctrlKey && event.altKey && event.code === "KeyH", handleToggle, @@ -101,7 +92,7 @@ function SharedDocumentHeader({ document }: Props) { : `${t("Show contents")} (${t("available when headings are added")})` } shortcut={`Ctrl+${altDisplay}+h`} - placement="bottom" + side="bottom" > {document.icon && ( @@ -136,11 +126,7 @@ function SharedDocumentHeader({ document }: Props) { } hasSidebar={hasSidebar} left={ - isMobile ? ( - hasHeadings ? ( - - ) : null - ) : hasSidebar ? ( + isMobile ? null : hasSidebar ? ( + {hasHeadings && isMobile && ( + + + + )} {hasHeadings && !isMobile && !tocInLeft && {toc}} {allowSubscriptions !== false && env.EMAIL_ENABLED && ( @@ -171,33 +162,9 @@ function SharedDocumentHeader({ document }: Props) { ); } -type StyledHeaderProps = { - $hidden: boolean; - /** Width of the window scrollbar, which the header end edge falls behind. */ - $scrollbarWidth: number; -}; - -/** - * The body spans the full viewport width, so the end of the header falls behind - * a visible scrollbar. The removed-body-scroll-bar-size variable is set while a - * modal holds the page scroll, when the scrollbar is momentarily gone, and - * keeps the padding constant as menus and dialogs open. - */ -const endPadding = (base: number) => (props: StyledHeaderProps) => - `calc(${base}px + ${props.$scrollbarWidth}px + var(--removed-body-scroll-bar-size, 0px))`; - -const StyledHeader = styled(Header)` +const StyledHeader = styled(Header)<{ $hidden: boolean }>` transition: opacity 500ms ease-in-out; ${(props) => props.$hidden && "opacity: 0;"} - - /* Doubled to take precedence over the padding shorthand of the header. */ - && { - padding-right: ${endPadding(16)}; - - ${breakpoint("tablet")` - padding-right: ${endPadding(12)}; - `} - } `; const TocButton = styled(Button)<{ $flipped?: boolean }>` diff --git a/app/scenes/Document/components/SizeWarning.tsx b/app/scenes/Document/components/SizeWarning.tsx index f3b8570bfe..f11c5bf777 100644 --- a/app/scenes/Document/components/SizeWarning.tsx +++ b/app/scenes/Document/components/SizeWarning.tsx @@ -27,7 +27,7 @@ export const SizeWarning = ({ document }: Props) => { {t("Warning")}
- {t("This document is large which may affect performance")} + {t("This document is large, which may affect performance")}
} > diff --git a/app/scenes/Document/hooks/useDocumentSave.ts b/app/scenes/Document/hooks/useDocumentSave.ts index 3cc7a94fe1..a341a3ae2c 100644 --- a/app/scenes/Document/hooks/useDocumentSave.ts +++ b/app/scenes/Document/hooks/useDocumentSave.ts @@ -12,7 +12,6 @@ import type Document from "~/models/Document"; import Template from "~/models/Template"; import type Revision from "~/models/Revision"; import type { Editor as TEditor } from "~/editor"; -import useIsMounted from "~/hooks/useIsMounted"; import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext"; import useStores from "~/hooks/useStores"; import { documentEditPath } from "~/utils/routeHelpers"; @@ -97,7 +96,6 @@ export function useDocumentSave({ const { auth, ui } = useStores(); const history = useHistory(); const sidebarContext = useLocationSidebarContext(); - const isMounted = useIsMounted(); // State const [isUploading, setIsUploading] = useState(false); @@ -169,9 +167,7 @@ export function useDocumentSave({ try { const savedDocument = await document.save(undefined, options); isEditorDirtyRef.current = false; - if (isMounted()) { - setIsEditorDirty(false); - } + setIsEditorDirty(false); if (options.done) { history.push({ @@ -189,13 +185,11 @@ export function useDocumentSave({ } catch (err) { toast.error(errToString(err)); } finally { - if (isMounted()) { - setIsSaving(false); - setIsPublishing(false); - } + setIsSaving(false); + setIsPublishing(false); } }, - [document, editorRef, history, sidebarContext, ui, isMounted] + [document, editorRef, history, sidebarContext, ui] ); const onSaveRef = useRef(onSave); @@ -331,7 +325,7 @@ export function useDocumentSave({ // Initial dirty check on mount useEffect(() => { updateIsDirty(); - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, []); // When readOnly changes from true to false, recalculate dirty state @@ -344,35 +338,49 @@ export function useDocumentSave({ }, [readOnly, updateIsDirty]); // Auto-delete/auto-save on unmount + debounce cleanup - useEffect( - () => () => { + const isMountedRef = useRef(false); + useEffect(() => { + isMountedRef.current = true; + + return () => { + isMountedRef.current = false; autosave.cancel(); + + // Read the editor now, as it may be destroyed by the time the check runs. + // oxlint-disable-next-line react-hooks/exhaustive-deps const currentDoc = editorRef.current?.view.state.doc; const isEditorEmpty = !currentDoc || ProsemirrorHelper.isEmpty(currentDoc); + const currentTitle = titleRef.current; - if ( - shouldAutoDeleteDraftOnUnmount({ - isEditorEmpty, - title: titleRef.current, - createdById: document.createdBy?.id, - currentUserId: auth.user?.id, - isDraft: document.isDraft, - isActive: document.isActive, - hasEmptyTitle: document.hasEmptyTitle, - isPersistedOnce: document.isPersistedOnce, - }) - ) { - void document.delete(); - } else if (document.isDirty()) { - void document.save(undefined, { - autosave: true, - }); - } - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [] - ); + // Defer the check so that a StrictMode remount does not count as an unmount. + queueMicrotask(() => { + if (isMountedRef.current) { + return; + } + + if ( + shouldAutoDeleteDraftOnUnmount({ + isEditorEmpty, + title: currentTitle, + createdById: document.createdBy?.id, + currentUserId: auth.user?.id, + isDraft: document.isDraft, + isActive: document.isActive, + hasEmptyTitle: document.hasEmptyTitle, + isPersistedOnce: document.isPersistedOnce, + }) + ) { + void document.delete(); + } else if (document.isDirty()) { + void document.save(undefined, { + autosave: true, + }); + } + }); + }; + // oxlint-disable-next-line react-hooks/exhaustive-deps + }, []); return { isUploading, diff --git a/app/scenes/Document/hooks/useDocumentSidebar.tsx b/app/scenes/Document/hooks/useDocumentSidebar.tsx index e1d5441280..2292ca85fe 100644 --- a/app/scenes/Document/hooks/useDocumentSidebar.tsx +++ b/app/scenes/Document/hooks/useDocumentSidebar.tsx @@ -10,7 +10,7 @@ import PlaceholderText from "~/components/PlaceholderText"; import { useSplitView } from "~/components/SplitView/context"; import useMobile from "~/hooks/useMobile"; import useStores from "~/hooks/useStores"; -import lazyWithRetry from "~/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; import { documentPath, matchDocumentHistory, @@ -18,10 +18,13 @@ import { } from "~/utils/routeHelpers"; import SidebarLayout from "~/scenes/Document/components/SidebarLayout"; -const DocumentComments = lazyWithRetry( +/** Lazy comments sidebar, exported so that triggers can preload it. */ +export const DocumentComments = lazyWithRetry( () => import("~/scenes/Document/components/Comments/Comments") ); -const DocumentHistory = lazyWithRetry( + +/** Lazy history sidebar, exported so that triggers can preload it. */ +export const DocumentHistory = lazyWithRetry( () => import("~/scenes/Document/components/History/History") ); @@ -43,18 +46,35 @@ const DocumentSidebarContent = observer(function DocumentSidebarContent({ const isMobile = useMobile(); const panel = ui.getRightSidebar(pane); + // The store clears the panel before the sidebar has animated closed, so the + // last panel stays visible until the content unmounts. + const [lastPanel, setLastPanel] = React.useState(panel); + if (panel && panel !== lastPanel) { + setLastPanel(panel); + } + const visiblePanel = panel ?? lastPanel; + + const fallback = ( + }> + {null} + + ); + + // Both panels stay mounted so that switching between them keeps their state + // and does not re-suspend on the lazy chunk. Effects, and with them the MobX + // reactions of observer components, are disposed while a panel is hidden. const inner = ( - }> - {null} - - } - > - {panel === "comments" && } - {panel === "history" && } - + + + + + + + + + + ); diff --git a/app/scenes/Document/index.tsx b/app/scenes/Document/index.tsx index 100692742c..99d0d55dcd 100644 --- a/app/scenes/Document/index.tsx +++ b/app/scenes/Document/index.tsx @@ -30,7 +30,7 @@ export default function DocumentScene(props: Props) { const { ui } = useStores(); const history = useHistory(); const { pane, isSplitView } = useSplitView(); - const { documentSlug, revisionId } = props.match.params; + const { documentSlug } = props.match.params; const currentPath = props.location.pathname; useTrackLastVisitedPath(currentPath); @@ -63,16 +63,12 @@ export default function DocumentScene(props: Props) { const urlParts = documentSlug ? documentSlug.split("-") : []; const urlId = urlParts.length ? urlParts[urlParts.length - 1] : undefined; - // Normalize the key so that it is *stable* between renders. - // Without this, the initial value can be "/undefined" and then flip to - // "/" when React stringifies `undefined` on the next render, causing a - // full unmount/mount cycle of the document subtree. Keeping the key constant - // prevents extra network requests and preserves editor state on resize. - const key = revisionId ? `${urlId}/${revisionId}` : urlId; - + // The revision is deliberately not part of the key: remounting the subtree + // between revisions would empty the page while the next one loads and reset + // the scroll position. DataLoader refetches when the revision id changes. return ( {nestedDocumentsCount < 1 ? ( , @@ -117,7 +120,7 @@ function DocumentDelete({ document, onSubmit }: Props) { count={nestedDocumentsCount} defaults="Are you sure about that? Deleting the {{ documentTitle }} document will delete all of its history and {{ any }} nested document." values={{ - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, any: nestedDocumentsCount, }} components={{ diff --git a/app/scenes/DocumentNew.tsx b/app/scenes/DocumentNew.tsx index 3bfe76a51a..6063b13ace 100644 --- a/app/scenes/DocumentNew.tsx +++ b/app/scenes/DocumentNew.tsx @@ -82,7 +82,7 @@ function DocumentNew() { } void createDocument(); - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, []); return ( diff --git a/app/scenes/DocumentPermanentDelete.tsx b/app/scenes/DocumentPermanentDelete.tsx index a7cf03da53..9c7465a6e2 100644 --- a/app/scenes/DocumentPermanentDelete.tsx +++ b/app/scenes/DocumentPermanentDelete.tsx @@ -37,7 +37,7 @@ function DocumentPermanentDelete({ document, onSubmit }: Props) { , diff --git a/app/scenes/Errors/Error403.tsx b/app/scenes/Errors/Error403.tsx index 14402cfd32..0c37e9c1b6 100644 --- a/app/scenes/Errors/Error403.tsx +++ b/app/scenes/Errors/Error403.tsx @@ -83,7 +83,7 @@ const Error403 = ({ documentId }: Props) => { ) : ( {t( - "It doesn't look like you have permission to access this document. You can request access." + "It doesn’t look like you have permission to access this document. You can request access." )} )} diff --git a/app/scenes/Errors/ErrorUnknown.tsx b/app/scenes/Errors/ErrorUnknown.tsx index 9d2b51bffb..75124d2e89 100644 --- a/app/scenes/Errors/ErrorUnknown.tsx +++ b/app/scenes/Errors/ErrorUnknown.tsx @@ -1,4 +1,9 @@ +import { faFaceFrown } from "@fortawesome/free-solid-svg-icons/faFaceFrown"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { Trans, useTranslation } from "react-i18next"; +import styled, { css, keyframes } from "styled-components"; +import { IconTitleWrapper } from "@shared/components/Icon"; +import { s } from "@shared/styles"; import Button from "~/components/Button"; import CenteredContent from "~/components/CenteredContent"; import Empty from "~/components/Empty"; @@ -14,7 +19,20 @@ const ErrorUnknown = () => { return ( - {t("Something went wrong")} + + <IconTitleWrapper aria-hidden> + <GlitchIcon> + <FontAwesomeIcon icon={faFaceFrown} /> + <GlitchLayer> + <FontAwesomeIcon icon={faFaceFrown} /> + </GlitchLayer> + <GlitchLayer $reverse> + <FontAwesomeIcon icon={faFaceFrown} /> + </GlitchLayer> + </GlitchIcon> + </IconTitleWrapper> + {t("Something went wrong")} + @@ -32,4 +50,96 @@ const ErrorUnknown = () => { ); }; +const red = "rgba(255, 0, 80, 0.75)"; +const cyan = "rgba(0, 220, 255, 0.75)"; + +const iconGlitch = keyframes` + 0%, 88%, 100% { + transform: none; + } + 89% { + transform: translate(-2px, 1px) skewX(10deg); + } + 91% { + transform: translate(2px, -1px) skewX(-6deg); + } + 93% { + transform: translate(-1px, 0); + } + 95% { + transform: none; + } +`; + +const sliceGlitch = keyframes` + 0%, 88%, 100% { + clip-path: inset(100% 0 0 0); + transform: none; + } + 89% { + clip-path: inset(10% 0 65% 0); + transform: translate(-4px, 0); + } + 90% { + clip-path: inset(55% 0 20% 0); + transform: translate(4px, 0); + } + 91.5% { + clip-path: inset(30% 0 45% 0); + transform: translate(-3px, 0); + } + 93% { + clip-path: inset(75% 0 5% 0); + transform: translate(3px, 0); + } + 94.5% { + clip-path: inset(0 0 85% 0); + transform: translate(-2px, 0); + } + 96% { + clip-path: inset(100% 0 0 0); + transform: none; + } +`; + +const Title = styled(Heading)` + position: relative; +`; + +const GlitchIcon = styled.span` + position: relative; + display: flex; + animation: ${iconGlitch} 4s steps(1, end) infinite; + + svg { + width: 27px; + height: 27px; + } +`; + +const GlitchLayer = styled.span<{ $reverse?: boolean }>` + position: absolute; + inset: 0; + display: flex; + background: ${s("background")}; + clip-path: inset(100% 0 0 0); + pointer-events: none; + animation: ${sliceGlitch} 4s steps(1, end) infinite; + + ${(props) => + props.$reverse + ? css` + animation-delay: 0.05s; + + svg { + filter: drop-shadow(2px 0 ${cyan}); + } + ` + : css` + svg { + filter: drop-shadow(-2px 0 ${red}); + } + `} +`; + export default ErrorUnknown; diff --git a/app/scenes/Home.tsx b/app/scenes/Home.tsx index f79799b7e8..6530aaec38 100644 --- a/app/scenes/Home.tsx +++ b/app/scenes/Home.tsx @@ -117,7 +117,7 @@ function Home() { {t("Weird, this shouldn't ever be empty")}} + empty={{t("Weird, this shouldn’t ever be empty")}} showCollection /> @@ -140,7 +140,9 @@ function Home() { documents={documents.createdByUser(userId)} fetch={documents.fetchOwned} options={{ - userId, + filters: [ + { field: "createdById", operator: "eq", value: userId }, + ], }} empty={ {t("You haven’t created any documents yet")} diff --git a/app/scenes/Invite.tsx b/app/scenes/Invite.tsx index a752999886..706da80aad 100644 --- a/app/scenes/Invite.tsx +++ b/app/scenes/Invite.tsx @@ -128,7 +128,7 @@ function Invite({ onSubmit }: Props) { content={ <> {collections.nonPrivate.map((collection) => ( -
  • {collection.name}
  • +
  • {collection.displayName}
  • ))} } @@ -262,7 +262,7 @@ function Invite({ onSubmit }: Props) { data-event-category="invite" data-event-action="sendInvites" > - {isSaving ? `${t("Inviting")}…` : t("Send Invites")} + {isSaving ? `${t("Inviting")}…` : t("Send invites")} diff --git a/app/scenes/Login/Login.tsx b/app/scenes/Login/Login.tsx index 99d8dc2bb1..bb657f8cc1 100644 --- a/app/scenes/Login/Login.tsx +++ b/app/scenes/Login/Login.tsx @@ -39,12 +39,13 @@ import AuthenticationProvider from "./components/AuthenticationProvider"; import { BackButton } from "./components/BackButton"; import { Background } from "./components/Background"; import { Centered } from "./components/Centered"; +import { EmailInboxButtons } from "./components/EmailInboxButtons"; import { Notices } from "./components/Notices"; import { PasskeyAuthenticationProvider } from "./components/PasskeyAuthenticationProvider"; import { SigningIn } from "./components/SigningIn"; import { SwitchHostButton } from "./components/SwitchHostButton"; import { navigateToSubdomain } from "./urls"; -import lazyWithRetry from "~/utils/lazyWithRetry"; +import lazyWithRetry from "@shared/utils/lazyWithRetry"; import { getRedirectUrl } from "~/utils/urls"; const WorkspaceSetup = lazyWithRetry( @@ -313,6 +314,7 @@ function Login({ children, onBack }: Props) { />
    + )} @@ -360,7 +362,7 @@ function Login({ children, onBack }: Props) { ) : ( <> - {t("Login to {{ authProviderName }}", { + {t("Log in to {{ authProviderName }}", { authProviderName: config.name || env.APP_NAME, })} diff --git a/app/scenes/Login/OAuthAuthorize.tsx b/app/scenes/Login/OAuthAuthorize.tsx index 07556aaab6..eb09e515e1 100644 --- a/app/scenes/Login/OAuthAuthorize.tsx +++ b/app/scenes/Login/OAuthAuthorize.tsx @@ -1,10 +1,11 @@ import { useState, useRef, useEffect } from "react"; import { Trans, useTranslation } from "react-i18next"; import styled from "styled-components"; -import { isLoopbackUri } from "~/utils/urls"; import Flex from "@shared/components/Flex"; import { s } from "@shared/styles"; import { parseDomain } from "@shared/utils/domains"; +import { getHostname, isLoopbackUri } from "@shared/utils/urls"; +import { OAuthClientValidation } from "@shared/validations"; import type OAuthClient from "~/models/oauth/OAuthClient"; import ButtonLarge from "~/components/ButtonLarge"; import ChangeLanguage from "~/components/ChangeLanguage"; @@ -22,6 +23,7 @@ import { AuthorizationError, BadRequestError, NotFoundError, + UnprocessableEntityError, } from "~/utils/errors"; import isCloudHosted from "~/utils/isCloudHosted"; import { detectLanguage } from "~/utils/language"; @@ -70,6 +72,22 @@ function inputScopes(scope?: string): string[] { return scope.split(" ").filter(Boolean); } +/** + * Returns the hostname of a client ID metadata document URL. + * + * @param clientId the OAuth client_id parameter. + * @returns the punycode hostname, or undefined if the client does not use a metadata document. + */ +function metadataDocumentHost(clientId: string) { + if ( + !clientId.startsWith(OAuthClientValidation.metadataDocumentClientIdPrefix) + ) { + return undefined; + } + + return getHostname(clientId); +} + /** * Authorize component is responsible for handling the OAuth authorization process. * It retrieves the OAuth client information, displays the authorization request, @@ -81,7 +99,7 @@ function Authorize() { const { t } = useTranslation(); const [isSubmitting, setIsSubmitting] = useState(false); const [isReady, setIsReady] = useState(false); - const timeoutRef = useRef(); + const timeoutRef = useRef(undefined); const { client_id: clientId, redirect_uri: redirectUri, @@ -152,6 +170,13 @@ function Authorize() { )}
    {redirectUri}
    + ) : clientError instanceof UnprocessableEntityError ? ( + + {t( + "The OAuth client could not be loaded from its metadata document" + )} +
    {clientError.message}
    +
    ) : clientError instanceof AuthorizationError ? ( {t( @@ -182,6 +207,8 @@ function Authorize() { } const { name, developerName, developerUrl } = response.data; + const clientHost = metadataDocumentHost(response.data.clientId); + const isLoopback = isLoopbackUri(redirectUri); return ( @@ -219,6 +246,15 @@ function Authorize() { /> )} + {clientHost && ( + + }} + /> + + )} {t( "{{ appName }} will be able to access your account and perform the following actions", @@ -237,8 +273,14 @@ function Authorize() { ) )} - - {isLoopbackUri(redirectUri) ? ( + + {isLoopback && clientHost ? ( + }} + /> + ) : isLoopback ? ( You will be redirected to a local application after authorizing. @@ -249,7 +291,7 @@ function Authorize() { redirectUri, }} components={{ - em: , + em: , }} /> )} @@ -304,6 +346,11 @@ const StyledHeading = styled(Heading).attrs({ margin-top: 0; `; +// Only the URL may break mid-word, so long URLs wrap without splitting prose. +const RedirectUri = styled.strong` + word-break: break-all; +`; + const Pre = styled.pre` background: ${s("backgroundSecondary")}; padding: 16px; diff --git a/app/scenes/Login/components/EmailInboxButtons.tsx b/app/scenes/Login/components/EmailInboxButtons.tsx new file mode 100644 index 0000000000..28ecf1a833 --- /dev/null +++ b/app/scenes/Login/components/EmailInboxButtons.tsx @@ -0,0 +1,54 @@ +import { observer } from "mobx-react"; +import { useTranslation } from "react-i18next"; +import styled from "styled-components"; +import { Inner } from "~/components/Button"; +import ButtonLarge from "~/components/ButtonLarge"; +import Flex from "~/components/Flex"; +import { GmailIcon } from "~/components/Icons/GmailIcon"; +import { OutlookIcon } from "~/components/Icons/OutlookIcon"; +import { useEmailInboxLinks } from "~/hooks/useEmailInboxLinks"; + +interface EmailInboxButtonsProps { + email: string; +} + +/** + * Shows links to find the sign-in email in Gmail or Outlook. + * + * @param props the recipient email address. + * @returns the available inbox buttons. + */ +export const EmailInboxButtons = observer(function EmailInboxButtons({ + email, +}: EmailInboxButtonsProps) { + const { t } = useTranslation(); + const links = useEmailInboxLinks(email); + + return ( + + {links.map(({ provider, href }) => ( + : } + fullwidth + neutral + > + {provider === "gmail" ? t("Open in Gmail") : t("Open in Outlook")} + + ))} + + ); +}); + +const Buttons = styled(Flex)` + width: 100%; + margin-bottom: 12px; + + ${Inner} { + height: 100%; + } +`; diff --git a/app/scenes/Login/components/Notices.tsx b/app/scenes/Login/components/Notices.tsx index 09cc986a47..78fc6737ad 100644 --- a/app/scenes/Login/components/Notices.tsx +++ b/app/scenes/Login/components/Notices.tsx @@ -1,4 +1,3 @@ -/* oxlint-disable react/no-unescaped-entities */ import { WarningIcon } from "outline-icons"; import { Trans } from "react-i18next"; import Notice from "~/components/Notice"; @@ -20,8 +19,8 @@ function Message({ notice }: { notice: string }) { case "domain-required": return ( - Unable to sign-in. Please navigate to your workspace's custom URL, - then try to sign-in again. + Unable to sign in. Please navigate to your workspace’s custom URL, + then try to sign in again.
    If you were invited to a workspace, you will find a link to it in the invite email. @@ -32,7 +31,7 @@ function Message({ notice }: { notice: string }) { Sorry, a new account cannot be created with a personal Gmail address.
    - Please use a Google Workspaces account instead. + Please use a Google Workspace account instead.
    ); case "pending-deletion": @@ -58,7 +57,7 @@ function Message({ notice }: { notice: string }) { case "email-auth-required": return ( - Your account uses email sign-in, please sign-in with email to + Your account uses email sign-in, please sign in with email to continue. ); diff --git a/app/scenes/Login/components/PasskeyAuthenticationProvider.tsx b/app/scenes/Login/components/PasskeyAuthenticationProvider.tsx index 9ee340ea2e..7b4c035cf6 100644 --- a/app/scenes/Login/components/PasskeyAuthenticationProvider.tsx +++ b/app/scenes/Login/components/PasskeyAuthenticationProvider.tsx @@ -7,6 +7,7 @@ import { CSRF } from "@shared/constants"; import { Client } from "@shared/types"; import { errToString } from "@shared/utils/error"; import ButtonLarge from "~/components/ButtonLarge"; +import ButtonLink from "~/components/ButtonLink"; import PluginIcon from "~/components/PluginIcon"; import useQuery from "~/hooks/useQuery"; import { client } from "~/utils/ApiClient"; @@ -51,9 +52,11 @@ function flattenFormFields( * Renders the "Continue with Passkey" login option and runs the WebAuthn * authentication ceremony. * - * In the desktop app the ceremony cannot run inside Electron's Chromium, so the - * flow is opened in the system browser and the resulting session is returned to - * the app via the outline:// deep link, mirroring the SSO desktop flow. + * In the desktop app the ceremony runs inside the app when it supports a + * platform authenticator. Otherwise, or if the user chooses a passkey that is + * not stored in the app, the flow is opened in the system browser and the + * resulting session is returned to the app via the outline:// deep link, + * mirroring the SSO desktop flow. */ export function PasskeyAuthenticationProvider(props: Props) { const { t } = useTranslation(); @@ -65,6 +68,13 @@ export function PasskeyAuthenticationProvider(props: Props) { ); const [isAuthenticating, setIsAuthenticating] = React.useState(false); const [hasError, setHasError] = React.useState(false); + const [isSupportedInApp, setIsSupportedInApp] = React.useState(false); + + React.useEffect(() => { + if (Desktop.isElectron()) { + void Desktop.isPasskeySupported().then(setIsSupportedInApp); + } + }, []); // True when this page was opened in the system browser from the desktop app // to complete a passkey login (see the /auth/passkey route). In that case the @@ -128,14 +138,19 @@ export function PasskeyAuthenticationProvider(props: Props) { } }, [isDesktopRedirect, runAuthentication]); + // Opens the flow in the system browser, which returns to the app via the + // outline:// deep link like SSO login. + const openInBrowser = () => { + window.location.href = `/auth/passkey?client=${Client.Desktop}`; + }; + const handleSubmit = (event: React.SyntheticEvent) => { event.preventDefault(); - // The WebAuthn ceremony cannot run inside Electron's Chromium as it lacks - // platform authenticator support. Open the flow in the system browser, - // which returns to the app via the outline:// deep link like SSO login. - if (Desktop.isElectron()) { - window.location.href = `/auth/passkey?client=${Client.Desktop}`; + // Older desktop apps and devices without a platform authenticator cannot + // run the WebAuthn ceremony inside the app. + if (Desktop.isElectron() && !isSupportedInApp) { + openInBrowser(); return; } @@ -172,6 +187,11 @@ export function PasskeyAuthenticationProvider(props: Props) {
    )} + {isSupportedInApp && hasError && ( + + {t("Use a passkey from your browser")} + + )} ); } @@ -180,6 +200,12 @@ const Wrapper = styled.div` width: 100%; `; +const Fallback = styled(ButtonLink)` + display: block; + margin: 12px auto 0; + font-size: 14px; +`; + const Form = styled.form` width: 100%; display: flex; diff --git a/app/scenes/Login/components/TeamSwitcher.tsx b/app/scenes/Login/components/TeamSwitcher.tsx index 842621bb86..0e9200d75e 100644 --- a/app/scenes/Login/components/TeamSwitcher.tsx +++ b/app/scenes/Login/components/TeamSwitcher.tsx @@ -37,7 +37,7 @@ export function TeamSwitcher({ sessions }: Props) { {t("Choose a workspace")} {t( - "Choose an {{ appName }} workspace or login to continue connecting this app", + "Choose an {{ appName }} workspace or log in to continue connecting this app", { appName } )} . @@ -63,7 +63,7 @@ export function TeamSwitcher({ sessions }: Props) { })} setShowLogin(true)}> - {t("Login to workspace")} + {t("Log in to workspace")} diff --git a/app/scenes/Login/components/WorkspaceSetup.tsx b/app/scenes/Login/components/WorkspaceSetup.tsx index a0edeb05f1..637e7c4a26 100644 --- a/app/scenes/Login/components/WorkspaceSetup.tsx +++ b/app/scenes/Login/components/WorkspaceSetup.tsx @@ -30,7 +30,7 @@ const WorkspaceSetup = ({ onBack }: { onBack?: () => void }) => { {t("Create workspace")} {t( - "Setup your workspace by providing a name and details for admin login. You can change these later." + "Set up your workspace by providing a name and details for admin login. You can change these later." )} @@ -38,7 +38,7 @@ const WorkspaceSetup = ({ onBack }: { onBack?: () => void }) => { name="teamName" type="text" label={t("Workspace name")} - placeholder="Acme, Inc" + placeholder="Acme, Inc." required autoFocus flex diff --git a/app/scenes/Search/components/CollectionFilter.tsx b/app/scenes/Search/components/CollectionFilter.tsx index 18768b7bfc..f61c65ef6a 100644 --- a/app/scenes/Search/components/CollectionFilter.tsx +++ b/app/scenes/Search/components/CollectionFilter.tsx @@ -20,7 +20,7 @@ function CollectionFilter(props: Props) { const options = useMemo(() => { const collectionOptions = collections.orderedData.map((collection) => ({ key: collection.id, - label: collection.name, + label: collection.displayName, icon: , })); return [ diff --git a/app/scenes/Search/components/DocumentFilter.tsx b/app/scenes/Search/components/DocumentFilter.tsx index f634cc7027..5416d5a370 100644 --- a/app/scenes/Search/components/DocumentFilter.tsx +++ b/app/scenes/Search/components/DocumentFilter.tsx @@ -19,7 +19,7 @@ export function DocumentFilter(props: Props) {
    } neutral> - {props.document.titleWithDefault} + {props.document.displayTitle}
    diff --git a/app/scenes/Search/components/RecentSearchListItem.tsx b/app/scenes/Search/components/RecentSearchListItem.tsx index 1698db0faf..5ad0bd11c5 100644 --- a/app/scenes/Search/components/RecentSearchListItem.tsx +++ b/app/scenes/Search/components/RecentSearchListItem.tsx @@ -1,7 +1,3 @@ -import { - useFocusEffect, - useRovingTabIndex, -} from "@getoutline/react-roving-tabindex"; import { CloseIcon } from "outline-icons"; import { useRef } from "react"; import { useTranslation } from "react-i18next"; @@ -11,6 +7,7 @@ import { s, hover } from "@shared/styles"; import type SearchQuery from "~/models/SearchQuery"; import NudeButton from "~/components/NudeButton"; import Tooltip from "~/components/Tooltip"; +import { useRovingTabIndex } from "~/hooks/useRovingTabIndex"; import { searchPath } from "~/utils/routeHelpers"; type Props = { @@ -23,7 +20,6 @@ function RecentSearchListItem({ searchQuery }: Props) { const ref = useRef(null); const { focused, ...rovingTabIndex } = useRovingTabIndex(ref, false); - useFocusEffect(focused, ref); return ( ) => void; + ref?: React.Ref; }; -function RecentSearches( - { onEscape }: Props, - ref: React.RefObject -) { +function RecentSearches({ onEscape, ref }: Props) { const { searches } = useStores(); const { t } = useTranslation(); @@ -67,4 +65,4 @@ const StyledArrowKeyNavigation = styled(ArrowKeyNavigation)` margin-top: 8px; `; -export default observer(React.forwardRef(RecentSearches)); +export default observer(RecentSearches); diff --git a/app/scenes/Search/components/SearchInput.tsx b/app/scenes/Search/components/SearchInput.tsx index 9eebe05137..df61fa074e 100644 --- a/app/scenes/Search/components/SearchInput.tsx +++ b/app/scenes/Search/components/SearchInput.tsx @@ -7,12 +7,10 @@ import Flex from "~/components/Flex"; interface Props extends React.InputHTMLAttributes { name: string; defaultValue: string; + ref: React.RefObject; } -function SearchInput( - { defaultValue, ...rest }: Props, - ref: React.RefObject -) { +function SearchInput({ defaultValue, ref, ...rest }: Props) { const theme = useTheme(); const focusInput = React.useCallback(() => { ref.current?.focus(); @@ -63,19 +61,19 @@ const StyledInput = styled.input` border-radius: 4px; color: ${s("text")}; - ::-webkit-search-cancel-button { + &::-webkit-search-cancel-button { -webkit-appearance: none; } - ::-webkit-input-placeholder { + &::-webkit-input-placeholder { color: ${s("placeholder")}; } - :-moz-placeholder { + &:-moz-placeholder { color: ${s("placeholder")}; } - ::-moz-placeholder { + &::-moz-placeholder { color: ${s("placeholder")}; } - :-ms-input-placeholder { + &:-ms-input-placeholder { color: ${s("placeholder")}; } `; @@ -86,4 +84,4 @@ const StyledIcon = styled(SearchIcon)` opacity: 0.7; `; -export default React.forwardRef(SearchInput); +export default SearchInput; diff --git a/app/scenes/Settings/Features.tsx b/app/scenes/Settings/AI.tsx similarity index 80% rename from app/scenes/Settings/Features.tsx rename to app/scenes/Settings/AI.tsx index 684f9c7afc..fa3261de67 100644 --- a/app/scenes/Settings/Features.tsx +++ b/app/scenes/Settings/AI.tsx @@ -17,7 +17,7 @@ import CopyToClipboard from "~/components/CopyToClipboard"; import NudeButton from "~/components/NudeButton"; import { useTheme } from "styled-components"; -function Features() { +function AI() { const { t } = useTranslation(); const team = useCurrentTeam(); const theme = useTheme(); @@ -53,18 +53,18 @@ function Features() { }> {t("AI")} - Manage AI and integration features for your workspace. + Control how AI features are used in the workspace. + {t("MCP server")} {t( - "Allow members to connect to this workspace with MCP to read and write data." + "Let members connect AI assistants and other apps to this workspace. Connected apps can read and edit content with the same permissions as the member who connects them." )} {team.getPreference(TeamPreference.MCP) && ( @@ -75,7 +75,7 @@ function Features() { style={{ marginTop: 8, marginBottom: 4 }} >
    - + @@ -106,6 +106,7 @@ function Features() { @@ -114,12 +115,13 @@ function Features() { {team.getPreference(TeamPreference.MCP) && (
    {t( - "You can use these optional instructions to tell MCP clients how to use your knowledge base." + "Optional instructions that are sent to connected AI apps, for example how your workspace is organized or where to find important information." )}
    )} + {t("AI answers")} @@ -153,4 +156,4 @@ function Features() { ); } -export default observer(Features); +export default observer(AI); diff --git a/app/scenes/Settings/APIAndAccess.tsx b/app/scenes/Settings/APIAndAccess.tsx index 66dd25b566..695f9d3d45 100644 --- a/app/scenes/Settings/APIAndAccess.tsx +++ b/app/scenes/Settings/APIAndAccess.tsx @@ -1,5 +1,5 @@ import { observer } from "mobx-react"; -import { PadlockIcon } from "outline-icons"; +import { CodeIcon } from "outline-icons"; import { useTranslation, Trans } from "react-i18next"; import type ApiKey from "~/models/ApiKey"; import type OAuthAuthentication from "~/models/oauth/OAuthAuthentication"; @@ -29,7 +29,7 @@ function APIAndAccess() { return ( } + icon={} actions={ <> {can.createApiKey && ( @@ -49,8 +49,7 @@ function APIAndAccess() { {can.createApiKey ? ( - {t("API Keys")} + {t("API keys")} - + diff --git a/app/scenes/Settings/Authentication.tsx b/app/scenes/Settings/Authentication.tsx index dd06e39abb..cef6030c9d 100644 --- a/app/scenes/Settings/Authentication.tsx +++ b/app/scenes/Settings/Authentication.tsx @@ -15,7 +15,9 @@ import Scene from "~/components/Scene"; import Switch from "~/components/Switch"; import Text from "~/components/Text"; import env from "~/env"; +import useConsumeQueryParam from "~/hooks/useConsumeQueryParam"; import useCurrentTeam from "~/hooks/useCurrentTeam"; +import usePolicy from "~/hooks/usePolicy"; import useRequest from "~/hooks/useRequest"; import useStores from "~/hooks/useStores"; import SettingRow from "./components/SettingRow"; @@ -32,6 +34,7 @@ import { VStack } from "~/components/primitives/VStack"; function Authentication() { const { authenticationProviders, dialogs } = useStores(); const team = useCurrentTeam(); + const can = usePolicy(team); const { t } = useTranslation(); const theme = useTheme(); @@ -47,6 +50,20 @@ function Authentication() { } }, [loading, providers, request]); + const groupSyncResult = useConsumeQueryParam("groupSync"); + + React.useEffect(() => { + if (!groupSyncResult) { + return; + } + + if (groupSyncResult === "connected") { + toast.success(t("Group sync connected")); + } else { + toast.error(t("Could not connect group sync")); + } + }, [groupSyncResult, t]); + const handleGuestSigninChange = React.useCallback( async (checked: boolean) => { try { @@ -109,6 +126,15 @@ function Authentication() { if (checked) { void (async () => { try { + if (provider.groupSyncRequiresSetup) { + const result = await client.post<{ data: { url: string } }>( + "/authenticationProviders.startGroupSync", + { id: provider.id } + ); + window.location.href = result.data.url; + return; + } + await provider.save({ settings: { ...provider.settings, @@ -162,116 +188,146 @@ function Authentication() { {t("Authentication")} - Manage how members sign-in to your workspace and which authentication + Manage how members sign in to your workspace and which authentication providers are enabled. - {t("Sign In")} + {t("Sign in")} - {authenticationProviders.orderedData.map((provider) => ( - - - {provider.displayName} - - } - name={provider.name} - description={ - provider.isConnected - ? t("Allow members to sign-in with {{ authProvider }}", { - authProvider: provider.displayName, - }) - : t("Connect {{ authProvider }} to allow members to sign-in", { - authProvider: provider.displayName, - }) - } - border={!(provider.isActive && provider.groupSyncSupported)} - > - - {provider.isConnected ? ( - + {authenticationProviders.orderedData.map((provider) => { + // Group sync can still be disabled after losing the entitlement. + const showGroupSync = + provider.isActive && + provider.groupSyncSupported && + (!!can.externalGroupSync || !!provider.settings?.groupSyncEnabled); + + return ( + + + {provider.displayName} + + } + name={provider.name} + description={ + provider.isConnected + ? t("Allow members to sign in with {{ authProvider }}", { + authProvider: provider.displayName, + }) + : t( + "Connect {{ authProvider }} to allow members to sign in", + { + authProvider: provider.displayName, + } + ) + } + border={!showGroupSync} + > + + {provider.isConnected ? ( + + + + {provider.providerId} + + + ) : ( - - {provider.providerId} - -
    - ) : ( - - )} - - - {provider.isActive && provider.groupSyncSupported && ( - - handleToggleGroupSync(provider, checked)} - /> - - )} - {provider.isActive && - provider.groupSyncSupported && - provider.groupSyncUsesClaim && - provider.settings?.groupSyncEnabled && ( - + + {showGroupSync && ( + - ) => { - const value = ev.target.value.trim(); - if (value !== (provider.settings?.groupClaim ?? "")) { - void handleGroupClaimChange(provider, value); + {provider.groupSyncRequiresSetup && + !provider.settings?.groupSyncEnabled ? ( + + ) : ( + + handleToggleGroupSync(provider, checked) } - }} - /> + /> + )} )} - - ))} + {showGroupSync && + provider.groupSyncUsesClaim && + provider.settings?.groupSyncEnabled && ( + + ) => { + const value = ev.target.value.trim(); + if (value !== (provider.settings?.groupClaim ?? "")) { + void handleGroupClaimChange(provider, value); + } + }} + /> + + )} + + ); + })} @@ -281,7 +337,7 @@ function Authentication() { name="guestSignin" description={ env.EMAIL_ENABLED - ? t("Allow members to sign-in using their email address") + ? t("Allow members to sign in using their email address") : t("The server must have SMTP configured to enable this setting") } border={false} @@ -301,7 +357,7 @@ function Authentication() { } name="passkeysEnabled" - description={t("Allow members to sign-in with a WebAuthn passkey")} + description={t("Allow members to sign in with a WebAuthn passkey")} > } > {t("New emoji")}… diff --git a/app/scenes/Settings/Details.tsx b/app/scenes/Settings/Details.tsx index 089817f1f0..03a76ae7e4 100644 --- a/app/scenes/Settings/Details.tsx +++ b/app/scenes/Settings/Details.tsx @@ -185,8 +185,8 @@ function Details() { return ( - }> - {t("Details")} + }> + {t("General")} These settings affect the way that your workspace appears to @@ -195,7 +195,7 @@ function Details() {
    - {t("Display")} + {t("Appearance")} ), }, + { + title: "OKF", + subtitle: t( + "Import a zip file of Markdown documents in the Open Knowledge Format" + ), + icon: , + action: ( + + ), + }, { title: "JSON", subtitle: t( diff --git a/app/scenes/Settings/Notifications.tsx b/app/scenes/Settings/Notifications.tsx index 65ed71a83b..b55b658207 100644 --- a/app/scenes/Settings/Notifications.tsx +++ b/app/scenes/Settings/Notifications.tsx @@ -36,7 +36,7 @@ function Notifications() { const options = [ { - event: NotificationEventType.PublishDocument, + events: [NotificationEventType.PublishDocument], icon: , title: t("Document published"), description: t( @@ -44,7 +44,7 @@ function Notifications() { ), }, { - event: NotificationEventType.UpdateDocument, + events: [NotificationEventType.UpdateDocument], icon: , title: t("Document updated"), description: t( @@ -52,7 +52,7 @@ function Notifications() { ), }, { - event: NotificationEventType.CreateComment, + events: [NotificationEventType.CreateComment], icon: , title: t("Comment posted"), description: t( @@ -60,7 +60,10 @@ function Notifications() { ), }, { - event: NotificationEventType.MentionedInComment, + events: [ + NotificationEventType.MentionedInComment, + NotificationEventType.MentionedInDocument, + ], icon: , title: t("Mentioned"), description: t( @@ -68,7 +71,10 @@ function Notifications() { ), }, { - event: NotificationEventType.GroupMentionedInDocument, + events: [ + NotificationEventType.GroupMentionedInDocument, + NotificationEventType.GroupMentionedInComment, + ], icon: , title: t("Group mentions"), description: t( @@ -76,7 +82,7 @@ function Notifications() { ), }, { - event: NotificationEventType.ResolveComment, + events: [NotificationEventType.ResolveComment], icon: , title: t("Resolved"), description: t( @@ -84,7 +90,7 @@ function Notifications() { ), }, { - event: NotificationEventType.ReactionsCreate, + events: [NotificationEventType.ReactionsCreate], icon: , title: t("Reaction added"), description: t( @@ -92,7 +98,7 @@ function Notifications() { ), }, { - event: NotificationEventType.CreateCollection, + events: [NotificationEventType.CreateCollection], icon: , title: t("Collection created"), description: t( @@ -100,7 +106,7 @@ function Notifications() { ), }, { - event: NotificationEventType.InviteAccepted, + events: [NotificationEventType.InviteAccepted], icon: , title: t("Invite accepted"), description: t( @@ -108,7 +114,7 @@ function Notifications() { ), }, { - event: NotificationEventType.AddUserToDocument, + events: [NotificationEventType.AddUserToDocument], icon: , title: t("Invited to document"), description: t( @@ -116,7 +122,7 @@ function Notifications() { ), }, { - event: NotificationEventType.AddUserToCollection, + events: [NotificationEventType.AddUserToCollection], icon: , title: t("Invited to collection"), description: t( @@ -124,7 +130,15 @@ function Notifications() { ), }, { - event: NotificationEventType.ExportCompleted, + events: [NotificationEventType.AddUserToGroup], + icon: , + title: t("Group membership"), + description: t( + "Receive a notification when you are added to or removed from a group" + ), + }, + { + events: [NotificationEventType.ExportCompleted], icon: , title: t("Export completed"), description: t( @@ -132,7 +146,7 @@ function Notifications() { ), }, { - event: NotificationEventType.RequestDocumentAccess, + events: [NotificationEventType.RequestDocumentAccess], icon: , title: t("Document access requested"), description: t( @@ -142,14 +156,14 @@ function Notifications() { { visible: isCloudHosted, icon: , - event: NotificationEventType.Onboarding, + events: [NotificationEventType.Onboarding], title: t("Getting started"), description: t("Tips on getting started with features and functionality"), }, { visible: isCloudHosted, icon: , - event: NotificationEventType.Features, + events: [NotificationEventType.Features], title: t("New features"), description: t("Receive an email when new features of note are added"), }, @@ -162,8 +176,11 @@ function Notifications() { }, 500); const handleChange = React.useCallback( - (eventType: NotificationEventType) => async (checked: boolean) => { - await user.setNotificationEventType(eventType, checked); + (eventTypes: NotificationEventType[]) => async (checked: boolean) => { + // Sequential, as each request saves the full settings object. + for (const eventType of eventTypes) { + await user.setNotificationEventType(eventType, checked); + } showSuccessMessage(); }, [user, showSuccessMessage] @@ -174,7 +191,9 @@ function Notifications() { runInAction(() => { const updated = { ...user.notificationSettings }; for (const option of visibleOptions) { - updated[option.event] = checked; + for (const eventType of option.events) { + updated[eventType] = checked; + } } user.notificationSettings = updated; }); @@ -189,7 +208,7 @@ function Notifications() { ); const allEnabled = visibleOptions.every((o) => - user.subscribedToEventType(o.event) + o.events.every((eventType) => user.subscribedToEventType(eventType)) ); const showSuccessNotice = window.location.search === "?success"; @@ -223,14 +242,17 @@ function Notifications() { {options.map((option) => { - const setting = user.subscribedToEventType(option.event); + const [name] = option.events; + const checked = option.events.every((eventType) => + user.subscribedToEventType(eventType) + ); return ( {option.description} @@ -239,11 +261,11 @@ function Notifications() { compact > ); diff --git a/app/scenes/Settings/Preferences.tsx b/app/scenes/Settings/Preferences.tsx index c0d3dc90da..1530a2f8b2 100644 --- a/app/scenes/Settings/Preferences.tsx +++ b/app/scenes/Settings/Preferences.tsx @@ -181,7 +181,7 @@ function Preferences() { Manage settings that affect your personal experience. - {t("Display")} + {t("Appearance")} Choose the interface language. Community translations are accepted - though our{" "} + through our{" "} @@ -303,7 +303,7 @@ function Preferences() { name={UserPreference.RememberLastPath} label={t("Remember previous location")} description={t( - "Automatically return to the document you were last viewing when the app is re-opened." + "Automatically return to the document you were last viewing when the app is reopened." )} > diff --git a/app/scenes/Settings/Security.tsx b/app/scenes/Settings/Security.tsx index 35ac63e6d0..51e8b312cd 100644 --- a/app/scenes/Settings/Security.tsx +++ b/app/scenes/Settings/Security.tsx @@ -31,7 +31,6 @@ function Security() { memberCollectionCreate: team.memberCollectionCreate, memberTeamCreate: team.memberTeamCreate, inviteRequired: team.inviteRequired, - passkeysEnabled: team.passkeysEnabled, }); const userRoleOptions: Option[] = React.useMemo( @@ -132,13 +131,6 @@ function Security() { [saveData] ); - const handlePasskeysEnabledChange = React.useCallback( - async (checked: boolean) => { - await saveData({ passkeysEnabled: checked }); - }, - [saveData] - ); - const handleMemberCollectionCreateChange = React.useCallback( async (checked: boolean) => { await saveData({ memberCollectionCreate: checked }); @@ -164,6 +156,17 @@ function Security() { [saveData, team.preferences] ); + const handlePersonalDocsChange = React.useCallback( + async (checked: boolean) => { + const preferences = { + ...team.preferences, + [TeamPreference.PersonalDocs]: checked, + }; + await saveData({ preferences }); + }, + [saveData, team.preferences] + ); + const handleViewersCanExportChange = React.useCallback( async (checked: boolean) => { const preferences = { @@ -301,21 +304,6 @@ function Security() { )} - {t("Authentication")} - - - - {t("Behavior")} + + + } wide> - {t("Shared Links")} + } wide> + {t("Shared links")} {can.update && !canShareDocuments && ( <> diff --git a/app/scenes/Settings/Template.tsx b/app/scenes/Settings/Template.tsx index b0dd9c1320..abccfb8835 100644 --- a/app/scenes/Settings/Template.tsx +++ b/app/scenes/Settings/Template.tsx @@ -81,7 +81,7 @@ const TemplateSetting = observer(function Template_({ template }: Props) { ...(collection ? [ createInternalLinkAction({ - name: collection.name, + name: collection.displayName, section: NavigationSection, icon: , to: collectionPath(collection), diff --git a/app/scenes/Settings/TemplateNew.tsx b/app/scenes/Settings/TemplateNew.tsx index 6369a3debf..d8d0ad3d72 100644 --- a/app/scenes/Settings/TemplateNew.tsx +++ b/app/scenes/Settings/TemplateNew.tsx @@ -32,7 +32,7 @@ function TemplateNewScene() { } void createTemplate(); - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, []); return ( diff --git a/app/scenes/Settings/Users.tsx b/app/scenes/Settings/Users.tsx index 2d9aa06d3b..df5c1b3def 100644 --- a/app/scenes/Settings/Users.tsx +++ b/app/scenes/Settings/Users.tsx @@ -7,6 +7,7 @@ import { Trans, useTranslation } from "react-i18next"; import { useHistory, useLocation } from "react-router-dom"; import { toast } from "sonner"; import styled from "styled-components"; +import breakpoint from "styled-components-breakpoint"; import type { Filter } from "@shared/helpers/FilterHelper"; import type UsersStore from "~/stores/UsersStore"; import { queriedUsers } from "~/stores/UsersStore"; @@ -155,7 +156,7 @@ function Users() { - + - + @@ -268,6 +269,12 @@ function getFilteredUsers({ return filteredUsers; } +const FilterGroup = styled(HStack)` + ${breakpoint("mobile", "tablet")` + display: contents; + `}; +`; + const LargeUserStatusFilter = styled(UserStatusFilter)` height: 32px; `; diff --git a/app/scenes/Settings/components/ApiKeyListItem.tsx b/app/scenes/Settings/components/ApiKeyListItem.tsx index 4aeb714aec..fdd2f47e13 100644 --- a/app/scenes/Settings/components/ApiKeyListItem.tsx +++ b/app/scenes/Settings/components/ApiKeyListItem.tsx @@ -78,7 +78,9 @@ const ApiKeyListItem = ({ apiKey }: Props) => { ); const [copied, setCopied] = useState(false); - const copyTimeoutIdRef = useRef>(); + const copyTimeoutIdRef = useRef | undefined>( + undefined + ); const handleCopy = useCallback(() => { if (copyTimeoutIdRef.current) { diff --git a/app/scenes/Settings/components/ConnectedButton.tsx b/app/scenes/Settings/components/ConnectedButton.tsx index d9a69e9b07..34360ea013 100644 --- a/app/scenes/Settings/components/ConnectedButton.tsx +++ b/app/scenes/Settings/components/ConnectedButton.tsx @@ -7,7 +7,7 @@ import { ConnectedIcon } from "~/components/Icons/ConnectedIcon"; import Text from "~/components/Text"; import useStores from "~/hooks/useStores"; -type Props = ButtonProps & { +type Props = ButtonProps<"button"> & { confirmationMessage: React.ReactNode; onClick: () => Promise | void; }; diff --git a/app/scenes/Settings/components/CopyButton.tsx b/app/scenes/Settings/components/CopyButton.tsx index 7334d19471..f442337673 100644 --- a/app/scenes/Settings/components/CopyButton.tsx +++ b/app/scenes/Settings/components/CopyButton.tsx @@ -26,7 +26,9 @@ export function CopyButton({ tooltip, icon = , }: Props) { - const timeout = React.useRef>(); + const timeout = React.useRef | undefined>( + undefined + ); const handleCopied = React.useCallback(() => { timeout.current = setTimeout(() => { @@ -41,7 +43,7 @@ export function CopyButton({ }, [success]); return ( - + {icon} diff --git a/app/scenes/Settings/components/DomainManagement.tsx b/app/scenes/Settings/components/DomainManagement.tsx index 68c3cb0481..dd72ee67a5 100644 --- a/app/scenes/Settings/components/DomainManagement.tsx +++ b/app/scenes/Settings/components/DomainManagement.tsx @@ -98,7 +98,7 @@ function DomainManagement({ onSuccess }: Props) { onChange={createOnDomainChangedHandler(index)} /> - + handleRemoveDomain(index)}> diff --git a/app/scenes/Settings/components/DropToImport.tsx b/app/scenes/Settings/components/DropToImport.tsx index 0831faba0d..ac95799450 100644 --- a/app/scenes/Settings/components/DropToImport.tsx +++ b/app/scenes/Settings/components/DropToImport.tsx @@ -26,7 +26,7 @@ import { EmptySelectValue } from "~/types"; import { uploadFile } from "~/utils/files"; type Props = { - children: JSX.Element; + children: React.JSX.Element; /** The importable service to create an import for. */ service: ImportableIntegrationService; disabled?: boolean; @@ -101,7 +101,7 @@ function DropToImport({ disabled, onSubmit, children, service }: Props) { {isImporting && } import("~/components/IconPicker")); + type Props = { group: Group; onSubmit: () => void; @@ -47,8 +53,18 @@ export function CreateGroupDialog() { const { t } = useTranslation(); const [name, setName] = React.useState(); const [description, setDescription] = React.useState(); + const [icon, setIcon] = React.useState(null); + const [color, setColor] = React.useState(null); const [isSaving, setIsSaving] = React.useState(false); + const handleIconChange = React.useCallback( + (newIcon: string | null, newColor: string | null) => { + setIcon(newIcon); + setColor(newColor); + }, + [] + ); + const handleSubmit = React.useCallback( async (ev: React.SyntheticEvent) => { ev.preventDefault(); @@ -58,6 +74,8 @@ export function CreateGroupDialog() { { name, description, + icon, + color, }, groups ); @@ -72,7 +90,7 @@ export function CreateGroupDialog() { setIsSaving(false); } }, - [dialogs, groups, name, description] + [dialogs, groups, name, description, icon, color] ); return ( @@ -87,10 +105,18 @@ export function CreateGroupDialog() { setName(e.target.value)} value={name} maxLength={GroupValidation.maxNameLength} + prefix={ + + } showCharacterCount required autoFocus @@ -98,7 +124,7 @@ export function CreateGroupDialog() { /> setDescription(e.target.value)} value={description || ""} @@ -121,6 +147,8 @@ export function EditGroupDialog({ group, onSubmit }: Props) { const { t } = useTranslation(); const [name, setName] = React.useState(group.name); const [description, setDescription] = React.useState(group.description || ""); + const [icon, setIcon] = React.useState(group.icon); + const [color, setColor] = React.useState(group.color); const [disableMentions, setDisableMentions] = React.useState( group.disableMentions || false ); @@ -134,6 +162,8 @@ export function EditGroupDialog({ group, onSubmit }: Props) { await group.save({ name, description, + icon, + color, disableMentions, }); onSubmit(); @@ -143,7 +173,15 @@ export function EditGroupDialog({ group, onSubmit }: Props) { setIsSaving(false); } }, - [group, onSubmit, name, description, disableMentions] + [group, onSubmit, name, description, icon, color, disableMentions] + ); + + const handleIconChange = React.useCallback( + (newIcon: string | null, newColor: string | null) => { + setIcon(newIcon); + setColor(newColor); + }, + [] ); const handleNameChange = React.useCallback( @@ -159,12 +197,12 @@ export function EditGroupDialog({ group, onSubmit }: Props) { {group.isExternallyManaged ? ( This group is managed by an external authentication provider. The - name is synced automatically and cannot be changed. + name and description are synced automatically and cannot be changed. ) : ( You can edit the name of this group at any time, however doing so - too often might confuse your team mates. + too often might confuse your teammates. )} @@ -175,6 +213,14 @@ export function EditGroupDialog({ group, onSubmit }: Props) { onChange={handleNameChange} value={name} maxLength={GroupValidation.maxNameLength} + prefix={ + + } showCharacterCount disabled={group.isExternallyManaged} required @@ -188,6 +234,7 @@ export function EditGroupDialog({ group, onSubmit }: Props) { onChange={(e) => setDescription(e.target.value)} value={description} maxLength={GroupValidation.maxDescriptionLength} + disabled={group.isExternallyManaged} flex /> ); }); + +type GroupIconPickerProps = { + icon: string | null; + color: string | null; + initial: string; + onChange: (icon: string | null, color: string | null) => void; +}; + +function GroupIconPicker({ + icon, + color, + initial, + onChange, +}: GroupIconPickerProps) { + const fallback = ; + + return ( + + + {icon ? undefined : fallback} + + + ); +} + +const StyledIconPicker = styled(IconPicker.Component)` + margin-left: 4px; + margin-right: 4px; +`; diff --git a/app/scenes/Settings/components/GroupMembersTable.tsx b/app/scenes/Settings/components/GroupMembersTable.tsx index 4c08d7ed89..9360c0c62e 100644 --- a/app/scenes/Settings/components/GroupMembersTable.tsx +++ b/app/scenes/Settings/components/GroupMembersTable.tsx @@ -117,6 +117,36 @@ export const GroupMembersTable = observer(function GroupMembersTable({ ), width: "1fr", }, + { + type: "data", + id: "addedAt", + header: t("Added"), + sortable: false, + accessor: (user) => + groupUsers.membership(group.id, user.id)?.createdAt ?? "", + component: (user) => { + const membership = groupUsers.membership(group.id, user.id); + if (!membership?.createdAt) { + return null; + } + return ( +