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..3869f76ae3 --- /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 + # the cluster forks a worker; stop the tree we started, never by process name. + pids="$(tree "$pid" | tr '\n' ' ')" + kill $pids 2>/dev/null || true + for _ in $(seq 1 10); do kill -0 $pids 2>/dev/null || break; sleep 1; done + kill -9 $pids 2>/dev/null || true + log "stopped server pids $pids" + fi + if lsof -nP -iTCP:"$PORT" -sTCP:LISTEN >/dev/null 2>&1; then + log "WARNING: port $PORT still has a listener; inspect with lsof before killing anything" + fi + docker rm -f "$PG_CONTAINER" "$REDIS_CONTAINER" >/dev/null 2>&1 || true + log "removed containers" + mkdir -p "$EVIDENCE" + cp "$SERVER_LOG" "$EVIDENCE/server.log" 2>/dev/null || true + rm -rf "$RUN_DIR" + log "removed $RUN_DIR; evidence kept at $EVIDENCE" + ls -la "$EVIDENCE" +} + +cmd_list() { + echo "runs:" + ls -1 "$ROOT/runs" 2>/dev/null | sed 's/^/ /' || true + echo "containers:" + docker ps -a --filter label=outline-verify --format ' {{.Names}}\t{{.Status}}' +} + +case "${1:-}" in + up) cmd_up "${2:-}" ;; + doctor) cmd_doctor "${2:-}" ;; + info) cmd_info "${2:-}" ;; + logs) cmd_logs "${2:-}" "${3:-}" ;; + psql) cmd_psql "${2:-}" "${3:-}" ;; + down) cmd_down "${2:-}" ;; + list) cmd_list ;; + *) sed -n '2,13p' "$0"; exit 1 ;; +esac diff --git a/.env.sample b/.env.sample index d56832fc34..58e8188cae 100644 --- a/.env.sample +++ b/.env.sample @@ -60,7 +60,8 @@ DEFAULT_LANGUAGE=en_US DATABASE_URL=postgres://user:pass@postgres:5432/outline # The in-memory database pool per-process settings. Ensure that the pool size that will not exceed -# the maximum number of connections allowed by your database. Defaults to 0 and 5. +# the maximum number of connections allowed by your database. Defaults to 0 and 5, the maximum +# must be at least 2. DATABASE_CONNECTION_POOL_MIN= DATABASE_CONNECTION_POOL_MAX= diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 8f02575b7b..d771b44bef 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -13,6 +13,9 @@ updates: update-types: ["version-update:semver-major"] schedule: interval: "weekly" + cooldown: + semver-patch-days: 3 + semver-minor-days: 7 groups: babel: patterns: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index deba3bc3cd..3c9cc7c78a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,10 +18,11 @@ env: jobs: changes: - # Blacksmith runners are only available to the outline organization, and are - # not used for pull requests from forks. - runs-on: ${{ (github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} + runs-on: ubuntu-latest outputs: + # Blacksmith runners are only available to the outline organization, and are + # not used for pull requests from forks. They are reserved for the test jobs + # that set the wall time of a CI run. runner: ${{ (github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} code: ${{ steps.filter.outputs.code }} config: ${{ steps.filter.outputs.config }} @@ -42,8 +43,8 @@ jobs: - '!shared/i18n/locales/**' config: - '.github/**' - - 'vite.config.ts' - - 'vitest.config.ts' + - 'vite.config.mts' + - 'vitest.config.mts' server: - 'server/**' - 'shared/**' @@ -63,7 +64,7 @@ jobs: lint: needs: changes if: ${{ needs.changes.outputs.code == 'true' }} - runs-on: ${{ needs.changes.outputs.runner }} + runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install @@ -82,7 +83,7 @@ jobs: types: needs: changes if: ${{ needs.changes.outputs.code == 'true' }} - runs-on: ${{ needs.changes.outputs.runner }} + runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install @@ -92,11 +93,20 @@ jobs: audit: needs: changes if: ${{ needs.changes.outputs.deps == 'true' }} - runs-on: ${{ needs.changes.outputs.runner }} + runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install - - run: yarn npm audit --severity high --recursive --environment production + # Pass when the audit service is unreachable, but still fail on vulnerabilities. + - run: | + set +e + yarn npm audit --severity high --recursive --environment production 2>&1 | tee audit.log + status=${PIPESTATUS[0]} + if [ "$status" -ne 0 ] && grep -qE "RequestError|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|Response Code: 5[0-9]{2}" audit.log; then + echo "::warning::yarn npm audit could not reach the audit service, skipping." + exit 0 + fi + exit "$status" test: needs: changes @@ -136,15 +146,17 @@ jobs: bundle-size: needs: changes if: ${{ (needs.changes.outputs.app == 'true' || needs.changes.outputs.config == 'true') && github.repository == 'outline/outline' }} - runs-on: ${{ needs.changes.outputs.runner }} + runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install - name: Set environment to production run: echo "NODE_ENV=production" >> "$GITHUB_ENV" - run: yarn vite:build + # RelativeCI is an external service, an outage should not block merging. - name: Send bundle stats to RelativeCI if: ${{ env.RELATIVE_CI_KEY != '' }} + continue-on-error: true env: RELATIVE_CI_KEY: ${{ secrets.RELATIVE_CI_KEY }} uses: relative-ci/agent-action@38328454d6a23942175eba485fca4fbb807b1f03 # v2 diff --git a/.github/workflows/dependabot-auto-merge.yml b/.github/workflows/dependabot-auto-merge.yml new file mode 100644 index 0000000000..57f691fa12 --- /dev/null +++ b/.github/workflows/dependabot-auto-merge.yml @@ -0,0 +1,58 @@ +name: Dependabot Auto-merge + +on: pull_request + +jobs: + auto-merge: + if: github.repository == 'outline/outline' && github.event.pull_request.user.login == 'dependabot[bot]' + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + + steps: + - name: Fetch Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3.1.0 + + # Patch bumps, and minor bumps from 1.0 or later, with no new publisher and + # that leave out packages the test suite does not cover well. The required + # "ci" check gates the merge. + - name: Enable auto-merge for eligible updates + env: + GH_TOKEN: ${{ github.token }} + PR_URL: ${{ github.event.pull_request.html_url }} + DEPENDENCIES: ${{ steps.metadata.outputs.updated-dependencies-json }} + run: | + # Turn off auto-merge from an earlier run, as Dependabot can refresh a PR in place. + skip() { + echo "$1" + if [ "$(gh pr view "$PR_URL" --json autoMergeRequest --jq '.autoMergeRequest != null')" = "true" ]; then + gh pr merge --disable-auto "$PR_URL" + fi + exit 0 + } + + if ! jq -e "length > 0" <<< "$DEPENDENCIES" > /dev/null; then + skip "No dependency metadata found, skipping auto-merge." + fi + + ineligible=$(jq -r ' + .[] + | select( + .maintainerChanges + or (.dependencyName | test("^(prosemirror-.*|yjs|y-.*|@hocuspocus/.*|sequelize.*|pg|pg-.*|react.*|mobx.*|koa.*|@koa/.*)$")) + or ( + .updateType != "version-update:semver-patch" + and (.updateType != "version-update:semver-minor" or (.prevVersion // "" | test("^v?[1-9]") | not)) + ) + ) + | "\(.dependencyName) \(.prevVersion) -> \(.newVersion) (\(.updateType)\(if .maintainerChanges then ", new publisher" else "" end))" + ' <<< "$DEPENDENCIES") + + if [ -n "$ineligible" ]; then + echo "Skipping auto-merge, these updates need review:" + skip "$ineligible" + fi + + gh pr merge --auto --squash "$PR_URL" diff --git a/.github/workflows/merge-translations.yml b/.github/workflows/merge-translations.yml new file mode 100644 index 0000000000..381f2c82cf --- /dev/null +++ b/.github/workflows/merge-translations.yml @@ -0,0 +1,44 @@ +name: Merge Translations + +on: + schedule: + # 09:00 UTC every Monday + - cron: "0 9 * * 1" + workflow_dispatch: + +jobs: + merge-translations: + if: github.repository == 'outline/outline' + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + + steps: + - name: Squash merge the Crowdin PR when required checks pass + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + pr=$(gh pr list \ + --head translations-main \ + --author outline-translations \ + --state open \ + --json number,headRefOid \ + --jq '.[0] // empty') + + if [ -z "$pr" ]; then + echo "No open translations PR." + exit 0 + fi + + number=$(jq -r '.number' <<< "$pr") + sha=$(jq -r '.headRefOid' <<< "$pr") + + if ! gh pr checks "$number" --required; then + echo "::error::Required checks are not passing on #$number." + exit 1 + fi + + # Only merge the commit that the checks ran against. + gh pr merge "$number" --squash --match-head-commit "$sha" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000000..620afb11c6 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,33 @@ +name: Draft release + +# Creates a draft GitHub release for each version tag pushed by `yarn release`, +# so the release is authored by github-actions rather than a maintainer. Edit +# the generated notes and publish the draft from the releases page. + +on: + push: + tags: + - "v*" + +permissions: {} + +jobs: + draft: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Create draft release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_REPO: ${{ github.repository }} + TAG: ${{ github.ref_name }} + run: | + args=(--draft --verify-tag --generate-notes --title "$TAG") + + # Tags such as v1.9.2-0 are prereleases. + if [[ "$TAG" == *-* ]]; then + args+=(--prerelease) + fi + + gh release create "$TAG" "${args[@]}" diff --git a/.husky/pre-commit b/.husky/pre-commit index 25d2235737..2312dc587f 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,4 +1 @@ -#!/usr/bin/env sh -. "$(dirname "$0")/_/husky.sh" - -npx lint-staged \ No newline at end of file +npx lint-staged 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/classes.mjs b/.oxlint/classes.mjs new file mode 100644 index 0000000000..5df7ce588b --- /dev/null +++ b/.oxlint/classes.mjs @@ -0,0 +1,38 @@ +/** + * Local oxlint plugin with class style rules. + */ + +const plugin = { + meta: { + name: "classes", + }, + rules: { + "no-private-identifier": { + meta: { + type: "suggestion", + docs: { + description: "Disallow `#` private class members.", + }, + messages: { + forbidden: + "Do not use `#` private members. Use the TypeScript `private` modifier instead.", + }, + }, + create(context) { + const check = (node) => { + if (node.key.type === "PrivateIdentifier") { + context.report({ node: node.key, messageId: "forbidden" }); + } + }; + + return { + AccessorProperty: check, + MethodDefinition: check, + PropertyDefinition: check, + }; + }, + }, + }, +}; + +export default plugin; diff --git a/.oxlint/editor.mjs b/.oxlint/editor.mjs new file mode 100644 index 0000000000..8af8fb5061 --- /dev/null +++ b/.oxlint/editor.mjs @@ -0,0 +1,198 @@ +/** + * Local oxlint plugin with ProseMirror editor-specific rules. + */ + +/** Files that contain editor schema code. */ +const EDITOR_FILE = + /(^|[\\/])(shared[\\/]editor|plugins[\\/][^\\/]+[\\/]shared)[\\/]/; + +/** Module that exports the url sanitizers, matched by any alias or relative path. */ +const SANITIZER_SOURCE = /(^|\/)utils\/urls$/; + +/** Exported names that sanitize a url for use in the DOM. */ +const SANITIZER_NAMES = new Set(["sanitizeUrl", "sanitizeImageSrc"]); + +/** Attributes that the browser can follow or load as a url. */ +const URL_ATTRIBUTES = new Set(["href", "src"]); + +/** Returns the static name of a property key, or null if it is computed. */ +function keyName(node, computed) { + if (!computed && node.type === "Identifier") { + return node.name; + } + if (node.type === "Literal" && typeof node.value === "string") { + return node.value; + } + return null; +} + +/** Returns true if the function is a `toDOM` method or `toDOM:` property. */ +function isToDOMFunction(node) { + const parent = node.parent; + if (!parent || parent.value !== node) { + return false; + } + if (parent.type !== "Property" && parent.type !== "MethodDefinition") { + return false; + } + return keyName(parent.key, parent.computed) === "toDOM"; +} + +/** Returns true if the node is inside the body of a `toDOM` function. */ +function isInsideToDOM(node) { + for (let current = node.parent; current; current = current.parent) { + if ( + (current.type === "FunctionExpression" || + current.type === "ArrowFunctionExpression") && + isToDOMFunction(current) + ) { + return true; + } + } + return false; +} + +/** Returns the variable that the identifier refers to, or null if it is not declared. */ +function resolveVariable(scope, identifier) { + for (let current = scope; current; current = current.upper) { + const variable = current.set.get(identifier.name); + if (variable) { + return variable; + } + } + return null; +} + +/** + * Returns true if the value cannot carry an unsafe url: a constant, an empty + * value, a direct sanitizer call, or a choice between such values. + */ +function isSafeValue(node, isSanitizer) { + switch (node.type) { + case "Literal": + return typeof node.value === "string" || node.value === null; + case "TemplateLiteral": + return node.expressions.length === 0; + case "Identifier": + return node.name === "undefined"; + case "CallExpression": + return node.callee.type === "Identifier" && isSanitizer(node.callee); + case "ConditionalExpression": + return ( + isSafeValue(node.consequent, isSanitizer) && + isSafeValue(node.alternate, isSanitizer) + ); + case "LogicalExpression": + return ( + isSafeValue(node.left, isSanitizer) && + isSafeValue(node.right, isSanitizer) + ); + default: + return false; + } +} + +const plugin = { + meta: { + name: "editor", + }, + rules: { + "sanitize-url-in-to-dom": { + meta: { + type: "problem", + docs: { + description: + "Require `sanitizeUrl()` for `href` and `src` values in ProseMirror `toDOM` methods, which write raw DOM attributes.", + }, + messages: { + unsanitized: + "Wrap the `{{name}}` value in `sanitizeUrl()` or `sanitizeImageSrc()` from `utils/urls`. `toDOM` writes raw DOM attributes, so a `javascript:` url in a node or mark attribute can run.", + }, + }, + create(context) { + if (!EDITOR_FILE.test(context.filename)) { + return {}; + } + + const sanitizerImports = new Set(); + + // Resolve by binding so a local function that shadows the import is not trusted. + const isSanitizer = (identifier) => { + const variable = resolveVariable( + context.sourceCode.getScope(identifier), + identifier + ); + return ( + !!variable && + variable.defs.some((def) => sanitizerImports.has(def.node)) + ); + }; + + const check = (node, name, value) => { + if (!isSafeValue(value, isSanitizer)) { + context.report({ + node, + messageId: "unsanitized", + data: { name }, + }); + } + }; + + return { + ImportDeclaration(node) { + if (!SANITIZER_SOURCE.test(node.source.value)) { + return; + } + for (const specifier of node.specifiers) { + if ( + specifier.type === "ImportSpecifier" && + SANITIZER_NAMES.has(keyName(specifier.imported, false)) + ) { + sanitizerImports.add(specifier); + } + } + }, + Property(node) { + const name = keyName(node.key, node.computed); + if ( + !URL_ATTRIBUTES.has(name) || + node.parent.type !== "ObjectExpression" || + !isInsideToDOM(node) + ) { + return; + } + check(node, name, node.value); + }, + CallExpression(node) { + const callee = node.callee; + if ( + callee.type !== "MemberExpression" || + keyName(callee.property, callee.computed) !== "setAttribute" || + node.arguments.length < 2 + ) { + return; + } + const name = keyName(node.arguments[0], true); + if (!URL_ATTRIBUTES.has(name) || !isInsideToDOM(node)) { + return; + } + check(node, name, node.arguments[1]); + }, + AssignmentExpression(node) { + const left = node.left; + if (left.type !== "MemberExpression") { + return; + } + const name = keyName(left.property, left.computed); + if (!URL_ATTRIBUTES.has(name) || !isInsideToDOM(node)) { + return; + } + check(node, name, node.right); + }, + }; + }, + }, + }, +}; + +export default plugin; diff --git a/.oxlint/koa.mjs b/.oxlint/koa.mjs new file mode 100644 index 0000000000..9b6400c44c --- /dev/null +++ b/.oxlint/koa.mjs @@ -0,0 +1,51 @@ +/** + * Local oxlint plugin with Koa-specific rules. + */ + +/** Returns true if the member expression accesses the given property name. */ +function isProperty(node, name) { + if (node.type !== "MemberExpression") { + return false; + } + + if (!node.computed) { + return node.property.type === "Identifier" && node.property.name === name; + } + + return node.property.type === "Literal" && node.property.value === name; +} + +const plugin = { + meta: { + name: "koa", + }, + rules: { + "no-request-origin": { + meta: { + type: "problem", + docs: { + description: + "Disallow `request.origin`, which returns the Origin header rather than the URL origin.", + }, + messages: { + forbidden: + "`request.origin` is the Origin request header and is null for same-origin requests. Use `request.URL.origin` instead.", + }, + }, + create(context) { + return { + MemberExpression(node) { + if ( + isProperty(node, "origin") && + isProperty(node.object, "request") + ) { + context.report({ node, messageId: "forbidden" }); + } + }, + }; + }, + }, + }, +}; + +export default plugin; diff --git a/.oxlint/react-router.mjs b/.oxlint/react-router.mjs new file mode 100644 index 0000000000..0f7d2d6f95 --- /dev/null +++ b/.oxlint/react-router.mjs @@ -0,0 +1,197 @@ +/** + * Local oxlint plugin with React Router rules. + */ + +const routerPackages = new Set(["react-router", "react-router-dom"]); + +/** Hooks whose callback runs later, outside of render. */ +const deferredHooks = new Set(["useCallback"]); + +/** Returns true if the node is a function. */ +function isFunction(node) { + return ( + node.type === "ArrowFunctionExpression" || + node.type === "FunctionExpression" || + node.type === "FunctionDeclaration" + ); +} + +/** Returns the hook name if the node is a call to `useX(…)` or `React.useX(…)`. */ +function hookName(node) { + if (node?.type !== "CallExpression") { + return null; + } + + const callee = node.callee; + if (callee.type === "Identifier") { + return callee.name; + } + + if (callee.type === "MemberExpression" && !callee.computed) { + return callee.property.name; + } + + return null; +} + +/** Returns true if the identifier is a reference rather than a property name. */ +function isReference(node, parent) { + if (parent.type === "MemberExpression" && parent.property === node) { + return parent.computed; + } + + if ( + (parent.type === "Property" || parent.type === "MethodDefinition") && + parent.key === node + ) { + return parent.computed || parent.value === node; + } + + return true; +} + +/** + * Returns true if the function is known to run later, outside of render: a + * JSX event handler such as `onClick`, or a `useCallback` callback. + */ +function isDeferredFunction(node, parent, grandparent) { + if (parent.type === "JSXExpressionContainer" && parent.expression === node) { + return ( + grandparent?.type === "JSXAttribute" && + grandparent.name.type === "JSXIdentifier" && + /^on[A-Z]/.test(grandparent.name.name) + ); + } + + return deferredHooks.has(hookName(parent)) && parent.arguments[0] === node; +} + +/** + * Classifies a reference by where it is read: "deferred" when it is read in a + * function known to run later, null when it does not read the value (a + * `useCallback` dependency array), and "render" otherwise. + */ +function classify(ancestors, owner) { + const start = ancestors.indexOf(owner); + + for (let i = start + 1; i < ancestors.length; i++) { + const node = ancestors[i]; + const parent = ancestors[i - 1]; + + if (isFunction(node)) { + return isDeferredFunction(node, parent, ancestors[i - 2]) + ? "deferred" + : "render"; + } + + if ( + node.type === "ArrayExpression" && + deferredHooks.has(hookName(parent)) && + parent.arguments[1] === node + ) { + return null; + } + } + + return "render"; +} + +const plugin = { + meta: { + name: "react-router", + }, + rules: { + "no-deferred-use-location": { + meta: { + type: "problem", + docs: { + description: + "Disallow `useLocation` when the location is only read in callbacks.", + }, + messages: { + forbidden: + "The location is only read in callbacks, but `useLocation` re-renders this component on every navigation. Read `history.location` in the callback instead.", + }, + }, + create(context) { + const useLocationNames = new Set(); + const tracked = []; + + return { + ImportDeclaration(node) { + if (!routerPackages.has(node.source.value)) { + return; + } + + for (const specifier of node.specifiers) { + if ( + specifier.type === "ImportSpecifier" && + specifier.imported.name === "useLocation" + ) { + useLocationNames.add(specifier.local.name); + } + } + }, + VariableDeclarator(node) { + if ( + node.id.type !== "Identifier" || + node.init?.type !== "CallExpression" || + node.init.callee.type !== "Identifier" || + !useLocationNames.has(node.init.callee.name) + ) { + return; + } + + const owner = context.sourceCode + .getAncestors(node) + .findLast(isFunction); + if (owner) { + tracked.push({ + node, + owner, + name: node.id.name, + render: false, + deferred: false, + }); + } + }, + Identifier(node) { + if (!tracked.length) { + return; + } + + const ancestors = context.sourceCode.getAncestors(node); + const parent = ancestors[ancestors.length - 1]; + if (!isReference(node, parent)) { + return; + } + + for (const entry of tracked) { + if ( + entry.name !== node.name || + entry.node.id === node || + !ancestors.includes(entry.owner) + ) { + continue; + } + + const kind = classify([...ancestors, node], entry.owner); + if (kind) { + entry[kind] = true; + } + } + }, + "Program:exit"() { + for (const entry of tracked) { + if (entry.deferred && !entry.render) { + context.report({ node: entry.node, messageId: "forbidden" }); + } + } + }, + }; + }, + }, + }, +}; + +export default plugin; diff --git a/.oxlint/sequelize.mjs b/.oxlint/sequelize.mjs new file mode 100644 index 0000000000..3dcedf862f --- /dev/null +++ b/.oxlint/sequelize.mjs @@ -0,0 +1,48 @@ +/** + * Local oxlint plugin with Sequelize-specific rules. + */ + +/** Returns true if the member expression accesses the given property name. */ +function isProperty(node, name) { + if (node.type !== "MemberExpression") { + return false; + } + + if (!node.computed) { + return node.property.type === "Identifier" && node.property.name === name; + } + + return node.property.type === "Literal" && node.property.value === name; +} + +const plugin = { + meta: { + name: "sequelize", + }, + rules: { + "prefer-after-commit-helper": { + meta: { + type: "problem", + docs: { + description: + "Disallow calling `transaction.afterCommit` directly. Use the `afterCommit` helper from `@server/storage/transaction` instead.", + }, + messages: { + forbidden: + "Use `afterCommit(transaction, callback)` from `@server/storage/transaction`. A nested transaction runs its hooks when the savepoint is released, before the commit, and the helper also runs the callback when there is no transaction.", + }, + }, + create(context) { + return { + CallExpression(node) { + if (isProperty(node.callee, "afterCommit")) { + context.report({ node: node.callee, messageId: "forbidden" }); + } + }, + }; + }, + }, + }, +}; + +export default plugin; diff --git a/.oxlint/vitest.mjs b/.oxlint/vitest.mjs new file mode 100644 index 0000000000..3fc12eaf7f --- /dev/null +++ b/.oxlint/vitest.mjs @@ -0,0 +1,76 @@ +/** + * Local oxlint plugin with rules for Vitest test files. + */ + +// Must match ISOLATED_MARKER and the header length checked in vitest.config.mts. +const ISOLATED_MARKER = "@vitest-isolate true"; +const HEADER_LENGTH = 512; + +const MODULE_METHODS = new Set(["mock", "doMock", "resetModules"]); + +/** Returns true if the file runs in the server Vitest projects. */ +function isServerTestFile(filename) { + return /(^|\/)(server|plugins)\/.*\.test\.tsx?$/.test( + filename.replace(/\\/g, "/") + ); +} + +/** Returns the method name if the callee is `vi.<method>`, else null. */ +function viMethodName(callee) { + if ( + callee.type !== "MemberExpression" || + callee.computed || + callee.object.type !== "Identifier" || + callee.object.name !== "vi" || + callee.property.type !== "Identifier" + ) { + return null; + } + return callee.property.name; +} + +const plugin = { + meta: { + name: "vitest-local", + }, + rules: { + "require-isolate-directive": { + meta: { + type: "problem", + docs: { + description: + "Require the `// @vitest-isolate true` header in server test files that mock or reset modules. Server tests share a module registry between files, so a mock leaks into other files.", + }, + messages: { + missing: + "`vi.{{method}}` changes the module registry that server test files share. Add `// @vitest-isolate true` as the first line of this file so it runs isolated.", + }, + }, + create(context) { + if (!isServerTestFile(context.filename)) { + return {}; + } + + const header = context.sourceCode.text.slice(0, HEADER_LENGTH); + if (header.includes(ISOLATED_MARKER)) { + return {}; + } + + return { + CallExpression(node) { + const method = viMethodName(node.callee); + if (method && MODULE_METHODS.has(method)) { + context.report({ + node: node.callee, + messageId: "missing", + data: { method }, + }); + } + }, + }; + }, + }, + }, +}; + +export default plugin; diff --git a/.oxlintrc.json b/.oxlintrc.json index 203bd0254f..75b70179c3 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -9,9 +9,38 @@ "patches/**", "*.d.ts" ], - "jsPlugins": ["./.oxlint/mobx.mjs"], + "jsPlugins": [ + "./.oxlint/mobx.mjs", + "./.oxlint/bundle.mjs", + "./.oxlint/sequelize.mjs", + "./.oxlint/vitest.mjs", + "./.oxlint/editor.mjs", + "./.oxlint/koa.mjs", + "./.oxlint/react-router.mjs", + "./.oxlint/classes.mjs" + ], + "plugins": ["eslint", "typescript", "unicorn", "oxc", "vitest"], "rules": { "mobx/observable-needs-initializer": "error", + "sequelize/prefer-after-commit-helper": "error", + "vitest/consistent-test-it": [ + "error", + { "fn": "it", "withinDescribe": "it" } + ], + "vitest/no-focused-tests": "error", + "vitest/no-disabled-tests": "error", + "vitest/no-identical-title": "error", + "vitest/expect-expect": "off", + "vitest/no-conditional-expect": "off", + "vitest/require-mock-type-parameters": "off", + "vitest/require-to-throw-message": "off", + "vitest/valid-expect": "off", + "vitest/valid-title": "off", + "vitest-local/require-isolate-directive": "error", + "editor/sanitize-url-in-to-dom": "error", + "koa/no-request-origin": "error", + "react-router/no-deferred-use-location": "error", + "classes/no-private-identifier": "error", "for-direction": "error", "no-async-promise-executor": "error", "no-case-declarations": "error", @@ -70,6 +99,24 @@ "valid-typeof": "error" }, "overrides": [ + { + "files": ["plugins/*/client/**/*.{js,jsx,ts,tsx}"], + "rules": { + "bundle/no-constructor-name": "error" + } + }, + { + "files": ["plugins/*/server/**/*.{js,ts}"], + "rules": { + "no-restricted-properties": [ + "error", + { + "property": "isBot", + "message": "Use `isbot` from the `isbot` package instead" + } + ] + } + }, { "files": ["**/*.{ts,tsx}"], "rules": { @@ -96,12 +143,19 @@ ], "message": "Use the wrappers from shared/editor/commands/table instead, which respect the target index and place the cursor in the inserted cell." } + ], + "patterns": [ + { + "group": ["lodash", "lodash/*", "lodash.*", "lodash-es"], + "message": "Use es-toolkit instead." + } ] } ], "no-unused-expressions": "error", "arrow-body-style": ["error", "as-needed"], "react/react-in-jsx-scope": "off", + "react/button-has-type": "error", "typescript/await-thenable": "error", "typescript/no-duplicate-type-constituents": "error", "typescript/no-meaningless-void-operator": "error", 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/AGENTS.md b/AGENTS.md index 0fe213fa37..d05be00ac3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,10 +32,12 @@ You're an expert in the following areas: - Critical – Do not create new markdown (.md) files. - Use early returns for readability. +- Leave an empty line above every comment, unless the comment is the first line in a block. - Emphasize type safety and static analysis. - Follow consistent oxfmt formatting. - Do not replace smart quotes ("") or ('') with simple quotes (""). - Do not add translation strings manually; they will be extracted automatically from the codebase. +- UI strings use US English and full grammar. Do not join two sentences with a comma. ## Dependencies and Upgrading @@ -94,6 +96,10 @@ This keeps overrides scoped to the affected dependents and avoids forcing unrela - Do not import React unless it is used directly. - Use styled-components for component styling. - Ensure high accessibility (a11y) standards using ARIA roles and semantic HTML. +- In components that stay mounted across navigation (layout, sidebar, command bar), do not use `useLocation`. Use `useLocationSelector` to select only the value you need, or read `history.location` in effects and handlers. +- Give stable props to memoized and `observer` components, especially list rows. Do not create new arrays, objects, or JSX on each render; use shared constants for empty arrays. +- Do not read `ref.current` during render to pass it to props or context. Keep the element in state with a callback ref. +- If the initial value of `useState` reads observables, use a lazy initializer. Otherwise the expression runs, and subscribes, on every render. ## MobX State Management @@ -102,6 +108,10 @@ This keeps overrides scoped to the affected dependents and avoids forcing unrela - Use `observable`, `action`, and `computed` decorators appropriately. - Prefer computed values over manual calculations in render. - Keep business logic in stores, not components. +- Do not read an observable during render only for an effect or a per-item check. Use `useComputed` to derive a narrow value (e.g. `isActive`) so only affected components re-render. +- Use `observable.map` rather than a set when observers check membership by key. `ObservableSet.has()` tracks the whole set, so any change re-renders every observer. +- Store lookups called for each row of a list must not scan a computed list such as `orderedData`, as this subscribes the component to every item in the store. +- A context value provided near the app root must not change on navigation. Expose frequently changing store values as getters read on access, not values read during render. ## Database & ORM @@ -116,6 +126,9 @@ yarn sequelize migration:create --name=add-field-to-table - Use transactions for multi-table operations. - Add appropriate indexes for query performance. - Always handle database errors gracefully. +- When updating Sequelize array or JSON attributes, replace the value instead of mutating it in place; reload the model in tests to verify persistence rather than trusting its in-memory state. +- Schedule optional background work that depends on a transaction from `afterCommit`, and use non-fatal scheduling so a queue failure does not fail the committed operation. +- When changing persisted task input fields, keep readers compatible with queued inputs or migrate them before removing old fields. ## API Design @@ -133,12 +146,18 @@ yarn sequelize migration:create --name=add-field-to-table - Use cancan-style ability checks. - Use authenticated middleware for protected routes. - Always verify user permissions before data access. +- When linking accounts by provider email, use exact case-insensitive equality within the workspace. +- Set account email and passkey management routes to `AuthenticationType.APP`; API-key authentication must not change login credentials or authenticators. ## Real-time Collaboration - WebSocket connections for real-time updates. - Use Y.js for collaborative editing. - Handle connection state changes gracefully. +- For bulk deletions that drive authorization or WebSocket processing, load affected models in the transaction and delete each with request context so downstream processors receive the expected per-item events. +- Do not persist viewer-specific unfurls in shared document mentions; only store unfurls that map to a stable mention type. +- When persisting pasted attachment URLs, use `signedUrlToAttachmentUrl` to convert this instance’s signed URLs to stable attachment redirects. Cover HTML, Markdown, and single-URL pastes, including pasting over selected text; document nodes and link marks must not retain expiring local URLs, and external URLs must remain unchanged. +- Editor plugins that repair the document (assigning missing IDs, fixing invalid structure) must use `RepairPlugin` from `shared/editor/plugins/RepairPlugin.ts`. Other plugins that change the document in `appendTransaction` must only respond to local changes, guard with `isLocalDocChange` from `shared/editor/lib/multiplayer.ts`. Otherwise every connected client writes the change in response to remote edits and is attributed as an editor. ## Documentation @@ -195,6 +214,7 @@ yarn test:shared # All shared code tests - Implement pagination for large lists. - Use database indexes effectively. - Cache expensive computations. +- Use `Redis.ephemeralClient` for request-path caches, rate limits, and locks, including lock extension and release. - Monitor performance with appropriate tools. - Lazy load routes and components where appropriate. diff --git a/Dockerfile b/Dockerfile index 417de10833..e704d2e430 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,7 +6,7 @@ ARG APP_PATH WORKDIR $APP_PATH # --- -FROM node:26.3.0-slim AS runner +FROM node:26.13.1-slim AS runner LABEL org.opencontainers.image.source="https://github.com/outline/outline" diff --git a/Dockerfile.base b/Dockerfile.base index 9b33ade00a..3267b7cd08 100644 --- a/Dockerfile.base +++ b/Dockerfile.base @@ -1,5 +1,5 @@ ARG APP_PATH=/opt/outline -FROM node:26.3.0 AS deps +FROM node:26.13.1 AS deps ARG APP_PATH WORKDIR $APP_PATH diff --git a/LICENSE b/LICENSE index 494e025dfb..8d7168ef0a 100644 --- a/LICENSE +++ b/LICENSE @@ -3,7 +3,7 @@ Business Source License 1.1 Parameters Licensor: General Outline, Inc. -Licensed Work: Outline 1.10.1 +Licensed Work: Outline 1.12.0 The Licensed Work is (c) 2026 General Outline, Inc. Additional Use Grant: You may make use of the Licensed Work, provided that you may not use the Licensed Work for a Document @@ -15,7 +15,7 @@ Additional Use Grant: You may make use of the Licensed Work, provided that Licensed Work by creating teams and documents controlled by such third parties. -Change Date: 2030-09-09 +Change Date: 2030-10-23 Change License: Apache License, Version 2.0 diff --git a/README.md b/README.md index a60d84414d..8dcb6a16cc 100644 --- a/README.md +++ b/README.md @@ -104,10 +104,6 @@ Or, to run migrations on test database: yarn db:migrate --env test ``` -# Activity - -![Alt](https://repobeats.axiom.co/api/embed/ff2e4e6918afff1acf9deb72d1ba6b071d586178.svg "Repobeats analytics image") - # License Outline is [BSL 1.1 licensed](LICENSE). 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 ce3d9271bf..2e3d42adca 100644 --- a/app/.oxlintrc.json +++ b/app/.oxlintrc.json @@ -6,6 +6,7 @@ { "files": ["**/*.{js,jsx,ts,tsx}"], "rules": { + "bundle/no-constructor-name": "error", "no-restricted-globals": [ "error", { @@ -37,6 +38,10 @@ { "group": ["mime-types"], "message": "Do not use the mime-types package in the browser." + }, + { + "group": ["lodash", "lodash/*", "lodash.*", "lodash-es"], + "message": "Use es-toolkit instead." } ] } diff --git a/app/actions/definitions/collections.tsx b/app/actions/definitions/collections.tsx index 83eeb357f0..a99d197bf7 100644 --- a/app/actions/definitions/collections.tsx +++ b/app/actions/definitions/collections.tsx @@ -65,13 +65,15 @@ export const openCollection = createActionWithChildren({ shortcut: ["o", "c"], icon: <CollectionIcon />, children: ({ stores }) => { - const collections = stores.collections.orderedData; + const collections = stores.collections.orderedData.filter( + (collection) => !collection.isPersonal + ); return collections.map((collection) => createInternalLinkAction({ // Note: using url which includes the slug rather than id here to bust // cache if the collection is renamed id: collection.path, - name: collection.name, + name: collection.displayName, icon: <ColorCollectionIcon collection={collection} />, section: CollectionSection, to: collection.path, @@ -98,7 +100,8 @@ export const editCollection = createAction({ analyticsName: "Edit collection", section: ActiveCollectionSection, icon: <EditIcon />, - visible: ({ getActivePolicies }) => + visible: ({ getActiveModel, getActivePolicies }) => + !getActiveModel(Collection)?.isPersonal && getActivePolicies(Collection).some((policy) => policy.abilities.update), perform: ({ t, getActiveModel, stores }) => { const collection = getActiveModel(Collection); @@ -125,7 +128,9 @@ export const editCollectionPermissions = createAction({ section: ActiveCollectionSection, icon: <PadlockIcon />, visible: ({ getActivePolicies }) => - getActivePolicies(Collection).some((policy) => policy.abilities.update), + getActivePolicies(Collection).some( + (policy) => policy.abilities.manageUsers + ), perform: ({ t, getActiveModel, stores }) => { const collection = getActiveModel(Collection); if (!collection) { @@ -385,6 +390,7 @@ export const subscribeCollection = createAction({ return ( !!collection.isActive && + !collection.isPersonal && !collection.isSubscribed && stores.policies.abilities(collection.id).subscribe ); diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index e89d86d31a..c5ac4603ca 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -7,7 +7,6 @@ import { StarredIcon, PrintIcon, UnstarredIcon, - DocumentIcon, NewDocumentIcon, ShapesIcon, ImportIcon, @@ -42,6 +41,7 @@ import { PDFIcon, } from "outline-icons"; import { toast } from "sonner"; +import { showPublicLinkCopiedToast } from "~/components/Sharing/components/toasts"; import Icon from "@shared/components/Icon"; import type { NavigationNode } from "@shared/types"; import { @@ -117,8 +117,10 @@ import env from "~/env"; import { isMac, isWindows } from "@shared/utils/browser"; import isCloudHosted from "~/utils/isCloudHosted"; import DocumentMove from "~/components/DocumentExplorer/DocumentMove"; +import { DocumentIcon } from "~/components/Icons/DocumentIcon"; -const Insights = lazyWithRetry( +/** Lazy insights dialog, exported so that triggers can preload it. */ +export const Insights = lazyWithRetry( () => import("~/scenes/Document/components/Insights") ); const SharePopover = lazyWithRetry( @@ -151,10 +153,11 @@ export const openDocument = createActionWithChildren({ .filter((item) => !recentIds.has(item.id)) .map((item) => { const document = stores.documents.get(item.id); + const path = item instanceof Document ? item.path : item.url; return createInternalLinkAction({ - // Note: using url which includes the slug rather than id here to bust + // Note: using path which includes the slug rather than id here to bust // cache if the document is renamed - id: item.url, + id: path, name: item.title, description: document ? documentBreadcrumbText(document, t) @@ -166,10 +169,10 @@ export const openDocument = createActionWithChildren({ color={item.color ?? undefined} /> ) : ( - <DocumentIcon outline={item.isDraft} /> + <DocumentIcon empty={document?.isEmpty} /> ), section: DocumentSection, - to: item.url, + to: path, }); }); }, @@ -491,7 +494,7 @@ export const starDocument = createAction({ (document) => document.star(), (documents, succeeded, t) => documents.length > 1 - ? t("{{ count }} documents starred", { count: succeeded }) + ? t("{{ count }} document starred", { count: succeeded }) : undefined ); setPersistedState(getHeaderExpandedKey("starred"), true); @@ -519,7 +522,7 @@ export const unstarDocument = createAction({ (document) => document.unstar(), (documents, succeeded, t) => documents.length > 1 - ? t("{{ count }} documents unstarred", { count: succeeded }) + ? t("{{ count }} document unstarred", { count: succeeded }) : undefined ), }); @@ -587,7 +590,7 @@ export const unpublishDocument = createAction({ ? t("Unpublished {{ documentName }}", { documentName: documents[0].noun, }) - : t("{{ count }} documents unpublished", { count: succeeded }) + : t("{{ count }} document unpublished", { count: succeeded }) ), }); @@ -720,20 +723,17 @@ export const shareDocument = createAction({ }, }); -/** - * Shows a file extension in the shortcut slot of menu items only, the command - * bar would otherwise register it as a key sequence. - */ +/** Shows a file extension at the end of menu items only. */ const fileExtensionHint = (extension: string) => ({ isMenu }: ActionContext) => - isMenu ? [extension] : undefined; + isMenu ? extension : undefined; export const downloadDocumentAsMarkdown = createAction({ name: ({ t, isMenu }) => (isMenu ? t("Markdown") : t("Download as Markdown")), analyticsName: "Download document as Markdown", section: ActiveDocumentSection, - shortcut: fileExtensionHint(".md"), + badge: fileExtensionHint(".md"), keywords: "md markdown export download", icon: <MarkdownIcon />, iconInContextMenu: false, @@ -755,7 +755,7 @@ export const downloadDocumentAsHTML = createAction({ name: ({ t, isMenu }) => (isMenu ? t("HTML") : t("Download as HTML")), analyticsName: "Download document as HTML", section: ActiveDocumentSection, - shortcut: fileExtensionHint(".html"), + badge: fileExtensionHint(".html"), keywords: "xml html export download", icon: <CodeIcon />, iconInContextMenu: false, @@ -778,7 +778,7 @@ export const downloadDocumentAsTextBundle = createAction({ isMenu ? t("TextBundle") : t("Download as TextBundle"), analyticsName: "Download document as TextBundle", section: ActiveDocumentSection, - shortcut: fileExtensionHint(".textpack"), + badge: fileExtensionHint(".textpack"), keywords: "textbundle textpack bear ulysses export download", icon: <ArchiveIcon />, iconInContextMenu: false, @@ -800,7 +800,7 @@ export const downloadDocumentAsPDF = createAction({ name: ({ t, isMenu }) => (isMenu ? t("PDF") : t("Download as PDF")), analyticsName: "Download document as PDF", section: ActiveDocumentSection, - shortcut: fileExtensionHint(".pdf"), + badge: fileExtensionHint(".pdf"), keywords: "pdf export download", icon: <PDFIcon />, iconInContextMenu: false, @@ -872,7 +872,7 @@ export const copyDocumentShareLink = createAction({ iconInContextMenu: false, visible: ({ activeDocumentId, stores }) => !!activeDocumentId && - !!stores.shares.getByDocumentId(activeDocumentId)?.published, + !!stores.shares.getByDocumentId(activeDocumentId)?.isActive, perform: ({ stores, activeDocumentId, t }) => { if (!activeDocumentId) { return; @@ -880,7 +880,7 @@ export const copyDocumentShareLink = createAction({ const share = stores.shares.getByDocumentId(activeDocumentId); if (share) { copy(share.url); - toast.success(t("Link copied to clipboard")); + showPublicLinkCopiedToast(share, t); } }, }); @@ -989,7 +989,7 @@ export const pinDocumentToCollection = createAction({ (documents, succeeded, t) => documents.length === 1 ? t("Pinned to collection") - : t("{{ count }} documents pinned", { count: succeeded }) + : t("{{ count }} document pinned", { count: succeeded }) ), }); @@ -1050,7 +1050,7 @@ export const unpinDocument = createAction({ (documents, succeeded, t) => documents.length === 1 ? t("Unpinned") - : t("{{ count }} documents unpinned", { count: succeeded }) + : t("{{ count }} document unpinned", { count: succeeded }) ), }); @@ -1373,7 +1373,7 @@ export const searchDocumentsForQueryActionFactory = (query: string) => createInternalLinkAction({ id: "search", name: ({ t }) => - t(`Search documents for "{{searchQuery}}"`, { searchQuery: query }), + t("Search documents for “{{ searchQuery }}”", { searchQuery: query }), analyticsName: "Search documents", section: SearchResultsSection, priority: -1, @@ -1389,31 +1389,32 @@ export const moveDocumentToCollection = createAction({ section: ActiveDocumentSection, icon: <MoveIcon />, iconInContextMenu: false, - visible: ({ activeDocumentId, stores }) => { - if (!activeDocumentId) { - return false; + visible: (context) => + everyActiveModel( + context, + Document, + (document) => !!context.stores.policies.abilities(document.id).move + ), + perform: ({ getActiveModels, stores, t }) => { + const documents = getActiveModels(Document); + if (!documents.length) { + return; } - return !!stores.policies.abilities(activeDocumentId).move; - }, - perform: ({ activeDocumentId, stores, t }) => { - if (activeDocumentId) { - const document = stores.documents.get(activeDocumentId); - if (!document) { - return; - } - stores.dialogs.openModal({ - title: ( + stores.dialogs.openModal({ + title: + documents.length === 1 ? ( <DialogTitle title={t("Move {{ documentType }}", { - documentType: document.noun, + documentType: documents[0].noun, })} - model={document} + model={documents[0]} /> + ) : ( + t("Move {{ count }} document", { count: documents.length }) ), - content: <DocumentMove document={document} />, - }); - } + content: <DocumentMove documents={documents} />, + }); }, }); @@ -1422,16 +1423,7 @@ export const moveDocument = createAction({ analyticsName: "Move document", section: ActiveDocumentSection, icon: <MoveIcon />, - visible: ({ activeDocumentId, stores }) => { - if (!activeDocumentId) { - return false; - } - const document = stores.documents.get(activeDocumentId); - if (!document) { - return false; - } - return !!stores.policies.abilities(activeDocumentId).move; - }, + visible: moveDocumentToCollection.visible, perform: moveDocumentToCollection.perform, }); @@ -1475,7 +1467,7 @@ export const archiveDocument = createAction({ toast.success( documents.length === 1 ? t("Document archived") - : t("{{ count }} documents archived", { count: succeeded }) + : t("{{ count }} document archived", { count: succeeded }) ); } }} @@ -1508,7 +1500,7 @@ export const restoreDocument = createAction({ ? t("{{ documentName }} restored", { documentName: capitalize(documents[0].noun), }) - : t("{{ count }} documents restored", { count: succeeded }) + : t("{{ count }} document restored", { count: succeeded }) ), }); @@ -1545,7 +1537,7 @@ export const restoreDocumentToCollection = createActionWithChildren({ const actions = collections.orderedData.map((collection) => { const can = policies.abilities(collection.id); return createAction({ - name: collection.name, + name: collection.displayName, section: ActiveDocumentSection, icon: <CollectionIcon collection={collection} />, visible: can.createDocument, @@ -1618,7 +1610,7 @@ export const deleteDocument = createAction({ ); if (succeeded) { toast.success( - t("{{ count }} documents moved to trash", { count: succeeded }) + t("{{ count }} document moved to trash", { count: succeeded }) ); } }} @@ -1824,12 +1816,9 @@ const headingPrefixNames: Record<HeadingPrefixStyle, (t: TFunction) => string> = const changeHeadingPrefixFactory = (style: HeadingPrefixStyle) => createAction({ name: ({ t }) => headingPrefixNames[style](t), - // The example is displayed in the shortcut slot of menu items, but must - // not be set on the command bar action where shortcuts are registered as - // key sequences. - shortcut: ({ isMenu }) => + badge: ({ isMenu }) => isMenu && headingPrefixExamples[style] - ? [headingPrefixExamples[style]] + ? headingPrefixExamples[style] : undefined, keywords: headingPrefixExamples[style], analyticsName: "Change heading numbering", 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/revisions.tsx b/app/actions/definitions/revisions.tsx index 98b14fd1c8..4d846a12d0 100644 --- a/app/actions/definitions/revisions.tsx +++ b/app/actions/definitions/revisions.tsx @@ -80,7 +80,7 @@ export const restoreRevision = createInternalLinkAction({ } return { - pathname: document.url, + pathname: document.path, state: { restore: true, revisionId }, }; }, diff --git a/app/actions/definitions/shares.tsx b/app/actions/definitions/shares.tsx index de89f4d00c..8c3503e2ad 100644 --- a/app/actions/definitions/shares.tsx +++ b/app/actions/definitions/shares.tsx @@ -1,15 +1,23 @@ import copy from "copy-to-clipboard"; +import { addDays, endOfDay } from "date-fns"; import Share from "~/models/Share"; -import { createAction, createInternalLinkAction } from ".."; +import { + ActionSeparator, + createAction, + createActionWithChildren, + createInternalLinkAction, +} from ".."; import { everyActiveModel, performBatchOnActiveModels, } from "~/actions/definitions/common"; -import { ArrowIcon, CopyIcon, TrashIcon } from "outline-icons"; +import { ArrowIcon, CalendarIcon, CopyIcon, TrashIcon } from "outline-icons"; import { ShareSection } from "../sections"; import type { ActionContext } from "~/types"; import env from "~/env"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; +import { ShareExpiryDialog } from "~/components/Sharing/components/ShareExpiryDialog"; export const copyShareUrl = createAction({ name: ({ t }) => t("Copy link"), @@ -51,6 +59,70 @@ export const goToShareSource = createInternalLinkAction({ }, }); +export const customShareExpiry = createAction({ + name: ({ t }) => `${t("Custom")}…`, + analyticsName: "Set custom share expiry", + section: ShareSection, + perform: (context) => { + const share = singleActiveShare(context); + if (!share) { + return; + } + + const { dialogs } = context.stores; + dialogs.openModal({ + title: context.t("Set expiry"), + width: "600px", + content: ( + <ShareExpiryDialog share={share} onSubmit={dialogs.closeAllModals} /> + ), + }); + }, +}); + +export const removeShareExpiry = createAction({ + name: ({ t }) => t("Remove expiry"), + analyticsName: "Remove share expiry", + section: ShareSection, + visible: (context) => !!singleActiveShare(context)?.expiresAt, + perform: (context) => + saveShareExpiry(context, null, context.t("Expiry removed")), +}); + +export const setShareExpiry = createActionWithChildren({ + name: ({ t }) => t("Set expiry"), + analyticsName: "Set share expiry", + section: ShareSection, + icon: <CalendarIcon />, + visible: (context) => { + const { auth, policies } = context.stores; + const share = singleActiveShare(context); + return ( + !!share && + !!policies.abilities(auth.team?.id || "").share && + !!policies.abilities(share.id).update + ); + }, + children: [ + ...[1, 7, 30].map((days) => + createAction({ + name: ({ t }) => t("{{ count }} days", { count: days }), + analyticsName: "Set share expiry preset", + section: ShareSection, + perform: (context) => + saveShareExpiry( + context, + endOfDay(addDays(new Date(), days)), + context.t("Expiry updated") + ), + }) + ), + customShareExpiry, + ActionSeparator, + removeShareExpiry, + ], +}); + export const revokeShare = createAction({ name: ({ t }) => t("Revoke link"), analyticsName: "Revoke share", @@ -86,6 +158,24 @@ export const revokeShare = createAction({ }, }); +const saveShareExpiry = async ( + context: ActionContext, + date: Date | null, + message: string +) => { + const share = singleActiveShare(context); + if (!share) { + return; + } + + try { + await share.save({ expiresAt: date ? date.toISOString() : null }); + toast.success(message); + } catch (err) { + toast.error(errToString(err)); + } +}; + const singleActiveShare = ({ getActiveModels }: ActionContext) => { const shares = getActiveModels(Share); return shares.length === 1 ? shares[0] : undefined; diff --git a/app/actions/definitions/teams.tsx b/app/actions/definitions/teams.tsx index 4727228087..25b02851ee 100644 --- a/app/actions/definitions/teams.tsx +++ b/app/actions/definitions/teams.tsx @@ -15,11 +15,18 @@ import Desktop from "~/utils/Desktop"; import { dialogActionFactory } from "./common"; import { TeamSection } from "../sections"; +/** + * Builds workspace links, indicating which workspaces require login. + * + * @param context the stores containing available workspaces. + * @returns the workspace switching actions. + */ export const switchTeamsList = ({ stores }: { stores: RootStore }) => stores.auth.availableTeams?.map<ExternalLinkAction>((session) => createExternalLinkAction({ id: `switch-${session.id}`, name: session.name, + badge: ({ t }) => (session.isSignedIn ? undefined : t("Logged out")), analyticsName: "Switch workspace", section: TeamSection, keywords: "change switch workspace organization team", @@ -78,8 +85,8 @@ export const createTeam = createAction({ export const desktopLoginTeam = dialogActionFactory({ analyticsName: "Login to workspace", section: TeamSection, - name: (t) => t("Login to workspace"), - title: (t) => t("Login to workspace"), + name: (t) => t("Log in to workspace"), + title: (t) => t("Log in to workspace"), content: () => <LoginDialog />, icon: <ArrowIcon />, keywords: "change switch workspace organization team", diff --git a/app/actions/definitions/templates.tsx b/app/actions/definitions/templates.tsx index af157ae117..8297cc6e84 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..d216b6f741 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, - path: document.url, + title: document.displayTitle, + path: document.path, } : undefined, collection: collection - ? { id: collection.id, name: collection.name, path: collection.path } + ? { + id: collection.id, + name: collection.displayName, + path: collection.path, + } : undefined, }); }, @@ -65,8 +69,8 @@ export const searchWorkspace = createAction({ return JSON.stringify( results.map((result) => ({ id: result.document.id, - title: result.document.titleWithDefault, - path: result.document.url, + title: result.document.displayTitle, + path: result.document.path, context: result.context, })) ); diff --git a/app/actions/index.ts b/app/actions/index.ts index 37cbcca3e7..63052e3255 100644 --- a/app/actions/index.ts +++ b/app/actions/index.ts @@ -152,6 +152,7 @@ export function actionToMenuItem( const visible = resolve<boolean>(action.visible, context) ?? true; const disabled = resolve<boolean>(action.disabled, context); const shortcut = resolve<string[] | undefined>(action.shortcut, context); + const badge = resolve<React.ReactNode>(action.badge, context); const icon = !!action.icon && action.iconInContextMenu !== false ? resolve<React.ReactNode>(action.icon, context) @@ -169,6 +170,7 @@ export function actionToMenuItem( selected: resolve<boolean>(action.selected, context), dangerous: action.dangerous, shortcut, + badge, onClick: () => performAction(action, context), }; @@ -181,6 +183,7 @@ export function actionToMenuItem( visible, disabled, shortcut, + badge, to, }; } @@ -193,6 +196,7 @@ export function actionToMenuItem( visible, disabled, shortcut, + badge, href: action.target ? { url: action.url, target: action.target } : action.url, 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 37884e206a..583bb58385 100644 --- a/app/components/ActionButton.tsx +++ b/app/components/ActionButton.tsx @@ -1,4 +1,3 @@ -/* oxlint-disable react/prop-types */ import { observer } from "mobx-react"; import * as React from "react"; import type { Props as TooltipProps } from "~/components/Tooltip"; @@ -16,6 +15,8 @@ export type Props = React.HTMLAttributes<HTMLButtonElement> & { action?: Exclude<ActionVariant, ActionWithChildren>; /** If tooltip props are provided the button will be wrapped in a tooltip */ tooltip?: Omit<TooltipProps, "children">; + /** The button type, defaults to "button" */ + type?: "button" | "submit" | "reset"; }; /** @@ -26,6 +27,7 @@ function ActionButton({ tooltip, hideOnActionDisabled, ref, + type = "button", ...rest }: Props & { ref?: React.Ref<HTMLButtonElement> }) { const actionContext = useActionContext({ @@ -34,7 +36,8 @@ function ActionButton({ const [executing, setExecuting] = React.useState(false); if (!actionContext || !action) { - return <button {...rest} ref={ref} />; + // oxlint-disable-next-line react/button-has-type -- type defaults to "button" + return <button {...rest} type={type} ref={ref} />; } const actionIsDisabled = @@ -55,6 +58,8 @@ function ActionButton({ const button = ( <button {...rest} + // oxlint-disable-next-line react/button-has-type -- type defaults to "button" + type={type} aria-label={typeof label === "string" ? label : undefined} disabled={disabled || executing} ref={ref} diff --git a/app/components/Actions.ts b/app/components/Actions.ts index aff0f693c8..7e1e637dc1 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 { breakpoint } from "@shared/styles/breakpoint"; +import { MOBILE_TOUCH_TARGET } from "@shared/constants"; import { s } from "@shared/styles"; import Flex from "~/components/Flex"; @@ -10,6 +11,10 @@ export const Action = styled(Flex)` font-size: 15px; flex-shrink: 0; + ${breakpoint("mobile", "tablet")` + height: ${MOBILE_TOUCH_TARGET}px; + `}; + &:empty { display: none; } 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/AuthenticatedLayout.tsx b/app/components/AuthenticatedLayout.tsx index c7aead0c45..75afb732a4 100644 --- a/app/components/AuthenticatedLayout.tsx +++ b/app/components/AuthenticatedLayout.tsx @@ -1,8 +1,6 @@ import { observer } from "mobx-react"; import * as React from "react"; -import { DndProvider } from "react-dnd"; -import { useLocation } from "react-router-dom"; -import { EditorAwareHTML5Backend } from "~/components/EditorAwareHTML5Backend"; +import { DragAndDropProvider } from "~/components/DragAndDrop"; import ErrorSuspended from "~/scenes/Errors/ErrorSuspended"; import Layout from "~/components/Layout"; import RegisterKeyDown from "~/components/RegisterKeyDown"; @@ -14,6 +12,7 @@ import useKeyDown from "~/hooks/useKeyDown"; import useWebMCPActions from "~/hooks/useWebMCPActions"; import { usePostLoginPath } from "~/hooks/useLastVisitedPath"; import usePolicy from "~/hooks/usePolicy"; +import { useLocationSelector } from "~/hooks/useLocationSelector"; import useStores from "~/hooks/useStores"; import Logger from "~/utils/Logger"; import history from "~/utils/history"; @@ -40,8 +39,12 @@ type Props = { const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => { const { ui, auth } = useStores(); - const location = useLocation(); - const layoutRef = React.useRef<HTMLDivElement>(null); + const isSettings = useLocationSelector((location) => + location.pathname.startsWith(settingsPath()) + ); + // State rather than a ref, so that portals receive the element once mounted. + const [layoutElement, setLayoutElement] = + React.useState<HTMLDivElement | null>(null); const canCollection = usePolicy(ui.activeCollectionId); const team = useCurrentTeam(); const [spendPostLoginPath] = usePostLoginPath(); @@ -87,8 +90,6 @@ const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => { return <ErrorSuspended />; } - const isSettings = location.pathname.startsWith(settingsPath()); - const sidebar = ( <Fade> <React.Suspense fallback={null}> @@ -103,13 +104,13 @@ const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => { return ( <DocumentContextProvider> <RightSidebarProvider> - <PortalContext.Provider value={layoutRef.current}> - <DndProvider backend={EditorAwareHTML5Backend}> + <PortalContext.Provider value={layoutElement}> + <DragAndDropProvider> <Layout title={team.name} sidebar={sidebar} sidebarCanCollapse={!isSettings} - ref={layoutRef} + ref={setLayoutElement} > <RegisterKeyDown trigger="n" handler={goToNewDocument} /> <RegisterKeyDown trigger="t" handler={goToSearch} /> @@ -118,7 +119,7 @@ const AuthenticatedLayout: React.FC<Props> = ({ children }: Props) => { <CommandBar /> <NotificationBadge /> </Layout> - </DndProvider> + </DragAndDropProvider> </PortalContext.Provider> </RightSidebarProvider> </DocumentContextProvider> 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 4a4b98aeb7..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"; @@ -75,13 +75,20 @@ function Breadcrumb({ } const item = actionToMenuItem(action, actionContext) as MenuInternalLink; + const highlight = !!highlightFirstItem && index === 0; + + // Items without a destination are shown as plain text. + if (!item.to) { + return ( + <StaticItem $highlight={highlight}> + {item.icon} + <Title>{item.title} + + ); + } return ( - + {item.icon} {item.title} @@ -110,7 +117,7 @@ const Slash = styled(GoToIcon)` fill: ${s("divider")}; `; -const Item = styled(Link)<{ $highlight: boolean }>` +const itemStyles = css<{ $highlight: boolean }>` ${undraggableOnDesktop()} display: flex; @@ -118,7 +125,6 @@ const Item = styled(Link)<{ $highlight: boolean }>` gap: 4px; flex-shrink: 1; min-width: 0; - cursor: var(--pointer); color: ${s("text")}; font-size: 15px; height: 32px; @@ -131,6 +137,11 @@ const Item = styled(Link)<{ $highlight: boolean }>` margin-inline-start: 0; } max-width: 460px; +`; + +const Item = styled(Link)<{ $highlight: boolean }>` + ${itemStyles} + cursor: var(--pointer); transition: background 100ms ease-in-out; &:hover, @@ -140,6 +151,11 @@ const Item = styled(Link)<{ $highlight: boolean }>` } `; +const StaticItem = styled.span<{ $highlight: boolean }>` + ${itemStyles} + cursor: default; +`; + const Title = styled.span` ${ellipsis()} min-width: 0; diff --git a/app/components/Button.tsx b/app/components/Button.tsx index 6bb3d8c9ad..524aa00672 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 "@shared/styles/breakpoint"; +import { MOBILE_TOUCH_TARGET } from "@shared/constants"; import { s } from "@shared/styles"; import type { Props as ActionButtonProps } from "~/components/ActionButton"; import ActionButton from "~/components/ActionButton"; @@ -36,6 +38,12 @@ const RealButton = styled(ActionButton)` 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 & { @@ -192,6 +214,7 @@ function Button( $danger={danger} $fullwidth={fullwidth} $borderOnHover={borderOnHover} + data-variant={danger ? "danger" : neutral ? "neutral" : "primary"} {...rest} > diff --git a/app/components/CenteredContent.tsx b/app/components/CenteredContent.tsx index 7281629634..22efd72fbe 100644 --- a/app/components/CenteredContent.tsx +++ b/app/components/CenteredContent.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; type Props = { diff --git a/app/components/CircularProgressBar.tsx b/app/components/CircularProgressBar.tsx index 9fc5aeb32a..04a143772e 100644 --- a/app/components/CircularProgressBar.tsx +++ b/app/components/CircularProgressBar.tsx @@ -17,12 +17,12 @@ const Circle = ({ }) => { const radius = offset * 0.7; const circumference = 2 * Math.PI * radius; - let strokePercentage; + let strokeDashoffset = 0; - if (percentage) { + if (percentage !== undefined) { // because the circle is so small, anything greater than 85% appears like 100% - percentage = percentage > 85 && percentage < 100 ? 85 : percentage; - strokePercentage = ((100 - percentage) * circumference) / 100; + const visible = percentage > 85 && percentage < 100 ? 85 : percentage; + strokeDashoffset = ((100 - visible) * circumference) / 100; } return ( @@ -31,13 +31,14 @@ const Circle = ({ cx={offset} cy={offset} fill="none" - stroke={strokePercentage !== circumference ? color : ""} + stroke={color} strokeWidth={2.5} strokeDasharray={circumference} - strokeDashoffset={percentage ? strokePercentage : 0} strokeLinecap="round" style={{ - transition: "stroke-dashoffset 0.6s ease 0s", + strokeDashoffset: `${strokeDashoffset}px`, + opacity: percentage === 0 ? 0 : 1, + transition: "stroke-dashoffset 0.6s ease, opacity 0.6s ease", }} /> ); @@ -76,13 +77,7 @@ const CircularProgressBar = ({ > - {percentage > 0 && ( - - )} + ); 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..8a1c6ed57b 100644 --- a/app/components/CollectionDeleteDialog.tsx +++ b/app/components/CollectionDeleteDialog.tsx @@ -42,9 +42,9 @@ function CollectionDeleteDialog({ collection, onSubmit }: Props) { <> , @@ -56,7 +56,7 @@ function CollectionDeleteDialog({ collection, onSubmit }: Props) { , diff --git a/app/components/CommandBar/CommandBar.tsx b/app/components/CommandBar/CommandBar.tsx index 9fdf606e9c..39f4b66608 100644 --- a/app/components/CommandBar/CommandBar.tsx +++ b/app/components/CommandBar/CommandBar.tsx @@ -3,7 +3,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { depths, s } from "@shared/styles"; import { Portal } from "~/components/Portal"; import SearchActions from "~/components/SearchActions"; 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 fe09861a77..8f41e847e0 100644 --- a/app/components/CommandBar/SharedCommandBar.tsx +++ b/app/components/CommandBar/SharedCommandBar.tsx @@ -3,7 +3,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { depths, s } from "@shared/styles"; import { Portal } from "~/components/Portal"; import CommandBarResults from "./CommandBarResults"; diff --git a/app/components/CommandBar/useRecentDocumentActions.tsx b/app/components/CommandBar/useRecentDocumentActions.tsx index 2d5545286c..f9fa9a33ad 100644 --- a/app/components/CommandBar/useRecentDocumentActions.tsx +++ b/app/components/CommandBar/useRecentDocumentActions.tsx @@ -1,13 +1,13 @@ -import { DocumentIcon } from "outline-icons"; -import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import Icon from "@shared/components/Icon"; import { createInternalLinkAction } from "~/actions"; import { RecentSection } from "~/actions/sections"; import { documentBreadcrumbText } from "~/components/DocumentBreadcrumb"; +import { useComputed } from "~/hooks/useComputed"; import useStores from "~/hooks/useStores"; import type Document from "~/models/Document"; import { documentPath } from "~/utils/routeHelpers"; +import { DocumentIcon } from "~/components/Icons/DocumentIcon"; /** The number of documents listed under "Recently viewed" in the command bar. */ export const recentDocumentCount = 6; @@ -35,7 +35,7 @@ const useRecentDocumentActions = (count = recentDocumentCount) => { const { documents, ui } = useStores(); const { t } = useTranslation(); - return useMemo( + return useComputed( () => recentDocuments( documents.recentlyViewed, @@ -43,7 +43,7 @@ const useRecentDocumentActions = (count = recentDocumentCount) => { count ).map((item) => createInternalLinkAction({ - name: item.titleWithDefault, + name: item.displayTitle, analyticsName: "Recently viewed document", section: RecentSection, visible: ({ isMCP }) => !isMCP, @@ -55,12 +55,12 @@ const useRecentDocumentActions = (count = recentDocumentCount) => { color={item.color ?? undefined} /> ) : ( - + ), to: documentPath(item), }) ), - [count, ui.activeDocumentId, documents.recentlyViewed, t] + [count, documents, ui, t] ); }; diff --git a/app/components/CommandBar/useSearchIndex.ts b/app/components/CommandBar/useSearchIndex.ts index d81900984c..ae33524e59 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, - url: doc.url, - text: doc.data ? getPlainText(doc) : stripHighlightTags(context), + title: doc.displayTitle, + url: doc.path, + text: content ? content.text : stripHighlightTags(context), + headings: content?.headings, icon: doc.icon, color: doc.color, isArchived: doc.isArchived, @@ -110,14 +125,14 @@ export function useSearchIndex(query: string): UseSearchIndex { const reset = useCallback(() => { index.clear(); - plainTextCache.clear(); + contentCache.clear(); setVersion((v) => v + 1); }, [index]); const results = useMemo( () => (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 8ce09d2d81..8aa6f09716 100644 --- a/app/components/CommandBar/useTemplatesAction.tsx +++ b/app/components/CommandBar/useTemplatesAction.tsx @@ -28,7 +28,7 @@ const useTemplatesAction = () => { () => 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 dd714bc539..fa066c4d6a 100644 --- a/app/components/ContentEditable.tsx +++ b/app/components/ContentEditable.tsx @@ -1,8 +1,8 @@ -import isPrintableKeyEvent from "is-printable-key-event"; import * as React from "react"; import { useMergeRefs } from "react-merge-refs"; import styled from "styled-components"; import { s } from "@shared/styles"; +import { isPrintableKeyEvent } from "@shared/utils/keyboard"; import { TextHelper } from "@shared/utils/TextHelper"; import useOnScreen from "~/hooks/useOnScreen"; diff --git a/app/components/DefaultCollectionInputSelect.tsx b/app/components/DefaultCollectionInputSelect.tsx index e87b5d814c..f6afff02b3 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(); @@ -40,7 +41,7 @@ const DefaultCollectionInputSelect = observer( }); } catch (error) { toast.error( - t("Collections could not be loaded, please reload the app") + t("Collections could not be loaded – please reload the app") ); setFetchError(toError(error)); } finally { @@ -55,36 +56,20 @@ const DefaultCollectionInputSelect = observer( return null; } - const isDark = ui.resolvedTheme === "dark"; - // Eagerly resolve collection icon properties within this observer context // to avoid MobX warnings when Radix Select clones elements for the trigger. const options: Option[] = collections.nonPrivate.reduce( (acc, collection) => { const collectionIcon = collection.icon; - const rawColor = collection.color ?? colorPalette[0]; + const color = contrastColor(collection.color ?? colorPalette[0]); let icon: React.ReactElement; if (!collectionIcon || collectionIcon === "collection") { - const color = - isDark && rawColor !== "currentColor" - ? getLuminance(rawColor) > 0.09 - ? rawColor - : "currentColor" - : rawColor; const Component = collection.isPrivate ? PrivateCollectionIcon : CollectionIconComponent; icon = ; } 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 = ( ) : ( - + ); return ( @@ -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 ec0dc5aa90..b943401b32 100644 --- a/app/components/Dialogs.tsx +++ b/app/components/Dialogs.tsx @@ -1,5 +1,6 @@ import { observer } from "mobx-react"; -import { Suspense } from "react"; +import { Suspense, useEffect } from "react"; +import { useHistory } from "react-router-dom"; import useStores from "~/hooks/useStores"; import lazyWithRetry from "@shared/utils/lazyWithRetry"; import { DialogProvider } from "./DialogContext"; @@ -9,9 +10,24 @@ const Modal = lazyWithRetry(() => import("~/components/Modal")); function Dialogs() { const { dialogs } = useStores(); + const history = useHistory(); const { guide, modalStack } = dialogs; const modals = [...modalStack]; + // Close open modals when navigating to another page. + useEffect(() => { + let pathname = history.location.pathname; + + return history.listen((location) => { + if (location.pathname === pathname) { + return; + } + pathname = location.pathname; + dialogs.modalStack.forEach((modal) => modal.onClose?.()); + dialogs.closeAllModals(); + }); + }, [dialogs, history]); + return ( diff --git a/app/components/DocumentBreadcrumb.tsx b/app/components/DocumentBreadcrumb.tsx index 9a9922440f..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. @@ -139,15 +139,17 @@ function DocumentBreadcrumb({ ) : undefined, section: ActiveDocumentSection, visible: !!(collection && can.readDocument), - to: collection - ? { - pathname: collection.path, - state: { sidebarContext }, - } - : "", + // A personal collection has no page to link to. + to: + collection && !collection.isPersonal + ? { + pathname: collection.path, + state: { sidebarContext }, + } + : "", }), createInternalLinkAction({ - name: t("Deleted Collection"), + name: t("Deleted collection"), section: ActiveDocumentSection, visible: document.isCollectionDeleted, to: "", @@ -262,7 +264,7 @@ const CollectionName = observer(function CollectionName_({ {icon} - {collection.name} + {collection.displayName} diff --git a/app/components/DocumentCard.tsx b/app/components/DocumentCard.tsx index 245dffb1c5..9b8f004d45 100644 --- a/app/components/DocumentCard.tsx +++ b/app/components/DocumentCard.tsx @@ -3,7 +3,7 @@ import { CSS } from "@dnd-kit/utilities"; import { subDays } from "date-fns"; import { m } from "framer-motion"; import { observer } from "mobx-react"; -import { CloseIcon, DocumentIcon, ClockIcon } from "outline-icons"; +import { CloseIcon, ClockIcon } from "outline-icons"; import { useRef, useCallback, Suspense } from "react"; import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; @@ -21,6 +21,7 @@ import Time from "~/components/Time"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import { DocumentContextMenu } from "~/menus/DocumentContextMenu"; +import { DocumentIcon } from "~/components/Icons/DocumentIcon"; import CollectionIcon from "./Icons/CollectionIcon"; import Text from "./Text"; import Tooltip from "./Tooltip"; @@ -127,7 +128,7 @@ function DocumentCard(props: Props) { to={{ pathname: document.path, state: { - title: document.titleWithDefault, + title: document.displayTitle, }, }} > @@ -162,15 +163,15 @@ function DocumentCard(props: Props) { pinnedToHome ? ( ) : ( - + )} )}
{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..deb2e72536 100644 --- a/app/components/DocumentChip.tsx +++ b/app/components/DocumentChip.tsx @@ -1,5 +1,5 @@ import { observer } from "mobx-react"; -import { CloseIcon, DocumentIcon } from "outline-icons"; +import { CloseIcon } from "outline-icons"; import { useCallback } from "react"; import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; @@ -14,6 +14,7 @@ import NudeButton from "~/components/NudeButton"; import Tooltip from "~/components/Tooltip"; import usePolicy from "~/hooks/usePolicy"; import { DocumentContextMenu } from "~/menus/DocumentContextMenu"; +import { DocumentIcon } from "~/components/Icons/DocumentIcon"; type Props = { /** The document to display */ @@ -34,7 +35,7 @@ export const DocumentChip = observer(function DocumentChip_({ const { icon, color } = document; const canPin = usePolicy(pin); const canDocument = usePolicy(document); - const title = document.titleWithDefault; + const title = document.displayTitle; const isEmoji = determineIconType(icon) === IconType.Emoji; // Pins in a collection are governed by the document policy, pins on home by @@ -68,7 +69,7 @@ export const DocumentChip = observer(function DocumentChip_({ initial={document.initial} /> ) : ( - + )} {isEmoji ? title.replace(icon!, "") : title} {pin && canUnpin && ( diff --git a/app/components/DocumentExplorer/DocumentCopy.tsx b/app/components/DocumentExplorer/DocumentCopy.tsx index fe36f738e3..8df50c05cd 100644 --- a/app/components/DocumentExplorer/DocumentCopy.tsx +++ b/app/components/DocumentExplorer/DocumentCopy.tsx @@ -59,7 +59,7 @@ function DocumentCopy({ document, onSubmit }: Props) { toast.success(t("Document copied")); onSubmit(result); } catch (_err) { - toast.error(t("Couldn’t copy the document, try again?")); + toast.error(t("Couldn’t copy the document. Try again?")); } finally { setCopying(false); } diff --git a/app/components/DocumentExplorer/DocumentExplorer.tsx b/app/components/DocumentExplorer/DocumentExplorer.tsx index 11719aa3a2..454c23eb01 100644 --- a/app/components/DocumentExplorer/DocumentExplorer.tsx +++ b/app/components/DocumentExplorer/DocumentExplorer.tsx @@ -3,19 +3,19 @@ import { concat, difference, fill, - filter, flatten, includes, map, + union, } from "es-toolkit/compat"; import { observer } from "mobx-react"; import { StarredIcon, DocumentIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; -import AutoSizer from "react-virtualized-auto-sizer"; -import { FixedSizeList as List } from "react-window"; +import type { ListImperativeAPI, RowComponentProps } from "react-window"; +import { List } from "react-window"; import styled, { useTheme } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import Icon from "@shared/components/Icon"; import type { NavigationNode } from "@shared/types"; import { isModKey } from "@shared/utils/keyboard"; @@ -40,36 +40,31 @@ type Props = { defaultValue?: string; /** Whether to show child documents */ showDocuments?: boolean; + /** Overrides the icon of a node, return undefined to keep the default. */ + renderIcon?: (node: NavigationNode) => React.ReactNode; }; const VERTICAL_PADDING = 6; const HORIZONTAL_PADDING = 24; -function innerElementType({ - style, - ref, - ...rest -}: React.HTMLAttributes & { - ref?: React.Ref; -}) { - return ( -
- ); +const expandableDescendantIds = (node: NavigationNode) => + descendants(node) + .filter((des) => des.children.length > 0) + .map((des) => des.id); + +interface RowProps { + data: NavigationNode[]; } +const rowKey = (index: number, { data }: RowProps) => data[index].id; + function DocumentExplorer({ onSubmit, onSelect, items, defaultValue, showDocuments, + renderIcon, }: Props) { const isMobile = useMobile(); const { collections, documents } = useStores(); @@ -103,6 +98,10 @@ function DocumentExplorer({ } return []; }); + // Nodes expanded with alt-click, whose descendants stay expanded as they load. + const [deepExpandedNodes, setDeepExpandedNodes] = React.useState( + [] + ); const [itemRefs, setItemRefs] = React.useState< React.RefObject[] @@ -111,7 +110,7 @@ function DocumentExplorer({ const inputSearchRef = React.useRef( null ); - const listRef = React.useRef>(null); + const listRef = React.useRef(null); const searchIndex = React.useMemo( () => @@ -125,6 +124,7 @@ function DocumentExplorer({ if (searchTerm) { selectNode(null); setExpandedNodes([]); + setDeepExpandedNodes([]); } setActiveNode(0); }, [searchTerm]); @@ -160,10 +160,13 @@ function DocumentExplorer({ if (defaultValue && selectedNode && listRef) { const index = nodes.findIndex((node) => node.id === selectedNode.id); if (index > 0) { - setTimeout(() => listRef.current?.scrollToItem(index, "center"), 50); + setTimeout( + () => listRef.current?.scrollToRow({ index, align: "center" }), + 50 + ); } } - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [defaultValue]); const baseDepth = nodes.reduce( (min, node) => (node.depth ? Math.min(min, node.depth) : min), @@ -173,7 +176,7 @@ function DocumentExplorer({ (baseDepth === Infinity ? 0 : baseDepth) + (showDocuments ? 0 : 1); const scrollNodeIntoView = React.useCallback((node: number) => { - listRef.current?.scrollToItem(node, "smart"); + listRef.current?.scrollToRow({ index: node, align: "smart" }); }, []); const handleSearch = (ev: React.ChangeEvent) => { @@ -182,38 +185,50 @@ function DocumentExplorer({ const isExpanded = (node: number) => includes(expandedNodes, nodes[node].id); - const preserveScrollOffset = (itemCount: number) => { - if (listRef.current) { - const { height, itemSize } = listRef.current.props; - const { scrollOffset } = listRef.current.state as { - scrollOffset: number; - }; - const itemsHeight = itemCount * itemSize; - const offset = itemsHeight < Number(height) ? 0 : scrollOffset; - setTimeout(() => listRef.current?.scrollTo(offset), 0); - } - }; - const collapse = (node: number) => { const descendantIds = descendants(nodes[node]).map((des) => des.id); + const ancestorIds = ancestors(nodes[node]).map((anc) => anc.id); setExpandedNodes( difference(expandedNodes, [...descendantIds, nodes[node].id]) ); - - // remove children - const newNodes = filter(nodes, (n) => !includes(descendantIds, n.id)); - preserveScrollOffset(newNodes.length); + setDeepExpandedNodes( + difference(deepExpandedNodes, [ + ...ancestorIds, + ...descendantIds, + nodes[node].id, + ]) + ); }; - const expand = (node: number) => { - setExpandedNodes(concat(expandedNodes, nodes[node].id)); - - // add children - const newNodes = nodes.slice(); - newNodes.splice(node + 1, 0, ...descendants(nodes[node], 1)); - preserveScrollOffset(newNodes.length); + const expand = (node: number, deep = false) => { + if (deep) { + setExpandedNodes( + union(expandedNodes, [ + nodes[node].id, + ...expandableDescendantIds(nodes[node]), + ]) + ); + setDeepExpandedNodes(union(deepExpandedNodes, [nodes[node].id])); + } else { + setExpandedNodes(concat(expandedNodes, nodes[node].id)); + } }; + // Expand descendants of alt-clicked nodes that load after the click. + React.useEffect(() => { + if (!deepExpandedNodes.length) { + return; + } + const ids = flatten(items.map(flattenTree)) + .filter((item) => deepExpandedNodes.includes(item.id)) + .flatMap(expandableDescendantIds); + + setExpandedNodes((prev) => { + const missing = difference(ids, prev); + return missing.length ? concat(prev, missing) : prev; + }); + }, [items, deepExpandedNodes]); + React.useEffect(() => { collections.orderedData .filter( @@ -238,14 +253,14 @@ function DocumentExplorer({ nodes[node].children.length > 0 || (showDocuments !== false && nodes[node].type === "collection"); - const toggleCollapse = (node: number) => { + const toggleCollapse = (node: number, deep = false) => { if (!hasChildren(node)) { return; } if (isExpanded(node)) { collapse(node); } else { - expand(node); + expand(node, deep); } }; @@ -265,15 +280,7 @@ function DocumentExplorer({ }; const ListItem = observer( - ({ - index, - data, - style, - }: { - index: number; - data: NavigationNode[]; - style: React.CSSProperties; - }) => { + ({ index, data, style }: RowComponentProps) => { const node = data[index]; const isCollection = node.type === "collection"; let renderedIcon, @@ -309,15 +316,17 @@ function DocumentExplorer({ .join(" / "); } + renderedIcon = renderIcon?.(node) ?? renderedIcon; + return deferredSearchTerm ? ( setActiveNode(index)} onClick={() => selectNode(nodes[index])} @@ -330,16 +339,16 @@ function DocumentExplorer({ setActiveNode(index)} onClick={() => selectNode(nodes[index])} onDoubleClick={() => submitNode(index)} onDisclosureClick={(ev) => { ev.stopPropagation(); - toggleCollapse(index); + toggleCollapse(index, ev.altKey); }} selected={isSelected(index)} active={activeNode === index} @@ -421,24 +430,15 @@ function DocumentExplorer({ /> {nodes.length ? ( - - {({ width, height }: { width: number; height: number }) => ( - - results[index].id} - > - {ListItem} - - - )} - + ) : ( @@ -465,6 +465,11 @@ const ListSearch = styled(InputSearch).attrs({ round: true })` padding-right: 24px; `; +// Rows are offset by the top padding, so the bottom needs room for both. +const StyledList = styled(List)` + padding-bottom: ${VERTICAL_PADDING * 2}px; +`; + const ListContainer = styled.div` height: 65vh; diff --git a/app/components/DocumentExplorer/DocumentExplorerNode.tsx b/app/components/DocumentExplorer/DocumentExplorerNode.tsx index 9dfc313e8d..9cebd9a7d0 100644 --- a/app/components/DocumentExplorer/DocumentExplorerNode.tsx +++ b/app/components/DocumentExplorer/DocumentExplorerNode.tsx @@ -1,8 +1,9 @@ import { observer } from "mobx-react"; +import { CheckmarkIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { s, ellipsis } from "@shared/styles"; import Flex from "~/components/Flex"; import Disclosure from "~/components/Sidebar/components/Disclosure"; @@ -79,10 +80,15 @@ function DocumentExplorerNode({ {icon} {title || t("Untitled")} + {selected && } ); } +export const SelectedIcon = styled(CheckmarkIcon)` + margin-left: auto; +`; + const Title = styled(Text)` ${ellipsis()} margin: 0 4px 0 4px; diff --git a/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx b/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx index 38d5449080..ad751487b1 100644 --- a/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx +++ b/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx @@ -3,7 +3,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import { ellipsis } from "@shared/styles"; -import { Node as SearchResult } from "./DocumentExplorerNode"; +import { Node as SearchResult, SelectedIcon } from "./DocumentExplorerNode"; import Flex from "~/components/Flex"; import Text from "~/components/Text"; @@ -51,6 +51,7 @@ function DocumentExplorerSearchResult({ {path} + {selected && } ); } diff --git a/app/components/DocumentExplorer/DocumentMove.tsx b/app/components/DocumentExplorer/DocumentMove.tsx index 80d9640a47..29c436c3a7 100644 --- a/app/components/DocumentExplorer/DocumentMove.tsx +++ b/app/components/DocumentExplorer/DocumentMove.tsx @@ -1,9 +1,10 @@ import { observer } from "mobx-react"; -import { useState, useMemo } from "react"; +import { useEffect, useState, useMemo } from "react"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; import type { NavigationNode } from "@shared/types"; -import { descendants, flattenTree } from "@shared/utils/tree"; +import { ancestors, descendants, flattenTree } from "@shared/utils/tree"; +import { performBatch } from "~/actions/definitions/common"; import type Document from "~/models/Document"; import Button from "~/components/Button"; import Text from "~/components/Text"; @@ -13,39 +14,74 @@ import { FlexContainer, Footer } from "./Components"; import DocumentExplorer from "./DocumentExplorer"; type Props = { - document: Document; + /** The documents to move. */ + documents: Document[]; }; -function DocumentMove({ document }: Props) { - const { dialogs, policies } = useStores(); +function DocumentMove({ documents }: Props) { + const { collections, dialogs, policies } = useStores(); const { t } = useTranslation(); const collectionTrees = useCollectionTrees(); const [moving, setMoving] = useState(false); const [selectedPath, selectPath] = useState(null); + const [treesFailed, setTreesFailed] = useState(false); - const items = useMemo(() => { - // Collect the IDs of the document itself and all of its descendants so they - // can be excluded from the move targets (moving to self or a descendant - // would create a cycle; moving to the exact same location is a no-op). + const sourceCollectionIds = useMemo( + () => + Array.from( + new Set( + documents + .map((document) => document.collectionId) + .filter((id): id is string => !!id) + ) + ), + [documents] + ); + + // The source trees are needed to exclude descendants and to keep nesting, + // so load any that have not been loaded yet. + useEffect(() => { + Promise.all( + sourceCollectionIds + .map((id) => collections.get(id)) + .filter((collection) => !!collection) + .map((collection) => collection.fetchDocuments()) + ).catch(() => setTreesFailed(true)); + }, [collections, sourceCollectionIds]); + + const isLoadingTrees = + !treesFailed && + sourceCollectionIds.some((id) => { + const collection = collections.get(id); + return !!collection && !collection.documents; + }); + + const { items, movableDocuments } = useMemo(() => { + const selectedIds = new Set(documents.map((document) => document.id)); const allNodes = collectionTrees.flatMap(flattenTree); - const sourceNode = allNodes.find((node) => node.id === document.id); - const excludedIds = new Set([document.id]); - if (sourceNode) { - descendants(sourceNode).forEach((n) => excludedIds.add(n.id)); + const nodesById = new Map(allNodes.map((node) => [node.id, node])); + + // Exclude the documents and all of their descendants from the move targets + // (moving to self or a descendant would create a cycle). + const excludedIds = new Set(selectedIds); + for (const id of selectedIds) { + const sourceNode = nodesById.get(id); + if (sourceNode) { + descendants(sourceNode).forEach((n) => excludedIds.add(n.id)); + } } - // Recursively filter out the document itself and its descendants. - // The document's current parent is intentionally kept so that siblings - // remain visible as valid move targets. - const filterSourceDocument = (node: NavigationNode): NavigationNode => ({ + // Recursively filter out the documents and their descendants. The current + // parents are intentionally kept so that siblings remain valid targets. + const filterSourceDocuments = (node: NavigationNode): NavigationNode => ({ ...node, children: node.children ?.filter((c) => !excludedIds.has(c.id)) - .map(filterSourceDocument), + .map(filterSourceDocuments), }); const nodes = collectionTrees - .map(filterSourceDocument) + .map(filterSourceDocuments) // Filter out collections that we don't have permission to create documents in. .filter((node) => node.collectionId @@ -53,10 +89,29 @@ function DocumentMove({ document }: Props) { : true ); - return nodes; - }, [policies, collectionTrees, document.id]); + // Documents nested under another selected document move along with it, + // so only the outermost documents are moved to keep the structure. They + // are moved in tree order to keep their relative order at the destination. + const positions = new Map(allNodes.map((node, index) => [node.id, index])); + const movable = documents + .filter( + (document) => + !ancestors(nodesById.get(document.id)).some((node) => + selectedIds.has(node.id) + ) + ) + .sort( + (a, b) => + (positions.get(a.id) ?? Infinity) - (positions.get(b.id) ?? Infinity) + ); + + return { items: nodes, movableDocuments: movable }; + }, [policies, collectionTrees, documents]); const move = async (path = selectedPath) => { + if (isLoadingTrees) { + return; + } if (!path) { toast.message(t("Select a location to move")); return; @@ -67,18 +122,28 @@ function DocumentMove({ document }: Props) { const { type, id: parentDocumentId } = path; const collectionId = path.collectionId as string; + const options = + type === "document" + ? { collectionId, parentDocumentId } + : { collectionId }; - if (type === "document") { - await document.move({ collectionId, parentDocumentId }); + if (movableDocuments.length === 1) { + await movableDocuments[0].move(options); + toast.success(t("Document moved")); } else { - await document.move({ collectionId }); + const succeeded = await performBatch(movableDocuments, (document) => + document.move(options) + ); + if (!succeeded) { + toast.error(t("Couldn’t move the document. Try again?")); + return; + } + toast.success(t("{{ count }} document moved", { count: succeeded })); } - toast.success(t("Document moved")); - dialogs.closeAllModals(); } catch (_err) { - toast.error(t("Couldn’t move the document, try again?")); + toast.error(t("Couldn’t move the document. Try again?")); } finally { setMoving(false); } @@ -103,7 +168,10 @@ function DocumentMove({ document }: Props) { t("Select a location to move") )} - diff --git a/app/components/DocumentExplorer/TemplateMove.tsx b/app/components/DocumentExplorer/TemplateMove.tsx index d16ca6941b..ff5afc9652 100644 --- a/app/components/DocumentExplorer/TemplateMove.tsx +++ b/app/components/DocumentExplorer/TemplateMove.tsx @@ -47,7 +47,7 @@ function TemplateMove({ template }: Props) { dialogs.closeAllModals(); } catch (_err) { - toast.error(t("Couldn’t move the template, try again?")); + toast.error(t("Couldn’t move the template. Try again?")); } }; diff --git a/app/components/DocumentListItem.tsx b/app/components/DocumentListItem.tsx index 76bd7fcd18..fccad897de 100644 --- a/app/components/DocumentListItem.tsx +++ b/app/components/DocumentListItem.tsx @@ -3,9 +3,9 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { mergeRefs } from "react-merge-refs"; import { Link } from "react-router-dom"; -import { CheckmarkIcon, DocumentIcon } from "outline-icons"; +import { CheckmarkIcon } from "outline-icons"; import styled, { css, useTheme } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import EventBoundary from "@shared/components/EventBoundary"; import Icon from "@shared/components/Icon"; import { s, hover } from "@shared/styles"; @@ -32,6 +32,7 @@ import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction"; import { ContextMenu } from "./Menu/ContextMenu"; import { useDocumentActiveModels } from "~/hooks/useDocumentActiveModels"; import { useRovingTabIndex } from "~/hooks/useRovingTabIndex"; +import { DocumentIcon } from "~/components/Icons/DocumentIcon"; type Props = { document: Document; @@ -170,7 +171,7 @@ function DocumentListItem(props: Props) { pathname: documentPath(document), search: highlight ? `?q=${encodeURIComponent(highlight)}` : undefined, state: { - title: document.titleWithDefault, + title: document.displayTitle, sidebarContext, }, }} @@ -204,7 +205,7 @@ function DocumentListItem(props: Props) { /> ) : ( )} @@ -213,7 +214,7 @@ function DocumentListItem(props: Props) { @@ -223,7 +224,7 @@ function DocumentListItem(props: Props) { {document.isDraft && showDraft && (isInteractive ? ( - <Tooltip content={t("Only visible to you")} placement="top"> + <Tooltip content={t("Only visible to you")}> <Badge>{t("Draft")}</Badge> </Tooltip> ) : ( 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/DocumentSelectionToolbar.tsx b/app/components/DocumentSelectionToolbar.tsx index 2dc7bcdabf..8d5a5bb831 100644 --- a/app/components/DocumentSelectionToolbar.tsx +++ b/app/components/DocumentSelectionToolbar.tsx @@ -2,6 +2,7 @@ import { observer } from "mobx-react"; import { archiveDocument, deleteDocument, + moveDocument, pinDocumentToCollection, restoreDocument, starDocument, @@ -25,6 +26,7 @@ const toolbarActions: Action[] = [ unstarDocument, pinDocumentToCollection, unpinDocument, + moveDocument, archiveDocument, unpublishDocument, restoreDocument, diff --git a/app/components/DragAndDrop/DragAndDropProvider.tsx b/app/components/DragAndDrop/DragAndDropProvider.tsx new file mode 100644 index 0000000000..77e21d100a --- /dev/null +++ b/app/components/DragAndDrop/DragAndDropProvider.tsx @@ -0,0 +1,351 @@ +import { + DndContext, + PointerSensor, + useDraggable, + useSensor, + useSensors, + type Announcements, +} from "@dnd-kit/core"; +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, + type ReactNode, + type RefObject, +} from "react"; +import { useTranslation } from "react-i18next"; +import { + DragDropManager, + type DragSource, + type Point, +} from "./DragDropManager"; +import { DragDropManagerContext } from "./hooks"; + +interface Props { + children: ReactNode; +} + +/** + * Provides drag and drop to the hooks in this module. dnd-kit detects and + * tracks the drag; the manager resolves the drop targets under the pointer. + */ +export function DragAndDropProvider({ children }: Props) { + const { t } = useTranslation(); + const [manager] = useState(() => new DragDropManager()); + const activatorRef = useRef<Activator | null>(null); + const pendingRef = useRef<{ source: DragSource; pointer: Point } | null>( + null + ); + const sessionRef = useRef<(() => void) | null>(null); + const titleRef = useRef(""); + + const sensors = useSensors( + useSensor(PointerSensor, { + activationConstraint: { + distance: 5, + }, + }) + ); + + // A single dnd-kit draggable is moved to the source under the pointer, so + // that dnd-kit context changes do not re-render every source. DndContext + // does not wrap the children, as its context changes on every move. + useEffect(() => { + const handlePointerDown = (event: PointerEvent) => { + // Touch gestures scroll the sidebar and swipe it closed instead. + if ( + event.pointerType === "touch" || + !(event.target instanceof Element) || + event.target.closest(EDITABLE_SELECTOR) + ) { + return; + } + const found = manager.findSource(event.target); + if (!found || !activatorRef.current) { + return; + } + pendingRef.current = { + source: found.source, + pointer: { x: event.clientX, y: event.clientY }, + }; + activatorRef.current(found.node, event); + }; + + // Runs before the sensor, so the move that starts a drag is included. + const handlePendingMove = (event: PointerEvent) => { + if (pendingRef.current) { + pendingRef.current.pointer = { x: event.clientX, y: event.clientY }; + } + }; + + document.addEventListener("pointerdown", handlePointerDown); + window.addEventListener("pointermove", handlePendingMove, { + capture: true, + passive: true, + }); + return () => { + document.removeEventListener("pointerdown", handlePointerDown); + window.removeEventListener("pointermove", handlePendingMove, { + capture: true, + }); + }; + }, [manager]); + + const handleDragStart = useCallback(() => { + const pending = pendingRef.current; + pendingRef.current = null; + if (!pending) { + return; + } + manager.beginDrag(pending.source); + titleRef.current = manager.layerMonitor.getItem()?.title ?? ""; + sessionRef.current = startDragSession(manager, pending.pointer); + }, [manager]); + + const endSession = useCallback(() => { + sessionRef.current?.(); + sessionRef.current = null; + }, []); + + const handleDragEnd = useCallback(() => { + endSession(); + manager.drop(); + }, [manager, endSession]); + + const handleDragCancel = useCallback(() => { + endSession(); + manager.endDrag(); + }, [manager, endSession]); + + const handleDragAbort = useCallback(() => { + pendingRef.current = null; + }, []); + + useEffect(() => handleDragCancel, [handleDragCancel]); + + const accessibility = useMemo(() => { + const announcements: Announcements = { + onDragStart: () => + t("Picked up {{ title }}", { title: titleRef.current }), + onDragOver: () => undefined, + onDragEnd: () => t("Dropped {{ title }}", { title: titleRef.current }), + onDragCancel: () => + t("Canceled dragging {{ title }}", { title: titleRef.current }), + }; + return { + announcements, + screenReaderInstructions: { draggable: "" }, + }; + }, [t]); + + return ( + <DragDropManagerContext.Provider value={manager}> + <DndContext + sensors={sensors} + autoScroll={false} + accessibility={accessibility} + onDragStart={handleDragStart} + onDragEnd={handleDragEnd} + onDragCancel={handleDragCancel} + onDragAbort={handleDragAbort} + > + <DragActivator activatorRef={activatorRef} /> + </DndContext> + {children} + </DragDropManagerContext.Provider> + ); +} + +type Activator = (node: HTMLElement, event: PointerEvent) => void; + +const DRAGGABLE_ID = "drag-source"; + +// Drags must not start from controls where the pointer selects text. +const EDITABLE_SELECTOR = + "input, textarea, select, [contenteditable='true'], [role='textbox']"; + +const POINTER_EVENTS = ["pointermove", "pointerup"]; + +// Mouse hover and move handlers do not run during a drag, as with a native +// drag. The drag itself is tracked with pointer events. +const MOUSE_EVENTS = [ + "pointerover", + "pointerout", + "mouseover", + "mouseout", + "mousemove", +]; + +// Distance from the edge of a scroll container where dragging scrolls it. +const SCROLL_EDGE = 48; + +// Scroll distance of one wheel line. +const LINE_HEIGHT = 16; + +// Maximum scroll distance per frame. +const SCROLL_SPEED = 14; + +/** + * Hosts the dnd-kit draggable and exposes a function that starts the dnd-kit + * sensor for a source element. + */ +function DragActivator({ + activatorRef, +}: { + activatorRef: RefObject<Activator | null>; +}) { + const { setNodeRef, listeners } = useDraggable({ id: DRAGGABLE_ID }); + + useEffect(() => { + activatorRef.current = (node, event) => { + setNodeRef(node); + listeners?.onPointerDown?.({ nativeEvent: event }); + }; + return () => { + activatorRef.current = null; + }; + }, [activatorRef, listeners, setNodeRef]); + + return null; +} + +/** + * Tracks the pointer during a drag, updates the hovered targets, scrolls the + * container under the pointer near its edges, blocks hover styles and + * handlers, and swallows the click that follows the drop. + * + * @param manager The drag and drop manager. + * @param initialPointer The pointer position where the drag started. + * @returns a function that ends the session. + */ +function startDragSession( + manager: DragDropManager, + initialPointer: Point +): () => void { + let pointer = initialPointer; + let hovered: Element | null = null; + let scroller: HTMLElement | null = null; + let scrollerRect: DOMRect | undefined; + let frame = 0; + + // A transparent layer takes the pointer so that no element shows a hover + // style, as with a native drag. Hit testing looks through it. + const overlay = document.createElement("div"); + overlay.style.cssText = + "position: fixed; inset: 0; z-index: 2147483647; cursor: grabbing;"; + document.body.appendChild(overlay); + + const update = () => { + const element = + document + .elementsFromPoint(pointer.x, pointer.y) + .find((el) => el !== overlay) ?? null; + if (element !== hovered) { + hovered = element; + scroller = getScrollContainer(element); + scrollerRect = scroller?.getBoundingClientRect(); + } + manager.hover(element, pointer); + }; + + const handlePointerMove = (event: PointerEvent) => { + pointer = { x: event.clientX, y: event.clientY }; + update(); + }; + + const handleClick = (event: MouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + }; + + const stopPropagation = (event: Event) => event.stopPropagation(); + + const handleWheel = (event: WheelEvent) => { + if (!scroller) { + return; + } + event.preventDefault(); + scroller.scrollTop += + event.deltaMode === WheelEvent.DOM_DELTA_LINE + ? event.deltaY * LINE_HEIGHT + : event.deltaY; + }; + + const scroll = () => { + frame = requestAnimationFrame(scroll); + if (!scroller || !scrollerRect) { + return; + } + const speed = + getScrollSpeed(scrollerRect.bottom - pointer.y) - + getScrollSpeed(pointer.y - scrollerRect.top); + if (speed) { + scroller.scrollTop += speed; + } + }; + + // The release position is checked too, before the sensor ends the drag. + for (const type of POINTER_EVENTS) { + window.addEventListener(type, handlePointerMove, { + capture: true, + passive: true, + }); + } + window.addEventListener("scroll", update, { capture: true, passive: true }); + window.addEventListener("click", handleClick, { capture: true }); + for (const type of MOUSE_EVENTS) { + window.addEventListener(type, stopPropagation, { capture: true }); + } + overlay.addEventListener("wheel", handleWheel, { passive: false }); + update(); + frame = requestAnimationFrame(scroll); + + return () => { + for (const type of POINTER_EVENTS) { + window.removeEventListener(type, handlePointerMove, { capture: true }); + } + window.removeEventListener("scroll", update, { capture: true }); + for (const type of MOUSE_EVENTS) { + window.removeEventListener(type, stopPropagation, { capture: true }); + } + cancelAnimationFrame(frame); + overlay.remove(); + setTimeout( + () => window.removeEventListener("click", handleClick, { capture: true }), + 50 + ); + }; +} + +/** + * Returns the nearest ancestor of the element that scrolls vertically. + * + * @param element The element to start from. + * @returns the scroll container, or null if there is none. + */ +function getScrollContainer(element: Element | null): HTMLElement | null { + let current = element; + while (current && current !== document.body) { + if ( + current instanceof HTMLElement && + current.scrollHeight > current.clientHeight && + /(auto|scroll|overlay)/.test(getComputedStyle(current).overflowY) + ) { + return current; + } + current = current.parentElement; + } + return null; +} + +/** + * Returns the scroll distance for one frame. + * + * @param distance The distance from the pointer to the edge of the container. + * @returns the scroll distance, 0 when the pointer is not near the edge. + */ +function getScrollSpeed(distance: number): number { + return SCROLL_SPEED * Math.max(0, 1 - Math.max(distance, 0) / SCROLL_EDGE); +} diff --git a/app/components/DragAndDrop/DragDropManager.ts b/app/components/DragAndDrop/DragDropManager.ts new file mode 100644 index 0000000000..fc550bf3d0 --- /dev/null +++ b/app/components/DragAndDrop/DragDropManager.ts @@ -0,0 +1,334 @@ +import type { ReactNode } from "react"; +import shallowEqual from "@shared/utils/shallowEqual"; + +/** A position in viewport coordinates. */ +export interface Point { + x: number; + y: number; +} + +/** The data carried by a drag operation. */ +export interface DragItem { + /** The id of the dragged model. */ + id: string; + /** The title shown in the drag preview. */ + title?: string; + /** The icon shown in the drag preview. */ + icon?: ReactNode; + /** Whether the dragged model is a draft. */ + isDraft?: boolean; +} + +/** Reads the drag state for a drop target. */ +export interface DropTargetMonitor { + /** + * Whether the pointer is over this target. With `shallow`, only when no + * nested target that accepts the item is between them. + */ + isOver(options?: { shallow?: boolean }): boolean; + /** Whether the dragged item can be dropped on this target. */ + canDrop(): boolean; + /** Whether a nested target has already handled the current drop. */ + didDrop(): boolean; + /** The type of the dragged item, or null when nothing is dragged. */ + getItemType(): string | null; +} + +/** Reads the global drag state. */ +export interface DragLayerMonitor { + /** Whether an item is being dragged. */ + isDragging(): boolean; + /** The dragged item, or null when nothing is dragged. */ + getItem(): DragItem | null; + /** The pointer position, or null when nothing is dragged. */ + getClientOffset(): Point | null; +} + +/** Describes an element that can be dragged. */ +export interface DragSourceSpec<Item extends DragItem> { + /** The type of the dragged item, matched against a target's `accept`. */ + type: string; + /** Returns the item that drop targets receive. */ + item(): Item; + /** Whether the source can be dragged now. */ + canDrag?(): boolean; +} + +/** Describes an element that dragged items can be dropped on. */ +export interface DropTargetSpec<Item extends DragItem> { + /** The item types that the target accepts. */ + accept: string | string[]; + /** Whether the item can be dropped on the target. */ + canDrop?(item: Item, monitor: DropTargetMonitor): boolean; + /** Called while an accepted item is over the target. */ + hover?(item: Item, monitor: DropTargetMonitor): void; + /** Called when the item is dropped on the target. */ + drop?(item: Item, monitor: DropTargetMonitor): unknown; +} + +/** A registered drag source. */ +export interface DragSource { + /** Returns the latest source specification. */ + getSpec(): DragSourceSpec<DragItem>; +} + +/** A registered drop target. */ +export interface DropTarget { + /** Returns the latest target specification. */ + getSpec(): DropTargetSpec<DragItem>; +} + +interface DragOperation { + source: DragSource; + type: string; + item: DragItem; +} + +const EMPTY_TARGETS: DropTarget[] = []; + +/** + * Holds the connected drag sources and drop targets, and the state of the + * current drag operation. Nested drop targets are resolved from the DOM: all + * connected targets that contain the element under the pointer are hovered, + * and a drop is offered to each of them from the innermost outwards. + */ +export class DragDropManager { + /** A monitor for the global drag state. */ + public readonly layerMonitor: DragLayerMonitor = { + isDragging: () => !!this.operation, + getItem: () => this.operation?.item ?? null, + getClientOffset: () => this.pointer, + }; + + /** + * Subscribes to changes in the drag operation and the hovered targets. + * + * @param listener Called after each change. + * @returns a function that removes the listener. + */ + public subscribe = (listener: () => void) => { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + }; + + /** + * Subscribes to changes in the pointer position. + * + * @param listener Called after each change. + * @returns a function that removes the listener. + */ + public subscribeToPointer = (listener: () => void) => { + this.pointerListeners.add(listener); + return () => { + this.pointerListeners.delete(listener); + }; + }; + + /** + * Connects a drag source to its DOM element. + * + * @param node The element. + * @param source The source. + * @returns a function that disconnects the source. + */ + public connectSource(node: HTMLElement, source: DragSource): () => void { + this.sources.set(node, source); + return () => { + if (this.sources.get(node) === source) { + this.sources.delete(node); + } + }; + } + + /** + * Connects a drop target to its DOM element. + * + * @param node The element. + * @param target The target. + * @returns a function that disconnects the target. + */ + public connectTarget(node: Element, target: DropTarget): () => void { + const targets = this.targets.get(node) ?? new Set<DropTarget>(); + targets.add(target); + this.targets.set(node, targets); + return () => { + targets.delete(target); + if (this.hovered.includes(target)) { + this.hovered = this.hovered.filter((t) => t !== target); + this.emit(); + } + }; + } + + /** + * Returns the nearest source connected to the element or one of its + * ancestors that can be dragged now. + * + * @param element The element where the drag starts. + * @returns the source and its element, or undefined if none can be dragged. + */ + public findSource( + element: Element + ): { source: DragSource; node: HTMLElement } | undefined { + for (let node: Element | null = element; node; node = node.parentElement) { + const source = this.sources.get(node); + if ( + source && + node instanceof HTMLElement && + (source.getSpec().canDrag?.() ?? true) + ) { + return { source, node }; + } + } + return undefined; + } + + /** + * Starts a drag operation. + * + * @param source The dragged source. + */ + public beginDrag(source: DragSource) { + const spec = source.getSpec(); + this.operation = { source, type: spec.type, item: spec.item() }; + this.hovered = EMPTY_TARGETS; + this.dropped = false; + this.emit(); + } + + /** + * Updates the pointer position and the hovered targets. + * + * @param element The element under the pointer. + * @param pointer The pointer position. + */ + public hover(element: Element | null, pointer: Point) { + const operation = this.operation; + if (!operation) { + return; + } + + this.pointer = pointer; + this.pointerListeners.forEach((listener) => listener()); + + const hovered: DropTarget[] = []; + for (let node = element; node; node = node.parentElement) { + for (const target of this.targets.get(node) ?? EMPTY_TARGETS) { + if (accepts(target, operation.type)) { + hovered.push(target); + } + } + } + if (!shallowEqual(hovered, this.hovered)) { + this.hovered = hovered.length ? hovered : EMPTY_TARGETS; + this.emit(); + } + + for (const target of this.hovered) { + target.getSpec().hover?.(operation.item, this.getTargetMonitor(target)); + } + } + + /** + * Offers the dragged item to the hovered targets that can accept it, from + * the innermost outwards, then ends the drag. + */ + public drop() { + const operation = this.operation; + if (!operation) { + return; + } + + try { + for (const target of this.hovered) { + if (this.canDrop(target)) { + const monitor = this.getTargetMonitor(target); + target.getSpec().drop?.(operation.item, monitor); + this.dropped = true; + } + } + } finally { + this.endDrag(); + } + } + + /** Ends the drag operation without a drop. */ + public endDrag() { + if (!this.operation) { + return; + } + this.operation = null; + this.pointer = null; + this.hovered = EMPTY_TARGETS; + this.emit(); + this.pointerListeners.forEach((listener) => listener()); + } + + /** + * Returns whether the source is being dragged. + * + * @param source The source. + * @returns true if the source is dragged. + */ + public isDragging(source: DragSource): boolean { + return this.operation?.source === source; + } + + /** + * Returns a monitor for a drop target. + * + * @param target The target. + * @returns the monitor. + */ + public getTargetMonitor(target: DropTarget): DropTargetMonitor { + return { + isOver: (options) => + options?.shallow + ? this.hovered[0] === target + : this.hovered.includes(target), + canDrop: () => this.canDrop(target), + didDrop: () => this.dropped, + getItemType: () => this.operation?.type ?? null, + }; + } + + private canDrop(target: DropTarget): boolean { + const operation = this.operation; + if (!operation || !accepts(target, operation.type)) { + return false; + } + return ( + target + .getSpec() + .canDrop?.(operation.item, this.getTargetMonitor(target)) ?? true + ); + } + + private emit() { + this.listeners.forEach((listener) => listener()); + } + + private operation: DragOperation | null = null; + + private pointer: Point | null = null; + + /** Hovered targets, from the innermost outwards. */ + private hovered = EMPTY_TARGETS; + + private dropped = false; + + private sources = new WeakMap<Element, DragSource>(); + + private targets = new WeakMap<Element, Set<DropTarget>>(); + + private listeners = new Set<() => void>(); + + private pointerListeners = new Set<() => void>(); +} + +function accepts(target: DropTarget, type: string): boolean { + const { accept } = target.getSpec(); + return Array.isArray(accept) ? accept.includes(type) : accept === type; +} diff --git a/app/components/DragAndDrop/hooks.ts b/app/components/DragAndDrop/hooks.ts new file mode 100644 index 0000000000..128254ef96 --- /dev/null +++ b/app/components/DragAndDrop/hooks.ts @@ -0,0 +1,183 @@ +import { + createContext, + useCallback, + useContext, + useLayoutEffect, + useRef, + useState, + useSyncExternalStore, + type RefCallback, +} from "react"; +import shallowEqual from "@shared/utils/shallowEqual"; +import { + DragDropManager, + type DragItem, + type DragLayerMonitor, + type DragSource, + type DragSourceSpec, + type DropTarget, + type DropTargetMonitor, + type DropTargetSpec, +} from "./DragDropManager"; + +/** Options for a drop target, with a collector for the props it renders. */ +export interface DropTargetHookSpec< + Item extends DragItem, + Collected extends object, +> extends DropTargetSpec<Item> { + /** Returns the props to render. The component re-renders when they change. */ + collect(monitor: DropTargetMonitor): Collected; +} + +/** Provides the drag and drop manager to the hooks. */ +export const DragDropManagerContext = createContext<DragDropManager>( + new DragDropManager() +); + +/** + * Makes an element draggable. + * + * @param spec The drag source specification. + * @returns a tuple of whether the element is being dragged and a ref callback for it. + */ +export function useDragRef<Item extends DragItem>( + spec: DragSourceSpec<Item> +): [boolean, RefCallback<HTMLElement>] { + const manager = useContext(DragDropManagerContext); + const specRef = useLatest(spec); + const [source] = useState<DragSource>(() => ({ + getSpec: () => specRef.current, + })); + + const ref = useCallback( + (node: HTMLElement | null) => + node ? manager.connectSource(node, source) : undefined, + [manager, source] + ); + + const isDragging = useSyncExternalStore(manager.subscribe, () => + manager.isDragging(source) + ); + + return [isDragging, ref]; +} + +/** + * Makes an element a drop target. Targets may be nested; a drop is offered to + * every hovered target that can accept it, from the innermost outwards. + * + * @param spec The drop target specification. + * @returns a tuple of the collected props and a ref callback for the element. + */ +export function useDropRef<Item extends DragItem, Collected extends object>( + spec: DropTargetHookSpec<Item, Collected> +): [Collected, RefCallback<HTMLElement>] { + const manager = useContext(DragDropManagerContext); + const specRef = useLatest(spec); + const [target] = useState<DropTarget>(() => ({ + getSpec: () => specRef.current, + })); + const [monitor] = useState(() => manager.getTargetMonitor(target)); + + const ref = useCallback( + (node: HTMLElement | null) => + node ? manager.connectTarget(node, target) : undefined, + [manager, target] + ); + + const collected = useCollected(manager.subscribe, () => + spec.collect(monitor) + ); + + return [collected, ref]; +} + +/** + * Collects props from the global drag state. + * + * @param collect Returns the props to render. The component re-renders when they change. + * @returns the collected props. + */ +export function useDragLayer<Collected extends object>( + collect: (monitor: DragLayerMonitor) => Collected +): Collected { + const manager = useContext(DragDropManagerContext); + return useCollected(manager.subscribe, () => collect(manager.layerMonitor)); +} + +/** + * Returns a ref callback for an element that follows the pointer during a + * drag. The element is moved directly, without a render. + * + * @param offsetX The horizontal distance from the pointer. + * @param offsetY The vertical distance from the pointer. + * @returns a ref callback for the element. + */ +export function useDragFollower( + offsetX: number, + offsetY: number +): RefCallback<HTMLElement> { + const manager = useContext(DragDropManagerContext); + + return useCallback( + (node: HTMLElement | null) => { + if (!node) { + return undefined; + } + const move = () => { + const pointer = manager.layerMonitor.getClientOffset(); + if (pointer) { + node.style.transform = `translate(${pointer.x + offsetX}px, ${pointer.y + offsetY}px)`; + } + }; + move(); + return manager.subscribeToPointer(move); + }, + [manager, offsetX, offsetY] + ); +} + +/** + * Returns a ref that always holds the latest value. + * + * @param value The value to hold. + * @returns the ref. + */ +function useLatest<T>(value: T): { readonly current: T } { + const ref = useRef(value); + useLayoutEffect(() => { + ref.current = value; + }); + return ref; +} + +/** + * Subscribes to a store and returns the collected value. The previous value is + * returned while the new one is shallowly equal, so the component only + * re-renders when a collected prop changes. + * + * @param subscribe Subscribes to changes in the store. + * @param collect Returns the collected value. + * @returns the collected value. + */ +function useCollected<T extends object>( + subscribe: (listener: () => void) => () => void, + collect: () => T +): T { + const cache = useRef<{ value: T } | null>(null); + + const getSnapshot = () => { + const value = collect(); + if ( + cache.current && + shallowEqual(Object.keys(cache.current.value), Object.keys(value)) && + shallowEqual(Object.values(cache.current.value), Object.values(value)) + ) { + return cache.current.value; + } + cache.current = { value }; + return value; + }; + + return useSyncExternalStore(subscribe, getSnapshot); +} diff --git a/app/components/DragAndDrop/index.ts b/app/components/DragAndDrop/index.ts new file mode 100644 index 0000000000..aceda7650a --- /dev/null +++ b/app/components/DragAndDrop/index.ts @@ -0,0 +1,3 @@ +export { DragAndDropProvider } from "./DragAndDropProvider"; +export { useDragFollower, useDragLayer, useDragRef, useDropRef } from "./hooks"; +export type { Point } from "./DragDropManager"; diff --git a/app/components/Editor.tsx b/app/components/Editor.tsx index 6df4c8ce88..8ca37e1b9a 100644 --- a/app/components/Editor.tsx +++ b/app/components/Editor.tsx @@ -1,8 +1,6 @@ import { difference } from "es-toolkit/compat"; import { observer } from "mobx-react"; import * as React from "react"; -import { useTranslation } from "react-i18next"; -import { toast } from "sonner"; import { mergeRefs } from "react-merge-refs"; import type { Optional } from "utility-types"; import EditorContainer from "@shared/editor/components/Styles"; @@ -31,30 +29,14 @@ export type Props = Optional< }; function Editor({ ref, ...props }: Props & { ref?: React.Ref<SharedEditor> }) { - const { - id, - onChange, - onCreateCommentMark, - onDeleteCommentMark, - onFileUploadStart, - onFileUploadStop, - } = props; + const { id, onChange, onCreateCommentMark, onDeleteCommentMark } = props; const { comments } = useStores(); const { shareId } = useShare(); - const { t } = useTranslation(); const embeds = useEmbeds(!shareId); const localRef = React.useRef<SharedEditor | null>(null); const preferences = useCurrentUser({ rejectOnEmpty: false })?.preferences; const previousCommentIds = React.useRef<string[] | undefined>(undefined); - // Upload progress tracking for delayed toast - const progressMap = React.useMemo(() => new Map<string, number>(), []); - const uploadState = React.useRef<{ - toastId?: string | number; - timeoutId?: ReturnType<typeof setTimeout>; - progress: Map<string, number>; - }>({ progress: progressMap }); - const handleUploadFile = React.useCallback( async ( file: File | string, @@ -80,49 +62,6 @@ function Editor({ ref, ...props }: Props & { ref?: React.Ref<SharedEditor> }) { const { handleClickLink } = useEditorClickHandlers({ shareId }); - // Show toast only after uploads have been running for 2 seconds - const handleFileUploadStart = React.useCallback(() => { - uploadState.current.timeoutId = setTimeout(() => { - uploadState.current.toastId = toast.loading( - t("Uploading… {{ progress }}%", { progress: 0 }) - ); - }, 2000); - onFileUploadStart?.(); - }, [onFileUploadStart, t]); - - const handleFileUploadProgress = React.useCallback( - (fileId: string, fractionComplete: number) => { - uploadState.current.progress.set(fileId, fractionComplete); - - // Calculate average progress across all files - const progressValues = Array.from(uploadState.current.progress.values()); - const avgProgress = - progressValues.reduce((a, b) => a + b, 0) / progressValues.length; - const percent = Math.round(avgProgress * 100); - - // Update toast if visible - if (uploadState.current.toastId) { - toast.loading(t("Uploading… {{ progress }}%", { progress: percent }), { - id: uploadState.current.toastId, - }); - } - }, - [t] - ); - - const handleFileUploadStop = React.useCallback(() => { - if (uploadState.current.timeoutId) { - clearTimeout(uploadState.current.timeoutId); - uploadState.current.timeoutId = undefined; - } - if (uploadState.current.toastId) { - toast.dismiss(uploadState.current.toastId); - uploadState.current.toastId = undefined; - } - uploadState.current.progress.clear(); - onFileUploadStop?.(); - }, [onFileUploadStop]); - const focusAtEnd = React.useCallback(() => { localRef?.current?.focusAtEnd(); }, [localRef]); @@ -244,9 +183,6 @@ function Editor({ ref, ...props }: Props & { ref?: React.Ref<SharedEditor> }) { {...props} onClickLink={handleClickLink} onChange={handleChange} - onFileUploadStart={handleFileUploadStart} - onFileUploadStop={handleFileUploadStop} - onFileUploadProgress={handleFileUploadProgress} placeholder={props.placeholder || ""} defaultValue={props.defaultValue || ""} /> diff --git a/app/components/EditorAwareHTML5Backend.ts b/app/components/EditorAwareHTML5Backend.ts deleted file mode 100644 index b1924052d4..0000000000 --- a/app/components/EditorAwareHTML5Backend.ts +++ /dev/null @@ -1,89 +0,0 @@ -import type { BackendFactory } from "dnd-core"; -import { HTML5Backend } from "react-dnd-html5-backend"; - -/** - * react-dnd's HTML5 backend installs global drag listeners on `window` in both - * the capture and bubble phases. The bubble-phase `dragover` handler runs after - * ProseMirror's and, when react-dnd isn't tracking a drag, forces - * `dataTransfer.dropEffect = "none"` – which tells the browser the drop is - * disallowed and silently rejects images dragged into the editor. - * - * These handlers live on `window`, so a propagation-based guard can't stop - * react-dnd without also starving the editor of the event. Instead we wrap the - * backend and make all of its top-level handlers no-op for events that occur - * within the editor surface, leaving ProseMirror to handle them itself. - */ -const topHandlerNames = [ - "handleTopDragStart", - "handleTopDragStartCapture", - "handleTopDragEnter", - "handleTopDragEnterCapture", - "handleTopDragLeaveCapture", - "handleTopDragOver", - "handleTopDragOverCapture", - "handleTopDrop", - "handleTopDropCapture", - "handleTopDragEndCapture", -] as const; - -const isWithinEditor = (target: EventTarget | null): boolean => - target instanceof Element && Boolean(target.closest(".ProseMirror")); - -// A file dragged over an element marked `data-drop-area`, which accepts native -// file drops itself. react-dnd never tracks these drags, so its handlers would -// otherwise reject them. -const isFileOverDropArea = (event: DragEvent): boolean => - Boolean(event.dataTransfer?.types.includes("Files")) && - event.target instanceof Element && - Boolean(event.target.closest("[data-drop-area]")); - -/** - * An HTML5 drag-and-drop backend that ignores drag events originating within the - * rich text editor so that ProseMirror can handle them itself. - * - * @param manager The drag-and-drop manager. - * @param context The global context. - * @param options Backend options. - * @returns The wrapped HTML5 backend instance. - */ -export const EditorAwareHTML5Backend: BackendFactory = ( - manager, - context, - options -) => { - const backend = HTML5Backend(manager, context, options); - const monitor = manager.getMonitor(); - - // The top-level handlers are private instance fields on the backend, so reach - // for them through an index signature view of the instance. - const handlers = backend as unknown as Record< - string, - (event: DragEvent) => void - >; - - for (const name of topHandlerNames) { - const original = handlers[name]; - if (typeof original === "function") { - handlers[name] = (event: DragEvent) => { - if (isWithinEditor(event.target) || isFileOverDropArea(event)) { - return; - } - // A drag that began or entered the page over the editor is never - // registered with react-dnd because those events are skipped above. - // The backend's drop handlers assume a registered drag and may call - // `actions.hover` unconditionally, which throws "Cannot call hover - // while not dragging" – so drops without a tracked drag must be - // ignored here. - if ( - (name === "handleTopDrop" || name === "handleTopDropCapture") && - !monitor.isDragging() - ) { - return; - } - original.call(backend, event); - }; - } - } - - return backend; -}; 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 a1a2b606c6..7d2740566a 100644 --- a/app/components/ErrorBoundary.tsx +++ b/app/components/ErrorBoundary.tsx @@ -145,7 +145,7 @@ class ErrorBoundaryClass extends React.Component<Props> { <> <PageTitle title={t("Module failed to load")} /> <Heading> - <Trans>Loading Failed</Trans> + <Trans>Loading failed</Trans> </Heading> </> )} @@ -167,9 +167,9 @@ class ErrorBoundaryClass extends React.Component<Props> { <Component> {showTitle && ( <> - <PageTitle title={t("Something Unexpected Happened")} /> + <PageTitle title={t("Something unexpected happened")} /> <Heading> - <Trans>Something Unexpected Happened</Trans> + <Trans>Something unexpected happened</Trans> </Heading> </> )} @@ -177,14 +177,14 @@ class ErrorBoundaryClass extends React.Component<Props> { {this.isRepeatedError ? ( <Text as="p" type="secondary"> <Trans> - An error has occurred multiple times recently. If it continues + An error has occurred multiple times recently. If it continues, please try clearing the cache or using a different browser. </Trans> </Text> ) : ( <Text as="p" type="secondary"> <Trans - defaults="Sorry, an unrecoverable error occurred{{notified}}. Please try reloading the page, it may have been a temporary glitch." + defaults="Sorry, an unrecoverable error occurred{{notified}}. Please try reloading the page – it may have been a temporary glitch." values={{ notified: isReported ? ` – ${t("our engineers have been notified")}` diff --git a/app/components/ExpiryDatePicker.tsx b/app/components/ExpiryDatePicker.tsx new file mode 100644 index 0000000000..b71797e3c2 --- /dev/null +++ b/app/components/ExpiryDatePicker.tsx @@ -0,0 +1,119 @@ +import { format as formatDate } from "date-fns"; +import { CloseIcon } from "outline-icons"; +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import styled, { useTheme } from "styled-components"; +import { Calendar } from "@shared/components/Calendar"; +import { dateLocale } from "@shared/utils/date"; +import Button from "~/components/Button"; +import ButtonSmall from "~/components/ButtonSmall"; +import NudeButton from "~/components/NudeButton"; +import Tooltip from "~/components/Tooltip"; +import { + Popover, + PopoverTrigger, + PopoverContent, +} from "~/components/primitives/Popover"; +import useUserLocale from "~/hooks/useUserLocale"; + +type Props = { + selectedDate?: Date; + onSelect: (date: Date) => void; + /** Called to remove the date, shows a remove button when a date is selected. */ + onClear?: () => void; + /** The text to display when no date is selected. */ + placeholder?: string; + /** Whether to display a smaller input. */ + small?: boolean; + /** Applied to the outer element. */ + className?: string; +}; + +const ExpiryDatePicker = ({ + selectedDate, + onSelect, + onClear, + placeholder, + small, + className, +}: Props) => { + const { t } = useTranslation(); + const theme = useTheme(); + const [open, setOpen] = React.useState(false); + + const userLocale = useUserLocale(); + const locale = dateLocale(userLocale); + const PickerButton = small ? SmallPickerButton : LargePickerButton; + const clearSize = small ? 18 : 24; + + const handleSelect = React.useCallback( + (date: Date) => { + setOpen(false); + onSelect(date); + }, + [onSelect] + ); + + return ( + <Wrapper className={className}> + <Popover open={open} onOpenChange={setOpen}> + <PopoverTrigger> + <PickerButton neutral> + {selectedDate + ? formatDate(selectedDate, "MMM dd, yyyy", { locale }) + : (placeholder ?? t("Choose a date"))} + </PickerButton> + </PopoverTrigger> + <PopoverContent + aria-label={t("Choose a date")} + width={280} + side="right" + shrink + > + <Calendar + required + mode="single" + selected={selectedDate} + onSelect={handleSelect} + locale={locale} + disabled={{ before: new Date() }} + /> + </PopoverContent> + </Popover> + {selectedDate && onClear && ( + <Tooltip content={t("Remove expiration")}> + <ClearButton + type="button" + onClick={onClear} + aria-label={t("Remove expiration")} + size={clearSize} + > + <CloseIcon color={theme.placeholder} size={clearSize} /> + </ClearButton> + </Tooltip> + )} + </Wrapper> + ); +}; + +const Wrapper = styled.div` + position: relative; + display: inline-flex; +`; + +const ClearButton = styled(NudeButton)` + position: absolute; + top: 50%; + right: 4px; + transform: translateY(-50%); +`; + +const LargePickerButton = styled(Button)` + width: 150px; +`; + +const SmallPickerButton = styled(ButtonSmall)` + width: 130px; +`; + +export default ExpiryDatePicker; diff --git a/app/components/Export/ExportDialog.tsx b/app/components/Export/ExportDialog.tsx index 80e1ea5dae..d129f6d01d 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 @@ -126,7 +126,7 @@ export const ExportDialog = observer(({ collection, onSubmit }: Props) => { {t("Include attachments")} </Text> <Text size="small" type="secondary"> - {t("Including uploaded images and files in the exported data")}. + {t("Include uploaded images and files in the exported data")}. </Text> </div> </Option> @@ -144,7 +144,7 @@ export const ExportDialog = observer(({ collection, onSubmit }: Props) => { </Text> <Text size="small" type="secondary"> {t( - "As an admin you can export collections you are not currently a member of" + "As an admin, you can export collections you are not currently a member of" )} . </Text> 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/FilterOptions.tsx b/app/components/FilterOptions.tsx index 99cf68c4a1..058807c49c 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 "@shared/styles/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"; @@ -359,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 16bcc71cd4..4b0d2fa73a 100644 --- a/app/components/Header.tsx +++ b/app/components/Header.tsx @@ -6,13 +6,13 @@ 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 breakpoint from "styled-components-breakpoint"; +import styled, { css } from "styled-components"; +import type { DefaultTheme } from "styled-components"; +import { breakpoint } from "@shared/styles/breakpoint"; import useMeasure from "react-use-measure"; -import { HEADER_HEIGHT } from "@shared/constants"; -import { depths, s } from "@shared/styles"; +import { HEADER_HEIGHT, MOBILE_TOUCH_TARGET } from "@shared/constants"; +import { depths, hover, s } from "@shared/styles"; import { metaDisplay } from "@shared/utils/keyboard"; -import { supportsPassiveListener } from "@shared/utils/browser"; import Button from "~/components/Button"; import Fade from "~/components/Fade"; import Flex from "~/components/Flex"; @@ -72,12 +72,7 @@ function Header({ left, title, actions, hasSidebar, className, ref }: Props) { [] ); - useEventListener( - "scroll", - handleScroll, - window, - supportsPassiveListener ? { passive: true } : { capture: false } - ); + useEventListener("scroll", handleScroll, window, { passive: true }); const handleClickTitle = React.useCallback(() => { window.scrollTo({ @@ -170,6 +165,29 @@ function Header({ left, title, actions, hasSidebar, className, ref }: Props) { ); } +/** Height of the fade at the bottom of the mobile header background. */ +const HeaderFadeHeight = 64; + +/** Eased mask stops for a fade of the given height, so it has no visible start or end. */ +const fadeStops = (height: number) => + [1, 0.85, 0.5, 0.15, 0] + .map( + (opacity, index, stops) => + `rgb(0 0 0 / ${opacity}) calc(100% - ${height * (1 - index / (stops.length - 1))}px)` + ) + .join(", "); + +const headerFadeStops = fadeStops(HeaderFadeHeight); + +/** 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; @@ -178,6 +196,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; `}; @@ -191,6 +223,46 @@ 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: ${(props) => + props.theme.isDark ? props.theme.text : props.theme.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; `}; @@ -230,7 +302,7 @@ 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; @@ -255,6 +327,45 @@ 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 or table header continues the header, so the header is solid above it. */ + body:has([data-stuck]) &::before { + inset: 0; + background: ${props.theme.background}; + backdrop-filter: none; + mask-image: none; + } + + /* iOS blurs the top of an installed web app unless the sticky header has a solid background. */ + @media (display-mode: standalone) { + background: ${props.theme.background}; + + &::before { + background: ${props.theme.background}; + mask-image: linear-gradient(to bottom, ${fadeStops(HeaderFadeHeight / 2)}); + } + } + `} + `}; + ${breakpoint("tablet")` padding: 12px; padding-inline-end: ${endPadding(12)}; @@ -288,7 +399,6 @@ const Title = styled("div")` `; const MobileMenuButton = styled(Button)` - margin-right: 8px; pointer-events: auto; @media print { diff --git a/app/components/HeaderMeta.tsx b/app/components/HeaderMeta.tsx index 68cd6c6484..06400216eb 100644 --- a/app/components/HeaderMeta.tsx +++ b/app/components/HeaderMeta.tsx @@ -1,5 +1,6 @@ import styled, { css } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { textSizeStyles } from "@shared/components/Text"; +import { breakpoint } from "@shared/styles/breakpoint"; import { s } from "@shared/styles"; import Flex from "~/components/Flex"; import NudeButton from "~/components/NudeButton"; @@ -47,7 +48,7 @@ export const metaStyles = css<{ $rtl?: boolean }>` */ export const headerMetaStyles = css` margin: -12px 0 2em 0; - font-size: 14px; + ${textSizeStyles("small")} position: relative; user-select: none; z-index: 1; diff --git a/app/components/Heading.ts b/app/components/Heading.ts index 940df0a7da..11e388065d 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 { breakpoint } from "@shared/styles/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 2edf7b7105..2a392ae9ae 100644 --- a/app/components/HoverPreview/HoverPreview.tsx +++ b/app/components/HoverPreview/HoverPreview.tsx @@ -122,7 +122,7 @@ const HoverPreviewDesktop = observer( <Animate initial={{ opacity: 0, - y: -20, + y: -8, filter: "blur(5px)", pointerEvents: "none", }} diff --git a/app/components/HoverPreview/HoverPreviewDocument.tsx b/app/components/HoverPreview/HoverPreviewDocument.tsx index 2979d3187d..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,58 +15,76 @@ import { Card, CardContent, Description, + BreadcrumbContainer, } from "./Components"; type Props = Omit<UnfurlResponse[UnfurlResourceType.Document], "type"> & { ref?: React.Ref<HTMLDivElement>; }; -function HoverPreviewDocument({ - url, - id, - title, - summary, - lastActivityByViewer, - ref, -}: Props) { - const parsedUrl = new URL(url, window.location.href); - const content = ( - <Card ref={ref}> - <CardContent> - <ErrorBoundary showTitle={false} reloadOnChunkMissing={false}> - <Flex column gap={2}> - <Title>{title} - {lastActivityByViewer && {lastActivityByViewer}} - - }> - - - - - - - - ); +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 = ( + + + + + {/* Wrap the built-in breadcrumb in your container for CSS spacing */} + {document && ( + + + + )} + + {title} + {lastActivityByViewer && {lastActivityByViewer}} + + }> + + + + + + + + ); + + if (parsedUrl.origin !== window.location.origin) { + return ( + + {content} + + ); + } - if (parsedUrl.origin !== window.location.origin) { return ( - + {content} ); } - - return ( - - {content} - - ); -} +); export default HoverPreviewDocument; diff --git a/app/components/HoverPreview/HoverPreviewIssue.tsx b/app/components/HoverPreview/HoverPreviewIssue.tsx index 2fd4ba3c9b..01369bc6f9 100644 --- a/app/components/HoverPreview/HoverPreviewIssue.tsx +++ b/app/components/HoverPreview/HoverPreviewIssue.tsx @@ -5,7 +5,6 @@ import { Backticks } from "@shared/components/Backticks"; import { IssueStatusIcon } from "@shared/components/IssueStatusIcon"; import { richExtensions } from "@shared/editor/nodes"; import type { UnfurlResourceType, UnfurlResponse } from "@shared/types"; -import { IntegrationService } from "@shared/types"; import { Avatar } from "~/components/Avatar"; import Editor from "~/components/Editor"; import Flex from "~/components/Flex"; @@ -37,13 +36,6 @@ function HoverPreviewIssue({ ref, }: Props) { const authorName = author.name; - const urlObj = new URL(url); - const service = - urlObj.hostname === "linear.app" - ? IntegrationService.Linear - : urlObj.hostname === "github.com" - ? IntegrationService.GitHub - : IntegrationService.GitLab; return ( @@ -52,11 +44,7 @@ function HoverPreviewIssue({ - <StyledIssueStatusIcon - service={service} - state={state} - size={18} - /> + <StyledIssueStatusIcon state={state} size={18} /> <span> <Backticks content={title} />  <Text type="tertiary">{id}</Text> diff --git a/app/components/IconPicker/components/EmojiPanel.tsx b/app/components/IconPicker/components/EmojiPanel.tsx index fc6cd16521..f66ec2f19f 100644 --- a/app/components/IconPicker/components/EmojiPanel.tsx +++ b/app/components/IconPicker/components/EmojiPanel.tsx @@ -1,6 +1,7 @@ import { concat } from "es-toolkit/compat"; import { PlusIcon } from "outline-icons"; import * as React from "react"; +import type { ListImperativeAPI } from "react-window"; import { useTranslation } from "react-i18next"; import type { EmojiSkinTone } from "@shared/types"; import { EmojiCategory, IconType } from "@shared/types"; @@ -26,6 +27,7 @@ const GRID_HEIGHT = 410; type Props = { panelWidth: number; + icon?: string | null; query: string; panelActive: boolean; height?: number; @@ -35,6 +37,7 @@ type Props = { const EmojiPanel = ({ panelWidth, + icon, query, panelActive, onEmojiChange, @@ -46,7 +49,7 @@ const EmojiPanel = ({ const team = useCurrentTeam(); const can = usePolicy(team); const searchRef = React.useRef<HTMLInputElement | null>(null); - const scrollableRef = React.useRef<HTMLDivElement | null>(null); + const scrollableRef = React.useRef<ListImperativeAPI>(null); const customEmojis = useComputed( () => emojis.orderedData.map(toIcon), [emojis.orderedData] @@ -160,7 +163,7 @@ const EmojiPanel = ({ if (!panelActive) { return; } - scrollableRef.current?.scroll({ top: 0 }); + scrollableRef.current?.element?.scroll({ top: 0 }); requestAnimationFrame(() => searchRef.current?.focus()); }, [panelActive]); @@ -188,6 +191,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 b82ac48bfc..3f8f8d8763 100644 --- a/app/components/IconPicker/components/Grid.tsx +++ b/app/components/IconPicker/components/Grid.tsx @@ -1,6 +1,6 @@ import React from "react"; -import type { ListChildComponentProps } from "react-window"; -import { FixedSizeList } from "react-window"; +import type { ListImperativeAPI, RowComponentProps } from "react-window"; +import { List } from "react-window"; import styled from "styled-components"; type Props = { @@ -10,7 +10,7 @@ type Props = { columns: number; itemWidth: number; onOverflowChange?: (hasMoreBelow: boolean) => void; - ref?: React.Ref<HTMLDivElement>; + ref?: React.Ref<ListImperativeAPI>; }; function Grid({ @@ -33,25 +33,26 @@ function Grid({ React.useEffect(notify, [notify]); const handleScroll = React.useCallback( - ({ scrollOffset }: { scrollOffset: number }) => { - offsetRef.current = scrollOffset; + (event: React.UIEvent<HTMLDivElement>) => { + offsetRef.current = event.currentTarget.scrollTop; notify(); }, [notify] ); + const style = React.useMemo(() => ({ width, height }), [width, height]); + const rowProps = React.useMemo(() => ({ data, columns }), [data, columns]); + return ( <Container - outerRef={ref} - width={width} - height={height} - itemCount={data.length} - itemSize={itemWidth} - itemData={{ data, columns }} + listRef={ref} + style={style} + rowCount={data.length} + rowHeight={itemWidth} + rowComponent={Row} + rowProps={rowProps} onScroll={handleScroll} - > - {Row} - </Container> + /> ); } @@ -60,32 +61,28 @@ type RowProps = { columns: number; }; -const Row = ({ index, style, data }: ListChildComponentProps<RowProps>) => { - const { data: rows, columns } = data; - const row = rows[index]; +const Row = ({ + index, + style, + ariaAttributes, + data, + columns, +}: RowComponentProps<RowProps>) => ( + <RowContainer style={style} columns={columns} {...ariaAttributes}> + {data[index]} + </RowContainer> +); - return ( - <RowContainer style={style} columns={columns}> - {row} - </RowContainer> - ); -}; - -const Container = styled(FixedSizeList<RowProps>)` - padding: 0px 12px; +const Container = styled(List<RowProps>)` overflow-x: hidden !important; - - // Needed for the absolutely positioned children - // to respect the VirtualList's padding - & > div { - position: relative; - } `; +// Rows are absolutely positioned, so the horizontal padding lives here. const RowContainer = styled.div<{ columns: number }>` display: grid; grid-template-columns: ${({ columns }) => `repeat(${columns}, 1fr)`}; align-content: center; + padding: 0 12px; `; export default Grid; diff --git a/app/components/IconPicker/components/GridTemplate.tsx b/app/components/IconPicker/components/GridTemplate.tsx index 2d0238a9b2..4b22274756 100644 --- a/app/components/IconPicker/components/GridTemplate.tsx +++ b/app/components/IconPicker/components/GridTemplate.tsx @@ -1,5 +1,6 @@ import { chunk, compact } from "es-toolkit/compat"; import * as React from "react"; +import type { ListImperativeAPI } from "react-window"; import styled from "styled-components"; import { IconType } from "@shared/types"; import { IconLibrary } from "@shared/utils/IconLibrary"; @@ -50,6 +51,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,14 +61,15 @@ 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<HTMLDivElement>; + /** Ref to the virtualized list */ + ref?: React.Ref<ListImperativeAPI>; }; function GridTemplate({ width, height, data, + selected, empty, onIconSelect, onIconActive, @@ -78,6 +82,26 @@ function GridTemplate({ // 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 +124,19 @@ function 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 ( <IconButton key={item.name} - onClick={() => 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 +155,8 @@ function GridTemplate({ return ( <IconButton key={item.id} - onClick={() => onIconSelect({ id: item.id, value: item.value })} + onClick={() => handleSelect(item.id, item.value)} + aria-current={isSelected ? "true" : undefined} onMouseEnter={handleActive} onFocus={handleActive} > @@ -161,6 +193,9 @@ function GridTemplate({ ); } +const valueOf = (icon: IconNode) => + icon.type === IconType.SVG ? icon.name : icon.value; + const CategoryName = styled(Text)` grid-column: 1 / -1; padding-left: 6px; 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 56f34016e7..e824892451 100644 --- a/app/components/IconPicker/components/IconPanel.tsx +++ b/app/components/IconPicker/components/IconPanel.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import type { ListImperativeAPI } from "react-window"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import { IconType } from "@shared/types"; @@ -24,6 +25,7 @@ const GRID_HEIGHT = 314 - PREVIEW_HEIGHT; type Props = { panelWidth: number; initial: string; + icon: string | null; color: string; query: string; panelActive: boolean; @@ -35,6 +37,7 @@ type Props = { const IconPanel = ({ panelWidth, initial, + icon, color, query, panelActive, @@ -45,7 +48,7 @@ const IconPanel = ({ const { t } = useTranslation(); const searchRef = React.useRef<HTMLInputElement | null>(null); - const scrollableRef = React.useRef<HTMLDivElement | null>(null); + const scrollableRef = React.useRef<ListImperativeAPI>(null); const { incrementIconCount, frequentIcons } = useIconState(IconType.SVG); @@ -129,7 +132,7 @@ const IconPanel = ({ if (!panelActive) { return; } - scrollableRef.current?.scroll({ top: 0 }); + scrollableRef.current?.element?.scroll({ top: 0 }); requestAnimationFrame(() => searchRef.current?.focus()); }, [panelActive]); @@ -153,6 +156,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 8799a558fd..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 = ({ <Content open={open} activeTab={activeTab} + icon={icon} iconColor={chosenColor} iconInitial={initial ?? ""} query={query} @@ -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 = ({ <IconPanel panelWidth={panelWidth} initial={iconInitial} + icon={icon} color={iconColor} query={query} panelActive={open && activeTab === TAB_NAMES["Icon"]} @@ -278,6 +284,7 @@ const Content = ({ <StyledTabContent value={TAB_NAMES["Emoji"]}> <EmojiPanel panelWidth={panelWidth} + icon={icon} query={query} panelActive={open && activeTab === TAB_NAMES["Emoji"]} onEmojiChange={onIconChange} diff --git a/app/components/Icons/CollectionIcon.tsx b/app/components/Icons/CollectionIcon.tsx index e17e890802..5c13bf59c7 100644 --- a/app/components/Icons/CollectionIcon.tsx +++ b/app/components/Icons/CollectionIcon.tsx @@ -1,8 +1,10 @@ import { observer } from "mobx-react"; import { CollectionIcon, PrivateCollectionIcon } from "outline-icons"; -import { getLuminance } from "polished"; +import styled from "styled-components"; import Icon from "@shared/components/Icon"; import { colorPalette } from "@shared/constants"; +import useContrastColor from "@shared/hooks/useContrastColor"; +import Avatar from "~/components/Avatar/Avatar"; import type Collection from "~/models/Collection"; import useStores from "~/hooks/useStores"; @@ -25,19 +27,23 @@ function ResolvedCollectionIcon({ size, className, }: Props) { - const { ui } = useStores(); + const contrastColor = useContrastColor(); + const { users } = useStores(); + const owner = collection.ownerId ? users.get(collection.ownerId) : undefined; + + // A personal collection always shows the avatar of its owner. + if (owner) { + const iconSize = size ?? 24; + return ( + <AvatarWrapper $size={iconSize} className={className}> + <Avatar model={owner} size={Math.round((iconSize * 2) / 3)} /> + </AvatarWrapper> + ); + } 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/DocumentIcon.tsx b/app/components/Icons/DocumentIcon.tsx new file mode 100644 index 0000000000..a4c48f60f0 --- /dev/null +++ b/app/components/Icons/DocumentIcon.tsx @@ -0,0 +1,47 @@ +import { DocumentIcon as BaseDocumentIcon } from "outline-icons"; + +interface Props { + /** The size of the icon, 24px is default to match standard icons. */ + size?: number; + /** The color of the icon, defaults to the current text color. */ + color?: string; + /** Whether the document has no content, shown as an outlined page. */ + empty?: boolean; + /** An optional class name. */ + className?: string; +} + +/** + * The default icon for a document. Documents with no content are shown with + * an outlined page of the same shape. + * + * @param props the icon props. + * @returns the icon element. + */ +export function DocumentIcon({ + empty, + size = 24, + color = "currentColor", + ...rest +}: Props) { + if (!empty) { + return <BaseDocumentIcon size={size} color={color} {...rest} />; + } + + return ( + <svg + fill={color} + width={size} + height={size} + viewBox="0 0 24 24" + xmlns="http://www.w3.org/2000/svg" + {...rest} + > + <path + fillRule="evenodd" + d="M12 4V9C12 10.105 12.895 11 14 11H19V18C19 19.105 18.105 20 17 20H7C5.895 20 5 19.105 5 18V6C5 4.895 5.895 4 7 4H12ZM10.5 5.5H7C6.724 5.5 6.5 5.724 6.5 6V18C6.5 18.276 6.724 18.5 7 18.5H17C17.276 18.5 17.5 18.276 17.5 18V12.5H14C12.067 12.5 10.5 10.933 10.5 9V5.5Z" + /> + <path d="M14 4L19 9H14V4Z" /> + </svg> + ); +} 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<Group, "icon" | "color" | "initial">; + /** 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 ( + <GroupIcon + color={color ?? contrastColor(group.color)} + size={size} + className={className} + /> + ); + } + + return ( + <Icon + value={group.icon} + color={color ?? group.color ?? undefined} + size={size} + initial={group.initial} + className={className} + forceColor={!!color} + /> + ); +}); diff --git a/app/components/Icons/UndoIcon.tsx b/app/components/Icons/UndoIcon.tsx new file mode 100644 index 0000000000..9b55d43b89 --- /dev/null +++ b/app/components/Icons/UndoIcon.tsx @@ -0,0 +1,36 @@ +type Props = { + /** The size of the icon, 24px is default to match standard icons */ + size?: number; + /** The color of the icon, defaults to the current text color */ + color?: string; +}; + +/** + * An arrow that curves back to the left, used for undo. + * + * @param props the icon props. + * @returns the icon element. + */ +export function UndoIcon({ + size = 24, + color = "currentColor", + ...rest +}: Props) { + return ( + <svg + width={size} + height={size} + viewBox="0 0 24 24" + fill="none" + stroke={color} + strokeWidth="2" + strokeLinecap="round" + strokeLinejoin="round" + xmlns="http://www.w3.org/2000/svg" + {...rest} + > + <path d="M9 14L5 10L9 6" /> + <path d="M5 10H14.5C16.9853 10 19 12.0147 19 14.5C19 16.9853 16.9853 19 14.5 19H11" /> + </svg> + ); +} diff --git a/app/components/ImportDocumentDialog.tsx b/app/components/ImportDocumentDialog.tsx index 0cbcd0704d..584f62b6b2 100644 --- a/app/components/ImportDocumentDialog.tsx +++ b/app/components/ImportDocumentDialog.tsx @@ -5,7 +5,7 @@ import Dropzone from "react-dropzone"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { DropzoneContainer, dropzoneIcon, @@ -92,7 +92,7 @@ export const ImportDocumentDialog = observer(function ImportDocumentDialog({ return ( <Columns gap={20}> <Dropzone - accept={documents.importFileTypesString} + accept={documents.importFileTypesAccept} onDropAccepted={handleDropAccepted} onDropRejected={handleDropRejected} multiple diff --git a/app/components/Input.tsx b/app/components/Input.tsx index 8c07f1ac67..7743daa040 100644 --- a/app/components/Input.tsx +++ b/app/components/Input.tsx @@ -2,7 +2,8 @@ import * as VisuallyHidden from "@radix-ui/react-visually-hidden"; import * as React from "react"; import { mergeRefs } from "react-merge-refs"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; +import { MOBILE_TOUCH_TARGET } from "@shared/constants"; import { s, ellipsis } from "@shared/styles"; import Flex from "~/components/Flex"; import Text from "~/components/Text"; @@ -75,6 +76,7 @@ export const NativeInput = styled.input<{ ${breakpoint("mobile", "tablet")` font-size: 16px; + height: ${MOBILE_TOUCH_TARGET - 2}px; `}; `; @@ -121,6 +123,11 @@ export const Outline = styled(Flex)<{ : props.theme.inputBorder}; border-radius: ${(props) => (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")}; @@ -197,6 +204,7 @@ function Input( 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") { @@ -284,6 +292,7 @@ function Input( onRequestSubmit, children, ref, + id = generatedId, ...rest } = props; @@ -310,7 +319,7 @@ function Input( return ( <Wrapper className={className} short={short} flex={flex}> - <label> + <label htmlFor={id}> {label && (labelHidden ? ( <VisuallyHidden.Root>{wrappedLabel}</VisuallyHidden.Root> @@ -335,6 +344,7 @@ function Input( $maxHeight={maxHeight} aria-label={fallbackAriaLabel} {...rest} + id={id} // set it after "rest" to override props from spread. maxLength={maxLength} onKeyDown={handleKeyDown} @@ -353,6 +363,7 @@ function Input( type={type} aria-label={fallbackAriaLabel} {...rest} + id={id} // set it after "rest" to override "onKeyDown" and "onChange" from prop. maxLength={maxLength} onKeyDown={handleKeyDown} diff --git a/app/components/InputColor.tsx b/app/components/InputColor.tsx index d0b5075784..95d6b00685 100644 --- a/app/components/InputColor.tsx +++ b/app/components/InputColor.tsx @@ -1,9 +1,11 @@ +import { WarningIcon } from "outline-icons"; import * as React from "react"; -import styled from "styled-components"; +import styled, { useTheme } from "styled-components"; +import useMobile from "~/hooks/useMobile"; import type { Props as InputProps } from "./Input"; import Input from "./Input"; -import Relative from "./Sidebar/components/Relative"; import { SwatchButton } from "./SwatchButton"; +import Text from "./Text"; /** * Props for the InputColor component. @@ -13,30 +15,66 @@ type Props = Omit<InputProps, "onChange"> & { value: string | undefined; /** Callback function invoked when the color value changes */ onChange: (value: string) => void; + /** An optional warning to show next to the color, such as low contrast */ + warning?: string; }; /** * A color input component that combines a text input with a color picker swatch button. * Automatically formats hex color values with a leading # character. */ -const InputColor: React.FC<Props> = ({ value, onChange, ...rest }: Props) => ( - <Relative> - <Input - value={value} - onChange={(event) => onChange(event.target.value.replace(/^#?/, "#"))} - placeholder="#" - maxLength={7} - {...rest} - /> - <PositionedSwatchButton color={value} onChange={onChange} size={22} /> - </Relative> -); +const InputColor: React.FC<Props> = ({ + value, + onChange, + warning, + ...rest +}: Props) => { + const theme = useTheme(); + const isMobile = useMobile(); + const warningId = React.useId(); -const PositionedSwatchButton = styled(SwatchButton)` + return ( + <> + <Input + value={value} + onChange={(event) => onChange(event.target.value.replace(/^#?/, "#"))} + placeholder="#" + maxLength={7} + aria-describedby={warning ? warningId : undefined} + {...rest} + > + {warning && ( + <WarningIcon + aria-hidden + color={theme.warning} + size={isMobile ? 26 : 22} + /> + )} + <StyledSwatchButton + color={value} + onChange={onChange} + size={isMobile ? 30 : 22} + /> + </Input> + {warning && ( + <WarningText id={warningId} type="secondary" size="xsmall"> + {warning} + </WarningText> + )} + </> + ); +}; + +const StyledSwatchButton = styled(SwatchButton)` + flex-shrink: 0; border: 1px solid ${(props) => props.theme.inputBorder}; - position: absolute; - bottom: 21px; - inset-inline-end: 6px; + margin-inline: 2px 6px; +`; + +const WarningText = styled(Text)` + display: block; + margin: -12px 0 16px; + line-height: 1.4; `; export default InputColor; diff --git a/app/components/InputSearchPage.tsx b/app/components/InputSearchPage.tsx index d4536df81a..8634ce331b 100644 --- a/app/components/InputSearchPage.tsx +++ b/app/components/InputSearchPage.tsx @@ -4,7 +4,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { useHistory } from "react-router-dom"; import styled, { useTheme } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { s } from "@shared/styles"; import { metaDisplay, shortcutSeparator } from "@shared/utils/keyboard"; import useBoolean from "~/hooks/useBoolean"; @@ -122,6 +122,8 @@ const InputMaxWidth = styled(Input).attrs({ round: true })` /* On mobile the input grows to fill the header, so add a gap before the * adjacent action button (e.g. "New doc"). */ ${breakpoint("mobile", "tablet")` + flex: 1; + min-width: 0; margin-inline-end: 8px; `} `; diff --git a/app/scenes/KeyboardShortcuts.tsx b/app/components/KeyboardShortcuts.tsx similarity index 96% rename from app/scenes/KeyboardShortcuts.tsx rename to app/components/KeyboardShortcuts.tsx index c39e94f1ec..5238b625c5 100644 --- a/app/scenes/KeyboardShortcuts.tsx +++ b/app/components/KeyboardShortcuts.tsx @@ -47,6 +47,14 @@ function KeyboardShortcuts({ defaultQuery = "" }: Props) { ), label: t("Forward"), }, + { + shortcut: <KeyboardShortcut keys={["alt", "up"]} />, + label: t("Previous document in sidebar"), + }, + { + shortcut: <KeyboardShortcut keys={["alt", "down"]} />, + label: t("Next document in sidebar"), + }, { shortcut: <KeyboardShortcut keys={["n"]} />, label: t("New document"), @@ -135,15 +143,15 @@ function KeyboardShortcuts({ defaultQuery = "" }: Props) { }, { shortcut: <KeyboardShortcut keys={["ctrl", "shift", "1"]} />, - label: t("Large header"), + label: t("Big heading"), }, { shortcut: <KeyboardShortcut keys={["ctrl", "shift", "2"]} />, - label: t("Medium header"), + label: t("Medium heading"), }, { shortcut: <KeyboardShortcut keys={["ctrl", "shift", "3"]} />, - label: t("Small header"), + label: t("Small heading"), }, { shortcut: <KeyboardShortcut keys={["ctrl", "shift", "\\"]} />, @@ -273,13 +281,13 @@ function KeyboardShortcuts({ defaultQuery = "" }: Props) { shortcut: ( <KeyboardShortcut keys={["#", "space"]} combination="sequence" /> ), - label: t("Large header"), + label: t("Big heading"), }, { shortcut: ( <KeyboardShortcut keys={["##", "space"]} combination="sequence" /> ), - label: t("Medium header"), + label: t("Medium heading"), }, { shortcut: ( @@ -288,7 +296,7 @@ function KeyboardShortcuts({ defaultQuery = "" }: Props) { combination="sequence" /> ), - label: t("Small header"), + label: t("Small heading"), }, { shortcut: ( 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")} </Link>{" "} ·{" "} <Link onClick={() => ui.set({ languagePromptDismissed: true })}> diff --git a/app/components/Layout.tsx b/app/components/Layout.tsx index ab806c8b31..eb333b8225 100644 --- a/app/components/Layout.tsx +++ b/app/components/Layout.tsx @@ -3,7 +3,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import type { DefaultTheme } from "styled-components"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { s } from "@shared/styles"; import Flex from "~/components/Flex"; import { LoadingIndicatorBar } from "~/components/LoadingIndicator"; diff --git a/app/components/LazyPolyfills.tsx b/app/components/LazyPolyfills.tsx deleted file mode 100644 index fc9fa182b5..0000000000 --- a/app/components/LazyPolyfills.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import * as React from "react"; -import Logger from "~/utils/Logger"; -import { loadPolyfills } from "~/utils/polyfills"; - -type Props = { - children?: React.ReactNode; -}; - -/** - * Asyncronously load required polyfills. Should wrap the React tree. - */ -export const LazyPolyfill: React.FC<Props> = ({ children }: Props) => { - const [isLoaded, setIsLoaded] = React.useState(false); - - React.useEffect(() => { - loadPolyfills() - .then(() => { - setIsLoaded(true); - }) - .catch((error) => { - Logger.error("Polyfills failed to load", error); - }); - }, []); - - if (!isLoaded) { - return null; - } - - return <>{children}</>; -}; - -export default LazyPolyfill; diff --git a/app/components/Lightbox.tsx b/app/components/Lightbox.tsx index 7efbb42d6d..aded9ed79a 100644 --- a/app/components/Lightbox.tsx +++ b/app/components/Lightbox.tsx @@ -789,7 +789,7 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { animation={animation.current} $commentsOpen={canShowComments && commentsOpen} > - <Tooltip content={t("Zoom in")} placement="bottom"> + <Tooltip content={t("Zoom in")} side="bottom"> <ActionButton tabIndex={-1} disabled={ @@ -808,7 +808,7 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { neutral /> </Tooltip> - <Tooltip content={t("Zoom out")} placement="bottom"> + <Tooltip content={t("Zoom out")} side="bottom"> <ActionButton tabIndex={-1} disabled={ @@ -830,7 +830,7 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { /> </Tooltip> <Separator /> - <Tooltip content={t("Copy link")} placement="bottom"> + <Tooltip content={t("Copy link")} side="bottom"> <CopyToClipboard text={imgRef.current?.src ?? ""}> <ActionButton tabIndex={-1} @@ -843,7 +843,7 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { /> </CopyToClipboard> </Tooltip> - <Tooltip content={t("Download")} placement="bottom"> + <Tooltip content={t("Download")} side="bottom"> <ActionButton tabIndex={-1} disabled={status.image === ImageStatus.ERROR} @@ -858,7 +858,7 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { {activeImage.source === ImageSource.DiagramsNet && !Desktop.isElectron() && !readOnly && ( - <Tooltip content={t("Edit diagram")} placement="bottom"> + <Tooltip content={t("Edit diagram")} side="bottom"> <ActionButton tabIndex={-1} disabled={status.image === ImageStatus.ERROR} @@ -872,7 +872,7 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { </Tooltip> )} {canShowComments && ( - <Tooltip content={t("Comments")} placement="bottom"> + <Tooltip content={t("Comments")} side="bottom"> <ActionButton tabIndex={-1} onClick={() => setCommentsOpen((open) => !open)} @@ -888,7 +888,7 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { </Actions> <CloseAction animation={animation.current}> <Dialog.Close asChild> - <Tooltip content={t("Close")} shortcut="Esc" placement="bottom"> + <Tooltip content={t("Close")} shortcut="Esc" side="bottom"> <ActionButton tabIndex={-1} onClick={close} diff --git a/app/components/LocaleTime.tsx b/app/components/LocaleTime.tsx index d1bd6a09d6..ed2b4be25d 100644 --- a/app/components/LocaleTime.tsx +++ b/app/components/LocaleTime.tsx @@ -10,15 +10,24 @@ export type Props = { shorten?: boolean; relative?: boolean; format?: Partial<Record<keyof typeof locales, string>>; + /** Additional content shown below the date in the tooltip. */ + tooltipDetail?: React.ReactNode; }; -const LocaleTime: React.FC<Props> = ({ children, ...rest }: Props) => { +const LocaleTime: React.FC<Props> = ({ + 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; const time = ( <time dateTime={rest.dateTime} + tabIndex={hasDetail ? 0 : undefined} onPointerEnter={() => setIsInteractive(true)} onFocus={() => setIsInteractive(true)} > @@ -26,8 +35,21 @@ const LocaleTime: React.FC<Props> = ({ children, ...rest }: Props) => { </time> ); - return isInteractive ? ( - <Tooltip content={tooltipContent} placement="bottom"> + return isInteractive || hasDetail ? ( + <Tooltip + content={ + hasDetail ? ( + <> + {tooltipContent} + <br /> + {tooltipDetail} + </> + ) : ( + tooltipContent + ) + } + side="bottom" + > {time} </Tooltip> ) : ( 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 = <T extends React.ElementType>({ - as: As = "div", - name, - children, - ...rest -}: { - as: T; - name: string; - children?: React.ReactNode; -} & React.ComponentProps<T>) => { - const [measureRef, rect] = useMeasure(); - - return ( - <As - {...rest} - ref={measureRef} - style={{ - [`--${name}-width`]: `${rect.width}px`, - [`--${name}-height`]: `${rect.height}px`, - }} - > - {children} - </As> - ); -}; diff --git a/app/components/Menu/ContextMenu.tsx b/app/components/Menu/ContextMenu.tsx index e9f734b4be..8c209b8996 100644 --- a/app/components/Menu/ContextMenu.tsx +++ b/app/components/Menu/ContextMenu.tsx @@ -4,6 +4,7 @@ import useActionContext from "~/hooks/useActionContext"; import useMobile from "~/hooks/useMobile"; import type { ActionFactory, ActionVariant, ActionWithChildren } from "~/types"; import { preventDefault } from "~/utils/events"; +import { MenuFilter, MenuFilterEmpty, useMenuFilter } from "./MenuFilter"; import { toMenuItems } from "./transformer"; import { observer } from "mobx-react"; import { useComputed } from "~/hooks/useComputed"; @@ -31,6 +32,13 @@ export const ContextMenu = observer( const actionContext = useActionContext({ isMenu: true, }); + const { + query, + setQuery, + handleKeyDownCapture, + handleEscapeKeyDown, + reset: resetFilter, + } = useMenuFilter(); // Menu items are only built while the menu is open. const menuItems = useComputed(() => { @@ -54,12 +62,13 @@ export const ContextMenu = observer( (open: boolean) => { setOpen(open); if (open) { + resetFilter(); onOpen?.(); } else { onClose?.(); } }, - [onOpen, onClose] + [onOpen, onClose, resetFilter] ); const enablePointerEvents = React.useCallback(() => { @@ -86,7 +95,7 @@ export const ContextMenu = observer( return <>{children}</>; } - const content = open ? toMenuItems(menuItems) : null; + const content = open ? toMenuItems(menuItems, query) : null; return ( <MenuProvider variant="context"> @@ -97,8 +106,11 @@ export const ContextMenu = observer( onAnimationStart={disablePointerEvents} onAnimationEnd={enablePointerEvents} onCloseAutoFocus={preventDefault} + onEscapeKeyDown={handleEscapeKeyDown} + onKeyDownCapture={handleKeyDownCapture} > - {content} + <MenuFilter query={query} onChange={setQuery} /> + {content ?? (query ? <MenuFilterEmpty /> : null)} </MenuContent> </Menu> </MenuProvider> diff --git a/app/components/Menu/DropdownMenu.tsx b/app/components/Menu/DropdownMenu.tsx index 6a8717adce..9a5036c772 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 { @@ -21,6 +20,7 @@ import type { MenuItem, MenuItemWithChildren, } from "~/types"; +import { MenuFilter, MenuFilterEmpty, useMenuFilter } from "./MenuFilter"; import { toMenuItems, toMobileMenuItems } from "./transformer"; import { observer } from "mobx-react"; import { useComputed } from "~/hooks/useComputed"; @@ -46,9 +46,7 @@ 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 - ref?: React.Ref<React.ComponentRef<typeof TooltipPrimitive.Trigger>>; -} & React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Trigger>; +} & Omit<React.ComponentProps<typeof MenuTrigger>, "children">; export const DropdownMenu = observer(function DropdownMenu({ ref, @@ -68,6 +66,13 @@ export const DropdownMenu = observer(function DropdownMenu({ const actionContext = useActionContext({ isMenu: true, }); + const { + query, + setQuery, + handleKeyDownCapture, + handleEscapeKeyDown, + reset: resetFilter, + } = useMenuFilter(); const menuItems = useComputed(() => { if (!open) { @@ -96,12 +101,13 @@ export const DropdownMenu = observer(function DropdownMenu({ (open: boolean) => { setOpen(open); if (open) { + resetFilter(); onOpen?.(); } else { onClose?.(); } }, - [onOpen, onClose] + [onOpen, onClose, resetFilter] ); const enablePointerEvents = React.useCallback(() => { @@ -133,7 +139,7 @@ export const DropdownMenu = observer(function DropdownMenu({ ); } - const content = toMenuItems(menuItems); + const content = toMenuItems(menuItems, query); return ( <MenuProvider variant="dropdown"> @@ -147,9 +153,12 @@ export const DropdownMenu = observer(function DropdownMenu({ onAnimationStart={disablePointerEvents} onAnimationEnd={enablePointerEvents} onCloseAutoFocus={preventDefault} + onEscapeKeyDown={handleEscapeKeyDown} + onKeyDownCapture={handleKeyDownCapture} > - {content} - {append} + <MenuFilter query={query} onChange={setQuery} /> + {content ?? (query ? <MenuFilterEmpty /> : null)} + {query ? null : append} </MenuContent> </Menu> </MenuProvider> @@ -229,7 +238,7 @@ function MobileDropdown({ onAnimationStart={disablePointerEvents} onAnimationEnd={enablePointerEvents} > - <DrawerTitle>{ariaLabel}</DrawerTitle> + <DrawerTitle hidden>{ariaLabel}</DrawerTitle> <StyledScrollable hiddenScrollbars> {content} {!submenuName ? append : null} diff --git a/app/components/Menu/MenuFilter.tsx b/app/components/Menu/MenuFilter.tsx new file mode 100644 index 0000000000..6fae2db542 --- /dev/null +++ b/app/components/Menu/MenuFilter.tsx @@ -0,0 +1,330 @@ +import { VISUALLY_HIDDEN_STYLES } from "@radix-ui/react-visually-hidden"; +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import styled from "styled-components"; +import { s } from "@shared/styles"; +import { breakpoint } from "@shared/styles/breakpoint"; +import isTextInput from "~/utils/isTextInput"; + +interface MenuFilterState { + /** The current filter query, or undefined when the filter is hidden. */ + query: string | undefined; + /** Sets the filter query. */ + setQuery: (query: string) => void; + /** Capture-phase keydown handler to attach to the menu content. */ + handleKeyDownCapture: (event: React.KeyboardEvent<HTMLElement>) => void; + /** Escape handler to attach to the menu content. */ + handleEscapeKeyDown: (event: KeyboardEvent) => void; + /** Hides the filter and clears the query. */ + reset: () => void; +} + +/** + * Lets the user filter a menu by typing. When a key that types text is pressed + * on a menu item, focus moves to the filter input, which then receives the + * text. + * + * @returns the filter query and the handlers to attach to the menu content. + */ +export function useMenuFilter(): MenuFilterState { + const [query, setQuery] = React.useState<string>(); + const contentRef = React.useRef<HTMLElement | null>(null); + const highlightRef = React.useRef<HTMLElement | null>(null); + + const reset = React.useCallback(() => { + contentRef.current = null; + highlightRef.current = null; + setQuery(undefined); + }, []); + + const handleKeyDownCapture = React.useCallback( + (event: React.KeyboardEvent<HTMLElement>) => { + const { target, currentTarget } = event; + if ( + !(target instanceof HTMLElement) || + target.closest("[data-radix-menu-content]") !== currentTarget || + (isTextInput(target) && !target.matches('[role^="menuitem"]')) || + target.isContentEditable + ) { + return; + } + + const input = currentTarget.querySelector<HTMLInputElement>( + `[${INPUT_ATTRIBUTE}]` + ); + + // AltGr is reported as Ctrl+Alt on Windows, but it types a character. + const isShortcut = + (event.ctrlKey || event.metaKey || event.altKey) && + !event.getModifierState("AltGraph"); + if (!input || isShortcut) { + return; + } + + // Move up from the first item to the input while the filter is visible. + if ( + event.key === "ArrowUp" && + query !== undefined && + target === currentTarget.querySelector(ITEM_SELECTOR) + ) { + event.preventDefault(); + event.stopPropagation(); + highlightRef.current = highlightItem(currentTarget, target); + input.focus(); + return; + } + + const isText = + Array.from(event.key).length === 1 || + (event.key === "Backspace" && !!query); + if (!isText) { + return; + } + + // Space selects the focused item until there is a query to add it to. + if (event.key === " " && !query) { + return; + } + + // The default action is kept, so the browser types into the input. Radix + // typeahead, item selection and global shortcuts must not handle the key. + event.stopPropagation(); + contentRef.current = currentTarget; + if (target.matches(ITEM_SELECTOR)) { + highlightRef.current = target; + } + if (query === undefined) { + lockLayout(currentTarget); + } + input.focus(); + }, + [query] + ); + + const handleEscapeKeyDown = React.useCallback( + (event: KeyboardEvent) => { + if (query === undefined) { + return; + } + event.preventDefault(); + setQuery(undefined); + }, + [query] + ); + + // While the input has focus, highlight the item that had focus before, or + // the first match if it was filtered out. Otherwise move focus to the first + // item if the focused item was filtered out, or if the filter was hidden + // while it had focus. A passive effect runs after Radix removes unmounted + // items from its collection. + React.useEffect(() => { + const content = contentRef.current; + if (!content) { + return; + } + + const active = document.activeElement; + if (query !== undefined && active?.hasAttribute(INPUT_ATTRIBUTE)) { + highlightRef.current = highlightItem(content, highlightRef.current); + return; + } + if ( + active && + content.contains(active) && + active.getAttribute("role")?.startsWith("menuitem") + ) { + return; + } + + const first = content.querySelector<HTMLElement>(ITEM_SELECTOR); + (first ?? content).focus(); + }, [query]); + + return { query, setQuery, handleKeyDownCapture, handleEscapeKeyDown, reset }; +} + +interface Props { + /** The current filter query, or undefined when the filter is hidden. */ + query: string | undefined; + /** Called when the user changes the query. */ + onChange: (query: string) => void; +} + +/** + * Displays the filter input at the top of a menu. The input is always + * rendered, so that it can receive focus before the first character is typed, + * but it is only visible while there is a query. + */ +export function MenuFilter({ query, onChange }: Props) { + const { t } = useTranslation(); + const isActive = query !== undefined; + + const handleChange = React.useCallback( + (event: React.ChangeEvent<HTMLInputElement>) => { + onChange(event.target.value); + }, + [onChange] + ); + + const handleKeyDown = React.useCallback( + (event: React.KeyboardEvent<HTMLInputElement>) => { + // Radix typeahead must not handle keys typed into the input, but Tab + // must reach the menu so that focus stays in it. + if (event.key !== "Tab") { + event.stopPropagation(); + } + if (event.nativeEvent.isComposing) { + return; + } + + const content = event.currentTarget.closest("[data-radix-menu-content]"); + const items = content + ? Array.from(content.querySelectorAll<HTMLElement>(ITEM_SELECTOR)) + : []; + const highlighted = + content?.querySelector<HTMLElement>(`[${HIGHLIGHT_ATTRIBUTE}]`) ?? + items[0]; + + if (event.key === "ArrowDown") { + event.preventDefault(); + highlighted?.focus(); + } else if (event.key === "ArrowUp") { + event.preventDefault(); + items[items.length - 1]?.focus(); + } else if (event.key === "Enter") { + event.preventDefault(); + highlighted?.click(); + } + }, + [] + ); + + return ( + <Wrapper style={isActive ? undefined : VISUALLY_HIDDEN_STYLES}> + <Input + value={query ?? ""} + onChange={handleChange} + onKeyDown={handleKeyDown} + placeholder={`${t("Filter")}…`} + aria-label={t("Filter")} + tabIndex={-1} + autoComplete="off" + spellCheck={false} + {...{ [INPUT_ATTRIBUTE]: "" }} + /> + </Wrapper> + ); +} + +/** + * Displays a message when no menu items match the filter query. + */ +export function MenuFilterEmpty() { + const { t } = useTranslation(); + return <Empty>{t("No results")}</Empty>; +} + +/** + * Records the current width and position of the menu. The filter row applies + * them, so that the menu does not move while the items are filtered. + */ +function lockLayout(content: HTMLElement) { + // The computed width is not changed by the scale of the open animation. + content.style.setProperty( + "--menu-filter-width", + getComputedStyle(content).width + ); + content.setAttribute(LOCKED_ATTRIBUTE, ""); + + const wrapper = content.closest<HTMLElement>( + "[data-radix-popper-content-wrapper]" + ); + if (wrapper?.style.transform) { + wrapper.style.setProperty( + "--menu-filter-transform", + wrapper.style.transform + ); + wrapper.setAttribute(LOCKED_ATTRIBUTE, ""); + } +} + +/** + * Marks the item that Enter selects while the filter input has focus. + * + * @param content the menu content. + * @param preferred the item to mark if it is still in the menu. + * @returns the marked item, or null if the menu has no items. + */ +function highlightItem(content: HTMLElement, preferred: HTMLElement | null) { + const item = + preferred?.isConnected && + content.contains(preferred) && + preferred.matches(ITEM_SELECTOR) + ? preferred + : content.querySelector<HTMLElement>(ITEM_SELECTOR); + + content + .querySelectorAll(`[${HIGHLIGHT_ATTRIBUTE}]`) + .forEach((element) => element.removeAttribute(HIGHLIGHT_ATTRIBUTE)); + item?.setAttribute(HIGHLIGHT_ATTRIBUTE, ""); + return item; +} + +const ITEM_SELECTOR = '[role^="menuitem"]:not([data-disabled])'; + +const HIGHLIGHT_ATTRIBUTE = "data-menu-filter-highlighted"; + +const LOCKED_ATTRIBUTE = "data-menu-filter-locked"; + +const INPUT_ATTRIBUTE = "data-menu-filter-input"; + +const Wrapper = styled.label` + position: sticky; + top: 0; + z-index: 1; + display: flex; + align-items: center; + min-height: 40px; + margin: -6px -6px 6px; + padding: 8px 18px; + cursor: text; + background: ${s("menuBackground")}; + border-bottom: 1px solid ${s("divider")}; + + // Keep the size and position that the menu had before filtering. This rule + // overrides the inline transform that Radix changes when the menu resizes. + [data-radix-menu-content][${LOCKED_ATTRIBUTE}]:has(&) { + width: var(--menu-filter-width); + } + + [data-radix-popper-content-wrapper][${LOCKED_ATTRIBUTE}]:has(&) { + transform: var(--menu-filter-transform) !important; + } +`; + +const Input = styled.input` + flex: 1; + min-width: 0; + margin: 0; + padding: 0; + border: 0; + outline: none; + background: none; + font: inherit; + font-size: 16px; + color: ${s("text")}; + + &::placeholder { + color: ${s("placeholder")}; + } + + ${breakpoint("tablet")` + font-size: 14px; + `} +`; + +const Empty = styled.div` + padding: 4px 12px; + font-size: 14px; + color: ${s("textTertiary")}; +`; diff --git a/app/components/Menu/transformer.test.tsx b/app/components/Menu/transformer.test.tsx new file mode 100644 index 0000000000..379aca1681 --- /dev/null +++ b/app/components/Menu/transformer.test.tsx @@ -0,0 +1,50 @@ +import type { ReactElement } from "react"; +import type { MenuItem } from "~/types"; +import { toMenuItems } from "./transformer"; + +const noop = () => undefined; + +const items: MenuItem[] = [ + { type: "button", title: "Team", onClick: noop }, + { type: "button", title: "Due date", onClick: noop }, + { type: "separator" }, + { + type: "submenu", + title: "Move to", + items: [ + { type: "button", title: "Engineering", onClick: noop }, + { type: "button", title: "Design", onClick: noop }, + ], + }, + { type: "button", title: "Hidden date", visible: false, onClick: noop }, +]; + +function render(query?: string) { + return (toMenuItems(items, query) ?? []).filter( + (element): element is ReactElement => !!element + ); +} + +describe("toMenuItems", () => { + it("returns all visible items without a query", () => { + expect(render().map((element) => element.key)).toEqual([ + "button-0", + "button-1", + "separator-2", + "submenu-3", + ]); + }); + + it("returns only matching items and keeps their keys", () => { + expect(render("DATE").map((element) => element.key)).toEqual(["button-1"]); + }); + + it("keeps a submenu when one of its items matches", () => { + const [submenu] = render("design"); + expect(submenu.key).toEqual("submenu-3"); + }); + + it("returns null when nothing matches", () => { + expect(toMenuItems(items, "zzz")).toBeNull(); + }); +}); diff --git a/app/components/Menu/transformer.tsx b/app/components/Menu/transformer.tsx index 0ede28d900..2dadb495ae 100644 --- a/app/components/Menu/transformer.tsx +++ b/app/components/Menu/transformer.tsx @@ -14,11 +14,27 @@ import type { MenuItem } from "~/types"; import { MouseSafeArea } from "~/components/MouseSafeArea"; import { createRef } from "react"; -export function toMenuItems(items: MenuItem[]) { +/** + * Converts menu items to menu elements. + * + * @param items the menu items to convert. + * @param query an optional filter query, only matching items are returned. + * @returns the menu elements, or null if there are none. + */ +export function toMenuItems(items: MenuItem[], query?: string) { const filteredItems = filterMenuItems(items); const parentRef = createRef<HTMLDivElement>(); + const normalizedQuery = query?.toLocaleLowerCase(); - if (!filteredItems.length) { + // Keys use the index before the query is applied, so that the focused item + // keeps its element while the query changes. + const entries = filteredItems + .map((item, index) => ({ item, index })) + .filter( + ({ item }) => !normalizedQuery || matchesQuery(item, normalizedQuery) + ); + + if (!entries.length) { return null; } @@ -31,13 +47,19 @@ export function toMenuItems(items: MenuItem[]) { !!item.icon ); - return filteredItems.map((item, index) => { + return entries.map(({ item, index }) => { const icon = showIcon ? ( <Components.MenuIconWrapper aria-hidden> {"icon" in item ? item.icon : null} </Components.MenuIconWrapper> ) : undefined; + // Children are filtered too, unless the parent title itself matches. + const childQuery = + normalizedQuery && !titleMatches(item, normalizedQuery) + ? normalizedQuery + : undefined; + switch (item.type) { case "button": return ( @@ -50,6 +72,7 @@ export function toMenuItems(items: MenuItem[]) { selected={item.selected} dangerous={item.dangerous} shortcut={item.shortcut} + badge={item.badge} onClick={item.onClick} /> ); @@ -62,6 +85,7 @@ export function toMenuItems(items: MenuItem[]) { icon={icon} disabled={item.disabled} shortcut={item.shortcut} + badge={item.badge} to={item.to} /> ); @@ -74,6 +98,7 @@ export function toMenuItems(items: MenuItem[]) { icon={icon} disabled={item.disabled} shortcut={item.shortcut} + badge={item.badge} href={typeof item.href === "string" ? item.href : item.href.url} target={ typeof item.href === "string" ? undefined : item.href.target @@ -82,7 +107,7 @@ export function toMenuItems(items: MenuItem[]) { ); case "submenu": { - const submenuItems = toMenuItems(item.items); + const submenuItems = toMenuItems(item.items, childQuery); if (!submenuItems?.length) { return null; @@ -113,7 +138,7 @@ export function toMenuItems(items: MenuItem[]) { } case "group": { - const groupItems = toMenuItems(item.items); + const groupItems = toMenuItems(item.items, childQuery); if (!groupItems?.length) { return null; @@ -181,6 +206,9 @@ export function toMobileMenuItems( > {icon} <Components.MenuLabel>{item.title}</Components.MenuLabel> + {item.badge && ( + <Components.MenuBadge>{item.badge}</Components.MenuBadge> + )} {item.selected !== undefined && ( <Components.SelectedIconWrapper aria-hidden> {item.selected ? <CheckmarkIcon size={18} /> : null} @@ -199,6 +227,9 @@ export function toMobileMenuItems( > {icon} <Components.MenuLabel>{item.title}</Components.MenuLabel> + {item.badge && ( + <Components.MenuBadge>{item.badge}</Components.MenuBadge> + )} </Components.MenuInternalLink> ); @@ -215,6 +246,9 @@ export function toMobileMenuItems( > {icon} <Components.MenuLabel>{item.title}</Components.MenuLabel> + {item.badge && ( + <Components.MenuBadge>{item.badge}</Components.MenuBadge> + )} </Components.MenuExternalLink> ); @@ -275,6 +309,35 @@ export function toMobileMenuItems( }); } +function titleMatches(item: MenuItem, query: string): boolean { + return ( + "title" in item && + typeof item.title === "string" && + item.title.toLocaleLowerCase().includes(query) + ); +} + +function matchesQuery(item: MenuItem, query: string): boolean { + if (item.visible === false) { + return false; + } + + switch (item.type) { + case "button": + case "route": + case "link": + return titleMatches(item, query); + case "submenu": + case "group": + return ( + titleMatches(item, query) || + item.items.some((child) => matchesQuery(child, query)) + ); + default: + return false; + } +} + function filterMenuItems(items: MenuItem[]): MenuItem[] { return items .filter((item) => item.visible !== false) diff --git a/app/components/Modal.tsx b/app/components/Modal.tsx index 5d75f32f34..7df1e6e782 100644 --- a/app/components/Modal.tsx +++ b/app/components/Modal.tsx @@ -4,7 +4,7 @@ import { CloseIcon, BackIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { depths, s, borderRadius } from "@shared/styles"; import Flex from "~/components/Flex"; import NudeButton from "~/components/NudeButton"; @@ -86,7 +86,7 @@ const Modal: React.FC<Props> = ({ <Centered onClick={(ev) => ev.stopPropagation()} // maxHeight needed for proper overflow behavior in Safari - style={{ maxHeight: "65vh" }} + style={{ maxHeight: height ? maxModalHeight(height) : "65vh" }} column reverse > @@ -117,6 +117,10 @@ const Modal: React.FC<Props> = ({ ); }; +// Limit the requested height so that the modal stays within the viewport. +const maxModalHeight = (value: number | string) => + `min(${typeof value === "number" ? `${value}px` : value}, 90vh)`; + const StyledOverlay = styled(Dialog.Overlay)` position: fixed; top: 0; @@ -244,11 +248,19 @@ const Wrapper = styled.div<{ }>` animation: ${fadeAndScaleIn} 250ms ease; - margin: 25vh auto auto auto; + // Move taller modals up so that they remain within the viewport. + margin-top: ${(props) => + props.$height + ? `min(25vh, calc(95vh - ${maxModalHeight(props.$height)}))` + : "25vh"}; + margin-right: auto; + margin-bottom: auto; + margin-left: auto; width: 75vw; min-width: 350px; max-width: ${(props) => props.$width || "450px"}; - max-height: ${(props) => props.$height || "70vh"}; + max-height: ${(props) => + props.$height ? maxModalHeight(props.$height) : "70vh"}; z-index: ${depths.modal}; display: flex; justify-content: center; diff --git a/app/components/Notice.tsx b/app/components/Notice.tsx index f94da2eef4..4d1da0aa76 100644 --- a/app/components/Notice.tsx +++ b/app/components/Notice.tsx @@ -39,13 +39,12 @@ const Title = styled.span` font-size: 16px; `; -const Container = styled(Text)` +const Container = styled(Text).attrs({ size: "small" })` background: ${s("sidebarBackground")}; color: ${s("textTertiary")}; padding: 10px 12px; border-radius: 4px; position: relative; - font-size: 14px; margin: 1em 0; svg { diff --git a/app/components/Notifications/NotificationListItem.tsx b/app/components/Notifications/NotificationListItem.tsx index 657a224843..0a6f5dcba7 100644 --- a/app/components/Notifications/NotificationListItem.tsx +++ b/app/components/Notifications/NotificationListItem.tsx @@ -80,11 +80,11 @@ function NotificationListItem({ notification, onNavigate }: Props) { {notification.actor?.name ?? t("Unknown")} </Text>{" "} {notification.eventText(t)}{" "} - <Text weight="bold">{notification.subject}</Text> + <Text weight="bold">{notification.subject(t)}</Text> </Text> <Text type="tertiary" size="xsmall"> <Time dateTime={notification.createdAt} addSuffix />{" "} - {collection && <>· {collection.name}</>} + {collection && <>· {collection.displayName}</>} </Text> {commentData && ( <StyledCommentEditor value={commentData} readOnly /> diff --git a/app/components/Notifications/Notifications.tsx b/app/components/Notifications/Notifications.tsx index d27b1f987b..1d985d06e3 100644 --- a/app/components/Notifications/Notifications.tsx +++ b/app/components/Notifications/Notifications.tsx @@ -152,7 +152,7 @@ function Notifications({ onRequestClose, ref }: Props) { items={filteredNotifications} empty={ <EmptyNotifications> - {t("You're all caught up")}. + {t("You’re all caught up")}. </EmptyNotifications> } renderItem={(item) => ( diff --git a/app/components/NudeButton.tsx b/app/components/NudeButton.tsx index d8b4a92abd..5fa4228671 100644 --- a/app/components/NudeButton.tsx +++ b/app/components/NudeButton.tsx @@ -10,9 +10,9 @@ type Props = ActionButtonProps & { type?: "button" | "submit" | "reset"; }; -const NudeButton = styled(ActionButton).attrs((props: Props) => ({ +const NudeButton = styled(ActionButton).attrs<Props>((props) => ({ type: "type" in props ? props.type : "button", -}))<Props>` +}))` width: ${(props) => typeof props.width === "string" ? props.width diff --git a/app/components/PaginatedList.tsx b/app/components/PaginatedList.tsx index e0c9258910..d15cfcbcb0 100644 --- a/app/components/PaginatedList.tsx +++ b/app/components/PaginatedList.tsx @@ -1,12 +1,12 @@ import { isEqual } from "es-toolkit/compat"; import * as React from "react"; import { useTranslation } from "react-i18next"; -import { Waypoint } from "react-waypoint"; import { toError } from "@shared/utils/error"; import { Pagination } from "@shared/constants"; import ArrowKeyNavigation from "~/components/ArrowKeyNavigation"; import DelayedMount from "~/components/DelayedMount"; import PlaceholderList from "~/components/List/Placeholder"; +import { Waypoint } from "~/components/Waypoint"; import useCurrentUser from "~/hooks/useCurrentUser"; import usePrevious from "~/hooks/usePrevious"; import { dateToHeading } from "~/utils/date"; @@ -56,6 +56,9 @@ interface Props< /** Array of items to display in the list */ items?: T[]; + /** ID of an item that must be included in the rendered page. */ + activeItemId?: string; + /** CSS class name to apply to the list container */ className?: string; @@ -112,6 +115,7 @@ const PaginatedList = <T extends PaginatedItem>({ empty = null, loading = null, items = [], + activeItemId, className, renderItem, renderError, @@ -135,6 +139,17 @@ const PaginatedList = <T extends PaginatedItem>({ const [offset, setOffset] = React.useState(0); const [allowLoadMore, setAllowLoadMore] = React.useState(true); + React.useEffect(() => { + if (!activeItemId) { + return; + } + + const activeIndex = items.findIndex((item) => item.id === activeItemId); + if (activeIndex >= 0) { + setRenderCount((count) => Math.max(count, activeIndex + 1)); + } + }, [items, activeItemId]); + const reset = React.useCallback(() => { setOffset(0); setAllowLoadMore(true); @@ -219,7 +234,7 @@ const PaginatedList = <T extends PaginatedItem>({ } // `fetchResults` changes identity as pagination advances, depending on it // here would re-run the initial fetch for every page. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [fetch]); // Handle updates to fetch or options diff --git a/app/components/PinnedDocuments.tsx b/app/components/PinnedDocuments.tsx index fb7a9ebed5..fef27fd480 100644 --- a/app/components/PinnedDocuments.tsx +++ b/app/components/PinnedDocuments.tsx @@ -21,7 +21,7 @@ import { CollapseIcon } from "outline-icons"; import { useState, useRef, useEffect, useCallback } from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { s, hover, hideScrollbars } from "@shared/styles"; import type Pin from "~/models/Pin"; import DocumentCard from "~/components/DocumentCard"; @@ -256,7 +256,7 @@ const List = styled.div<{ $flush?: boolean }>` grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 0; list-style: none; - margin: ${(props) => (props.$flush ? "0" : "16px")} 0 32px; + margin: ${(props) => (props.$flush ? "0" : "16px")} 0 0; &:empty { display: none; diff --git a/app/components/PlaceholderDocument.tsx b/app/components/PlaceholderDocument.tsx index cdc16d90b3..e40d6eef58 100644 --- a/app/components/PlaceholderDocument.tsx +++ b/app/components/PlaceholderDocument.tsx @@ -1,4 +1,5 @@ import styled from "styled-components"; +import { breakpoint } from "@shared/styles/breakpoint"; import DelayedMount from "~/components/DelayedMount"; import Fade from "~/components/Fade"; import Flex from "~/components/Flex"; @@ -54,6 +55,10 @@ export default function PlaceholderDocument({ const Wrapper = styled(Fade)` display: block; - margin: 6vh 0; + margin: 0 0 6vh; padding: 12px 0; + + ${breakpoint("tablet")` + margin-top: 6vh; + `}; `; diff --git a/app/components/Reactions/Reaction.tsx b/app/components/Reactions/Reaction.tsx index e97fa9f449..f0cf59b4e6 100644 --- a/app/components/Reactions/Reaction.tsx +++ b/app/components/Reactions/Reaction.tsx @@ -150,7 +150,7 @@ const Reaction: React.FC<Props> = ({ ); return tooltipContent ? ( - <Tooltip content={tooltipContent} placement="bottom"> + <Tooltip content={tooltipContent} side="bottom"> {DisplayedEmoji} </Tooltip> ) : ( diff --git a/app/components/Reactions/ReactionPicker.tsx b/app/components/Reactions/ReactionPicker.tsx index 6037ce24c6..7aa0f87087 100644 --- a/app/components/Reactions/ReactionPicker.tsx +++ b/app/components/Reactions/ReactionPicker.tsx @@ -57,7 +57,7 @@ const ReactionPicker: React.FC<Props> = ({ onSelect, className, size }) => { return ( <Popover open={open} onOpenChange={setOpen} modal={true}> - <Tooltip content={t("Add reaction")} placement="top"> + <Tooltip content={t("Add reaction")}> <PopoverTrigger> <NudeButton aria-label={t("Reaction picker")} diff --git a/app/components/ResizingHeightContainer.tsx b/app/components/ResizingHeightContainer.tsx index 3a2e4df478..d245903d34 100644 --- a/app/components/ResizingHeightContainer.tsx +++ b/app/components/ResizingHeightContainer.tsx @@ -36,14 +36,21 @@ export function ResizingHeightContainer(props: Props) { ref: forwardedRef, } = props; - const [measureRef, { height }] = useMeasure(); + const [measureRef, { width, height }] = useMeasure(); + + // Bounds are zero until first measured, do not animate toward them on mount. + const isMeasured = width > 0 || height > 0; return ( <m.div - animate={{ - ...config, - height: Math.round(height), - }} + animate={ + isMeasured + ? { + ...config, + height: Math.round(height), + } + : undefined + } style={{ ...style, overflow: hideOverflow ? "hidden" : "inherit", diff --git a/app/components/ScrollToTop.ts b/app/components/ScrollToTop.ts index 5098a57121..e768bebd6f 100644 --- a/app/components/ScrollToTop.ts +++ b/app/components/ScrollToTop.ts @@ -1,6 +1,6 @@ // based on: https://reacttraining.com/react-router/web/guides/scroll-restoration import { useEffect } from "react"; -import { useLocation } from "react-router-dom"; +import { useLocationSelector } from "~/hooks/useLocationSelector"; import usePrevious from "~/hooks/usePrevious"; import { useScrollContext } from "./ScrollContext"; @@ -9,24 +9,26 @@ type Props = { }; export default function ScrollToTop({ children }: Props) { - const location = useLocation<{ retainScrollPosition?: boolean }>(); - const previousLocationPathname = usePrevious(location.pathname); + const pathname = useLocationSelector((location) => location.pathname); + const hash = useLocationSelector((location) => location.hash); + const retainScrollPosition = useLocationSelector< + { retainScrollPosition?: boolean } | undefined, + boolean | undefined + >((location) => location.state?.retainScrollPosition); + const previousLocationPathname = usePrevious(pathname); const scrollContainerRef = useScrollContext(); useEffect(() => { - if ( - location.pathname === previousLocationPathname || - location.state?.retainScrollPosition - ) { + if (pathname === previousLocationPathname || retainScrollPosition) { return; } // The destination has an anchor, scrolling is handled by the target itself - if (location.hash) { + if (hash) { return; } // exception for when entering or exiting document edit, scroll position should not reset if ( - location.pathname.match(/\/edit\/?$/) || + pathname.match(/\/edit\/?$/) || previousLocationPathname?.match(/\/edit\/?$/) ) { return; @@ -34,10 +36,10 @@ export default function ScrollToTop({ children }: Props) { (scrollContainerRef?.current || window).scrollTo(0, 0); }, [ scrollContainerRef, - location.pathname, - location.hash, + pathname, + hash, previousLocationPathname, - location.state?.retainScrollPosition, + retainScrollPosition, ]); return children; diff --git a/app/components/Sharing/Collection/AccessControlList.tsx b/app/components/Sharing/Collection/AccessControlList.tsx index 1220ae34cb..542f81eafb 100644 --- a/app/components/Sharing/Collection/AccessControlList.tsx +++ b/app/components/Sharing/Collection/AccessControlList.tsx @@ -2,9 +2,7 @@ import { observer } from "mobx-react"; import { PadlockIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; -import { toast } from "sonner"; import styled, { useTheme } from "styled-components"; -import { errToString } from "@shared/utils/error"; import Squircle from "@shared/components/Squircle"; import { s } from "@shared/styles"; import { CollectionPermission } from "@shared/types"; @@ -32,6 +30,7 @@ import { Placeholder } from "../components/Placeholder"; import { PublicAccess } from "./PublicAccess"; import Flex from "@shared/components/Flex"; import ButtonLink from "~/components/ButtonLink"; +import { showErrorToast } from "../components/toasts"; type Props = { /** Collection to which team members are supposed to be invited */ @@ -169,7 +168,7 @@ export const AccessControlList = observer( }} label={t("Access")} labelHidden - disabled={!can.update} + disabled={!can.manageUsers} short nude /> @@ -194,7 +193,7 @@ export const AccessControlList = observer( }} label={t("Permission")} labelHidden - disabled={!can.update} + disabled={!can.manageUsers} nude /> )} @@ -258,12 +257,12 @@ export const AccessControlList = observer( }); } } catch (err) { - toast.error(errToString(err)); + showErrorToast(err); return false; } return true; }} - disabled={!can.update} + disabled={!can.manageUsers} value={membership.permission} /> </div> @@ -312,12 +311,12 @@ export const AccessControlList = observer( }); } } catch (err) { - toast.error(errToString(err)); + showErrorToast(err); return false; } return true; }} - disabled={!can.update} + disabled={!can.manageUsers} value={membership.permission} /> </div> diff --git a/app/components/Sharing/Collection/PublicAccess.tsx b/app/components/Sharing/Collection/PublicAccess.tsx index 3f38e0a85b..535bad5001 100644 --- a/app/components/Sharing/Collection/PublicAccess.tsx +++ b/app/components/Sharing/Collection/PublicAccess.tsx @@ -4,7 +4,6 @@ import { observer } from "mobx-react"; import { CopyIcon, GlobeIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; -import { toast } from "sonner"; import { useTheme } from "styled-components"; import { errToString } from "@shared/utils/error"; import Squircle from "@shared/components/Squircle"; @@ -13,6 +12,11 @@ import type Collection from "~/models/Collection"; import type Share from "~/models/Share"; import { AvatarSize } from "~/components/Avatar"; import CopyToClipboard from "~/components/CopyToClipboard"; +import { + showErrorToast, + showPublicLinkCopiedToast, +} from "../components/toasts"; +import { ShareExpiredNotice } from "../components/ShareExpiredNotice"; import Flex from "~/components/Flex"; import NudeButton from "~/components/NudeButton"; import { ResizingHeightContainer } from "~/components/ResizingHeightContainer"; @@ -24,7 +28,12 @@ import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import { ListItem } from "../components/ListItem"; import ShareSettingsPopover from "../components/ShareSettingsPopover"; -import { DomainPrefix, ShareLinkInput, StyledInfoIcon } from "../components"; +import { + DomainPrefix, + ShareLinkInput, + ShareNotice, + StyledInfoIcon, +} from "../components"; type Props = { /** The collection to share. */ @@ -46,6 +55,11 @@ function InnerPublicAccess({ collection, share, ref }: Props) { const collectionAbilities = usePolicy(collection); const canPublish = share ? can.update : collectionAbilities.share; const [creating, setCreating] = React.useState(false); + const [settingsOpen, setSettingsOpen] = React.useState(false); + + const handleUpdateExpiry = React.useCallback(() => { + setSettingsOpen(true); + }, []); React.useEffect(() => { setUrlId(share?.urlId); @@ -62,16 +76,16 @@ function InnerPublicAccess({ collection, share, ref }: Props) { published: true, }); copy(newShare.url); - toast.success(t("Public link copied to clipboard")); + showPublicLinkCopiedToast(newShare, t); } else if (share) { await share.save({ published: checked }); if (checked) { copy(share.url); - toast.success(t("Public link copied to clipboard")); + showPublicLinkCopiedToast(share, t); } } } catch (err) { - toast.error(errToString(err)); + showErrorToast(err); } finally { setCreating(false); } @@ -112,11 +126,11 @@ function InnerPublicAccess({ collection, share, ref }: Props) { ); const handleCopied = React.useCallback(() => { - toast.success(t("Public link copied to clipboard")); - }, [t]); + showPublicLinkCopiedToast(share, t); + }, [t, share]); const copyButton = ( - <Tooltip content={t("Copy public link")} placement="top"> + <Tooltip content={t("Copy public link")}> <CopyToClipboard text={share?.url ?? ""} onCopy={handleCopied}> <NudeButton type="button" disabled={!share} style={{ marginRight: 3 }}> <CopyIcon color={theme.placeholder} size={18} /> @@ -166,17 +180,24 @@ function InnerPublicAccess({ collection, share, ref }: Props) { > {copyButton} </ShareLinkInput> - <ShareSettingsPopover share={share} /> - </Flex> - <Flex align="flex-start" gap={4}> - <StyledInfoIcon color={theme.textTertiary} /> - <Text type="tertiary" size="xsmall"> - {t( - "All documents in this collection will be shared on the web, including any new documents added later" - )} - . - </Text> + <ShareSettingsPopover + share={share} + open={settingsOpen} + onOpenChange={setSettingsOpen} + /> </Flex> + <ShareExpiredNotice share={share} onUpdate={handleUpdateExpiry} /> + {!share.isExpired && ( + <ShareNotice> + <StyledInfoIcon color={theme.textTertiary} /> + <Text type="tertiary" size="xsmall"> + {t( + "All documents in this collection will be shared on the web, including any new documents added later" + )} + . + </Text> + </ShareNotice> + )} </> )} </ResizingHeightContainer> diff --git a/app/components/Sharing/Collection/SharePopover.tsx b/app/components/Sharing/Collection/SharePopover.tsx index 89c6d3427b..054e4f0416 100644 --- a/app/components/Sharing/Collection/SharePopover.tsx +++ b/app/components/Sharing/Collection/SharePopover.tsx @@ -271,6 +271,12 @@ function SharePopover({ count: invitedUsers.length, }) ); + } else if (invitedGroups.length === 1) { + toast.success( + t("{{ count }} people and a group added to the collection", { + count: invitedUsers.length, + }) + ); } else { toast.success( t( @@ -364,7 +370,7 @@ function SharePopover({ return ( <Wrapper ref={wrapperRef} tabIndex={-1}> - {can.update && ( + {can.manageUsers && ( <SearchInput ref={searchInputRef} onChange={handleQuery} diff --git a/app/components/Sharing/Document/AccessControlList.tsx b/app/components/Sharing/Document/AccessControlList.tsx index 7eee1f7f88..320605f27e 100644 --- a/app/components/Sharing/Document/AccessControlList.tsx +++ b/app/components/Sharing/Document/AccessControlList.tsx @@ -17,6 +17,7 @@ import TeamLogo from "~/components/TeamLogo"; import Scrollable from "~/components/Scrollable"; import Text from "~/components/Text"; import useCurrentTeam from "~/hooks/useCurrentTeam"; +import useCurrentUser from "~/hooks/useCurrentUser"; import useMaxHeight from "~/hooks/useMaxHeight"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; @@ -58,12 +59,21 @@ export const AccessControlList = observer( const { t } = useTranslation(); const theme = useTheme(); const collection = document.collection; - const { documents, groupMemberships } = useStores(); + const { documents, groupMemberships, users } = useStores(); const collectionSharingDisabled = document.collection?.sharing === false; const team = useCurrentTeam(); + const user = useCurrentUser(); const can = usePolicy(document); const canCollection = usePolicy(collection); const documentId = document.id; + const ownerId = document.ownerId; + const owner = ownerId ? users.get(ownerId) : undefined; + + React.useEffect(() => { + if (ownerId && !owner) { + void users.fetch(ownerId); + } + }, [ownerId, owner, users]); const containerRef = React.useRef<HTMLDivElement | null>(null); const publicAccessRef = React.useRef<HTMLDivElement | null>(null); @@ -122,7 +132,7 @@ export const AccessControlList = observer( maxHeight: maxHeight ? maxHeight - publicAccessHeight : undefined, }} > - {!document.isDraft && can.manageUsers && ( + {!document.isDraft && !collection?.isPersonal && can.manageUsers && ( <> <ListItem image={ @@ -166,7 +176,7 @@ export const AccessControlList = observer( defaults="Access managed by <link>{{ documentTitle }}</link>" values={{ documentTitle: - restrictionSource?.titleWithDefault ?? t("parent"), + restrictionSource?.displayTitle ?? t("parent"), }} components={{ link: ( @@ -226,6 +236,13 @@ export const AccessControlList = observer( </> ) : collection && canCollection.readDocument ? ( <> + {collection.isPersonal && ( + <ListItem + image={<Avatar model={user} />} + title={user.name} + subtitle={t("You have full access")} + /> + )} {(showLoading || hasMemberships) && ( <SectionHeading>{t("People with access")}</SectionHeading> )} @@ -240,6 +257,20 @@ export const AccessControlList = observer( </> ) : ( <> + {owner && ( + <ListItem + image={<Avatar model={owner} />} + title={owner.name} + subtitle={t("Owner")} + actions={ + <AccessTooltip + content={t("This document is in their personal space")} + > + {t("Can edit")} + </AccessTooltip> + } + /> + )} {showLoading ? ( <Placeholder /> ) : ( @@ -248,22 +279,24 @@ export const AccessControlList = observer( invitedInSession={invitedInSession} /> )} - <ListItem - image={ - <Squircle color={theme.accent} size={AvatarSize.Medium}> - <MoreIcon color={theme.accentText} size={16} /> - </Squircle> - } - title={t("Other people")} - subtitle={t("Other workspace members may have access")} - actions={ - <AccessTooltip - content={t( - "This document may be shared with more workspace members through a parent document or collection you do not have access to" - )} - /> - } - /> + {!ownerId && ( + <ListItem + image={ + <Squircle color={theme.accent} size={AvatarSize.Medium}> + <MoreIcon color={theme.accentText} size={16} /> + </Squircle> + } + title={t("Other people")} + subtitle={t("Other workspace members may have access")} + actions={ + <AccessTooltip + content={t( + "This document may be shared with more workspace members through a parent document or collection you do not have access to" + )} + /> + } + /> + )} </> )} </ScrollableContainer> diff --git a/app/components/Sharing/Document/PublicAccess.tsx b/app/components/Sharing/Document/PublicAccess.tsx index ca9621a94b..3337eb14b5 100644 --- a/app/components/Sharing/Document/PublicAccess.tsx +++ b/app/components/Sharing/Document/PublicAccess.tsx @@ -4,7 +4,6 @@ import { observer } from "mobx-react"; import { CopyIcon, GlobeIcon } from "outline-icons"; import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; -import { toast } from "sonner"; import { useTheme } from "styled-components"; import { errToString } from "@shared/utils/error"; import Flex from "@shared/components/Flex"; @@ -18,11 +17,16 @@ import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import { AvatarSize } from "../../Avatar"; import CopyToClipboard from "../../CopyToClipboard"; +import { + showErrorToast, + showPublicLinkCopiedToast, +} from "../components/toasts"; import NudeButton from "../../NudeButton"; import { ResizingHeightContainer } from "../../ResizingHeightContainer"; import Text from "../../Text"; import Tooltip from "../../Tooltip"; import { ListItem } from "../components/ListItem"; +import { ShareExpiredNotice } from "../components/ShareExpiredNotice"; import ShareSettingsPopover from "../components/ShareSettingsPopover"; import { DomainPrefix, @@ -56,6 +60,11 @@ function PublicAccess({ document, share, sharedParent, ref }: Props) { const documentAbilities = usePolicy(document); const canPublish = share ? can.update : documentAbilities.share; const [creating, setCreating] = React.useState(false); + const [settingsOpen, setSettingsOpen] = React.useState(false); + + const handleUpdateExpiry = React.useCallback(() => { + setSettingsOpen(true); + }, []); React.useEffect(() => { setUrlId(share?.urlId); @@ -72,16 +81,16 @@ function PublicAccess({ document, share, sharedParent, ref }: Props) { published: true, }); copy(newShare.url); - toast.success(t("Public link copied to clipboard")); + showPublicLinkCopiedToast(newShare, t); } else if (share) { await share.save({ published: checked }); if (checked) { copy(share.url); - toast.success(t("Public link copied to clipboard")); + showPublicLinkCopiedToast(share, t); } } } catch (err) { - toast.error(errToString(err)); + showErrorToast(err); } finally { setCreating(false); } @@ -121,17 +130,19 @@ function PublicAccess({ document, share, sharedParent, ref }: Props) { [t, share] ); + const linkShare = sharedParent && !document.isDraft ? sharedParent : share; + const handleCopied = React.useCallback(() => { - toast.success(t("Public link copied to clipboard")); - }, [t]); + showPublicLinkCopiedToast(linkShare, t); + }, [t, linkShare]); const shareUrl = sharedParent?.url && !document.isDraft - ? `${sharedParent.url}${document.url}` + ? `${sharedParent.url}${document.path}` : (share?.url ?? ""); const copyButton = ( - <Tooltip content={t("Copy public link")} placement="top"> + <Tooltip content={t("Copy public link")}> <CopyToClipboard text={shareUrl} onCopy={handleCopied}> <NudeButton type="button" disabled={!share} style={{ marginRight: 3 }}> <CopyIcon color={theme.placeholder} size={18} /> @@ -148,24 +159,27 @@ function PublicAccess({ document, share, sharedParent, ref }: Props) { <> {sharedParent && !document.isDraft ? ( sharedParent.collectionId ? ( - <Trans> - Anyone with the link can access because the containing - collection,{" "} - <UnderlinedLink - to={`/collection/${sharedParent.collectionId}`} - > - {sharedParent.sourceTitle} - </UnderlinedLink> - , is shared - </Trans> + <Trans + defaults="Anyone with the link can access because the containing collection, <link>{{ sourceTitle }}</link>, is shared" + values={{ sourceTitle: sharedParent.sourceTitle }} + components={{ + link: ( + <UnderlinedLink + to={`/collection/${sharedParent.collectionId}`} + /> + ), + }} + /> ) : ( - <Trans> - Anyone with the link can access because the parent document,{" "} - <UnderlinedLink to={`/doc/${sharedParent.documentId}`}> - {sharedParent.sourceTitle} - </UnderlinedLink> - , is shared - </Trans> + <Trans + defaults="Anyone with the link can access because the parent document, <link>{{ sourceTitle }}</link>, is shared" + values={{ sourceTitle: sharedParent.sourceTitle }} + components={{ + link: ( + <UnderlinedLink to={`/doc/${sharedParent.documentId}`} /> + ), + }} + /> ) ) : ( t("Allow anyone with the link to access") @@ -213,18 +227,23 @@ function PublicAccess({ document, share, sharedParent, ref }: Props) { > {copyButton} </ShareLinkInput> - <ShareSettingsPopover share={share} /> + <ShareSettingsPopover + share={share} + open={settingsOpen} + onOpenChange={setSettingsOpen} + /> </Flex> ) : null} + <ShareExpiredNotice share={linkShare} onUpdate={handleUpdateExpiry} /> + {share?.published && !share.includeChildDocuments ? ( <Text as="p" type="tertiary" size="xsmall"> <StyledInfoIcon color={theme.textTertiary} /> <span> {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." )} - . </span> </Text> ) : null} 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" > <Button icon={resolvedTheme === "light" ? <SunIcon /> : <MoonIcon />} @@ -63,7 +63,7 @@ export function SubscribeAction({ return ( <Action> <Popover open={open} onOpenChange={setOpen}> - <Tooltip content={t("Subscribe to updates")} placement="bottom"> + <Tooltip content={t("Subscribe to updates")} side="bottom"> <PopoverTrigger> <Button icon={<SubscribeIcon />} diff --git a/app/components/Sharing/components/AuthenticatedIsland.tsx b/app/components/Sharing/components/AuthenticatedIsland.tsx index c90d910086..1dff97f71f 100644 --- a/app/components/Sharing/components/AuthenticatedIsland.tsx +++ b/app/components/Sharing/components/AuthenticatedIsland.tsx @@ -65,7 +65,7 @@ function AuthenticatedIsland({ document, share, compact }: Props) { <Tooltip content={t("Edit {{noun}}", { noun: document.noun })} shortcut="e" - placement="bottom" + side="bottom" > <IconButton as={Link} diff --git a/app/components/Sharing/components/CopyLinkButton.tsx b/app/components/Sharing/components/CopyLinkButton.tsx index f6c653fed5..2dd47f5647 100644 --- a/app/components/Sharing/components/CopyLinkButton.tsx +++ b/app/components/Sharing/components/CopyLinkButton.tsx @@ -31,7 +31,7 @@ export function CopyLinkButton({ }, [onCopy, t]); return ( - <Tooltip content={t("Copy link")} placement="top"> + <Tooltip content={t("Copy link")}> <CopyToClipboard text={url} onCopy={handleCopied}> <NudeButton type="button"> <LinkIcon size={20} /> diff --git a/app/components/Sharing/components/GroupMembersPopover.tsx b/app/components/Sharing/components/GroupMembersPopover.tsx index 645a7a00cb..89bd5f140c 100644 --- a/app/components/Sharing/components/GroupMembersPopover.tsx +++ b/app/components/Sharing/components/GroupMembersPopover.tsx @@ -30,10 +30,9 @@ export const GroupMembersPopover = observer(({ group, children }: Props) => { // `orderedData` is an observable dependency, it is what recomputes the list // when group membership changes in the store. - // eslint-disable-next-line react-hooks/exhaustive-deps const members = React.useMemo( () => groupUsers.inGroup(group.id), - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps [groupUsers.orderedData, group.id] ); diff --git a/app/components/Sharing/components/ShareExpiredNotice.tsx b/app/components/Sharing/components/ShareExpiredNotice.tsx new file mode 100644 index 0000000000..0b5f2cc509 --- /dev/null +++ b/app/components/Sharing/components/ShareExpiredNotice.tsx @@ -0,0 +1,63 @@ +import { format as formatDate } from "date-fns"; +import { observer } from "mobx-react"; +import { useTranslation } from "react-i18next"; +import styled, { useTheme } from "styled-components"; +import { s } from "@shared/styles"; +import { dateLocale } from "@shared/utils/date"; +import ButtonLink from "~/components/ButtonLink"; +import Text from "~/components/Text"; +import type Share from "~/models/Share"; +import usePolicy from "~/hooks/usePolicy"; +import useUserLocale from "~/hooks/useUserLocale"; +import { ShareNotice, StyledInfoIcon } from "."; + +interface Props { + /** The share to display a warning for, if its link has expired. */ + share: Share | null | undefined; + /** Called when the user chooses to update the expiry. */ + onUpdate: () => void; +} + +/** + * A warning that the link of a published share has expired. + */ +export const ShareExpiredNotice = observer(function ShareExpiredNotice({ + share, + onUpdate, +}: Props) { + const { t } = useTranslation(); + const theme = useTheme(); + const userLocale = useUserLocale(); + const can = usePolicy(share); + + if (!share?.published || !share.expiresAt || !share.isExpired) { + return null; + } + + return ( + <ShareNotice role="status"> + <StyledInfoIcon color={theme.textTertiary} /> + <Text type="tertiary" size="xsmall"> + {t("This link expired on {{ date }} and can no longer be accessed.", { + date: formatDate(new Date(share.expiresAt), "MMM dd, yyyy", { + locale: dateLocale(userLocale), + }), + })} + {can.update && ( + <> + {" "} + <UpdateLink type="button" onClick={onUpdate}> + {t("Update expiry")} + </UpdateLink> + </> + )} + </Text> + </ShareNotice> + ); +}); + +const UpdateLink = styled(ButtonLink)` + font: inherit; + color: ${s("textSecondary")}; + text-decoration: underline; +`; diff --git a/app/components/Sharing/components/ShareExpiryDialog.tsx b/app/components/Sharing/components/ShareExpiryDialog.tsx new file mode 100644 index 0000000000..25e0dd2970 --- /dev/null +++ b/app/components/Sharing/components/ShareExpiryDialog.tsx @@ -0,0 +1,92 @@ +import { addWeeks, endOfDay } from "date-fns"; +import { observer } from "mobx-react"; +import { useCallback, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; +import styled from "styled-components"; +import { Calendar } from "@shared/components/Calendar"; +import { dateLocale } from "@shared/utils/date"; +import type Share from "~/models/Share"; +import Button from "~/components/Button"; +import Flex from "~/components/Flex"; +import useUserLocale from "~/hooks/useUserLocale"; +import { showErrorToast } from "./toasts"; + +interface Props { + /** The share to change the expiry of. */ + share: Share; + /** Called after the expiry is saved. */ + onSubmit: () => void; +} + +/** + * Dialog content to choose the date after which a public link stops working. + */ +export const ShareExpiryDialog = observer(function ShareExpiryDialog({ + share, + onSubmit, +}: Props) { + const { t } = useTranslation(); + const userLocale = useUserLocale(); + const [date, setDate] = useState<Date | undefined>(() => { + if (!share.expiresAt) { + return undefined; + } + + // A past date cannot be selected, so suggest a week from today instead. + return share.isExpired + ? addWeeks(new Date(), 1) + : new Date(share.expiresAt); + }); + const [isSaving, setIsSaving] = useState(false); + + const handleSubmit = useCallback( + async (ev: React.FormEvent) => { + ev.preventDefault(); + if (!date) { + return; + } + + setIsSaving(true); + try { + await share.save({ expiresAt: endOfDay(date).toISOString() }); + toast.success(t("Expiry updated")); + onSubmit(); + } catch (err) { + showErrorToast(err); + } finally { + setIsSaving(false); + } + }, + [date, share, onSubmit, t] + ); + + return ( + <form onSubmit={handleSubmit}> + <Flex gap={12} column> + <CalendarWrapper> + <Calendar + required + mode="single" + numberOfMonths={2} + selected={date} + onSelect={setDate} + defaultMonth={date} + locale={dateLocale(userLocale)} + disabled={{ before: new Date() }} + /> + </CalendarWrapper> + <Flex justify="flex-end"> + <Button type="submit" disabled={!date || isSaving}> + {isSaving ? `${t("Saving")}…` : t("Save")} + </Button> + </Flex> + </Flex> + </form> + ); +}); + +const CalendarWrapper = styled.div` + display: flex; + justify-content: center; +`; diff --git a/app/components/Sharing/components/ShareSettingsPopover.tsx b/app/components/Sharing/components/ShareSettingsPopover.tsx index 3f3baaabcc..88ddf799e2 100644 --- a/app/components/Sharing/components/ShareSettingsPopover.tsx +++ b/app/components/Sharing/components/ShareSettingsPopover.tsx @@ -1,3 +1,4 @@ +import { endOfDay } from "date-fns"; import { debounce, uniqueId } from "es-toolkit/compat"; import { observer } from "mobx-react"; import { @@ -10,7 +11,6 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled, { useTheme } from "styled-components"; -import { errToString } from "@shared/utils/error"; import { s } from "@shared/styles"; import { HStack } from "~/components/primitives/HStack"; import { AttachmentPreset } from "@shared/types"; @@ -19,6 +19,7 @@ import type Share from "~/models/Share"; import { createAction } from "~/actions"; import { ShareSection } from "~/actions/sections"; import { AvatarSize } from "~/components/Avatar"; +import ExpiryDatePicker from "~/components/ExpiryDatePicker"; import Input from "~/components/Input"; import { DropdownMenu } from "~/components/Menu/DropdownMenu"; import NudeButton from "~/components/NudeButton"; @@ -37,12 +38,17 @@ import { PopoverContent, } from "~/components/primitives/Popover"; import { ListItem } from "./ListItem"; +import { showErrorToast } from "./toasts"; type Props = { /** The share model to configure settings for. */ share: Share; /** Custom trigger element. If not provided, a default settings icon button is rendered. */ children?: React.ReactElement; + /** Whether the popover is open, if controlled by the parent. */ + open?: boolean; + /** Called when the popover opens or closes. */ + onOpenChange?: (open: boolean) => void; }; /** @@ -50,7 +56,7 @@ type Props = { * for configuring a published share link (indexing, subscriptions, etc.), * as well as custom title and logo branding. */ -function ShareSettingsPopover({ share, children }: Props) { +function ShareSettingsPopover({ share, children, open, onOpenChange }: Props) { const { t } = useTranslation(); const { auth } = useStores(); const theme = useTheme(); @@ -71,7 +77,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ title: val || null }); hasChangesRef.current = true; } catch (err) { - toast.error(errToString(err)); + showErrorToast(err); } }, 500), [share] @@ -101,7 +107,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ iconUrl: attachment.url }); hasChangesRef.current = true; } catch (err) { - toast.error(errToString(err)); + showErrorToast(err); } finally { setIsUploading(false); if (fileInputRef.current) { @@ -117,7 +123,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ iconUrl: null }); hasChangesRef.current = true; } catch (err) { - toast.error(errToString(err)); + showErrorToast(err); } }, [share]); @@ -127,7 +133,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ allowIndexing: checked }); hasChangesRef.current = true; } catch (err) { - toast.error(errToString(err)); + showErrorToast(err); } }, [share] @@ -139,7 +145,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ allowSubscriptions: checked }); hasChangesRef.current = true; } catch (err) { - toast.error(errToString(err)); + showErrorToast(err); } }, [share] @@ -151,7 +157,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ showLastUpdated: checked }); hasChangesRef.current = true; } catch (err) { - toast.error(errToString(err)); + showErrorToast(err); } }, [share] @@ -163,12 +169,31 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ showTOC: checked }); hasChangesRef.current = true; } catch (err) { - toast.error(errToString(err)); + showErrorToast(err); } }, [share] ); + const handleExpiryChanged = React.useCallback( + async (date: Date | null) => { + try { + await share.save({ + expiresAt: date ? endOfDay(date).toISOString() : null, + }); + hasChangesRef.current = true; + } catch (err) { + showErrorToast(err); + } + }, + [share] + ); + + const handleExpiryCleared = React.useCallback( + () => handleExpiryChanged(null), + [handleExpiryChanged] + ); + const flushChangeToast = React.useCallback(() => { if (hasChangesRef.current) { toast.success(t("Sharing settings updated")); @@ -177,12 +202,13 @@ function ShareSettingsPopover({ share, children }: Props) { }, [t]); const handleOpenChange = React.useCallback( - (open: boolean) => { - if (!open) { + (isOpen: boolean) => { + if (!isOpen) { flushChangeToast(); } + onOpenChange?.(isOpen); }, - [flushChangeToast] + [flushChangeToast, onOpenChange] ); // Also flush on unmount in case the parent popover closes us before @@ -217,8 +243,8 @@ function ShareSettingsPopover({ share, children }: Props) { const iconRootAction = useMenuAction(iconActions); return ( - <Popover modal onOpenChange={handleOpenChange}> - <Tooltip content={t("Display settings")} placement="top"> + <Popover modal open={open} onOpenChange={handleOpenChange}> + <Tooltip content={t("Display settings")}> <PopoverTrigger> {children ?? ( <SettingsTrigger type="button"> @@ -391,6 +417,33 @@ function ShareSettingsPopover({ share, children }: Props) { } /> )} + <ListItem + title={ + <ExpiryLabel> + {t("Expiration")}  + <Tooltip + content={t( + "The public link will stop working after the selected date" + )} + > + <NudeButton size={18} aria-label={t("More information")}> + <QuestionMarkIcon size={18} /> + </NudeButton> + </Tooltip> + </ExpiryLabel> + } + actions={ + <CompactExpiryDatePicker + small + placeholder={t("No expiry")} + selectedDate={ + share.expiresAt ? new Date(share.expiresAt) : undefined + } + onSelect={handleExpiryChanged} + onClear={handleExpiryCleared} + /> + } + /> </PopoverContent> </Popover> ); @@ -403,6 +456,17 @@ const SwitchLabel = styled.label` cursor: var(--pointer); `; +const ExpiryLabel = styled.span` + display: flex; + align-items: center; + color: ${s("textSecondary")}; +`; + +// Keeps the row the same height as the rows that contain a switch. +const CompactExpiryDatePicker = styled(ExpiryDatePicker)` + margin: -3px 0; +`; + const SettingsTrigger = styled(NudeButton)` width: 32px; height: 32px; diff --git a/app/components/Sharing/components/Suggestions.tsx b/app/components/Sharing/components/Suggestions.tsx index 9605ff68c7..5ca7e285d3 100644 --- a/app/components/Sharing/components/Suggestions.tsx +++ b/app/components/Sharing/components/Suggestions.tsx @@ -117,7 +117,7 @@ export const Suggestions = observer(function Suggestions({ ]; // The store collections listed below are observable dependencies, they // are what recompute the suggestions when the underlying data changes. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [ getSuggestionForEmail, users, @@ -153,7 +153,6 @@ export const Suggestions = observer(function Suggestions({ return { title: suggestion.name, subtitle: ( - // eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events <span onClick={(ev) => ev.stopPropagation()}> <GroupMembersPopover group={suggestion}> <StyledButtonLink> diff --git a/app/components/Sharing/components/index.tsx b/app/components/Sharing/components/index.tsx index bcf32090ef..1d8b8c6ae6 100644 --- a/app/components/Sharing/components/index.tsx +++ b/app/components/Sharing/components/index.tsx @@ -12,7 +12,7 @@ import { transparentize } from "polished"; export { GroupMembersPopover } from "./GroupMembersPopover"; -// TODO: Temp until Button/NudeButton styles are normalized +// Highlights nude buttons within sharing popovers on hover or while expanded. export const Wrapper = styled.div` ${NudeButton}:${hover}, ${NudeButton}[aria-expanded="true"] { @@ -33,6 +33,17 @@ export const StyledInfoIcon = styled(InfoIcon).attrs({ flex-shrink: 0; `; +export const ShareNotice = styled(Flex).attrs({ + align: "flex-start", + gap: 4, +})` + padding-bottom: 4px; + + &:not(:last-child) { + margin-bottom: 4px; + } +`; + export const ShareLinkInput = styled(Input)` padding: 12px 0 1px; min-width: 100px; diff --git a/app/components/Sharing/components/toasts.ts b/app/components/Sharing/components/toasts.ts new file mode 100644 index 0000000000..ac1f4a6b86 --- /dev/null +++ b/app/components/Sharing/components/toasts.ts @@ -0,0 +1,32 @@ +import type { TFunction } from "i18next"; +import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; +import type Share from "~/models/Share"; +import { daysToExpiry } from "~/utils/date"; + +/** + * Shows a toast that confirms a public link was copied, with the days until + * the link expires if it has an expiry. + * + * @param share the share that the link belongs to. + * @param t the translation function. + */ +export function showPublicLinkCopiedToast( + share: Share | null | undefined, + t: TFunction +) { + toast.success(t("Public link copied to clipboard"), { + description: share?.expiresAt + ? daysToExpiry(share.expiresAt, t) + : undefined, + }); +} + +/** + * Shows a toast with the message of an error. + * + * @param err the caught error. + */ +export function showErrorToast(err: unknown) { + toast.error(errToString(err)); +} diff --git a/app/components/Sidebar/App.tsx b/app/components/Sidebar/App.tsx index f662b5e676..c7b0b5c02c 100644 --- a/app/components/Sidebar/App.tsx +++ b/app/components/Sidebar/App.tsx @@ -32,10 +32,12 @@ import { DraftsLink } from "./components/DraftsLink"; import DragPlaceholder from "./components/DragPlaceholder"; import { DismissableSidebarAction } from "./components/DismissableSidebarAction"; import HistoryNavigation from "./components/HistoryNavigation"; +import { PersonalDocs } from "./components/PersonalDocs"; import Section from "./components/Section"; import SharedWithMe from "./components/SharedWithMe"; import SidebarButton from "./components/SidebarButton"; import SidebarLink from "./components/SidebarLink"; +import { SidebarNavigationProvider } from "./components/SidebarNavigation"; import Starred from "./components/Starred"; import ToggleButton from "./components/ToggleButton"; import TrashLink from "./components/TrashLink"; @@ -78,6 +80,7 @@ function AppSidebar() { [SidebarSection.Starred]: <Starred />, [SidebarSection.SharedWithMe]: <SharedWithMe />, [SidebarSection.Collections]: <Collections />, + [SidebarSection.Personal]: <PersonalDocs />, }; return ( @@ -135,16 +138,18 @@ function AppSidebar() { </Overflow> <Scrollable flex shadow ref={setScrollArea}> <SidebarScrollProvider value={scrollArea}> - {sectionOrder.map((section) => ( - <DraggableSection key={section} section={section}> - {sectionContent[section]} - </DraggableSection> - ))} - {can.createDocument && ( - <Section auto> - <ArchiveLink /> - </Section> - )} + <SidebarNavigationProvider> + {sectionOrder.map((section) => ( + <DraggableSection key={section} section={section}> + {sectionContent[section]} + </DraggableSection> + ))} + {can.createDocument && ( + <Section auto> + <ArchiveLink /> + </Section> + )} + </SidebarNavigationProvider> <Section> {can.createDocument && <TrashLink />} <DismissableSidebarAction diff --git a/app/components/Sidebar/Aside.tsx b/app/components/Sidebar/Aside.tsx index 5f825127b2..15cc2e7953 100644 --- a/app/components/Sidebar/Aside.tsx +++ b/app/components/Sidebar/Aside.tsx @@ -3,7 +3,7 @@ import { m } from "framer-motion"; import { observer } from "mobx-react"; import * as React from "react"; import styled, { useTheme } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { depths, s } from "@shared/styles"; import ErrorBoundary from "~/components/ErrorBoundary"; import ResizeBorder from "~/components/Sidebar/components/ResizeBorder"; diff --git a/app/components/Sidebar/Settings.tsx b/app/components/Sidebar/Settings.tsx index 3b993e93dd..6291c7bfc4 100644 --- a/app/components/Sidebar/Settings.tsx +++ b/app/components/Sidebar/Settings.tsx @@ -3,11 +3,12 @@ import { observer } from "mobx-react"; import { BackIcon } from "outline-icons"; import { useCallback } from "react"; import { useTranslation } from "react-i18next"; -import { useHistory, useLocation } from "react-router-dom"; +import { useHistory } from "react-router-dom"; import styled from "styled-components"; import Flex from "~/components/Flex"; import Scrollable from "~/components/Scrollable"; import useSettingsConfig from "~/hooks/useSettingsConfig"; +import { useLocationSelector } from "~/hooks/useLocationSelector"; import useStores from "~/hooks/useStores"; import isCloudHosted from "~/utils/isCloudHosted"; import { settingsPath } from "~/utils/routeHelpers"; @@ -23,7 +24,7 @@ function SettingsSidebar() { const { integrations } = useStores(); const { t } = useTranslation(); const history = useHistory(); - const location = useLocation(); + const pathname = useLocationSelector((location) => location.pathname); const configs = useSettingsConfig(); const groupedConfig = groupBy( @@ -42,7 +43,7 @@ function SettingsSidebar() { return ( <Sidebar canCollapse={false}> <SidebarButton - title={t("Return to App")} + title={t("Back to app")} image={<StyledBackIcon />} onClick={returnToApp} /> @@ -60,7 +61,7 @@ function SettingsSidebar() { active={ item.path.startsWith(settingsPath("templates")) || item.path.startsWith(settingsPath("groups")) - ? location.pathname.startsWith(item.path) + ? pathname.startsWith(item.path) : undefined } icon={<item.icon />} diff --git a/app/components/Sidebar/Shared.tsx b/app/components/Sidebar/Shared.tsx index 49932ed893..c74ea9cca5 100644 --- a/app/components/Sidebar/Shared.tsx +++ b/app/components/Sidebar/Shared.tsx @@ -53,12 +53,12 @@ function SharedSidebar({ share }: Props) { () => (rootNode ? [rootNode] : undefined), [rootNode] ); - const expansion = useSidebarExpansionState(rootChildren, ui.activeDocumentId); + const expansion = useSidebarExpansionState(rootChildren); useEffect(() => { ui.tocVisible = share.showTOC; // Only seed the initial visibility, the user can toggle it afterwards. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, []); if (!rootNode?.children.length) { diff --git a/app/components/Sidebar/Sidebar.tsx b/app/components/Sidebar/Sidebar.tsx index 3c48cb99b3..4ed10740dc 100644 --- a/app/components/Sidebar/Sidebar.tsx +++ b/app/components/Sidebar/Sidebar.tsx @@ -1,21 +1,21 @@ import { observer } from "mobx-react"; import * as React from "react"; import { mergeRefs } from "react-merge-refs"; -import { useLocation } from "react-router-dom"; -import styled, { css, useTheme } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { useHistory } from "react-router-dom"; +import styled, { ThemeProvider, useTheme } from "styled-components"; +import { breakpoint } from "@shared/styles/breakpoint"; import { depths, s } from "@shared/styles"; import { Avatar } from "~/components/Avatar"; import Flex from "~/components/Flex"; import useCurrentUser from "~/hooks/useCurrentUser"; import useEventListener from "~/hooks/useEventListener"; import useMobile from "~/hooks/useMobile"; -import usePrevious from "~/hooks/usePrevious"; import { useResizeHandle } from "~/hooks/useResizeHandle"; import useStores from "~/hooks/useStores"; +import { useSwipeToDismiss } from "~/hooks/useSwipeToDismiss"; import AccountMenu from "~/menus/AccountMenu"; import { fadeOnDesktopBackgrounded } from "~/styles"; -import { fadeIn } from "~/styles/animations"; +import { drawerTransition } from "~/styles/animations"; import Desktop from "~/utils/Desktop"; import NotificationIcon from "../Notifications/NotificationIcon"; import NotificationsPopover from "../Notifications/NotificationsPopover"; @@ -55,8 +55,7 @@ function Sidebar({ const { t } = useTranslation(); const theme = useTheme(); const { ui } = useStores(); - const location = useLocation(); - const previousLocation = usePrevious(location); + const history = useHistory(); const user = useCurrentUser({ rejectOnEmpty: false }); const isMobile = useMobile(); const width = ui.sidebarWidth; @@ -73,6 +72,7 @@ function Sidebar({ const isSmallerThanMinimum = width < minWidth; const hoverTimeoutRef = React.useRef<NodeJS.Timeout | null>(null); const internalRef = React.useRef<HTMLDivElement | null>(null); + const backdropRef = React.useRef<HTMLAnchorElement | null>(null); const mergedRef = React.useMemo(() => mergeRefs([internalRef, ref]), [ref]); const measure = React.useCallback( @@ -250,82 +250,109 @@ function Sidebar({ ui.setSidebarResizing(isResizing); }, [ui, isResizing]); - React.useEffect(() => { - if (location !== previousLocation) { - ui.hideMobileSidebar(); - } - }, [ui, location, previousLocation]); - - const style = React.useMemo( - () => ({ - width: `${width}px`, - }), - [width] + // Subscribe to history rather than the location, so that the sidebar does + // not re-render on every navigation. + React.useEffect( + () => + history.listen(() => { + ui.hideMobileSidebar(); + }), + [ui, history] ); - const handleCloseSidebar = () => { - ui.toggleMobileSidebar(); - }; + // On mobile the width comes from the viewport, not the resizable desktop width. + const style = React.useMemo( + () => (isMobile ? undefined : { width: `${width}px` }), + [isMobile, width] + ); + + // On mobile the sidebar is a drawer, so it uses the drawer colors. + const sidebarTheme = React.useMemo( + () => + isMobile + ? { + ...theme, + sidebarBackground: theme.menuBackground, + sidebarHoverBackground: theme.menuItemSelected, + sidebarActiveBackground: theme.menuItemSelected, + } + : theme, + [isMobile, theme] + ); + + useSwipeToDismiss(internalRef, backdropRef, { + enabled: isMobile && ui.mobileSidebarVisible, + side: direction === "rtl" ? "right" : "left", + onDismiss: ui.hideMobileSidebar, + }); return ( - <TooltipProvider> - <Container - id="sidebar" - ref={mergedRef} - style={style} - $hidden={hidden} - $isHovering={isHovering} - $isAnimating={isAnimating} - $isSmallerThanMinimum={isSmallerThanMinimum} - $mobileSidebarVisible={ui.mobileSidebarVisible} - $collapsed={collapsed} - $isMobile={isMobile} - className={className} - onPointerDown={handlePointerActivity} - onPointerMove={handlePointerActivity} - onPointerLeave={handlePointerLeave} - column - > - {children} + <ThemeProvider theme={sidebarTheme}> + <TooltipProvider> + <Container + id="sidebar" + ref={mergedRef} + style={style} + $hidden={hidden} + $isHovering={isHovering} + $isAnimating={isAnimating} + $isSmallerThanMinimum={isSmallerThanMinimum} + $mobileSidebarVisible={ui.mobileSidebarVisible} + $collapsed={collapsed} + $isMobile={isMobile} + className={className} + onPointerDown={handlePointerActivity} + onPointerMove={handlePointerActivity} + onPointerLeave={handlePointerLeave} + column + > + {children} - {user && showAccountMenu && ( - <AccountMenu> - <SidebarButton - showMoreMenu - title={user.name} - position="bottom" - image={ - <Avatar - alt={t("Avatar of {{ name }}", { name: user.name })} - model={user} - size={24} - showHoverCard={false} - /> - } - > - <NotificationsPopover> - <SidebarButton - position="bottom" - image={<NotificationIcon />} - aria-label={t("Notifications")} - style={{ paddingInline: 4 }} - /> - </NotificationsPopover> - </SidebarButton> - </AccountMenu> - )} - <ResizeBorder - onMouseDown={handleMouseDown} - onDoubleClick={sidebarIsClosed ? undefined : handleReset} + {user && showAccountMenu && ( + <AccountMenu> + <SidebarButton + showMoreMenu + title={user.name} + position="bottom" + image={ + <Avatar + alt={t("Avatar of {{ name }}", { name: user.name })} + model={user} + size={24} + showHoverCard={false} + /> + } + > + <NotificationsPopover> + <SidebarButton + position="bottom" + image={<NotificationIcon />} + aria-label={t("Notifications")} + style={{ paddingInline: 4 }} + /> + </NotificationsPopover> + </SidebarButton> + </AccountMenu> + )} + {!isMobile && ( + <ResizeBorder + onMouseDown={handleMouseDown} + onDoubleClick={sidebarIsClosed ? undefined : handleReset} + /> + )} + </Container> + <Backdrop + ref={backdropRef} + $visible={ui.mobileSidebarVisible} + onClick={ui.hideMobileSidebar} + aria-hidden /> - </Container> - {ui.mobileSidebarVisible && <Backdrop onClick={handleCloseSidebar} />} - </TooltipProvider> + </TooltipProvider> + </ThemeProvider> ); } -const Backdrop = styled.a` - animation: ${fadeIn} 250ms ease-in-out; +const Backdrop = styled.a<{ $visible: boolean }>` position: fixed; top: 0; left: 0; @@ -334,6 +361,13 @@ const Backdrop = styled.a` cursor: default; z-index: ${depths.mobileSidebar - 1}; background: ${s("backdrop")}; + opacity: ${(props) => (props.$visible ? 1 : 0)}; + pointer-events: ${(props) => (props.$visible ? "auto" : "none")}; + transition: opacity ${drawerTransition}; + + ${breakpoint("tablet")` + display: none; + `}; `; type ContainerProps = { @@ -370,7 +404,7 @@ const Container = styled(Flex)<ContainerProps>` background: ${s("sidebarBackground")}; transition: box-shadow 150ms ease-in-out, - transform 250ms cubic-bezier(0.34, 1.15, 0.64, 1) + transform ${drawerTransition} ${(props: ContainerProps) => props.$isAnimating ? `, width ${ANIMATION_MS}ms ease-out` : ""}; transform: translateX( @@ -380,8 +414,54 @@ const Container = styled(Flex)<ContainerProps>` max-width: 80%; min-width: 280px; padding-inline-start: var(--sal); + padding-bottom: var(--sab, 0px); ${fadeOnDesktopBackgrounded()} + ${breakpoint("mobile", "tablet")` + /* Leaves a strip of the page visible to tap and close, as in Material navigation drawers. */ + width: calc(100% - 56px); + max-width: 360px; + min-width: 0; + border-start-end-radius: 8px; + border-end-end-radius: 8px; + /* The negative spread keeps the shadow off the edge side, so a stretch cannot reveal it. */ + box-shadow: ${(props: ContainerProps) => + props.$mobileSidebarVisible + ? "12px 0 24px -12px rgb(0 0 0 / 16%)" + : "none"}; + + [dir="rtl"] & { + box-shadow: ${(props: ContainerProps) => + props.$mobileSidebarVisible + ? "-12px 0 24px -12px rgb(0 0 0 / 16%)" + : "none"}; + } + + @supports (corner-shape: superellipse(2)) { + border-start-end-radius: 14px; + border-end-end-radius: 14px; + corner-shape: superellipse(2); + } + + /* Fills the space behind the edge when the sidebar is stretched past open, + overlapping by a pixel so no seam shows at fractional offsets. */ + &::after { + content: ""; + position: absolute; + top: 0; + bottom: 0; + inset-inline-end: calc(100% - 1px); + width: 100%; + background: inherit; + } + + /* Horizontal gestures drag the sidebar closed, scroll containers inside reset the value. */ + &, + & * { + touch-action: pan-y pinch-zoom; + } + `}; + [dir="rtl"] & { transform: translateX( ${(props) => (props.$mobileSidebarVisible ? 0 : "100%")} @@ -428,7 +508,7 @@ const Container = styled(Flex)<ContainerProps>` props.$collapsed ? `calc(100% - 8px)` : 0}); } - ${(props: ContainerProps) => props.$isHovering && css(hoverStyles)} + ${(props: ContainerProps) => props.$isHovering && hoverStyles(props)} &:hover { ${ToggleButton} { diff --git a/app/components/Sidebar/components/ArchivedCollectionLink.tsx b/app/components/Sidebar/components/ArchivedCollectionLink.tsx index 1940cc344d..4b21c91191 100644 --- a/app/components/Sidebar/components/ArchivedCollectionLink.tsx +++ b/app/components/Sidebar/components/ArchivedCollectionLink.tsx @@ -1,7 +1,6 @@ import type * as React from "react"; import { useState, useCallback } from "react"; import type Collection from "~/models/Collection"; -import useStores from "~/hooks/useStores"; import CollectionLink from "./CollectionLink"; type Props = { @@ -12,7 +11,6 @@ type Props = { }; export function ArchivedCollectionLink({ collection, depth = 0 }: Props) { - const { documents } = useStores(); const [expanded, setExpanded] = useState(false); const handleDisclosureClick = useCallback( @@ -33,7 +31,6 @@ export function ArchivedCollectionLink({ collection, depth = 0 }: Props) { depth={depth} collection={collection} expanded={expanded} - activeDocument={documents.active} onDisclosureClick={handleDisclosureClick} onClick={handleClick} /> diff --git a/app/components/Sidebar/components/CollectionLink.tsx b/app/components/Sidebar/components/CollectionLink.tsx index 8f553745e7..70cdecc898 100644 --- a/app/components/Sidebar/components/CollectionLink.tsx +++ b/app/components/Sidebar/components/CollectionLink.tsx @@ -4,7 +4,6 @@ import { useHistory } from "react-router-dom"; import { UserPreference } from "@shared/types"; import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper"; import type Collection from "~/models/Collection"; -import type Document from "~/models/Document"; import type { RefHandle } from "~/components/EditableTitle"; import useCurrentUser from "~/hooks/useCurrentUser"; import { useCollectionMenuAction } from "~/hooks/useCollectionMenuAction"; @@ -23,7 +22,6 @@ type Props = { collection: Collection; expanded?: boolean; onDisclosureClick: (ev?: React.MouseEvent<HTMLElement>) => void; - activeDocument: Document | undefined; isDraggingAnyCollection?: boolean; depth?: number; onClick?: () => void; @@ -61,8 +59,7 @@ const CollectionLink: React.FC<Props> = ({ const parentRef = React.useRef<HTMLDivElement>(null); const [{ isOver, canDrop }, dropRef] = useDropToChangeCollection( collection, - handleExpand, - parentRef + handleExpand ); const handlePrefetch = React.useCallback(() => { @@ -119,7 +116,7 @@ const CollectionLink: React.FC<Props> = ({ onDisclosureClick={onDisclosureClick} onExpand={handleExpand} canEdit={can.update} - labelText={collection.name} + labelText={collection.displayName} onTitleChange={handleTitleChange} editableTitleRef={editableTitleRef} contextAction={contextMenuAction} @@ -131,12 +128,16 @@ const CollectionLink: React.FC<Props> = ({ dropRef={dropRef} isActiveDropTarget={isOver && canDrop} > - <CollectionLinkChildren - collection={collection} - expanded={!!expanded} - depth={depth} - prefetchDocument={documents.prefetchDocument} - /> + {(newChild) => ( + <CollectionLinkChildren + collection={collection} + expanded={!!expanded} + depth={depth} + prefetchDocument={documents.prefetchDocument} + > + {newChild} + </CollectionLinkChildren> + )} </CollectionRow> ); }; diff --git a/app/components/Sidebar/components/CollectionLinkChildren.tsx b/app/components/Sidebar/components/CollectionLinkChildren.tsx index d897513fff..e014ec155a 100644 --- a/app/components/Sidebar/components/CollectionLinkChildren.tsx +++ b/app/components/Sidebar/components/CollectionLinkChildren.tsx @@ -1,14 +1,14 @@ import { noop } from "es-toolkit/compat"; import { observer } from "mobx-react"; -import { useState, useRef, useEffect, useCallback } from "react"; +import { useCallback } from "react"; import { useTranslation } from "react-i18next"; -import { Waypoint } from "react-waypoint"; import styled from "styled-components"; import type Collection from "~/models/Collection"; import type Document from "~/models/Document"; import DocumentsLoader from "~/components/DocumentsLoader"; import { ResizingHeightContainer } from "~/components/ResizingHeightContainer"; import Text from "~/components/Text"; +import { useComputed } from "~/hooks/useComputed"; import useStores from "~/hooks/useStores"; import history from "~/utils/history"; import useCollectionDocuments from "../hooks/useCollectionDocuments"; @@ -16,16 +16,13 @@ import { useDropToChangeCollection } from "../hooks/useDragAndDrop"; import SidebarExpansionContext, { useSidebarExpansionState, } from "./SidebarExpansionContext"; -import DocumentLink from "./DocumentLink"; +import { DocumentTree } from "./DocumentTree"; import DropCursor from "./DropCursor"; import Folder from "./Folder"; import PlaceholderCollections from "./PlaceholderCollections"; import { useSidebarDisclosure } from "./SidebarDisclosureContext"; import SidebarLink from "./SidebarLink"; -// The number of child documents to initially render -const DEFAULT_PAGE_SIZE = 50; - type Props = { /** The collection to render the children of. */ collection: Collection; @@ -33,6 +30,8 @@ type Props = { expanded: boolean; /** Indentation depth of the parent collection. */ depth?: number; + /** Indentation depth of the child documents, defaults to below the collection. */ + childDepth?: number; /** Function to prefetch a document by ID. */ prefetchDocument?: (documentId: string) => Promise<Document | void>; /** Element to display above the child documents */ @@ -43,35 +42,24 @@ function CollectionLinkChildren({ collection, expanded, depth = 0, + childDepth: childDepthProp, prefetchDocument, children, }: Props) { // Documents sit one level below the collection, with a minimum that leaves // room for their own disclosure to the left of the label. - const childDepth = Math.max(depth + 1, 2); - const pageSize = DEFAULT_PAGE_SIZE; - const { documents, ui } = useStores(); + const childDepth = childDepthProp ?? Math.max(depth + 1, 2); + const { documents } = useStores(); const { t } = useTranslation(); - const activeDocument = documents.active; + // Scoped to this collection so that other collections do not re-render when + // the active document changes. + const activeDocument = useComputed(() => { + const active = documents.active; + return active?.collectionId === collection.id ? active : undefined; + }, [documents, collection]); const childDocuments = useCollectionDocuments(collection, activeDocument); - const [showing, setShowing] = useState(pageSize); - useEffect(() => { - if (!expanded) { - setShowing(pageSize); - } - }, [expanded, pageSize]); - - const showMore = useCallback(() => { - if (childDocuments && childDocuments.length > showing) { - setShowing((value) => value + pageSize); - } - }, [childDocuments, showing, pageSize]); - - const expansion = useSidebarExpansionState( - childDocuments, - ui.activeDocumentId - ); + const expansion = useSidebarExpansionState(childDocuments); // Handle collection-level alt-click cascade from DraggableCollectionLink const handleCascadeExpand = useCallback(() => { @@ -97,32 +85,27 @@ function CollectionLinkChildren({ <Loading /> </ResizingHeightContainer> )} - {childDocuments?.slice(0, showing).map((node, index) => ( - <DocumentLink - key={node.id} - node={node} - collection={collection} - activeDocument={activeDocument} - prefetchDocument={prefetchDocument} - isDraft={node.isDraft} - depth={childDepth} - index={index} - /> - ))} - {childDocuments?.length === 0 && !children && ( - <SidebarLink - label={ - <Text type="tertiary" size="small" italic> - {t("Empty")} - </Text> - } - onClick={() => history.push(collection.url)} - depth={childDepth} - /> - )} {childDocuments && ( - <Waypoint key={showing} onEnter={showMore} fireOnRapidScroll /> + <DocumentTree + nodes={childDocuments} + depth={childDepth} + collection={collection} + prefetchDocument={prefetchDocument} + /> )} + {childDocuments?.length === 0 && + !children && + !collection.isPersonal && ( + <SidebarLink + label={ + <Text type="tertiary" size="small" italic> + {t("Empty")} + </Text> + } + onClick={() => history.push(collection.url)} + depth={childDepth} + /> + )} </DocumentsLoader> </Folder> </SidebarExpansionContext.Provider> @@ -131,20 +114,13 @@ function CollectionLinkChildren({ const DynamicDropCursor = observer( ({ collection }: { collection: Collection }) => { - const dummyRef = useRef<HTMLDivElement>(null); - const [{ isOver, canDrop }] = useDropToChangeCollection( - collection, - noop, - dummyRef - ); + const [{ isOver, canDrop }] = useDropToChangeCollection(collection, noop); if (!canDrop || !collection.isManualSort) { return null; } - return ( - <DropCursor isActiveDrop={isOver} innerRef={dummyRef} position="top" /> - ); + return <DropCursor isActiveDrop={isOver} position="top" />; } ); diff --git a/app/components/Sidebar/components/CollectionRow.tsx b/app/components/Sidebar/components/CollectionRow.tsx index 19f05789ac..a72e1173fd 100644 --- a/app/components/Sidebar/components/CollectionRow.tsx +++ b/app/components/Sidebar/components/CollectionRow.tsx @@ -5,6 +5,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { mergeRefs } from "react-merge-refs"; import type { match } from "react-router"; +import { isTouchDevice } from "@shared/utils/browser"; import { CollectionValidation, DocumentValidation } from "@shared/validations"; import type Collection from "~/models/Collection"; import EditableTitle, { type RefHandle } from "~/components/EditableTitle"; @@ -17,8 +18,10 @@ import { ActionContextProvider } from "~/hooks/useActionContext"; import DropToImport from "./DropToImport"; import Relative from "./Relative"; import SidebarLink from "./SidebarLink"; +import { StaticLink } from "./StaticLink"; import type { SidebarContextType } from "./SidebarContext"; import { useSidebarContext } from "./SidebarContext"; +import { useSidebarNavigation } from "./SidebarNavigation"; import type { ActionWithChildren } from "~/types"; export type CollectionRowProps = { @@ -74,15 +77,18 @@ export type CollectionRowProps = { /** Depth of the inline new-child SidebarLink. Defaults to one level below the row. */ newChildDepth?: number; - /** Ref forwarded to the outer Relative; for drag hover timers. */ - parentRef?: React.Ref<HTMLDivElement>; + /** Ref forwarded to the outer Relative; for drag hover timers and keyboard navigation. */ + parentRef: React.RefObject<HTMLDivElement | null>; /** Drop target connector for "change collection" / reorder. */ dropRef?: React.Ref<HTMLDivElement>; /** Whether the row is an active drop target (visual highlight). */ isActiveDropTarget?: boolean; - /** Content rendered after the row (e.g. CollectionLinkChildren). */ - children?: React.ReactNode; + /** + * Renders the content after the row (e.g. CollectionLinkChildren), given the + * inline new document input to show above the child documents. + */ + children: (newChild: React.ReactNode) => React.ReactNode; }; function CollectionRow({ @@ -161,7 +167,7 @@ function CollectionRow({ const labelElement = canEdit ? ( <EditableTitle - title={labelText ?? collection.name} + title={labelText ?? collection.displayName} onSubmit={onTitleChange ?? (async () => undefined)} isEditing={isEditing} onEditing={setIsEditing} @@ -170,19 +176,25 @@ function CollectionRow({ ref={editableTitleRef} /> ) : ( - collection.name + collection.displayName ); const iconElement = icon ?? ( <CollectionIcon collection={collection} expanded={expanded} /> ); - const hasMenuContent = Boolean(menu) || canCreateChild; + // Touch devices cannot hover to reveal the actions, so the new doc button + // stays on screen in place of the other actions. + const isTouch = isTouchDevice(); + const showCreateChild = isTouch && !!canCreateChild && !isEditing; + const rowMenu = isTouch ? undefined : menu; + + const hasMenuContent = Boolean(rowMenu) || canCreateChild; const menuVisible = hasMenuContent && !isEditing; const menuElement = menuVisible ? ( <Fade> {canCreateChild && ( - <Tooltip content={t("New doc")} delay={500}> + <Tooltip content={t("New doc")}> <NudeButton aria-label={t("New nested document")} onClick={handleAddChild} @@ -191,7 +203,7 @@ function CollectionRow({ </NudeButton> </Tooltip> )} - {menu} + {rowMenu} </Fade> ) : undefined; @@ -203,10 +215,23 @@ function CollectionRow({ [parentRef, dropRef] ); + const getNavigationItems = React.useCallback( + () => [ + { + id: collection.id, + url: collection.path, + title: collection.displayName, + sidebarContext, + collapsedChildren: expanded ? undefined : collection.sortedDocuments, + }, + ], + [collection, sidebarContext, expanded] + ); + useSidebarNavigation(parentRef, getNavigationItems); + const sidebarLinkElement = ( <SidebarLink - // @ts-expect-error react-router type is wrong, string component is fine. - component={isEditing ? "div" : undefined} + component={isEditing ? StaticLink : undefined} depth={depth} to={to} onClick={onClick} @@ -220,7 +245,7 @@ function CollectionRow({ label={labelElement} ellipsis={!isEditing} exact={false} - $showActions={menuOpen} + $showActions={menuOpen || showCreateChild} menu={menuElement} /> ); @@ -234,26 +259,27 @@ function CollectionRow({ {sidebarLinkElement} </DropToImport> </Relative> - {isAddingNewChild && onCreateChild && ( - <SidebarLink - isActive={() => true} - depth={newChildDepth ?? Math.max(depth + 1, 2)} - ellipsis={false} - label={ - <EditableTitle - title="" - canUpdate - isEditing - placeholder={`${t("New doc")}…`} - onCancel={closeAddingNewChild} - onSubmit={handleNewChildSubmit} - maxLength={DocumentValidation.maxTitleLength} - ref={newChildTitleRef} - /> - } - /> + {children( + isAddingNewChild && onCreateChild ? ( + <SidebarLink + isActive={() => true} + depth={newChildDepth ?? Math.max(depth + 1, 2)} + ellipsis={false} + label={ + <EditableTitle + title="" + canUpdate + isEditing + placeholder={`${t("New doc")}…`} + onCancel={closeAddingNewChild} + onSubmit={handleNewChildSubmit} + maxLength={DocumentValidation.maxTitleLength} + ref={newChildTitleRef} + /> + } + /> + ) : undefined )} - {children} </ActionContextProvider> ); } diff --git a/app/components/Sidebar/components/Collections.tsx b/app/components/Sidebar/components/Collections.tsx index e6adbeadcd..23c31bc3a7 100644 --- a/app/components/Sidebar/components/Collections.tsx +++ b/app/components/Sidebar/components/Collections.tsx @@ -8,8 +8,10 @@ import Flex from "~/components/Flex"; import Error from "~/components/List/Error"; import PaginatedList from "~/components/PaginatedList"; import { createCollection } from "~/actions/definitions/collections"; +import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; import useStores from "~/hooks/useStores"; -import { type DragObject, useDropRef } from "../hooks/useDragAndDrop"; +import { useDropRef } from "~/components/DragAndDrop"; +import type { DragObject } from "../hooks/useDragAndDrop"; import DraggableCollectionLink from "./DraggableCollectionLink"; import DropCursor from "./DropCursor"; import Header from "./Header"; @@ -24,7 +26,8 @@ import usePolicy from "~/hooks/usePolicy"; const headerActions = [createCollection]; function Collections() { - const { documents, auth, collections, policies } = useStores(); + const { auth, collections, policies, ui } = useStores(); + const activeSidebarContext = useActiveSidebarContext() ?? "collections"; const { t } = useTranslation(); const can = usePolicy(auth.team?.id); const orderedCollections = collections.allActive; @@ -70,6 +73,11 @@ function Collections() { options={params} aria-label={t("Collections")} items={orderedCollections} + activeItemId={ + activeSidebarContext === "collections" + ? ui.activeCollectionId + : undefined + } loading={<PlaceholderCollections />} heading={ isDraggingAnyCollection ? ( @@ -99,7 +107,6 @@ function Collections() { <DraggableCollectionLink key={item.id} collection={item} - activeDocument={documents.active} belowCollection={orderedCollections[index + 1]} /> )} diff --git a/app/components/Sidebar/components/Disclosure.tsx b/app/components/Sidebar/components/Disclosure.tsx index 0a2dad9004..60c457da46 100644 --- a/app/components/Sidebar/components/Disclosure.tsx +++ b/app/components/Sidebar/components/Disclosure.tsx @@ -2,7 +2,7 @@ import { CollapsedIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import { extraArea, s } from "@shared/styles"; +import { extraArea, hover, s } from "@shared/styles"; import NudeButton from "~/components/NudeButton"; type Props = React.ComponentProps<typeof Button> & { @@ -34,7 +34,7 @@ const Button = styled(NudeButton)` margin: 2px; ${extraArea(4)} - &:hover { + &:${hover} { color: ${s("text")}; background: ${s("sidebarControlHoverBackground")}; } diff --git a/app/components/Sidebar/components/DismissableSidebarAction.tsx b/app/components/Sidebar/components/DismissableSidebarAction.tsx index 0911f98961..aee76e8d1e 100644 --- a/app/components/Sidebar/components/DismissableSidebarAction.tsx +++ b/app/components/Sidebar/components/DismissableSidebarAction.tsx @@ -35,7 +35,7 @@ export function DismissableSidebarAction({ id, ...rest }: Props) { {...rest} menu={ <Fade> - <Tooltip content={t("Hide")} delay={500}> + <Tooltip content={t("Hide")}> <DismissButton aria-label={t("Hide")} onClick={handleDismiss}> <CloseIcon size={18} /> </DismissButton> diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 34e2660dde..47c6ac3358 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -1,43 +1,38 @@ import type { Location } from "history"; import { observer } from "mobx-react"; import * as React from "react"; -import { useMergeRefs } from "react-merge-refs"; import { useTranslation } from "react-i18next"; import type { match } from "react-router"; import { useHistory } from "react-router-dom"; -import scrollIntoView from "scroll-into-view-if-needed"; import Icon from "@shared/components/Icon"; import type { NavigationNode } from "@shared/types"; import { DocumentPermission, UserPreference } from "@shared/types"; import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper"; -import { sortNavigationNodes } from "@shared/utils/collections"; +import type { FlattenedTreeNode } from "@shared/utils/tree"; import type Collection from "~/models/Collection"; import type Document from "~/models/Document"; import type GroupMembership from "~/models/GroupMembership"; import type UserMembership from "~/models/UserMembership"; import type { RefHandle } from "~/components/EditableTitle"; -import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; import useBoolean from "~/hooks/useBoolean"; import { useComputed } from "~/hooks/useComputed"; import useCurrentUser from "~/hooks/useCurrentUser"; import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction"; -import useOnScreen from "~/hooks/useOnScreen"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import DocumentMenu from "~/menus/DocumentMenu"; import { preloadEditor } from "~/routes/scenes"; import { documentEditPath } from "~/utils/routeHelpers"; +import { DocumentIcon } from "~/components/Icons/DocumentIcon"; import { useDragDocument, useDropToReorderDocument, useDropToReparentDocument, } from "../hooks/useDragAndDrop"; -import { useIsDragActive, useSidebarScrollElement } from "./DragActiveContext"; import { useSidebarExpansion } from "./SidebarExpansionContext"; import DocumentRow from "./DocumentRow"; import DropCursor from "./DropCursor"; -import Folder from "./Folder"; -import { indentForDepth } from "./SidebarLink"; +import { childDepthFor, indentForDepth } from "./SidebarLink"; import type { SidebarContextType } from "./SidebarContext"; import { useSidebarContext } from "./SidebarContext"; @@ -45,18 +40,17 @@ type Props = { node: NavigationNode; collection?: Collection; membership?: UserMembership | GroupMembership; - activeDocument: Document | null | undefined; prefetchDocument?: (documentId: string) => Promise<Document | void>; isDraft?: boolean; depth: number; index: number; parentId?: string; + hasChildren: boolean; /** - * Positions directly after each ancestor whose subtree ends with this node, - * nearest first. They let a drop at the end of an expanded subtree land - * beside an ancestor instead of inside it. + * Ancestors whose subtree ends with this node, nearest first. A drop at the + * end of an expanded subtree can land beside one of them instead of inside. */ - ancestorDropTargets?: DropTarget[]; + trailingAncestors: FlattenedTreeNode[]; }; /** A position in the document tree that a dragged document can be dropped at. */ @@ -66,166 +60,7 @@ type DropTarget = { depth: number; }; -// Approximate rendered row height; used to reserve space for unmounted rows so -// the scroll container stays the right height and IntersectionObserver triggers -// correctly as the user scrolls. -const ROW_HEIGHT = 30; - -// Pre-mount rows just outside the viewport so scrolling stays smooth and drop -// targets exist a screen ahead when a drag starts. -const ROOT_MARGIN = "300px 0px"; - -const DocumentLink = observer(function DocumentLink(props: Props) { - const { node, collection, activeDocument } = props; - const { documents } = useStores(); - const expansion = useSidebarExpansion(); - const expanded = expansion.isExpanded(node.id); - const isActiveDocument = activeDocument && activeDocument.id === node.id; - const hasChildDocuments = - !!node.children.length || activeDocument?.parentDocumentId === node.id; - const sidebarContext = useSidebarContext(); - const activeSidebarContext = useActiveSidebarContext(); - const { fetchChildDocuments } = documents; - - // Keep expansion/data effects on the outer so they run regardless of whether - // the heavy row content is currently mounted. - React.useEffect(() => { - if (expanded && !hasChildDocuments) { - expansion.collapse(node.id); - } - }, [expansion, expanded, hasChildDocuments, node.id]); - - React.useEffect(() => { - if ( - isActiveDocument && - (hasChildDocuments || sidebarContext !== "collections") - ) { - void fetchChildDocuments(node.id); - } - }, [ - fetchChildDocuments, - node.id, - hasChildDocuments, - sidebarContext, - isActiveDocument, - ]); - - const insertDraftChild = !!( - activeDocument?.isDraft && - activeDocument?.isActive && - activeDocument?.parentDocumentId === node.id - ); - - const draftNavNode = insertDraftChild - ? activeDocument?.asNavigationNode - : undefined; - - const nodeChildren = React.useMemo( - () => - collection && draftNavNode - ? sortNavigationNodes( - [draftNavNode, ...node.children], - collection.sort, - false - ) - : node.children, - [draftNavNode, collection, node.children] - ); - - // The last child shares its bottom edge with this node's subtree, so a drop - // there may also target the position after this node or its ancestors. - const lastChildDropTargets = React.useMemo<DropTarget[]>( - () => [ - { - parentDocumentId: props.parentId, - index: props.index + 1, - depth: props.depth, - }, - ...(props.ancestorDropTargets ?? []), - ], - [props.parentId, props.index, props.depth, props.ancestorDropTargets] - ); - - // Visibility gate: only mount the heavy inner content when scrolled near the - // viewport, but keep it mounted while a drag is in progress so the dragged - // source (or a drop target the user is heading toward) isn't yanked. - const scrollRoot = useSidebarScrollElement(); - const placeholderRef = React.useRef<HTMLDivElement>(null); - const observerOptions = React.useMemo( - () => ({ root: scrollRoot, rootMargin: ROOT_MARGIN }), - [scrollRoot] - ); - const [onScreenRef, isOnScreen] = useOnScreen(observerOptions); - const mergedRef = useMergeRefs<HTMLDivElement>([placeholderRef, onScreenRef]); - const isDragActive = useIsDragActive(); - const [mounted, setMounted] = React.useState(false); - - // Flip mount state during render (not in an effect) so the first paint - // already contains the row content when the placeholder is on screen, - // avoiding a blank frame. - if (isOnScreen && !mounted) { - setMounted(true); - } else if (!isOnScreen && !isDragActive && mounted) { - setMounted(false); - } - - // The inner row's own scrollIntoView only fires while it is mounted, which - // skips active documents that are virtualized off-screen. Only scroll the tree - // that matches the navigation context so a document rendered in multiple - // contexts (collections/starred/shared) doesn't jump to an unexpected section; - // when no context is set, fall back to the collections tree alone. - React.useLayoutEffect(() => { - if ( - isActiveDocument && - (activeSidebarContext === sidebarContext || - (!activeSidebarContext && sidebarContext === "collections")) && - placeholderRef.current - ) { - scrollIntoView(placeholderRef.current, { - scrollMode: "if-needed", - behavior: "auto", - boundary: (parent) => parent.id !== "sidebar", - }); - } - }, [isActiveDocument, sidebarContext, activeSidebarContext]); - - return ( - <> - <div ref={mergedRef} style={{ minHeight: ROW_HEIGHT }}> - {mounted ? ( - <DocumentLinkInner {...props} hasChildren={nodeChildren.length > 0} /> - ) : null} - </div> - <Folder expanded={expanded}> - {nodeChildren.map((childNode, childIndex) => ( - <DocumentLink - key={childNode.id} - collection={collection} - membership={props.membership} - node={childNode} - activeDocument={activeDocument} - prefetchDocument={props.prefetchDocument} - isDraft={childNode.isDraft} - depth={props.depth + 1} - index={childIndex} - parentId={node.id} - ancestorDropTargets={ - childIndex === nodeChildren.length - 1 - ? lastChildDropTargets - : undefined - } - /> - ))} - </Folder> - </> - ); -}); - -type InnerProps = Props & { - hasChildren: boolean; -}; - -const DocumentLinkInner = observer(function DocumentLinkInner({ +const DocumentLink = observer(function DocumentLink({ node, collection, membership, @@ -235,8 +70,8 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ index, parentId, hasChildren, - ancestorDropTargets, -}: InnerProps) { + trailingAncestors, +}: Props) { const { documents } = useStores(); const { t } = useTranslation(); const history = useHistory(); @@ -337,11 +172,18 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ const icon = document?.icon || node.icon || node.emoji; const color = document?.color || node.color; const initial = document?.initial || node.title.charAt(0).toUpperCase(); + const isEmpty = document?.isEmpty; + // Rows at the top level of a section show the default icon, so that they + // align with the other rows in the sidebar. const iconElement = React.useMemo( () => - icon ? <Icon value={icon} color={color} initial={initial} /> : undefined, - [icon, color, initial] + icon ? ( + <Icon value={icon} color={color} initial={initial} /> + ) : depth === 0 ? ( + <DocumentIcon empty={isEmpty} /> + ) : undefined, + [icon, color, initial, depth, isEmpty] ); const [{ isDragging }, drag] = useDragDocument( @@ -354,8 +196,8 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ const parentRef = React.useRef<HTMLDivElement>(null); const [{ isOverReparent }, dropToReparent] = useDropToReparentDocument( node, - handleExpand, - parentRef + collection, + handleExpand ); // Fall back so document-only access (e.g. "Manage" on a parent) can reorder. @@ -372,12 +214,19 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ // dragged skips the position after itself, which would be a no-op. const targetsBelow = React.useMemo<DropTarget[]>(() => { if (expanded && hasChildren) { - return [{ parentDocumentId: node.id, index: 0, depth: depth + 1 }]; + return [ + { parentDocumentId: node.id, index: 0, depth: childDepthFor(depth) }, + ]; } const afterSelf = isDragging ? [] : [{ parentDocumentId: parentId, index: index + 1, depth }]; - return [...afterSelf, ...(ancestorDropTargets ?? [])]; + const afterAncestors = trailingAncestors.map((ancestor) => ({ + parentDocumentId: ancestor.parentId, + index: ancestor.index + 1, + depth: ancestor.depth, + })); + return [...afterSelf, ...afterAncestors]; }, [ expanded, hasChildren, @@ -386,7 +235,7 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ parentId, index, depth, - ancestorDropTargets, + trailingAncestors, ]); const title = document?.title || node.title || t("Untitled"); diff --git a/app/components/Sidebar/components/DocumentRow.tsx b/app/components/Sidebar/components/DocumentRow.tsx index 98520bc413..e446f3d803 100644 --- a/app/components/Sidebar/components/DocumentRow.tsx +++ b/app/components/Sidebar/components/DocumentRow.tsx @@ -15,7 +15,8 @@ import useBoolean from "~/hooks/useBoolean"; import { ActionContextProvider } from "~/hooks/useActionContext"; import DropToImport from "./DropToImport"; import Relative from "./Relative"; -import SidebarLink from "./SidebarLink"; +import SidebarLink, { childDepthFor } from "./SidebarLink"; +import { StaticLink } from "./StaticLink"; import type { SidebarContextType } from "./SidebarContext"; import { useSidebarContext } from "./SidebarContext"; import type { ActionFactory, ActionWithChildren } from "~/types"; @@ -93,8 +94,6 @@ export type DocumentRowProps = { canCreateChild?: boolean; /** Submit handler for the inline new-child title input. */ onCreateChild?: (title: string) => Promise<void>; - /** Depth of the inline new-child SidebarLink. Defaults to `depth + 1`. */ - newChildDepth?: number; /** Context menu action for the row. */ contextAction?: ActionWithChildren | ActionFactory; @@ -144,7 +143,6 @@ function DocumentRow({ menuOpen, canCreateChild, onCreateChild, - newChildDepth, contextAction, isActiveOverride, children, @@ -251,8 +249,7 @@ function DocumentRow({ const sidebarLinkElement = ( <SidebarLink - // @ts-expect-error react-router type is wrong, string component is fine. - component={isEditing ? "div" : undefined} + component={isEditing ? StaticLink : undefined} depth={depth} to={to} expanded={hasChildren && !isDragging ? expanded : undefined} @@ -306,7 +303,7 @@ function DocumentRow({ {isAddingNewChild && onCreateChild && ( <SidebarLink isActive={() => true} - depth={newChildDepth ?? depth + 1} + depth={childDepthFor(depth)} ellipsis={false} label={ <EditableTitle diff --git a/app/components/Sidebar/components/DocumentTree.tsx b/app/components/Sidebar/components/DocumentTree.tsx new file mode 100644 index 0000000000..deae349cde --- /dev/null +++ b/app/components/Sidebar/components/DocumentTree.tsx @@ -0,0 +1,306 @@ +import type { Range } from "@tanstack/react-virtual"; +import { defaultRangeExtractor, useVirtualizer } from "@tanstack/react-virtual"; +import { noop } from "es-toolkit/compat"; +import { observer } from "mobx-react"; +import * as React from "react"; +import scrollIntoView from "scroll-into-view-if-needed"; +import type { NavigationNode } from "@shared/types"; +import { sortNavigationNodes } from "@shared/utils/collections"; +import { + flattenExpandedTree, + type FlattenedTreeNode, +} from "@shared/utils/tree"; +import type Collection from "~/models/Collection"; +import type Document from "~/models/Document"; +import type GroupMembership from "~/models/GroupMembership"; +import type UserMembership from "~/models/UserMembership"; +import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; +import { useComputed } from "~/hooks/useComputed"; +import useStores from "~/hooks/useStores"; +import { useScrollMargin } from "../hooks/useScrollMargin"; +import DocumentLink from "./DocumentLink"; +import { useDraggedItemId, useSidebarScrollElement } from "./DragActiveContext"; +import { isActiveSidebarContext, useSidebarContext } from "./SidebarContext"; +import { useSidebarExpansion } from "./SidebarExpansionContext"; +import { useSidebarNavigation } from "./SidebarNavigation"; + +// Approximate rendered row height, rows are measured once mounted. +const ROW_HEIGHT = 30; + +// Mount rows just outside the visible area so that scrolling stays smooth. +const OVERSCAN = 10; + +const estimateSize = () => ROW_HEIGHT; + +const noAdjustment = () => false; + +interface Props { + /** The documents at the root of the tree. */ + nodes: NavigationNode[]; + /** Indentation depth of the root documents. */ + depth: number; + /** Id of the document that contains the root documents, if any. */ + parentId?: string; + /** The collection that the documents belong to, if loaded. */ + collection?: Collection; + /** The membership that grants access to the documents, if any. */ + membership?: UserMembership | GroupMembership; + /** Function to prefetch a document by ID. */ + prefetchDocument?: (documentId: string) => Promise<Document | void>; +} + +/** + * Renders the expanded part of a sidebar document tree as a flat list, and + * mounts only the rows that are near the visible area of the sidebar. + */ +export const DocumentTree = observer(function DocumentTree({ + nodes, + depth, + parentId, + collection, + membership, + prefetchDocument, +}: Props) { + const { documents } = useStores(); + const expansion = useSidebarExpansion(); + const sidebarContext = useSidebarContext(); + const activeSidebarContext = useActiveSidebarContext(); + const scrollElement = useSidebarScrollElement(); + const draggedItemId = useDraggedItemId(); + const containerRef = React.useRef<HTMLDivElement>(null); + const scrollMargin = useScrollMargin(containerRef, scrollElement); + const activeDocument = documents.active; + + // Read on its own so that the rows are not rebuilt when the active document + // changes, unless an open draft is involved. + const activeDraft = useComputed(() => { + const active = documents.active; + return collection && active?.isDraft && active.isActive + ? active + : undefined; + }, [collection, documents]); + + const rows = useComputed( + () => + withChildDepth( + flattenExpandedTree({ + nodes, + depth, + parentId, + isExpanded: (nodeId) => expansion.isExpanded(nodeId), + getChildren: (node) => { + // Show an unpublished draft below its parent while it is open. + if ( + collection && + activeDraft && + activeDraft.parentDocumentId === node.id + ) { + return sortNavigationNodes( + [activeDraft.asNavigationNode, ...node.children], + collection.sort, + false + ); + } + return node.children; + }, + }), + depth + ), + [nodes, depth, parentId, collection, expansion, activeDraft] + ); + + const activeIndex = React.useMemo( + () => rows.findIndex((row) => row.node.id === activeDocument?.id), + [rows, activeDocument?.id] + ); + const draggedIndex = React.useMemo( + () => rows.findIndex((row) => row.node.id === draggedItemId), + [rows, draggedItemId] + ); + + // Keep the active row mounted so that it can scroll into view, and the + // dragged row so that it keeps its dragging state when it scrolls away. + const rangeExtractor = React.useCallback( + (range: Range) => { + const indexes = new Set(defaultRangeExtractor(range)); + for (const index of [activeIndex, draggedIndex]) { + if (index !== -1) { + indexes.add(index); + } + } + return [...indexes].sort((a, b) => a - b); + }, + [activeIndex, draggedIndex] + ); + + const getScrollElement = React.useCallback( + () => scrollElement, + [scrollElement] + ); + const getScrollOffset = React.useCallback( + () => scrollElement?.scrollTop ?? 0, + [scrollElement] + ); + const getItemKey = React.useCallback( + (index: number) => rows[index].node.id, + [rows] + ); + + const virtualizer = useVirtualizer({ + count: rows.length, + getScrollElement, + getItemKey, + estimateSize, + overscan: OVERSCAN, + scrollMargin, + rangeExtractor, + // The virtualizer only learns the offset from scroll events, and scrolls + // to its initial offset when it mounts. Start from the current position + // and never scroll, as the browser and scrollIntoView own the position. + initialOffset: getScrollOffset, + scrollToFn: noop, + }); + + // Rows stay in the normal flow, so the browser's scroll anchoring already + // compensates when a row above the visible area changes size. + virtualizer.shouldAdjustScrollPositionOnItemSizeChange = noAdjustment; + + const virtualItems = virtualizer.getVirtualItems(); + // The virtualizer renders no rows until it has measured the scroll element, + // so the active row can appear a render after the tree mounts. + const isActiveRowRendered = virtualItems.some( + (item) => item.index === activeIndex + ); + const activeNodeId = + activeIndex === -1 ? undefined : rows[activeIndex].node.id; + const activeHasChildren = + activeIndex !== -1 && rows[activeIndex].node.children.length > 0; + const activeParentId = activeDocument?.parentDocumentId; + + // Only scroll the tree that matches the navigation context so a document + // rendered in multiple contexts (collections/starred/shared) doesn't jump to + // an unexpected section; when no context is set, fall back to the collections + // tree alone. + const isScrollContext = isActiveSidebarContext( + sidebarContext, + activeSidebarContext + ); + + React.useLayoutEffect(() => { + const element = containerRef.current?.querySelector( + `[data-index="${activeIndex}"]` + ); + if (isActiveRowRendered && isScrollContext && element) { + scrollIntoView(element, { + scrollMode: "if-needed", + behavior: "auto", + boundary: (parent) => parent.id !== "sidebar", + }); + } + // Scroll when the active row appears, not when rows above it change. + // oxlint-disable-next-line react-hooks/exhaustive-deps + }, [activeNodeId, isActiveRowRendered, isScrollContext]); + + React.useEffect(() => { + if ( + activeNodeId && + (activeHasChildren || sidebarContext !== "collections") + ) { + void documents.fetchChildDocuments(activeNodeId); + } + }, [documents, activeNodeId, activeHasChildren, sidebarContext]); + + const getNavigationItems = React.useCallback( + () => + rows.map((row) => ({ + id: row.node.id, + url: row.node.url, + title: row.node.title, + sidebarContext, + collapsedChildren: expansion.isExpanded(row.node.id) + ? undefined + : row.node.children, + })), + [rows, expansion, sidebarContext] + ); + useSidebarNavigation(containerRef, getNavigationItems); + + // Collapse documents that no longer have children, so that they do not show + // as expanded when a child is added again. + React.useEffect(() => { + for (const row of rows) { + if ( + !row.node.children.length && + row.node.id !== activeParentId && + expansion.isExpanded(row.node.id) + ) { + expansion.collapse(row.node.id); + } + } + }, [rows, expansion, activeParentId]); + + // Rows outside of the rendered range are replaced by spacers of the same + // height, so that the rows keep their place in the normal document flow. + let offset = 0; + const items = virtualItems.map((item) => { + const row = rows[item.index]; + const start = item.start - virtualizer.options.scrollMargin; + const gap = start - offset; + offset = start + item.size; + + return ( + <React.Fragment key={item.key}> + {gap > 0 && <div style={{ height: gap }} />} + <div data-index={item.index} ref={virtualizer.measureElement}> + <DocumentLink + node={row.node} + collection={collection} + membership={membership} + prefetchDocument={prefetchDocument} + isDraft={row.node.isDraft} + depth={row.depth} + index={row.index} + parentId={row.parentId} + hasChildren={row.hasChildren} + trailingAncestors={row.trailingAncestors} + /> + </div> + </React.Fragment> + ); + }); + const remainder = virtualizer.getTotalSize() - offset; + + // The container stays mounted while the tree is empty, so that its scroll + // margin is already tracked when the first rows are added. + return ( + <div ref={containerRef}> + {items} + {remainder > 0 && <div style={{ height: remainder }} />} + </div> + ); +}); + +/** + * Moves the descendants of root rows at depth 0 one level deeper, so that the + * rows match childDepthFor. + * + * @param rows The flattened rows of the tree. + * @param depth The depth of the root rows. + * @returns the rows with adjusted depths. + */ +function withChildDepth( + rows: FlattenedTreeNode[], + depth: number +): FlattenedTreeNode[] { + if (depth !== 0) { + return rows; + } + + const adjust = (row: FlattenedTreeNode): FlattenedTreeNode => + row.depth === 0 ? row : { ...row, depth: row.depth + 1 }; + + return rows.map((row) => ({ + ...adjust(row), + trailingAncestors: row.trailingAncestors.map(adjust), + })); +} diff --git a/app/components/Sidebar/components/DragActiveContext.tsx b/app/components/Sidebar/components/DragActiveContext.tsx index a4de11d3d3..cda9c5d203 100644 --- a/app/components/Sidebar/components/DragActiveContext.tsx +++ b/app/components/Sidebar/components/DragActiveContext.tsx @@ -1,13 +1,13 @@ import * as React from "react"; -import { useDragLayer } from "react-dnd"; +import { useDragLayer } from "~/components/DragAndDrop"; -const DragActiveContext = React.createContext(false); +const DraggedItemContext = React.createContext<string | undefined>(undefined); const SidebarScrollContext = React.createContext<HTMLElement | null>(null); /** - * Provides the sidebar's scroll container so descendants can use it as the - * IntersectionObserver root when deciding whether to render heavy content. + * Provides the sidebar's scroll container so descendants can virtualize their + * content against it. */ export const SidebarScrollProvider = SidebarScrollContext.Provider; @@ -20,18 +20,21 @@ export function useSidebarScrollElement(): HTMLElement | null { } /** - * Subscribes once to react-dnd's drag state and exposes a boolean via context. + * Subscribes once to the drag state and exposes the id of the dragged item via + * context. * - * Visibility-gated sidebar rows read this to keep their inner content mounted - * for the duration of a drag, so that scrolling away from the dragged source - * (or a drop target the user is heading toward) does not unmount it mid-drag. + * Virtualized sidebar trees read this to keep the dragged row mounted for the + * duration of a drag, so that the row keeps its dragging state. */ export function DragActiveProvider({ children, }: { children: React.ReactNode; }) { - const isDragging = useDragLayer((monitor) => monitor.isDragging()); + const { isDragging, itemId } = useDragLayer((monitor) => ({ + isDragging: monitor.isDragging(), + itemId: monitor.getItem()?.id, + })); // Expose drag state to CSS so per-row UI (e.g. the hover actions slot) can // be hidden for the duration of a drag without re-rendering @@ -41,15 +44,16 @@ export function DragActiveProvider({ }, [isDragging]); return ( - <DragActiveContext.Provider value={isDragging}> + <DraggedItemContext.Provider value={itemId}> {children} - </DragActiveContext.Provider> + </DraggedItemContext.Provider> ); } /** - * Returns whether any react-dnd drag is currently active. + * Returns the id of the item being dragged, or undefined when no drag is in + * progress. */ -export function useIsDragActive(): boolean { - return React.useContext(DragActiveContext); +export function useDraggedItemId(): string | undefined { + return React.useContext(DraggedItemContext); } diff --git a/app/components/Sidebar/components/DragPlaceholder.tsx b/app/components/Sidebar/components/DragPlaceholder.tsx index 1631cabcc9..09340f0e57 100644 --- a/app/components/Sidebar/components/DragPlaceholder.tsx +++ b/app/components/Sidebar/components/DragPlaceholder.tsx @@ -1,9 +1,7 @@ import * as React from "react"; -import type { XYCoord } from "react-dnd"; -import { useDragLayer } from "react-dnd"; -import { NativeTypes } from "react-dnd-html5-backend"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; +import { useDragFollower, useDragLayer } from "~/components/DragAndDrop"; import useStores from "~/hooks/useStores"; import SidebarLink from "./SidebarLink"; @@ -17,56 +15,26 @@ const layerStyles: React.CSSProperties = { height: "100%", }; -// Browser-native drags (files, text, or ProseMirror nodes leaving the editor) -// are tracked by react-dnd too, but they are not sidebar items. -const nativeItemTypes = new Set<string | symbol>(Object.values(NativeTypes)); - // Keep the ghost beside the pointer so it never covers the drop cursor. const POINTER_OFFSET_X = 12; const POINTER_OFFSET_Y = 14; -function getItemStyles(pointerOffset: XYCoord | null, sidebarWidth: number) { - if (!pointerOffset) { - return { - display: "none", - }; - } - const x = pointerOffset.x + POINTER_OFFSET_X; - const y = pointerOffset.y - POINTER_OFFSET_Y; - - const transform = `translate(${x}px, ${y}px)`; - return { - width: sidebarWidth - 24, - transform, - WebkitTransform: transform, - }; -} - const DragPlaceholder = () => { const { t } = useTranslation(); const { ui } = useStores(); + const followPointer = useDragFollower(POINTER_OFFSET_X, -POINTER_OFFSET_Y); - const { isDragging, item, itemType, pointerOffset } = useDragLayer( - (monitor) => ({ - item: monitor.getItem(), - itemType: monitor.getItemType(), - pointerOffset: monitor.getClientOffset(), - isDragging: monitor.isDragging(), - }) - ); + const { item } = useDragLayer((monitor) => ({ + item: monitor.getItem(), + })); - if ( - !isDragging || - !pointerOffset || - !itemType || - nativeItemTypes.has(itemType) - ) { + if (!item) { return null; } return ( <div style={layerStyles}> - <div style={getItemStyles(pointerOffset, ui.sidebarWidth)}> + <div ref={followPointer} style={{ width: ui.sidebarWidth - 24 }}> <GhostLink icon={item.icon} label={item.title || t("Untitled")} diff --git a/app/components/Sidebar/components/DraggableCollectionLink.tsx b/app/components/Sidebar/components/DraggableCollectionLink.tsx index c6f53bc14b..e1f0b5b1fb 100644 --- a/app/components/Sidebar/components/DraggableCollectionLink.tsx +++ b/app/components/Sidebar/components/DraggableCollectionLink.tsx @@ -2,14 +2,13 @@ import fractionalIndex from "fractional-index"; import { observer } from "mobx-react"; import type * as React from "react"; import { useState, useEffect, useCallback } from "react"; -import { getEmptyImage } from "react-dnd-html5-backend"; import styled from "styled-components"; import type Collection from "~/models/Collection"; -import type Document from "~/models/Document"; +import { useDragRef, useDropRef } from "~/components/DragAndDrop"; import CollectionIcon from "~/components/Icons/CollectionIcon"; import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; +import { useComputed } from "~/hooks/useComputed"; import useStores from "~/hooks/useStores"; -import { useDragRef, useDropRef } from "../hooks/useDragAndDrop"; import CollectionLink from "./CollectionLink"; import DropCursor from "./DropCursor"; import SidebarDisclosureContext, { @@ -20,7 +19,6 @@ import { useSidebarContext } from "./SidebarContext"; type Props = { collection: Collection; - activeDocument: Document | undefined; belowCollection: Collection | void; }; @@ -30,17 +28,22 @@ interface CollectionDragItem { icon: React.ReactNode; } -function DraggableCollectionLink({ - collection, - activeDocument, - belowCollection, -}: Props) { - const activeSidebarContext = useActiveSidebarContext(); +function DraggableCollectionLink({ collection, belowCollection }: Props) { + const activeSidebarContext = useActiveSidebarContext() ?? "collections"; const sidebarContext = useSidebarContext(); const { ui, policies, collections } = useStores(); + // Computed so that only the collections that become active or inactive + // re-render when navigating. + const isActiveCollection = useComputed( + () => collection.id === ui.activeCollectionId, + [collection, ui] + ); + const activeDocumentId = useComputed( + () => (isActiveCollection ? ui.activeDocumentId : undefined), + [isActiveCollection, ui] + ); const [expanded, setExpanded] = useState( - collection.id === ui.activeCollectionId && - sidebarContext === activeSidebarContext + isActiveCollection && sidebarContext === activeSidebarContext ); const belowCollectionIndex = belowCollection ? belowCollection.index : null; @@ -54,7 +57,6 @@ function DraggableCollectionLink({ dropToReorderCollection, ] = useDropRef< CollectionDragItem, - void, { isCollectionDropping: boolean; isDraggingAnyCollection: boolean } >({ accept: "collection", @@ -75,34 +77,24 @@ function DraggableCollectionLink({ }); // Drag to reorder collection - const [{ isDragging }, dragToReorderCollection, preview] = useDragRef({ + const [isDragging, dragToReorderCollection] = useDragRef({ type: "collection", item: () => ({ id: collection.id, - title: collection.name, + title: collection.displayName, icon: <CollectionIcon collection={collection} />, }), - collect: (monitor) => ({ - isDragging: monitor.isDragging(), - }), }); - useEffect(() => { - preview(getEmptyImage(), { captureDraggingState: false }); - }, [preview]); - // If the current collection is active and relevant to the sidebar section we // are in then expand it automatically useEffect(() => { - if ( - collection.id === ui.activeCollectionId && - sidebarContext === activeSidebarContext - ) { + if (isActiveCollection && sidebarContext === activeSidebarContext) { setExpanded(true); } }, [ - collection.id, - ui.activeCollectionId, + isActiveCollection, + activeDocumentId, sidebarContext, activeSidebarContext, ]); @@ -131,7 +123,6 @@ function DraggableCollectionLink({ <CollectionLink collection={collection} expanded={displayChildDocuments} - activeDocument={activeDocument} onDisclosureClick={handleDisclosureClick} isDraggingAnyCollection={isDraggingAnyCollection} /> diff --git a/app/components/Sidebar/components/DraggableSection.tsx b/app/components/Sidebar/components/DraggableSection.tsx index 29577e158b..5cc1db89e4 100644 --- a/app/components/Sidebar/components/DraggableSection.tsx +++ b/app/components/Sidebar/components/DraggableSection.tsx @@ -2,7 +2,6 @@ import { observer } from "mobx-react"; import { createContext, useCallback, - useEffect, useMemo, useState, type ReactNode, @@ -112,6 +111,7 @@ function DraggableSection({ section, children }: Props) { [SidebarSection.Starred]: t("Starred"), [SidebarSection.SharedWithMe]: t("Shared with me"), [SidebarSection.Collections]: t("Collections"), + [SidebarSection.Personal]: t("Personal"), }; const order = normalizeSidebarSectionOrder( @@ -205,12 +205,6 @@ function DraggableSection({ section, children }: Props) { (dragged) => moveSidebarSection(order, dragged, "after", section) ); - // The drop cursors and the drag styling must not appear inside the - // browser's dragstart dispatch — Chromium aborts the drag when the element - // under the drag origin changes before the drag session starts. - const showCursors = useDeferredFlag(bottomProps.isDragging); - const isDraggingDeferred = useDeferredFlag(isDragging); - const contextValue = useMemo( () => ({ dragRef, menuActions }), [dragRef, menuActions] @@ -218,19 +212,19 @@ function DraggableSection({ section, children }: Props) { return ( <SectionWrapper ref={setWrapper} data-section={section}> - {showCursors && ( + {bottomProps.isDragging && ( <TopDropCursor isActiveDrop={topProps.isOverCursor} innerRef={dropTopRef} position="top" /> )} - <Draggable $isDragging={isDraggingDeferred}> + <Draggable $isDragging={isDragging}> <SidebarSectionContext.Provider value={contextValue}> {children} </SidebarSectionContext.Provider> </Draggable> - {showCursors && ( + {bottomProps.isDragging && ( <SectionDropCursor isActiveDrop={bottomProps.isOverCursor} innerRef={dropBottomRef} @@ -240,28 +234,6 @@ function DraggableSection({ section, children }: Props) { ); } -/** - * Returns the given flag with its rising edge deferred by one task. A falling - * edge resets immediately. - * - * @param value The flag to defer. - * @returns the deferred flag. - */ -function useDeferredFlag(value: boolean): boolean { - const [deferred, setDeferred] = useState(false); - - useEffect(() => { - if (!value) { - setDeferred(false); - return undefined; - } - const timer = setTimeout(() => setDeferred(true), 0); - return () => clearTimeout(timer); - }, [value]); - - return deferred; -} - const Draggable = styled.div<{ $isDragging: boolean }>` display: flex; flex-direction: column; diff --git a/app/components/Sidebar/components/DropCursor.tsx b/app/components/Sidebar/components/DropCursor.tsx index a32b4e9642..0f5a100382 100644 --- a/app/components/Sidebar/components/DropCursor.tsx +++ b/app/components/Sidebar/components/DropCursor.tsx @@ -3,7 +3,7 @@ import styled from "styled-components"; type Props = { isActiveDrop: boolean; - innerRef: React.Ref<HTMLDivElement>; + innerRef?: React.Ref<HTMLDivElement>; position?: "top"; /** Inline-start offset of the visible line in pixels, to match a tree depth. */ indent?: number; @@ -53,7 +53,7 @@ const Cursor = styled.div<{ background: transparent; ${(props) => (props.position === "top" ? "top: -7px;" : "bottom: -7px;")} - ::after { + &::after { background: ${(props) => props.theme.accent}; position: absolute; top: 6px; diff --git a/app/components/Sidebar/components/DropToImport.tsx b/app/components/Sidebar/components/DropToImport.tsx index 31cdb89852..f691bf303a 100644 --- a/app/components/Sidebar/components/DropToImport.tsx +++ b/app/components/Sidebar/components/DropToImport.tsx @@ -1,13 +1,12 @@ import { VisuallyHidden } from "@radix-ui/react-visually-hidden"; import invariant from "invariant"; import { observer } from "mobx-react"; -import { useCallback, useState } from "react"; +import { useCallback, useSyncExternalStore } from "react"; import Dropzone from "react-dropzone"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled, { css } from "styled-components"; import LoadingIndicator from "~/components/LoadingIndicator"; -import useEventListener from "~/hooks/useEventListener"; import useImportDocument from "~/hooks/useImportDocument"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; @@ -20,30 +19,38 @@ type Props = { activeClassName?: string; }; -function DropToImport({ disabled, children, collectionId, documentId }: Props) { +/** + * Wraps sidebar content in a dropzone that imports the files dropped on it. + * The dropzone is only prepared once files are dragged into the window. + */ +function DropToImport(props: Props) { + const hasDraggedFiles = useSyncExternalStore( + subscribeToFileDrag, + getHasDraggedFiles + ); + invariant( + props.collectionId || props.documentId, + "Must provide either collectionId or documentId" + ); + + if (props.disabled || !hasDraggedFiles) { + return props.children; + } + + return <ImportDropzone {...props} />; +} + +const ImportDropzone = observer(function ImportDropzone({ + children, + collectionId, + documentId, +}: Props) { const { t } = useTranslation(); const { documents } = useStores(); - const [prerender, setPreRendered] = useState(false); const { handleFiles, isImporting } = useImportDocument( collectionId, documentId ); - invariant( - collectionId || documentId, - "Must provide either collectionId or documentId" - ); - - // Only prepare the dropzone for OS file drags, internal react-dnd drags - // fire native dragenter too - useEventListener("dragenter", (event: Event) => { - if ( - typeof DragEvent !== "undefined" && - event instanceof DragEvent && - Array.from(event.dataTransfer?.types ?? []).includes("Files") - ) { - setPreRendered(true); - } - }); const canCollection = usePolicy(collectionId); const canDocument = usePolicy(documentId); @@ -53,8 +60,6 @@ function DropToImport({ disabled, children, collectionId, documentId }: Props) { }, [t]); if ( - disabled || - !prerender || (collectionId && !canCollection.createDocument) || (documentId && !canDocument.createChildDocument) ) { @@ -63,11 +68,12 @@ function DropToImport({ disabled, children, collectionId, documentId }: Props) { return ( <Dropzone - accept={documents.importFileTypesString} + accept={documents.importFileTypesAccept} onDropAccepted={handleFiles} onDropRejected={handleRejection} noClick multiple + noPaste > {({ getRootProps, getInputProps, isDragActive }) => ( <DropzoneContainer @@ -87,7 +93,37 @@ function DropToImport({ disabled, children, collectionId, documentId }: Props) { )} </Dropzone> ); -} +}); + +let hasDraggedFiles = false; +const fileDragListeners = new Set<() => void>(); + +// Only prepare dropzones for OS file drags, text and editor content drags fire +// native dragenter too. +const handleDragEnter = (event: DragEvent) => { + if (!Array.from(event.dataTransfer?.types ?? []).includes("Files")) { + return; + } + hasDraggedFiles = true; + window.removeEventListener("dragenter", handleDragEnter); + fileDragListeners.forEach((listener) => listener()); +}; + +const subscribeToFileDrag = (listener: () => void) => { + if (!hasDraggedFiles && !fileDragListeners.size) { + window.addEventListener("dragenter", handleDragEnter); + } + fileDragListeners.add(listener); + + return () => { + fileDragListeners.delete(listener); + if (!fileDragListeners.size) { + window.removeEventListener("dragenter", handleDragEnter); + } + }; +}; + +const getHasDraggedFiles = () => hasDraggedFiles; const DropzoneContainer = styled.div<{ $isDragActive: boolean }>` border-radius: 4px; @@ -106,4 +142,4 @@ const DropzoneContainer = styled.div<{ $isDragActive: boolean }>` `} `; -export default observer(DropToImport); +export default DropToImport; diff --git a/app/components/Sidebar/components/GroupLink.tsx b/app/components/Sidebar/components/GroupLink.tsx index b3067ccda7..32fadf7ea4 100644 --- a/app/components/Sidebar/components/GroupLink.tsx +++ b/app/components/Sidebar/components/GroupLink.tsx @@ -1,7 +1,7 @@ import { observer } from "mobx-react"; -import { GroupIcon } from "outline-icons"; import * as React from "react"; import type Group from "~/models/Group"; +import { ResolvedGroupIcon } from "~/components/Icons/GroupIcon"; import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; import Folder from "./Folder"; import Relative from "./Relative"; @@ -49,7 +49,7 @@ const GroupLink: React.FC<Props> = ({ group }) => { <Relative> <SidebarLink label={group.name} - icon={<GroupIcon />} + icon={<ResolvedGroupIcon group={group} />} expanded={expanded} onClick={handleDisclosureClick} depth={0} diff --git a/app/components/Sidebar/components/Header.tsx b/app/components/Sidebar/components/Header.tsx index f8b5736742..fd542e4226 100644 --- a/app/components/Sidebar/components/Header.tsx +++ b/app/components/Sidebar/components/Header.tsx @@ -95,7 +95,6 @@ export const Header: React.FC<Props> = ({ hideOnActionDisabled tooltip={{ content: resolve<string>(primaryAction.name, actionContext), - delay: 500, }} > {resolve<React.ReactNode>(primaryAction.icon, actionContext)} 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<typeof Flex>) { 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 b19cbef993..3e6f1c54a0 100644 --- a/app/components/Sidebar/components/NavLink.tsx +++ b/app/components/Sidebar/components/NavLink.tsx @@ -233,9 +233,9 @@ const NavLink = observer(function NavLink({ event.preventDefault(); } - // Fire onActiveClick on click rather than mousedown so that the native - // HTML5 drag gesture can initiate from an active row without being - // blocked by a preventDefault on mousedown. + // Fire onActiveClick on click rather than mousedown so that a drag can + // start from an active row without being blocked by a preventDefault on + // mousedown. if (isActive && wasActive) { onActiveClick?.(event); } 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<RefHandle>(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: <PlusIcon />, + 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<SidebarContextType>) => context === "personal", + [] + ), + useCallback( + (activeDocumentId: string) => + collectionId && + documents.get(activeDocumentId)?.collectionId === collectionId + ? "personal" + : undefined, + [documents, collectionId] + ) + ); + + if (!collection && !canCreate) { + return null; + } + + const newDocRow = + isAddingNew && canCreate ? ( + <SidebarLink + isActive={() => true} + depth={0} + icon={<DocumentIcon />} + ellipsis={false} + label={ + <EditableTitle + title="" + canUpdate + isEditing + placeholder={`${t("New doc")}…`} + onCancel={closeAddingNew} + onSubmit={handleNewDocSubmit} + maxLength={DocumentValidation.maxTitleLength} + ref={newTitleRef} + /> + } + /> + ) : null; + + return ( + <SidebarContext.Provider value="personal"> + <ActionContextProvider value={{ activeModels }}> + <Flex column> + <Header + id="personal" + title={t("Personal")} + actions={headerActions} + primaryAction={canCreate ? newDocAction : undefined} + > + <Relative> + {collection ? ( + <CollectionLinkChildren + collection={collection} + expanded + childDepth={0} + prefetchDocument={documents.prefetchDocument} + > + {newDocRow} + </CollectionLinkChildren> + ) : ( + newDocRow + )} + <SidebarAction action={newDocAction} depth={0} /> + </Relative> + </Header> + </Flex> + </ActionContextProvider> + </SidebarContext.Provider> + ); +}); 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..dc49d68837 100644 --- a/app/components/Sidebar/components/SharedWithMeLink.tsx +++ b/app/components/Sidebar/components/SharedWithMeLink.tsx @@ -3,15 +3,21 @@ import type { Location } from "history"; import { observer } from "mobx-react"; import * as React from "react"; import type { match } from "react-router"; -import { IconType, NotificationEventType } from "@shared/types"; +import { useHistory } from "react-router-dom"; +import { IconType, NotificationEventType, UserPreference } from "@shared/types"; +import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper"; import { determineIconType } from "@shared/utils/icon"; 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 useCurrentUser from "~/hooks/useCurrentUser"; +import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import DocumentMenu from "~/menus/DocumentMenu"; import * as Scenes from "~/routes/scenes"; +import { documentEditPath } from "~/utils/routeHelpers"; import { useDragMembership, useDropToReorderUserMembership, @@ -21,7 +27,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 +36,8 @@ import SidebarDisclosureContext, { useSidebarDisclosureState, } from "./SidebarDisclosureContext"; import { useSidebarContext, type SidebarContextType } from "./SidebarContext"; +import { childDepthFor } from "./SidebarLink"; +import { useSidebarNavigation } from "./SidebarNavigation"; type Props = { membership: UserMembership | GroupMembership; @@ -41,19 +49,26 @@ 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 can = usePolicy(document); + const history = useHistory(); + const user = useCurrentUser(); 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 @@ -116,6 +131,45 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { ] ); + const handleNewDoc = React.useCallback( + async (input: string) => { + if (!document) { + return; + } + const newDocument = await documents.create( + { + collectionId: document.collectionId ?? undefined, + parentDocumentId: document.id, + fullWidth: + document.fullWidth ?? + user.getPreference(UserPreference.FullWidthDocuments), + title: input, + data: ProsemirrorDataHelper.getEmpty(), + }, + { publish: true } + ); + if (newDocument.collectionId) { + collections + .get(newDocument.collectionId) + ?.addDocument(newDocument, document.id); + } + membership.addDocument(newDocument, document.id); + history.push({ + pathname: documentEditPath(newDocument), + state: { sidebarContext }, + }); + }, + [ + documents, + collections, + document, + membership, + sidebarContext, + user, + history, + ] + ); + const parentRef = React.useRef<HTMLDivElement>(null); const reparentableNode = React.useMemo( () => document?.asNavigationNode, @@ -123,8 +177,8 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { ); const [{ isOverReparent }, dropToReparent] = useDropToReparentDocument( reparentableNode, - setExpanded, - parentRef + undefined, + setExpanded ); const { icon } = useSidebarLabelAndIcon(membership); @@ -150,6 +204,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 +231,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,35 +274,36 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { parentRef={parentRef} dropToReparentRef={dropToReparent} isActiveDropTarget={isOverReparent} + cursorAfter={ + reorderProps.isDragging ? ( + <DropCursor + isActiveDrop={reorderProps.isOverCursor} + innerRef={dropToReorderRef} + /> + ) : undefined + } menu={menu} menuOpen={menuOpen} + canCreateChild={can.createChildDocument} + onCreateChild={handleNewDoc} isActiveOverride={isActive} > <SidebarDisclosureContext.Provider value={disclosureEvent}> <SidebarExpansionContext.Provider value={expansion}> <Folder expanded={displayChildDocuments}> - {childDocuments.map((childNode, index) => ( - <DocumentLink - key={childNode.id} - node={childNode} - collection={collection} - membership={membership} - activeDocument={documents.active} - isDraft={childNode.isDraft} - depth={depth + 1} - index={index} - parentId={document.id} - /> - ))} + <DocumentTree + nodes={childDocuments} + depth={childDepthFor(depth)} + parentId={document.id} + collection={collection} + membership={membership} + // Loads the document and its policies on hover, without which + // rows that were never opened cannot be dragged or dropped on. + prefetchDocument={documents.prefetchDocument} + /> </Folder> </SidebarExpansionContext.Provider> </SidebarDisclosureContext.Provider> - {reorderProps.isDragging && ( - <DropCursor - isActiveDrop={reorderProps.isOverCursor} - innerRef={dropToReorderRef} - /> - )} </DocumentRow> ); } diff --git a/app/components/Sidebar/components/SidebarActions.tsx b/app/components/Sidebar/components/SidebarActions.tsx index aa305f6134..571950b193 100644 --- a/app/components/Sidebar/components/SidebarActions.tsx +++ b/app/components/Sidebar/components/SidebarActions.tsx @@ -1,14 +1,15 @@ import styled, { css } from "styled-components"; import EventBoundary from "@shared/components/EventBoundary"; -import { s } from "@shared/styles"; +import { hover, 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. + * the row itself for a context menu, a descendant button for a dropdown. On + * touch devices `:hover` sticks after a tap, so only `:active` is matched. */ -export const hoveredOrMenuOpen = `&:hover, &:active, &[data-state="open"], &:has([data-state="open"])`; +export const hoveredOrMenuOpen = `&:${hover}, &:active, &[data-state="open"], &:has([data-state="open"])`; /** * Trailing action buttons for a sidebar row. Hidden until the row reveals @@ -25,7 +26,7 @@ export const SidebarActions = styled(EventBoundary)<{ margin-block: auto; height: 24px; color: ${s("textTertiary")}; - background: var(--background); + background: var(--background, ${s("sidebarBackground")}); transition: opacity 50ms; [data-drag-active] & { diff --git a/app/components/Sidebar/components/SidebarButton.tsx b/app/components/Sidebar/components/SidebarButton.tsx index 5e114e6379..11d9fae736 100644 --- a/app/components/Sidebar/components/SidebarButton.tsx +++ b/app/components/Sidebar/components/SidebarButton.tsx @@ -2,7 +2,7 @@ import { MoreIcon } from "outline-icons"; import { observer } from "mobx-react"; import * as React from "react"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { extraArea, hover, s } from "@shared/styles"; import Flex from "~/components/Flex"; import Text from "~/components/Text"; @@ -10,7 +10,10 @@ import { draggableOnDesktop, undraggableOnDesktop } from "~/styles"; import Desktop from "~/utils/Desktop"; import { HStack } from "~/components/primitives/HStack"; -export type SidebarButtonProps = React.ComponentProps<typeof Button> & { +export type SidebarButtonProps = Omit< + React.ButtonHTMLAttributes<HTMLButtonElement>, + "title" +> & { position?: "top" | "bottom"; title?: React.ReactNode; image: React.ReactNode; 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<string>(); + expandedIds = observable.map<string, true>(); 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<string>): 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 d0001d626c..1c5211788a 100644 --- a/app/components/Sidebar/components/SidebarLink.tsx +++ b/app/components/Sidebar/components/SidebarLink.tsx @@ -1,7 +1,7 @@ import type { LocationDescriptor } from "history"; import * as React from "react"; import styled, { useTheme, css } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { ellipsis, hover, s } from "@shared/styles"; import { isMobile } from "@shared/utils/browser"; import { UnreadBadge } from "~/components/UnreadBadge"; @@ -30,6 +30,17 @@ 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. @@ -44,7 +55,7 @@ type Props = Omit<NavLinkProps, "to"> & { /** Callback fired when the link is clicked */ onClick?: React.MouseEventHandler<HTMLAnchorElement>; /** Callback when we expect the user to click on the link. Used for prefetching data. */ - onClickIntent?: React.MouseEventHandler<HTMLElement>; + onClickIntent?: () => void; /** Callback fired when the disclosure icon is clicked */ onDisclosureClick?: React.MouseEventHandler<HTMLElement>; /** Icon to display on the left side of the link */ @@ -81,9 +92,8 @@ const activeDropStyle = { fontWeight: 600, }; -// Prevents the parent NavLink's mousedown handler from firing (which would -// navigate or toggle), without calling preventDefault — that would block the -// native HTML5 drag from initiating on the draggable row. +// Prevents the parent NavLink's mousedown handler from firing, which would +// navigate or toggle. const stopPropagation = (ev: React.MouseEvent) => { ev.stopPropagation(); }; @@ -195,7 +205,7 @@ function SidebarLink({ ) : ( content )} - {isInteractive && menu && ( + {(isInteractive || $showActions) && menu && ( <SidebarActions $showActions={$showActions}>{menu}</SidebarActions> )} </> @@ -227,6 +237,7 @@ function SidebarLink({ return ( <Link + as={NavLink} $isActiveDrop={isActiveDrop} $isDraft={isDraft} $disabled={disabled} @@ -243,7 +254,6 @@ function SidebarLink({ to={to!} href={href} className={className} - // @ts-expect-error spread props cause overload mismatch with styled NavLink ref={ref} {...rest} > @@ -269,15 +279,15 @@ const Content = styled.span` min-width: 0; `; +// 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; @@ -290,7 +300,14 @@ const Link = styled(NavLink)<{ --background: ${s("sidebarActiveBackground")}; } - ${(props) => props.$isActiveDrop && `--background: ${props.theme.slateDark};`} + ${(props) => + props.$isActiveDrop && + css` + &, + ${hoveredOrMenuOpen} { + --background: ${props.theme.slateDark}; + } + `} display: flex; position: relative; @@ -339,12 +356,11 @@ const Link = styled(NavLink)<{ &: ${hover}, &:has([data-state="open"]) { ${HiddenDisclosure} { - display: block; + opacity: 1; } ${HiddenDisclosure} + ${IconWrapper} { visibility: hidden; opacity: 0; - width: 0; } } 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<SidebarNavigationItem, "url" | "title"> = 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 ( + <SidebarNavigationContext.Provider value={registry}> + {children} + </SidebarNavigationContext.Provider> + ); + } +); + +/** + * 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<HTMLElement | null>, + 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<HTMLElement | null>; + 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<RegistryEntry>(); +} + +const SidebarNavigationContext = + React.createContext<SidebarNavigationRegistry | null>(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 5eb2ca58ca..d582ba9e2b 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<HTMLDivElement>(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} @@ -220,7 +235,6 @@ const StarredDocumentLink = observer(function StarredDocumentLink({ menuOpen={menuOpen} canCreateChild={can.createChildDocument} onCreateChild={handleNewDoc} - newChildDepth={2} contextAction={contextMenuAction} isActiveOverride={isActive} onClickIntent={handlePrefetch} @@ -229,19 +243,13 @@ const StarredDocumentLink = observer(function StarredDocumentLink({ <SidebarExpansionContext.Provider value={expansion}> <Relative> <Folder expanded={displayChildDocuments}> - {childDocuments.map((node, index) => ( - <DocumentLink - key={node.id} - node={node} - collection={documentCollection} - activeDocument={documents.active} - prefetchDocument={documents.prefetchDocument} - isDraft={node.isDraft} - depth={2} - index={index} - parentId={document.id} - /> - ))} + <DocumentTree + nodes={childDocuments} + depth={2} + parentId={document.id} + collection={documentCollection} + prefetchDocument={documents.prefetchDocument} + /> </Folder> {cursor} </Relative> @@ -286,8 +294,7 @@ const StarredCollectionLink = observer(function StarredCollectionLink({ const parentRef = React.useRef<HTMLDivElement>(null); const [{ isOver, canDrop }, dropRef] = useDropToChangeCollection( collection, - handleExpand, - parentRef + handleExpand ); const handleRename = React.useCallback(() => { @@ -344,7 +351,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 +363,15 @@ const StarredCollectionLink = observer(function StarredCollectionLink({ dropRef={dropRef} isActiveDropTarget={isOver && canDrop} > - <CollectionLinkChildren - collection={collection} - expanded={displayChildDocuments} - prefetchDocument={documents.prefetchDocument} - /> + {(newChild) => ( + <CollectionLinkChildren + collection={collection} + expanded={displayChildDocuments} + prefetchDocument={documents.prefetchDocument} + > + {newChild} + </CollectionLinkChildren> + )} </CollectionRow> </Draggable> <Relative>{cursor}</Relative> @@ -378,33 +389,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, ]); @@ -456,21 +473,31 @@ function StarredLink({ star }: Props) { const [reorderStarProps, dropToReorderRef] = useDropToReorderStar(getIndex); const [createStarProps, dropToStarRef] = useDropToCreateStar(getIndex); - const cursor = ( - <> - {reorderStarProps.isDragging && ( - <DropCursor - isActiveDrop={reorderStarProps.isOverCursor} - innerRef={dropToReorderRef} - /> - )} - {createStarProps.isDragging && ( - <DropCursor - isActiveDrop={createStarProps.isOverCursor} - innerRef={dropToStarRef} - /> - )} - </> + const cursor = React.useMemo( + () => ( + <> + {reorderStarProps.isDragging && ( + <DropCursor + isActiveDrop={reorderStarProps.isOverCursor} + innerRef={dropToReorderRef} + /> + )} + {createStarProps.isDragging && ( + <DropCursor + isActiveDrop={createStarProps.isOverCursor} + innerRef={dropToStarRef} + /> + )} + </> + ), + [ + 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<HTMLDivElement> { + /** 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<HTMLDivElement>; +} + +/** + * 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 <div ref={innerRef} {...rest} />; +} diff --git a/app/components/Sidebar/components/TrashLink.tsx b/app/components/Sidebar/components/TrashLink.tsx index 77fc4e9286..72fc24670f 100644 --- a/app/components/Sidebar/components/TrashLink.tsx +++ b/app/components/Sidebar/components/TrashLink.tsx @@ -6,7 +6,8 @@ import { DialogTitle } from "~/components/DialogTitle"; import useStores from "~/hooks/useStores"; import * as Scenes from "~/routes/scenes"; import { trashPath } from "~/utils/routeHelpers"; -import { type DragObject, useDropRef } from "../hooks/useDragAndDrop"; +import { useDropRef } from "~/components/DragAndDrop"; +import type { DragObject } from "../hooks/useDragAndDrop"; import SidebarLink from "./SidebarLink"; function TrashLink() { diff --git a/app/components/Sidebar/hooks/useDragAndDrop.tsx b/app/components/Sidebar/hooks/useDragAndDrop.tsx index 0a880d48a5..127b4e1427 100644 --- a/app/components/Sidebar/hooks/useDragAndDrop.tsx +++ b/app/components/Sidebar/hooks/useDragAndDrop.tsx @@ -1,15 +1,5 @@ import fractionalIndex from "fractional-index"; import * as React from "react"; -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"; import { toast } from "sonner"; import { errToString } from "@shared/utils/error"; @@ -25,6 +15,7 @@ import type GroupMembership from "~/models/GroupMembership"; import type Star from "~/models/Star"; import UserMembership from "~/models/UserMembership"; import ConfirmMoveDialog from "~/components/ConfirmMoveDialog"; +import { useDragRef, useDropRef } from "~/components/DragAndDrop"; import useCurrentUser from "~/hooks/useCurrentUser"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; @@ -37,102 +28,39 @@ export type DragObject = NavigationNode & { }; /** - * 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. + * Returns functions to start and cancel a timer that calls the callback once + * an item has been held over a target for half a second. * - * @param connect The connector to adapt. - * @returns a ref callback. + * @param callback The function to call. + * @returns a tuple of the start and cancel functions. */ -function useConnectorRef( - connect: ConnectDragSource | ConnectDropTarget -): React.RefCallback<HTMLElement> { - return React.useCallback( - (node: HTMLElement | null) => void connect(node), - [connect] +function useHoverTimer(callback: () => void) { + const timeoutRef = React.useRef<ReturnType<typeof setTimeout> | undefined>( + undefined ); -} + const callbackRef = React.useRef(callback); -/** - * 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<DragObj, DropResult, CollectedProps> - > -): [CollectedProps, React.RefCallback<HTMLElement>, ConnectDragPreview] { - const [collected, connect, preview] = useDrag< - DragObj, - DropResult, - CollectedProps - >(spec); - return [collected, useConnectorRef(connect), preview]; -} + React.useEffect(() => { + callbackRef.current = callback; + }); -/** - * 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<DragObj, DropResult, CollectedProps> - > -): [CollectedProps, React.RefCallback<HTMLElement>] { - const [collected, connect] = useDrop<DragObj, DropResult, CollectedProps>( - spec - ); - return [collected, useConnectorRef(connect)]; -} - -function useHover( - elementRef: React.RefObject<HTMLDivElement | null>, - callback: () => void -) { - const hoverTimeoutRef = React.useRef< - ReturnType<typeof setTimeout> | undefined - >(undefined); - - const startHover = React.useCallback(() => { - if (!hoverTimeoutRef.current) { - hoverTimeoutRef.current = setTimeout(() => { - hoverTimeoutRef.current = undefined; - callback(); + const start = React.useCallback(() => { + if (!timeoutRef.current) { + timeoutRef.current = setTimeout(() => { + timeoutRef.current = undefined; + callbackRef.current(); }, 500); } - }, [callback]); - - const unsetHover = React.useCallback(() => { - if (hoverTimeoutRef.current) { - clearTimeout(hoverTimeoutRef.current); - hoverTimeoutRef.current = undefined; - } }, []); - // We set a timeout when the user first starts hovering over the document link, - // to trigger expansion of children. Clear this timeout when they stop hovering. - React.useEffect(() => { - const element = elementRef.current; - element?.addEventListener("dragleave", unsetHover); - return () => element?.removeEventListener("dragleave", unsetHover); - }, [elementRef, unsetHover]); + const cancel = React.useCallback(() => { + clearTimeout(timeoutRef.current); + timeoutRef.current = undefined; + }, []); - return startHover; + React.useEffect(() => cancel, [cancel]); + + return [start, cancel] as const; } /** @@ -146,18 +74,11 @@ export function useDragStar( const id = star.id; const { label: title, icon } = useSidebarLabelAndIcon(star); - const [{ isDragging }, dragRef, preview] = useDragRef({ + const [isDragging, dragRef] = useDragRef({ type: "star", item: () => ({ id, title, icon }), - collect: (monitor) => ({ - isDragging: !!monitor.isDragging(), - }), }); - React.useEffect(() => { - preview(getEmptyImage(), { captureDraggingState: true }); - }, [preview]); - return [{ isDragging }, dragRef]; } @@ -176,40 +97,38 @@ export function useDropToCreateStar(getIndex?: () => string) { const { documents, stars, collections, userMemberships, groupMemberships } = useStores(); - return useDropRef< - DragObject, - Promise<void>, - { isOverCursor: boolean; isDragging: boolean } - >({ - accept, - drop: async (item, monitor) => { - // A more specific drop target (e.g. a reorder cursor) has already - // handled this drop, so avoid creating a duplicate star. - if (monitor.didDrop()) { - return; - } + return useDropRef<DragObject, { isOverCursor: boolean; isDragging: boolean }>( + { + accept, + drop: async (item, monitor) => { + // A more specific drop target (e.g. a reorder cursor) has already + // handled this drop, so avoid creating a duplicate star. + if (monitor.didDrop()) { + return; + } - const type = monitor.getItemType(); - let model; + const type = monitor.getItemType(); + let model; - if (type === "collection") { - model = collections.get(item.id); - } else if (type === "userMembership") { - model = userMemberships.get(item.id)?.document; - } else if (type === "groupMembership") { - model = groupMemberships.get(item.id)?.document; - } else { - model = documents.get(item.id); - } - await model?.star( - getIndex?.() ?? fractionalIndex(null, stars.orderedData[0].index) - ); - }, - collect: (monitor) => ({ - isOverCursor: !!monitor.isOver({ shallow: true }), - isDragging: accept.includes(String(monitor.getItemType())), - }), - }); + if (type === "collection") { + model = collections.get(item.id); + } else if (type === "userMembership") { + model = userMemberships.get(item.id)?.document; + } else if (type === "groupMembership") { + model = groupMemberships.get(item.id)?.document; + } else { + model = documents.get(item.id); + } + await model?.star( + getIndex?.() ?? fractionalIndex(null, stars.orderedData[0].index) + ); + }, + collect: (monitor) => ({ + isOverCursor: !!monitor.isOver({ shallow: true }), + isDragging: accept.includes(String(monitor.getItemType())), + }), + } + ); } /** @@ -220,24 +139,22 @@ export function useDropToCreateStar(getIndex?: () => string) { export function useDropToReorderStar(getIndex?: () => string) { const { stars } = useStores(); - return useDropRef< - DragObject, - Promise<void>, - { isOverCursor: boolean; isDragging: boolean } - >({ - accept: "star", - drop: async (item) => { - const star = stars.get(item.id); - void star?.save({ - index: - getIndex?.() ?? fractionalIndex(null, stars.orderedData[0].index), - }); - }, - collect: (monitor) => ({ - isOverCursor: !!monitor.isOver(), - isDragging: monitor.getItemType() === "star", - }), - }); + return useDropRef<DragObject, { isOverCursor: boolean; isDragging: boolean }>( + { + accept: "star", + drop: async (item) => { + const star = stars.get(item.id); + void star?.save({ + index: + getIndex?.() ?? fractionalIndex(null, stars.orderedData[0].index), + }); + }, + collect: (monitor) => ({ + isOverCursor: !!monitor.isOver(), + isDragging: monitor.getItemType() === "star", + }), + } + ); } /** @@ -250,18 +167,11 @@ export function useDragSidebarSection( section: SidebarSection, title: string ): [{ isDragging: boolean }, React.RefCallback<HTMLElement>] { - const [{ isDragging }, dragRef, preview] = useDragRef({ + const [isDragging, dragRef] = useDragRef({ type: "sidebarSection", item: () => ({ id: section, title }), - collect: (monitor) => ({ - isDragging: !!monitor.isDragging(), - }), }); - React.useEffect(() => { - preview(getEmptyImage(), { captureDraggingState: true }); - }, [preview]); - return [{ isDragging }, dragRef]; } @@ -278,7 +188,6 @@ export function useDropToReorderSidebarSection( return useDropRef< { id: SidebarSection; title: string }, - void, { isOverCursor: boolean; isDragging: boolean } >({ accept: "sidebarSection", @@ -315,11 +224,7 @@ export function useDragDocument( const color = document?.color || node.color; const initial = document?.initial || node.title; - const [{ isDragging }, dragRef, preview] = useDragRef< - DragObject, - Promise<void>, - { isDragging: boolean } - >({ + const [isDragging, dragRef] = useDragRef<DragObject>({ type: "document", item: () => ({ @@ -331,33 +236,28 @@ export function useDragDocument( collectionId: document?.collectionId || "", }) as DragObject, canDrag: () => !!document?.isActive && !isEditing, - collect: (monitor) => ({ - isDragging: monitor.isDragging(), - }), }); - React.useEffect(() => { - preview(getEmptyImage(), { captureDraggingState: true }); - }, [preview]); - return [{ isDragging }, dragRef] as const; } +/** + * Hook for shared logic that allows dropping documents on a collection to move + * them to the top of it. + * + * @param collection The collection to move documents to. + * @param expandNode A function to expand the collection. + */ export function useDropToChangeCollection( collection: Collection, - expandNode: () => void, - parentRef: React.RefObject<HTMLDivElement | null> + expandNode: () => void ) { const { t } = useTranslation(); const { documents, collections, dialogs, policies } = useStores(); const can = usePolicy(collection); - const startHover = useHover(parentRef, expandNode); + const [startHover, cancelHover] = useHoverTimer(expandNode); - return useDropRef< - DragObject, - Promise<void>, - { isOver: boolean; canDrop: boolean } - >({ + const result = useDropRef<DragObject, { isOver: boolean; canDrop: boolean }>({ accept: "document", drop: async (item, monitor) => { if (monitor.didDrop()) { @@ -394,7 +294,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, } ) ); @@ -419,54 +319,61 @@ export function useDropToChangeCollection( canDrop: monitor.canDrop(), }), }); + + const isOver = result[0].isOver; + React.useEffect(() => { + if (!isOver) { + cancelHover(); + } + }, [isOver, cancelHover]); + + return result; } /** * 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, - setExpanded: () => void, - parentRef: React.RefObject<HTMLDivElement | null> + collection: Collection | undefined, + setExpanded: () => void ) { 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); + const [startHover, cancelHover] = useHoverTimer(setExpanded); - return useDropRef<DragObject, Promise<void>, { isOverReparent: boolean }>({ + const result = useDropRef<DragObject, { 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: ( <ConfirmMoveDialog item={item} - collection={collection} + collection={targetCollection} parentDocumentId={node.id} /> ), @@ -504,7 +411,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 @@ -526,6 +436,15 @@ export function useDropToReparentDocument( isOverReparent: monitor.isOver({ shallow: true }) && monitor.canDrop(), }), }); + + const isOverReparent = result[0].isOverReparent; + React.useEffect(() => { + if (!isOverReparent) { + cancelHover(); + } + }, [isOverReparent, cancelHover]); + + return result; } /** @@ -552,7 +471,7 @@ export function useDropToReorderDocument( const document = documents.get(node.id); - return useDropRef<DragObject, Promise<void>, { isOverReorder: boolean }>({ + return useDropRef<DragObject, { isOverReorder: boolean }>({ accept: "document", canDrop: (item: DragObject) => { if ( @@ -578,7 +497,7 @@ export function useDropToReorderDocument( 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; @@ -641,21 +560,14 @@ export function useDragMembership( const id = membership.id; const { label: title, icon } = useSidebarLabelAndIcon(membership); - const [{ isDragging }, dragRef, preview] = useDragRef({ + const [isDragging, dragRef] = useDragRef({ type: membership instanceof UserMembership ? "userMembership" : "groupMembership", item: () => ({ id, title, icon }), - collect: (monitor) => ({ - isDragging: !!monitor.isDragging(), - }), }); - React.useEffect(() => { - preview(getEmptyImage(), { captureDraggingState: true }); - }, [preview]); - return [{ isDragging }, dragRef] as const; } @@ -668,25 +580,23 @@ export function useDropToReorderUserMembership(getIndex?: () => string) { const { userMemberships } = useStores(); const user = useCurrentUser(); - return useDropRef< - DragObject, - Promise<void>, - { isOverCursor: boolean; isDragging: boolean } - >({ - accept: "userMembership", - drop: async (item) => { - const userMembership = userMemberships.get(item.id); - void userMembership?.save({ - index: - getIndex?.() ?? - fractionalIndex(null, user.documentMemberships[0].index), - }); - }, - collect: (monitor) => ({ - isOverCursor: !!monitor.isOver(), - isDragging: monitor.getItemType() === "userMembership", - }), - }); + return useDropRef<DragObject, { isOverCursor: boolean; isDragging: boolean }>( + { + accept: "userMembership", + drop: async (item) => { + const userMembership = userMemberships.get(item.id); + void userMembership?.save({ + index: + getIndex?.() ?? + fractionalIndex(null, user.documentMemberships[0].index), + }); + }, + collect: (monitor) => ({ + isOverCursor: !!monitor.isOver(), + isDragging: monitor.getItemType() === "userMembership", + }), + } + ); } /** @@ -699,7 +609,6 @@ export function useDropToArchive() { return useDropRef< DragObject, - Promise<void>, { isOverArchiveSection: boolean; isDragging: boolean } >({ accept, @@ -734,11 +643,7 @@ export function useDropToUnpublish() { const { t } = useTranslation(); const { policies, documents } = useStores(); - return useDropRef< - DragObject, - Promise<void>, - { isOver: boolean; canDrop: boolean } - >({ + return useDropRef<DragObject, { isOver: boolean; canDrop: boolean }>({ accept: "document", drop: async (item) => { const document = documents.get(item.id); 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<HTMLElement | null>, + 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..0da7c3d469 100644 --- a/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx +++ b/app/components/Sidebar/hooks/useSidebarLabelAndIcon.tsx @@ -1,8 +1,9 @@ -import { DocumentIcon, QuestionMarkIcon } from "outline-icons"; +import { QuestionMarkIcon } from "outline-icons"; import * as React from "react"; import Icon from "@shared/components/Icon"; import CollectionIcon from "~/components/Icons/CollectionIcon"; import useStores from "~/hooks/useStores"; +import { DocumentIcon } from "~/components/Icons/DocumentIcon"; interface SidebarItem { documentId?: string; @@ -10,44 +11,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 = <QuestionMarkIcon />; + 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 isEmpty = document?.isEmpty; + const collectionName = collection?.displayName; + + return React.useMemo(() => { if (document) { return { - label: document.titleWithDefault, - icon: document.icon ? ( + label: title ?? "", + icon: documentIcon ? ( <Icon - value={document.icon} - initial={document.initial} - color={document.color ?? undefined} + value={documentIcon} + initial={initial ?? ""} + color={color ?? undefined} /> ) : groupId ? null : ( - <DocumentIcon outline={document.isDraft} /> + <DocumentIcon empty={isEmpty} /> ), }; } - } - if (collectionId) { - const collection = collections.get(collectionId); if (collection) { return { - label: collection.name, + label: collectionName ?? "", icon: <CollectionIcon collection={collection} />, }; } - } - return { - label: "", - icon, - }; + return { + label: "", + icon: <QuestionMarkIcon />, + }; + }, [ + document, + title, + documentIcon, + initial, + color, + isEmpty, + groupId, + collection, + collectionName, + ]); } 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<HTMLDivElement>(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 fa78f9d597..fcf33b1a13 100644 --- a/app/components/Star.tsx +++ b/app/components/Star.tsx @@ -60,7 +60,6 @@ function Star({ content: target.isStarred ? t("Unstar document") : t("Star document"), - delay: 500, } } action={ diff --git a/app/components/Switch.tsx b/app/components/Switch.tsx index a1bac9ff45..431bc0cc96 100644 --- a/app/components/Switch.tsx +++ b/app/components/Switch.tsx @@ -2,6 +2,7 @@ import * as RadixSwitch from "@radix-ui/react-switch"; import { darken } from "polished"; import * as React from "react"; import styled from "styled-components"; +import { breakpoint } from "@shared/styles/breakpoint"; import { s } from "@shared/styles"; import { LabelText } from "~/components/Input"; import Text from "~/components/Text"; @@ -67,7 +68,7 @@ function Switch({ className={label ? undefined : className} {...props} > - <StyledSwitchThumb width={width} height={height} /> + <StyledSwitchThumb /> </StyledSwitchRoot> ); @@ -128,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; @@ -144,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))); } `; @@ -156,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; @@ -190,12 +200,12 @@ 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) ); } @@ -203,7 +213,7 @@ const StyledSwitchRoot = styled(RadixSwitch.Root)<{ &: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) ); } `; diff --git a/app/components/Table.tsx b/app/components/Table.tsx index 7900ef2d89..59d96418c9 100644 --- a/app/components/Table.tsx +++ b/app/components/Table.tsx @@ -17,8 +17,9 @@ import { observer } from "mobx-react"; import { CollapsedIcon, SettingsIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; -import { Waypoint } from "react-waypoint"; -import styled from "styled-components"; +import styled, { css, keyframes } from "styled-components"; +import { breakpoint } from "@shared/styles/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"; @@ -42,11 +43,24 @@ import Tooltip from "~/components/Tooltip"; import useMobile from "~/hooks/useMobile"; import usePersistedState from "~/hooks/usePersistedState"; import usePrevious from "~/hooks/usePrevious"; +import { useStuckAttribute } from "~/hooks/useStuckAttribute"; import { preventDefault } from "~/utils/events"; import { transparentize } from "polished"; const HEADER_HEIGHT = 40; +/** Minimum width of a flexible column before the table scrolls horizontally. */ +const DEFAULT_MIN_COLUMN_WIDTH = 100; + +/** Space beside the scrolling area, so the selected row highlight is not clipped. */ +const SCROLL_GUTTER = 8; + +/** Whether the header can follow the horizontal scroll of the body in CSS. */ +const supportsScrollTimeline = + typeof CSS !== "undefined" && + CSS.supports("timeline-scope", "--table") && + CSS.supports("animation-timeline", "scroll()"); + type DataColumn<TData> = { type: "data"; header: string; @@ -63,8 +77,12 @@ export type Column<TData> = { id: string; component: (data: TData) => React.ReactNode; width: string; - /** Whether the column is hidden on narrow viewports (defaults to false). */ - hideOnMobile?: boolean; + /** + * The minimum width of the column in pixels. When the columns do not fit, + * the table scrolls horizontally. Defaults to the pixel width of fixed + * columns, or 100px for flexible columns. + */ + minWidth?: number; } & (DataColumn<TData> | ActionColumn); /** The minimum shape of a row, rows are identified by the model identifier. */ @@ -144,9 +162,18 @@ function TableViewInner<TData extends RowData>({ const selection = useModelSelection(); const isMobile = useMobile(); const virtualContainerRef = React.useRef<HTMLDivElement>(null); + const tableRef = React.useRef<HTMLDivElement>(null); + const headRef = React.useRef<HTMLDivElement>(null); + const headScrollRef = React.useRef<HTMLDivElement>(null); + const bodyScrollRef = React.useRef<HTMLDivElement>(null); const [virtualContainerTop, setVirtualContainerTop] = React.useState<number>(); + useStuckAttribute( + headRef, + isMobile ? Math.min(stickyOffset, APP_HEADER_HEIGHT) : stickyOffset + ); + const [hiddenColumns, setHiddenColumns] = usePersistedState<string[]>( `hiddenTableColumns-${id}`, [] @@ -167,10 +194,9 @@ function TableViewInner<TData extends RowData>({ () => columns.filter( (column) => - (!isMobile || !column.hideOnMobile) && - (!id || column.type !== "data" || !hiddenColumns.includes(column.id)) + !id || column.type !== "data" || !hiddenColumns.includes(column.id) ), - [id, columns, hiddenColumns, isMobile] + [id, columns, hiddenColumns] ); const allColumns = React.useMemo(() => { @@ -227,10 +253,77 @@ function TableViewInner<TData extends RowData>({ ); const gridColumns = React.useMemo( - () => allColumns.map((column) => column.width).join(" "), + () => allColumns.map(getColumnTrack).join(" "), [allColumns] ); + const minWidth = React.useMemo( + () => allColumns.reduce((sum, column) => sum + getMinWidth(column), 0), + [allColumns] + ); + + // Set on the DOM directly to avoid a re-render on scroll. + const updateOverflow = React.useCallback(() => { + const element = tableRef.current; + const scroller = bodyScrollRef.current; + if (!element || !scroller) { + return; + } + + const scrollLeft = Math.abs(scroller.scrollLeft); + const maxScrollLeft = scroller.scrollWidth - scroller.clientWidth; + element.toggleAttribute("data-overflow-start", scrollLeft > 0); + element.toggleAttribute( + "data-overflow-end", + maxScrollLeft - scrollLeft > 1 + ); + }, []); + + const handleBodyScroll = React.useCallback( + (ev: React.UIEvent<HTMLDivElement>) => { + // A scroll event fires after the frame is painted, so syncing here lags. + if (!supportsScrollTimeline && headScrollRef.current) { + headScrollRef.current.scrollLeft = ev.currentTarget.scrollLeft; + } + updateOverflow(); + }, + [updateOverflow] + ); + + // Focus can scroll the header to an offscreen column, pass it to the body. + const handleHeadScroll = React.useCallback( + (ev: React.UIEvent<HTMLDivElement>) => { + const head = ev.currentTarget; + const body = bodyScrollRef.current; + if (!body) { + return; + } + + if (supportsScrollTimeline) { + if (head.scrollLeft !== 0) { + body.scrollLeft += head.scrollLeft; + head.scrollLeft = 0; + } + } else if (body.scrollLeft !== head.scrollLeft) { + body.scrollLeft = head.scrollLeft; + } + }, + [] + ); + + React.useLayoutEffect(() => { + const scroller = bodyScrollRef.current; + if (!scroller) { + return; + } + + updateOverflow(); + + const observer = new ResizeObserver(updateOverflow); + observer.observe(scroller); + return () => observer.disconnect(); + }, [updateOverflow, minWidth]); + const handleChangeSort = React.useCallback( (sortState: SortingState) => { const newState = functionalUpdate(sortState, [sort]); @@ -268,6 +361,17 @@ function TableViewInner<TData extends RowData>({ overscan: 5, }); + const virtualItems = rowVirtualizer.getVirtualItems(); + const lastRenderedIndex = virtualItems[virtualItems.length - 1]?.index ?? -1; + const { hasNext, fetchNext } = page; + + // Fetch the next page once the overscanned rows reach the end of the data. + React.useEffect(() => { + if (hasNext && lastRenderedIndex >= rows.length - 1) { + fetchNext?.(); + } + }, [hasNext, fetchNext, lastRenderedIndex, rows.length]); + React.useEffect(() => { if (!sortChanged || !virtualContainerTop) { return; @@ -295,78 +399,94 @@ function TableViewInner<TData extends RowData>({ return ( <> - <InnerTable role="table"> - <THead role="rowgroup" $topPos={stickyOffset}> - {table.getHeaderGroups().map((headerGroup) => { - const headerRow = ( - <TR role="row" $columns={gridColumns}> - {headerGroup.headers.map((header) => { - const sorted = header.column.getIsSorted(); - const canSort = header.column.getCanSort(); - const toggleSorting = header.column.getToggleSortingHandler(); - const handleSortKeyDown = ( - ev: React.KeyboardEvent<HTMLDivElement> - ) => { - if (!ev.repeat && (ev.key === "Enter" || ev.key === " ")) { - ev.preventDefault(); - toggleSorting?.(ev); - } - }; + <InnerTable ref={tableRef} role="table" $minWidth={minWidth}> + <THead ref={headRef} $topPos={stickyOffset}> + <HeadScroller + ref={headScrollRef} + role="rowgroup" + onScroll={handleHeadScroll} + > + <HeadContent> + {table.getHeaderGroups().map((headerGroup) => { + const headerRow = ( + <TR role="row" $columns={gridColumns}> + {headerGroup.headers.map((header) => { + const sorted = header.column.getIsSorted(); + const canSort = header.column.getCanSort(); + const toggleSorting = + header.column.getToggleSortingHandler(); + const handleSortKeyDown = ( + ev: React.KeyboardEvent<HTMLDivElement> + ) => { + if ( + !ev.repeat && + (ev.key === "Enter" || ev.key === " ") + ) { + ev.preventDefault(); + toggleSorting?.(ev); + } + }; - return ( - <TH - role="columnheader" - key={header.id} - aria-sort={ - !canSort - ? undefined - : sorted === "asc" - ? "ascending" - : sorted === "desc" - ? "descending" - : "none" - } - > - <SortWrapper - align="center" - gap={4} - onClick={toggleSorting} - onKeyDown={canSort ? handleSortKeyDown : undefined} - role={canSort ? "button" : undefined} - tabIndex={canSort ? 0 : undefined} - $sortable={canSort} - > - {flexRender( - header.column.columnDef.header, - header.getContext() - )} - {sorted === "asc" ? ( - <AscSortIcon /> - ) : sorted === "desc" ? ( - <DescSortIcon /> - ) : ( - <div /> - )} - </SortWrapper> - </TH> - ); - })} - </TR> - ); + return ( + <TH + role="columnheader" + key={header.id} + aria-sort={ + !canSort + ? undefined + : sorted === "asc" + ? "ascending" + : sorted === "desc" + ? "descending" + : "none" + } + > + <SortWrapper + align="center" + gap={4} + onClick={toggleSorting} + onKeyDown={canSort ? handleSortKeyDown : undefined} + role={canSort ? "button" : undefined} + tabIndex={canSort ? 0 : undefined} + $sortable={canSort} + > + {flexRender( + header.column.columnDef.header, + header.getContext() + )} + {sorted === "asc" ? ( + <AscSortIcon /> + ) : sorted === "desc" ? ( + <DescSortIcon /> + ) : ( + <div /> + )} + </SortWrapper> + </TH> + ); + })} + </TR> + ); - return id && !isMobile ? ( - <ColumnVisibilityMenu - key={headerGroup.id} - columns={columns} - hiddenColumns={hiddenColumns} - onToggleColumn={handleToggleColumn} - > - {headerRow} - </ColumnVisibilityMenu> - ) : ( - <React.Fragment key={headerGroup.id}>{headerRow}</React.Fragment> - ); - })} + return id && !isMobile ? ( + <ColumnVisibilityMenu + key={headerGroup.id} + columns={columns} + hiddenColumns={hiddenColumns} + onToggleColumn={handleToggleColumn} + > + {headerRow} + </ColumnVisibilityMenu> + ) : ( + <React.Fragment key={headerGroup.id}> + {headerRow} + </React.Fragment> + ); + })} + </HeadContent> + </HeadScroller> + <Fade $side="start" /> + <Fade $side="end" /> {id && !isMobile && ( <ColumnVisibilityButton columns={columns} @@ -376,73 +496,78 @@ function TableViewInner<TData extends RowData>({ )} </THead> - <TBody - ref={virtualContainerRef} - role="rowgroup" - $height={rowVirtualizer.getTotalSize()} - > - {rowVirtualizer.getVirtualItems().map((virtualRow) => { - const row = rows[virtualRow.index] as TRow<TData>; - const rowProps = { - role: "row", - "data-index": virtualRow.index, - style: { - position: "absolute" as const, - transform: `translateY(${ - virtualRow.start - rowVirtualizer.options.scrollMargin - }px)`, - height: `${virtualRow.size}px`, - }, - $columns: gridColumns, - children: row.getAllCells().map((cell) => ( - <TD - role="cell" - key={cell.id} - className={ - cell.column.id === "action" - ? "actions" - : cell.column.id === "select" - ? "select" - : "" - } - > - {flexRender(cell.column.columnDef.cell, cell.getContext())} - </TD> - )), - }; + <BodyFrame> + <BodyScroller ref={bodyScrollRef} onScroll={handleBodyScroll}> + <TBody + ref={virtualContainerRef} + role="rowgroup" + $height={rowVirtualizer.getTotalSize()} + > + {virtualItems.map((virtualRow) => { + const row = rows[virtualRow.index] as TRow<TData>; + const rowProps = { + role: "row", + "data-index": virtualRow.index, + style: { + position: "absolute" as const, + transform: `translateY(${ + virtualRow.start - rowVirtualizer.options.scrollMargin + }px)`, + height: `${virtualRow.size}px`, + }, + $columns: gridColumns, + children: row.getAllCells().map((cell) => ( + <TD + role="cell" + key={cell.id} + className={ + cell.column.id === "action" + ? "actions" + : cell.column.id === "select" + ? "select" + : "" + } + > + {flexRender( + cell.column.columnDef.cell, + cell.getContext() + )} + </TD> + )), + }; - const baseRow = selection ? ( - <SelectableRow - key={row.id} - selection={selection} - id={row.original.id} - {...rowProps} + const baseRow = selection ? ( + <SelectableRow + key={row.id} + selection={selection} + id={row.original.id} + {...rowProps} + /> + ) : ( + <TR key={row.id} {...rowProps} /> + ); + + return decorateRow ? ( + <React.Fragment key={row.id}> + {decorateRow(row.original, baseRow)} + </React.Fragment> + ) : ( + baseRow + ); + })} + </TBody> + {showPlaceholder && ( + <Placeholder + columns={allColumns.length} + gridColumns={gridColumns} /> - ) : ( - <TR key={row.id} {...rowProps} /> - ); - - return decorateRow ? ( - <React.Fragment key={row.id}> - {decorateRow(row.original, baseRow)} - </React.Fragment> - ) : ( - baseRow - ); - })} - </TBody> - {showPlaceholder && ( - <Placeholder columns={allColumns.length} gridColumns={gridColumns} /> - )} + )} + </BodyScroller> + <Fade $side="start" /> + <Fade $side="end" /> + </BodyFrame> </InnerTable> - {page.hasNext && ( - <Waypoint - key={data?.length} - onEnter={page.fetchNext} - bottomOffset={-rowHeight * 5} - /> - )} - {isEmpty && <Empty>{t("No results")}</Empty>} + {isEmpty && <NoResults>{t("No results")}</NoResults>} </> ); } @@ -521,7 +646,7 @@ function ColumnVisibilityButton<TData>(props: ColumnVisibilityProps<TData>) { return ( <MenuProvider variant="dropdown"> <Menu> - <Tooltip content={label} placement="bottom"> + <Tooltip content={label} side="bottom"> <MenuTrigger aria-label={label}> <ColumnOptions> <SettingsIcon size={18} /> @@ -589,6 +714,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) { @@ -618,6 +747,34 @@ const ObservedCell = observer(function <TData>({ return <>{render(data)}</>; }); +/** + * Returns the minimum width of a column in pixels. + * + * @param column the column. + * @returns the minimum width. + */ +function getMinWidth<TData>(column: Column<TData>): number { + if (column.minWidth !== undefined) { + return column.minWidth; + } + + const match = /^(?:minmax\(\s*)?(\d+)px/.exec(column.width); + return match ? Number(match[1]) : DEFAULT_MIN_COLUMN_WIDTH; +} + +/** + * Returns the grid track of a column, flexible columns are given a minimum + * width so that every row has the same layout. + * + * @param column the column. + * @returns the grid track. + */ +function getColumnTrack<TData>(column: Column<TData>): string { + return /^[\d.]+fr$/.test(column.width) + ? `minmax(${getMinWidth(column)}px, ${column.width})` + : column.width; +} + function Placeholder({ columns, rows = 3, @@ -644,6 +801,11 @@ function Placeholder({ ); } +const NoResults = styled(Empty)` + display: block; + margin-top: 8px; +`; + const DescSortIcon = styled(CollapsedIcon)` margin-left: -2px; @@ -692,8 +854,84 @@ const ColumnOptions = styled(NudeButton)` } `; -const InnerTable = styled.div` +const InnerTable = styled.div<{ $minWidth: number }>` + --table-min-width: ${({ $minWidth }) => `${$minWidth}px`}; width: 100%; + timeline-scope: --table-scroll; +`; + +const Scroller = styled.div` + margin: 0 -${SCROLL_GUTTER}px; + padding: 0 ${SCROLL_GUTTER}px; +`; + +const HeadScroller = styled(Scroller)` + overflow: hidden; + container-type: inline-size; +`; + +const followScroll = keyframes` + from { + transform: translateX(0); + } + + to { + transform: translateX(calc((100cqw - 100%) * var(--scroll-direction))); + } +`; + +/** Moved with the body scroll on the compositor, so it does not lag. */ +const HeadContent = styled.div` + --scroll-direction: 1; + min-width: var(--table-min-width); + + &:dir(rtl) { + --scroll-direction: -1; + } + + ${ + supportsScrollTimeline && + css` + animation: ${followScroll} linear both; + animation-timeline: --table-scroll; + ` + } +`; + +const BodyScroller = styled(Scroller)` + overflow-x: auto; + overflow-y: hidden; + overscroll-behavior-x: none; + scroll-timeline: --table-scroll inline; +`; + +const BodyFrame = styled.div` + position: relative; +`; + +/** Shown at an edge of the table while there are hidden columns past it. */ +const Fade = styled.div<{ $side: "start" | "end" }>` + position: absolute; + top: 0; + bottom: 0; + inset-inline-${({ $side }) => $side}: -${SCROLL_GUTTER}px; + width: 24px; + background: linear-gradient( + to ${({ $side }) => ($side === "start" ? "right" : "left")}, + ${s("background")}, + transparent + ); + pointer-events: none; + opacity: 0; + transition: opacity 100ms ease-in-out; + + &:dir(rtl) { + transform: scaleX(-1); + } + + ${InnerTable}[data-overflow-${({ $side }) => $side}] & { + opacity: 1; + } `; const THead = styled.div<{ $topPos: number }>` @@ -708,15 +946,22 @@ 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 }>` position: relative; + min-width: var(--table-min-width); height: ${({ $height }) => `${$height}px`}; `; const TR = styled.div<{ $columns: string }>` width: 100%; + min-width: var(--table-min-width); display: grid; grid-template-columns: ${({ $columns }) => `${$columns}`}; align-items: center; @@ -775,7 +1020,7 @@ const TD = styled.span` position: relative; padding: 10px 6px; font-size: 14px; - text-wrap: wrap; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; @@ -803,11 +1048,6 @@ const TD = styled.span` vertical-align: bottom; } - &.actions { - position: sticky; - right: 0; - } - ${NudeButton}[aria-haspopup="menu"] { vertical-align: middle; opacity: 0; diff --git a/app/components/Tabs/Tab.tsx b/app/components/Tabs/Tab.tsx index ac69ac36bf..d9ee50fd2c 100644 --- a/app/components/Tabs/Tab.tsx +++ b/app/components/Tabs/Tab.tsx @@ -5,7 +5,8 @@ import { isEqual } from "es-toolkit/compat"; import queryString from "query-string"; import * as React from "react"; import styled, { css, useTheme } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; +import { MOBILE_TOUCH_TARGET } from "@shared/constants"; import { s, hover } from "@shared/styles"; import NavLink from "~/components/NavLink"; @@ -60,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; `}; `; diff --git a/app/components/Tabs/Tabs.tsx b/app/components/Tabs/Tabs.tsx index 8175761e38..196346fd27 100644 --- a/app/components/Tabs/Tabs.tsx +++ b/app/components/Tabs/Tabs.tsx @@ -4,6 +4,7 @@ import { transparentize } from "polished"; import * as React from "react"; import styled from "styled-components"; import { s } from "@shared/styles"; +import { useStuckAttribute } from "~/hooks/useStuckAttribute"; import useWindowSize from "~/hooks/useWindowSize"; const Nav = styled.nav<{ $shadowVisible?: boolean }>` @@ -44,9 +45,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 +80,7 @@ export const TabsGroup: React.FC<Props> = ({ children }: Props) => { export const Tabs: React.FC<Props> = ({ children }: Props) => { const ref = React.useRef<HTMLElement>(null); + const stickyRef = React.useRef<HTMLDivElement>(null); const [shadowVisible, setShadow] = React.useState(false); const { width } = useWindowSize(); @@ -97,9 +102,11 @@ export const Tabs: React.FC<Props> = ({ children }: Props) => { updateShadows(); }, [width, updateShadows]); + useStuckAttribute(stickyRef, StickyTop); + return ( <TabsGroup> - <Sticky> + <Sticky ref={stickyRef}> <Nav ref={ref} onScroll={updateShadows} $shadowVisible={shadowVisible}> {children} </Nav> diff --git a/app/components/Template/TemplateForm.tsx b/app/components/Template/TemplateForm.tsx index 01c15b8eb0..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 [] ); diff --git a/app/components/TemplatizeDialog/SelectLocation.tsx b/app/components/TemplatizeDialog/SelectLocation.tsx index 1a293d3131..43a8ba73bd 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: <CollectionIcon collection={collection} />, }); @@ -77,7 +77,7 @@ const SelectLocation = ({ defaultCollectionId, onSelect }: Props) => { ); if (error) { - toast.error(t("Collections could not be loaded, please reload the app")); + toast.error(t("Collections could not be loaded – please reload the app")); } if (loading || !options.length) { diff --git a/app/components/TemplatizeDialog/index.tsx b/app/components/TemplatizeDialog/index.tsx index e31859fa36..54f0495a01 100644 --- a/app/components/TemplatizeDialog/index.tsx +++ b/app/components/TemplatizeDialog/index.tsx @@ -35,7 +35,7 @@ function DocumentTemplatizeDialog({ documentId }: Props) { if (template) { history.push(template.path); - toast.success(t("Template created, go ahead and customize it")); + toast.success(t("Template created – go ahead and customize it")); } }, [t, templates, documentId, history, collectionId, publish]); @@ -48,7 +48,7 @@ function DocumentTemplatizeDialog({ documentId }: Props) { <Flex column gap={12}> <div> {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." )} </div> <SelectLocation diff --git a/app/components/Theme.tsx b/app/components/Theme.tsx index de70551122..5fb449bab1 100644 --- a/app/components/Theme.tsx +++ b/app/components/Theme.tsx @@ -3,6 +3,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { ThemeProvider } from "styled-components"; +import { StyleSheetProvider } from "@shared/components/StyleSheetProvider"; import GlobalStyles from "@shared/styles/globals"; import { TeamPreference, UserPreference } from "@shared/types"; import { isRTLLanguage } from "@shared/utils/rtl"; @@ -14,7 +15,7 @@ type Props = { }; const Theme: React.FC<Props> = ({ 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<Props> = ({ 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 ( <DirectionProvider dir={direction}> - <ThemeProvider theme={theme}> - <> - <GlobalStyles - useCursorPointer={ - // Default to showing the cursor pointer if no user is logged in (public share) - auth.user?.getPreference(UserPreference.UseCursorPointer) ?? true - } - /> - {children} - </> - </ThemeProvider> + <StyleSheetProvider> + <ThemeProvider theme={theme}> + <> + <GlobalStyles + useCursorPointer={ + // Default to showing the cursor pointer if no user is logged in (public share) + auth.user?.getPreference(UserPreference.UseCursorPointer) ?? + true + } + /> + {children} + </> + </ThemeProvider> + </StyleSheetProvider> </DirectionProvider> ); }; 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 ( <StyledToaster - // @ts-expect-error styled-components overrides sonner's theme prop with DefaultTheme - theme={ui.resolvedTheme as ResolvedTheme} + resolvedTheme={ui.resolvedTheme as ResolvedTheme} closeButton toastOptions={{ duration: 5000, @@ -27,7 +26,15 @@ function Toasts() { ); } -const StyledToaster = styled(Toaster)` +// styled-components reserves the `theme` prop, so it is passed under another name. +function ThemedToaster({ + resolvedTheme, + ...rest +}: Omit<ToasterProps, "theme"> & { resolvedTheme: ResolvedTheme }) { + return <Toaster {...rest} theme={resolvedTheme} />; +} + +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 c4878cdd28..8522cea7a6 100644 --- a/app/components/Tooltip.tsx +++ b/app/components/Tooltip.tsx @@ -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} > <TooltipPrimitive.Trigger asChild>{children}</TooltipPrimitive.Trigger> <TooltipPrimitive.Portal> <StyledContent - side={finalSide} - sideOffset={finalSideOffset} - align={finalAlign} + side={side} + sideOffset={sideOffset} + align={align} alignOffset={alignOffset} avoidCollisions={avoidCollisions} collisionBoundary={collisionBoundary} @@ -193,7 +143,7 @@ function Tooltip({ // Otherwise, wrap with a provider for standalone usage return ( <TooltipPrimitive.Provider - delayDuration={finalDelayDuration} + delayDuration={delayDuration} skipDelayDuration={skipDelayDuration} > {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 ( <TooltipPrimitive.Provider - delayDuration={finalDelayDuration} + delayDuration={delayDuration} skipDelayDuration={skipDelayDuration} disableHoverableContent={disableHoverableContent} > diff --git a/app/components/UserDialogs.tsx b/app/components/UserDialogs.tsx index 8653f18129..c804cca53c 100644 --- a/app/components/UserDialogs.tsx +++ b/app/components/UserDialogs.tsx @@ -13,6 +13,7 @@ import Input from "~/components/Input"; import useCurrentUser from "~/hooks/useCurrentUser"; import useStores from "~/hooks/useStores"; import ImageInput from "~/scenes/Settings/components/ImageInput"; +import type { ImageUploadHandle } from "~/scenes/Settings/components/ImageUpload"; import { performBatch } from "~/actions/definitions/common"; import { client } from "~/utils/ApiClient"; import Text from "./Text"; @@ -58,14 +59,20 @@ export function UserChangeRoleDialog({ return ( <ConfirmationDialog onSubmit={handleSubmit} savingText={`${t("Saving")}…`}> {users.length === 1 - ? t("Are you sure you want to make {{ userName }} a {{ role }}?", { - role, - userName: users[0].name, - }) - : t("Are you sure you want to make {{ count }} user a {{ role }}?", { - role, - count: users.length, - })}{" "} + ? t( + "Are you sure you want to change the role of {{ userName }} to {{ role }}?", + { + role, + userName: users[0].name, + } + ) + : t( + "Are you sure you want to change the role of {{ count }} user to {{ role }}?", + { + role, + count: users.length, + } + )}{" "} {accessNote} </ConfirmationDialog> ); @@ -160,7 +167,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 @@ -177,6 +184,11 @@ export const UserChangeAvatarDialog = observer(function UserChangeAvatarDialog({ onSubmit, }: Props) { const { t } = useTranslation(); + const imageRef = React.useRef<ImageUploadHandle>(null); + + const handleReplace = () => { + imageRef.current?.open(); + }; const handleAvatarChange = async (avatarUrl: string | null) => { try { @@ -199,15 +211,21 @@ export const UserChangeAvatarDialog = observer(function UserChangeAvatarDialog({ onSuccess={handleAvatarChange} onError={handleAvatarError} model={user} - showRemoveOption={false} + showActions={false} + ref={imageRef} /> </Flex> - <Flex justify="flex-end" gap={8}> - {user.avatarUrl && ( - <Button onClick={() => handleAvatarChange(null)} neutral> - {t("Remove")} + <Flex justify="space-between" gap={8}> + <Flex gap={8}> + <Button onClick={handleReplace} neutral> + {user.avatarUrl ? t("Replace") : t("Upload")}… </Button> - )} + {user.avatarUrl && ( + <Button onClick={() => handleAvatarChange(null)} neutral> + {t("Delete")} + </Button> + )} + </Flex> <Button onClick={onSubmit}>{t("Done")}</Button> </Flex> </Flex> @@ -265,7 +283,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/Waypoint.tsx b/app/components/Waypoint.tsx new file mode 100644 index 0000000000..d258b37c3c --- /dev/null +++ b/app/components/Waypoint.tsx @@ -0,0 +1,20 @@ +import useWaypoint from "~/hooks/useWaypoint"; + +interface Props { + /** Function to call when the waypoint enters the viewport. */ + onEnter?: () => void; + /** Margin around the viewport in CSS margin syntax, e.g. "0px 0px 200px 0px". */ + rootMargin?: string; +} + +/** + * Renders an empty element that calls onEnter when it enters the viewport. To + * check again after the content changes, remount it with a new key. + * + * @param props - the component props. + * @returns the waypoint element. + */ +export function Waypoint({ onEnter, rootMargin }: Props) { + const ref = useWaypoint(onEnter, { rootMargin }); + return <div ref={ref} aria-hidden />; +} diff --git a/app/components/WebsocketProvider.tsx b/app/components/WebsocketProvider.tsx index 8aacc678b8..9662ca26e9 100644 --- a/app/components/WebsocketProvider.tsx +++ b/app/components/WebsocketProvider.tsx @@ -26,6 +26,7 @@ import type Import from "~/models/Import"; import type Membership from "~/models/Membership"; import type Notification from "~/models/Notification"; import type Pin from "~/models/Pin"; +import type Share from "~/models/Share"; import type Star from "~/models/Star"; import type Subscription from "~/models/Subscription"; import type Team from "~/models/Team"; @@ -51,6 +52,7 @@ type SocketWithAuthentication = Socket & { const unreportableErrorIds = [ "authentication_required", "invalid_authentication", + "user_suspended", ]; export const WebsocketContext = createContext<SocketWithAuthentication | null>( @@ -292,7 +294,7 @@ function useDocumentHandlers() { socket.on( "documents.update", - action((event: PartialExcept<Document, "id" | "title" | "url">) => { + action((event: PartialExcept<Document, "id" | "title" | "path">) => { documents.add(event); if (event.collectionId) { @@ -311,7 +313,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 @@ -827,6 +829,24 @@ function usePinHandlers() { }; } +function useShareHandlers() { + const { shares } = useStores(); + + return (socket: SocketWithAuthentication) => { + socket.on("shares.create", (event: PartialExcept<Share, "id">) => { + shares.add(event); + }); + + socket.on("shares.update", (event: PartialExcept<Share, "id">) => { + shares.add(event); + }); + + socket.on("shares.revoke", (event: WebsocketEntityDeletedEvent) => { + shares.remove(event.modelId); + }); + }; +} + function useStarHandlers() { const { stars } = useStores(); @@ -906,6 +926,7 @@ function WebsocketProvider({ children }: React.PropsWithChildren<object>) { const registerUserHandlers = useUserHandlers(); const registerNotificationHandlers = useNotificationHandlers(); const registerPinHandlers = usePinHandlers(); + const registerShareHandlers = useShareHandlers(); const registerStarHandlers = useStarHandlers(); const registerImportHandlers = useImportHandlers(); @@ -934,6 +955,7 @@ function WebsocketProvider({ children }: React.PropsWithChildren<object>) { registerUserHandlers(currentSocket); registerNotificationHandlers(currentSocket); registerPinHandlers(currentSocket); + registerShareHandlers(currentSocket); registerStarHandlers(currentSocket); registerImportHandlers(currentSocket); @@ -961,7 +983,7 @@ function WebsocketProvider({ children }: React.PropsWithChildren<object>) { } 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 f1eda8be44..073e23a92c 100644 --- a/app/components/primitives/Drawer.tsx +++ b/app/components/primitives/Drawer.tsx @@ -108,7 +108,9 @@ const StyledContent = styled(m.div)` 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/Menu/index.tsx b/app/components/primitives/Menu/index.tsx index f0c0bfc961..ffaf031601 100644 --- a/app/components/primitives/Menu/index.tsx +++ b/app/components/primitives/Menu/index.tsx @@ -232,6 +232,8 @@ type BaseItemProps = { icon?: React.ReactElement; disabled?: boolean; shortcut?: string[]; + /** Additional content displayed at the end of the item. */ + badge?: React.ReactNode; }; /** @@ -290,6 +292,7 @@ function MenuButton(props: MenuButtonProps) { selected, dangerous, shortcut, + badge, onClick, ...rest } = props; @@ -308,6 +311,7 @@ function MenuButton(props: MenuButtonProps) { > {icon} <Components.MenuLabel>{label}</Components.MenuLabel> + {badge && <Components.MenuBadge>{badge}</Components.MenuBadge>} {selected !== undefined && ( <Components.SelectedIconWrapper aria-hidden> {selected ? <CheckmarkIcon size={18} /> : null} @@ -319,7 +323,7 @@ function MenuButton(props: MenuButtonProps) { ); return tooltip ? ( - <Tooltip content={tooltip} placement="bottom"> + <Tooltip content={tooltip} side="bottom"> <div>{button}</div> </Tooltip> ) : ( @@ -343,7 +347,7 @@ type MenuInternalLinkProps = BaseItemProps & { function MenuInternalLink(props: MenuInternalLinkProps) { const { variant } = useMenuContext(); - const { ref, label, icon, disabled, shortcut, to, ...rest } = props; + const { ref, label, icon, disabled, shortcut, badge, to, ...rest } = props; const Item = variant === "dropdown" @@ -355,6 +359,7 @@ function MenuInternalLink(props: MenuInternalLinkProps) { <Components.MenuInternalLink to={to} disabled={disabled}> {icon} <Components.MenuLabel>{label}</Components.MenuLabel> + {badge && <Components.MenuBadge>{badge}</Components.MenuBadge>} <MenuItemShortcut shortcut={shortcut} /> </Components.MenuInternalLink> </Item> @@ -378,7 +383,8 @@ type MenuExternalLinkProps = BaseItemProps & { function MenuExternalLink(props: MenuExternalLinkProps) { const { variant } = useMenuContext(); - const { ref, label, icon, disabled, shortcut, href, target, ...rest } = props; + const { ref, label, icon, disabled, shortcut, badge, href, target, ...rest } = + props; const Item = variant === "dropdown" @@ -394,6 +400,7 @@ function MenuExternalLink(props: MenuExternalLinkProps) { > {icon} <Components.MenuLabel>{label}</Components.MenuLabel> + {badge && <Components.MenuBadge>{badge}</Components.MenuBadge>} <MenuItemShortcut shortcut={shortcut} /> </Components.MenuExternalLink> </Item> diff --git a/app/components/primitives/components/InputSelect.tsx b/app/components/primitives/components/InputSelect.tsx index 5655e5c8cc..31a698dfc3 100644 --- a/app/components/primitives/components/InputSelect.tsx +++ b/app/components/primitives/components/InputSelect.tsx @@ -4,7 +4,7 @@ import { CheckmarkIcon } from "outline-icons"; import styled, { css } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { s } from "@shared/styles"; import Button, { Inner } from "~/components/Button"; import Flex from "~/components/Flex"; diff --git a/app/components/primitives/components/Menu.tsx b/app/components/primitives/components/Menu.tsx index 412178d5fb..82cc2b1a52 100644 --- a/app/components/primitives/components/Menu.tsx +++ b/app/components/primitives/components/Menu.tsx @@ -2,7 +2,7 @@ import { ExpandedIcon } from "outline-icons"; import { ellipsis } from "polished"; import { Link } from "react-router-dom"; import styled, { css } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { depths, s, borderRadius } from "@shared/styles"; import Scrollable from "~/components/Scrollable"; import { fadeAndScaleIn } from "~/styles/animations"; @@ -68,7 +68,9 @@ const BaseMenuItemCSS = css<BaseMenuItemProps>` ` &[data-highlighted], &[data-state="open"], - &:focus-visible { + &:focus-visible, + [data-radix-menu-content]:has([data-menu-filter-input]:focus) + &[data-menu-filter-highlighted] { color: ${props.theme.accentText}; background: ${props.$dangerous ? props.theme.danger : props.theme.accent}; outline-color: ${ @@ -98,11 +100,11 @@ export const MenuButton = styled.button<MenuButtonProps>` ${BaseMenuItemCSS} `; -export const MenuInternalLink = styled(Link)` +export const MenuInternalLink = styled(Link)<BaseMenuItemProps>` ${BaseMenuItemCSS} `; -export const MenuExternalLink = styled.a` +export const MenuExternalLink = styled.a<BaseMenuItemProps>` ${BaseMenuItemCSS} `; @@ -169,6 +171,14 @@ export const SelectedIconWrapper = styled.span` justify-content: center; `; +export const MenuBadge = styled.span` + font-size: 13px; + color: currentColor; + opacity: 0.5; + margin-inline-start: 16px; + flex-shrink: 0; +`; + export const MenuShortcut = styled.span` display: flex; align-items: center; diff --git a/app/editor/components/BlockMenu.tsx b/app/editor/components/BlockMenu.tsx index 5737fdf700..95ada775a6 100644 --- a/app/editor/components/BlockMenu.tsx +++ b/app/editor/components/BlockMenu.tsx @@ -55,10 +55,7 @@ function useTemplateMenuItem(isActive: boolean): 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 ? ( <Icon value={template.icon} @@ -68,7 +65,7 @@ function useTemplateMenuItem(isActive: boolean): MenuItem | undefined { ) : ( <DocumentIcon /> ), - keywords: template.titleWithDefault, + keywords: template.displayTitle, onClick: () => { const data = cloneDeep(template.data); ProsemirrorHelper.replaceTemplateVariables(data, user); diff --git a/app/editor/components/CodeBlockHoverToolbar.tsx b/app/editor/components/CodeBlockHoverToolbar.tsx new file mode 100644 index 0000000000..4184439099 --- /dev/null +++ b/app/editor/components/CodeBlockHoverToolbar.tsx @@ -0,0 +1,125 @@ +import { observer } from "mobx-react"; +import * as React from "react"; +import { buildSelectionContext } from "@shared/editor/lib/buildSelectionContext"; +import filterExcessSeparators from "@shared/editor/lib/filterExcessSeparators"; +import { isCode } from "@shared/editor/lib/isCode"; +import { findParentNodeClosestToPos } from "@shared/editor/queries/findParentNode"; +import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; +import { isTouchDevice } from "@shared/utils/browser"; +import useEventListener from "~/hooks/useEventListener"; +import useMobile from "~/hooks/useMobile"; +import getCodeMenuItems from "../menus/code"; +import { useEditor } from "./EditorContext"; +import StickyBlockToolbar from "./StickyBlockToolbar"; + +interface Props { + /** Whether the text direction is right-to-left. */ + rtl: boolean; + /** Whether the current document is a template. */ + isTemplate: boolean; +} + +/** Delay in ms before the toolbar hides once the pointer leaves the block. */ +const hideDelay = 150; + +/** + * Renders the code block toolbar over the code block under the pointer, for + * read-only editors where there is no selection to show it for. + * + * @param props - the component props. + * @returns the toolbar, or null when no code block is hovered. + */ +export const CodeBlockHoverToolbar = observer(function CodeBlockHoverToolbar({ + rtl, + isTemplate, +}: Props) { + const editor = useEditor(); + const { view } = editor; + const isMobile = useMobile(); + const [element, setElement] = React.useState<HTMLElement | null>(null); + const hideTimeout = React.useRef<ReturnType<typeof setTimeout>>(undefined); + const toolbarRef = React.useRef<HTMLDivElement>(null); + + const cancelHide = React.useCallback(() => { + clearTimeout(hideTimeout.current); + }, []); + + // Hide after a delay so the pointer can cross the gap to the toolbar. + const scheduleHide = React.useCallback(() => { + clearTimeout(hideTimeout.current); + hideTimeout.current = setTimeout(() => { + // Keep the toolbar while it holds keyboard focus. + if (toolbarRef.current?.contains(document.activeElement)) { + return; + } + setElement(null); + }, hideDelay); + }, []); + + React.useEffect(() => cancelHide, [cancelHide]); + + useEventListener( + "mouseover", + (event: MouseEvent) => { + const block = + event.target instanceof Element + ? event.target.closest<HTMLElement>(`.${EditorStyleHelper.codeBlock}`) + : null; + + if (block) { + cancelHide(); + setElement(block); + } else { + scheduleHide(); + } + }, + view.dom + ); + useEventListener( + "mouseleave", + (event: MouseEvent) => { + // React fires the toolbar's mouseenter before this event, so ignore it + // when the pointer moves onto the toolbar. + if ( + event.relatedTarget instanceof Node && + toolbarRef.current?.contains(event.relatedTarget) + ) { + return; + } + scheduleHide(); + }, + view.dom + ); + + if (isMobile || isTouchDevice() || !element || !view.dom.contains(element)) { + return null; + } + + const state = editor.editorState; + const codeBlock = findParentNodeClosestToPos( + state.doc.resolve(view.posAtDOM(element, 0)), + isCode + ); + if (!codeBlock) { + return null; + } + + const ctx = buildSelectionContext(state, { readOnly: true, isTemplate, rtl }); + const items = filterExcessSeparators( + getCodeMenuItems(ctx, codeBlock).filter((item) => item.visible !== false) + ); + if (!items.length) { + return null; + } + + return ( + <StickyBlockToolbar + ref={toolbarRef} + items={items} + rtl={rtl} + element={element} + onMouseEnter={cancelHide} + onMouseLeave={scheduleHide} + /> + ); +}); 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 a204a173ab..c723f233e0 100644 --- a/app/editor/components/FindAndReplace.tsx +++ b/app/editor/components/FindAndReplace.tsx @@ -369,8 +369,13 @@ export default function FindAndReplace({ [] ); + // 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(); @@ -389,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 @@ -406,7 +411,7 @@ export default function FindAndReplace({ <Tooltip content={t("Previous match")} shortcut="Shift+Enter" - placement="bottom" + side="bottom" > <ButtonLarge disabled={disabled} @@ -419,7 +424,7 @@ export default function FindAndReplace({ <CaretUpIcon /> </ButtonLarge> </Tooltip> - <Tooltip content={t("Next match")} shortcut="Enter" placement="bottom"> + <Tooltip content={t("Next match")} shortcut="Enter" side="bottom"> <ButtonLarge disabled={disabled} onClick={() => { @@ -435,7 +440,7 @@ export default function FindAndReplace({ <Tooltip content={t("Replace options")} shortcut={`${altDisplay}+${metaDisplay}+f`} - placement="bottom" + side="bottom" > <ButtonLarge onClick={handleMore} aria-label={t("Replace options")}> <ReplaceIcon color={theme.textSecondary} /> @@ -484,7 +489,7 @@ export default function FindAndReplace({ <Tooltip content={t("Match case")} shortcut={`${altDisplay}+${metaDisplay}+c`} - placement="bottom" + side="bottom" > <ButtonSmall onClick={handleCaseSensitive} @@ -498,7 +503,7 @@ export default function FindAndReplace({ <Tooltip content={t("Enable regex")} shortcut={`${altDisplay}+${metaDisplay}+r`} - placement="bottom" + side="bottom" > <ButtonSmall onClick={handleRegex} @@ -533,11 +538,7 @@ export default function FindAndReplace({ onRequestSubmit={handleReplaceAll} onChange={(ev) => setReplaceTerm(ev.currentTarget.value)} /> - <Tooltip - content={t("Replace")} - shortcut="Enter" - placement="bottom" - > + <Tooltip content={t("Replace")} shortcut="Enter" side="bottom"> <Button onClick={handleReplace} disabled={disabled} neutral> {t("Replace")} </Button> @@ -545,7 +546,7 @@ export default function FindAndReplace({ <Tooltip content={t("Replace all")} shortcut={`${metaDisplay}+Enter`} - placement="bottom" + side="bottom" > <Button onClick={handleReplaceAll} diff --git a/app/editor/components/FloatingToolbar.tsx b/app/editor/components/FloatingToolbar.tsx index 06f926c600..8ae33e186f 100644 --- a/app/editor/components/FloatingToolbar.tsx +++ b/app/editor/components/FloatingToolbar.tsx @@ -56,7 +56,7 @@ function usePosition({ // Measure the menu width after DOM updates to ensure accurate positioning. // Runs after every render by design, the width comparison prevents a loop. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps React.useLayoutEffect(() => { if (menuRef.current) { const width = menuRef.current.offsetWidth; @@ -66,6 +66,11 @@ function usePosition({ } }); + // Measuring the selection forces a layout, so skip it while hidden. + if (!active || !menuRef.current) { + return defaultPosition; + } + // based on the start and end of the selection calculate the position at // the center top let fromPos; @@ -124,10 +129,6 @@ function usePosition({ } } - if (!active || !menuRef.current || !menuHeight) { - return defaultPosition; - } - // tables are an oddity, and need their own positioning logic const colIndex = getColumnIndex(view.state); const rowIndex = getRowIndex(view.state); diff --git a/app/editor/components/LinkEditor.tsx b/app/editor/components/LinkEditor.tsx index 556ec0c42e..8306052d6a 100644 --- a/app/editor/components/LinkEditor.tsx +++ b/app/editor/components/LinkEditor.tsx @@ -153,9 +153,9 @@ const LinkEditor: React.FC<Props> = ({ if (selectedIndex >= 0 && results[selectedIndex]) { const selectedDoc = results[selectedIndex]; if (!mark) { - addLink(selectedDoc.url); + addLink(selectedDoc.path); } else { - updateLink(selectedDoc.url); + updateLink(selectedDoc.path); } } else if (!trimmedQuery) { removeLink(); diff --git a/app/editor/components/MediaDimension.tsx b/app/editor/components/MediaDimension.tsx index 20a7b64550..e216a723dd 100644 --- a/app/editor/components/MediaDimension.tsx +++ b/app/editor/components/MediaDimension.tsx @@ -3,8 +3,8 @@ import { useCallback, useEffect, useRef, useState } from "react"; import styled from "styled-components"; import Flex from "@shared/components/Flex"; import Text from "@shared/components/Text"; +import { contentWidth } from "@shared/editor/lib/contentWidth"; import { resolvePDFDimensions } from "@shared/editor/lib/pdf"; -import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; import { extraArea } from "@shared/styles"; import Input, { NativeInput, Outline } from "~/components/Input"; import { useEditor } from "./EditorContext"; @@ -17,7 +17,6 @@ type Dimension = { }; export function MediaDimension() { - const ref = useRef<HTMLDivElement>(null); const isDraggingRef = useRef(false); const boundsRef = useRef< | { @@ -51,11 +50,8 @@ export function MediaDimension() { height: false, }); - if (!boundsRef.current && ref.current) { - const docWidth = parseInt( - getComputedStyle(ref.current).getPropertyValue("--document-width") - ); - const maxWidth = docWidth - EditorStyleHelper.padding * 2; + if (!boundsRef.current) { + const maxWidth = contentWidth(view.dom); const constrainedWidth = Math.min(width, maxWidth); // Ensure media width does not exceed the max width of the editor. const aspectRatio = height / constrainedWidth; @@ -174,6 +170,11 @@ export function MediaDimension() { width: finalWidth, height: finalHeight, }); + } else if (nodeType === "video") { + commands["resizeVideo"]({ + width: finalWidth, + height: finalHeight, + }); } }, [ commands, @@ -248,7 +249,7 @@ export function MediaDimension() { }; }, [nodeType]); - // hacky debounce for checking error. + // Debounce validation so errors are not shown while typing. useEffect(() => { const timeout = setTimeout(() => { const isWidthError = localDimension.width @@ -272,7 +273,7 @@ export function MediaDimension() { }, [width, height, localDimension, isOutsideBounds]); return ( - <StyledFlex ref={ref} align="center"> + <StyledFlex align="center"> <StyledInput label={t("Image width")} labelHidden diff --git a/app/editor/components/MediaLinkEditor.tsx b/app/editor/components/MediaLinkEditor.tsx index cb1af7fcab..76ae8c1965 100644 --- a/app/editor/components/MediaLinkEditor.tsx +++ b/app/editor/components/MediaLinkEditor.tsx @@ -34,10 +34,10 @@ export function MediaLinkEditor({ const [localUrl, setLocalUrl] = useState(url); const wrapperRef = useRef<HTMLDivElement>(null); - // If we're attempting to edit an image, autofocus the input - // Not doing for embed type because it made the editor scroll to top - // unexpectedly–leaving that out for now - const isEditingImgUrl = node?.type.name === "image"; + // Image and video nodes store their URL in `src` and autofocus the input. + // Embeds use `href` and do not autofocus, as it made the editor scroll to + // top unexpectedly–leaving that out for now + const isSrcNode = node?.type.name === "image" || node?.type.name === "video"; const moveSelectionToEnd = useCallback(() => { const { state, dispatch } = view; @@ -64,7 +64,7 @@ export function MediaLinkEditor({ const update = useCallback(() => { const { state } = view; - const hrefType = node?.type.name === "image" ? "src" : "href"; + const hrefType = isSrcNode ? "src" : "href"; const tr = state.tr.setNodeMarkup(state.selection.from, undefined, { ...node?.attrs, [hrefType]: localUrl, @@ -73,7 +73,7 @@ export function MediaLinkEditor({ view.dispatch(tr); moveSelectionToEnd(); onLinkUpdate(); - }, [localUrl, node, view, moveSelectionToEnd, onLinkUpdate]); + }, [localUrl, node, isSrcNode, view, moveSelectionToEnd, onLinkUpdate]); useOnClickOutside(wrapperRef, onClickOutside); @@ -108,7 +108,7 @@ export function MediaLinkEditor({ return ( <Wrapper ref={wrapperRef}> <Input - autoFocus={isEditingImgUrl} + autoFocus={isSrcNode} value={localUrl} placeholder={`${t("Paste a link")}…`} onChange={(e) => setLocalUrl(e.target.value)} @@ -123,7 +123,11 @@ export function MediaLinkEditor({ {view.editable && ( <Tooltip content={ - node.type.name === "embed" ? t("Delete embed") : t("Delete image") + node.type.name === "embed" + ? t("Delete embed") + : node.type.name === "video" + ? t("Delete video") + : t("Delete image") } > <ToolbarButton onClick={remove}> diff --git a/app/editor/components/MentionMenu.tsx b/app/editor/components/MentionMenu.tsx index 55778f7cf4..5f45ceafca 100644 --- a/app/editor/components/MentionMenu.tsx +++ b/app/editor/components/MentionMenu.tsx @@ -3,7 +3,6 @@ import { v4 as uuidv4 } from "uuid"; import { runInAction } from "mobx"; import { useState, useCallback, useEffect } from "react"; import { useTranslation } from "react-i18next"; -import { useLocation } from "react-router-dom"; import { toast } from "sonner"; import { MentionType } from "@shared/types"; import { @@ -29,6 +28,7 @@ import { import useRequest from "~/hooks/useRequest"; import useStores from "~/hooks/useStores"; import useUserLocale from "~/hooks/useUserLocale"; +import { useLocationSelector } from "~/hooks/useLocationSelector"; import type Model from "~/models/base/Model"; import { client } from "~/utils/ApiClient"; import { useEditor } from "./EditorContext"; @@ -53,8 +53,9 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) { const { auth, documents, users, collections, groups } = useStores(); const { props: editorProps } = useEditor(); const actorId = auth.currentUserId; - const location = useLocation(); - const documentId = parseDocumentSlug(location.pathname); + const documentId = useLocationSelector((location) => + parseDocumentSlug(location.pathname) + ); const userLocale = useUserLocale(); const maxResultsInSection = search ? 25 : 5; @@ -184,6 +185,8 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) { .concat( collections .findByQuery(search, { maxResults: maxResultsInSection, weight }) + // A personal collection has no page for a mention to link to. + .filter((collection) => !collection.isPersonal) .map((collection) => collectionMentionItem(collection, actorId)) ) .concat( @@ -220,7 +223,7 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) { const user = users.get(item.attrs.modelId); toast.message( t( - "{{ userName }} won't be notified, as they do not have access to this document", + "{{ userName }} won’t be notified, as they do not have access to this document", { userName: item.attrs.label, } @@ -235,7 +238,7 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) { const group = groups.get(item.attrs.modelId); toast.message( t( - `Members of "{{ groupName }}" that have access to this document will be notified`, + "Members of “{{ groupName }}” with access to this document will be notified", { groupName: item.attrs.label, } diff --git a/app/editor/components/NoticeIcon.tsx b/app/editor/components/NoticeIcon.tsx new file mode 100644 index 0000000000..a7027df84d --- /dev/null +++ b/app/editor/components/NoticeIcon.tsx @@ -0,0 +1,44 @@ +import { DoneIcon, InfoIcon, StarredIcon, WarningIcon } from "outline-icons"; +import styled from "styled-components"; +import { NoticeTypes } from "@shared/editor/nodes/Notice"; +import { s } from "@shared/styles"; + +interface Props { + /** The style of the notice. */ + type: NoticeTypes; +} + +/** + * Renders the icon for a notice style, colored to match the notice in the editor. + * + * @param props the component props. + * @returns the icon element. + */ +export function NoticeIcon({ type }: Props) { + switch (type) { + case NoticeTypes.Success: + return <SuccessIcon />; + case NoticeTypes.Warning: + return <NoticeWarningIcon />; + case NoticeTypes.Tip: + return <TipIcon />; + default: + return <NoticeInfoIcon />; + } +} + +const NoticeInfoIcon = styled(InfoIcon)` + color: ${s("noticeInfoText")}; +`; + +const SuccessIcon = styled(DoneIcon)` + color: ${s("noticeSuccessText")}; +`; + +const NoticeWarningIcon = styled(WarningIcon)` + color: ${s("noticeWarningText")}; +`; + +const TipIcon = styled(StarredIcon)` + color: ${s("noticeTipText")}; +`; diff --git a/app/editor/components/PasteMenu.tsx b/app/editor/components/PasteMenu.tsx index 12a3efafb7..016cda69d8 100644 --- a/app/editor/components/PasteMenu.tsx +++ b/app/editor/components/PasteMenu.tsx @@ -1,11 +1,11 @@ import { observer } from "mobx-react"; import { v4 as uuidv4 } from "uuid"; -import { EmailIcon, LinkIcon } from "outline-icons"; +import { AlignImageRightIcon, EmailIcon, LinkIcon } from "outline-icons"; import { useCallback, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import type { EmbedDescriptor } from "@shared/editor/embeds"; import type { MenuItem } from "@shared/editor/types"; -import { MentionType } from "@shared/types"; +import { MentionDisplay, MentionType } from "@shared/types"; import { isInternalUrl, isUrl } from "@shared/utils/urls"; import type Integration from "~/models/Integration"; import useCurrentUser from "~/hooks/useCurrentUser"; @@ -142,6 +142,21 @@ function useItems({ }, appendSpace: true, }, + { + name: "mention", + title: t("Card"), + icon: <AlignImageRightIcon />, + visible: mentionType === MentionType.URL && !isInternal, + attrs: { + id: uuidv4(), + type: MentionType.URL, + label: pastedText, + href: pastedText, + modelId: uuidv4(), + actorId: user?.id, + display: MentionDisplay.Card, + }, + }, { name: "embed", title: t("Embed"), diff --git a/app/editor/components/SelectionToolbar.tsx b/app/editor/components/SelectionToolbar.tsx index adec360b00..b256f1d394 100644 --- a/app/editor/components/SelectionToolbar.tsx +++ b/app/editor/components/SelectionToolbar.tsx @@ -1,3 +1,4 @@ +import { observer } from "mobx-react"; import type { EditorState, Selection } from "prosemirror-state"; import Suggestion from "~/editor/extensions/Suggestion"; import { NodeSelection, TextSelection } from "prosemirror-state"; @@ -26,6 +27,7 @@ import LinkEditor from "./LinkEditor"; import ToolbarMenu from "./ToolbarMenu"; import InlineMenu from "./InlineMenu"; import StickyBlockToolbar from "./StickyBlockToolbar"; +import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; import { isModKey } from "@shared/utils/keyboard"; type Props = { @@ -67,9 +69,12 @@ enum Toolbar { Menu = "menu", } -export function SelectionToolbar(props: Props) { +export const SelectionToolbar = observer(function SelectionToolbar( + props: Props +) { const { readOnly = false, isEditorFocused } = props; - const { view, extensions, commands, selectionToolbarMenus } = useEditor(); + const editor = useEditor(); + const { view, extensions, commands, selectionToolbarMenus } = editor; const menuRef = React.useRef<HTMLDivElement | null>(null); const isMobile = useMobile(); const isActive = props.isActive || isMobile; @@ -78,7 +83,10 @@ export function SelectionToolbar(props: Props) { // visible for as long as the editor is being edited rather than only while // there is a selection. const isMobileEditing = isMobile && !readOnly && isEditorFocused; - const { state } = view; + + // Only an active toolbar follows the editor state, so an inactive toolbar + // does not render on each transaction. + const state = isActive ? editor.editorState : view.state; const [autoFocusLinkInput, setAutoFocusLinkInput] = React.useState(false); const isDragging = useIsDragging(state); const { selection } = state; @@ -122,7 +130,7 @@ export function SelectionToolbar(props: Props) { } // `activeToolbar` is read to decide whether the link toolbar should stay // open, re-running when it changes would fight the user's own selection. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [ readOnly, isActive, @@ -248,7 +256,7 @@ export function SelectionToolbar(props: Props) { items = items.map((item) => { if (item.children && Array.isArray(item.children)) { item.children = item.children.map((child) => { - if (child.name === "editImageUrl") { + if (child.name === "editImageUrl" || child.name === "editVideoUrl") { child.onClick = () => { setActiveToolbar(Toolbar.Media); }; @@ -267,7 +275,10 @@ export function SelectionToolbar(props: Props) { }); const handleClickOutsideLinkEditor = (ev: MouseEvent | TouchEvent) => { - if (ev.target instanceof Element && ev.target.closest(".image-wrapper")) { + if ( + ev.target instanceof Element && + ev.target.closest(`.${EditorStyleHelper.imageWrapper}`) + ) { return; } setActiveToolbar(null); @@ -283,6 +294,11 @@ export function SelectionToolbar(props: Props) { return <InlineMenu items={items} rtl={rtl} />; } + // Read-only code blocks show their toolbar on hover, see CodeBlockHoverToolbar. + if (matched?.sticky && readOnly && !isMobile && !ctx.isTouch) { + return null; + } + // Block toolbars (code, notice) stick to the top of the viewport as the block // scrolls instead of floating at a position fixed on selection. On mobile the // floating toolbar renders as a bottom bar, so the sticky path is desktop only. @@ -333,8 +349,8 @@ export function SelectionToolbar(props: Props) { /> ) : (activeToolbar === Toolbar.Menu || isMobileEditing) && items.length ? ( - <ToolbarMenu items={items} {...rest} /> + <ToolbarMenu items={items} showUndo={isMobileEditing} {...rest} /> ) : null} </FloatingToolbar> ); -} +}); diff --git a/app/editor/components/StickyBlockToolbar.tsx b/app/editor/components/StickyBlockToolbar.tsx index e438dd60fa..2bd0dcaa7f 100644 --- a/app/editor/components/StickyBlockToolbar.tsx +++ b/app/editor/components/StickyBlockToolbar.tsx @@ -19,6 +19,12 @@ type Props = { rtl: boolean; /** Ref to the track element. */ ref?: React.RefObject<HTMLDivElement | null>; + /** The block element to track, defaults to the block holding the selection. */ + element?: HTMLElement | null; + /** Called when the pointer enters the toolbar. */ + onMouseEnter?: React.MouseEventHandler<HTMLDivElement>; + /** Called when the pointer leaves the toolbar. */ + onMouseLeave?: React.MouseEventHandler<HTMLDivElement>; }; type TrackRect = { @@ -79,11 +85,17 @@ function sameRect(a: TrackRect | null, b: TrackRect | null) { * it visible without any scroll listener and releases it when the block leaves * the viewport. * - * @param items - the menu items to render. - * @param rtl - whether the document is right-to-left. + * @param props - the component props. * @returns the sticky block toolbar. */ -function StickyBlockToolbar({ items, rtl, ref }: Props) { +function StickyBlockToolbar({ + items, + rtl, + ref, + onMouseEnter, + onMouseLeave, + ...props +}: Props) { const { view } = useEditor(); const trackRef = ref || React.createRef<HTMLDivElement>(); const [rect, setRect] = React.useState<TrackRect | null>(null); @@ -92,7 +104,8 @@ function StickyBlockToolbar({ items, rtl, ref }: Props) { // Re-measure when the window resizes; scroll is handled by `position: sticky`. useWindowSize(); - const element = getBlockElement(view); + const element = + props.element === undefined ? getBlockElement(view) : props.element; // Re-measure when the block's size changes (e.g. after an auto-expand that // settles after the initial mount, or a font load that shifts layout). @@ -107,7 +120,7 @@ function StickyBlockToolbar({ items, rtl, ref }: Props) { // Measure the block relative to the portal's offset parent. Runs after every // render by design, the rect comparison prevents a loop. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps React.useLayoutEffect(() => { const track = trackRef.current; if (!element || !track) { @@ -152,7 +165,7 @@ function StickyBlockToolbar({ items, rtl, ref }: Props) { : undefined } > - <Sticky> + <Sticky onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}> <Background> <ToolbarMenu items={items} /> </Background> diff --git a/app/editor/components/SuggestionsMenu.tsx b/app/editor/components/SuggestionsMenu.tsx index 5b381f4a0d..0089d910a9 100644 --- a/app/editor/components/SuggestionsMenu.tsx +++ b/app/editor/components/SuggestionsMenu.tsx @@ -42,7 +42,6 @@ export type Props<T extends MenuItem = MenuItem> = { uploadFile?: (file: File) => Promise<string>; onFileUploadStart?: () => void; onFileUploadStop?: () => void; - onFileUploadProgress?: (id: string, fractionComplete: number) => void; /** Callback when the menu is closed */ onClose: (insertNewLine?: boolean) => void; /** Optional callback when a suggestion is selected */ @@ -281,7 +280,7 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) { } else { selectionRef.current = null; } - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [props.isActive, props.search]); React.useEffect(() => { @@ -525,12 +524,7 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) { ) => { restoreSelection(); - const { - uploadFile, - onFileUploadStart, - onFileUploadStop, - onFileUploadProgress, - } = props; + const { uploadFile, onFileUploadStart, onFileUploadStop } = props; const files = getEventFiles(event); const parent = findParentNode((node) => !!node)(view.state.selection); const attrs = event.currentTarget.dataset.attrs @@ -548,7 +542,6 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) { uploadFile, onFileUploadStart, onFileUploadStop, - onFileUploadProgress, onNotice: toastNotice, isAttachment: inputRef.current?.accept === "*", attrs, @@ -562,7 +555,14 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) { props.onClose(); }; + const lastFilteredRef = React.useRef<(EmbedDescriptor | MenuItem)[]>([]); const filtered = React.useMemo(() => { + // The list is not visible while the menu is closed, keep the last result + // for any closing animation rather than building it again. + if (!props.isActive) { + return lastFilteredRef.current; + } + const { embeds = [], search = "", uploadFile, filterable = true } = props; let items: (EmbedDescriptor | MenuItem)[] = [...props.items]; const embedItems: EmbedDescriptor[] = []; @@ -676,6 +676,7 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) { ).map(({ item }) => item) ); }, [commands, props]); + lastFilteredRef.current = filtered; const openSubmenu = React.useCallback( (index: number) => { @@ -917,6 +918,18 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) { submenu, }); + // Keep the items rendered on mobile until the drawer has animated closed. + const [isDrawerVisible, setDrawerVisible] = React.useState(false); + if (isActive && !isDrawerVisible) { + setDrawerVisible(true); + } + + const handleDrawerAnimationEnd = React.useCallback((open: boolean) => { + if (!open) { + setDrawerVisible(false); + } + }, []); + const handleOpenChange = React.useCallback( (open: boolean) => { if (!open) { @@ -1084,7 +1097,11 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) { if (isMobile) { return ( <> - <Drawer open={isActive} onOpenChange={handleOpenChange}> + <Drawer + open={isActive} + onOpenChange={handleOpenChange} + onAnimationEnd={handleDrawerAnimationEnd} + > <DrawerContent aria-describedby={undefined}> <DrawerTitle hidden> {Array.isArray(props.trigger) ? props.trigger[0] : props.trigger} @@ -1098,7 +1115,7 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) { "placeholder" in insertItem && !!insertItem.placeholder ? insertItem.placeholder : insertItem.title - ? t("Paste a {{service}} link…", { + ? t("Paste a link from {{service}}…", { service: insertItem.title, }) : `${t("Paste a link")}…` @@ -1114,7 +1131,7 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) { id={listboxId} aria-label={t("Suggestions")} > - {renderItems()} + {isDrawerVisible && renderItems()} </List> )} </MobileScrollable> @@ -1156,7 +1173,7 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) { "placeholder" in insertItem && !!insertItem.placeholder ? insertItem.placeholder : insertItem.title - ? t("Paste a {{service}} link…", { + ? t("Paste a link from {{service}}…", { service: insertItem.title, }) : `${t("Paste a link")}…` @@ -1168,7 +1185,7 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) { </LinkInputWrapper> ) : ( <List role="listbox" id={listboxId} aria-label={t("Suggestions")}> - {renderItems()} + {isActive && renderItems()} </List> )} </BouncyPopoverContent> diff --git a/app/editor/components/ToolbarMenu.tsx b/app/editor/components/ToolbarMenu.tsx index dd0fbad807..fa67f235d0 100644 --- a/app/editor/components/ToolbarMenu.tsx +++ b/app/editor/components/ToolbarMenu.tsx @@ -1,10 +1,11 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import * as Toolbar from "@radix-ui/react-toolbar"; import { closeHistory } from "@shared/editor/lib/closeHistory"; import { MenuItemGroup, type MenuItem } from "@shared/editor/types"; import { hideScrollbars, s } from "@shared/styles"; +import { UndoIcon } from "~/components/Icons/UndoIcon"; import { TooltipProvider } from "~/components/TooltipContext"; import useMobile from "~/hooks/useMobile"; import type { MenuItem as TMenuItem } from "~/types"; @@ -15,6 +16,11 @@ import ToolbarButton from "./ToolbarButton"; import ToolbarSeparator from "./ToolbarSeparator"; import Tooltip from "./Tooltip"; import { toMenuItems } from "~/components/Menu/transformer"; +import { + MenuFilter, + MenuFilterEmpty, + useMenuFilter, +} from "~/components/Menu/MenuFilter"; import { MenuContent } from "~/components/primitives/Menu"; import { MenuProvider } from "~/components/primitives/Menu/MenuContext"; import { Menu, MenuTrigger } from "~/components/primitives/Menu"; @@ -23,6 +29,8 @@ import EventBoundary from "@shared/components/EventBoundary"; type Props = { items: MenuItem[]; + /** Whether to pin an undo button to the start of the toolbar. */ + showUndo?: boolean; }; type ToolbarDropdownProps = { @@ -41,10 +49,23 @@ function ToolbarDropdown(props: ToolbarDropdownProps) { const { item, shortcut, tooltip } = props; const { state } = view; const [isOpen, setIsOpen] = useState<boolean>(false); + const { + query, + setQuery, + handleKeyDownCapture, + handleEscapeKeyDown, + reset: resetFilter, + } = useMenuFilter(); - const handleOpenChange = useCallback((open: boolean) => { - setIsOpen(open); - }, []); + const handleOpenChange = useCallback( + (open: boolean) => { + setIsOpen(open); + if (open) { + resetFilter(); + } + }, + [resetFilter] + ); const items: TMenuItem[] = useMemo(() => { if (!isOpen) { @@ -58,7 +79,7 @@ function ToolbarDropdown(props: ToolbarDropdownProps) { : []; // Menu items are resolved against the editor state at the moment the menu // opens, recomputing on every transaction would rebuild the open menu. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [isOpen, commands]); const handleCloseAutoFocus = useCallback((ev: Event) => { @@ -83,8 +104,14 @@ function ToolbarDropdown(props: ToolbarDropdownProps) { align="end" aria-label={item.tooltip || t("More options")} onCloseAutoFocus={handleCloseAutoFocus} + onEscapeKeyDown={handleEscapeKeyDown} + onKeyDownCapture={handleKeyDownCapture} > - <EventBoundary>{toMenuItems(items)}</EventBoundary> + <MenuFilter query={query} onChange={setQuery} /> + <EventBoundary> + {toMenuItems(items, query) ?? + (query ? <MenuFilterEmpty /> : null)} + </EventBoundary> </MenuContent> </Menu> </MenuProvider> @@ -94,7 +121,8 @@ function ToolbarDropdown(props: ToolbarDropdownProps) { function ToolbarMenu(props: Props) { const { commands, view } = useEditor(); - const { items } = props; + const { t } = useTranslation(); + const { items, showUndo } = props; const { state } = view; const isMobile = useMobile(); const wrapperRef = useRef<HTMLDivElement>(null); @@ -141,67 +169,85 @@ function ToolbarMenu(props: Props) { closeHistory(view); }; + const handleUndo = () => { + commands.undo(); + }; + + const content = ( + <FlexibleWrapper ref={wrapperRef} $pinned={showUndo}> + {items.map((item, index) => { + if (item.name === "separator" && item.visible !== false) { + // The mobile bar spaces its buttons evenly instead, as dividers + // would eat into the room for them. + return isMobile ? null : <ToolbarSeparator key={index} />; + } + if (item.visible === false || (!item.skipIcon && !item.icon)) { + return null; + } + const isActive = item.active ? item.active(state) : false; + + if (item.children) { + return ( + <ToolbarDropdown + key={index} + active={isActive && !item.label} + item={item} + tooltip={item.label === item.tooltip ? undefined : item.tooltip} + shortcut={item.shortcut} + /> + ); + } + + return ( + <Tooltip + key={index} + shortcut={item.shortcut} + content={item.label === item.tooltip ? undefined : item.tooltip} + > + {item.name === "dimensions" ? ( + <MediaDimension key={index} /> + ) : ( + <Toolbar.Button asChild> + <ToolbarButton + data-group={item.group} + onClick={handleClick(item)} + active={isActive && !item.label} + aria-label={item.label ? undefined : item.tooltip} + disabled={item.disabled} + > + {item.label && <Label>{item.label}</Label>} + {item.icon} + </ToolbarButton> + </Toolbar.Button> + )} + </Tooltip> + ); + })} + </FlexibleWrapper> + ); + return ( <TooltipProvider> <Toolbar.Root asChild> - <FlexibleWrapper ref={wrapperRef}> - {items.map((item, index) => { - if (item.name === "separator" && item.visible !== false) { - // The mobile bar spaces its buttons evenly instead, as dividers - // would eat into the room for them. - return isMobile ? null : <ToolbarSeparator key={index} />; - } - if (item.visible === false || (!item.skipIcon && !item.icon)) { - return null; - } - const isActive = item.active ? item.active(state) : false; - - if (item.children) { - return ( - <ToolbarDropdown - key={index} - active={isActive && !item.label} - item={item} - tooltip={ - item.label === item.tooltip ? undefined : item.tooltip - } - shortcut={item.shortcut} - /> - ); - } - - return ( - <Tooltip - key={index} - shortcut={item.shortcut} - content={item.label === item.tooltip ? undefined : item.tooltip} - > - {item.name === "dimensions" ? ( - <MediaDimension key={index} /> - ) : ( - <Toolbar.Button asChild> - <ToolbarButton - data-group={item.group} - onClick={handleClick(item)} - active={isActive && !item.label} - aria-label={item.label ? undefined : item.tooltip} - disabled={item.disabled} - > - {item.label && <Label>{item.label}</Label>} - {item.icon} - </ToolbarButton> - </Toolbar.Button> - )} - </Tooltip> - ); - })} - </FlexibleWrapper> + {showUndo ? ( + <PinnedWrapper> + <Toolbar.Button asChild> + <PinnedButton onClick={handleUndo} aria-label={t("Undo")}> + <UndoIcon /> + </PinnedButton> + </Toolbar.Button> + <PinnedSeparator /> + {content} + </PinnedWrapper> + ) : ( + content + )} </Toolbar.Root> </TooltipProvider> ); } -const FlexibleWrapper = styled.div` +const FlexibleWrapper = styled.div<{ $pinned?: boolean }>` color: ${s("textSecondary")}; overflow: hidden; display: flex; @@ -237,6 +283,37 @@ const FlexibleWrapper = styled.div` ${hideScrollbars()} `} + + // A pinned button takes the place of one of the six. The space after the + // separator is padding so buttons scroll right up to the separator. + ${(props) => + props.$pinned && + breakpoint("mobile", "tablet")` + flex: 1; + gap: 0 calc((100% - 20px) / 5 - 40px); + padding-inline-start: 8px; + scroll-padding-inline-start: 8px; + `} +`; + +const PinnedWrapper = styled.div` + display: flex; + align-items: center; + min-width: 0; +`; + +const PinnedButton = styled(ToolbarButton)` + flex-shrink: 0; + min-width: 40px; + height: 40px; + justify-content: center; + border-radius: 20px; +`; + +const PinnedSeparator = styled(ToolbarSeparator)` + flex-shrink: 0; + height: 24px; + margin: 0 0 0 4px; `; const Label = styled.span` diff --git a/app/editor/extensions/BlockMenu.tsx b/app/editor/extensions/BlockMenu.tsx index 4f3cc1faed..543ef62f58 100644 --- a/app/editor/extensions/BlockMenu.tsx +++ b/app/editor/extensions/BlockMenu.tsx @@ -123,7 +123,6 @@ export default class BlockMenuExtension extends Suggestion { uploadFile={props.uploadFile} onFileUploadStart={props.onFileUploadStart} onFileUploadStop={props.onFileUploadStop} - onFileUploadProgress={props.onFileUploadProgress} embeds={props.embeds} /> ); diff --git a/app/editor/extensions/DragHandle.ts b/app/editor/extensions/DragHandle.ts new file mode 100644 index 0000000000..62ba35274a --- /dev/null +++ b/app/editor/extensions/DragHandle.ts @@ -0,0 +1,485 @@ +import { t } from "i18next"; +import { NodeSelection, Plugin, PluginKey, Selection } from "prosemirror-state"; +import type { EditorView } from "prosemirror-view"; +import { Decoration, DecorationSet } from "prosemirror-view"; +import Extension from "@shared/editor/lib/Extension"; +import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; +import type { DragTargetKind } from "~/editor/plugins/DragTarget"; +import { DragTarget } from "~/editor/plugins/DragTarget"; + +const HANDLE_SIZE = 24; + +// Vertical offset of the icon within the handle, matches its mask-position. +const ICON_OFFSET_Y = 2; + +// Vertical center of the icon within the handle. +const ICON_CENTER_Y = HANDLE_SIZE / 2 + ICON_OFFSET_Y; + +// Tolerance when checking that text is rendered inside its block. +const RECT_TOLERANCE = 1; +const META_KEY = "drag-handle"; + +// Horizontal distance from the block's edge to the handle, per kind of block. +const GUTTER_OFFSET: Record<DragTargetKind, number> = { + block: 24, + listItem: 40, + checkboxItem: 0, +}; + +type PluginState = { + pos: number; + size: number; +} | null; + +const pluginKey = new PluginKey<PluginState>(META_KEY); +const HOVER_META_KEY = "drag-handle-hover"; +const hoverPluginKey = new PluginKey<number | null>(HOVER_META_KEY); + +/** + * Renders a floating drag handle to the left of block-level nodes when the + * user hovers near the side of the editor, and lets the user drag the block to reorder + * it. The handle is a real, always-draggable DOM element rather than a CSS + * pseudo on the block, which keeps drag-and-drop working uniformly across + * node types regardless of whether the schema declares `draggable: true`. + */ +export default class DragHandle extends Extension { + get name() { + return "drag-handle"; + } + + get plugins() { + return [ + // Marks the heading that owns the handle, so its level label in the + // gutter can be hidden. + new Plugin<number | null>({ + key: hoverPluginKey, + state: { + init: () => null, + apply: (tr, value) => { + const meta = tr.getMeta(HOVER_META_KEY) as + | { pos: number | null } + | undefined; + if (meta) { + return meta.pos; + } + if (value !== null && tr.docChanged) { + const { pos: newPos, deleted } = tr.mapping.mapResult(value, 1); + return !deleted && tr.doc.nodeAt(newPos)?.type.name === "heading" + ? newPos + : null; + } + return value; + }, + }, + props: { + decorations: (state) => { + const pos = hoverPluginKey.getState(state) ?? null; + const node = pos === null ? null : state.doc.nodeAt(pos); + if (pos === null || !node) { + return DecorationSet.empty; + } + return DecorationSet.create(state.doc, [ + Decoration.node(pos, pos + node.nodeSize, { + class: EditorStyleHelper.dragHandleTarget, + }), + ]); + }, + }, + }), + new Plugin<PluginState>({ + key: pluginKey, + state: { + init: () => null, + apply: (tr, value) => { + const meta = tr.getMeta(META_KEY) as + | { pos: number | null } + | undefined; + if (meta) { + if (meta.pos === null) { + return null; + } + const node = tr.doc.nodeAt(meta.pos); + if (!node) { + return null; + } + return { pos: meta.pos, size: node.nodeSize }; + } + if (value && tr.docChanged) { + const newPos = tr.mapping.map(value.pos); + const node = tr.doc.nodeAt(newPos); + if (!node) { + return null; + } + return { pos: newPos, size: node.nodeSize }; + } + return value; + }, + }, + appendTransaction: (transactions, oldState, newState) => { + const isDrop = transactions.some( + (tr) => tr.getMeta("uiEvent") === "drop" + ); + if (!isDrop || !pluginKey.getState(oldState)) { + return null; + } + + // ProseMirror selects the dropped content, which would open the + // formatting toolbar, so collapse it to a cursor at the end instead. + const $end = newState.doc.resolve(newState.selection.to); + const selection = + Selection.findFrom($end, -1, true) ?? + Selection.findFrom($end, 1, true); + const tr = newState.tr.setMeta(META_KEY, { pos: null }); + return selection ? tr.setSelection(selection) : tr; + }, + props: { + decorations: (state) => { + const dragState = pluginKey.getState(state); + if (!dragState) { + return DecorationSet.empty; + } + return DecorationSet.create(state.doc, [ + Decoration.node(dragState.pos, dragState.pos + dragState.size, { + class: EditorStyleHelper.draggingSource, + }), + ]); + }, + handleDOMEvents: { + dragstart: (view) => { + view.dom.classList.add("dragging"); + return false; + }, + drop: (view) => { + view.dom.classList.remove("dragging"); + return false; + }, + dragend: (view) => { + view.dom.classList.remove("dragging"); + if (pluginKey.getState(view.state)) { + view.dispatch(view.state.tr.setMeta(META_KEY, { pos: null })); + } + return false; + }, + }, + }, + view: (view) => { + const handle = createHandle(); + document.body.appendChild(handle); + + let target: DragTarget | null = null; + + const onDragEnd = () => { + view.dom.classList.remove("dragging"); + + // The handle is outside the editor DOM, so ProseMirror's own + // dragend cleanup does not run for it. + view.dragging = null; + if (pluginKey.getState(view.state)) { + view.dispatch(view.state.tr.setMeta(META_KEY, { pos: null })); + } + }; + + const position = (next: DragTarget) => { + const rect = next.element.getBoundingClientRect(); + const offsetX = GUTTER_OFFSET[next.kind]; + + // Center the icon on the first line of text when the block has + // one, or on blocks shorter than the handle, otherwise align it + // with the top of the block. + const lineMiddle = + (next.element === view.nodeDOM(next.pos) + ? getFirstLineMiddle(view, next.pos, rect) + : null) ?? + (rect.height < HANDLE_SIZE ? rect.top + rect.height / 2 : null); + + // RTL blocks lay out their gutter on the right, so mirror the + // handle to the opposite edge to match the rest of the editor's + // :dir(rtl) handling. + const isRTL = + window.getComputedStyle(next.element).direction === "rtl"; + const top = + lineMiddle === null + ? rect.top - ICON_OFFSET_Y + : lineMiddle - ICON_CENTER_Y; + const left = isRTL + ? rect.right + offsetX - HANDLE_SIZE + : rect.left - offsetX; + + // Hide the handle past the viewport edge, such as when an inner + // scroll container clips its block, so it does not grow the page. + const { clientWidth, clientHeight } = document.documentElement; + if ( + top + HANDLE_SIZE > clientHeight || + left + HANDLE_SIZE > clientWidth + ) { + handle.classList.remove("visible", "dragging"); + return; + } + + // Position in document coordinates so that the browser scrolls + // the handle with the page, rather than after the scroll event. + handle.style.top = `${top + window.scrollY}px`; + handle.style.left = `${left + window.scrollX}px`; + handle.classList.remove("dragging"); + handle.classList.add("visible"); + }; + + const show = (next: DragTarget) => { + target = next; + position(next); + setHoveredHeading( + view.state.doc.nodeAt(next.pos)?.type.name === "heading" + ? next.pos + : null + ); + }; + + const hideHandle = () => { + target = null; + handle.classList.remove("visible", "dragging"); + }; + + const hide = () => { + hideHandle(); + setHoveredHeading(null); + }; + + const setHoveredHeading = (pos: number | null) => { + if ((hoverPluginKey.getState(view.state) ?? null) === pos) { + return; + } + view.dispatch(view.state.tr.setMeta(HOVER_META_KEY, { pos })); + }; + + const onMouseMove = (event: MouseEvent) => { + if (!view.editable) { + hide(); + return; + } + + // When the cursor is over the handle itself, keep the current + // target. Re-resolving from a cursor in the gutter can land on + // a different (often parent) block, causing the handle to + // flicker between the hovered block and its parent. + if (target && isOverElement(handle, event)) { + return; + } + const next = DragTarget.fromEvent(view, event); + if (next && !next.hasOwnControls(view.state)) { + // Skip repositioning when still hovering the same block — + // avoids a getBoundingClientRect and style writes on every + // mousemove. Scroll repositioning is handled separately. + if (next.equals(target)) { + return; + } + show(next); + } else { + hide(); + } + }; + + const onScroll = () => { + // While a drag is in progress the handle is intentionally hidden; + // don't let a scroll (trackpad / auto-scroll) reposition and + // re-show it mid-drag. + if (pluginKey.getState(view.state)) { + return; + } + if (target?.element.isConnected) { + show(target); + } else { + hide(); + } + }; + + const onDragStart = (event: DragEvent) => { + if (!target || !event.dataTransfer) { + return; + } + const pos = target.pos; + if (!view.state.doc.nodeAt(pos)) { + return; + } + const sourceElement = target.element; + + // Snapshot the drag image of the unmodified element first, so + // it isn't baked with the dragging-source opacity. Anchor it to + // its original screen position by offsetting by the cursor's + // location within the block (negative X — the cursor sits in + // the gutter to the left of the block). + const rect = sourceElement.getBoundingClientRect(); + event.dataTransfer.setDragImage( + sourceElement, + event.clientX - rect.left, + event.clientY - rect.top + ); + event.dataTransfer.clearData(); + event.dataTransfer.effectAllowed = "copyMove"; + + // Hide the handle for the duration of the drag — keep it + // interactive so the in-flight drag isn't cancelled. + handle.classList.add("dragging"); + const selection = NodeSelection.create(view.state.doc, pos); + + // Use the slice from the original NodeSelection rather than + // view.state.selection, which prosemirror-tables' tableEditing + // normalizes from a NodeSelection on a table into a CellSelection + // covering only the cells. + const slice = selection.content(); + const { dom, text } = view.serializeForClipboard(slice); + event.dataTransfer.setData("text/html", dom.innerHTML); + event.dataTransfer.setData("text/plain", text); + + // Include the original NodeSelection as `node` so ProseMirror's + // drop handler removes the source via node.replace(tr) rather + // than tr.deleteSelection() (which would operate on the + // normalized CellSelection and leave the table behind). + const dragging: { + slice: typeof slice; + move: boolean; + node: NodeSelection; + } = { + slice, + move: !event.ctrlKey, + node: selection, + }; + view.dragging = dragging; + view.dom.classList.add("dragging"); + view.focus(); + + // Apply the source decoration via the plugin's state and set + // the NodeSelection in a single transaction so the + // dragging-source class survives any DOM re-rendering caused + // by selection changes (e.g., tableEditing normalizing a table + // NodeSelection into a CellSelection). + view.dispatch( + view.state.tr.setSelection(selection).setMeta(META_KEY, { pos }) + ); + }; + + const onClick = () => { + if (!target) { + return; + } + view.focus(); + view.dispatch( + view.state.tr.setSelection( + NodeSelection.create(view.state.doc, target.pos) + ) + ); + }; + + window.addEventListener("mousemove", onMouseMove); + window.addEventListener("scroll", onScroll, { + capture: true, + passive: true, + }); + handle.addEventListener("dragstart", onDragStart); + handle.addEventListener("dragend", onDragEnd); + handle.addEventListener("click", onClick); + + return { + update: (_view, prevState) => { + if (!target) { + return; + } + const docChanged = view.state.doc !== prevState.doc; + if (docChanged) { + // Positions shift when the document changes, e.g. from a + // collaborator's edit, so resolve the target again from its DOM. + const next = DragTarget.fromElement(view, target.element); + if (!next) { + hideHandle(); + return; + } + target = next; + } + + // Leave the handle alone mid-drag so the drag is not cancelled. + if (pluginKey.getState(view.state)) { + return; + } + if (target.hasOwnControls(view.state)) { + hideHandle(); + return; + } + if (docChanged) { + position(target); + } + }, + destroy: () => { + window.removeEventListener("mousemove", onMouseMove); + window.removeEventListener("scroll", onScroll, { capture: true }); + handle.removeEventListener("dragstart", onDragStart); + handle.removeEventListener("dragend", onDragEnd); + handle.removeEventListener("click", onClick); + handle.remove(); + + // Only clean up the DOM class here — the plugin state is + // discarded on unmount, so avoid dispatching onto a view that + // is being torn down (e.g. unmounted mid-drag). + view.dom.classList.remove("dragging"); + }, + }; + }, + }), + ]; + } +} + +function createHandle(): HTMLElement { + const handle = document.createElement("button"); + handle.type = "button"; + handle.className = EditorStyleHelper.blockDragHandle; + handle.draggable = true; + handle.contentEditable = "false"; + handle.setAttribute("aria-label", t("Drag to reorder")); + return handle; +} + +function isOverElement(element: HTMLElement, event: MouseEvent): boolean { + const rect = element.getBoundingClientRect(); + return ( + event.clientX >= rect.left && + event.clientX <= rect.right && + event.clientY >= rect.top && + event.clientY <= rect.bottom + ); +} + +function getFirstLineMiddle( + view: EditorView, + pos: number, + rect: DOMRect +): number | null { + // Descend to the first textblock, and only use it when it begins with + // text – inline atoms such as images have no meaningful line. + let node = view.state.doc.nodeAt(pos); + let nodePos = pos; + while (node && !node.isTextblock) { + node = node.firstChild; + nodePos += 1; + } + if (!node?.firstChild?.isText) { + return null; + } + const textPos = nodePos + 1; + + let coords: { top: number; bottom: number }; + try { + coords = view.coordsAtPos(textPos, 1); + } catch { + return null; + } + + // Ignore text that is hidden or rendered outside the block, such as the + // source of a rendered math block. + if ( + coords.bottom <= coords.top || + coords.top < rect.top - RECT_TOLERANCE || + coords.bottom > rect.bottom + RECT_TOLERANCE + ) { + return null; + } + return (coords.top + coords.bottom) / 2; +} diff --git a/app/editor/extensions/FindAndReplace.tsx b/app/editor/extensions/FindAndReplace.tsx index c69a6bc964..9bfa478ea4 100644 --- a/app/editor/extensions/FindAndReplace.tsx +++ b/app/editor/extensions/FindAndReplace.tsx @@ -8,9 +8,8 @@ import scrollIntoView from "scroll-into-view-if-needed"; import type { WidgetProps } from "@shared/editor/lib/Extension"; import Extension from "@shared/editor/lib/Extension"; import { expandCodeBlockAt } from "@shared/editor/nodes/CodeFence"; -import { Action, toggleFoldPluginKey } from "@shared/editor/nodes/ToggleBlock"; -import { isToggleBlock } from "@shared/editor/queries/toggleBlock"; -import { ancestors } from "@shared/editor/utils"; +import { unfoldToggleBlocksAt } from "@shared/editor/commands/toggleBlock"; +import { toggleFoldPluginKey } from "@shared/editor/nodes/ToggleBlock"; import isTextInput from "~/utils/isTextInput"; import FindAndReplace from "../components/FindAndReplace"; import { deburrWithMap } from "./deburrWithMap"; @@ -264,48 +263,8 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt return; } - const state = this.editor.view.state; - const pluginState = toggleFoldPluginKey.getState(state); - if (!pluginState) { - return; - } - - const $pos = state.doc.resolve(result.from); - const isToggle = isToggleBlock(state); - - // Find all ancestor toggle block IDs that are folded - const foldedToggleIds = ancestors($pos) - .filter( - (node) => isToggle(node) && pluginState.foldedIds.has(node.attrs.id) - ) - .map((node) => node.attrs.id as string); - - // Unfold each toggle by ID (getting fresh state after each dispatch) - foldedToggleIds.forEach((toggleId) => { - const currentState = this.editor.view.state; - - // Find the position of this toggle in the current document - let togglePos: number | null = null; - currentState.doc.descendants((node, pos) => { - if ( - node.type.name === "container_toggle" && - node.attrs.id === toggleId - ) { - togglePos = pos; - return false; - } - return true; - }); - - if (togglePos !== null) { - this.editor.view.dispatch( - currentState.tr.setMeta(toggleFoldPluginKey, { - type: Action.UNFOLD, - at: togglePos, - }) - ); - } - }); + const view = this.editor.view; + unfoldToggleBlocksAt(result.from)(view.state, view.dispatch); } /** @@ -423,9 +382,9 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt const from = type === "inline" ? pos + start : pos; const to = type === "inline" ? pos + end : pos + node.nodeSize; - // A match against the deburred text can cover only part of a - // decomposed sequence (e.g. a single jamo of a Hangul syllable), - // which maps back to a zero-length range in the original text. + // A match against the deburred text can cover only part of an + // expanded letter (e.g. a single "s" of "ß"), which maps back to a + // zero-length range in the original text. // Skip these so replace operations don't degenerate into inserts. if (to <= from) { continue; @@ -452,9 +411,9 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt // Also search the diacritics-stripped text so that, for example, "cafe" // matches "café". Because deburring can change the string length (e.g. it - // decomposes CJK/Hangul characters), match indices are translated back to - // the original text rather than assumed equal. Skip it when deburring was - // a no-op, since it would only re-find the matches already collected. + // expands "ß" to "ss"), match indices are translated back to the original + // text rather than assumed equal. Skip it when deburring was a no-op, since + // it would only re-find the matches already collected. const { deburred, toOriginalIndex } = deburrWithMap(text); if (deburred !== text) { collect(deburred, toOriginalIndex); diff --git a/app/editor/extensions/Multiplayer.ts b/app/editor/extensions/Multiplayer.ts index 5b63648706..0b18310e3d 100644 --- a/app/editor/extensions/Multiplayer.ts +++ b/app/editor/extensions/Multiplayer.ts @@ -5,12 +5,7 @@ import { ySyncPlugin, ySyncPluginKey, yCursorPlugin, - yUndoPlugin, yUndoPluginKey, - undo, - redo, - undoCommand, - redoCommand, } from "y-prosemirror"; import * as Y from "yjs"; import Extension from "@shared/editor/lib/Extension"; @@ -142,7 +137,6 @@ export default class Multiplayer extends Extension<MultiplayerOptions> { awarenessStateFilter, selectionBuilder, }), - yUndoPlugin(), // Facade plugin that exposes the collaboration operations to shared // code without a static dependency on the collaboration libraries. new Plugin({ @@ -155,19 +149,4 @@ export default class Multiplayer extends Extension<MultiplayerOptions> { }), ]; } - - commands() { - return { - undo: () => undo, - redo: () => redo, - }; - } - - keys() { - return { - "Mod-z": undoCommand, - "Mod-y": redoCommand, - "Shift-Mod-z": redoCommand, - }; - } } diff --git a/app/editor/extensions/MultiplayerUndo.ts b/app/editor/extensions/MultiplayerUndo.ts new file mode 100644 index 0000000000..dd43812ca8 --- /dev/null +++ b/app/editor/extensions/MultiplayerUndo.ts @@ -0,0 +1,39 @@ +import { + yUndoPlugin, + undo, + redo, + undoCommand, + redoCommand, +} from "y-prosemirror"; +import Extension from "@shared/editor/lib/Extension"; + +/** + * Undo and redo for collaborative documents, backed by the Yjs undo manager. + * Must be registered after the Multiplayer extension, whose sync plugin it + * depends on. It is not created in read-only mode, so the undo manager is + * created fresh when the editor becomes editable. + */ +export class MultiplayerUndo extends Extension { + get name() { + return "multiplayerUndo"; + } + + get plugins() { + return [yUndoPlugin()]; + } + + commands() { + return { + undo: () => undo, + redo: () => redo, + }; + } + + keys() { + return { + "Mod-z": undoCommand, + "Mod-y": redoCommand, + "Shift-Mod-z": redoCommand, + }; + } +} diff --git a/app/editor/extensions/PasteHandler.tsx b/app/editor/extensions/PasteHandler.tsx index 9b9a861e49..7ea1843725 100644 --- a/app/editor/extensions/PasteHandler.tsx +++ b/app/editor/extensions/PasteHandler.tsx @@ -2,12 +2,13 @@ import { action, observable } from "mobx"; import { v4 as uuidv4 } from "uuid"; import { toggleMark } from "prosemirror-commands"; import type { Node } from "prosemirror-model"; -import { Slice } from "prosemirror-model"; +import { Fragment, Slice } from "prosemirror-model"; import type { EditorState } from "prosemirror-state"; import { Plugin, PluginKey, TextSelection } from "prosemirror-state"; import { Decoration, DecorationSet } from "prosemirror-view"; import type { WidgetProps } from "@shared/editor/lib/Extension"; import Extension from "@shared/editor/lib/Extension"; +import { pasteIntoListItem } from "@shared/editor/commands/pasteIntoListItem"; import { codeLanguages } from "@shared/editor/lib/code"; import isMarkdown from "@shared/editor/lib/isMarkdown"; import normalizePastedMarkdown from "@shared/editor/lib/markdown/normalize"; @@ -20,7 +21,12 @@ import { IconType, MentionType } from "@shared/types"; import { determineIconType } from "@shared/utils/icon"; import parseCollectionSlug from "@shared/utils/parseCollectionSlug"; import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; -import { isCollectionUrl, isDocumentUrl, isUrl } from "@shared/utils/urls"; +import { + isCollectionUrl, + isDocumentUrl, + isUrl, + signedUrlToAttachmentUrl, +} from "@shared/utils/urls"; import stores from "~/stores"; import { PasteMenu } from "../components/PasteMenu"; @@ -53,6 +59,7 @@ export default class PasteHandler extends Extension { } return html; }, + transformPasted: (slice) => this.replaceSignedUrls(slice), handleDOMEvents: { keydown: (_, event) => { this.shiftKey = event.shiftKey; @@ -63,7 +70,7 @@ export default class PasteHandler extends Extension { return false; }, }, - handlePaste: (view, event: ClipboardEvent) => { + handlePaste: (view, event: ClipboardEvent, slice: Slice) => { // Do nothing if the document isn't currently editable or there is no clipboard data if (!view.editable || !event.clipboardData) { return false; @@ -98,14 +105,14 @@ export default class PasteHandler extends Extension { if (!this.shiftKey) { // If the HTML on the clipboard is from Prosemirror then the best - // compatability is to just use the HTML parser, regardless of + // compatibility is to just use the HTML parser, regardless of // whether it "looks" like Markdown, see: outline/outline#2416 if (html?.includes("data-pm-slice")) { - return false; + return pasteIntoListItem(slice)(state, dispatch); } // If the HTML on the clipboard is from Claude then the best - // compatability is to just use the HTML parser. + // compatibility is to just use the HTML parser. if (html?.includes("font-claude-response-body")) { return false; } @@ -116,10 +123,13 @@ export default class PasteHandler extends Extension { // detection and skip the paste menu. const trimmedText = text.trim(); if (isUrl(trimmedText)) { + const href = + signedUrlToAttachmentUrl(trimmedText) ?? trimmedText; + // If there is selected text then we want to wrap it in a link to the url if (!state.selection.empty) { toggleMark(this.editor.schema.marks.link, { - href: trimmedText, + href, })(state, dispatch); return true; } @@ -149,7 +159,7 @@ export default class PasteHandler extends Extension { state.schema.nodes.mention.create({ type: MentionType.Document, modelId: document.id, - label: document.titleWithDefault, + label: document.displayTitle, id: uuidv4(), anchorId: trimmedHash.length ? trimmedHash @@ -164,7 +174,7 @@ export default class PasteHandler extends Extension { IconType.Emoji; const title = `${hasEmoji ? document.icon + " " : ""}${ - document.titleWithDefault + document.displayTitle }`; this.insertLink(`${document.path}${hash}`, title); @@ -197,7 +207,7 @@ export default class PasteHandler extends Extension { state.schema.nodes.mention.create({ type: MentionType.Collection, modelId: collection.id, - label: collection.name, + label: collection.displayName, id: uuidv4(), }) ) @@ -209,7 +219,7 @@ export default class PasteHandler extends Extension { IconType.Emoji; const title = `${hasEmoji ? collection.icon + " " : ""}${ - collection.name + collection.displayName }`; this.insertLink(`${collection.path}${hash}`, title); @@ -224,7 +234,7 @@ export default class PasteHandler extends Extension { }); } } else { - this.insertLink(trimmedText); + this.insertLink(href); } return true; @@ -288,7 +298,7 @@ export default class PasteHandler extends Extension { return false; } - const slice = paste.slice(0); + const slice = this.replaceSignedUrls(paste.slice(0)); const tr = view.state.tr; // If the pasted content is a single paragraph then we slice @@ -476,6 +486,51 @@ export default class PasteHandler extends Extension { } }; + /** + * Replaces signed attachment urls in the slice with stable attachment urls, + * as signed urls expire and must not be stored in the document. + * + * @param slice The pasted slice. + * @returns The slice with signed urls replaced. + */ + private replaceSignedUrls(slice: Slice): Slice { + const replaceUrl = (value: unknown) => + typeof value === "string" ? signedUrlToAttachmentUrl(value) : undefined; + + const mapFragment = (fragment: Fragment): Fragment => { + const nodes: Node[] = []; + + fragment.forEach((node) => { + const marks = node.marks.map((mark) => { + const href = replaceUrl(mark.attrs.href); + return href ? mark.type.create({ ...mark.attrs, href }) : mark; + }); + + if (node.isText) { + nodes.push(node.mark(marks)); + return; + } + + const attrs = { ...node.attrs }; + for (const name of ["src", "href"]) { + const url = replaceUrl(attrs[name]); + if (url) { + attrs[name] = url; + } + } + nodes.push(node.type.create(attrs, mapFragment(node.content), marks)); + }); + + return Fragment.from(nodes); + }; + + return new Slice( + mapFragment(slice.content), + slice.openStart, + slice.openEnd + ); + } + private handleList(listNode: Node) { const { view, schema } = this.editor; const { state } = view; diff --git a/app/editor/extensions/SelectionToolbar.tsx b/app/editor/extensions/SelectionToolbar.tsx index e710711abb..67f438fe95 100644 --- a/app/editor/extensions/SelectionToolbar.tsx +++ b/app/editor/extensions/SelectionToolbar.tsx @@ -4,6 +4,7 @@ import { NodeSelection, Plugin, TextSelection } from "prosemirror-state"; import type { EditorView } from "prosemirror-view"; import type { WidgetProps } from "@shared/editor/lib/Extension"; import Extension from "@shared/editor/lib/Extension"; +import { canDisplayAsCard } from "@shared/editor/lib/mention"; import { isInNotice } from "@shared/editor/queries/isInNotice"; import { isMarkActive } from "@shared/editor/queries/isMarkActive"; import { isNodeActive } from "@shared/editor/queries/isNodeActive"; @@ -11,6 +12,7 @@ import { MenuType, type SelectionToolbarMenuDescriptor, } from "@shared/editor/types"; +import { CodeBlockHoverToolbar } from "../components/CodeBlockHoverToolbar"; import { SelectionToolbar } from "../components/SelectionToolbar"; import getAttachmentMenuItems from "../menus/attachment"; import getCodeMenuItems from "../menus/code"; @@ -22,6 +24,7 @@ import getReadOnlyMenuItems from "../menus/readOnly"; import getTableMenuItems from "../menus/table"; import getTableColMenuItems from "../menus/tableCol"; import getTableRowMenuItems from "../menus/tableRow"; +import getVideoMenuItems from "../menus/video"; export default class SelectionToolbarExtension extends Extension { get name() { @@ -38,6 +41,14 @@ export default class SelectionToolbarExtension extends Extension { view: () => ({ update: this.handleUpdate, }), + props: { + handleDOMEvents: { + focus: (view) => { + this.handleUpdate(view, view.state); + return false; + }, + }, + }, }), ]; } @@ -98,6 +109,11 @@ export default class SelectionToolbarExtension extends Extension { matches: (ctx) => ctx.selectedNodeType === "attachment", getItems: (ctx) => getAttachmentMenuItems(ctx), }, + { + priority: 50, + matches: (ctx) => ctx.selectedNodeType === "video", + getItems: (ctx) => getVideoMenuItems(ctx), + }, { priority: 30, matches: (ctx) => ctx.readOnly, @@ -119,12 +135,15 @@ export default class SelectionToolbarExtension extends Extension { ]; } - private handleUpdate = action((view: EditorView) => { - const { state } = view; - this.state = this.calculateState(state); + private handleUpdate = action((view: EditorView, prevState: EditorState) => { + this.state = this.calculateState(view, prevState); }); - private calculateState(state: EditorState): Selection | boolean { + private calculateState( + view: EditorView, + prevState: EditorState + ): Selection | boolean { + const { state } = view; const { selection, doc, schema } = state; if (isMarkActive(schema.marks.link)(state)) { @@ -133,13 +152,10 @@ export default class SelectionToolbarExtension extends Extension { if ( isNodeActive(schema.nodes.code_block)(state) || - isNodeActive(schema.nodes.code_fence)(state) + isNodeActive(schema.nodes.code_fence)(state) || + (isInNotice(state) && selection.from > 0) ) { - return selection; - } - - if (isInNotice(state) && selection.from > 0) { - return selection; + return this.isBlockToolbarAllowed(view, prevState) ? selection : false; } if (!selection || selection.empty) { @@ -155,7 +171,17 @@ export default class SelectionToolbarExtension extends Extension { if ( selection instanceof NodeSelection && - ["image", "attachment", "embed"].includes(selection.node.type.name) + ["image", "attachment", "embed", "video"].includes( + selection.node.type.name + ) + ) { + return selection; + } + + if ( + selection instanceof NodeSelection && + view.editable && + canDisplayAsCard(selection.node) ) { return selection; } @@ -180,18 +206,43 @@ export default class SelectionToolbarExtension extends Extension { return false; } + /** + * Whether a block toolbar can show, only for a selection the user placed. + * + * @param view The editor view. + * @param prevState The editor state before this update. + * @returns True if a block toolbar can show for the current selection. + */ + private isBlockToolbarAllowed(view: EditorView, prevState: EditorState) { + if (!view.editable || view.hasFocus()) { + return true; + } + + // Focus moves into the toolbar's own menus, keep it open while they edit + // the block. + return !!this.state && prevState.selection.eq(view.state.selection); + } + widget = (props: WidgetProps) => { const editorProps = this.editor.props; return ( - <SelectionToolbar - {...props} - isActive={!!this.state} - selection={this.state ? (this.state as Selection) : undefined} - canUpdate={editorProps.canUpdate} - canComment={editorProps.canComment} - isTemplate={editorProps.template === true} - /> + <> + <SelectionToolbar + {...props} + isActive={!!this.state} + selection={this.state ? (this.state as Selection) : undefined} + canUpdate={editorProps.canUpdate} + canComment={editorProps.canComment} + isTemplate={editorProps.template === true} + /> + {props.readOnly && ( + <CodeBlockHoverToolbar + rtl={props.rtl} + isTemplate={editorProps.template === true} + /> + )} + </> ); }; } diff --git a/app/editor/extensions/Suggestion.ts b/app/editor/extensions/Suggestion.ts index e4616dc384..8a57a9bb2a 100644 --- a/app/editor/extensions/Suggestion.ts +++ b/app/editor/extensions/Suggestion.ts @@ -76,7 +76,8 @@ export default class Suggestion< this.state, this.openRegex, this.enabledInMarks, - this.triggerLength + this.triggerLength, + this.options.allowSpaces ), ]; } diff --git a/app/editor/extensions/deburrWithMap.test.ts b/app/editor/extensions/deburrWithMap.test.ts index bfc1b46455..3f48d04891 100644 --- a/app/editor/extensions/deburrWithMap.test.ts +++ b/app/editor/extensions/deburrWithMap.test.ts @@ -17,13 +17,22 @@ describe("deburrWithMap", () => { } }); - it("maps decomposed (longer) output back to original indices for Hangul", () => { + it("leaves Hangul unchanged and maps indices 1:1 (fast path)", () => { const text = "강의"; const { deburred, toOriginalIndex } = deburrWithMap(text); - // NFD decomposition expands each precomposed syllable into jamo, so the - // deburred string is longer than the original. - expect(deburred.length).toBeGreaterThan(text.length); + expect(deburred).toBe(text); + for (let i = 0; i <= deburred.length; i++) { + expect(toOriginalIndex(i)).toBe(i); + } + }); + + it("maps expanded (longer) output back to original indices", () => { + const text = "߯"; + const { deburred, toOriginalIndex } = deburrWithMap(text); + + // Each letter expands to two letters, so the deburred string is longer. + expect(deburred).toBe("ssAe"); // The end position must map to the original length, not the deburred length. expect(toOriginalIndex(deburred.length)).toBe(text.length); @@ -35,8 +44,8 @@ describe("deburrWithMap", () => { } }); - it("recovers correct original positions for an ASCII match surrounded by CJK", () => { - const text = "강의a평가"; + it("recovers correct original positions for an ASCII match surrounded by expanded letters", () => { + const text = "߯a߯"; const { deburred, toOriginalIndex } = deburrWithMap(text); const index = deburred.indexOf("a"); @@ -48,22 +57,24 @@ describe("deburrWithMap", () => { expect(text.slice(from, to)).toBe("a"); }); - it("maps a deburred match for CJK text back to the original code unit", () => { - const text = "abc평가"; - const { toOriginalIndex } = deburrWithMap(text); + it("maps Hangul back to the original code unit when another letter expands", () => { + const text = "강ß의"; + const { deburred, toOriginalIndex } = deburrWithMap(text); - // "abc" appears at the start of both the original and deburred strings. - expect(toOriginalIndex(0)).toBe(0); - expect(toOriginalIndex(3)).toBe(3); - expect(text.slice(toOriginalIndex(0), toOriginalIndex(3))).toBe("abc"); + expect(deburred).toBe("강ss의"); + + const index = deburred.indexOf("의"); + expect(text.slice(toOriginalIndex(index), toOriginalIndex(index + 1))).toBe( + "의" + ); }); - it("keeps the map consistent across interleaved ASCII and Hangul", () => { - const text = "a강b의c"; + it("keeps the map consistent across interleaved ASCII and expanded letters", () => { + const text = "aßbÆc"; const { deburred, toOriginalIndex } = deburrWithMap(text); // Every ASCII character must still resolve to its exact original code unit, - // even though the Hangul characters between them expand under NFD. + // even though the letters between them expand. for (const ascii of ["a", "b", "c"]) { const index = deburred.indexOf(ascii); expect( @@ -78,17 +89,18 @@ describe("deburrWithMap", () => { expect(toOriginalIndex(deburred.length)).toBe(text.length); }); - it("maps a partial decomposed sequence to a zero-length original range", () => { - // A precomposed Hangul syllable decomposes into multiple jamo that all - // originate from the same single original code unit. Matching only part of - // that sequence therefore collapses to an empty range in the original text, - // which consumers must detect and skip. - const text = "강"; + it("maps a partial expanded sequence to a zero-length original range", () => { + // An expanded letter emits multiple code units from one original code unit. + // Matching only part of that sequence therefore collapses to an empty range + // in the original text, which consumers must detect and skip. + const text = "ß"; const { deburred, toOriginalIndex } = deburrWithMap(text); - expect(deburred.length).toBeGreaterThan(1); - // The first jamo alone maps back to a zero-length range (start === end). + expect(deburred).toBe("ss"); + + // The first letter alone maps back to a zero-length range (start === end). expect(toOriginalIndex(0)).toBe(toOriginalIndex(1)); + // The full sequence still spans the whole original character. expect(toOriginalIndex(0)).toBe(0); expect(toOriginalIndex(deburred.length)).toBe(text.length); diff --git a/app/editor/extensions/deburrWithMap.ts b/app/editor/extensions/deburrWithMap.ts index a273c6de62..faf38309ee 100644 --- a/app/editor/extensions/deburrWithMap.ts +++ b/app/editor/extensions/deburrWithMap.ts @@ -5,11 +5,10 @@ import { deburr } from "es-toolkit/compat"; * any index in the stripped string back to the corresponding index in the * original string. * - * `deburr` normalizes to NFD form, which can change the length of the string – - * most notably it decomposes precomposed CJK/Hangul syllables (e.g. "강" is a - * single UTF-16 code unit but decomposes into three jamo). When that happens a - * naive offset no longer lines up with the original, so the source index of - * every emitted code unit is recorded instead. + * `deburr` can change the length of the string – it expands some letters (e.g. + * "ß" is a single UTF-16 code unit but becomes "ss") and removes combining + * marks. When that happens a naive offset no longer lines up with the original, + * so the source index of every emitted code unit is recorded instead. * * When deburring does not change the length – the common case for ASCII and * ordinary accented Latin text – indices line up one-to-one and the cheap @@ -31,17 +30,17 @@ export function deburrWithMap(text: string): { return { deburred, toOriginalIndex: (index) => index }; } - // Slow path: deburring changed the length (e.g. NFD decomposed a CJK/Hangul - // syllable or expanded a ligature). Rebuild the deburred string per code - // point so it stays consistent with the index map, recording the original - // index of every emitted code unit plus a sentinel for the end position. + // Slow path: deburring changed the length (e.g. it expanded a letter or + // removed a combining mark). Rebuild the deburred string per code point so it + // stays consistent with the index map, recording the original index of every + // emitted code unit plus a sentinel for the end position. const parts: string[] = []; const map: number[] = []; let originalIndex = 0; // Iterate by code point so surrogate pairs are deburred as a unit. for (const char of text) { - // ASCII characters are never altered or decomposed by deburr, so emit them + // ASCII characters are never altered by deburr, so emit them // directly and skip the comparatively expensive normalization. if (char.charCodeAt(0) < 0x80) { map.push(originalIndex); diff --git a/app/editor/extensions/index.ts b/app/editor/extensions/index.ts index c98251f945..ddfec14644 100644 --- a/app/editor/extensions/index.ts +++ b/app/editor/extensions/index.ts @@ -4,6 +4,7 @@ import ClipboardTextSerializer from "~/editor/extensions/ClipboardTextSerializer import CommentGutterExtension from "~/editor/extensions/CommentGutter"; import DiagramsExtension from "@shared/editor/extensions/Diagrams"; import DocumentMenuExtension from "~/editor/extensions/DocumentMenu"; +import DragHandle from "~/editor/extensions/DragHandle"; import EmojiMenuExtension from "~/editor/extensions/EmojiMenu"; import FindAndReplaceExtension from "~/editor/extensions/FindAndReplace"; import HoverPreviewsExtension from "~/editor/extensions/HoverPreviews"; @@ -30,6 +31,7 @@ export const withUIExtensions = (nodes: Nodes) => [ SelectionToolbarExtension, CommentGutterExtension, DiagramsExtension, + DragHandle, // Order these default key handlers last PreventTab, Keys, diff --git a/app/editor/index.tsx b/app/editor/index.tsx index acd704b270..8a4c77864d 100644 --- a/app/editor/index.tsx +++ b/app/editor/index.tsx @@ -1,6 +1,6 @@ /* global File Promise */ import type { PluginSimple } from "markdown-it"; -import { observable } from "mobx"; +import { observable, runInAction } from "mobx"; import { Observer } from "mobx-react"; import { darken, transparentize } from "polished"; import { baseKeymap } from "prosemirror-commands"; @@ -26,16 +26,18 @@ import { import type { Decoration, NodeViewConstructor } from "prosemirror-view"; import { EditorView } from "prosemirror-view"; import * as React from "react"; -import type { DefaultTheme, ThemeProps } from "styled-components"; +import type { DefaultTheme } from "styled-components"; import styled, { css } from "styled-components"; import type { CommentAnchor } from "@shared/editor/commands/comment"; import insertFiles from "@shared/editor/commands/insertFiles"; +import { unfoldToggleBlocksAt } from "@shared/editor/commands/toggleBlock"; import { draftCommentAnchorPluginKey } from "@shared/editor/plugins/DraftCommentAnchorPlugin"; import Styles from "@shared/editor/components/Styles"; import type { EmbedDescriptor } from "@shared/editor/embeds"; import type { CommandFactory, WidgetProps } from "@shared/editor/lib/Extension"; import type { AnyExtension, AnyExtensionClass } from "@shared/editor/lib/types"; import ExtensionManager from "@shared/editor/lib/ExtensionManager"; +import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; import { inputRules } from "@shared/editor/lib/inputRules"; import type { MarkdownSerializer } from "@shared/editor/lib/markdown/serializer"; import { isRemoteTransaction } from "@shared/editor/lib/multiplayer"; @@ -58,7 +60,6 @@ import { headingPrefixPluginKey } from "@shared/editor/extensions/HeadingPrefix" import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; import EventEmitter from "@shared/utils/events"; import { getDataTransferFiles } from "@shared/utils/files"; -import { AttachmentValidation } from "@shared/validations"; import type Document from "~/models/Document"; import Flex from "~/components/Flex"; import { PortalContext } from "~/components/Portal"; @@ -161,8 +162,6 @@ export type Props = { onFileUploadStart?: () => void; /** Callback when a file upload ends */ onFileUploadStop?: () => void; - /** Callback when file upload progress changes */ - onFileUploadProgress?: (id: string, fractionComplete: number) => void; /** Callback when a link is created, should return url to created document */ onCreateLink?: ( params: Properties<Document>, @@ -213,7 +212,7 @@ type State = { * ~/components/Editor instead. */ export class Editor extends React.PureComponent< - Props & ThemeProps<DefaultTheme>, + Props & { theme: DefaultTheme }, State > { static defaultProps = { @@ -246,9 +245,6 @@ export class Editor extends React.PureComponent< wrapperRef = React.createRef<HTMLDivElement>(); view: EditorView; schema: Schema; - serializer: MarkdownSerializer; - parser: MarkdownParser; - pasteParser: MarkdownParser; plugins: Plugin[]; keymaps: Plugin[]; inputRules: InputRule[]; @@ -260,6 +256,9 @@ export class Editor extends React.PureComponent< nodeRenderers = observable.set<NodeViewRenderer<ComponentProps>>(); decorationRenderers = observable.set<PortalRenderer>(); private portalDestroyers = new WeakMap<HTMLElement, () => void>(); + private cachedSerializer?: MarkdownSerializer; + private cachedParser?: MarkdownParser; + private cachedPasteParser?: MarkdownParser; nodes: { [name: string]: NodeSpec }; marks: { [name: string]: MarkSpec }; commands: Record<string, CommandFactory>; @@ -267,6 +266,44 @@ export class Editor extends React.PureComponent< rulePlugins: PluginSimple[]; events = new EventEmitter(); mutationObserver?: MutationObserver; + private observableState = observable.box<EditorState | undefined>(undefined, { + deep: false, + }); + + /** + * The current editor state. Unlike `view.state` it is observable, so an + * observer component that reads it during render updates on every + * transaction, and a component that does not read it is not rendered. + */ + public get editorState(): EditorState { + return this.observableState.get() ?? this.view.state; + } + + /** + * The markdown serializer for the editor schema, created on first use. + */ + public get serializer(): MarkdownSerializer { + this.cachedSerializer ??= this.createSerializer(); + return this.cachedSerializer; + } + + /** + * The markdown parser for the editor schema, created on first use. + */ + public get parser(): MarkdownParser { + this.cachedParser ??= this.createParser(); + return this.cachedParser; + } + + /** + * The markdown parser used for pasted content, created on first use. + */ + public get pasteParser(): MarkdownParser { + this.cachedPasteParser ??= this.props.readOnly + ? this.parser + : this.createPasteParser(); + return this.cachedPasteParser; + } /** * We use componentDidMount instead of constructor as the init method requires @@ -275,7 +312,9 @@ export class Editor extends React.PureComponent< public componentDidMount() { this.init(); this.handleEditorInit(); - window.addEventListener("theme-changed", this.dispatchThemeChanged); + + // The widgets are created by init, render again to mount them. + this.forceUpdate(); if (this.props.scrollTo) { void this.scrollToAnchor(this.props.scrollTo); @@ -297,16 +336,16 @@ export class Editor extends React.PureComponent< if (this.props.value && prevProps.value !== this.props.value) { const newState = this.createState(this.props.value); this.view.updateState(newState); + this.syncObservableState(); + + // Positions held by the lightbox refer to the previous document. + if (this.state.activeLightboxImage) { + this.updateActiveLightboxImage(null); + } } - // When transitioning from readOnly to editable, reinitialize to create - // editing extensions, keymaps, input rules, and commands that were skipped. if (prevProps.readOnly && !this.props.readOnly) { - const docJSON = this.view.state.doc.toJSON(); - this.view.destroy(); - this.init(); - const newState = this.createState(docJSON); - this.view.updateState(newState); + this.setEditable(); } else if (!prevProps.readOnly && this.props.readOnly) { // pass readOnly changes through to underlying editor instance this.view.update({ @@ -357,7 +396,6 @@ export class Editor extends React.PureComponent< } public componentWillUnmount(): void { - window.removeEventListener("theme-changed", this.dispatchThemeChanged); this.view?.destroy(); this.mutationObserver?.disconnect(); this.handleEditorDestroy(); @@ -370,8 +408,9 @@ export class Editor extends React.PureComponent< this.schema = this.createSchema(); this.plugins = this.createPlugins(); this.rulePlugins = this.createRulePlugins(); - this.serializer = this.createSerializer(); - this.parser = this.createParser(); + this.cachedSerializer = undefined; + this.cachedParser = undefined; + this.cachedPasteParser = undefined; this.nodeViews = this.createNodeViews(); this.widgets = this.createWidgets(); @@ -379,14 +418,15 @@ export class Editor extends React.PureComponent< if (this.props.readOnly) { this.keymaps = []; this.inputRules = []; - this.pasteParser = this.parser; } else { this.keymaps = this.createKeymaps(); this.inputRules = this.createInputRules(); - this.pasteParser = this.createPasteParser(); } - this.view = this.createView(); + // Node views register their renderers as they are created, batch them so + // that React renders them once. + this.view = runInAction(() => this.createView()); + this.syncObservableState(); this.commands = this.createCommands(); this.selectionToolbarMenus = this.extensions.selectionToolbarMenus; } @@ -485,35 +525,35 @@ export class Editor extends React.PureComponent< } private createState(value?: string | ProsemirrorData | ProsemirrorNode) { - const doc = this.createDocument(value || this.props.defaultValue); - - if (this.props.readOnly) { - return EditorState.create({ - schema: this.schema, - doc, - plugins: [...this.plugins, anchorPlugin()], - }); - } - return EditorState.create({ schema: this.schema, - doc, - plugins: [ - ...this.plugins, - ...this.keymaps, - anchorPlugin(), - dropCursor({ - color: this.props.theme.cursor, - }), - gapCursor(), - inputRules({ - rules: this.inputRules, - }), - keymap(baseKeymap), - ], + doc: this.createDocument(value || this.props.defaultValue), + plugins: this.createStatePlugins(), }); } + private createStatePlugins() { + if (this.props.readOnly) { + return [...this.plugins, anchorPlugin()]; + } + + return [ + ...this.plugins, + ...this.keymaps, + anchorPlugin(), + dropCursor({ + color: this.props.theme.accent, + width: 2, + class: EditorStyleHelper.dropCursor, + }), + gapCursor(), + inputRules({ + rules: this.inputRules, + }), + keymap(baseKeymap), + ]; + } + private createDocument(content: string | object | ProsemirrorNode) { // Already a ProsemirrorNode if (content instanceof ProsemirrorNode) { @@ -522,6 +562,10 @@ export class Editor extends React.PureComponent< // Looks like Markdown if (typeof content === "string") { + // An empty document needs no parsing, the state fills in the default. + if (!content) { + return undefined; + } return this.parser.parse(content) || undefined; } @@ -569,7 +613,11 @@ export class Editor extends React.PureComponent< const { state, transactions } = this.state.applyTransaction(transaction); - this.updateState(state); + // Batch node view renderer changes so that React renders them once. + runInAction(() => { + this.updateState(state); + self.observableState.set(state); + }); // If any of the transactions being dispatched resulted in the doc // changing then call our own change handler to let the outside world @@ -590,10 +638,6 @@ export class Editor extends React.PureComponent< self.handleEditorInit(); self.calculateDir(); - - // Because Prosemirror and React are not linked we must tell React that - // a render is needed whenever the Prosemirror state changes. - self.forceUpdate(); }, }); @@ -669,14 +713,68 @@ export class Editor extends React.PureComponent< ).toJSON(); }; + private syncObservableState() { + runInAction(() => this.observableState.set(this.view.state)); + } + + /** + * Make the editor editable. The document, schema and node views are kept, so + * the editor DOM is not redrawn. + */ + private setEditable() { + this.view.setProps({ + attributes: { translate: "no" }, + editable: () => !this.props.readOnly, + }); + + // Changing the plugins recreates every plugin view, so only do it once. + if (this.extensions.readOnly) { + this.addEditingExtensions(); + } + + this.syncObservableState(); + Array.from(this.nodeRenderers).forEach((view) => + view.setProp("isEditable", true) + ); + this.forceUpdate(); + } + + /** + * Add the extensions, keymaps, input rules and commands that were skipped in + * read-only mode. + */ + private addEditingExtensions() { + this.extensions.setEditable(this.props.extensions, this); + this.plugins = this.createPlugins(); + this.rulePlugins = this.createRulePlugins(); + this.cachedSerializer = undefined; + this.cachedParser = undefined; + this.cachedPasteParser = undefined; + this.widgets = this.createWidgets(); + this.keymaps = this.createKeymaps(); + this.inputRules = this.createInputRules(); + + this.view.updateState( + this.view.state.reconfigure({ plugins: this.createStatePlugins() }) + ); + this.commands = this.createCommands(); + this.selectionToolbarMenus = this.extensions.selectionToolbarMenus; + } + private calculateDir = () => { - if (!this.elementRef.current) { + const element = this.elementRef.current; + if (!element) { return; } + // Prefer the closest dir attribute, computing the style forces a style + // recalculation of the whole document. + const dir = element.closest("[dir]")?.getAttribute("dir"); const isRTL = this.props.dir === "rtl" || - getComputedStyle(this.elementRef.current).direction === "rtl"; + (dir === "auto" || !dir + ? getComputedStyle(element).direction === "rtl" + : dir === "rtl"); if (this.state.isRTL !== isRTL) { this.setState({ isRTL }); @@ -793,15 +891,7 @@ export class Editor extends React.PureComponent< return; } - // Insert all files as attachments if any of the files are not images. - const isAttachment = files.some( - (file) => !AttachmentValidation.imageContentTypes.includes(file.type) - ); - - return insertFiles(view, event, pos, files, { - ...this.props, - isAttachment, - }); + return insertFiles(view, event, pos, files, this.props); }; /** @@ -827,7 +917,7 @@ export class Editor extends React.PureComponent< public getLightboxImages = (): LightboxImage[] => { const lightboxNodes = ProsemirrorHelper.getLightboxNodes( - this.view.state.doc + this.editorState.doc ); return map(lightboxNodes, (node) => @@ -849,6 +939,51 @@ export class Editor extends React.PureComponent< */ public getComments = () => ProsemirrorHelper.getComments(this.view.state.doc); + /** + * Unfold any collapsed toggle blocks that hide the start of a comment. + * + * @param commentId the id of the comment to reveal. + */ + public revealComment = (commentId: string) => { + const { state, dispatch } = this.view; + + let commentPos: number | undefined; + state.doc.descendants((node, pos) => { + if (commentPos !== undefined) { + return false; + } + + const hasComment = + node.marks.some( + (m) => + m.type === state.schema.marks.comment && m.attrs.id === commentId + ) || + (isArray(node.attrs?.marks) && + (node.attrs.marks as ProsemirrorMark[]).some( + (m) => m.type === "comment" && m.attrs?.id === commentId + )); + + if (hasComment) { + commentPos = pos; + return false; + } + return true; + }); + + // Pending comments from users without edit access exist only as decorations. + commentPos ??= draftCommentAnchorPluginKey + .getState(state) + ?.decorations.find( + undefined, + undefined, + (spec) => spec.id === commentId + )[0]?.from; + + if (commentPos !== undefined) { + unfoldToggleBlocksAt(commentPos)(state, dispatch); + } + }; + /** * Remove all marks related to a specific comment from the document. * @@ -960,10 +1095,6 @@ export class Editor extends React.PureComponent< return textBetween(doc, 0, doc.content.size); }; - private dispatchThemeChanged = (event: CustomEvent) => { - this.view.dispatch(this.view.state.tr.setMeta("theme", event.detail)); - }; - private handleChange = (event?: { remote: boolean }) => { if (!this.props.onChange) { return; @@ -1056,7 +1187,7 @@ export class Editor extends React.PureComponent< public render() { const { readOnly, canUpdate, grow, style, className, onKeyDown } = this.props; - const { isRTL } = this.state; + const { isRTL, activeLightboxImage } = this.state; return ( <PortalContext.Provider value={this.wrapperRef.current}> @@ -1091,8 +1222,6 @@ export class Editor extends React.PureComponent< key={String(index)} rtl={isRTL} readOnly={readOnly} - selection={this.view.state.selection} - storedMarks={this.view.state.storedMarks} isEditorFocused={this.state.isEditorFocused} /> ))} @@ -1106,14 +1235,18 @@ export class Editor extends React.PureComponent< )} </Observer> </Flex> - {!isNull(this.state.activeLightboxImage) && ( - <Lightbox - readOnly={readOnly} - images={this.getLightboxImages()} - activeImage={this.state.activeLightboxImage} - onUpdate={this.updateActiveLightboxImage} - onClose={this.view.focus.bind(this.view)} - /> + {!isNull(activeLightboxImage) && ( + <Observer> + {() => ( + <Lightbox + readOnly={readOnly} + images={this.getLightboxImages()} + activeImage={activeLightboxImage} + onUpdate={this.updateActiveLightboxImage} + onClose={this.view.focus.bind(this.view)} + /> + )} + </Observer> )} </EditorContext.Provider> </PortalContext.Provider> @@ -1121,7 +1254,7 @@ export class Editor extends React.PureComponent< } } -const EditorContainer = styled(Styles)<{ +const StyledEditorContainer = styled(Styles)<{ userId?: string; focusedCommentId?: string; hoveredCommentId?: string; @@ -1139,7 +1272,7 @@ const EditorContainer = styled(Styles)<{ } a#comment-${props.focusedCommentId} ~ span.component-image - div.image-wrapper { + div.${EditorStyleHelper.imageWrapper} { outline: ${props.theme.commentedImageOutlineDark} solid 2px; } `} @@ -1157,7 +1290,7 @@ const EditorContainer = styled(Styles)<{ } a#comment-${props.hoveredCommentId} ~ span.component-image - div.image-wrapper { + div.${EditorStyleHelper.imageWrapper} { outline: ${props.theme.commentedImageOutlineDark} solid 2px; } `} @@ -1180,6 +1313,10 @@ const EditorContainer = styled(Styles)<{ `} `; +// The editor re-renders on every transaction, memoize the container so that +// its large stylesheet is not regenerated when the props have not changed. +const EditorContainer = React.memo(StyledEditorContainer); + function LazyLoadedEditor({ ref, ...props diff --git a/app/editor/menus/block.tsx b/app/editor/menus/block.tsx index ee5433decc..55d4404f40 100644 --- a/app/editor/menus/block.tsx +++ b/app/editor/menus/block.tsx @@ -13,13 +13,9 @@ import { TableIcon, TodoListIcon, ImageIcon, - StarredIcon, - WarningIcon, - InfoIcon, AttachmentIcon, CalendarIcon, MathIcon, - DoneIcon, EmbedIcon, CollapseIcon, } from "outline-icons"; @@ -28,10 +24,12 @@ import styled from "styled-components"; import { v4 as uuidv4 } from "uuid"; import type { TFunction } from "i18next"; import Image from "@shared/editor/components/Img"; +import { NoticeTypes } from "@shared/editor/nodes/Notice"; import type { MenuItem } from "@shared/editor/types"; import { MentionType } from "@shared/types"; import { toISODate } from "@shared/utils/date"; import { metaDisplay } from "@shared/utils/keyboard"; +import { NoticeIcon } from "~/editor/components/NoticeIcon"; import Desktop from "~/utils/Desktop"; const Img = styled(Image)` @@ -243,45 +241,45 @@ export default function blockMenuItems( { name: "container_notice", title: t("Info notice"), - icon: <InfoIcon />, + icon: <NoticeIcon type={NoticeTypes.Info} />, keywords: "card callout hint information note", - attrs: { style: "info" }, + attrs: { style: NoticeTypes.Info }, }, { name: "container_notice", title: t("Success notice"), - icon: <DoneIcon />, + icon: <NoticeIcon type={NoticeTypes.Success} />, keywords: "card callout hint", - attrs: { style: "success" }, + attrs: { style: NoticeTypes.Success }, }, { name: "container_notice", title: t("Warning notice"), - icon: <WarningIcon />, + icon: <NoticeIcon type={NoticeTypes.Warning} />, keywords: "card callout hint error caution danger alert", - attrs: { style: "warning" }, + attrs: { style: NoticeTypes.Warning }, }, { name: "container_notice", title: t("Tip notice"), - icon: <StarredIcon />, + icon: <NoticeIcon type={NoticeTypes.Tip} />, keywords: "card callout hint suggestion", - attrs: { style: "tip" }, + attrs: { style: NoticeTypes.Tip }, }, { name: "separator", }, { name: "code_block", - title: "Mermaid Diagram", - icon: <Img src="/images/mermaidjs.png" alt="Mermaid Diagram" />, + title: "Mermaid diagram", + icon: <Img src="/images/mermaidjs.png" alt="Mermaid diagram" />, keywords: "flowchart graph sequence gantt", attrs: { language: "mermaid" }, }, { name: "editDiagram", - title: "Diagrams.net Diagram", - icon: <Img src="/images/diagrams.png" alt="Diagrams.net Diagram" />, + title: "Diagrams.net diagram", + icon: <Img src="/images/diagrams.png" alt="Diagrams.net diagram" />, keywords: "flowchart drawio draw.io whiteboard", }, ]; diff --git a/app/editor/menus/code.tsx b/app/editor/menus/code.tsx index 05ae234f28..d0099b1eb3 100644 --- a/app/editor/menus/code.tsx +++ b/app/editor/menus/code.tsx @@ -12,21 +12,31 @@ import { } from "@shared/editor/lib/code"; import { isMermaid } from "@shared/editor/lib/isCode"; import { t } from "i18next"; -import type { MenuItem, SelectionContext } from "@shared/editor/types"; +import type { + MenuItem, + NodeWithPos, + SelectionContext, +} from "@shared/editor/types"; import { metaDisplay } from "@shared/utils/keyboard"; /** * Returns menu items for the code block selection toolbar. * * @param ctx - the current selection context. + * @param codeBlock - the code block to act on, defaults to the selected one. * @returns an array of menu items. */ -export default function codeMenuItems(ctx: SelectionContext): MenuItem[] { +export default function codeMenuItems( + ctx: SelectionContext, + codeBlock?: NodeWithPos +): MenuItem[] { const { state, readOnly } = ctx; - const node = - state.selection instanceof NodeSelection - ? state.selection.node - : state.selection.$from.node(); + const { selection } = state; + const { node, pos } = + codeBlock ?? + (selection instanceof NodeSelection + ? { node: selection.node, pos: selection.from } + : { node: selection.$from.node(), pos: selection.$from.before() }); const frequentLanguages = getFrequentCodeLanguages(); @@ -63,6 +73,7 @@ export default function codeMenuItems(ctx: SelectionContext): MenuItem[] { ? getLabelForLanguage(node.attrs.language ?? "none") : undefined, tooltip: t("Copy"), + attrs: { pos }, }, { name: "separator", diff --git a/app/editor/menus/mention.tsx b/app/editor/menus/mention.tsx index 8daeada921..1027c08384 100644 --- a/app/editor/menus/mention.tsx +++ b/app/editor/menus/mention.tsx @@ -16,7 +16,8 @@ import { GroupSection, MentionUserSection, } from "~/actions/sections"; -import { Avatar, AvatarSize, GroupAvatar } from "~/components/Avatar"; +import { Avatar, AvatarSize } from "~/components/Avatar"; +import { ResolvedGroupIcon } from "~/components/Icons/GroupIcon"; import DocumentBreadcrumb from "~/components/DocumentBreadcrumb"; import Flex from "~/components/Flex"; import type Collection from "~/models/Collection"; @@ -88,15 +89,7 @@ export function groupMentionItem( ): MentionMenuItem { return { name: "mention", - icon: ( - <Flex - align="center" - justify="center" - style={{ width: 24, height: 24, marginRight: 4 }} - > - <GroupAvatar group={group} size={AvatarSize.Small} /> - </Flex> - ), + icon: <ResolvedGroupIcon group={group} />, title: group.name, subtitle: t("{{ count }} members", { count: group.memberCount, @@ -135,7 +128,7 @@ export function collectionMentionItem( ) : ( <CollectionIcon /> ), - title: collection.name, + title: collection.displayName, section: CollectionsSection, appendSpace: true, attrs: { @@ -143,7 +136,7 @@ export function collectionMentionItem( type: MentionType.Collection, modelId: collection.id, actorId, - label: collection.name, + label: collection.displayName, }, }; } diff --git a/app/editor/menus/notice.tsx b/app/editor/menus/notice.tsx index 549e0682cc..96b78ae3f4 100644 --- a/app/editor/menus/notice.tsx +++ b/app/editor/menus/notice.tsx @@ -1,14 +1,9 @@ import { t } from "i18next"; -import { - DoneIcon, - ExpandedIcon, - InfoIcon, - StarredIcon, - WarningIcon, -} from "outline-icons"; +import { ExpandedIcon } from "outline-icons"; import { NoticeTypes } from "@shared/editor/nodes/Notice"; import { findParentNode } from "@shared/editor/queries/findParentNode"; import type { MenuItem, SelectionContext } from "@shared/editor/types"; +import { NoticeIcon } from "~/editor/components/NoticeIcon"; /** * Returns menu items for the notice/callout selection toolbar. @@ -39,25 +34,25 @@ export default function noticeMenuItems(ctx: SelectionContext): MenuItem[] { children: [ { name: NoticeTypes.Info, - icon: <InfoIcon />, + icon: <NoticeIcon type={NoticeTypes.Info} />, label: t("Info notice"), active: () => currentStyle === NoticeTypes.Info, }, { name: NoticeTypes.Success, - icon: <DoneIcon />, + icon: <NoticeIcon type={NoticeTypes.Success} />, label: t("Success notice"), active: () => currentStyle === NoticeTypes.Success, }, { name: NoticeTypes.Warning, - icon: <WarningIcon />, + icon: <NoticeIcon type={NoticeTypes.Warning} />, label: t("Warning notice"), active: () => currentStyle === NoticeTypes.Warning, }, { name: NoticeTypes.Tip, - icon: <StarredIcon />, + icon: <NoticeIcon type={NoticeTypes.Tip} />, label: t("Tip notice"), active: () => currentStyle === NoticeTypes.Tip, }, diff --git a/app/editor/menus/table.tsx b/app/editor/menus/table.tsx index 8592d6c319..628b8730b7 100644 --- a/app/editor/menus/table.tsx +++ b/app/editor/menus/table.tsx @@ -31,6 +31,7 @@ export default function tableMenuItems(ctx: SelectionContext): MenuItem[] { label: isFullWidth ? t("Default width") : t("Full width"), icon: <AlignFullWidthIcon />, attrs: isFullWidth ? { layout: null } : { layout: TableLayout.fullWidth }, + visible: !ctx.isInNotice, }, { name: "distributeColumns", diff --git a/app/editor/menus/video.tsx b/app/editor/menus/video.tsx new file mode 100644 index 0000000000..892fac7ffe --- /dev/null +++ b/app/editor/menus/video.tsx @@ -0,0 +1,56 @@ +import { t } from "i18next"; +import { TrashIcon, DownloadIcon, ReplaceIcon } from "outline-icons"; +import { NodeSelection } from "prosemirror-state"; +import type { MenuItem, SelectionContext } from "@shared/editor/types"; + +/** + * Returns menu items for the video selection toolbar. + * + * @param ctx - the current selection context. + * @returns an array of menu items. + */ +export default function videoMenuItems(ctx: SelectionContext): MenuItem[] { + if (ctx.readOnly) { + return []; + } + + const { selection } = ctx.state; + const hasWidth = + selection instanceof NodeSelection && !!selection.node.attrs.width; + + return [ + { + name: "dimensions", + tooltip: `${t("Width")} × ${t("Height")}`, + visible: hasWidth, + skipIcon: true, + }, + { + name: "separator", + }, + { + name: "downloadVideo", + tooltip: t("Download video"), + icon: <DownloadIcon />, + }, + { + tooltip: t("Replace video"), + icon: <ReplaceIcon />, + children: [ + { + name: "replaceVideo", + label: t("Upload a video"), + }, + { + name: "editVideoUrl", + label: t("Edit video URL"), + }, + ], + }, + { + name: "deleteVideo", + tooltip: t("Delete video"), + icon: <TrashIcon />, + }, + ]; +} diff --git a/app/editor/plugins/DragTarget.test.ts b/app/editor/plugins/DragTarget.test.ts new file mode 100644 index 0000000000..64619d2b41 --- /dev/null +++ b/app/editor/plugins/DragTarget.test.ts @@ -0,0 +1,107 @@ +import { + bulletList, + createEditorState, + createEditorStateWithSelection, + doc, + heading, + hr, + p, + schema, + table, + td, + tr, +} from "@shared/test/editor"; +import { DragTarget } from "./DragTarget"; + +describe("DragTarget.resolvePos", () => { + it("resolves a position in a top-level block to the block", () => { + const state = createEditorState(doc([p("one"), heading("two")])); + + // Inside the heading text, which starts after the 5-size paragraph. + expect(DragTarget.resolvePos(state, 7)).toEqual({ pos: 5, kind: "block" }); + }); + + it("resolves a position in a list item to the list item", () => { + const state = createEditorState(doc([bulletList(["one", "two"])])); + const items: number[] = []; + state.doc.descendants((node, pos) => { + if (node.type.name === "list_item") { + items.push(pos); + } + }); + expect(DragTarget.resolvePos(state, items[1] + 3)).toEqual({ + pos: items[1], + kind: "listItem", + }); + }); + + it("resolves a position in a checkbox item to the checkbox item", () => { + const list = schema.nodes.checkbox_list.create(null, [ + schema.nodes.checkbox_item.create(null, p("todo")), + ]); + const state = createEditorState(doc([list])); + expect(DragTarget.resolvePos(state, 4)).toEqual({ + pos: 1, + kind: "checkboxItem", + }); + }); + + it("returns null for an empty top-level paragraph", () => { + const state = createEditorState(doc([p("one"), p("")])); + expect(DragTarget.resolvePos(state, 6)).toBeNull(); + }); + + it("returns null for a paragraph that holds a layout image", () => { + const image = schema.nodes.image.create({ + src: "https://example.com/image.png", + layoutClass: "full-width", + }); + const state = createEditorState( + doc([p("one"), schema.nodes.paragraph.create(null, image)]) + ); + expect(DragTarget.resolvePos(state, 6)).toBeNull(); + }); + + it("resolves a position between top-level atoms to the adjacent atom", () => { + const state = createEditorState(doc([p("one"), hr()])); + expect(DragTarget.resolvePos(state, 5)).toEqual({ pos: 5, kind: "block" }); + expect(DragTarget.resolvePos(state, 6)).toEqual({ pos: 5, kind: "block" }); + }); +}); + +describe("DragTarget#hasOwnControls", () => { + const testDoc = doc([p("one"), table([tr([td("a"), td("b")])])]); + + // The table starts after the 5-size paragraph. + const target = new DragTarget(5, document.createElement("div"), "block"); + + it("returns true when the selection is inside the table", () => { + const state = createEditorStateWithSelection(testDoc, 9); + expect(target.hasOwnControls(state)).toBe(true); + }); + + it("returns false when the selection is outside the table", () => { + const state = createEditorStateWithSelection(testDoc, 2); + expect(target.hasOwnControls(state)).toBe(false); + }); + + it("returns false for a block that is not a table", () => { + const state = createEditorStateWithSelection(testDoc, 2); + const paragraph = new DragTarget(0, document.createElement("div"), "block"); + expect(paragraph.hasOwnControls(state)).toBe(false); + }); + + it("returns true for an empty paragraph that holds the selection", () => { + const emptyDoc = doc([p("one"), p("")]); + const state = createEditorStateWithSelection(emptyDoc, 6); + const paragraph = new DragTarget(5, document.createElement("div"), "block"); + expect(paragraph.hasOwnControls(state)).toBe(true); + }); + + it("returns false for an empty paragraph without the selection", () => { + const emptyDoc = doc([p("one"), p("")]); + const state = createEditorStateWithSelection(emptyDoc, 2); + const paragraph = new DragTarget(5, document.createElement("div"), "block"); + expect(paragraph.hasOwnControls(state)).toBe(false); + }); +}); diff --git a/app/editor/plugins/DragTarget.ts b/app/editor/plugins/DragTarget.ts new file mode 100644 index 0000000000..95dd87febd --- /dev/null +++ b/app/editor/plugins/DragTarget.ts @@ -0,0 +1,329 @@ +import type { Node as ProsemirrorNode } from "prosemirror-model"; +import type { EditorState } from "prosemirror-state"; +import type { EditorView } from "prosemirror-view"; +import { findParentNodeClosestToPos } from "@shared/editor/queries/findParentNode"; +import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; + +/** The kind of block that a drag target points at. */ +export type DragTargetKind = "block" | "listItem" | "checkboxItem"; + +/** A document position and the kind of block found there. */ +export interface ResolvedDragTarget { + /** Position of the block in the document. */ + pos: number; + + /** The kind of block at the position. */ + kind: DragTargetKind; +} + +const LIST_TYPES = ["bullet_list", "ordered_list", "checkbox_list"]; + +// Inset from the content edges, so that posAtCoords lands inside the block. +const CONTENT_INSET = 1; + +// Fraction of the content width, from the handle side, in which hover shows +// the handle. +const HOVER_ZONE_RATIO = 0.25; + +/** + * A block in the editor that the drag handle can attach to. Holds the + * position of the block in the document and the DOM element that the handle + * aligns with, which is not always the node's own DOM (e.g. Mermaid diagrams). + */ +export class DragTarget { + /** Position of the block in the document. */ + public readonly pos: number; + + /** The DOM element that the handle aligns with. */ + public readonly element: HTMLElement; + + /** The kind of block. */ + public readonly kind: DragTargetKind; + + constructor(pos: number, element: HTMLElement, kind: DragTargetKind) { + this.pos = pos; + this.element = element; + this.kind = kind; + } + + /** + * Finds the block at the cursor's height when the cursor is on the side + * where the handle renders, either outside the content or in the first 25% + * of the content width. + * + * @param view - the editor view. + * @param event - the mouse event. + * @returns the target, or null if there is no block under the cursor. + */ + public static fromEvent( + view: EditorView, + event: MouseEvent + ): DragTarget | null { + const rect = view.dom.getBoundingClientRect(); + if (event.clientY < rect.top || event.clientY > rect.bottom) { + return null; + } + + // Ignore the cursor over other regions, such as the sidebar or a modal. + const region = view.dom.closest("[role='main']"); + if ( + region && + !(event.target instanceof Node && region.contains(event.target)) + ) { + return null; + } + const style = window.getComputedStyle(view.dom); + const paddingLeft = parseFloat(style.paddingLeft) || 0; + const paddingRight = parseFloat(style.paddingRight) || 0; + const contentLeft = rect.left + paddingLeft + CONTENT_INSET; + const contentRight = rect.right - paddingRight - CONTENT_INSET; + const projectedX = Math.max( + contentLeft, + Math.min(contentRight, event.clientX) + ); + + // Mermaid diagrams hide their source code block and render an SVG widget + // next to it — target the underlying code block but anchor the handle to + // the visible diagram element. + const target = + this.mermaidFromEvent(view, event, projectedX) ?? + this.blockFromCoords(view, projectedX, event.clientY); + if (!target) { + return null; + } + + // Only show the handle when the cursor is on the side it renders on. + const zoneWidth = (contentRight - contentLeft) * HOVER_ZONE_RATIO; + const isRTL = window.getComputedStyle(target.element).direction === "rtl"; + const inZone = isRTL + ? event.clientX >= contentRight - zoneWidth + : event.clientX <= contentLeft + zoneWidth; + return inZone ? target : null; + } + + /** + * Finds the block that a DOM element renders, e.g. to update a target after + * the document changes. + * + * @param view - the editor view. + * @param element - the DOM element that the handle aligns with. + * @returns the target, or null if the element is no longer in the editor. + */ + public static fromElement( + view: EditorView, + element: HTMLElement + ): DragTarget | null { + if (!element.isConnected) { + return null; + } + if (element.classList.contains(EditorStyleHelper.mermaidDiagram)) { + const pos = this.mermaidPos(view, element); + return pos === null ? null : new DragTarget(pos, element, "block"); + } + const parent = element.parentNode; + if (!parent) { + return null; + } + let pos: number; + try { + pos = view.posAtDOM( + parent, + Array.from(parent.childNodes).indexOf(element) + ); + } catch { + return null; + } + const node = view.state.doc.nodeAt(pos); + if (!node || view.nodeDOM(pos) !== element) { + return null; + } + return new DragTarget(pos, element, this.kindOf(node)); + } + + /** + * Finds the draggable block that contains a document position. + * + * @param state - the editor state. + * @param pos - a position in the document. + * @returns the block position and kind, or null if there is no draggable block. + */ + public static resolvePos( + state: EditorState, + pos: number + ): ResolvedDragTarget | null { + const $pos = state.doc.resolve(pos); + + const listItem = findParentNodeClosestToPos( + $pos, + (node) => this.kindOf(node) !== "block" + ); + if (listItem) { + return { pos: listItem.pos, kind: this.kindOf(listItem.node) }; + } + + if ($pos.depth >= 1) { + const node = $pos.node(1); + if (LIST_TYPES.includes(node.type.name)) { + return null; + } + + // Skip empty top-level paragraphs — the block menu trigger is shown + // there instead. + if (node.type.name === "paragraph" && node.content.size === 0) { + return null; + } + + // Floated and full-width images sit outside the content column, so a + // handle in the gutter would not line up with them. + if (this.hasLayoutImage(node)) { + return null; + } + return { pos: $pos.before(1), kind: "block" }; + } + + // Hovering on a top-level atom block (video, etc.) — there are no + // positions inside an atom, so posAtCoords lands at depth 0 between + // siblings of the doc. Pick whichever neighbouring atom block the + // position is adjacent to. + const after = $pos.nodeAfter; + if (after?.isBlock && after.isAtom) { + return { pos: $pos.pos, kind: "block" }; + } + const before = $pos.nodeBefore; + if (before?.isBlock && before.isAtom) { + return { pos: $pos.pos - before.nodeSize, kind: "block" }; + } + return null; + } + + /** + * Whether the editor shows its own controls for this block, which would + * overlap the drag handle, e.g. a table that holds the selection or an + * empty paragraph that shows the block menu trigger. + * + * @param state - the editor state. + * @returns true if the drag handle should be hidden for this block. + */ + public hasOwnControls(state: EditorState): boolean { + const node = state.doc.nodeAt(this.pos); + const { $from, from, to } = state.selection; + + switch (node?.type.name) { + case "table": + return from > this.pos && to < this.pos + node.nodeSize; + case "paragraph": + return ( + node.content.size === 0 && + $from.depth === 1 && + $from.before() === this.pos + ); + default: + return false; + } + } + + /** + * Whether this target points at the same block as another target. + * + * @param other - the target to compare with. + * @returns true if both targets have the same position and element. + */ + public equals(other: DragTarget | null): boolean { + return !!other && this.pos === other.pos && this.element === other.element; + } + + private static kindOf(node: ProsemirrorNode): DragTargetKind { + switch (node.type.name) { + case "list_item": + return "listItem"; + case "checkbox_item": + return "checkboxItem"; + default: + return "block"; + } + } + + private static hasLayoutImage(node: ProsemirrorNode): boolean { + if (!node.isTextblock) { + return false; + } + let found = false; + node.forEach((child) => { + if (child.type.name === "image" && child.attrs.layoutClass) { + found = true; + } + }); + return found; + } + + private static blockFromCoords( + view: EditorView, + left: number, + top: number + ): DragTarget | null { + const coords = view.posAtCoords({ left, top }); + if (!coords) { + return null; + } + const resolved = this.resolvePos(view.state, coords.pos); + if (!resolved) { + return null; + } + const dom = view.nodeDOM(resolved.pos); + if (!(dom instanceof HTMLElement)) { + return null; + } + return new DragTarget(resolved.pos, dom, resolved.kind); + } + + private static mermaidFromEvent( + view: EditorView, + event: MouseEvent, + projectedX: number + ): DragTarget | null { + // Look at the element directly under the cursor, and at the projected X + // inside the editor so we still find the diagram when the cursor sits in + // the left gutter where the handle is rendered. + const eventTarget = event.target instanceof Element ? event.target : null; + const projectedTarget = + projectedX !== event.clientX + ? document.elementFromPoint(projectedX, event.clientY) + : null; + const diagram = + eventTarget?.closest<HTMLElement>( + `.${EditorStyleHelper.mermaidDiagram}` + ) ?? + (projectedTarget instanceof Element + ? projectedTarget.closest<HTMLElement>( + `.${EditorStyleHelper.mermaidDiagram}` + ) + : null); + if (!diagram) { + return null; + } + const pos = this.mermaidPos(view, diagram); + return pos === null ? null : new DragTarget(pos, diagram, "block"); + } + + private static mermaidPos( + view: EditorView, + diagram: HTMLElement + ): number | null { + const codeBlockDom = diagram.previousElementSibling; + if (!(codeBlockDom instanceof HTMLElement)) { + return null; + } + let pos: number; + try { + pos = view.posAtDOM(codeBlockDom, 0); + } catch { + return null; + } + if (pos < 0) { + return null; + } + const $pos = view.state.doc.resolve(pos); + const blockPos = $pos.depth > 0 ? $pos.before($pos.depth) : 0; + return view.state.doc.nodeAt(blockPos) ? blockPos : null; + } +} diff --git a/app/hooks/useActionContext.tsx b/app/hooks/useActionContext.tsx index 46ec02b14e..eaee904cb2 100644 --- a/app/hooks/useActionContext.tsx +++ b/app/hooks/useActionContext.tsx @@ -1,15 +1,8 @@ -import { isEqualWith } from "es-toolkit/compat"; -import { observer } from "mobx-react"; import type { ReactNode } from "react"; -import React, { - createContext, - useCallback, - useContext, - useMemo, - useRef, -} from "react"; +import { createContext, useContext, useMemo, useRef } from "react"; import { useTranslation } from "react-i18next"; import { useHistory } from "react-router"; +import shallowEqual from "@shared/utils/shallowEqual"; import useStores from "~/hooks/useStores"; import type Model from "~/models/base/Model"; import type Policy from "~/models/Policy"; @@ -20,6 +13,10 @@ export const ActionContext = createContext<ActionContextType | undefined>( undefined ); +const EMPTY_MODELS: Model[] = []; + +const EMPTY_OVERRIDES: Partial<ActionContextType> = {}; + interface ActionContextProviderValue { /** Models to add to the active models context for this subtree. */ activeModels?: Model[]; @@ -55,7 +52,7 @@ type ActionContextProviderProps = { * </ActionContextProvider> * ``` */ -export const ActionContextProvider = observer(function ActionContextProvider_({ +export function ActionContextProvider({ children, value = {}, }: ActionContextProviderProps) { @@ -69,142 +66,120 @@ export const ActionContextProvider = observer(function ActionContextProvider_({ // which react-router updates on every navigation. const history = useHistory<{ sidebarContext?: SidebarContextType }>(); - const { - activeModels: valueModels, - isMenu, - isCommandBar, - isButton, - sidebarContext, - event, - } = value; + const { isMenu, isCommandBar, isButton, sidebarContext, event } = value; + const valueModels = useStableValue(value.activeModels ?? EMPTY_MODELS); - // Track membership of stores.ui.activeModels so memos invalidate when it changes. - // Reading inside the observer-wrapped render keeps MobX subscriptions intact. - const activeModelsKey = Array.from(stores.ui.activeModels.keys()).join(","); - const activeCollectionIdFromStore = stores.ui.activeCollectionId ?? undefined; - const activeDocumentIdFromStore = stores.ui.activeDocumentId ?? undefined; - const currentUserId = stores.auth.user?.id; - const currentTeamId = stores.auth.team?.id; - - const getActiveModels = useCallback( - <T extends Model>(modelClass: new (...args: never[]) => T): T[] => { - if (valueModels && valueModels.length > 0) { - const matching = valueModels.filter( - (model): model is T => model instanceof modelClass - ); - if (matching.length > 0) { - return matching; - } + // Values derived from the UI store are getters, so that the context value + // stays the same when the active document changes. Observers that read them + // still re-render, as the store is observable. + const contextValue = useMemo<ActionContextType>(() => { + const getActiveModels = <T extends Model>( + modelClass: new (...args: never[]) => T + ): T[] => { + const matching = valueModels.filter( + (model): model is T => model instanceof modelClass + ); + if (matching.length > 0) { + return matching; } if (parentContext) { return parentContext.getActiveModels(modelClass); } return stores.ui.getActiveModels<T>(modelClass); - }, - [valueModels, parentContext, stores] - ); + }; - const getActiveModel = useCallback( - <T extends Model>(modelClass: new (...args: never[]) => T): T | undefined => - getActiveModels(modelClass)[0], - [getActiveModels] - ); + const getActiveModel = <T extends Model>( + modelClass: new (...args: never[]) => T + ): T | undefined => getActiveModels(modelClass)[0]; - const getActivePolicies = useCallback( - <T extends Model>(modelClass: new (...args: never[]) => T): Policy[] => + const getActivePolicies = <T extends Model>( + modelClass: new (...args: never[]) => T + ): Policy[] => getActiveModels(modelClass) .map((node) => stores.policies.get(node.id)) - .filter((policy): policy is Policy => policy !== undefined), - [getActiveModels, stores] - ); + .filter((policy): policy is Policy => policy !== undefined); - const allActiveModels = useMemo(() => { - const base = parentContext - ? parentContext.activeModels - : new Set(stores.ui.activeModels.values()); - if (valueModels && valueModels.length > 0) { - return new Set([...base, ...valueModels]); - } - return base; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [parentContext, stores, valueModels, activeModelsKey]); + const isModelActive = (model: Model): boolean => + valueModels.includes(model) || + (parentContext + ? parentContext.isModelActive(model) + : stores.ui.isModelActive(model)); - const isModelActive = useCallback( - (model: Model): boolean => allActiveModels.has(model), - [allActiveModels] - ); + const findValueModelId = (modelName: string) => + valueModels.find( + (m) => (m.constructor as typeof Model).modelName === modelName + )?.id; + const valueCollectionId = findValueModelId("Collection"); + const valueDocumentId = findValueModelId("Document"); - const contextValue = useMemo<ActionContextType>(() => { const baseContext: ActionContextType = parentContext ?? { isMenu: false, isCommandBar: false, isButton: false, - - // Legacy (backward compatibility) - activeCollectionId: activeCollectionIdFromStore, - activeDocumentId: activeDocumentIdFromStore, - + get activeCollectionId() { + return stores.ui.activeCollectionId ?? undefined; + }, + get activeDocumentId() { + return stores.ui.activeDocumentId ?? undefined; + }, + get activeModels() { + return new Set(stores.ui.activeModels.values()); + }, + get currentUserId() { + return stores.auth.user?.id; + }, + get currentTeamId() { + return stores.auth.team?.id; + }, + get location() { + return history.location; + }, + get sidebarContext() { + return history.location.state?.sidebarContext; + }, getActiveModels, getActiveModel, getActivePolicies, isModelActive, - activeModels: allActiveModels, - - currentUserId, - currentTeamId, - // Consumers reading `ctx.location` get the current location at access time. - location: history.location, stores, t, }; - // Derive legacy IDs from value models, falling back to base context - const activeCollectionId = - valueModels?.find( - (m) => (m.constructor as typeof Model).modelName === "Collection" - )?.id ?? baseContext.activeCollectionId; - - const activeDocumentId = - valueModels?.find( - (m) => (m.constructor as typeof Model).modelName === "Document" - )?.id ?? baseContext.activeDocumentId; - - const result = { - ...baseContext, + return mergeLazy<ActionContextType>(baseContext, { ...(isMenu !== undefined ? { isMenu } : {}), ...(isCommandBar !== undefined ? { isCommandBar } : {}), ...(isButton !== undefined ? { isButton } : {}), ...(event !== undefined ? { event } : {}), - activeCollectionId, - activeDocumentId, + + // Read from this provider's history, which is the pane's own history + // inside a split view. + get location() { + return history.location; + }, + get sidebarContext() { + return ( + sidebarContext ?? + parentContext?.sidebarContext ?? + history.location.state?.sidebarContext + ); + }, + get activeCollectionId() { + return valueCollectionId ?? baseContext.activeCollectionId; + }, + get activeDocumentId() { + return valueDocumentId ?? baseContext.activeDocumentId; + }, + get activeModels() { + const base = baseContext.activeModels; + return valueModels.length > 0 + ? new Set([...base, ...valueModels]) + : base; + }, getActiveModels, getActiveModel, getActivePolicies, isModelActive, - activeModels: allActiveModels, - }; - - // Define `location` as a getter so reads always return the current - // location without invalidating this memo on navigation. - Object.defineProperty(result, "location", { - get: () => history.location, - enumerable: true, - configurable: true, }); - - // The sidebar context is carried in location state, so fall back to the - // current location when no ancestor provider supplies one. A getter for the - // same reason as `location` above. - Object.defineProperty(result, "sidebarContext", { - get: () => - sidebarContext ?? - parentContext?.sidebarContext ?? - history.location.state?.sidebarContext, - enumerable: true, - configurable: true, - }); - - return result; }, [ parentContext, stores, @@ -216,15 +191,6 @@ export const ActionContextProvider = observer(function ActionContextProvider_({ isButton, sidebarContext, event, - activeCollectionIdFromStore, - activeDocumentIdFromStore, - currentUserId, - currentTeamId, - getActiveModels, - getActiveModel, - getActivePolicies, - isModelActive, - allActiveModels, ]); return ( @@ -232,7 +198,22 @@ export const ActionContextProvider = observer(function ActionContextProvider_({ {children} </ActionContext.Provider> ); -}); +} + +/** + * Merges objects in the same way as an object spread, but copies property + * descriptors so that getters are kept and evaluated on access. + * + * @param base the object to extend. + * @param overrides the properties that replace those of `base`. + * @returns a new object with the properties of both. + */ +function mergeLazy<T extends object>(base: T, overrides: Partial<T>): T { + return Object.defineProperties({} as T, { + ...Object.getOwnPropertyDescriptors(base), + ...Object.getOwnPropertyDescriptors(overrides), + }); +} /** * Returns the same object reference across calls as long as `value`'s own @@ -247,9 +228,9 @@ export const ActionContextProvider = observer(function ActionContextProvider_({ function useStableValue<T extends object>(value: T): T { const ref = useRef(value); - const isEqual = isEqualWith(ref.current, value, (x, y, key) => - key === undefined ? undefined : Object.is(x, y) - ); + const isEqual = + shallowEqual(Object.keys(ref.current), Object.keys(value)) && + shallowEqual(Object.values(ref.current), Object.values(value)); if (!isEqual) { ref.current = value; @@ -282,12 +263,18 @@ export default function useActionContext( ); } - const hasOverrides = !!overrides && Object.keys(overrides).length > 0; - // Stabilize the reference so callers that memoize on the returned context // (e.g. DropdownMenu's `useComputed`) don't invalidate on every render - // just because `overrides` is a new object literal each time. - return useStableValue( - hasOverrides ? { ...contextValue, ...overrides } : contextValue + // just because `overrides` is a new object literal each time. The getters of + // the context are not evaluated here, so that consumers do not observe them + // unless they are used. + const stableOverrides = useStableValue(overrides ?? EMPTY_OVERRIDES); + + return useMemo( + () => + Object.keys(stableOverrides).length > 0 + ? mergeLazy(contextValue, stableOverrides) + : contextValue, + [contextValue, stableOverrides] ); } diff --git a/app/hooks/useActiveSidebarContext.ts b/app/hooks/useActiveSidebarContext.ts index 56654c60b6..84fef045f1 100644 --- a/app/hooks/useActiveSidebarContext.ts +++ b/app/hooks/useActiveSidebarContext.ts @@ -1,6 +1,7 @@ import type { SidebarContextType } from "~/components/Sidebar/components/SidebarContext"; -import { useFocusedSplitLocation } from "./useFocusedSplitLocation"; -import { useLocationSidebarContext } from "./useLocationSidebarContext"; +import { useSplitView } from "~/components/SplitView/context"; +import { getFocusedSplitPane, getSplitPath } from "~/utils/splitView"; +import { useLocationSelector } from "./useLocationSelector"; /** * Hook to retrieve the sidebar context that the sidebar should treat as @@ -14,12 +15,19 @@ import { useLocationSidebarContext } from "./useLocationSidebarContext"; * @returns the active sidebar context. */ export function useActiveSidebarContext(): SidebarContextType { - const locationSidebarContext = useLocationSidebarContext(); - const splitLocation = useFocusedSplitLocation(); + const focusedPane = getFocusedSplitPane(); + const { isSplitView } = useSplitView(); + const isSecondaryFocused = !isSplitView && focusedPane === "secondary"; - if (splitLocation) { - return splitLocation.state?.sidebarContext; - } - - return locationSidebarContext; + // Select only the sidebar context, so that callers do not re-render on + // every navigation. + return useLocationSelector< + { sidebarContext?: SidebarContextType }, + SidebarContextType + >((location) => { + if (isSecondaryFocused && getSplitPath(location.search)) { + return location.state?.sidebarContext ?? "collections"; + } + return location.state?.sidebarContext; + }); } diff --git a/app/hooks/useClickIntent.ts b/app/hooks/useClickIntent.ts index ecff289a29..f5f8ff5829 100644 --- a/app/hooks/useClickIntent.ts +++ b/app/hooks/useClickIntent.ts @@ -1,16 +1,54 @@ +import { ForesightManager } from "js.foresight"; import * as React from "react"; +import { Second } from "@shared/utils/time"; import useUnmount from "./useUnmount"; +interface Options { + /** Milliseconds the cursor must hover before intent fires, defaults to 100. */ + delay?: number; + /** + * Also fire when the cursor moves towards the element, or keyboard focus is + * about to reach it. Use only for a small number of elements. + */ + predict?: boolean; +} + /** - * Hook to handle click intent logic with mouse enter/leave events. - * Sets a timer on mouse enter to call the intent callback after a delay, - * and clears the timer on mouse leave or component unmount. + * Hook to call a callback when the user is likely to click an element, used + * to preload data or code. Intent fires after the cursor hovers the element for + * a delay. With the predict option, it also fires when the cursor moves towards + * the element; attach the returned ref for this. + * + * @param onClickIntent callback to call when click intent is detected. + * @param options optional configuration. + * @returns mouse handlers and a ref to attach to the element. */ export default function useClickIntent( - onClickIntent?: React.MouseEventHandler<HTMLElement>, - delay = 100 + onClickIntent?: () => void, + { delay = 100, predict = false }: Options = {} ) { const timer = React.useRef<number | undefined>(undefined); + const callbackRef = React.useRef(onClickIntent); + const [element, setElement] = React.useState<HTMLElement | null>(null); + + React.useEffect(() => { + callbackRef.current = onClickIntent; + }, [onClickIntent]); + + React.useEffect(() => { + if (!predict || !element) { + return; + } + + const manager = ForesightManager.initialize({ setDataAttributes: false }); + const { unregister } = manager.register({ + element, + callback: () => callbackRef.current?.(), + reactivateAfter: 5 * Second.ms, + }); + + return unregister; + }, [predict, element]); const handleMouseEnter = React.useCallback(() => { if (timer.current) { @@ -34,5 +72,5 @@ export default function useClickIntent( } }); - return { handleMouseEnter, handleMouseLeave }; + return { ref: setElement, handleMouseEnter, handleMouseLeave }; } diff --git a/app/hooks/useCollectionTrees.ts b/app/hooks/useCollectionTrees.ts index 829e50b6b7..a106ce8fa9 100644 --- a/app/hooks/useCollectionTrees.ts +++ b/app/hooks/useCollectionTrees.ts @@ -30,7 +30,7 @@ export default function useCollectionTrees(): NavigationNode[] { function getCollectionTree(collection: Collection): NavigationNode { const root: NavigationNode = { id: collection.id, - title: collection.name, + title: collection.displayName, url: collection.path, type: NavigationNodeType.Collection, collectionId: collection.id, diff --git a/app/hooks/useCommandBarActions.ts b/app/hooks/useCommandBarActions.ts index c7df712efe..77cd08b58b 100644 --- a/app/hooks/useCommandBarActions.ts +++ b/app/hooks/useCommandBarActions.ts @@ -1,9 +1,9 @@ import { useRegisterActions } from "kbar"; import { flattenDeep } from "es-toolkit/compat"; -import { useLocation } from "react-router-dom"; import { actionToKBar } from "~/actions"; import type { ActionVariant } from "~/types"; import useActionContext from "./useActionContext"; +import { useLocationSelector } from "./useLocationSelector"; import useWebMCPActions from "./useWebMCPActions"; /** @@ -17,7 +17,7 @@ export default function useCommandBarActions( actions: ActionVariant[], additionalDeps: React.DependencyList = [] ) { - const location = useLocation(); + const pathname = useLocationSelector((location) => location.pathname); const context = useActionContext({ isCommandBar: true, }); @@ -30,7 +30,7 @@ export default function useCommandBarActions( useRegisterActions(registerable, [ registerable.map((r) => r.id).join(""), - location.pathname, + pathname, ...additionalDeps, ]); } diff --git a/app/hooks/useComputed.ts b/app/hooks/useComputed.ts index c68a6dfe02..92e120a068 100644 --- a/app/hooks/useComputed.ts +++ b/app/hooks/useComputed.ts @@ -12,7 +12,7 @@ export function useComputed<T>( inputs: DependencyList = [] ): T { // The dependency list is supplied by the caller so it cannot be verified here. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps const value = useMemo(() => computed(callback), inputs); return value.get(); } diff --git a/app/hooks/useEditingFocus.ts b/app/hooks/useEditingFocus.ts index 740282b435..9d3cc7f834 100644 --- a/app/hooks/useEditingFocus.ts +++ b/app/hooks/useEditingFocus.ts @@ -1,5 +1,6 @@ import { useDocumentContext } from "~/components/DocumentContext"; import useIdle from "./useIdle"; +import useMobile from "./useMobile"; const activityEvents = [ "click", @@ -12,8 +13,15 @@ const activityEvents = [ "focus", ]; +/** + * Hook to detect when the user is focused on editing, so that surrounding UI + * can be hidden. Always false on mobile, where the header stays visible. + * + * @returns true if the editor has focus and the user is otherwise idle. + */ export default function useEditingFocus() { const { editor } = useDocumentContext(); + const isMobile = useMobile(); const isIdle = useIdle(3000, activityEvents); - return isIdle && !!editor?.view.hasFocus(); + return !isMobile && isIdle && !!editor?.view.hasFocus(); } diff --git a/app/hooks/useEmbeds.ts b/app/hooks/useEmbeds.ts index 2c1c3ccc3c..128edff078 100644 --- a/app/hooks/useEmbeds.ts +++ b/app/hooks/useEmbeds.ts @@ -5,6 +5,7 @@ import embeds from "@shared/editor/embeds"; import { IntegrationType, TeamPreference } from "@shared/types"; import type Integration from "~/models/Integration"; import Logger from "~/utils/Logger"; +import { Hook, PluginManager } from "~/utils/PluginManager"; import useCurrentTeam from "./useCurrentTeam"; import useStores from "./useStores"; @@ -34,6 +35,8 @@ export default function useEmbeds(loadIfMissing = false) { } }, [integrations, loadIfMissing]); + // Plugins may register instance URL resolvers after integrations load. + const pluginsLoaded = PluginManager.isLoaded; const disabledEmbeds = (team?.getPreference(TeamPreference.DisabledEmbeds) as string[]) || []; @@ -46,13 +49,16 @@ export default function useEmbeds(loadIfMissing = false) { if (integration?.settings) { e.settings = integration.settings; + e.instanceUrl = PluginManager.getHooks(Hook.InstanceUrl) + .find((hook) => hook.value.service === e.name) + ?.value.url(integration.settings); } e.disabled = disabledEmbeds.includes(e.id); return e; }), - // eslint-disable-next-line react-hooks/exhaustive-deps - [integrations.orderedData, team?.preferences] + // oxlint-disable-next-line react-hooks/exhaustive-deps + [integrations.orderedData, team?.preferences, pluginsLoaded] ); } diff --git a/app/hooks/useInterval.ts b/app/hooks/useInterval.ts index be98672ebf..f154a54bc8 100644 --- a/app/hooks/useInterval.ts +++ b/app/hooks/useInterval.ts @@ -16,7 +16,6 @@ export default function useInterval(callback: Callback, delay: number) { savedCallback.current = callback; }, [callback]); - // Set up the interval. useEffect(() => { function tick() { savedCallback.current?.(); diff --git a/app/hooks/useKeyDown.ts b/app/hooks/useKeyDown.ts index 344e625967..2929b04e90 100644 --- a/app/hooks/useKeyDown.ts +++ b/app/hooks/useKeyDown.ts @@ -1,7 +1,10 @@ import { useContext, useEffect } from "react"; import { isModKey } from "@shared/utils/keyboard"; import { SplitViewContext } from "~/components/SplitView/context"; -import { isKeyboardWidget } from "~/utils/isKeyboardWidget"; +import { + isKeyboardWidget, + isWithinKeyboardWidget, +} from "~/utils/isKeyboardWidget"; import { getFocusedSplitPane } from "~/utils/splitView"; type Callback = (event: KeyboardEvent) => void; @@ -14,6 +17,12 @@ export type Options = { * input, such as a text input, menu, or dialog. */ allowInInput?: boolean; + /** + * Fire when focus is inside a text input, such as the editor, but not inside + * a widget such as a menu or dialog. Keys that the input already handled are + * ignored. + */ + allowInTextInput?: boolean; /** Require the platform modifier key (Cmd on macOS, Ctrl elsewhere) to be held. */ metaKey?: boolean; /** Require the Alt/Option key to be held. */ @@ -124,6 +133,9 @@ window.addEventListener("keydown", (event) => { // Radix UI's DismissableLayer) so we only break on preventDefault calls made // by our own callbacks. const wasDefaultPrevented = event.defaultPrevented; + const isWidget = isKeyboardWidget(event.target); + const allowsTextInput = + !wasDefaultPrevented && !isWithinKeyboardWidget(event.target); // reverse so that the last registered callbacks get executed first for (const registered of [...callbacks].reverse()) { @@ -132,8 +144,9 @@ window.addEventListener("keydown", (event) => { } if ( - !isKeyboardWidget(event.target) || + !isWidget || registered.options?.allowInInput || + (registered.options?.allowInTextInput && allowsTextInput) || isModKey(event) ) { registered.callback(event); diff --git a/app/hooks/useKeyboardShortcutsQuery.tsx b/app/hooks/useKeyboardShortcutsQuery.tsx index f2384133b4..5d5737f5f0 100644 --- a/app/hooks/useKeyboardShortcutsQuery.tsx +++ b/app/hooks/useKeyboardShortcutsQuery.tsx @@ -1,6 +1,6 @@ import { useEffect } from "react"; import { useTranslation } from "react-i18next"; -import KeyboardShortcuts from "~/scenes/KeyboardShortcuts"; +import KeyboardShortcuts from "~/components/KeyboardShortcuts"; import useQuery from "./useQuery"; import useStores from "./useStores"; @@ -26,6 +26,6 @@ export default function useKeyboardShortcutsQuery() { }); // Only the query param should open the guide, re-running when the other // dependencies change would reopen an already dismissed dialog. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [shortcutsQuery]); } diff --git a/app/hooks/useLastVisitedPath.test.ts b/app/hooks/useLastVisitedPath.test.ts new file mode 100644 index 0000000000..091f76bbbc --- /dev/null +++ b/app/hooks/useLastVisitedPath.test.ts @@ -0,0 +1,32 @@ +import { getCookie, removeCookie } from "tiny-cookie"; +import { setPostLoginPath } from "./useLastVisitedPath"; + +const key = "postLoginRedirectPath"; + +describe("setPostLoginPath", () => { + beforeEach(() => { + sessionStorage.clear(); + removeCookie(key); + }); + + it("stores the path in session storage and the shared cookie", () => { + setPostLoginPath("/doc/a"); + + expect(sessionStorage.getItem(key)).toBe("/doc/a"); + expect(getCookie(key)).toBe("/doc/a"); + }); + + it("does not change the shared cookie when tabOnly is set", () => { + setPostLoginPath("/doc/a"); + setPostLoginPath("/doc/b", { tabOnly: true }); + + expect(sessionStorage.getItem(key)).toBe("/doc/b"); + expect(getCookie(key)).toBe("/doc/a"); + }); + + it("ignores paths that are not allowed as a login redirect", () => { + setPostLoginPath("/home", { tabOnly: true }); + + expect(sessionStorage.getItem(key)).toBeNull(); + }); +}); diff --git a/app/hooks/useLastVisitedPath.tsx b/app/hooks/useLastVisitedPath.tsx index e7f29b6135..a8b25bbfbc 100644 --- a/app/hooks/useLastVisitedPath.tsx +++ b/app/hooks/useLastVisitedPath.tsx @@ -56,12 +56,19 @@ export function useTrackLastVisitedPath(currentPath: string): void { * Sets the path that the user visited before being asked to login. * * @param path The path to set as the post login path. + * @param options.tabOnly Whether to store the path for the current tab only, rather than + * also sharing it with other tabs through a cookie. */ -export function setPostLoginPath(path: string) { +export function setPostLoginPath( + path: string, + options: { tabOnly?: boolean } = {} +) { const key = "postLoginRedirectPath"; if (isAllowedLoginRedirect(path)) { - setCookie(key, path, { expires: 1 }); + if (!options.tabOnly) { + setCookie(key, path, { expires: 1 }); + } try { sessionStorage.setItem(key, path); diff --git a/app/hooks/useLocationSelector.ts b/app/hooks/useLocationSelector.ts new file mode 100644 index 0000000000..a2df81fd93 --- /dev/null +++ b/app/hooks/useLocationSelector.ts @@ -0,0 +1,24 @@ +import type { Location } from "history"; +import { useCallback, useSyncExternalStore } from "react"; +import { useHistory } from "react-router-dom"; + +/** + * Returns a value derived from the current location. Unlike `useLocation`, + * the component only re-renders when the derived value changes, not on every + * navigation. + * + * @param selector derives the value from the location. Values are compared + * with `Object.is`, so it should return a primitive or a stable reference. + * @returns the derived value. + */ +export function useLocationSelector<State, Value>( + selector: (location: Location<State>) => Value +): Value { + const history = useHistory<State>(); + const subscribe = useCallback( + (onChange: () => void) => history.listen(onChange), + [history] + ); + + return useSyncExternalStore(subscribe, () => selector(history.location)); +} diff --git a/app/hooks/useLocationSidebarContext.ts b/app/hooks/useLocationSidebarContext.ts index dd57c67e7f..906df26783 100644 --- a/app/hooks/useLocationSidebarContext.ts +++ b/app/hooks/useLocationSidebarContext.ts @@ -1,12 +1,14 @@ -import { useLocation } from "react-router-dom"; import type { SidebarContextType } from "../components/Sidebar/components/SidebarContext"; +import { useLocationSelector } from "./useLocationSelector"; /** * Hook to retrieve the sidebar context from the current location state. + * + * @returns the sidebar context of the current location, if any. */ export function useLocationSidebarContext() { - const location = useLocation<{ - sidebarContext?: SidebarContextType; - }>(); - return location.state?.sidebarContext; + return useLocationSelector< + { sidebarContext?: SidebarContextType }, + SidebarContextType | undefined + >((location) => location.state?.sidebarContext); } diff --git a/app/hooks/useLoggedInSessions.ts b/app/hooks/useLoggedInSessions.ts deleted file mode 100644 index dbdbbcf719..0000000000 --- a/app/hooks/useLoggedInSessions.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { getCookie } from "tiny-cookie"; - -export type Sessions = Record< - string, - { - name: string; - logoUrl: string; - url: string; - } ->; - -export function useLoggedInSessions(): Sessions { - return JSON.parse(getCookie("sessions") || "{}"); -} diff --git a/app/hooks/useOnScreen.ts b/app/hooks/useOnScreen.ts index ee73370150..e35165e5f4 100644 --- a/app/hooks/useOnScreen.ts +++ b/app/hooks/useOnScreen.ts @@ -74,7 +74,7 @@ export default function useOnScreen( return () => observer.disconnect(); }, // Re-create when option primitives change; options object identity ignored - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps [root, rootMargin, threshold] ); diff --git a/app/hooks/usePaginatedRequest.ts b/app/hooks/usePaginatedRequest.ts index 1d27f4faea..19e9e41867 100644 --- a/app/hooks/usePaginatedRequest.ts +++ b/app/hooks/usePaginatedRequest.ts @@ -83,7 +83,7 @@ export default function usePaginatedRequest<T = unknown>( } // `params` is intentionally omitted, callers pass an object literal which // changes identity on every render. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [offset, fetchLimit, requestFn]); const next = useCallback(() => { @@ -105,7 +105,7 @@ export default function usePaginatedRequest<T = unknown>( ); // `params` and `fetchLimit` are intentionally omitted, resetting pagination // should only be driven by the request function changing. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [requestFn]); return { data, next, loading, error, page, offset, end }; diff --git a/app/hooks/useQuery.ts b/app/hooks/useQuery.ts index 42ae9349da..610f923213 100644 --- a/app/hooks/useQuery.ts +++ b/app/hooks/useQuery.ts @@ -1,5 +1,5 @@ import { useMemo } from "react"; -import { useLocation } from "react-router-dom"; +import { useLocationSelector } from "./useLocationSelector"; /** * Hook to access URL query parameters from the current location. @@ -7,12 +7,9 @@ import { useLocation } from "react-router-dom"; * @returns URLSearchParams object containing the current URL query parameters */ export default function useQuery() { - const location = useLocation(); + const search = useLocationSelector((location) => location.search); - const query = useMemo( - () => new URLSearchParams(location.search), - [location.search] - ); + const query = useMemo(() => new URLSearchParams(search), [search]); return query; } diff --git a/app/hooks/useRequest.ts b/app/hooks/useRequest.ts index 8267aacc12..86810bef34 100644 --- a/app/hooks/useRequest.ts +++ b/app/hooks/useRequest.ts @@ -52,7 +52,7 @@ export default function useRequest<T = unknown>( } // Only ever request on mount, later changes to the request function are // surfaced through the returned `request` for the caller to invoke. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, []); return { data, loading, loaded, error, request }; diff --git a/app/hooks/useSettingsConfig.ts b/app/hooks/useSettingsConfig.ts index 39b9462438..c1764bd520 100644 --- a/app/hooks/useSettingsConfig.ts +++ b/app/hooks/useSettingsConfig.ts @@ -30,13 +30,13 @@ import useCurrentUser from "./useCurrentUser"; import usePolicy from "./usePolicy"; import useStores from "./useStores"; +const AI = lazy(() => import("~/scenes/Settings/AI")); const ApiKeys = lazy(() => import("~/scenes/Settings/ApiKeys")); const Applications = lazy(() => import("~/scenes/Settings/Applications")); const APIAndAccess = lazy(() => import("~/scenes/Settings/APIAndAccess")); const Authentication = lazy(() => import("~/scenes/Settings/Authentication")); const Details = lazy(() => import("~/scenes/Settings/Details")); const Export = lazy(() => import("~/scenes/Settings/Export")); -const Features = lazy(() => import("~/scenes/Settings/Features")); const Groups = lazy(() => import("~/scenes/Settings/Groups")); const Import = lazy(() => import("~/scenes/Settings/Import")); const Integrations = lazy(() => import("~/scenes/Settings/Integrations")); @@ -114,11 +114,11 @@ const useSettingsConfig = () => { preload: APIAndAccess.preload, enabled: true, group: t("Account"), - icon: PadlockIcon, + icon: CodeIcon, }, // Workspace { - name: t("Details"), + name: t("General"), path: settingsPath("details"), component: Details.Component, preload: Details.preload, @@ -126,33 +126,6 @@ const useSettingsConfig = () => { group: t("Workspace"), icon: TeamIcon, }, - { - name: t("Authentication"), - path: settingsPath("authentication"), - component: Authentication.Component, - preload: Authentication.preload, - enabled: can.update, - group: t("Workspace"), - icon: PadlockIcon, - }, - { - name: t("Security"), - path: settingsPath("security"), - component: Security.Component, - preload: Security.preload, - enabled: can.update, - group: t("Workspace"), - icon: ShieldIcon, - }, - { - name: t("AI"), - path: settingsPath("features"), - component: Features.Component, - preload: Features.preload, - enabled: can.update, - group: t("Workspace"), - icon: SparklesIcon, - }, { name: t("Users"), path: settingsPath("users"), @@ -171,6 +144,24 @@ const useSettingsConfig = () => { group: t("Workspace"), icon: GroupIcon, }, + { + name: t("Authentication"), + path: settingsPath("authentication"), + component: Authentication.Component, + preload: Authentication.preload, + enabled: can.update, + group: t("Workspace"), + icon: PadlockIcon, + }, + { + name: t("Security"), + path: settingsPath("security"), + component: Security.Component, + preload: Security.preload, + enabled: can.update, + group: t("Workspace"), + icon: ShieldIcon, + }, { name: t("Templates"), path: settingsPath("templates"), @@ -190,25 +181,16 @@ const useSettingsConfig = () => { icon: SmileyIcon, }, { - name: t("API Keys"), - path: settingsPath("api-keys"), - component: ApiKeys.Component, - preload: ApiKeys.preload, - enabled: can.listApiKeys, + name: t("AI"), + path: settingsPath("ai"), + component: AI.Component, + preload: AI.preload, + enabled: can.update, group: t("Workspace"), - icon: CodeIcon, + icon: SparklesIcon, }, { - name: t("Applications"), - path: settingsPath("applications"), - component: Applications.Component, - preload: Applications.preload, - enabled: can.listOAuthClients, - group: t("Workspace"), - icon: InternetIcon, - }, - { - name: t("Shared Links"), + name: t("Shared links"), path: settingsPath("shares"), component: Shares.Component, preload: Shares.preload, @@ -256,6 +238,25 @@ const useSettingsConfig = () => { group: t("Integrations"), icon: PlusIcon, }, + // Developer + { + name: t("API keys"), + path: settingsPath("api-keys"), + component: ApiKeys.Component, + preload: ApiKeys.preload, + enabled: can.listApiKeys, + group: t("Developer"), + icon: CodeIcon, + }, + { + name: t("Applications"), + path: settingsPath("applications"), + component: Applications.Component, + preload: Applications.preload, + enabled: can.listOAuthClients, + group: t("Developer"), + icon: InternetIcon, + }, ]; // Plugins diff --git a/app/hooks/useShareMenuActions.tsx b/app/hooks/useShareMenuActions.tsx index 531851c54a..536e1efd3d 100644 --- a/app/hooks/useShareMenuActions.tsx +++ b/app/hooks/useShareMenuActions.tsx @@ -4,6 +4,7 @@ import { copyShareUrl, goToShareSource, revokeShare, + setShareExpiry, } from "~/actions/definitions/shares"; import { useMenuAction } from "~/hooks/useMenuAction"; @@ -15,7 +16,13 @@ import { useMenuAction } from "~/hooks/useMenuAction"; */ export function useShareMenuActions() { const actions = useMemo( - () => [copyShareUrl, goToShareSource, ActionSeparator, revokeShare], + () => [ + copyShareUrl, + goToShareSource, + setShareExpiry, + ActionSeparator, + revokeShare, + ], [] ); diff --git a/app/hooks/useStuckAttribute.ts b/app/hooks/useStuckAttribute.ts new file mode 100644 index 0000000000..9bb0483233 --- /dev/null +++ b/app/hooks/useStuckAttribute.ts @@ -0,0 +1,37 @@ +import * as React from "react"; + +/** + * Toggles a `data-stuck` attribute on a sticky element while it is stuck, so + * that other elements, such as the app header, can style themselves to match. + * The attribute is set on the DOM directly to avoid a re-render on scroll. + * + * @param ref the sticky element. + * @param top the offset from the top of the viewport at which the element sticks. + */ +export function useStuckAttribute( + ref: React.RefObject<HTMLElement | null>, + top: number +) { + React.useEffect(() => { + const element = ref.current; + if (!element || typeof IntersectionObserver === "undefined") { + return; + } + const observer = new IntersectionObserver( + ([entry]) => { + element.toggleAttribute( + "data-stuck", + entry.isIntersecting && + entry.intersectionRatio < 1 && + entry.boundingClientRect.top <= top + 1 + ); + }, + { threshold: [0, 1], rootMargin: `-${top + 1}px 0px 0px 0px` } + ); + observer.observe(element); + return () => { + observer.disconnect(); + element.removeAttribute("data-stuck"); + }; + }, [ref, top]); +} diff --git a/app/hooks/useSwipeToDismiss.ts b/app/hooks/useSwipeToDismiss.ts new file mode 100644 index 0000000000..be49b7cc50 --- /dev/null +++ b/app/hooks/useSwipeToDismiss.ts @@ -0,0 +1,175 @@ +import { useEffect } from "react"; +import type { RefObject } from "react"; + +interface Options { + /** Whether the panel is open and can be swiped away. */ + enabled: boolean; + /** The screen edge that the panel is attached to. */ + side: "left" | "right"; + /** Called when a swipe passes the dismiss threshold. */ + onDismiss: () => void; +} + +/** Distance in pixels a pointer must move before the gesture is a drag or a scroll. */ +const DragSlop = 8; + +/** Release speed in px/ms above which the panel is dismissed, matches vaul. */ +const VelocityThreshold = 0.4; + +/** Fraction of the panel width past which the panel is dismissed, matches vaul. */ +const CloseThreshold = 0.25; + +/** Rubber band resistance for a drag away from the edge, matches vaul. */ +const dampen = (value: number) => Math.max(8 * (Math.log(value + 1) - 2), 0); + +/** + * Lets the user drag an edge-attached panel toward its edge to dismiss it, with + * the same thresholds as the vaul drawer. The panel follows the pointer, and on + * release it either dismisses or springs back using the CSS transition of the + * panel. A vertical gesture is left to the browser so that the panel can scroll. + * + * @param panelRef ref to the panel element that moves. + * @param overlayRef ref to an optional backdrop that fades as the panel moves. + * @param options the swipe options. + */ +export function useSwipeToDismiss( + panelRef: RefObject<HTMLElement | null>, + overlayRef: RefObject<HTMLElement | null>, + { enabled, side, onDismiss }: Options +) { + useEffect(() => { + const panel = panelRef.current; + if (!enabled || !panel) { + return; + } + const overlay = overlayRef.current; + const sign = side === "left" ? -1 : 1; + + let start: { x: number; y: number; time: number } | null = null; + let isDragging = false; + let width = 0; + let distance = 0; + + const setStyles = ( + transition: string, + transform: string, + opacity: string + ) => { + panel.style.transition = transition; + panel.style.transform = transform; + if (overlay) { + overlay.style.transition = transition; + overlay.style.opacity = opacity; + } + }; + + const suppressClick = (event: MouseEvent) => { + event.preventDefault(); + event.stopPropagation(); + }; + + const handlePointerDown = (event: PointerEvent) => { + if (!event.isPrimary || event.button !== 0) { + return; + } + start = { x: event.clientX, y: event.clientY, time: event.timeStamp }; + isDragging = false; + distance = 0; + }; + + const handlePointerMove = (event: PointerEvent) => { + if (!start || !event.isPrimary) { + return; + } + const dx = event.clientX - start.x; + const dy = event.clientY - start.y; + + if (!isDragging) { + if (Math.abs(dx) < DragSlop && Math.abs(dy) < DragSlop) { + return; + } + + // A mostly vertical gesture is a scroll, so leave it to the browser. + if (Math.abs(dy) >= Math.abs(dx)) { + start = null; + return; + } + isDragging = true; + width = panel.getBoundingClientRect().width; + panel.setPointerCapture(event.pointerId); + } + + // A drag away from the edge stretches with resistance. Whole pixels + // stop a visible line where the panel meets its fill. + const dragged = dx * sign; + distance = Math.round( + dragged >= 0 ? Math.min(dragged, width) : -dampen(-dragged) + ); + setStyles( + "none", + `translateX(${distance * sign}px)`, + String(1 - Math.max(distance, 0) / width) + ); + }; + + const handlePointerUp = (event: PointerEvent) => { + if (!event.isPrimary) { + return; + } + if (!start || !isDragging) { + start = null; + return; + } + const velocity = + Math.abs(event.clientX - start.x) / + Math.max(event.timeStamp - start.time, 1); + start = null; + isDragging = false; + + // The pointer moved, so the click that follows is not a tap. + panel.addEventListener("click", suppressClick, { + capture: true, + once: true, + }); + setTimeout(() => { + panel.removeEventListener("click", suppressClick, { capture: true }); + }, 0); + + if ( + distance > 0 && + (velocity > VelocityThreshold || distance >= width * CloseThreshold) + ) { + // Hold the closed position until the closed styles apply, then the + // cleanup below removes the inline styles. + setStyles("", `translateX(${sign * 100}%)`, "0"); + onDismiss(); + return; + } + setStyles("", "", ""); + }; + + const handlePointerCancel = (event: PointerEvent) => { + if (!event.isPrimary) { + return; + } + if (isDragging) { + setStyles("", "", ""); + } + start = null; + isDragging = false; + }; + + panel.addEventListener("pointerdown", handlePointerDown); + panel.addEventListener("pointermove", handlePointerMove); + panel.addEventListener("pointerup", handlePointerUp); + panel.addEventListener("pointercancel", handlePointerCancel); + + return () => { + panel.removeEventListener("pointerdown", handlePointerDown); + panel.removeEventListener("pointermove", handlePointerMove); + panel.removeEventListener("pointerup", handlePointerUp); + panel.removeEventListener("pointercancel", handlePointerCancel); + setStyles("", "", ""); + }; + }, [panelRef, overlayRef, enabled, side, onDismiss]); +} diff --git a/app/hooks/useSyncSidebarContext.ts b/app/hooks/useSyncSidebarContext.ts new file mode 100644 index 0000000000..d9adb853d7 --- /dev/null +++ b/app/hooks/useSyncSidebarContext.ts @@ -0,0 +1,53 @@ +import { useEffect } from "react"; +import { useHistory } from "react-router-dom"; +import type { SidebarContextType } from "~/components/Sidebar/components/SidebarContext"; +import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext"; +import useStores from "~/hooks/useStores"; +import { patchLocation } from "~/utils/history"; + +/** + * Writes the sidebar context of the active document into the location state, so + * that the section which contains the document is the one revealed in the + * sidebar. Sections the user is already looking at, and the starred section, + * are left alone. + * + * @param belongsToSection whether the given context is one of this section's own. + * @param resolve returns the context for the active document, or undefined when + * the document does not belong to this section. + */ +export function useSyncSidebarContext( + belongsToSection: (context: NonNullable<SidebarContextType>) => boolean, + resolve: (activeDocumentId: string) => SidebarContextType | undefined +) { + const { ui } = useStores(); + const history = useHistory(); + const locationSidebarContext = useLocationSidebarContext(); + + useEffect(() => { + if ( + !ui.activeDocumentId || + (locationSidebarContext && + (belongsToSection(locationSidebarContext) || + locationSidebarContext.startsWith("starred"))) + ) { + return; + } + + const sidebarContext = resolve(ui.activeDocumentId); + if (!sidebarContext) { + return; + } + + history.push( + patchLocation(history.location, { + state: { + ...(history.location.state as Record<string, unknown>), + sidebarContext, + }, + }) + ); + // `history` is read imperatively, the sidebar context should only be + // recalculated when the active document or memberships change. + // oxlint-disable-next-line react-hooks/exhaustive-deps + }, [ui.activeDocumentId, locationSidebarContext, belongsToSection, resolve]); +} diff --git a/app/hooks/useTableRequest.ts b/app/hooks/useTableRequest.ts index 7c845b62da..fac00153d9 100644 --- a/app/hooks/useTableRequest.ts +++ b/app/hooks/useTableRequest.ts @@ -1,5 +1,5 @@ import type { ColumnSort } from "@tanstack/react-table"; -import { orderBy } from "es-toolkit/compat"; +import { orderBy, uniqBy } from "es-toolkit/compat"; import { useState, useRef, useCallback, useEffect } from "react"; import type { FetchPageParams, PaginatedResponse } from "~/stores/base/Store"; import { PAGINATION_SYMBOL } from "~/stores/base/Store"; @@ -9,7 +9,12 @@ const INITIAL_OFFSET = 0; const PAGE_SIZE = 25; type Props<T> = { - data: T[]; + /** + * The rows to display, usually derived from a store. When omitted the rows + * returned by the server for the current params are displayed, which is + * required when the server filtering can't be reproduced on the client. + */ + data?: T[]; sort: ColumnSort; reqFn: (params: FetchPageParams) => Promise<PaginatedResponse<T>>; reqParams: Omit<FetchPageParams, "offset" | "limit">; @@ -28,6 +33,7 @@ export function useTableRequest<T extends { id: string }>({ reqFn, reqParams, }: Props<T>): Response<T> { + const [rows, setRows] = useState<T[]>([]); const [hasNext, setHasNext] = useState(false); const [offset, setOffset] = useState({ value: INITIAL_OFFSET }); const prevParamsRef = useRef(reqParams); @@ -48,9 +54,11 @@ export function useTableRequest<T extends { id: string }>({ [] ); - const sortedData = data - ? orderBy(data, sortRef.current.id, sortRef.current.desc ? "desc" : "asc") - : undefined; + const sortedData = orderBy( + data ?? rows, + sortRef.current.id, + sortRef.current.desc ? "desc" : "asc" + ); const next = !loading && hasNext ? nextPage : undefined; @@ -71,6 +79,11 @@ export function useTableRequest<T extends { id: string }>({ } sortRef.current = sort; // Change sort once we receive a response from server - avoids flicker with stale data. + setRows((prev) => + offset.value === INITIAL_OFFSET + ? response + : uniqBy([...prev, ...response], "id") + ); const pagination = response[PAGINATION_SYMBOL]; setHasNext( !!pagination && pagination.offset + response.length < pagination.total diff --git a/app/hooks/useTemplateMenuActions.tsx b/app/hooks/useTemplateMenuActions.tsx index f1d4a30765..ad1545b387 100644 --- a/app/hooks/useTemplateMenuActions.tsx +++ b/app/hooks/useTemplateMenuActions.tsx @@ -47,10 +47,7 @@ export function useTemplateMenuActions({ const templateToAction = useCallback( (template: Template): Action => createAction({ - name: TextHelper.replaceTemplateVariables( - template.titleWithDefault, - user - ), + name: TextHelper.replaceTemplateVariables(template.displayTitle, user), section: DocumentsSection, icon: template.icon ? ( <Icon diff --git a/app/hooks/useWaypoint.ts b/app/hooks/useWaypoint.ts new file mode 100644 index 0000000000..52d18caeaa --- /dev/null +++ b/app/hooks/useWaypoint.ts @@ -0,0 +1,49 @@ +import * as React from "react"; + +interface WaypointOptions { + /** Margin around the viewport in CSS margin syntax, e.g. "0px 0px 200px 0px". */ + rootMargin?: string; +} + +/** + * Hook to call a function when an element enters the viewport. The function is + * also called on mount if the element is already in view. To check again after + * the content changes, remount the element with a new key. + * + * @param onEnter - function to call when the element enters the viewport. + * @param options - options for the observer. + * @returns a ref callback to attach to the element. + */ +export default function useWaypoint( + onEnter: (() => void) | undefined, + options?: WaypointOptions +): React.RefCallback<HTMLElement> { + const savedOnEnter = React.useRef(onEnter); + const rootMargin = options?.rootMargin; + + React.useLayoutEffect(() => { + savedOnEnter.current = onEnter; + }, [onEnter]); + + return React.useCallback( + (element: HTMLElement | null) => { + if (!element || typeof IntersectionObserver === "undefined") { + return; + } + + let wasIntersecting = false; + const observer = new IntersectionObserver( + ([entry]) => { + if (entry.isIntersecting && !wasIntersecting) { + savedOnEnter.current?.(); + } + wasIntersecting = entry.isIntersecting; + }, + { rootMargin } + ); + observer.observe(element); + return () => observer.disconnect(); + }, + [rootMargin] + ); +} diff --git a/app/hooks/useWebMCPActions.ts b/app/hooks/useWebMCPActions.ts index 1f4d7d60f6..380a9ba1ee 100644 --- a/app/hooks/useWebMCPActions.ts +++ b/app/hooks/useWebMCPActions.ts @@ -1,6 +1,5 @@ import { snakeCase } from "es-toolkit"; import * as React from "react"; -import { useLocation } from "react-router-dom"; import { TeamPreference } from "@shared/types"; import { toError } from "@shared/utils/error"; import { performAction, resolve } from "~/actions"; @@ -17,6 +16,7 @@ import { registerModelContextTool, } from "~/utils/ModelContext"; import useActionContext from "./useActionContext"; +import { useLocationSelector } from "./useLocationSelector"; import useStores from "./useStores"; type PerformableAction = Exclude<ActionVariant, ActionWithChildren>; @@ -31,7 +31,7 @@ export default function useWebMCPActions( actions: ActionVariant[], additionalDeps: React.DependencyList = [] ) { - const location = useLocation(); + const pathname = useLocationSelector((location) => location.pathname); const { auth } = useStores(); const context = useActionContext({ isMCP: true }); @@ -107,8 +107,8 @@ export default function useWebMCPActions( Analytics.track("webmcp", "register"); return () => controller.abort(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [enabled, toolNames.join(","), location.pathname, ...additionalDeps]); + // oxlint-disable-next-line react-hooks/exhaustive-deps + }, [enabled, toolNames.join(","), pathname, ...additionalDeps]); } function flattenActions( diff --git a/app/hooks/useWindowScrollPosition.ts b/app/hooks/useWindowScrollPosition.ts index a2c49ae232..966903b028 100644 --- a/app/hooks/useWindowScrollPosition.ts +++ b/app/hooks/useWindowScrollPosition.ts @@ -2,7 +2,6 @@ // maintained. import { throttle } from "es-toolkit/compat"; import { useCallback, useRef, useSyncExternalStore } from "react"; -import { supportsPassiveListener } from "@shared/utils/browser"; type ScrollPosition = { x: number; y: number }; @@ -41,11 +40,7 @@ export default function useWindowScrollPosition(options: { const subscribe = useCallback( (onStoreChange: () => void) => { const handleScroll = throttle(onStoreChange, throttleMs); - window.addEventListener( - "scroll", - handleScroll, - supportsPassiveListener ? { passive: true } : false - ); + window.addEventListener("scroll", handleScroll, { passive: true }); return () => { handleScroll.cancel(); window.removeEventListener("scroll", handleScroll); diff --git a/app/hooks/useWorkspaceSessions.ts b/app/hooks/useWorkspaceSessions.ts new file mode 100644 index 0000000000..846c4d37e4 --- /dev/null +++ b/app/hooks/useWorkspaceSessions.ts @@ -0,0 +1,19 @@ +import { getCookie } from "tiny-cookie"; +import type { Sessions } from "@shared/utils/sessions"; +import { + getRememberedSessions, + parseSessionsCookie, +} from "@shared/utils/sessions"; + +export type { Sessions } from "@shared/utils/sessions"; + +/** + * Reads workspaces used in the last three months, including logged-out entries. + * + * @returns the remembered workspace sessions. + */ +export function useWorkspaceSessions(): Sessions { + return getRememberedSessions( + parseSessionsCookie(getCookie("sessions") || "{}") + ); +} diff --git a/app/index.tsx b/app/index.tsx index 5912923611..aff036a6ab 100644 --- a/app/index.tsx +++ b/app/index.tsx @@ -1,4 +1,3 @@ -// oxlint-disable-next-line import/no-unresolved import "vite/modulepreload-polyfill"; // Keep ahead of the other imports so polyfills apply before they evaluate. import "~/utils/polyfills"; @@ -22,9 +21,8 @@ import Toasts from "~/components/Toasts"; import env from "~/env"; import { initI18n } from "~/utils/i18n"; import Desktop from "./components/DesktopEventHandler"; -import LazyPolyfill from "./components/LazyPolyfills"; import PageScroll from "./components/PageScroll"; -import Routes from "./routes"; +import Routes, { preloadShared } from "./routes"; import Logger from "./utils/Logger"; import { PluginManager } from "./utils/PluginManager"; import history from "./utils/history"; @@ -77,20 +75,18 @@ if (element) { <ActionContextProvider> <ErrorBoundary showTitle> <KBarProvider actions={[]} options={commandBarOptions}> - <LazyPolyfill> - <LazyMotion features={domMax}> - <PageScroll> - <PageTheme /> - <ScrollToTop> - <Routes /> - </ScrollToTop> - <Toasts /> - <Dialogs /> - <Presentation /> - <Desktop /> - </PageScroll> - </LazyMotion> - </LazyPolyfill> + <LazyMotion features={domMax}> + <PageScroll> + <PageTheme /> + <ScrollToTop> + <Routes /> + </ScrollToTop> + <Toasts /> + <Dialogs /> + <Presentation /> + <Desktop /> + </PageScroll> + </LazyMotion> </KBarProvider> </ErrorBoundary> </ActionContextProvider> @@ -101,8 +97,16 @@ if (element) { </StrictMode> ); - element.__reactRoot ??= createRoot(element); - element.__reactRoot.render(<App />); + // A lazy chunk that suspends the first render holds back the content for + // 300ms after it loads, so share pages wait for their chunks before render. + const ready = env.isShare + ? preloadShared().catch(() => undefined) + : Promise.resolve(); + + void ready.then(() => { + element.__reactRoot ??= createRoot(element); + element.__reactRoot.render(<App />); + }); } window.addEventListener("load", async () => { diff --git a/app/menus/DocumentMenu.tsx b/app/menus/DocumentMenu.tsx index 6e676955ce..22010c351e 100644 --- a/app/menus/DocumentMenu.tsx +++ b/app/menus/DocumentMenu.tsx @@ -3,7 +3,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { s } from "@shared/styles"; import { SubscriptionType, UserPreference } from "@shared/types"; import type Document from "~/models/Document"; diff --git a/app/menus/NewChildDocumentMenu.tsx b/app/menus/NewChildDocumentMenu.tsx index b3264c26d5..8f80fd35b6 100644 --- a/app/menus/NewChildDocumentMenu.tsx +++ b/app/menus/NewChildDocumentMenu.tsx @@ -25,7 +25,7 @@ function NewChildDocumentMenu({ document }: Props) { const collection = document.collectionId ? collections.get(document.collectionId) : undefined; - const collectionName = collection ? collection.name : t("collection"); + const collectionName = collection ? collection.displayName : t("collection"); const actions = React.useMemo( () => [ @@ -50,7 +50,7 @@ function NewChildDocumentMenu({ document }: Props) { <Trans defaults="New document in <em>{{ collectionName }}</em>" values={{ - collectionName: document.titleWithDefault, + collectionName: document.displayTitle, }} components={{ em: <strong />, @@ -66,7 +66,7 @@ function NewChildDocumentMenu({ document }: Props) { collectionName, canCollection.createDocument, document.id, - document.titleWithDefault, + document.displayTitle, document.collectionId, ] ); @@ -74,7 +74,7 @@ function NewChildDocumentMenu({ document }: Props) { const rootAction = useMenuAction(actions); return ( - <Tooltip content={t("New document")} shortcut="n" placement="bottom"> + <Tooltip content={t("New document")} shortcut="n" side="bottom"> <DropdownMenu action={rootAction} align="end" diff --git a/app/menus/NewDocumentMenu.tsx b/app/menus/NewDocumentMenu.tsx index dd43fa26bf..796412ae06 100644 --- a/app/menus/NewDocumentMenu.tsx +++ b/app/menus/NewDocumentMenu.tsx @@ -19,7 +19,7 @@ function NewDocumentMenu() { } return ( - <Tooltip content={t("New document")} shortcut="n" placement="bottom"> + <Tooltip content={t("New document")} shortcut="n" side="bottom"> <Button as={Link} to={newDocumentPath()} diff --git a/app/menus/NewTemplateMenu.tsx b/app/menus/NewTemplateMenu.tsx index dd7e7f3a6b..23a4e264c5 100644 --- a/app/menus/NewTemplateMenu.tsx +++ b/app/menus/NewTemplateMenu.tsx @@ -30,7 +30,7 @@ function NewTemplateMenu() { collections.orderedData.map((collection) => { const canCollection = policies.abilities(collection.id); return createInternalLinkAction({ - name: collection.name, + name: collection.displayName, section: DocumentSection, icon: <CollectionIcon collection={collection} />, visible: !!canCollection.createTemplate, diff --git a/app/menus/TableOfContentsMenu.tsx b/app/menus/TableOfContentsMenu.tsx index 74cee2f55a..e400eba13c 100644 --- a/app/menus/TableOfContentsMenu.tsx +++ b/app/menus/TableOfContentsMenu.tsx @@ -98,7 +98,11 @@ function TableOfContentsMenu() { const rootAction = useMenuAction(actions); return ( - <DropdownMenu action={rootAction} ariaLabel={t("Table of contents")}> + <DropdownMenu + action={rootAction} + align="end" + ariaLabel={t("Table of contents")} + > <Button icon={<TableOfContentsIcon />} aria-label={t("Table of contents")} diff --git a/app/menus/TemplatesMenu.tsx b/app/menus/TemplatesMenu.tsx index 1e7680b886..fe019792d0 100644 --- a/app/menus/TemplatesMenu.tsx +++ b/app/menus/TemplatesMenu.tsx @@ -1,8 +1,11 @@ import { observer } from "mobx-react"; import { ShapesIcon } from "outline-icons"; +import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import type Document from "~/models/Document"; import type Template from "~/models/Template"; +import { ActionSeparator } from "~/actions"; +import { manageTemplates } from "~/actions/definitions/templates"; import Button from "~/components/Button"; import { DropdownMenu } from "~/components/Menu/DropdownMenu"; import { useMenuAction } from "~/hooks/useMenuAction"; @@ -23,7 +26,11 @@ function TemplatesMenu({ isCompact, onSelectTemplate, document }: Props) { onSelectTemplate, documentId: document.id, }); - const rootAction = useMenuAction(allActions); + const actions = useMemo( + () => [...allActions, ActionSeparator, manageTemplates], + [allActions] + ); + const rootAction = useMenuAction(actions); if (!allActions.length) { return null; diff --git a/app/models/Collection.test.ts b/app/models/Collection.test.ts index 6397b90444..6ef23460fc 100644 --- a/app/models/Collection.test.ts +++ b/app/models/Collection.test.ts @@ -1,12 +1,42 @@ -/* oxlint-disable */ import stores from "~/stores"; describe("Collection model", () => { - test("should initialize with data", () => { + it("should initialize with data", () => { const collection = stores.collections.add({ id: "123", name: "Engineering", }); expect(collection.name).toBe("Engineering"); }); + + it("should show the translated name for a personal collection", () => { + const collection = stores.collections.add({ + id: "456", + name: "Renamed", + ownerId: "user-id", + }); + expect(collection.displayName).toBe("Personal"); + + const shared = stores.collections.add({ id: "789", name: "Design" }); + expect(shared.displayName).toBe("Design"); + }); + + it("should not add a document that is already in the collection", () => { + const collection = stores.collections.add({ + id: "abc", + name: "Personal", + sort: { field: "title", direction: "asc" }, + documents: [], + }); + const document = stores.documents.add({ + id: "doc-1", + title: "Doc", + path: "/doc/doc-1", + collectionId: collection.id, + }); + + collection.addDocument(document); + collection.addDocument(document); + expect(collection.documents?.map((node) => node.id)).toEqual(["doc-1"]); + }); }); diff --git a/app/models/Collection.ts b/app/models/Collection.ts index 228cac21ff..837ed8ff74 100644 --- a/app/models/Collection.ts +++ b/app/models/Collection.ts @@ -1,3 +1,4 @@ +import i18n from "i18next"; import invariant from "invariant"; import { action, @@ -17,6 +18,7 @@ import { import { sortNavigationNodes } from "@shared/utils/collections"; import type CollectionsStore from "~/stores/CollectionsStore"; import type Document from "~/models/Document"; +import { CoalescedFetch } from "~/models/base/CoalescedFetch"; import ParanoidModel from "~/models/base/ParanoidModel"; import { client } from "~/utils/ApiClient"; import type User from "./User"; @@ -60,6 +62,10 @@ export default class Collection extends ParanoidModel { @Field @observable permission?: CollectionPermission = undefined; + + /** The user that owns this collection, if it is a personal collection. */ + @observable + ownerId: string | null; /** * Whether public sharing is enabled for the collection. Note this can also be disabled at the * workspace level. @@ -116,7 +122,18 @@ export default class Collection extends ParanoidModel { archivedBy?: User = undefined; @computed get searchContent(): string { - return this.name; + return this.displayName; + } + + /** + * The name to show for the collection. A personal collection is always shown + * with a translated name, whatever name is stored. + * + * @returns the name to display. + */ + @computed + get displayName(): string { + return this.isPersonal ? i18n.t("Personal") : this.name; } /** Returns whether the collection is empty, or undefined if not loaded. */ @@ -143,6 +160,15 @@ export default class Collection extends ParanoidModel { return this.permission === null; } + /** + * Whether this collection is the personal collection of a user. + * + * @returns boolean + */ + get isPersonal(): boolean { + return !!this.ownerId; + } + @computed get isStarred(): boolean { return !!this.store.rootStore.stars.orderedData.find( @@ -199,7 +225,7 @@ export default class Collection extends ParanoidModel { /** The initial letter of the collection name as a string. */ @computed get initial() { - return (this.name?.charAt(0) ?? "?").toUpperCase(); + return (this.displayName?.charAt(0) ?? "?").toUpperCase(); } @computed @@ -241,15 +267,11 @@ export default class Collection extends ParanoidModel { } fetchDocuments = async (options?: { force: boolean }) => { - if (this.isFetching) { - return; - } if (this.documents && options?.force !== true) { return; } - try { - this.isFetching = true; + await this.documentsFetch.run(async () => { const res = await client.post("/collections.documents", { id: this.id, }); @@ -258,9 +280,7 @@ export default class Collection extends ParanoidModel { runInAction(() => { this.documents = res.data; }); - } finally { - this.isFetching = false; - } + }, options?.force); }; /** @@ -271,7 +291,7 @@ export default class Collection extends ParanoidModel { */ @action updateDocument( - document: Pick<Document, "id" | "title" | "url" | "color" | "icon"> + document: Pick<Document, "id" | "title" | "path" | "color" | "icon"> ) { if (!this.documents) { return; @@ -283,7 +303,7 @@ export default class Collection extends ParanoidModel { node.color = document.color ?? undefined; node.icon = document.icon ?? undefined; node.title = document.title; - node.url = document.url; + node.url = document.path; } else { travelNodes(node.children); } @@ -319,14 +339,15 @@ export default class Collection extends ParanoidModel { /** * Adds the document identified by the given id to the collection in - * memory. Does not add the document to the database or store. + * memory, if it is not already present. Does not add the document to the + * database or store. * * @param document The document to add. * @param parentDocumentId The id of the document to add the new document to. */ @action addDocument(document: Document, parentDocumentId?: string) { - if (!this.documents) { + if (!this.documents || this.childrenByDocumentId.has(document.id)) { return; } @@ -468,5 +489,5 @@ export default class Collection extends ParanoidModel { } } - private isFetching = false; + private documentsFetch = new CoalescedFetch(); } diff --git a/app/models/Document.ts b/app/models/Document.ts index d54040e3e8..4a9235da4c 100644 --- a/app/models/Document.ts +++ b/app/models/Document.ts @@ -24,9 +24,9 @@ import { NotificationEventType, } from "@shared/types"; import { DocumentPreferenceDefaults } from "@shared/constants"; +import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper"; import Storage from "@shared/utils/Storage"; import { isRTL } from "@shared/utils/rtl"; -import slugify from "@shared/utils/slugify"; import type DocumentsStore from "~/stores/DocumentsStore"; import User from "~/models/User"; import type { Properties } from "~/types"; @@ -41,7 +41,6 @@ import type { Searchable } from "./interfaces/Searchable"; type SaveOptions = JSONObject & { publish?: boolean; - done?: boolean; autosave?: boolean; }; @@ -135,6 +134,12 @@ export default class Document extends ArchivableModel implements Searchable { @Relation(() => Collection, { onDelete: "cascade" }) collection?: Collection; + /** + * The owner of the personal collection that this document is in, if any. + */ + @observable + ownerId?: string | null; + /** * The title of the document. */ @@ -240,11 +245,9 @@ export default class Document extends ArchivableModel implements Searchable { @observable popularityScore: number; - /** - * @deprecated Use path instead - */ + /** The path to the document. The server makes the slug from the title. */ @observable - url: string; + path: string; @observable urlId: string; @@ -312,18 +315,6 @@ export default class Document extends ArchivableModel implements Searchable { return (this.title?.charAt(0) ?? "?").toUpperCase(); } - @computed - get path(): string { - const prefix = "/doc"; - - if (!this.title) { - return `${prefix}/untitled-${this.urlId}`; - } - - const slugifiedTitle = slugify(this.title); - return `${prefix}/${slugifiedTitle}-${this.urlId}`; - } - @computed get noun(): string { return t("document"); @@ -381,7 +372,7 @@ export default class Document extends ArchivableModel implements Searchable { return !!( auth.team?.sharing !== false && this.collection?.sharing !== false && - (share?.published || (sharedParent?.published && !this.isDraft)) + (share?.isActive || (sharedParent && !this.isDraft)) ); } @@ -430,6 +421,15 @@ export default class Document extends ArchivableModel implements Searchable { return !this.publishedAt; } + /** + * Whether the document has no content. Returns false if the content is not + * loaded. + */ + @computed + get isEmpty(): boolean { + return !!this.data && ProsemirrorDataHelper.isEmpty(this.data); + } + get hasEmptyTitle(): boolean { return this.title === ""; } @@ -499,7 +499,7 @@ export default class Document extends ArchivableModel implements Searchable { return path.map((item) => item.asNavigationNode); } - get titleWithDefault(): string { + get displayTitle(): string { return this.title || i18n.t("Untitled"); } @@ -726,7 +726,7 @@ export default class Document extends ArchivableModel implements Searchable { color: this.color ?? undefined, icon: this.icon ?? undefined, children: this.childDocuments.map((doc) => doc.asNavigationNode), - url: this.url, + url: this.path, isDraft: this.isDraft, }; } diff --git a/app/models/Group.ts b/app/models/Group.ts index e496025da2..08151c5be3 100644 --- a/app/models/Group.ts +++ b/app/models/Group.ts @@ -1,6 +1,7 @@ import { computed, observable } from "mobx"; import type GroupMembership from "./GroupMembership"; import Model from "./base/Model"; +import NavigableModel from "./base/NavigableModel"; import Field from "./decorators/Field"; import { GroupPermission } from "@shared/types"; import type { Searchable } from "./interfaces/Searchable"; @@ -37,6 +38,16 @@ class Group extends Model implements Searchable { @observable description: string; + /** An icon (or) emoji to use as the group icon. */ + @Field + @observable + icon: string | null; + + /** The color of the group icon. */ + @Field + @observable + color: string | null; + @observable externalId: string | undefined = undefined; @@ -50,6 +61,14 @@ class Group extends Model implements Searchable { @observable externalGroup: ExternalGroupInfo | undefined = undefined; + /** + * The initial letter of the group name. + */ + @computed + get initial(): string { + return (this.name ?? "").charAt(0).toUpperCase(); + } + /** * Whether this group's membership is managed by an external authentication provider. */ @@ -92,6 +111,7 @@ class Group extends Model implements Searchable { /** * Returns the direct memberships that this group has to documents. Documents that the current * user already has access to through a collection, archived, and trashed documents are not included. + * Documents nested under another shared document in the list are also not included. * * @returns A list of group memberships */ @@ -100,7 +120,7 @@ class Group extends Model implements Searchable { const { groupMemberships, groupUsers, documents, policies, auth } = this.store.rootStore; - return groupMemberships.orderedData + const memberships = groupMemberships.orderedData .filter((groupMembership) => groupUsers.orderedData.some( (groupUser) => @@ -118,6 +138,8 @@ class Group extends Model implements Searchable { : undefined; return !policy?.abilities?.readDocument && !!document?.isActive; }); + + return NavigableModel.filterRoots(memberships, documents); } } diff --git a/app/models/GroupUser.ts b/app/models/GroupUser.ts index 43fc93589b..12f0a9bfa8 100644 --- a/app/models/GroupUser.ts +++ b/app/models/GroupUser.ts @@ -31,6 +31,13 @@ class GroupUser extends Model { @Relation(() => Group, { onDelete: "cascade" }) group: Group; + /** The ID of the user that added the user to the group. */ + createdById: string; + + /** The user that added the user to the group. */ + @Relation(() => User, { onDelete: "null" }) + createdBy?: User; + /** The permission of the user in the group. */ @Field @observable diff --git a/app/models/Import.ts b/app/models/Import.ts index 3a62283ba4..26d100466a 100644 --- a/app/models/Import.ts +++ b/app/models/Import.ts @@ -35,6 +35,12 @@ class Import extends Model { @observable documentCount: number; + /** The existing collection to import into, if any. */ + collectionId: string | null; + + /** The existing document to import under, if any. */ + documentId: string | null; + /** The user who created the import. */ @Relation(() => User, {}) createdBy: User; diff --git a/app/models/Notification.ts b/app/models/Notification.ts index c7524934e8..e925f3193d 100644 --- a/app/models/Notification.ts +++ b/app/models/Notification.ts @@ -11,6 +11,7 @@ import { import Collection from "./Collection"; import Comment from "./Comment"; import Document from "./Document"; +import Group from "./Group"; import User from "./User"; import Model from "./base/Model"; import Field from "./decorators/Field"; @@ -64,6 +65,8 @@ class Notification extends Model { NotificationEventType.Onboarding, NotificationEventType.Features, NotificationEventType.ExportCompleted, + NotificationEventType.AddUserToGroup, + NotificationEventType.RemoveUserFromGroup, ], }; @@ -121,6 +124,17 @@ class Notification extends Model { @Relation(() => Collection, { onDelete: "cascade" }) collection?: Collection; + /** + * The group ID that the notification is associated with. + */ + groupId?: string; + + /** + * The group that the notification is associated with. + */ + @Relation(() => Group, { onDelete: "cascade" }) + group?: Group; + commentId?: string; /** @@ -213,6 +227,10 @@ class Notification extends Model { return t("shared"); case NotificationEventType.AddUserToCollection: return t("invited you to"); + case NotificationEventType.AddUserToGroup: + return t("added you to the group"); + case NotificationEventType.RemoveUserFromGroup: + return t("removed you from the group"); case NotificationEventType.RequestDocumentAccess: if (this.accessRequestStatus === "approved") { return t("was granted access to"); @@ -227,19 +245,23 @@ class Notification extends Model { } /** - * Returns the subject of the notification. This is the title of the associated - * document. + * Returns translated text for the subject of the notification. This is the + * name of the associated document, collection, or group. * - * @returns The subject + * @param t - The translation function. + * @returns The subject. */ - get subject() { + subject(t: TFunction): string { if (this.documentId) { - return this.document?.title ?? "a document"; + return this.document?.title ?? t("a document"); } if (this.collectionId) { - return this.collection?.name ?? "a collection"; + return this.collection?.displayName ?? t("a collection"); } - return "Unknown"; + if (this.groupId) { + return this.group?.name ?? t("a group"); + } + return t("Unknown"); } /** @@ -288,6 +310,12 @@ class Notification extends Model { case NotificationEventType.ExportCompleted: { return settingsPath("export"); } + case NotificationEventType.AddUserToGroup: + case NotificationEventType.RemoveUserFromGroup: { + return this.groupId + ? settingsPath("groups", this.groupId, "members") + : ""; + } default: this.event satisfies never; return; diff --git a/app/models/Share.ts b/app/models/Share.ts index 76fe11d8a3..94c4bd585b 100644 --- a/app/models/Share.ts +++ b/app/models/Share.ts @@ -1,3 +1,4 @@ +import { isPast } from "date-fns"; import { computed, observable } from "mobx"; import type { NavigationNode, PublicTeam } from "@shared/types"; import type SharesStore from "~/stores/SharesStore"; @@ -19,6 +20,7 @@ class Share extends Model implements Searchable { store: SharesStore; + /** Whether the share is published. This ignores expiry, prefer `isActive` to check if the link works. */ @Field @observable published: boolean; @@ -97,6 +99,11 @@ class Share extends Model implements Searchable { @observable iconUrl: string | null; + /** The time after which the public link stops working, if any. */ + @Field + @observable + expiresAt: string | null; + @observable views: number; @@ -104,6 +111,16 @@ class Share extends Model implements Searchable { @Relation(() => User, { onDelete: "null" }) createdBy: User; + /** Whether the expiry date has passed, not computed as time is not observable. */ + get isExpired(): boolean { + return this.expiresAt ? isPast(new Date(this.expiresAt)) : false; + } + + /** Whether the share is published and its public link still works. */ + get isActive(): boolean { + return this.published && !this.isExpired; + } + @computed get sourcePathWithFallback(): string { return this.sourcePath ?? this.documentUrl; diff --git a/app/models/Template.ts b/app/models/Template.ts index 1705e716a6..d7adc0260d 100644 --- a/app/models/Template.ts +++ b/app/models/Template.ts @@ -4,10 +4,8 @@ import { computed, observable, override } from "mobx"; import type { ProsemirrorData } from "@shared/types"; import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper"; import { isRTL } from "@shared/utils/rtl"; -import slugify from "@shared/utils/slugify"; import type TemplatesStore from "~/stores/TemplatesStore"; import User from "~/models/User"; -import { settingsPath } from "~/utils/routeHelpers"; import Collection from "./Collection"; import ParanoidModel from "./base/ParanoidModel"; import Field from "./decorators/Field"; @@ -89,6 +87,10 @@ export default class Template extends ParanoidModel implements Searchable { @Relation(() => User) updatedBy: User | undefined; + /** The path to the template. The server makes the slug from the title. */ + @observable + path: string; + @observable urlId: string; @@ -132,16 +134,6 @@ export default class Template extends ParanoidModel implements Searchable { return isRTL(this.title); } - @computed - get path(): string { - if (!this.title) { - return `${settingsPath("templates")}/untitled-${this.urlId}`; - } - - const slugifiedTitle = slugify(this.title); - return `${settingsPath("templates")}/${slugifiedTitle}-${this.urlId}`; - } - @override get isDeleted(): boolean { return !!this.deletedAt; @@ -185,13 +177,13 @@ export default class Template extends ParanoidModel implements Searchable { return addDays(new Date(this.deletedAt), 30).toString(); } - get titleWithDefault(): string { + get displayTitle(): string { return this.title || i18n.t("Untitled"); } @computed get initial(): string { - return (this.titleWithDefault?.charAt(0) ?? "?").toUpperCase(); + return (this.displayTitle?.charAt(0) ?? "?").toUpperCase(); } @computed diff --git a/app/models/User.test.ts b/app/models/User.test.ts index d3ac40e297..9800ecafc8 100644 --- a/app/models/User.test.ts +++ b/app/models/User.test.ts @@ -5,7 +5,7 @@ describe("User model", () => { const users = stores.users; describe("initial", () => { - test("should return first character of name uppercased", () => { + it("should return first character of name uppercased", () => { const user = new User( { id: "123", @@ -16,7 +16,7 @@ describe("User model", () => { expect(user.initial).toBe("A"); }); - test("should return first character when name is already uppercase", () => { + it("should return first character when name is already uppercase", () => { const user = new User( { id: "124", @@ -27,7 +27,7 @@ describe("User model", () => { expect(user.initial).toBe("B"); }); - test("should return ? when name is empty", () => { + it("should return ? when name is empty", () => { const user = new User( { id: "125", @@ -38,7 +38,7 @@ describe("User model", () => { expect(user.initial).toBe("?"); }); - test("should return ? when name is null", () => { + it("should return ? when name is null", () => { const user = new User( { id: "126", @@ -49,7 +49,7 @@ describe("User model", () => { expect(user.initial).toBe("?"); }); - test("should return ? when name is undefined", () => { + it("should return ? when name is undefined", () => { const user = new User( { id: "127", @@ -62,7 +62,7 @@ describe("User model", () => { }); describe("initials", () => { - test("should return empty string when name is empty", () => { + it("should return empty string when name is empty", () => { const user = new User( { id: "201", @@ -73,7 +73,7 @@ describe("User model", () => { expect(user.initials).toBe(""); }); - test("should return empty string when name is null", () => { + it("should return empty string when name is null", () => { const user = new User( { id: "202", @@ -84,7 +84,7 @@ describe("User model", () => { expect(user.initials).toBe(""); }); - test("should return single character uppercased for single word name", () => { + it("should return single character uppercased for single word name", () => { const user = new User( { id: "203", @@ -95,7 +95,7 @@ describe("User model", () => { expect(user.initials).toBe("A"); }); - test("should return single character uppercased for single word name already uppercase", () => { + it("should return single character uppercased for single word name already uppercase", () => { const user = new User( { id: "204", @@ -106,7 +106,7 @@ describe("User model", () => { expect(user.initials).toBe("B"); }); - test("should return first and last initials for two word name", () => { + it("should return first and last initials for two word name", () => { const user = new User( { id: "205", @@ -117,7 +117,7 @@ describe("User model", () => { expect(user.initials).toBe("AS"); }); - test("should return first and last initials for three word name", () => { + it("should return first and last initials for three word name", () => { const user = new User( { id: "206", @@ -128,7 +128,7 @@ describe("User model", () => { expect(user.initials).toBe("AS"); }); - test("should return first and last initials for many word name", () => { + it("should return first and last initials for many word name", () => { const user = new User( { id: "207", @@ -139,7 +139,7 @@ describe("User model", () => { expect(user.initials).toBe("AS"); }); - test("should handle names with extra spaces", () => { + it("should handle names with extra spaces", () => { const user = new User( { id: "208", @@ -150,7 +150,7 @@ describe("User model", () => { expect(user.initials).toBe("AS"); }); - test("should handle names with mixed case", () => { + it("should handle names with mixed case", () => { const user = new User( { id: "209", @@ -161,7 +161,7 @@ describe("User model", () => { expect(user.initials).toBe("AS"); }); - test("should handle names with special characters", () => { + it("should handle names with special characters", () => { const user = new User( { id: "210", @@ -172,7 +172,7 @@ describe("User model", () => { expect(user.initials).toBe("JO"); }); - test("should handle single letter names", () => { + it("should handle single letter names", () => { const user = new User( { id: "211", @@ -183,7 +183,7 @@ describe("User model", () => { expect(user.initials).toBe("X"); }); - test("should handle names with unicode characters", () => { + it("should handle names with unicode characters", () => { const user = new User( { id: "212", @@ -194,4 +194,76 @@ describe("User model", () => { expect(user.initials).toBe("JG"); }); }); + + describe("documentMemberships", () => { + const user = new User({ id: "300", name: "Member" }, users); + + beforeEach(() => { + stores.documents.clear(); + stores.userMemberships.clear(); + }); + + const addDocument = (id: string, parentDocumentId?: string) => + stores.documents.add({ + id, + title: id, + parentDocumentId, + collectionId: "collection", + }); + + const addMembership = (id: string, documentId: string) => + stores.userMemberships.add({ + id, + userId: user.id, + documentId, + sourceId: null, + index: id, + }); + + it("should only include the highest shared document of a tree", () => { + addDocument("parent"); + addDocument("child", "parent"); + addDocument("grandchild", "child"); + addMembership("m1", "grandchild"); + addMembership("m2", "child"); + addMembership("m3", "parent"); + + expect(user.documentMemberships.map((m) => m.documentId)).toEqual([ + "parent", + ]); + }); + + it("should include a moved document that is still in a cached tree", () => { + addDocument("parent"); + addDocument("child"); + addMembership("m1", "child"); + const parent = addMembership("m2", "parent"); + parent.node = { + id: "parent", + title: "parent", + url: "/doc/parent", + children: [ + { id: "child", title: "child", url: "/doc/child", children: [] }, + ], + }; + + expect(user.documentMemberships.map((m) => m.documentId)).toEqual([ + "child", + "parent", + ]); + }); + + it("should include a document whose parent is not shared", () => { + addDocument("parent"); + addDocument("child", "parent"); + addDocument("other"); + addMembership("m1", "child"); + addMembership("m2", "other"); + + expect(user.documentMemberships.map((m) => m.documentId)).toEqual([ + "child", + "other", + ]); + }); + }); }); diff --git a/app/models/User.ts b/app/models/User.ts index acd9e00130..fbff30f53a 100644 --- a/app/models/User.ts +++ b/app/models/User.ts @@ -17,6 +17,7 @@ import { client } from "~/utils/ApiClient"; import type Document from "./Document"; import type Group from "./Group"; import type UserMembership from "./UserMembership"; +import NavigableModel from "./base/NavigableModel"; import ParanoidModel from "./base/ParanoidModel"; import Field from "./decorators/Field"; import Relation from "./decorators/Relation"; @@ -211,13 +212,14 @@ class User extends ParanoidModel implements Searchable { /** * Returns the direct memberships that this user has to documents. Documents that the * user already has access to through a collection, archived, and trashed documents are not included. + * Documents nested under another shared document in the list are also not included. * * @returns A list of user memberships */ @computed get documentMemberships(): UserMembership[] { const { userMemberships, documents, policies } = this.store.rootStore; - return userMemberships.orderedData + const memberships = userMemberships.orderedData .filter( (m) => m.userId === this.id && m.sourceId === null && m.documentId ) @@ -228,6 +230,8 @@ class User extends ParanoidModel implements Searchable { : undefined; return !policy?.abilities?.readDocument && !!document?.isActive; }); + + return NavigableModel.filterRoots(memberships, documents); } @computed diff --git a/app/models/UserMembership.ts b/app/models/UserMembership.ts index eab66c31d9..d43a2bbf32 100644 --- a/app/models/UserMembership.ts +++ b/app/models/UserMembership.ts @@ -29,7 +29,7 @@ class UserMembership extends NavigableModel { document?: Document; /** The source ID points to the root membership from which this inherits */ - sourceId?: string; + sourceId?: string | null; /** The source points to the root membership from which this inherits */ @Relation(() => UserMembership, { onDelete: "cascade" }) diff --git a/app/models/base/CoalescedFetch.test.ts b/app/models/base/CoalescedFetch.test.ts new file mode 100644 index 0000000000..8773c82219 --- /dev/null +++ b/app/models/base/CoalescedFetch.test.ts @@ -0,0 +1,110 @@ +import { CoalescedFetch, KeyedCoalescedFetch } from "./CoalescedFetch"; + +function deferred() { + let resolve = () => {}; + let reject = (_err: Error) => {}; + const promise = new Promise<void>((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +describe("CoalescedFetch", () => { + it("should share an in-flight request with unforced calls", async () => { + const queue = new CoalescedFetch(); + const request = deferred(); + const fetch = vi.fn(() => request.promise); + + const first = queue.run(fetch); + const second = queue.run(fetch); + request.resolve(); + await Promise.all([first, second]); + + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it("should run one more request after an in-flight request when forced", async () => { + const queue = new CoalescedFetch(); + const requests = [deferred(), deferred()]; + let calls = 0; + const fetch = vi.fn(() => requests[calls++].promise); + + const first = queue.run(fetch); + const forced = queue.run(fetch, true); + const forcedAgain = queue.run(fetch, true); + expect(fetch).toHaveBeenCalledTimes(1); + + requests[0].resolve(); + await first; + await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2)); + + let settled = false; + void forced.then(() => { + settled = true; + }); + await Promise.resolve(); + expect(settled).toBe(false); + + requests[1].resolve(); + await Promise.all([forced, forcedAgain]); + expect(fetch).toHaveBeenCalledTimes(2); + }); + + it("should run the forced request when the in-flight request fails", async () => { + const queue = new CoalescedFetch(); + const failed = deferred(); + const fetch = vi + .fn<() => Promise<void>>() + .mockReturnValueOnce(failed.promise) + .mockResolvedValueOnce(undefined); + + const first = queue.run(fetch); + const forced = queue.run(fetch, true); + failed.reject(new Error("Network error")); + + await expect(first).rejects.toThrow("Network error"); + await expect(forced).resolves.toBeUndefined(); + expect(fetch).toHaveBeenCalledTimes(2); + }); + + it("should start a new request after the previous one completes", async () => { + const queue = new CoalescedFetch(); + const fetch = vi.fn(() => Promise.resolve()); + + await queue.run(fetch); + await queue.run(fetch); + + expect(fetch).toHaveBeenCalledTimes(2); + }); +}); + +describe("KeyedCoalescedFetch", () => { + it("should share requests for the same key only", async () => { + const fetches = new KeyedCoalescedFetch<string>(); + const fetch = vi.fn((value: string) => Promise.resolve(value)); + + const results = await Promise.all([ + fetches.run("a", () => fetch("a1")), + fetches.run("a", () => fetch("a2")), + fetches.run("b", () => fetch("b1")), + ]); + + expect(results).toEqual(["a1", "a1", "b1"]); + expect(fetch).toHaveBeenCalledTimes(2); + }); + + it("should return the result of the follow-up request to a forced call", async () => { + const fetches = new KeyedCoalescedFetch<number>(); + let calls = 0; + const fetch = () => Promise.resolve(++calls); + + const results = await Promise.all([ + fetches.run("a", fetch), + fetches.run("a", fetch, true), + ]); + + expect(results).toEqual([1, 2]); + expect(await fetches.run("a", fetch)).toBe(3); + }); +}); diff --git a/app/models/base/CoalescedFetch.ts b/app/models/base/CoalescedFetch.ts new file mode 100644 index 0000000000..16f983ed54 --- /dev/null +++ b/app/models/base/CoalescedFetch.ts @@ -0,0 +1,76 @@ +/** + * Runs an async fetch so that concurrent calls share one request. A forced + * call made while a request is in flight runs one more request after it, so + * the result is never older than the forced call. + */ +export class CoalescedFetch<T = void> { + /** Whether no request is in flight or queued. */ + get isIdle(): boolean { + return !this.current && !this.next; + } + + /** + * Runs the fetch, or joins the request that is in flight. + * + * @param fetch the function that performs the request. + * @param force whether the result must start after this call. + * @returns a promise that resolves with the result of the request. + */ + run(fetch: () => Promise<T>, force = false): Promise<T> { + if (!this.current) { + this.current = fetch().finally(() => { + this.current = undefined; + }); + return this.current; + } + + if (!force) { + return this.current; + } + + this.next ??= this.current + .catch(() => undefined) + .then(() => { + this.next = undefined; + return this.run(fetch, true); + }); + return this.next; + } + + private current?: Promise<T>; + private next?: Promise<T>; +} + +/** + * Runs a separate {@link CoalescedFetch} for each key, and discards it when + * its requests are complete. + */ +export class KeyedCoalescedFetch<T> { + /** + * Runs the fetch for the key, or joins the request for the key that is in + * flight. + * + * @param key the key that identifies the resource. + * @param fetch the function that performs the request. + * @param force whether the result must start after this call. + * @returns a promise that resolves with the result of the request. + */ + run(key: string, fetch: () => Promise<T>, force = false): Promise<T> { + let entry = this.entries.get(key); + if (!entry) { + entry = new CoalescedFetch<T>(); + this.entries.set(key, entry); + } + + const promise = entry.run(fetch, force); + const cleanup = () => { + if (entry.isIdle && this.entries.get(key) === entry) { + this.entries.delete(key); + } + }; + void promise.then(cleanup, cleanup); + return promise; + } + + private entries = new Map<string, CoalescedFetch<T>>(); +} diff --git a/app/models/base/Model.test.ts b/app/models/base/Model.test.ts index 1b9b72e66e..3c8478331b 100644 --- a/app/models/base/Model.test.ts +++ b/app/models/base/Model.test.ts @@ -1,4 +1,3 @@ -/* oxlint-disable */ import { autorun, isAction, isObservableProp } from "mobx"; import stores from "~/stores"; diff --git a/app/models/base/Model.ts b/app/models/base/Model.ts index 0f0c5dbdc7..d5201203a8 100644 --- a/app/models/base/Model.ts +++ b/app/models/base/Model.ts @@ -128,42 +128,34 @@ export default abstract class Model { this: Model, options: { withoutPolicies?: boolean } = {} ): Promise<unknown> { - // this is to ensure that multiple loads don’t happen in parallel - if (this.loadingRelations) { - return this.loadingRelations; - } + return this.store.relationFetches.run(this.id, () => { + const promises = []; - const promises = []; + const relations = getRelationsForModelClass( + this.constructor as typeof Model + ); - const relations = getRelationsForModelClass( - this.constructor as typeof Model - ); - - if (relations) { - for (const properties of relations.values()) { - const store = this.store.rootStore.getStoreForModelName( - properties.relationClassResolver().modelName - ); - if ("canFetchById" in store && store.canFetchById) { - const id = this[properties.idKey]; - if (id) { - promises.push(store.fetch(id as string)); + if (relations) { + for (const properties of relations.values()) { + const store = this.store.rootStore.getStoreForModelName( + properties.relationClassResolver().modelName + ); + if ("canFetchById" in store && store.canFetchById) { + const id = this[properties.idKey]; + if (id) { + promises.push(store.fetch(id as string)); + } } } } - } - const policy = this.store.rootStore.policies.get(this.id); - if (!policy && !options.withoutPolicies && this.store.canFetchById) { - promises.push(this.store.fetch(this.id, { force: true })); - } + const policy = this.store.rootStore.policies.get(this.id); + if (!policy && !options.withoutPolicies && this.store.canFetchById) { + promises.push(this.store.fetch(this.id, { force: true })); + } - try { - this.loadingRelations = Promise.all(promises); - return await this.loadingRelations; - } finally { - this.loadingRelations = undefined; - } + return Promise.all(promises); + }); } /** @@ -232,15 +224,13 @@ export default abstract class Model { if (key === "initialized") { continue; } - // @ts-expect-error TODO - if (isEqual(toJS(this[key]), data[key])) { + if (isEqual(toJS(Reflect.get(this, key)), data[key])) { continue; } // A field declared without a default does not exist until it is first // assigned, so MobX could not annotate it when the model was created. addedKeys ||= !(key in this); - // @ts-expect-error TODO - this[key] = data[key]; + Reflect.set(this, key, data[key]); } catch (error) { Logger.warn(`Error setting ${key} on model`, { error }); } @@ -350,9 +340,6 @@ export default abstract class Model { protected persistedAttributes: Partial<Model> = {}; - /** A promise that resolves when all relations have been loaded. */ - private loadingRelations: Promise<unknown[]> | undefined; - /** A boolean representing if the constructor has been called. */ private initialized = false; } diff --git a/app/models/base/NavigableModel.ts b/app/models/base/NavigableModel.ts index 6edd3b4af9..34c7068643 100644 --- a/app/models/base/NavigableModel.ts +++ b/app/models/base/NavigableModel.ts @@ -1,11 +1,66 @@ import { action, computed, observable, runInAction } from "mobx"; import type { JSONObject, NavigationNode } from "@shared/types"; import { client } from "~/utils/ApiClient"; +import { CoalescedFetch } from "./CoalescedFetch"; import Model from "./Model"; import type Document from "../Document"; +import type DocumentsStore from "~/stores/DocumentsStore"; export default abstract class NavigableModel extends Model { - private isFetching = false; + /** + * Filters memberships to those whose document is not nested under the + * document of another membership in the list, so that each shared tree is + * shown once from its highest shared document. + * + * @param memberships the memberships to filter. + * @param documents the documents store used to find parent documents. + * @returns the memberships that are roots of a shared tree. + */ + static filterRoots<T extends NavigableModel>( + memberships: T[], + documents: DocumentsStore + ): T[] { + if (memberships.length < 2) { + return memberships; + } + + const rootIds = new Set(memberships.map((m) => m.documentId)); + + return memberships.filter((membership) => { + const { documentId } = membership; + if (!documentId) { + return true; + } + + const visited = new Set([documentId]); + let document = documents.get(documentId); + while (document?.parentDocumentId) { + const { parentDocumentId } = document; + if (rootIds.has(parentDocumentId)) { + return false; + } + if (visited.has(parentDocumentId)) { + return true; + } + visited.add(parentDocumentId); + document = documents.get(parentDocumentId); + } + + // The parent chain is complete, so the loaded trees are not needed. + if (document) { + return true; + } + + // Parent documents may not be loaded, so also check the loaded trees. + return !memberships.some( + (other) => + other.documentId !== documentId && + other.childrenByDocumentId.has(documentId) + ); + }); + } + + private documentsFetch = new CoalescedFetch(); /** The document ID associated with this model. */ documentId?: string; @@ -20,24 +75,17 @@ export default abstract class NavigableModel extends Model { params: JSONObject; force?: boolean; }) { - if (this.isFetching) { - return; - } - if (this.documents && options.force !== true) { return; } - try { - this.isFetching = true; + await this.documentsFetch.run(async () => { const res = await client.post(options.path, options.params); runInAction(() => { this.node = res.data; }); - } finally { - this.isFetching = false; - } + }, options.force); } /** @@ -128,14 +176,15 @@ export default abstract class NavigableModel extends Model { /** * Adds the document identified by the given id to the model in - * memory. Does not add the document to the database or store. + * memory, if it is not already present. Does not add the document to the + * database or store. * * @param document The document to add. * @param parentDocumentId The id of the document to add the new document to. */ @action addDocument(document: Document, parentDocumentId: string) { - if (!this.documents || !document || !parentDocumentId?.trim()) { + if (!this.documents || this.childrenByDocumentId.has(document.id)) { return; } diff --git a/app/models/decorators/Field.test.ts b/app/models/decorators/Field.test.ts new file mode 100644 index 0000000000..d7abe58db9 --- /dev/null +++ b/app/models/decorators/Field.test.ts @@ -0,0 +1,24 @@ +import type Model from "../base/Model"; +import Field, { getFieldsForModelClass } from "./Field"; + +describe("Field", () => { + it("records fields on the decorated class", () => { + class Example {} + Field(Example.prototype as Model, "name"); + Field(Example.prototype as Model, "color"); + + expect(getFieldsForModelClass(Example)).toEqual(["name", "color"]); + }); + + it("does not leak fields between classes that share a name", () => { + // Minified builds can mangle two unrelated classes to the same name. + const One = class Model {}; + const Two = class Model {}; + + Field(One.prototype as Model, "name"); + Field(Two.prototype as Model, "index"); + + expect(getFieldsForModelClass(One)).toEqual(["name"]); + expect(getFieldsForModelClass(Two)).toEqual(["index"]); + }); +}); diff --git a/app/models/decorators/Field.ts b/app/models/decorators/Field.ts index 351aa53ddf..84e083e055 100644 --- a/app/models/decorators/Field.ts +++ b/app/models/decorators/Field.ts @@ -1,6 +1,10 @@ import type Model from "../base/Model"; -const fields = new Map<string, (string | number | symbol)[]>(); +type ModelClass = Function; + +// Keyed by the class itself – minified builds mangle class names and two +// classes in separate chunks can end up sharing one. +const fields = new WeakMap<ModelClass, (string | number | symbol)[]>(); /** * Returns the keys recorded as serializable fields on a model. @@ -17,8 +21,8 @@ export const getFieldsForModel = <T extends Model>(target: T) => * @param model the model class to inspect. * @returns the keys decorated with @Field. */ -export function getFieldsForModelClass(model: { name: string }) { - return fields.get(model.name) ?? []; +export function getFieldsForModelClass(model: ModelClass) { + return fields.get(model) ?? []; } /** @@ -29,8 +33,8 @@ export function getFieldsForModelClass(model: { name: string }) { * @param propertyKey the key to record as a field. */ const Field = (target: Model, propertyKey: string | symbol) => { - const className = target.constructor.name; - fields.set(className, [...(fields.get(className) ?? []), propertyKey]); + const modelClass = target.constructor; + fields.set(modelClass, [...(fields.get(modelClass) ?? []), propertyKey]); }; export default Field; diff --git a/app/models/decorators/Relation.ts b/app/models/decorators/Relation.ts index 2f72755bd2..068b4353a1 100644 --- a/app/models/decorators/Relation.ts +++ b/app/models/decorators/Relation.ts @@ -42,7 +42,9 @@ const relations = new Map<string, Map<string, RelationProperties>>(new Map()); * @param targetClass The model class to get inverse relations for. * @returns A map of inverse relation properties keyed by the property name. */ -export const getInverseRelationsForModelClass = (targetClass: typeof Model) => { +export const getInverseRelationsForModelClass = ( + targetClass: Pick<typeof Model, "modelName"> +) => { const inverseRelations = new Map<string, InverseRelationProperties>(); relations.forEach((relation, modelName) => { @@ -91,24 +93,17 @@ export default function Relation<T extends typeof Model>( ? `${String(singular(propertyKey))}Ids` : `${String(propertyKey)}Id`; - // If the relation has options provided then register them in a map for later lookup. We can use - // this to determine how to update relations when a model is deleted. - // - // TODO: requestAnimationFrame is a temporary solution to a bug in rolldown compiled code that - // will place static methods _after_ decorators. Temporary fix is to delay the registration until - // the next frame. - const modelName = (target.constructor as typeof Model).modelName; - requestAnimationFrame(() => { - if (options) { - const configForClass = relations.get(modelName) ?? new Map(); - configForClass.set(propertyKey, { - options, - relationClassResolver: classResolver, - idKey, - }); - relations.set(modelName, configForClass); - } - }); + // Register relation options to determine how to update relations when a model is deleted. + if (options) { + const modelName = (target.constructor as typeof Model).modelName; + const configForClass = relations.get(modelName) ?? new Map(); + configForClass.set(propertyKey, { + options, + relationClassResolver: classResolver, + idKey, + }); + relations.set(modelName, configForClass); + } Object.defineProperty(target, propertyKey, { get() { diff --git a/app/models/helpers/ProsemirrorHelper.ts b/app/models/helpers/ProsemirrorHelper.ts index d57ce7519a..d58d5136dd 100644 --- a/app/models/helpers/ProsemirrorHelper.ts +++ b/app/models/helpers/ProsemirrorHelper.ts @@ -114,4 +114,12 @@ export class ProsemirrorHelper { ); return text; }; + + /** + * Returns the ProseMirror node for the document data. + * + * @param document The document to parse. + * @returns The parsed node. + */ + static toNode = (document: HasData) => Node.fromJSON(schema, document.data); } diff --git a/app/routes/authenticated.tsx b/app/routes/authenticated.tsx index 87e6695524..c451f3e482 100644 --- a/app/routes/authenticated.tsx +++ b/app/routes/authenticated.tsx @@ -1,7 +1,7 @@ import { observer } from "mobx-react"; import { Suspense, useEffect } from "react"; import type { RouteComponentProps } from "react-router-dom"; -import { Switch, Redirect, matchPath, useLocation } from "react-router-dom"; +import { Switch, Redirect, matchPath, useHistory } from "react-router-dom"; import DocumentNew from "~/scenes/DocumentNew"; import Error404 from "~/scenes/Errors/Error404"; import AuthenticatedLayout from "~/components/AuthenticatedLayout"; @@ -54,19 +54,19 @@ function AuthenticatedRoutes() { useKeyboardShortcutsQuery(); const team = useCurrentTeam(); const can = usePolicy(team); - const location = useLocation(); + const history = useHistory(); // Warm the editor chunks alongside the scene chunk so a document can render // as soon as its data arrives. useEffect(() => { if ( - matchPath(location.pathname, { + matchPath(history.location.pathname, { path: [`/doc/${documentSlug}`, `/d/${documentSlug}`], }) ) { Scenes.preloadEditor(); } - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, []); return ( diff --git a/app/routes/index.tsx b/app/routes/index.tsx index 03b43f44e4..2e3e5ddbcd 100644 --- a/app/routes/index.tsx +++ b/app/routes/index.tsx @@ -1,5 +1,6 @@ import { Suspense } from "react"; import { Switch, Redirect } from "react-router-dom"; +import AsyncEditor from "~/components/AsyncEditor"; import DesktopRedirect from "~/scenes/DesktopRedirect"; import DelayedMount from "~/components/DelayedMount"; import FullscreenLoading from "~/components/FullscreenLoading"; @@ -8,6 +9,9 @@ import env from "~/env"; import lazy from "@shared/utils/lazyWithRetry"; import { matchDocumentSlug as documentSlug } from "~/utils/routeHelpers"; import useAutoRefresh from "~/hooks/useAutoRefresh"; +import { useWorkspaceSessions } from "~/hooks/useWorkspaceSessions"; +import isCloudHosted from "~/utils/isCloudHosted"; +import { isAppRootDomain } from "~/utils/urls"; const Authenticated = lazy(() => import("~/components/Authenticated")); const AuthenticatedRoutes = lazy(() => import("./authenticated")); @@ -15,9 +19,30 @@ const Shared = lazy(() => import("~/scenes/Shared")); const Login = lazy(() => import("~/scenes/Login")); const Logout = lazy(() => import("~/scenes/Logout")); const OAuthAuthorize = lazy(() => import("~/scenes/Login/OAuthAuthorize")); +const TeamSwitcher = lazy(() => + import("~/scenes/Login/components/TeamSwitcher").then((module) => ({ + default: module.TeamSwitcher, + })) +); + +/** + * Loads the chunks that a share page renders, so that the first render of the + * page does not suspend. + * + * @returns A promise that resolves when the chunks have loaded. + */ +export function preloadShared() { + return Promise.all([Shared.preload(), AsyncEditor.preload()]); +} export default function Routes() { useAutoRefresh(); + const sessions = useWorkspaceSessions(); + + // The root domain of a cloud hosted install has no workspace session, so + // app paths list the signed-in workspaces to continue to. + const showTeamSwitcher = + isCloudHosted && isAppRootDomain() && Object.keys(sessions).length > 0; return ( <Suspense @@ -60,9 +85,13 @@ export default function Routes() { component={Shared} /> - <Authenticated> - <AuthenticatedRoutes /> - </Authenticated> + {showTeamSwitcher ? ( + <Route render={() => <TeamSwitcher sessions={sessions} />} /> + ) : ( + <Authenticated> + <AuthenticatedRoutes /> + </Authenticated> + )} </Switch> )} </Suspense> diff --git a/app/routes/settings.tsx b/app/routes/settings.tsx index ce9a9a5e46..2a66d85639 100644 --- a/app/routes/settings.tsx +++ b/app/routes/settings.tsx @@ -32,7 +32,8 @@ function SettingsRoutes() { from={settingsPath("members")} to={settingsPath("users")} /> - {/* TODO: Refactor these exceptions into config? */} + {/* Features was renamed to AI, redirect for backwards compatibility */} + <Redirect exact from={settingsPath("features")} to={settingsPath("ai")} /> <Route exact path={settingsPath("groups", ":id", "members")} diff --git a/app/scenes/ApiKeyNew/components/ExpiryDatePicker.tsx b/app/scenes/ApiKeyNew/components/ExpiryDatePicker.tsx deleted file mode 100644 index 516e9985da..0000000000 --- a/app/scenes/ApiKeyNew/components/ExpiryDatePicker.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import { format as formatDate } from "date-fns"; -import * as React from "react"; -import { useTranslation } from "react-i18next"; -import styled from "styled-components"; -import { Calendar } from "@shared/components/Calendar"; -import { dateLocale } from "@shared/utils/date"; -import Button from "~/components/Button"; -import { - Popover, - PopoverTrigger, - PopoverContent, -} from "~/components/primitives/Popover"; -import useUserLocale from "~/hooks/useUserLocale"; - -type Props = { - selectedDate?: Date; - onSelect: (date: Date) => void; -}; - -const ExpiryDatePicker = ({ selectedDate, onSelect }: Props) => { - const { t } = useTranslation(); - const [open, setOpen] = React.useState(false); - - const userLocale = useUserLocale(); - const locale = dateLocale(userLocale); - - const handleSelect = React.useCallback( - (date: Date) => { - setOpen(false); - onSelect(date); - }, - [onSelect] - ); - - return ( - <Popover open={open} onOpenChange={setOpen}> - <PopoverTrigger> - <StyledPopoverButton neutral> - {selectedDate - ? formatDate(selectedDate, "MMM dd, yyyy", { locale }) - : t("Choose a date")} - </StyledPopoverButton> - </PopoverTrigger> - <PopoverContent - aria-label={t("Choose a date")} - width={280} - side="right" - shrink - > - <Calendar - required - mode="single" - selected={selectedDate} - onSelect={handleSelect} - locale={locale} - disabled={{ before: new Date() }} - /> - </PopoverContent> - </Popover> - ); -}; - -const StyledPopoverButton = styled(Button)` - margin-top: 12px; - width: 150px; -`; - -export default ExpiryDatePicker; diff --git a/app/scenes/ApiKeyNew/index.tsx b/app/scenes/ApiKeyNew/index.tsx index 2258ca742e..11e277526d 100644 --- a/app/scenes/ApiKeyNew/index.tsx +++ b/app/scenes/ApiKeyNew/index.tsx @@ -6,6 +6,7 @@ import styled from "styled-components"; import { errToString } from "@shared/utils/error"; import { ApiKeyValidation } from "@shared/validations"; import Button from "~/components/Button"; +import ExpiryDatePicker from "~/components/ExpiryDatePicker"; import Flex from "~/components/Flex"; import Input from "~/components/Input"; import type { Option } from "~/components/InputSelect"; @@ -14,7 +15,6 @@ import Text from "~/components/Text"; import useStores from "~/hooks/useStores"; import useUserLocale from "~/hooks/useUserLocale"; import { dateToExpiry } from "~/utils/date"; -import ExpiryDatePicker from "./components/ExpiryDatePicker"; import { ExpiryType, ExpiryValues, calculateExpiryDate } from "./utils"; type Props = { @@ -125,9 +125,8 @@ function ApiKeyNew({ onSubmit }: Props) { /> <Text type="secondary" size="small" as="p"> {t( - "Space-separated scopes restrict the access of this API key to specific parts of the API. Leave blank for full access" + "Space-separated scopes restrict the access of this API key to specific parts of the API. Leave blank for full access." )} - . </Text> <Flex align="center" gap={8}> <StyledExpirySelect @@ -137,7 +136,7 @@ function ApiKeyNew({ onSubmit }: Props) { label={t("Expiration")} /> {expiryType === ExpiryType.Custom ? ( - <ExpiryDatePicker + <StyledExpiryDatePicker selectedDate={expiresAt} onSelect={handleSelectCustomDate} /> @@ -164,6 +163,10 @@ const StyledExpirySelect = styled(InputSelect)` margin-bottom: 16px; `; +const StyledExpiryDatePicker = styled(ExpiryDatePicker)` + margin-top: 12px; +`; + const StyledExpiryText = styled(Text)` position: relative; top: 4px; diff --git a/app/scenes/Collection/components/Actions.tsx b/app/scenes/Collection/components/Actions.tsx index 8b638d9b59..63772a7a97 100644 --- a/app/scenes/Collection/components/Actions.tsx +++ b/app/scenes/Collection/components/Actions.tsx @@ -53,7 +53,7 @@ function Actions({ collection, isEditing, sidebarContext }: Props) { return ( <> - {(!isEditing || !user?.separateEditMode) && ( + {(!isEditing || !user?.separateEditMode) && !collection.isPersonal && ( <Action> <ShareButton collection={collection} /> </Action> @@ -61,11 +61,7 @@ function Actions({ collection, isEditing, sidebarContext }: Props) { {!isEditing && user?.separateEditMode && ( <Action> <RegisterKeyDown trigger="e" handler={goToEdit} /> - <Tooltip - content={t("Edit collection")} - shortcut="e" - placement="bottom" - > + <Tooltip content={t("Edit collection")} shortcut="e" side="bottom"> <Button icon={<EditIcon />} onClick={goToEdit} neutral> {t("Edit")} </Button> @@ -80,7 +76,7 @@ function Actions({ collection, isEditing, sidebarContext }: Props) { )} {can.createDocument && ( <Action> - <Tooltip content={t("New document")} shortcut="n" placement="bottom"> + <Tooltip content={t("New document")} shortcut="n" side="bottom"> <Button as={Link} to={collection ? newDocumentPath(collection.id) : ""} diff --git a/app/scenes/Collection/components/CollectionMeta.tsx b/app/scenes/Collection/components/CollectionMeta.tsx index 3b89148ee2..1599679ca0 100644 --- a/app/scenes/Collection/components/CollectionMeta.tsx +++ b/app/scenes/Collection/components/CollectionMeta.tsx @@ -3,7 +3,7 @@ import { GlobeIcon, PadlockIcon, TeamIcon } from "outline-icons"; import { useEffect } from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { flattenTree } from "@shared/utils/tree"; import type Collection from "~/models/Collection"; import Flex from "~/components/Flex"; @@ -30,9 +30,7 @@ export const CollectionMeta = observer(function CollectionMeta_({ const share = shares.getByCollectionId(collection.id); const isPubliclyShared = - team.sharing !== false && - collection.sharing !== false && - !!share?.published; + team.sharing !== false && collection.sharing !== false && !!share?.isActive; // The document structure is cached on the collection once loaded, so this is // a no-op when the sidebar or another tab has already requested it. @@ -52,7 +50,7 @@ export const CollectionMeta = observer(function CollectionMeta_({ ? t("Only members with access can view") : t("All members in the workspace can view") } - placement="bottom" + side="bottom" > <IconLabel align="center"> {collection.isPrivate ? ( @@ -66,10 +64,7 @@ export const CollectionMeta = observer(function CollectionMeta_({ {isPubliclyShared && ( <> <Separator /> - <Tooltip - content={t("Anyone with the link can view")} - placement="bottom" - > + <Tooltip content={t("Anyone with the link can view")} side="bottom"> <IconLabel align="center"> <GlobeIcon size={18} /> {t("Publicly shared")} diff --git a/app/scenes/Collection/components/DropToImport.tsx b/app/scenes/Collection/components/DropToImport.tsx index 8ac485b1dc..f47c1b1901 100644 --- a/app/scenes/Collection/components/DropToImport.tsx +++ b/app/scenes/Collection/components/DropToImport.tsx @@ -1,6 +1,6 @@ import { observer } from "mobx-react"; import * as React from "react"; -import Dropzone from "react-dropzone"; +import Dropzone, { type Accept } from "react-dropzone"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled, { css } from "styled-components"; @@ -10,7 +10,7 @@ import useImportDocument from "~/hooks/useImportDocument"; type Props = { disabled: boolean; - accept: string; + accept: Accept; collectionId: string; children?: React.ReactNode; }; @@ -36,6 +36,7 @@ const DropToImport: React.FC<Props> = ({ disabled={disabled} noClick multiple + noPaste > {({ getRootProps, getInputProps, isDragActive }) => ( <DropzoneContainer diff --git a/app/scenes/Collection/components/Empty.tsx b/app/scenes/Collection/components/Empty.tsx index 7694ef119b..19cb5dbda7 100644 --- a/app/scenes/Collection/components/Empty.tsx +++ b/app/scenes/Collection/components/Empty.tsx @@ -12,15 +12,14 @@ type Props = { }; function EmptyCollection({ collection }: Props) { - const collectionName = collection ? collection.name : ""; + const collectionName = collection ? collection.displayName : ""; return ( <Fade> <Centered column> <Text as="p" type="secondary"> <Trans - defaults="<em>{{ collectionName }}</em> doesn’t contain any - documents yet." + defaults="<em>{{ collectionName }}</em> doesn’t contain any documents yet." values={{ collectionName, }} diff --git a/app/scenes/Collection/components/Header.tsx b/app/scenes/Collection/components/Header.tsx index c9252fb53e..407e1b1c3f 100644 --- a/app/scenes/Collection/components/Header.tsx +++ b/app/scenes/Collection/components/Header.tsx @@ -1,5 +1,5 @@ import { IconTitleWrapper } from "@shared/components/Icon"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { first } from "es-toolkit/compat"; import { Suspense, useCallback } from "react"; import styled from "styled-components"; @@ -49,7 +49,7 @@ export const Header = observer(function Header_({ <CollectionIcon collection={collection} size={40} expanded /> ) : null; - const dir = isRTL(collection.name) ? "rtl" : "ltr"; + const dir = isRTL(collection.displayName) ? "rtl" : "ltr"; return ( <StyledHeading dir={dir}> @@ -80,7 +80,7 @@ export const Header = observer(function Header_({ dir="auto" /> ) : ( - collection.name + collection.displayName )} </StyledHeading> ); diff --git a/app/scenes/Collection/components/MembershipPreview.tsx b/app/scenes/Collection/components/MembershipPreview.tsx index d09d19868c..e07c13f71b 100644 --- a/app/scenes/Collection/components/MembershipPreview.tsx +++ b/app/scenes/Collection/components/MembershipPreview.tsx @@ -91,7 +91,7 @@ const MembershipPreview = ({ collection, limit = 8 }: Props) => { groupsCount, count: groupsCount, }), - delay: 250, + delayDuration: 250, }} width="auto" height="auto" diff --git a/app/scenes/Collection/components/Overview.tsx b/app/scenes/Collection/components/Overview.tsx index f2ee5f16b2..cfec0d3dd2 100644 --- a/app/scenes/Collection/components/Overview.tsx +++ b/app/scenes/Collection/components/Overview.tsx @@ -13,7 +13,6 @@ import type Document from "~/models/Document"; import Editor from "~/components/Editor"; import LoadingIndicator from "~/components/LoadingIndicator"; import Text from "~/components/Text"; -import { MeasuredContainer } from "~/components/MeasuredContainer"; import { withUIExtensions } from "~/editor/extensions"; import useCurrentUser from "~/hooks/useCurrentUser"; import usePolicy from "~/hooks/usePolicy"; @@ -80,7 +79,7 @@ function Overview({ collection, readOnly }: Props) { } ); - return newDocument.url; + return newDocument.path; }, [collection, documents] ); @@ -90,7 +89,7 @@ function Overview({ collection, readOnly }: Props) { {collections.isSaving && <LoadingIndicator />} {(can.update || readOnly) && ( <Suspense fallback={<Placeholder>Loading…</Placeholder>}> - <MeasuredContainer name="document"> + <div> <Editor defaultValue={collection.data} onChange={handleSave} @@ -104,7 +103,7 @@ function Overview({ collection, readOnly }: Props) { editorStyle={editorStyle} /> <div ref={childRef} /> - </MeasuredContainer> + </div> </Suspense> )} </> diff --git a/app/scenes/Collection/components/ShareButton.tsx b/app/scenes/Collection/components/ShareButton.tsx index 7e8305fecc..17a998c859 100644 --- a/app/scenes/Collection/components/ShareButton.tsx +++ b/app/scenes/Collection/components/ShareButton.tsx @@ -11,6 +11,7 @@ import { } from "~/components/primitives/Popover"; import useCurrentTeam from "~/hooks/useCurrentTeam"; import useMobile from "~/hooks/useMobile"; +import useClickIntent from "~/hooks/useClickIntent"; import useShareDataLoader from "~/hooks/useShareDataLoader"; import useStores from "~/hooks/useStores"; import { preventDefault } from "~/utils/events"; @@ -33,7 +34,7 @@ function ShareButton({ collection }: Props) { const team = useCurrentTeam(); const share = shares.getByCollectionId(collection.id); const isPubliclyShared = - team.sharing !== false && collection?.sharing !== false && share?.published; + team.sharing !== false && collection?.sharing !== false && share?.isActive; const { preload, loading, reset } = useShareDataLoader({ collection }); const handleOpenChange = useCallback( @@ -48,6 +49,16 @@ function ShareButton({ collection }: 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]); @@ -65,7 +76,13 @@ function ShareButton({ collection }: Props) { return ( <Popover open={open} onOpenChange={handleOpenChange}> <PopoverTrigger> - <Button icon={icon} neutral onMouseEnter={preload}> + <Button + ref={intentRef} + icon={icon} + neutral + onMouseEnter={handleMouseEnter} + onMouseLeave={handleMouseLeave} + > {t("Share")} </Button> </PopoverTrigger> 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 <Loading />; } + // A personal collection is only shown in the sidebar, it has no page. + if (collection.isPersonal) { + return <Error404 />; + } + const showOverview = can.update || hasDescription; return ( <Scene centered={false} - textTitle={collection.name} + textTitle={collection.displayName} left={ collection.isArchived ? ( <CollectionBreadcrumb collection={collection} /> @@ -161,12 +166,14 @@ const CollectionScene = observer(function CollectionScene_() { title={ <> <CollectionIcon collection={collection} expanded /> -  {collection.name} +  {collection.displayName} </> } actions={ <> - <MembershipPreview collection={collection} /> + {!collection.isPersonal && ( + <MembershipPreview collection={collection} /> + )} <Actions collection={collection} isEditing={isEditRoute} @@ -176,7 +183,7 @@ const CollectionScene = observer(function CollectionScene_() { } > <DropToImport - accept={documents.importFileTypesString} + accept={documents.importFileTypesAccept} disabled={!can.createDocument} collectionId={collection.id} > diff --git a/app/scenes/DesktopRedirect.tsx b/app/scenes/DesktopRedirect.tsx index 5d681ca3f8..8d5c0dc9c5 100644 --- a/app/scenes/DesktopRedirect.tsx +++ b/app/scenes/DesktopRedirect.tsx @@ -16,7 +16,7 @@ const DesktopRedirect = () => { "_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/ChangesNavigation.tsx b/app/scenes/Document/components/ChangesNavigation.tsx index 36fe6e1ec4..dee3c5638c 100644 --- a/app/scenes/Document/components/ChangesNavigation.tsx +++ b/app/scenes/Document/components/ChangesNavigation.tsx @@ -39,7 +39,7 @@ export const ChangesNavigation = observer(function ChangesNavigation_() { count: totalChanges, })} </NavigationLabel> - <Tooltip content={t("Previous change")} placement="bottom"> + <Tooltip content={t("Previous change")} side="bottom"> <NavigationButton icon={<CaretUpIcon />} onClick={() => editor?.commands.prevChange()} @@ -47,7 +47,7 @@ export const ChangesNavigation = observer(function ChangesNavigation_() { aria-label={t("Previous change")} /> </Tooltip> - <Tooltip content={t("Next change")} placement="bottom"> + <Tooltip content={t("Next change")} side="bottom"> <NavigationButton icon={<CaretDownIcon />} onClick={() => editor?.commands.nextChange()} diff --git a/app/scenes/Document/components/Comments/CommentForm.tsx b/app/scenes/Document/components/Comments/CommentForm.tsx index 1e08bddeef..8a36b85d4d 100644 --- a/app/scenes/Document/components/Comments/CommentForm.tsx +++ b/app/scenes/Document/components/Comments/CommentForm.tsx @@ -411,7 +411,7 @@ function CommentForm({ {t("Cancel")} </ButtonSmall> </HStack> - <Tooltip content={t("Upload image")} placement="top"> + <Tooltip content={t("Upload image")}> <NudeButton onClick={handleImageUpload}> <ImageIcon color={theme.textTertiary} /> </NudeButton> diff --git a/app/scenes/Document/components/Comments/CommentThread.tsx b/app/scenes/Document/components/Comments/CommentThread.tsx index 99ec741fd7..40dcb64602 100644 --- a/app/scenes/Document/components/Comments/CommentThread.tsx +++ b/app/scenes/Document/components/Comments/CommentThread.tsx @@ -5,7 +5,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import scrollIntoView from "scroll-into-view-if-needed"; import styled, { css } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { s, hover } from "@shared/styles"; import type { ProsemirrorData } from "@shared/types"; import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; @@ -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 ( <Thread diff --git a/app/scenes/Document/components/Comments/CommentThreadItem.tsx b/app/scenes/Document/components/Comments/CommentThreadItem.tsx index 0540584387..edf49fff8d 100644 --- a/app/scenes/Document/components/Comments/CommentThreadItem.tsx +++ b/app/scenes/Document/components/Comments/CommentThreadItem.tsx @@ -7,7 +7,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled, { css } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import EventBoundary from "@shared/components/EventBoundary"; import { s, hover } from "@shared/styles"; import type { ProsemirrorData } from "@shared/types"; @@ -317,7 +317,7 @@ const ResolveButton = ({ const { t } = useTranslation(); return ( - <Tooltip content={t("Mark as resolved")} placement="top"> + <Tooltip content={t("Mark as resolved")}> <Action as={NudeButton} action={resolveCommentActionFactory({ diff --git a/app/scenes/Document/components/Comments/HighlightText.ts b/app/scenes/Document/components/Comments/HighlightText.ts index b2ae52984a..9dac580ccd 100644 --- a/app/scenes/Document/components/Comments/HighlightText.ts +++ b/app/scenes/Document/components/Comments/HighlightText.ts @@ -5,10 +5,9 @@ import Text from "~/components/Text"; /** * Highlighted text associated with a comment. */ -export const HighlightedText = styled(Text)` +export const HighlightedText = styled(Text).attrs({ size: "small" })` position: relative; color: ${s("textSecondary")}; - font-size: 14px; padding: 0 8px; margin: 4px 0; display: inline-block; diff --git a/app/scenes/Document/components/ConnectionStatus.tsx b/app/scenes/Document/components/ConnectionStatus.tsx index bde1b5e073..6372703a19 100644 --- a/app/scenes/Document/components/ConnectionStatus.tsx +++ b/app/scenes/Document/components/ConnectionStatus.tsx @@ -2,7 +2,7 @@ import { observer } from "mobx-react"; import { DisconnectedIcon } from "outline-icons"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { AuthenticationFailed, AuthorizationFailed, @@ -32,7 +32,7 @@ function ConnectionStatus() { }, [AuthorizationFailed.code]: { title: t("Authorization failed"), - body: t("You may have lost access to this document, try reloading"), + body: t("You may have lost access to this document – try reloading"), }, [TooManyConnections.code]: { title: t("Too many users connected to document"), @@ -66,7 +66,7 @@ function ConnectionStatus() { </Centered> ) } - placement="bottom" + side="bottom" > <Fade> <Button width="auto"> diff --git a/app/scenes/Document/components/Contents.tsx b/app/scenes/Document/components/Contents.tsx index 68a2df5c04..1c06c86f5c 100644 --- a/app/scenes/Document/components/Contents.tsx +++ b/app/scenes/Document/components/Contents.tsx @@ -4,13 +4,12 @@ import { useState, useEffect, useMemo, useRef, useCallback } from "react"; import { useTranslation } from "react-i18next"; import { useHistory } from "react-router-dom"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { EmojiText } from "@shared/components/EmojiText"; import { HeadingPrefixHelper } from "@shared/editor/extensions/HeadingPrefix"; import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; import { DocumentPreference, HeadingPrefixStyle } from "@shared/types"; import { depths, hideScrollbars, s } from "@shared/styles"; -import { supportsPassiveListener } from "@shared/utils/browser"; import { useDocumentContext } from "~/components/DocumentContext"; import useWindowScrollPosition from "~/hooks/useWindowScrollPosition"; import { patchLocation } from "~/utils/history"; @@ -110,11 +109,7 @@ function Contents() { } }; - window.addEventListener( - "scroll", - handleScroll, - supportsPassiveListener ? { passive: true } : false - ); + window.addEventListener("scroll", handleScroll, { passive: true }); return () => window.removeEventListener("scroll", handleScroll); }, [selectedSlug]); diff --git a/app/scenes/Document/components/DataLoader.tsx b/app/scenes/Document/components/DataLoader.tsx index 747c78677d..8d3137e9c6 100644 --- a/app/scenes/Document/components/DataLoader.tsx +++ b/app/scenes/Document/components/DataLoader.tsx @@ -101,7 +101,7 @@ function DataLoader({ match, children }: Props) { const missingPolicy = !can || Object.keys(can).length === 0; const isJustCreated = React.useMemo( () => !!document?.isJustCreated, - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps [document?.id] ); @@ -211,7 +211,7 @@ function DataLoader({ match, children }: Props) { } ); - return newDocument.url; + return newDocument.path; }, [document, documents] ); @@ -230,7 +230,7 @@ function DataLoader({ match, children }: Props) { // If we're attempting to update an archived, deleted, or otherwise // uneditable document then forward to the canonical read url. if (!missingPolicy && !can.update && isEditRoute) { - history.push(document.url); + history.push(document.path); return; } diff --git a/app/scenes/Document/components/Document.tsx b/app/scenes/Document/components/Document.tsx index a4dea7a5d9..4fa46416a7 100644 --- a/app/scenes/Document/components/Document.tsx +++ b/app/scenes/Document/components/Document.tsx @@ -1,17 +1,19 @@ +import type { Location } from "history"; import { observer } from "mobx-react"; import { AllSelection } from "prosemirror-state"; import { useRef, useCallback } from "react"; import * as React from "react"; import { useTranslation } from "react-i18next"; -import { Prompt, useHistory, useLocation } from "react-router-dom"; +import { Prompt, matchPath, useHistory } from "react-router-dom"; import { toast } from "sonner"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; import { s } from "@shared/styles"; import type { NavigationNode } from "@shared/types"; import { IconType, TOCPosition, TeamPreference } from "@shared/types"; import { determineIconType } from "@shared/utils/icon"; +import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; import type Document from "~/models/Document"; import type Revision from "~/models/Revision"; import { useDocumentContext } from "~/components/DocumentContext"; @@ -22,17 +24,22 @@ import LoadingIndicator from "~/components/LoadingIndicator"; import PageTitle from "~/components/PageTitle"; import PlaceholderDocument from "~/components/PlaceholderDocument"; import RegisterKeyDown from "~/components/RegisterKeyDown"; -import { MeasuredContainer } from "~/components/MeasuredContainer"; import type { Editor as TEditor } from "~/editor"; import type { Properties } from "~/types"; import useEventListener from "~/hooks/useEventListener"; +import type { SidebarContextType } from "~/components/Sidebar/components/SidebarContext"; import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext"; import useMobile from "~/hooks/useMobile"; import useStores from "~/hooks/useStores"; import isTextInput from "~/utils/isTextInput"; +import Logger from "~/utils/Logger"; import { client } from "~/utils/ApiClient"; import { emojiToUrl } from "~/utils/emoji"; -import { documentHistoryPath, documentEditPath } from "~/utils/routeHelpers"; +import { + documentHistoryPath, + documentEditPath, + matchDocumentHistory, +} from "~/utils/routeHelpers"; import { useDocumentSave } from "../hooks/useDocumentSave"; import Container from "./Container"; import Contents from "./Contents"; @@ -47,6 +54,7 @@ type LocationState = { title?: string; restore?: boolean; revisionId?: string; + sidebarContext?: SidebarContextType; }; interface Props { @@ -88,8 +96,7 @@ function DocumentScene({ const documentContext = useDocumentContext(); const isMobile = useMobile(); const { t } = useTranslation(); - const history = useHistory(); - const location = useLocation<LocationState>(); + const history = useHistory<LocationState>(); const sidebarContext = useLocationSidebarContext(); const { team, user } = auth; @@ -111,8 +118,8 @@ function DocumentScene({ } = useDocumentSave({ document, editorRef, readOnly }); const onSynced = useCallback(async () => { - const restore = location.state?.restore; - const revisionId = location.state?.revisionId; + const restore = history.location.state?.restore; + const revisionId = history.location.state?.revisionId; const editor = editorRef.current; if (!editor) { @@ -120,7 +127,7 @@ function DocumentScene({ } // Highlight search term when navigating from search results - const params = new URLSearchParams(location.search); + const params = new URLSearchParams(history.location.search); const searchTerm = params.get("q"); if (searchTerm) { editor.commands.find({ text: searchTerm }); @@ -130,8 +137,8 @@ function DocumentScene({ return; } - history.replace(document.url, { - ...location.state, + history.replace(document.path, { + ...history.location.state, restore: undefined, revisionId: undefined, }); @@ -151,7 +158,7 @@ function DocumentScene({ ); toast.success(t("Document restored")); } - }, [location, replaceSelection, t, history, document.url]); + }, [replaceSelection, t, history, document.path]); const onUndoRedo = useCallback( (event: KeyboardEvent) => { @@ -186,7 +193,7 @@ function DocumentScene({ if (abilities.move) { dialogs.openModal({ title: t("Move document"), - content: <DocumentMove document={document} />, + content: <DocumentMove documents={[document]} />, }); } }, @@ -252,7 +259,7 @@ function DocumentScene({ } ev.preventDefault(); - if (location.pathname.endsWith("history")) { + if (history.location.pathname.endsWith("history")) { history.push({ pathname: document.path, state: { sidebarContext }, @@ -264,7 +271,7 @@ function DocumentScene({ }); } }, - [readOnly, location.pathname, history, document, sidebarContext] + [readOnly, history, document, sidebarContext] ); const onPublish = useCallback( @@ -294,7 +301,7 @@ function DocumentScene({ const goBack = useCallback(() => { if (!readOnly) { history.push({ - pathname: document.url, + pathname: document.path, state: { sidebarContext }, }); } @@ -324,28 +331,39 @@ function DocumentScene({ const hasUnsyncedChanges = !readOnly && documentContext.hasUnsyncedChanges; - const handleBlockNavigation = () => { - if (hasUnsyncedChanges) { - return documentContext.hasLocalPersistence - ? t( - `Your changes haven’t synced yet, they are saved on this device.\nAre you sure you want to leave?` - ) - : t( - `Your changes haven’t synced yet and will be lost.\nAre you sure you want to leave?` - ); + const warnUnsyncedChanges = () => { + Logger.warn("Leaving document with unsynced changes", { + documentId: document.id, + hasLocalPersistence: documentContext.hasLocalPersistence, + }); + }; + + const handleBlockNavigation = (nextLocation: Location) => { + // Moving between views of this document, such as edit mode or a heading + // anchor, keeps the editor mounted, but a revision view replaces it. + const isLeaving = + !parseDocumentSlug(nextLocation.pathname)?.endsWith(document.urlId) || + !!matchPath<{ revisionId?: string }>( + nextLocation.pathname, + matchDocumentHistory + )?.params.revisionId; + if (!isLeaving) { + return true; } if (isUploading && !isEditorDirty) { return t( `Images are still uploading.\nAre you sure you want to discard them?` ); } + if (hasUnsyncedChanges) { + warnUnsyncedChanges(); + } return true; }; - const handleUnload = (event: BeforeUnloadEvent) => { + const handleUnload = () => { if (hasUnsyncedChanges) { - event.preventDefault(); - event.returnValue = ""; + warnUnsyncedChanges(); } }; @@ -353,8 +371,8 @@ function DocumentScene({ const hasEmojiInTitle = determineIconType(document.icon) === IconType.Emoji; const pageTitle = hasEmojiInTitle - ? document.titleWithDefault.replace(document.icon!, "") - : document.titleWithDefault; + ? document.displayTitle.replace(document.icon!, "") + : document.displayTitle; const favicon = hasEmojiInTitle ? emojiToUrl(document.icon!) : undefined; const fullWidthTransformOffsetStyle = { @@ -377,15 +395,7 @@ function DocumentScene({ }} handler={onPublish} /> - <MeasuredContainer - as={Background} - name="container" - column - auto - onDragOver={handleDragOver} - onDrop={handleDrop} - data-drop-area - > + <Background column auto onDragOver={handleDragOver} onDrop={handleDrop}> <PageTitle title={pageTitle} favicon={favicon} /> {(isUploading || isSaving) && <LoadingIndicator />} <Container column auto> @@ -429,9 +439,7 @@ function DocumentScene({ </EditorContainer> } > - <MeasuredContainer - name="document" - as={EditorContainer} + <EditorContainer docFullWidth={document.fullWidth} showContents={showContents} tocPosition={tocPos} @@ -482,7 +490,7 @@ function DocumentScene({ </Editor> </> )} - </MeasuredContainer> + </EditorContainer> {showContents && ( <ContentsContainer docFullWidth={document.fullWidth} @@ -495,7 +503,7 @@ function DocumentScene({ </Main> {children} </Container> - </MeasuredContainer> + </Background> </ErrorBoundary> ); } @@ -578,7 +586,7 @@ const EditorContainer = styled.div<EditorContainerProps>` // A notice above the editor already provides the space from the header &:has(> ${DocumentNotice}) { - --document-title-margin-top: 0; + --document-title-margin-top: 0px; } ${breakpoint("tablet")` @@ -604,6 +612,10 @@ const EditorContainer = styled.div<EditorContainerProps>` const Background = styled(Container)` position: relative; background: ${s("background")}; + + // A container unit, unlike a measured value, does not restyle the document on resize. + container-type: inline-size; + --container-width: 100cqi; `; const ReferencesWrapper = styled.div` diff --git a/app/scenes/Document/components/DocumentMeta.tsx b/app/scenes/Document/components/DocumentMeta.tsx index fed0588b73..11b66384cc 100644 --- a/app/scenes/Document/components/DocumentMeta.tsx +++ b/app/scenes/Document/components/DocumentMeta.tsx @@ -8,7 +8,10 @@ import styled from "styled-components"; import type Document from "~/models/Document"; import type Revision from "~/models/Revision"; import type Template from "~/models/Template"; -import { openDocumentInsights } from "~/actions/definitions/documents"; +import { + Insights, + openDocumentInsights, +} from "~/actions/definitions/documents"; import DocumentMeta from "~/components/DocumentMeta"; import { MetaButton, @@ -17,11 +20,13 @@ import { } from "~/components/HeaderMeta"; import Fade from "~/components/Fade"; import { useSplitView } from "~/components/SplitView/context"; +import useClickIntent from "~/hooks/useClickIntent"; import useCurrentTeam from "~/hooks/useCurrentTeam"; import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import { documentPath } from "~/utils/routeHelpers"; +import { DocumentComments, DocumentHistory } from "../hooks/useDocumentSidebar"; type Props = { /* The document to display meta data for */ @@ -50,6 +55,19 @@ function TitleDocumentMeta({ to, document, revision, rtl, ...rest }: Props) { const commentingEnabled = team.commentingEnabled; const commentsOpen = ui.getRightSidebar(pane) === "comments"; + const { + ref: commentsRef, + handleMouseEnter: handleCommentsMouseEnter, + handleMouseLeave: handleCommentsMouseLeave, + } = useClickIntent(DocumentComments.preload, { + predict: true, + }); + const { + ref: insightsRef, + handleMouseEnter: handleInsightsMouseEnter, + handleMouseLeave: handleInsightsMouseLeave, + } = useClickIntent(Insights.preload, { predict: true }); + const handleClickMeta = useCallback(() => { if (to) { history.replace(to); @@ -69,13 +87,20 @@ function TitleDocumentMeta({ to, document, revision, rtl, ...rest }: Props) { document={document as Document} revision={revision} onClick={to ? handleClickMeta : undefined} + onClickIntent={to ? DocumentHistory.preload : undefined} $rtl={rtl} {...rest} > {commentingEnabled && can.comment && ( <> <Separator /> - <MetaButton onClick={handleClickComment} aria-expanded={commentsOpen}> + <MetaButton + ref={commentsRef} + onClick={handleClickComment} + onMouseEnter={handleCommentsMouseEnter} + onMouseLeave={handleCommentsMouseLeave} + aria-expanded={commentsOpen} + > <CommentIcon size={18} /> {commentsCount ? t("{{ count }} comment", { count: commentsCount }) @@ -86,7 +111,12 @@ function TitleDocumentMeta({ to, document, revision, rtl, ...rest }: Props) { {totalViewers && can.listViews && !(document as Document).isDraft ? ( <Wrapper> <Separator /> - <MetaButton action={openDocumentInsights}> + <MetaButton + ref={insightsRef} + action={openDocumentInsights} + onMouseEnter={handleInsightsMouseEnter} + onMouseLeave={handleInsightsMouseLeave} + > {t("Viewed by")}{" "} {onlyYou ? t("only you") diff --git a/app/scenes/Document/components/DocumentStats.tsx b/app/scenes/Document/components/DocumentStats.tsx index da84a567ed..106ee90cfd 100644 --- a/app/scenes/Document/components/DocumentStats.tsx +++ b/app/scenes/Document/components/DocumentStats.tsx @@ -1,7 +1,7 @@ import { observer } from "mobx-react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { s } from "@shared/styles"; import Flex from "~/components/Flex"; import Text from "~/components/Text"; diff --git a/app/scenes/Document/components/DocumentTitle.tsx b/app/scenes/Document/components/DocumentTitle.tsx index 38df259914..e3007adf58 100644 --- a/app/scenes/Document/components/DocumentTitle.tsx +++ b/app/scenes/Document/components/DocumentTitle.tsx @@ -5,7 +5,7 @@ import { __parseFromClipboard } from "prosemirror-view"; import * as React from "react"; import { mergeRefs } from "react-merge-refs"; import styled, { css } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import Icon, { IconTitleWrapper } from "@shared/components/Icon"; import isMarkdown from "@shared/editor/lib/isMarkdown"; import normalizePastedMarkdown from "@shared/editor/lib/markdown/normalize"; @@ -292,7 +292,10 @@ const StyledIconPicker = styled(IconPicker)` const Title = styled(ContentEditable)<TitleProps>` position: relative; line-height: ${lineHeight}; - margin-top: var(--document-title-margin-top, 8vh); + margin-top: ${(props) => + props.$containsIcon || !props.readOnly + ? "calc(var(--document-title-margin-top, 16px) + 44px)" + : "var(--document-title-margin-top, 16px)"}; margin-bottom: 0.5em; font-size: ${fontSize}; font-weight: 600; diff --git a/app/scenes/Document/components/Editor.tsx b/app/scenes/Document/components/Editor.tsx index 0c90e23f5c..453e305fa5 100644 --- a/app/scenes/Document/components/Editor.tsx +++ b/app/scenes/Document/components/Editor.tsx @@ -20,6 +20,7 @@ import Editor from "~/components/Editor"; import { useSplitView } from "~/components/SplitView/context"; import type { Editor as SharedEditor } from "~/editor"; import Flex from "~/components/Flex"; +import { headerMetaStyles } from "~/components/HeaderMeta"; import PlaceholderDocument from "~/components/PlaceholderDocument"; import Time from "~/components/Time"; import { withUIExtensions } from "~/editor/extensions"; @@ -227,9 +228,7 @@ function DocumentEditor(props: Props) { readOnly={readOnly} documentId={document.id} title={ - !document.title && readOnly - ? document.titleWithDefault - : document.title + !document.title && readOnly ? document.displayTitle : document.title } icon={document.icon} color={iconColor} @@ -306,8 +305,7 @@ function DocumentEditor(props: Props) { } const SharedMeta = styled(Text)` - margin: -12px 0 2em 0; - font-size: 14px; + ${headerMetaStyles} `; export default observer(DocumentEditor); diff --git a/app/scenes/Document/components/Header.tsx b/app/scenes/Document/components/Header.tsx index 0c8061284b..53c2d377bb 100644 --- a/app/scenes/Document/components/Header.tsx +++ b/app/scenes/Document/components/Header.tsx @@ -121,7 +121,7 @@ function DocumentHeader({ : `${t("Show contents")} (${t("available when headings are added")})` } shortcut={`Ctrl+${altDisplay}+h`} - placement="bottom" + side="bottom" > <TocButton aria-label={t("Show contents")} @@ -139,7 +139,7 @@ function DocumentHeader({ noun: document.noun, })} shortcut="e" - placement="bottom" + side="bottom" > <Button as={Link} @@ -170,9 +170,7 @@ function DocumentHeader({ $hidden={isEditingFocus} hasSidebar left={ - isMobile ? ( - <TableOfContentsMenu /> - ) : ( + isMobile ? null : ( <DocumentBreadcrumb document={document}> {toc}{" "} <StarAction> @@ -192,7 +190,7 @@ function DocumentHeader({ )} {document.title} {document.isPrivate && ( - <Tooltip content={t("Access restricted")} placement="bottom"> + <Tooltip content={t("Access restricted")} side="bottom"> <PadlockIcon size={16} /> </Tooltip> )} @@ -229,7 +227,7 @@ function DocumentHeader({ <Tooltip content={isDraft ? t("Save draft") : t("Done editing")} shortcut={`${metaDisplay}+enter`} - placement="bottom" + side="bottom" > <Button onClick={handleSave} @@ -262,7 +260,7 @@ function DocumentHeader({ <ChangesNavigation /> </Action> <Action> - <Tooltip content={t("Restore version")} placement="bottom"> + <Tooltip content={t("Restore version")} side="bottom"> <Button action={restoreRevision} disabled={revision.createdAt === document.updatedAt} @@ -287,6 +285,11 @@ function DocumentHeader({ </Button> </Action> )} + {isMobile && ( + <Action> + <TableOfContentsMenu /> + </Action> + )} <Action> <DocumentMenu document={document} diff --git a/app/scenes/Document/components/History/History.tsx b/app/scenes/Document/components/History/History.tsx index 18f63c199c..10c47e5dcf 100644 --- a/app/scenes/Document/components/History/History.tsx +++ b/app/scenes/Document/components/History/History.tsx @@ -1,6 +1,7 @@ import isEqual from "fast-deep-equal"; import { orderBy } from "es-toolkit/compat"; import { observer } from "mobx-react"; +import queryString from "query-string"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { useHistory, useRouteMatch } from "react-router-dom"; @@ -17,7 +18,11 @@ import useKeyDown from "~/hooks/useKeyDown"; import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext"; import useQuery from "~/hooks/useQuery"; import useStores from "~/hooks/useStores"; -import { documentPath, matchDocumentHistory } from "~/utils/routeHelpers"; +import { + documentHistoryPath, + documentPath, + matchDocumentHistory, +} from "~/utils/routeHelpers"; import { isTruthyQueryValue } from "~/utils/urls"; import Sidebar from "../SidebarLayout"; import useMobile from "~/hooks/useMobile"; @@ -113,16 +118,6 @@ function History() { } }, [selectedRevisionId, updateLocation]); - const handleCompareToChange = React.useCallback( - (value: string) => { - setCompareTo(value); - updateLocation({ - compareTo: value === COMPARE_TO_PREVIOUS ? null : value, - }); - }, - [updateLocation] - ); - // Ensure that the URL parameter is in sync with the persisted state on mount React.useEffect(() => { if (defaultShowChanges) { @@ -174,7 +169,7 @@ function History() { .getByDocumentId(document.id) .filter((revision: Revision) => revision.id !== latestRevisionId) .slice(0, revisionsOffset); - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [document, revisions.orderedData, revisionsOffset]); // The revisions list is lightweight and omits document content, so load the @@ -203,12 +198,51 @@ function History() { (latestRevision.title !== document.title || (!!latestRevision.data && !isEqual(latestRevision.data, document.data))); + // The entry for the current content, the top revision only once it is known to match. + const currentRevisionId = + isDocUpdated || !latestRevision?.data || latestRevision.deletedAt + ? "latest" + : latestRevision.id; + + const handleCompareToChange = React.useCallback( + (value: string) => { + const changes = { + compareTo: value === COMPARE_TO_PREVIOUS ? null : value, + }; + setCompareTo(value); + + if (selectedRevisionId || !document || document.isDeleted) { + updateLocation(changes); + return; + } + + // With no revision selected, compare against the current version. + prevSelectedRef.current = currentRevisionId; + history.push({ + pathname: documentHistoryPath(document, currentRevisionId), + search: queryString.stringify( + { ...queryString.parse(history.location.search), ...changes }, + { skipNull: true } + ), + state: { sidebarContext, retainScrollPosition: true }, + }); + }, + [ + currentRevisionId, + document, + history, + selectedRevisionId, + sidebarContext, + updateLocation, + ] + ); + const nonRevisionEvents = React.useMemo( () => document ? events.getByDocumentId(document.id).slice(0, eventsOffset) : [], - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps [document, events.orderedData, eventsOffset] ); @@ -261,7 +295,7 @@ function History() { onShowChangesToggle={handleShowChangesToggle} items={items} document={document} - selectedRevisionId={selectedRevisionId} + selectedRevisionId={selectedRevisionId ?? currentRevisionId} compareTo={compareTo} onCompareToChange={handleCompareToChange} /> diff --git a/app/scenes/Document/components/MarkAsViewed.ts b/app/scenes/Document/components/MarkAsViewed.ts index 9d95726ffb..3e668fc174 100644 --- a/app/scenes/Document/components/MarkAsViewed.ts +++ b/app/scenes/Document/components/MarkAsViewed.ts @@ -1,5 +1,8 @@ -import { useRef, useEffect } from "react"; +import { useRef, useEffect, useState } from "react"; +import useConsumeQueryParam from "~/hooks/useConsumeQueryParam"; import type Document from "~/models/Document"; +import { SuppressViewParam } from "~/utils/suppressView"; +import { isTruthyQueryValue } from "~/utils/urls"; const MARK_AS_VIEWED_AFTER = 3 * 1000; type Props = { @@ -10,8 +13,19 @@ type Props = { function MarkAsViewed(props: Props) { const { document, children } = props; const viewTimeout = useRef<ReturnType<typeof setTimeout> | null>(null); + const suppress = isTruthyQueryValue(useConsumeQueryParam(SuppressViewParam)); + + // Only the document that was linked to is suppressed, not any navigated to + // afterwards. + const [suppressedDocumentId] = useState(() => + suppress ? document.id : undefined + ); useEffect(() => { + if (document.id === suppressedDocumentId) { + return; + } + viewTimeout.current = setTimeout(async () => { const view = await document.view(); @@ -25,7 +39,7 @@ function MarkAsViewed(props: Props) { clearTimeout(viewTimeout.current); } }; - }, [document]); + }, [document, suppressedDocumentId]); return children || null; } diff --git a/app/scenes/Document/components/MultiplayerEditor.tsx b/app/scenes/Document/components/MultiplayerEditor.tsx index 6e407259cd..3c85dba71e 100644 --- a/app/scenes/Document/components/MultiplayerEditor.tsx +++ b/app/scenes/Document/components/MultiplayerEditor.tsx @@ -18,12 +18,12 @@ import { EditorUpdateError } from "@shared/collaboration/CloseEvents"; import History from "@shared/editor/extensions/History"; import EDITOR_VERSION from "@shared/editor/version"; import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper"; -import { supportsPassiveListener } from "@shared/utils/browser"; import type { Props as EditorProps } from "~/components/Editor"; import { useDocumentContext } from "~/components/DocumentContext"; import Editor from "~/components/Editor"; import type { Editor as SharedEditor } from "~/editor"; import MultiplayerExtension from "~/editor/extensions/Multiplayer"; +import { MultiplayerUndo } from "~/editor/extensions/MultiplayerUndo"; import env from "~/env"; import useCurrentUser from "~/hooks/useCurrentUser"; import useIdle from "~/hooks/useIdle"; @@ -110,11 +110,7 @@ function MultiplayerEditor({ onSynced, ref, ...props }: Props) { window.addEventListener("click", finishObserving); window.addEventListener("wheel", finishObserving); - window.addEventListener( - "scroll", - syncScrollPosition, - supportsPassiveListener ? { passive: true } : false - ); + window.addEventListener("scroll", syncScrollPosition, { passive: true }); provider.on("authenticationFailed", () => { provider.shouldConnect = false; @@ -248,7 +244,7 @@ function MultiplayerEditor({ onSynced, ref, ...props }: Props) { }; // `token` is intentionally omitted, it is only read when establishing the // connection and a refreshed token must not tear down the provider. - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps }, [ history, t, @@ -275,8 +271,8 @@ function MultiplayerEditor({ onSynced, ref, ...props }: Props) { return props.extensions; } - // The Yjs undo manager (added by the Multiplayer extension below) is the - // sole source of undo/redo history when collaborating. + // The Yjs undo manager (added by MultiplayerUndo below) is the sole source + // of undo/redo history when collaborating. return [ ...(props.extensions || []).filter( (extension) => extension !== History && !(extension instanceof History) @@ -286,6 +282,7 @@ function MultiplayerEditor({ onSynced, ref, ...props }: Props) { provider: remoteProvider, document: ydoc, }), + MultiplayerUndo, ]; }, [remoteProvider, user, ydoc, props.extensions]); diff --git a/app/scenes/Document/components/PresentationMode.tsx b/app/scenes/Document/components/PresentationMode.tsx index 602e30ca07..e9e6ca3d4e 100644 --- a/app/scenes/Document/components/PresentationMode.tsx +++ b/app/scenes/Document/components/PresentationMode.tsx @@ -5,6 +5,7 @@ import { ShrinkIcon, GrowIcon, CloseIcon } from "outline-icons"; import styled, { useTheme } from "styled-components"; import Icon from "@shared/components/Icon"; import { richExtensions } from "@shared/editor/nodes"; +import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; import { canUseElementFullscreen } from "@shared/utils/browser"; import { s, depths, hover } from "@shared/styles"; import { cloneDeep } from "es-toolkit/compat"; @@ -293,7 +294,7 @@ function PresentationMode({ title, icon, iconColor, data, onClose }: Props) { <Container ref={containerRef} $background={theme.background} $idle={isIdle}> <TopBar $idle={isIdle}> <Flex align="center" gap={12}> - <Tooltip content={t("Previous slide")} delay={500}> + <Tooltip content={t("Previous slide")}> <Button onClick={goPrev} disabled={currentSlide === 0}> <ArrowLeftIcon /> </Button> @@ -301,7 +302,7 @@ function PresentationMode({ title, icon, iconColor, data, onClose }: Props) { <SlideCounter> {currentSlide + 1} / {totalSlides} </SlideCounter> - <Tooltip content={t("Next slide")} delay={500}> + <Tooltip content={t("Next slide")}> <Button onClick={goNext} disabled={currentSlide === totalSlides - 1} @@ -312,7 +313,7 @@ function PresentationMode({ title, icon, iconColor, data, onClose }: Props) { </Flex> <RightButtons> {supportsFullscreen && ( - <Tooltip content={t("Toggle fullscreen")} delay={500}> + <Tooltip content={t("Toggle fullscreen")}> <Button onClick={toggleFullscreen}> {isFullscreen ? ( <ShrinkIcon color="currentColor" /> @@ -322,7 +323,7 @@ function PresentationMode({ title, icon, iconColor, data, onClose }: Props) { </Button> </Tooltip> )} - <Tooltip content={t("Close")} delay={500}> + <Tooltip content={t("Close")}> <Button onClick={onClose}> <CloseIcon /> </Button> @@ -425,9 +426,9 @@ const SlideContent = styled.div` font-size: 1.4em; } - .image-wrapper, - .image-wrapper img, - .mermaid-diagram-wrapper { + .${EditorStyleHelper.imageWrapper}, + .${EditorStyleHelper.imageWrapper} img, + .${EditorStyleHelper.mermaidDiagram} { pointer-events: none !important; } @@ -479,10 +480,9 @@ const TopBar = styled.div<{ $idle: boolean }>` transition: opacity 300ms ease; `; -const SlideCounter = styled(Text)` +const SlideCounter = styled(Text).attrs({ size: "small" })` font-variant-numeric: tabular-nums; color: ${s("textTertiary")}; - font-size: 14px; min-width: 60px; text-align: center; `; diff --git a/app/scenes/Document/components/ReferenceListItem.tsx b/app/scenes/Document/components/ReferenceListItem.tsx index 17259c84cc..114499c932 100644 --- a/app/scenes/Document/components/ReferenceListItem.tsx +++ b/app/scenes/Document/components/ReferenceListItem.tsx @@ -3,7 +3,7 @@ import { CheckmarkIcon, DocumentIcon, PlusIcon } from "outline-icons"; import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; import styled, { css } from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import EventBoundary from "@shared/components/EventBoundary"; import Icon from "@shared/components/Icon"; import { s, hover, ellipsis } from "@shared/styles"; @@ -238,7 +238,8 @@ function ReferenceListItem({ const { icon, color } = document; const isEmoji = determineIconType(icon) === IconType.Emoji; const title = - document instanceof Document ? document.titleWithDefault : document.title; + document instanceof Document ? document.displayTitle : document.title; + const path = document instanceof Document ? document.path : document.url; const initial = title.charAt(0).toUpperCase(); const showContextMenu = document instanceof Document && !!user; @@ -280,9 +281,7 @@ function ReferenceListItem({ $menuOpen={menuOpen} $selectable={selectable} to={{ - pathname: shareId - ? sharedModelPath(shareId, document.url) - : document.url, + pathname: shareId ? sharedModelPath(shareId, path) : path, hash: anchor ? `d-${anchor}` : undefined, state: { title: document.title, diff --git a/app/scenes/Document/components/References.tsx b/app/scenes/Document/components/References.tsx index f55e4bc185..8a6e170538 100644 --- a/app/scenes/Document/components/References.tsx +++ b/app/scenes/Document/components/References.tsx @@ -33,7 +33,7 @@ function References({ document }: Props) { const [activeTab, setActiveTab] = useState<TabType>("children"); const isJustCreated = useMemo( () => document.isJustCreated, - // eslint-disable-next-line react-hooks/exhaustive-deps + // oxlint-disable-next-line react-hooks/exhaustive-deps [document.id] ); @@ -196,11 +196,11 @@ function useChildren( function useBacklinks( document: Document, sharedTree: NavigationNode | undefined -): Document[] { +): (Document | NavigationNode)[] { if (sharedTree) { return flattenTree(sharedTree).filter((node) => document.backlinkIds?.includes(node.id) - ) as Document[]; + ); } return document.backlinks; } 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 ( - <Tooltip - content={t("Clear search highlight")} - shortcut="Esc" - placement="bottom" - > + <Tooltip content={t("Clear search highlight")} shortcut="Esc" side="bottom"> <Chip type="button" onClick={handleClick} diff --git a/app/scenes/Document/components/ShareButton.tsx b/app/scenes/Document/components/ShareButton.tsx index 91f09921fe..47c00eafaf 100644 --- a/app/scenes/Document/components/ShareButton.tsx +++ b/app/scenes/Document/components/ShareButton.tsx @@ -10,13 +10,14 @@ import { PopoverContent, } from "~/components/primitives/Popover"; import useMobile from "~/hooks/useMobile"; +import useClickIntent from "~/hooks/useClickIntent"; import useShareDataLoader from "~/hooks/useShareDataLoader"; import useStores from "~/hooks/useStores"; import { preventDefault } from "~/utils/events"; import lazyWithRetry from "@shared/utils/lazyWithRetry"; const SharePopover = lazyWithRetry( - () => 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]); @@ -63,7 +74,13 @@ function ShareButton({ document }: Props) { return ( <Popover open={open} onOpenChange={handleOpenChange}> <PopoverTrigger> - <Button icon={icon} neutral onMouseEnter={preload}> + <Button + ref={intentRef} + icon={icon} + neutral + onMouseEnter={handleMouseEnter} + onMouseLeave={handleMouseLeave} + > {t("Share")} {domain && <>· {domain}</>} </Button> </PopoverTrigger> diff --git a/app/scenes/Document/components/SharedHeader.tsx b/app/scenes/Document/components/SharedHeader.tsx index a31a26c310..4a0047d437 100644 --- a/app/scenes/Document/components/SharedHeader.tsx +++ b/app/scenes/Document/components/SharedHeader.tsx @@ -92,7 +92,7 @@ function SharedDocumentHeader({ document }: Props) { : `${t("Show contents")} (${t("available when headings are added")})` } shortcut={`Ctrl+${altDisplay}+h`} - placement="bottom" + side="bottom" > <TocButton aria-label={t("Show contents")} @@ -126,11 +126,7 @@ function SharedDocumentHeader({ document }: Props) { } hasSidebar={hasSidebar} left={ - isMobile ? ( - hasHeadings ? ( - <TableOfContentsMenu /> - ) : null - ) : hasSidebar ? ( + isMobile ? null : hasSidebar ? ( <PublicBreadcrumb documentId={document.id} shareId={shareId} @@ -145,6 +141,11 @@ function SharedDocumentHeader({ document }: Props) { actions={ <> <SearchHighlightChip /> + {hasHeadings && isMobile && ( + <Action> + <TableOfContentsMenu /> + </Action> + )} {hasHeadings && !isMobile && !tocInLeft && <Action>{toc}</Action>} {allowSubscriptions !== false && env.EMAIL_ENABLED && ( <SubscribeAction shareId={shareId} documentId={document.id} /> diff --git a/app/scenes/Document/components/SizeWarning.tsx b/app/scenes/Document/components/SizeWarning.tsx index f3b8570bfe..019f4e15c4 100644 --- a/app/scenes/Document/components/SizeWarning.tsx +++ b/app/scenes/Document/components/SizeWarning.tsx @@ -1,7 +1,7 @@ import { WarningIcon } from "outline-icons"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { DocumentValidation } from "@shared/validations"; import type Document from "~/models/Document"; import Fade from "~/components/Fade"; @@ -27,7 +27,7 @@ export const SizeWarning = ({ document }: Props) => { <Centered> <strong>{t("Warning")}</strong> <br /> - {t("This document is large which may affect performance")} + {t("This document is large, which may affect performance")} </Centered> } > diff --git a/app/scenes/Document/hooks/useDocumentSave.ts b/app/scenes/Document/hooks/useDocumentSave.ts index d32f2e64c9..ba30a17bf6 100644 --- a/app/scenes/Document/hooks/useDocumentSave.ts +++ b/app/scenes/Document/hooks/useDocumentSave.ts @@ -165,13 +165,16 @@ export function useDocumentSave({ setIsPublishing(!!options.publish); try { - const savedDocument = await document.save(undefined, options); + const savedDocument = await document.save(undefined, { + publish: options.publish, + autosave: options.autosave, + }); isEditorDirtyRef.current = false; setIsEditorDirty(false); if (options.done) { history.push({ - pathname: savedDocument.url, + pathname: savedDocument.path, state: { sidebarContext }, }); ui.setActiveDocument(savedDocument); @@ -325,7 +328,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 @@ -338,35 +341,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 7259f5cedb..2292ca85fe 100644 --- a/app/scenes/Document/hooks/useDocumentSidebar.tsx +++ b/app/scenes/Document/hooks/useDocumentSidebar.tsx @@ -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") ); diff --git a/app/scenes/DocumentDelete.tsx b/app/scenes/DocumentDelete.tsx index 70bc5a7afb..a8d05716b9 100644 --- a/app/scenes/DocumentDelete.tsx +++ b/app/scenes/DocumentDelete.tsx @@ -59,7 +59,10 @@ function DocumentDelete({ document, onSubmit }: Props) { } } - const path = collection ? collectionPath(collection) : homePath(); + const path = + collection && !collection.isPersonal + ? collectionPath(collection) + : homePath(); history.push(path); } @@ -104,9 +107,9 @@ function DocumentDelete({ document, onSubmit }: Props) { <Text as="p" type="secondary"> {nestedDocumentsCount < 1 ? ( <Trans - defaults="Are you sure about that? Deleting the <em>{{ documentTitle }}</em> document will delete all of its history</em>." + defaults="Are you sure about that? Deleting the <em>{{ documentTitle }}</em> document will delete all of its history." values={{ - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, }} components={{ em: <strong />, @@ -117,7 +120,7 @@ function DocumentDelete({ document, onSubmit }: Props) { count={nestedDocumentsCount} defaults="Are you sure about that? Deleting the <em>{{ documentTitle }}</em> document will delete all of its history and <em>{{ any }} nested document</em>." values={{ - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, any: nestedDocumentsCount, }} components={{ diff --git a/app/scenes/DocumentNew.tsx b/app/scenes/DocumentNew.tsx index 3bfe76a51a..03ca49e8fa 100644 --- a/app/scenes/DocumentNew.tsx +++ b/app/scenes/DocumentNew.tsx @@ -76,13 +76,13 @@ function DocumentNew() { location.state ); } catch (_err) { - toast.error(t("Couldn’t create the document, try again?")); + toast.error(t("Couldn’t create the document. Try again?")); history.goBack(); } } 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) { <Trans defaults="Are you sure you want to permanently delete the <em>{{ documentTitle }}</em> document? This action is immediate and cannot be undone." values={{ - documentTitle: document.titleWithDefault, + documentTitle: document.displayTitle, }} components={{ em: <strong />, diff --git a/app/scenes/DocumentPublish.tsx b/app/scenes/DocumentPublish.tsx index a80fd18212..95a1adf139 100644 --- a/app/scenes/DocumentPublish.tsx +++ b/app/scenes/DocumentPublish.tsx @@ -56,7 +56,7 @@ function DocumentPublish({ document }: Props) { dialogs.closeAllModals(); } catch (_err) { - toast.error(t("Couldn’t publish the document, try again?")); + toast.error(t("Couldn’t publish the document. Try again?")); } }; diff --git a/app/scenes/Drafts.tsx b/app/scenes/Drafts.tsx index a858d95587..95db69b5af 100644 --- a/app/scenes/Drafts.tsx +++ b/app/scenes/Drafts.tsx @@ -87,7 +87,7 @@ function Drafts() { <Empty> {isFiltered ? t("No documents found for your filters.") - : t("You’ve not got any drafts at the moment.")} + : t("You don’t have any drafts at the moment.")} </Empty> } fetch={documents.fetchDrafts} 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) => { ) : ( <Empty size="large"> {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." )} </Empty> )} 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 ( <CenteredContent> <PageTitle title={t("Something went wrong")} /> - <Heading>{t("Something went wrong")}</Heading> + <Title> + <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 cd76f6b209..f11654779f 100644 --- a/app/scenes/Home.tsx +++ b/app/scenes/Home.tsx @@ -24,7 +24,7 @@ enum HomeTab { Viewed = "", Popular = "popular", Updated = "recent", - Created = "created", + Edited = "edited", } function Home() { @@ -104,8 +104,8 @@ function Home() { > {t("Recently updated")} - setHomeTab(HomeTab.Created)}> - {t("Created by me")} + setHomeTab(HomeTab.Edited)}> + {t("Edited by me")} )} @@ -117,7 +117,7 @@ function Home() { {t("Weird, this shouldn't ever be empty")}} + empty={{t("Weird, this shouldn’t ever be empty")}} showCollection /> @@ -134,19 +134,16 @@ function Home() { showCollection /> - + + {t("You haven’t created any documents yet")} - } + empty={{t("You haven’t edited any documents yet")}} showCollection /> diff --git a/app/scenes/Invite.tsx b/app/scenes/Invite.tsx index a752999886..44012cac4e 100644 --- a/app/scenes/Invite.tsx +++ b/app/scenes/Invite.tsx @@ -128,13 +128,13 @@ function Invite({ onSubmit }: Props) { content={ <> {collections.nonPrivate.map((collection) => ( -
  • {collection.name}
  • +
  • {collection.displayName}
  • ))} } > - {{ collectionCount }} collections + {t("{{ count }} collection", { count: collectionCount })} .{" "} @@ -194,7 +194,7 @@ function Invite({ onSubmit }: Props) { {collectionAccessNote} {can.update && ( - As an admin you can also{" "} + As an admin, you can also{" "} enable email sign-in. )} @@ -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 f27959a7f2..8f56485405 100644 --- a/app/scenes/Login/Login.tsx +++ b/app/scenes/Login/Login.tsx @@ -212,7 +212,7 @@ function Login({ children, onBack }: Props) { {t("Almost there")}… {t( - "Your custom domain is successfully pointing at Outline. To complete the setup process please contact support." + "Your custom domain is successfully pointing at Outline. To complete the setup process, please contact support." )} @@ -362,7 +362,7 @@ function Login({ children, onBack }: Props) { ) : ( <> - {t("Login to {{ authProviderName }}", { + {t("Log in to {{ authProviderName }}", { authProviderName: config.name || env.APP_NAME, })} @@ -445,10 +445,9 @@ const Content = styled(Text)` margin-top: -8px; `; -const Note = styled(Text)` +const Note = styled(Text).attrs({ size: "small" })` color: ${s("textTertiary")}; text-align: center; - font-size: 14px; margin-top: 8px; em { diff --git a/app/scenes/Login/OAuthAuthorize.tsx b/app/scenes/Login/OAuthAuthorize.tsx index 85b276a9b4..e43381339c 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 { isAppRootDomain } from "~/utils/urls"; +import { OAuthClientValidation } from "@shared/validations"; import type OAuthClient from "~/models/oauth/OAuthClient"; import ButtonLarge from "~/components/ButtonLarge"; import ChangeLanguage from "~/components/ChangeLanguage"; @@ -14,7 +15,7 @@ import PageTitle from "~/components/PageTitle"; import Text from "~/components/Text"; import env from "~/env"; import useCurrentTeam from "~/hooks/useCurrentTeam"; -import { useLoggedInSessions } from "~/hooks/useLoggedInSessions"; +import { useWorkspaceSessions } from "~/hooks/useWorkspaceSessions"; import useQuery from "~/hooks/useQuery"; import useRequest from "~/hooks/useRequest"; import { client } from "~/utils/ApiClient"; @@ -22,6 +23,7 @@ import { AuthorizationError, BadRequestError, NotFoundError, + UnprocessableEntityError, } from "~/utils/errors"; import isCloudHosted from "~/utils/isCloudHosted"; import { detectLanguage } from "~/utils/language"; @@ -34,8 +36,9 @@ import { TeamSwitcher } from "./components/TeamSwitcher"; import { Form } from "~/components/primitives/Form"; export default function OAuthAuthorize() { + const { t } = useTranslation(); const team = useCurrentTeam({ rejectOnEmpty: false }); - const sessions = useLoggedInSessions(); + const sessions = useWorkspaceSessions(); // We're self-hosted or on a team subdomain already, just show the authorize screen. if (team) { @@ -43,11 +46,17 @@ export default function OAuthAuthorize() { } // Cloud hosted and on root domain – show the workspace switcher. - const isAppRoot = - parseDomain(window.location.hostname).host === parseDomain(env.URL).host; - const hasLoggedInSessions = Object.keys(sessions).length > 0; - if (isCloudHosted && hasLoggedInSessions && isAppRoot) { - return ; + const hasRememberedWorkspaces = Object.keys(sessions).length > 0; + if (isCloudHosted && hasRememberedWorkspaces && isAppRootDomain()) { + return ( + + ); } return ; @@ -70,6 +79,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, @@ -101,6 +126,9 @@ function Authorize() { if (redirectUri && !clientError) { const url = new URL(redirectUri); url.searchParams.set("error", "access_denied"); + if (state) { + url.searchParams.set("state", state); + } window.location.href = url.toString(); return; } @@ -141,21 +169,28 @@ function Authorize() { {clientError instanceof NotFoundError ? ( {t( - "The OAuth client could not be found, please check the provided client ID" + "The OAuth client could not be found – please check the provided client ID" )}
    {clientId}
    ) : clientError instanceof BadRequestError ? ( {t( - "The OAuth client could not be loaded, please check the redirect URI is valid" + "The OAuth client could not be loaded – please check that the redirect URI is valid" )}
    {redirectUri}
    + ) : clientError instanceof UnprocessableEntityError ? ( + + {t( + "The OAuth client could not be loaded from its metadata document" + )} +
    {clientError.message}
    +
    ) : clientError instanceof AuthorizationError ? ( {t( - "The OAuth client could not be loaded, please check your workspace subdomain is correct" + "The OAuth client could not be loaded – please check that your workspace subdomain is correct" )}
    {clientError.message}
    @@ -182,6 +217,8 @@ function Authorize() { } const { name, developerName, developerUrl } = response.data; + const clientHost = metadataDocumentHost(response.data.clientId); + const isLoopback = isLoopbackUri(redirectUri); return ( @@ -219,6 +256,15 @@ function Authorize() { /> )} + {clientHost && ( + + }} + /> + + )} {t( "{{ appName }} will be able to access your account and perform the following actions", @@ -237,8 +283,14 @@ function Authorize() { ) )} - - {isLoopbackUri(redirectUri) ? ( + + {isLoopback && clientHost ? ( + }} + /> + ) : isLoopback ? ( You will be redirected to a local application after authorizing. @@ -249,7 +301,7 @@ function Authorize() { redirectUri, }} components={{ - em: , + em: , }} /> )} @@ -304,6 +356,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/Notices.tsx b/app/scenes/Login/components/Notices.tsx index 09cc986a47..85fd0f12d7 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,14 +57,14 @@ 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. ); case "email-auth-ratelimit": return ( - An email sign-in link was recently sent, please check your inbox or + An email sign-in link was recently sent. Please check your inbox or try again in a few minutes. ); @@ -87,7 +86,7 @@ function Message({ notice }: { notice: string }) { case "expired-token": return ( - Sorry, it looks like that sign-in link is no longer valid, please try + Sorry, it looks like that sign-in link is no longer valid. Please try requesting another. ); diff --git a/app/scenes/Login/components/PasskeyAuthenticationProvider.tsx b/app/scenes/Login/components/PasskeyAuthenticationProvider.tsx index 9ee340ea2e..64aef12792 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"; @@ -15,6 +16,8 @@ import { getCSRFToken } from "~/utils/csrf"; type Props = React.ComponentProps; +const verifyAuthenticationPath = "/auth/passkeys.verifyAuthentication"; + /** * Flattens a nested object into form field entries using bracket notation * (e.g. `response[authenticatorData]`) so the values can be rendered as hidden @@ -47,13 +50,39 @@ function flattenFormFields( return out; } +/** + * Submits the passkey authentication response with fetch and then opens the + * page that the server redirects to. The desktop app opens navigations to + * /auth/ paths in the system browser, so a native form submit cannot be used. + * + * @param fields The form fields to submit. + * @throws if the server rejects the authentication response. + */ +async function submitInApp(fields: Record) { + const response = await fetch(verifyAuthenticationPath, { + method: "POST", + body: new URLSearchParams(fields), + credentials: "same-origin", + redirect: "follow", + }); + + if (!response.ok || !response.redirected) { + const body: { message?: string } = await response.json().catch(() => ({})); + throw new Error(body.message || response.statusText); + } + + window.location.href = response.url; +} + /** * 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 +94,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 @@ -91,18 +127,22 @@ export function PasskeyAuthenticationProvider(props: Props) { ); const { challengeId, ...optionsData } = resp.data; const authResp = await startAuthentication(optionsData); + const formFields = flattenFormFields({ + ...authResp, + challengeId, + [CSRF.fieldName]: getCSRFToken(), + client: verifyClient, + }); + + if (Desktop.isElectron()) { + await submitInApp(formFields); + return; + } // Render the authentication response as hidden inputs; the effect below // submits the form natively once they're in the DOM so the browser // follows the redirect and applies cookies. - setFields( - flattenFormFields({ - ...authResp, - challengeId, - [CSRF.fieldName]: getCSRFToken(), - client: verifyClient, - }) - ); + setFields(formFields); } catch (err) { toast.error(errToString(err)); // Re-enable the button so the user can retry; on success the form submits @@ -128,14 +168,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; } @@ -147,7 +192,7 @@ export function PasskeyAuthenticationProvider(props: Props) {
    {fields && @@ -172,6 +217,11 @@ export function PasskeyAuthenticationProvider(props: Props) { )}
    + {isSupportedInApp && hasError && ( + + {t("Use a passkey from your browser")} + + )} ); } @@ -180,6 +230,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/SigningIn.tsx b/app/scenes/Login/components/SigningIn.tsx index cf16eb3fe0..22675fd02a 100644 --- a/app/scenes/Login/components/SigningIn.tsx +++ b/app/scenes/Login/components/SigningIn.tsx @@ -29,10 +29,9 @@ export function SigningIn() { ); } -const Note = styled(Text)` +const Note = styled(Text).attrs({ size: "small" })` color: ${s("textTertiary")}; text-align: center; - font-size: 14px; margin-top: 8px; em { diff --git a/app/scenes/Login/components/TeamSwitcher.tsx b/app/scenes/Login/components/TeamSwitcher.tsx index 842621bb86..76fe08a407 100644 --- a/app/scenes/Login/components/TeamSwitcher.tsx +++ b/app/scenes/Login/components/TeamSwitcher.tsx @@ -4,25 +4,38 @@ import { useTranslation } from "react-i18next"; import styled from "styled-components"; import Text from "@shared/components/Text"; import { s } from "@shared/styles"; +import type { Sessions } from "@shared/utils/sessions"; +import { isSessionActive } from "@shared/utils/sessions"; +import { sanitizeUrl } from "@shared/utils/urls"; import { AvatarSize } from "~/components/Avatar"; import Avatar, { AvatarVariant } from "~/components/Avatar/Avatar"; import ChangeLanguage from "~/components/ChangeLanguage"; import Heading from "~/components/Heading"; import OutlineIcon from "~/components/Icons/OutlineIcon"; import env from "~/env"; -import type { Sessions } from "~/hooks/useLoggedInSessions"; import { detectLanguage } from "~/utils/language"; import Login from "../Login"; import { Background } from "./Background"; import { Centered } from "./Centered"; -type Props = { sessions: Sessions }; +interface Props { + /** The remembered workspaces, including logged-out ones. */ + sessions: Sessions; + /** Text shown below the heading, defaults to a generic prompt. */ + description?: string; +} -export function TeamSwitcher({ sessions }: Props) { +/** + * Shows remembered workspaces so the user can choose which one to continue to + * with the current path, with a login path for logged-out sessions. + * + * @param props the remembered workspace sessions and optional description. + * @returns the workspace selector. + */ +export function TeamSwitcher({ sessions, description }: Props) { const { t } = useTranslation(); const [showLogin, setShowLogin] = useState(false); - const url = new URL(window.location.href); - const appName = env.APP_NAME; + const { pathname, search } = window.location; if (showLogin) { return setShowLogin(false)} />; @@ -36,17 +49,17 @@ export function TeamSwitcher({ sessions }: Props) { {t("Choose a workspace")} - {t( - "Choose an {{ appName }} workspace or login to continue connecting this app", - { appName } - )} + {description ?? + t("Choose an {{ appName }} workspace or log in to continue", { + appName: env.APP_NAME, + })} . - {Object.keys(sessions)?.map((teamId) => { + {Object.keys(sessions).map((teamId) => { const session = sessions[teamId]; - const location = session.url + url.pathname + url.search; + const location = sanitizeUrl(session.url + pathname + search); return ( - + - {session.name} + + {session.name} + {!isSessionActive(session) && ( + + {t("Logged out")} + + )} + ); })} setShowLogin(true)}> - {t("Login to workspace")} + {t("Log in to workspace")}
    @@ -77,6 +97,11 @@ const StyledArrowIcon = styled(ArrowIcon)` right: 12px; `; +const WorkspaceName = styled.span` + display: flex; + flex-direction: column; +`; + const TeamLink = styled.a` position: relative; left: -8px; 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/Search.tsx b/app/scenes/Search/Search.tsx index 6f91173b14..7dd9c6b8f0 100644 --- a/app/scenes/Search/Search.tsx +++ b/app/scenes/Search/Search.tsx @@ -3,10 +3,9 @@ import { v4 as uuidv4 } from "uuid"; import queryString from "query-string"; import * as React from "react"; import { useTranslation } from "react-i18next"; -import { useHistory, useLocation, useRouteMatch } from "react-router-dom"; -import { Waypoint } from "react-waypoint"; +import { useHistory, useRouteMatch } from "react-router-dom"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { Pagination } from "@shared/constants"; import type { Filter } from "@shared/helpers/FilterHelper"; import { DURATION_BY_DATE_FILTER } from "@shared/helpers/FilterHelper"; @@ -27,7 +26,7 @@ import RegisterKeyDown from "~/components/RegisterKeyDown"; import Scene from "~/components/Scene"; import Switch from "~/components/Switch"; import Text from "~/components/Text"; -import env from "~/env"; +import { Waypoint } from "~/components/Waypoint"; import usePaginatedRequest from "~/hooks/usePaginatedRequest"; import useQuery from "~/hooks/useQuery"; import useStores from "~/hooks/useStores"; @@ -53,7 +52,6 @@ function Search() { // routing const params = useQuery(); - const location = useLocation(); const history = useHistory(); const routeMatch = useRouteMatch<{ query: string }>(); const handleGoBack = React.useCallback(() => history.goBack(), [history]); @@ -220,12 +218,14 @@ function Search() { const updateLocation = (query: string) => { // If query came from route params, navigate to base search path - const pathname = routeMatch.params.query ? searchPath() : location.pathname; + const pathname = routeMatch.params.query + ? searchPath() + : history.location.pathname; history.replace({ pathname, search: queryString.stringify( - { ...queryString.parse(location.search), q: query }, + { ...queryString.parse(history.location.search), q: query }, { skipEmptyString: true, } @@ -251,9 +251,9 @@ function Search() { } history.replace({ - pathname: location.pathname, + pathname: history.location.pathname, search: queryString.stringify( - { ...queryString.parse(location.search), ...search }, + { ...queryString.parse(history.location.search), ...search }, { skipEmptyString: true, } @@ -447,7 +447,6 @@ function Search() { 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/SearchInput.tsx b/app/scenes/Search/components/SearchInput.tsx index 99e22edd01..df61fa074e 100644 --- a/app/scenes/Search/components/SearchInput.tsx +++ b/app/scenes/Search/components/SearchInput.tsx @@ -61,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")}; } `; diff --git a/app/scenes/Settings/AI.tsx b/app/scenes/Settings/AI.tsx new file mode 100644 index 0000000000..6f6f61ef11 --- /dev/null +++ b/app/scenes/Settings/AI.tsx @@ -0,0 +1,160 @@ +import { observer } from "mobx-react"; +import { CopyIcon, SparklesIcon } from "outline-icons"; +import * as React from "react"; +import { useTranslation, Trans } from "react-i18next"; +import { toast } from "sonner"; +import { TeamPreference } from "@shared/types"; +import { TeamValidation } from "@shared/validations"; +import Heading from "~/components/Heading"; +import Scene from "~/components/Scene"; +import Switch from "~/components/Switch"; +import Text from "~/components/Text"; +import useCurrentTeam from "~/hooks/useCurrentTeam"; +import SettingRow from "./components/SettingRow"; +import { SettingsSection } from "./components/SettingsSection"; +import Input from "~/components/Input"; +import Tooltip from "~/components/Tooltip"; +import CopyToClipboard from "~/components/CopyToClipboard"; +import NudeButton from "~/components/NudeButton"; +import { useTheme } from "styled-components"; + +function AI() { + const { t } = useTranslation(); + const team = useCurrentTeam(); + const theme = useTheme(); + + const handleMCPChange = React.useCallback( + async (checked: boolean) => { + team.setPreference(TeamPreference.MCP, checked); + await team.save(); + toast.success(t("Settings saved")); + }, + [team, t] + ); + + const handleGuidanceMCPChange = React.useCallback( + async (ev: React.ChangeEvent) => { + team.guidanceMCP = ev.target.value || null; + }, + [team] + ); + + const handleGuidanceMCPBlur = React.useCallback(async () => { + await team.save(); + toast.success(t("Settings saved")); + }, [team, t]); + + const handleCopied = React.useCallback(() => { + toast.success(t("Copied to clipboard")); + }, [t]); + + const mcpEndpoint = window.location.origin + "/mcp"; + + return ( + }> + {t("AI")} + + Control how AI features are used in the workspace. + + + + + + {t( + "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) && ( + <> + + + ), + }} + /> + + + + + + + + + + + + )} + + } + > + + + + {team.getPreference(TeamPreference.MCP) && ( + +
    + {t( + "Optional instructions that are sent to connected AI apps, for example how your workspace is organized or where to find important information." + )} +
    + + + } + /> + )} +
    + + + + + + +
    + ); +} + +export default observer(AI); diff --git a/app/scenes/Settings/APIAndAccess.tsx b/app/scenes/Settings/APIAndAccess.tsx index 66dd25b566..52b3fa702f 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/Applications.tsx b/app/scenes/Settings/Applications.tsx index 5e8ea5f455..dbd05f1015 100644 --- a/app/scenes/Settings/Applications.tsx +++ b/app/scenes/Settings/Applications.tsx @@ -41,7 +41,7 @@ function Applications() { {t("Applications")} {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")} + + {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); - {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", - { + return ( + + + {provider.displayName} + + } + name={provider.name} + description={ + provider.isConnected + ? t("Allow members to sign in with {{ authProvider }}", { authProvider: provider.displayName, - } - ) - } - border={!showGroupSync} - > - - {provider.isConnected ? ( - + }) + : t( + "Connect {{ authProvider }} to allow members to sign in", + { + authProvider: provider.displayName, + } + ) + } + border={!showGroupSync} + > + + {provider.isConnected ? ( + + + + {provider.providerId} + + + ) : ( - - {provider.providerId} - - - ) : ( - - )} - - - {showGroupSync && ( - - {provider.groupSyncRequiresSetup && - !provider.settings?.groupSyncEnabled ? ( - - ) : ( - - handleToggleGroupSync(provider, checked) - } - /> - )} - - )} - {showGroupSync && - 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) } - }} - /> + /> + )} )} - - ); - })} - - {t("Email")} - - } - name="guestSignin" - description={ - env.EMAIL_ENABLED - ? t("Allow members to sign-in using their email address") - : t("The server must have SMTP configured to enable this setting") - } - border={false} - > - - + {showGroupSync && + provider.groupSyncUsesClaim && + provider.settings?.groupSyncEnabled && ( + + ) => { + const value = ev.target.value.trim(); + if (value !== (provider.settings?.groupClaim ?? "")) { + void handleGroupClaimChange(provider, value); + } + }} + /> + + )} + + ); + })} + + {t("Email")} + + } + name="guestSignin" + description={ + env.EMAIL_ENABLED + ? t("Allow members to sign in using their email address") + : t("The server must have SMTP configured to enable this setting") + } + > + + - - {t("Passkeys")} - - } - name="passkeysEnabled" - description={t("Allow members to sign-in with a WebAuthn passkey")} - > - { - try { - await team.save({ passkeysEnabled: checked }); - toast.success(t("Settings saved")); - } catch (err) { - toast.error(errToString(err)); - } - }} - /> - + + {t("Passkeys")} + + } + name="passkeysEnabled" + description={t("Allow members to sign in with a WebAuthn passkey")} + > + { + try { + await team.save({ passkeysEnabled: checked }); + toast.success(t("Settings saved")); + } catch (err) { + toast.error(errToString(err)); + } + }} + /> + + - {t("Restrictions")} - + + + ); } diff --git a/app/scenes/Settings/CustomEmojis.tsx b/app/scenes/Settings/CustomEmojis.tsx index 00245ff67f..d81f930e0d 100644 --- a/app/scenes/Settings/CustomEmojis.tsx +++ b/app/scenes/Settings/CustomEmojis.tsx @@ -4,7 +4,7 @@ import { PlusIcon, SmileyIcon } from "outline-icons"; import type * as React from "react"; import { useState, useMemo, useCallback, useEffect } from "react"; import { useTranslation } from "react-i18next"; -import { useHistory, useLocation } from "react-router-dom"; +import { useHistory } from "react-router-dom"; import { toast } from "sonner"; import { Action } from "~/components/Actions"; import Button from "~/components/Button"; @@ -24,7 +24,6 @@ import { StickyFilters } from "./components/StickyFilters"; import type EmojisStore from "~/stores/EmojiStore"; function Emojis() { - const location = useLocation(); const history = useHistory(); const team = useCurrentTeam(); const { emojis } = useStores(); @@ -71,11 +70,11 @@ function Emojis() { } history.replace({ - pathname: location.pathname, + pathname: history.location.pathname, search: params.toString(), }); }, - [params, history, location.pathname] + [params, history] ); const handleSearch = useCallback( diff --git a/app/scenes/Settings/Details.tsx b/app/scenes/Settings/Details.tsx index 089817f1f0..544722edf0 100644 --- a/app/scenes/Settings/Details.tsx +++ b/app/scenes/Settings/Details.tsx @@ -1,45 +1,52 @@ import { isHexColor } from "class-validator"; -import { pickBy } from "es-toolkit/compat"; +import { debounce, pickBy } from "es-toolkit/compat"; import { observer } from "mobx-react"; import { TeamIcon } from "outline-icons"; -import { useRef, useState } from "react"; +import { useState } from "react"; import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; import { ThemeProvider } from "styled-components"; import { errToString } from "@shared/utils/error"; import { buildDarkTheme, buildLightTheme } from "@shared/styles/theme"; -import type { CustomTheme } from "@shared/types"; -import { TOCPosition, TeamPreference } from "@shared/types"; +import type { CustomTheme, TeamPreferences } from "@shared/types"; +import { TOCPosition, TeamPreference, UserPreference } from "@shared/types"; import { getBaseDomain } from "@shared/utils/domains"; import { TeamValidation } from "@shared/validations"; +import { AvatarVariant } from "~/components/Avatar/Avatar"; import Button from "~/components/Button"; import ButtonLink from "~/components/ButtonLink"; import DefaultCollectionInputSelect from "~/components/DefaultCollectionInputSelect"; import Heading from "~/components/Heading"; import Input from "~/components/Input"; -import InputColor from "~/components/InputColor"; import type { Option } from "~/components/InputSelect"; import { InputSelect } from "~/components/InputSelect"; import Scene from "~/components/Scene"; import Switch from "~/components/Switch"; import Text from "~/components/Text"; import useCurrentTeam from "~/hooks/useCurrentTeam"; +import useCurrentUser from "~/hooks/useCurrentUser"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; +import type Team from "~/models/Team"; import isCloudHosted from "~/utils/isCloudHosted"; import TeamDelete from "../TeamDelete"; -import { ActionRow } from "./components/ActionRow"; import ImageInput from "./components/ImageInput"; import SettingRow from "./components/SettingRow"; +import { SettingsSection } from "./components/SettingsSection"; +import { ThemeColorInputs } from "./components/ThemeColorInputs"; + +type TeamUpdate = Partial< + Pick +> & { preferences?: TeamPreferences }; function Details() { const { dialogs, ui } = useStores(); const { t } = useTranslation(); const team = useCurrentTeam(); + const user = useCurrentUser(); const can = usePolicy(team); - const form = useRef(null); const [accent, setAccent] = useState( team.preferences?.customTheme?.accent ); @@ -49,23 +56,17 @@ function Details() { const [name, setName] = useState(team.name); const [description, setDescription] = useState(team.description || ""); const [subdomain, setSubdomain] = useState(team.subdomain); - const [publicBranding, setPublicBranding] = useState( - team.preferences?.publicBranding - ); - const [defaultCollectionId, setDefaultCollectionId] = useState( - team.defaultCollectionId - ); - const customTheme: Partial = pickBy( - { - accent, - accentText, - }, - isHexColor - ); - - const [tocPosition, setTocPosition] = useState( - team.getPreference(TeamPreference.TocPosition) as TOCPosition + const customTheme: Partial = React.useMemo( + () => + pickBy( + { + accent, + accentText, + }, + isHexColor + ), + [accent, accentText] ); const tocPositionOptions: Option[] = React.useMemo( @@ -85,47 +86,103 @@ function Details() { [t] ); - const handleTocPositionChange = React.useCallback((position: string) => { - setTocPosition(position as TOCPosition); - }, []); - - const handleSubmit = React.useCallback( - async (event?: React.SyntheticEvent) => { - if (event) { - event.preventDefault(); - } - - try { - await team.save({ - name, - description, - subdomain, - defaultCollectionId, - preferences: { - ...team.preferences, - publicBranding, - customTheme, - tocPosition, - }, - }); + const showSuccessMessage = React.useMemo( + () => + debounce(() => { toast.success(t("Settings saved")); + }, 250), + [t] + ); + + const saveData = React.useCallback( + async (data: TeamUpdate) => { + try { + await team.save(data); + showSuccessMessage(); + return true; } catch (err) { toast.error(errToString(err)); + return false; } }, - [ - tocPosition, - team, - name, - description, - subdomain, - defaultCollectionId, - publicBranding, - customTheme, - t, - ] + [team, showSuccessMessage] ); + const savePreference = React.useCallback( + (key: T, value: TeamPreferences[T]) => + saveData({ preferences: { [key]: value } }), + [saveData] + ); + + const saveTheme = React.useMemo( + () => + debounce((theme: Partial) => { + void savePreference(TeamPreference.CustomTheme, theme); + }, 500), + [savePreference] + ); + + // Save a pending theme change when the user leaves the page. + React.useEffect(() => () => saveTheme.flush(), [saveTheme]); + + const handleThemeChange = React.useCallback( + ( + nextAccent: string | null | undefined, + nextText: string | null | undefined + ) => { + // Wait until every entered color is complete or empty before saving. + const isReady = (value: string | null | undefined) => + !value || value === "#" || isHexColor(value); + if (!isReady(nextAccent) || !isReady(nextText)) { + return; + } + saveTheme( + pickBy({ accent: nextAccent, accentText: nextText }, isHexColor) + ); + }, + [saveTheme] + ); + + const handleAccentChange = React.useCallback( + (value: string) => { + setAccent(value); + handleThemeChange(value, accentText); + }, + [accentText, handleThemeChange] + ); + + const handleAccentTextChange = React.useCallback( + (value: string) => { + setAccentText(value); + handleThemeChange(accent, value); + }, + [accent, handleThemeChange] + ); + + const handleResetTheme = React.useCallback(() => { + setAccent(null); + setAccentText(null); + saveTheme.cancel(); + void savePreference(TeamPreference.CustomTheme, {}); + }, [saveTheme, savePreference]); + + const handleSubmit = React.useCallback((ev: React.FormEvent) => { + ev.preventDefault(); + }, []); + + const handleKeyDown = React.useCallback((ev: React.KeyboardEvent) => { + // Text fields save on blur, so Enter saves the focused field. + if ( + ev.key === "Enter" && + !ev.nativeEvent.isComposing && + ev.target instanceof HTMLInputElement && + ev.currentTarget.contains(ev.target) + ) { + ev.preventDefault(); + ev.target.blur(); + } + }, []); + const handleNameChange = React.useCallback( (ev: React.ChangeEvent) => { setName(ev.target.value); @@ -133,6 +190,31 @@ function Details() { [] ); + const handleNameBlur = React.useCallback(async () => { + if (name === team.name) { + return; + } + if (!name.trim() || !(await saveData({ name }))) { + setName(team.name); + } + }, [name, team, saveData]); + + const handleDescriptionChange = React.useCallback( + (ev: React.ChangeEvent) => { + setDescription(ev.target.value); + }, + [] + ); + + const handleDescriptionBlur = React.useCallback(async () => { + if (description === (team.description || "")) { + return; + } + if (!(await saveData({ description }))) { + setDescription(team.description || ""); + } + }, [description, team, saveData]); + const handleSubdomainChange = React.useCallback( (ev: React.ChangeEvent) => { setSubdomain(ev.target.value.toLowerCase()); @@ -140,6 +222,33 @@ function Details() { [] ); + const handleSubdomainBlur = React.useCallback(async () => { + if (subdomain === team.subdomain) { + return; + } + if (!(await saveData({ subdomain }))) { + setSubdomain(team.subdomain); + } + }, [subdomain, team, saveData]); + + const handlePublicBrandingChange = React.useCallback( + (checked: boolean) => + savePreference(TeamPreference.PublicBranding, checked), + [savePreference] + ); + + const handleTocPositionChange = React.useCallback( + (position: string) => + savePreference(TeamPreference.TocPosition, position as TOCPosition), + [savePreference] + ); + + const handleSelectCollection = React.useCallback( + (value: string) => + saveData({ defaultCollectionId: value === "home" ? null : value }), + [saveData] + ); + const handleAvatarChange = async (avatarUrl: string | null) => { await team.save({ avatarUrl }); toast.success(t("Logo updated")); @@ -159,21 +268,24 @@ function Details() { }); }; - const onSelectCollection = React.useCallback((value: string) => { - const selectedValue = value === "home" ? null : value; - setDefaultCollectionId(selectedValue); - }, []); - const handleSeamlessEditChange = React.useCallback( async (checked: boolean) => { - team.setPreference(TeamPreference.SeamlessEdit, !checked); - await team.save(); - toast.success(t("Settings saved")); - }, - [team, t] - ); + if (!(await savePreference(TeamPreference.SeamlessEdit, !checked))) { + return; + } - const isValid = form.current?.checkValidity(); + // Enabling separate editing also applies it to the current user. + if (checked) { + try { + user.setPreference(UserPreference.SeamlessEdit, false); + await user.save(); + } catch (err) { + toast.error(errToString(err)); + } + } + }, + [savePreference, user] + ); const newTheme = React.useMemo( () => @@ -185,8 +297,8 @@ function Details() { return ( - }> - {t("Details")} + }> + {t("General")} These settings affect the way that your workspace appears to @@ -194,214 +306,192 @@ function Details() { -
    - {t("Display")} - - - - - - - - ) => { - setDescription(ev.target.value); - }} - maxLength={TeamValidation.maxDescriptionLength} - showCharacterCount - /> - - - {t("Customize the interface look and feel.")}{" "} - {accent && ( - <> - { - setAccent(null); - setAccentText(null); - }} - > + + + + + + + + + + + + + {t("Customize the interface look and feel.")}{" "} + {accent && ( + {t("Reset theme")} - + )} + + } + > + + + {(team.avatarUrl || team.description) && ( + - } - > - - - - {(team.avatarUrl || team.description) && ( + > + + + )} + + + + + + + Your workspace will be accessible at{" "} + + {subdomain}.{getBaseDomain()} + + + ) : ( + t( + "Choose a subdomain to enable a login page just for your team." + ) + ) + } + > + + + + + + setPublicBranding(checked)} + id={TeamPreference.SeamlessEdit} + name={TeamPreference.SeamlessEdit} + checked={!team.getPreference(TeamPreference.SeamlessEdit)} + onChange={handleSeamlessEditChange} /> - )} - - - - - {t("Behavior")} - - - Your workspace will be accessible at{" "} - - {subdomain}.{getBaseDomain()} - - - ) : ( - t( - "Choose a subdomain to enable a login page just for your team." - ) - ) - } - > - - - - - - - - - - - - - - {can.delete && ( - <> -

     

    - - {t("Danger")} - - - - - - - )} +
    + + {can.delete && ( + + + + + + + + )}
    ); diff --git a/app/scenes/Settings/Embeds.tsx b/app/scenes/Settings/Embeds.tsx index f12209ed56..5b51ef5ce9 100644 --- a/app/scenes/Settings/Embeds.tsx +++ b/app/scenes/Settings/Embeds.tsx @@ -12,6 +12,7 @@ import Text from "~/components/Text"; import useCurrentTeam from "~/hooks/useCurrentTeam"; import { IntegrationScene } from "./components/IntegrationScene"; import SettingRow from "./components/SettingRow"; +import { SettingsSection } from "./components/SettingsSection"; import { HStack } from "~/components/primitives/HStack"; /** List of embed providers available for configuration. */ @@ -99,15 +100,16 @@ function Embeds() { {team.documentEmbeds && ( - <> - {t("Providers")} - + Enabled providers will appear in the editor slash menu and embed automatically when a compatible link is pasted. Existing embeds in documents will continue to display regardless of these settings. - + } + > ); })} - + )} ); diff --git a/app/scenes/Settings/Export.tsx b/app/scenes/Settings/Export.tsx index b459e65752..a01978bcab 100644 --- a/app/scenes/Settings/Export.tsx +++ b/app/scenes/Settings/Export.tsx @@ -35,7 +35,7 @@ function Export() { {t("Export")} { - team.setPreference(TeamPreference.MCP, checked); - await team.save(); - toast.success(t("Settings saved")); - }, - [team, t] - ); - - const handleGuidanceMCPChange = React.useCallback( - async (ev: React.ChangeEvent) => { - team.guidanceMCP = ev.target.value || null; - }, - [team] - ); - - const handleGuidanceMCPBlur = React.useCallback(async () => { - await team.save(); - toast.success(t("Settings saved")); - }, [team, t]); - - const handleCopied = React.useCallback(() => { - toast.success(t("Copied to clipboard")); - }, [t]); - - const mcpEndpoint = window.location.origin + "/mcp"; - - return ( - }> - {t("AI")} - - Manage AI and integration features for your workspace. - - - - - {t( - "Allow members to connect to this workspace with MCP to read and write data." - )} - - {team.getPreference(TeamPreference.MCP) && ( - <> - - - ), - }} - /> - - - - - - - - - - - - )} - - } - > - - - - {team.getPreference(TeamPreference.MCP) && ( - -
    - {t( - "You can use these optional instructions to tell MCP clients how to use your knowledge base." - )} -
    - - - } - /> - )} - - - - -
    - ); -} - -export default observer(Features); diff --git a/app/scenes/Settings/GroupMembers.tsx b/app/scenes/Settings/GroupMembers.tsx index 2c0b9baaf8..9b067f7fb3 100644 --- a/app/scenes/Settings/GroupMembers.tsx +++ b/app/scenes/Settings/GroupMembers.tsx @@ -4,7 +4,7 @@ import { GroupIcon, HiddenIcon } from "outline-icons"; import { useCallback, useEffect, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { useParams } from "react-router-dom"; -import { useHistory, useLocation } from "react-router-dom"; +import { useHistory } from "react-router-dom"; import styled, { useTheme } from "styled-components"; import { toast } from "sonner"; import type User from "~/models/User"; @@ -76,7 +76,6 @@ const GroupMembersPage = observer(function GroupMembersPage({ const group = groups.get(groupId)!; const currentUser = useCurrentUser(); const history = useHistory(); - const location = useLocation(); const params = useQuery(); const [query, setQuery] = useState(""); @@ -149,11 +148,11 @@ const GroupMembersPage = observer(function GroupMembersPage({ } history.replace({ - pathname: location.pathname, + pathname: history.location.pathname, search: params.toString(), }); }, - [params, history, location.pathname] + [params, history] ); const updateQuery = useCallback( diff --git a/app/scenes/Settings/Groups.tsx b/app/scenes/Settings/Groups.tsx index 84d6d4c30a..426329e5b4 100644 --- a/app/scenes/Settings/Groups.tsx +++ b/app/scenes/Settings/Groups.tsx @@ -5,7 +5,7 @@ import { PlusIcon, GroupIcon } from "outline-icons"; import * as React from "react"; import { useState, useMemo, useCallback, useEffect } from "react"; import { useTranslation, Trans } from "react-i18next"; -import { useHistory, useLocation } from "react-router-dom"; +import { useHistory } from "react-router-dom"; import { toast } from "sonner"; import type Group from "~/models/Group"; import { Action } from "~/components/Actions"; @@ -54,7 +54,6 @@ function Groups() { const team = useCurrentTeam(); const can = usePolicy(team); const history = useHistory(); - const location = useLocation(); const params = useQuery(); const [query, setQuery] = useState(""); @@ -100,11 +99,11 @@ function Groups() { } history.replace({ - pathname: location.pathname, + pathname: history.location.pathname, search: params.toString(), }); }, - [params, history, location.pathname] + [params, history] ); const handleSourceFilter = useCallback( diff --git a/app/scenes/Settings/Import.tsx b/app/scenes/Settings/Import.tsx index 6893ae7bc1..561fe4d5bb 100644 --- a/app/scenes/Settings/Import.tsx +++ b/app/scenes/Settings/Import.tsx @@ -1,6 +1,6 @@ import { orderBy } from "es-toolkit/compat"; import { observer } from "mobx-react"; -import { NewDocumentIcon } from "outline-icons"; +import { GlobeIcon, NewDocumentIcon } from "outline-icons"; import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; import { Pagination } from "@shared/constants"; @@ -23,6 +23,7 @@ import FileOperationListItem from "./components/FileOperationListItem"; import ImportJSONDialog from "./components/ImportJSONDialog"; import { ImportListItem } from "./components/ImportListItem"; import ImportMarkdownDialog from "./components/ImportMarkdownDialog"; +import ImportOKFDialog from "./components/ImportOKFDialog"; type Config = { /** The title of the import. */ @@ -63,6 +64,27 @@ function useImportsConfig() { ), }, + { + 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..c79fab6405 100644 --- a/app/scenes/Settings/Preferences.tsx +++ b/app/scenes/Settings/Preferences.tsx @@ -24,6 +24,7 @@ import useStores from "~/hooks/useStores"; import UserDelete from "../UserDelete"; import { AutoLaunchSetting } from "./components/AutoLaunchSetting"; import SettingRow from "./components/SettingRow"; +import { SettingsSection } from "./components/SettingsSection"; function Preferences() { const { t } = useTranslation(); @@ -181,178 +182,177 @@ function Preferences() { Manage settings that affect your personal experience. - {t("Display")} - - - Choose the interface language. Community translations are accepted - though our{" "} - - translation portal - - . - - - } - > - + - - - - - - - - - - - - - - - - - - {t("Behavior")} - - + + Choose the interface language. Community translations are + accepted through our{" "} + + translation portal + + . + + } - onChange={handleSeamlessEditChange} - /> - - - + + + + + + + + + + + + + + + + + + + + + + + + - - - + + + - - - - + + + + - + description={t( + "Choose how unread notifications are indicated on the app icon." + )} + > + + + {can.delete && ( - <> - {t("Danger")} + @@ -361,7 +361,7 @@ function Preferences() { - + )} ); diff --git a/app/scenes/Settings/Profile.tsx b/app/scenes/Settings/Profile.tsx index 4ee6b30051..13d0303754 100644 --- a/app/scenes/Settings/Profile.tsx +++ b/app/scenes/Settings/Profile.tsx @@ -4,7 +4,6 @@ import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; import { toast } from "sonner"; import { errToString } from "@shared/utils/error"; -import Button from "~/components/Button"; import Heading from "~/components/Heading"; import Input from "~/components/Input"; import Scene from "~/components/Scene"; @@ -20,17 +19,40 @@ import SettingRow from "./components/SettingRow"; const Profile = () => { const user = useCurrentUser(); const { dialogs } = useStores(); - const form = React.useRef(null); const [name, setName] = React.useState(user.name); const { t } = useTranslation(); - const handleSubmit = async (ev: React.SyntheticEvent) => { + const handleSubmit = (ev: React.FormEvent) => { ev.preventDefault(); + }; + + const handleKeyDown = (ev: React.KeyboardEvent) => { + // The name saves on blur, so Enter saves it. + if ( + ev.key === "Enter" && + !ev.nativeEvent.isComposing && + ev.target instanceof HTMLInputElement && + ev.currentTarget.contains(ev.target) + ) { + ev.preventDefault(); + ev.target.blur(); + } + }; + + const handleNameBlur = async () => { + if (name === user.name) { + return; + } + if (!name.trim()) { + setName(user.name); + return; + } try { await user.save({ name }); toast.success(t("Profile saved")); } catch (err) { + setName(user.name); toast.error(errToString(err)); } }; @@ -57,9 +79,6 @@ const Profile = () => { toast.error(error || t("Unable to upload new profile picture")); }; - const isValid = form.current?.checkValidity(); - const { isSaving } = user; - return ( }> {t("Profile")} @@ -67,7 +86,7 @@ const Profile = () => { Manage how you appear to other members of the workspace. -
    + { autoComplete="name" value={name} onChange={handleNameChange} + onBlur={handleNameBlur} maxLength={UserValidation.maxNameLength} showCharacterCount required @@ -109,10 +129,6 @@ const Profile = () => { /> )} - -
    ); diff --git a/app/scenes/Settings/Security.tsx b/app/scenes/Settings/Security.tsx index 35ac63e6d0..bb7b092a42 100644 --- a/app/scenes/Settings/Security.tsx +++ b/app/scenes/Settings/Security.tsx @@ -6,6 +6,7 @@ import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; import { errToString } from "@shared/utils/error"; +import { TeamValidation } from "@shared/validations"; import type { TeamPreferences, UserRole } from "@shared/types"; import { CommentingAccess, TeamPreference, EmailDisplay } from "@shared/types"; import ConfirmationDialog from "~/components/ConfirmationDialog"; @@ -16,14 +17,17 @@ import Scene from "~/components/Scene"; import Switch from "~/components/Switch"; import Text from "~/components/Text"; import useCurrentTeam from "~/hooks/useCurrentTeam"; +import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import isCloudHosted from "~/utils/isCloudHosted"; import SettingRow from "./components/SettingRow"; +import { SettingsSection } from "./components/SettingsSection"; function Security() { const { dialogs } = useStores(); const team = useCurrentTeam(); const { t } = useTranslation(); + const can = usePolicy(team); const [data, setData] = useState({ sharing: team.sharing, @@ -31,7 +35,6 @@ function Security() { memberCollectionCreate: team.memberCollectionCreate, memberTeamCreate: team.memberTeamCreate, inviteRequired: team.inviteRequired, - passkeysEnabled: team.passkeysEnabled, }); const userRoleOptions: Option[] = React.useMemo( @@ -95,6 +98,16 @@ function Security() { [t] ); + const defaultShareExpiryOptions: Option[] = React.useMemo( + () => + TeamValidation.defaultShareExpiryDays.map((count): Option => ({ + type: "item", + label: count === 0 ? t("Never") : t("{{ count }} days", { count }), + value: String(count), + })), + [t] + ); + const showSuccessMessage = React.useMemo( () => debounce(() => { @@ -132,13 +145,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 +170,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 = { @@ -208,6 +225,17 @@ function Security() { [saveData, team.preferences] ); + const handleDefaultShareExpiryChange = React.useCallback( + async (days: string) => { + const preferences = { + ...team.preferences, + [TeamPreference.DefaultShareExpiryDays]: Number(days), + }; + await saveData({ preferences }); + }, + [saveData, team.preferences] + ); + const handleInviteRequiredChange = React.useCallback( async (checked: boolean) => { const inviteRequired = checked; @@ -253,168 +281,189 @@ function Security() { - {t("Invites")} - - - - {isCloudHosted && ( + - )} + {isCloudHosted && ( + + + + )} - {!data.inviteRequired && ( + {!data.inviteRequired && ( + + + + )} + + + + + + {can.setDefaultShareExpiry && ( + + + + )} + + + + + + + - )} - - {t("Authentication")} - - - - - {t("Behavior")} - - - - - - - - - - - - - - - - - - - {isCloudHosted && ( - - )} + + + + + + + {isCloudHosted && ( + + + + )} + ); } diff --git a/app/scenes/Settings/Shares.tsx b/app/scenes/Settings/Shares.tsx index c8073451fc..42c9c5f68e 100644 --- a/app/scenes/Settings/Shares.tsx +++ b/app/scenes/Settings/Shares.tsx @@ -4,7 +4,7 @@ import { GlobeIcon, WarningIcon } from "outline-icons"; import type * as React from "react"; import { useState, useMemo, useCallback, useEffect } from "react"; import { useTranslation, Trans } from "react-i18next"; -import { Link, useHistory, useLocation } from "react-router-dom"; +import { Link, useHistory } from "react-router-dom"; import { toast } from "sonner"; import { ConditionalFade } from "~/components/Fade"; import Heading from "~/components/Heading"; @@ -13,6 +13,7 @@ import Notice from "~/components/Notice"; import Scene from "~/components/Scene"; import Text from "~/components/Text"; import useCurrentTeam from "~/hooks/useCurrentTeam"; +import useCurrentUser from "~/hooks/useCurrentUser"; import usePolicy from "~/hooks/usePolicy"; import useQuery from "~/hooks/useQuery"; import useStores from "~/hooks/useStores"; @@ -22,8 +23,8 @@ import { StickyFilters } from "./components/StickyFilters"; function Shares() { const team = useCurrentTeam(); + const user = useCurrentUser(); const { t } = useTranslation(); - const location = useLocation(); const history = useHistory(); const { shares, auth } = useStores(); const canShareDocuments = auth.team && auth.team.sharing; @@ -51,7 +52,7 @@ function Shares() { ); const { data, error, loading, next } = useTableRequest({ - data: shares.findByQuery(reqParams.query ?? ""), + data: shares.findListedByQuery(reqParams.query ?? "", user), sort, reqFn: shares.fetchPage, reqParams, @@ -66,11 +67,11 @@ function Shares() { } history.replace({ - pathname: location.pathname, + pathname: history.location.pathname, search: params.toString(), }); }, - [params, history, location.pathname] + [params, history] ); const handleSearch = useCallback( @@ -93,8 +94,8 @@ function Shares() { }, [query, updateParams]); return ( - } wide> - {t("Shared Links")} + } wide> + {t("Shared links")} {can.update && !canShareDocuments && ( <> @@ -113,7 +114,7 @@ function Shares() { - Documents that have been shared are listed below. Anyone that has the + Documents that have been shared are listed below. Anyone with the public link can access a read-only version of the document until the link has been revoked. 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..53476334d0 100644 --- a/app/scenes/Settings/TemplateNew.tsx +++ b/app/scenes/Settings/TemplateNew.tsx @@ -26,13 +26,13 @@ function TemplateNewScene() { ); history.replace(template.path); } catch (_err) { - toast.error(t("Couldn’t create the template, try again?")); + toast.error(t("Couldn’t create the template. Try again?")); history.replace(settingsPath("templates")); } } 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/Templates.tsx b/app/scenes/Settings/Templates.tsx index 806e015ffb..325ac357ac 100644 --- a/app/scenes/Settings/Templates.tsx +++ b/app/scenes/Settings/Templates.tsx @@ -5,7 +5,7 @@ import { ShapesIcon } from "outline-icons"; import type * as React from "react"; import { useEffect, useMemo, useCallback, useState } from "react"; import { useTranslation, Trans } from "react-i18next"; -import { useHistory, useLocation } from "react-router-dom"; +import { useHistory } from "react-router-dom"; import { toast } from "sonner"; import type Template from "~/models/Template"; import { Action } from "~/components/Actions"; @@ -41,7 +41,6 @@ function Templates() { const team = useCurrentTeam(); const can = usePolicy(team); const history = useHistory(); - const location = useLocation(); const params = useQuery(); const [query, setQuery] = useState(""); @@ -82,11 +81,11 @@ function Templates() { } history.replace({ - pathname: location.pathname, + pathname: history.location.pathname, search: params.toString(), }); }, - [params, history, location.pathname] + [params, history] ); const handleSearch = useCallback( diff --git a/app/scenes/Settings/Users.tsx b/app/scenes/Settings/Users.tsx index 2d9aa06d3b..ab45fc7b46 100644 --- a/app/scenes/Settings/Users.tsx +++ b/app/scenes/Settings/Users.tsx @@ -4,9 +4,10 @@ import { PlusIcon, UserIcon } from "outline-icons"; import type * as React from "react"; import { useState, useMemo, useCallback, useEffect } from "react"; import { Trans, useTranslation } from "react-i18next"; -import { useHistory, useLocation } from "react-router-dom"; +import { useHistory } from "react-router-dom"; import { toast } from "sonner"; import styled from "styled-components"; +import { breakpoint } from "@shared/styles/breakpoint"; import type { Filter } from "@shared/helpers/FilterHelper"; import type UsersStore from "~/stores/UsersStore"; import { queriedUsers } from "~/stores/UsersStore"; @@ -33,7 +34,6 @@ import { HStack } from "~/components/primitives/HStack"; function Users() { const appName = env.APP_NAME; - const location = useLocation(); const history = useHistory(); const team = useCurrentTeam(); const { users } = useStores(); @@ -86,11 +86,11 @@ function Users() { } history.replace({ - pathname: location.pathname, + pathname: history.location.pathname, search: params.toString(), }); }, - [params, history, location.pathname] + [params, history] ); const handleStatusFilter = useCallback( @@ -149,13 +149,13 @@ function Users() { {t("Users")} - Everyone that has signed into {{ appName }} is listed here. It’s + Everyone who has signed in to {{ appName }} is listed here. It’s possible that there are other users who have access through{" "} {{ signinMethods: team.signinMethods }} but haven’t signed in yet. - + - + @@ -268,6 +268,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/ActionRow.tsx b/app/scenes/Settings/components/ActionRow.tsx index 00a90dc3bf..ddc4cf1560 100644 --- a/app/scenes/Settings/components/ActionRow.tsx +++ b/app/scenes/Settings/components/ActionRow.tsx @@ -1,6 +1,6 @@ import { transparentize } from "polished"; import styled from "styled-components"; -import breakpoint from "styled-components-breakpoint"; +import { breakpoint } from "@shared/styles/breakpoint"; import { s } from "@shared/styles"; import { HStack } from "~/components/primitives/HStack"; diff --git a/app/scenes/Settings/components/CopyButton.tsx b/app/scenes/Settings/components/CopyButton.tsx index 2599bd9931..f442337673 100644 --- a/app/scenes/Settings/components/CopyButton.tsx +++ b/app/scenes/Settings/components/CopyButton.tsx @@ -43,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 b82e670aa9..9dc1a27372 100644 --- a/app/scenes/Settings/components/DropToImport.tsx +++ b/app/scenes/Settings/components/DropToImport.tsx @@ -12,21 +12,22 @@ import { type ImportableIntegrationService, } from "@shared/types"; import { bytesToHumanReadable } from "@shared/utils/files"; -import Button from "~/components/Button"; import { DropzoneContainer, dropzoneIcon, } from "~/components/DropzoneContainer"; import Flex from "~/components/Flex"; -import { InputSelectPermission } from "~/components/InputSelectPermission"; import LoadingIndicator from "~/components/LoadingIndicator"; import Text from "~/components/Text"; import useStores from "~/hooks/useStores"; -import { EmptySelectValue } from "~/types"; import { uploadFile } from "~/utils/files"; +import type { ImportOptions } from "./ImportSteps"; +import { ImportSteps } from "./ImportSteps"; type Props = { children: React.JSX.Element; + /** Explains what the file should contain, shown above the dropzone. */ + description?: React.ReactNode; /** The importable service to create an import for. */ service: ImportableIntegrationService; disabled?: boolean; @@ -34,15 +35,18 @@ type Props = { onSubmit: () => void; }; -function DropToImport({ disabled, onSubmit, children, service }: Props) { +function DropToImport({ + disabled, + onSubmit, + children, + description, + service, +}: Props) { const { t } = useTranslation(); const { imports } = useStores(); const [file, setFile] = useState(null); const [isImporting, setImporting] = useState(false); const [uploadProgress, setUploadProgress] = useState(0); - const [permission, setPermission] = useState( - CollectionPermission.ReadWrite - ); const handleFiles = (files: File[]) => { if (files.length > 1) { @@ -52,7 +56,10 @@ function DropToImport({ disabled, onSubmit, children, service }: Props) { setFile(files[0]); }; - const handleStartImport = async () => { + const handleStartImport = async ({ + destination, + permission, + }: ImportOptions) => { if (!file) { return; } @@ -70,14 +77,15 @@ function DropToImport({ disabled, onSubmit, children, service }: Props) { { service }, { attachmentId: attachment.id, - permission: permission ?? undefined, + permission, + ...destination, } ); onSubmit(); toast.message(file.name, { description: t( - "Your import is being processed, you can safely leave this page" + "Your import is being processed – you can safely leave this page" ), }); } catch (err) { @@ -97,65 +105,71 @@ function DropToImport({ disabled, onSubmit, children, service }: Props) { } return ( - + <> {isImporting && } - - - {({ getRootProps, getInputProps, isDragActive }) => ( - - - - - {file - ? t(`${file.name} (${bytesToHumanReadable(file.size)})`) - : children} - - - )} - - -
    - { - setPermission(value === EmptySelectValue ? null : value); - }} - /> - - {t( - "Set the default permission level for collections created from the import" - )} - . - -
    - - - -
    + + {description} + + + {({ getRootProps, getInputProps, isDragActive }) => ( + + + + + {file + ? t(`${file.name} (${bytesToHumanReadable(file.size)})`) + : children} + + + )} + + + + } + canContinue={!!file} + defaultPermission={CollectionPermission.ReadWrite} + isSubmitting={isImporting} + submittingLabel={t("Uploading {{progress}}%", { + progress: Math.min(99, Math.floor(uploadProgress * 100)), + })} + onStart={handleStartImport} + /> + ); } +const zipAccept = { + "application/zip": [], + "application/x-zip-compressed": [], +}; + const Icon = styled(NewDocumentIcon)` ${dropzoneIcon} `; +const DropzoneText = styled(Text)` + display: flex; + flex: 1; + margin-bottom: 12px; +`; + const Container = styled(DropzoneContainer)` + display: flex; + flex: 1; + align-items: center; + justify-content: center; padding: 52px; `; diff --git a/app/scenes/Settings/components/GroupDialogs.tsx b/app/scenes/Settings/components/GroupDialogs.tsx index 7fa577b06e..a9c24bbc01 100644 --- a/app/scenes/Settings/components/GroupDialogs.tsx +++ b/app/scenes/Settings/components/GroupDialogs.tsx @@ -3,6 +3,8 @@ import { observer } from "mobx-react"; import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; import { toast } from "sonner"; +import styled from "styled-components"; +import { colorPalette } from "@shared/constants"; import { errToString } from "@shared/utils/error"; import { GroupPermissionHelper } from "@shared/utils/GroupPermissionHelper"; import Group from "~/models/Group"; @@ -17,7 +19,9 @@ import ConfirmationDialog from "~/components/ConfirmationDialog"; import DelayedMount from "~/components/DelayedMount"; import Empty from "~/components/Empty"; import Flex from "~/components/Flex"; +import { ResolvedGroupIcon } from "~/components/Icons/GroupIcon"; import Input from "~/components/Input"; +import { createLazyComponent } from "~/components/LazyLoad"; import PlaceholderList from "~/components/List/Placeholder"; import PaginatedList from "~/components/PaginatedList"; import { ListItem } from "~/components/Sharing/components/ListItem"; @@ -37,6 +41,8 @@ import Switch from "~/components/Switch"; import history from "~/utils/history"; import { settingsPath } from "~/utils/routeHelpers"; +const IconPicker = createLazyComponent(() => 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 ( @@ -80,17 +98,25 @@ export function CreateGroupDialog() { Groups are for organizing your team. They work best when centered - around a function or a responsibility — Support or Engineering for + around a function or a responsibility — Support or Engineering, for example. 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( @@ -163,8 +201,8 @@ export function EditGroupDialog({ group, onSubmit }: Props) { ) : ( - You can edit the name of this group at any time, however doing so - too often might confuse your team mates. + You can edit the name of this group at any time, but doing so 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 @@ -242,7 +288,7 @@ export function DeleteGroupDialog({ /> ) : ( t( - "Are you sure about that? Deleting {{ count }} group will cause their members to lose access to collections and documents that they are associated with.", + "Are you sure about that? Deleting {{ count }} group will cause its members to lose access to collections and documents that it is associated with.", { count: groups.length } ) )} @@ -466,3 +512,39 @@ const GroupMemberListItem = observer(function ({ /> ); }); + +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..05d03402af 100644 --- a/app/scenes/Settings/components/GroupMembersTable.tsx +++ b/app/scenes/Settings/components/GroupMembersTable.tsx @@ -117,6 +117,35 @@ 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 ( +