feat(web): adopt @usememos/ui as the design system (#6528)

This commit is contained in:
Johnny
2026-11-06 08:25:06 +08:00
committed by GitHub
parent 1a496231fe
commit 99a7e33e77
334 changed files with 15849 additions and 7925 deletions
+20 -5
View File
@@ -8,7 +8,7 @@ repo. If a fact here conflicts with source files or CI config, trust the source
Memos is a self-hosted note-taking app.
- Backend: Go 1.27.2, net/http, Connect RPC, gRPC-Gateway, Protocol Buffers.
- Frontend: React 19, TypeScript 7, Vite 8, Tailwind CSS v4, React Query v5.
- Frontend: React 19, TypeScript 7, Vite 8, Tailwind CSS v4, `@usememos/ui` on Base UI, React Query v5.
- Storage: SQLite, MySQL, PostgreSQL.
- Generated API outputs: `proto/gen/` for Go/OpenAPI, `web/src/types/proto/` for TypeScript.
@@ -51,7 +51,7 @@ golangci-lint run --fix # Auto-fix lint, including goimports
# Frontend
cd web && pnpm install # Install dependencies
cd web && pnpm dev # Dev server on :3001, proxying API to :8081
cd web && pnpm dev # Dev server on :3001, proxying API to :8081 (or $DEV_PROXY_SERVER)
cd web && pnpm lint # Type check + Biome lint
cd web && pnpm test # Vitest unit tests
cd web && pnpm build # Production build
@@ -83,7 +83,7 @@ Every root folder is named for what it holds. Read the folder's `doc.go` or `REA
| `provider/` | Backends configured by instance settings: `ai`, `idp`, `storage` | proto/gen, internal |
| `internal/` | Private plumbing with no memos vocabulary (`identifier`, `email`, `webhook`, `ratelimit`, …) | third party only |
| `proto/api/`, `proto/store/` | Public API and internal storage proto sources; `proto/gen/` is generated | |
| `web/src/` | React SPA: `connect.ts` clients, `auth-state.ts`, `hooks/`, `contexts/`, `components/`, `themes/` | |
| `web/src/` | React SPA: `connect.ts` clients, `auth-state.ts`, `hooks/`, `contexts/`, `components/`, `lib/`, `locales/`, `themes/` | |
Layering rules, enforced by `depguard` in `.golangci.yaml`:
@@ -126,9 +126,24 @@ Black-box service tests live in `server/api/test/`, unit tests next to the code.
- Follow Biome formatting: 2-space indent, double quotes, semicolons, 140-character line width.
- Put server data in React Query hooks under `web/src/hooks/`; keep UI-only state in contexts or component state.
- Show, edit and compose memos through `web/src/components/MemoEditor` (a name or draft seed plus a mode); see its `README.md`.
- Use Tailwind CSS v4 utilities, `cn()` for class merging, and CVA for variants.
- Reuse Base UI primitives and existing components before adding new UI primitives.
- Keep generated proto TypeScript under `web/src/types/proto/` out of manual edits and Biome rewrites.
- UI work reads `web/node_modules/@usememos/ui/llms.txt` first: `@usememos/ui` is the design system (tokens, type classes,
components). Controls come from the package; build a part it lacks on Base UI as its `custom-components.md` describes.
- Use a package component when one fits (`Button`, `Link`, `Spinner`, `Badge`). Its class functions (`buttonClasses()`,
`menuClasses()`, `badgeClasses()`) are for elements it can't render, such as a router link or a Base UI trigger.
- Style with Tailwind CSS v4 and the package's `mu-` utilities (`bg-mu-surface`, `text-mu-ink-muted`, `rounded-mu-md`),
text with its type classes (`mu-caption`, `mu-body`, `mu-label`, `mu-title`), and `cn()` for class merging. No Tailwind
text sizes or old color names (`muted-foreground`, `destructive`, `popover`). The exceptions are the brand wordmark and
emoji glyphs, whose font size is their icon box (`SpaceIcon`, `SpaceMark`, `MemoViewIcon`, `CustomIconPicker`).
- Focus shows through `mu-focus`. Never add `ring-*` or `focus-visible:ring-*`, and never pair `mu-focus` with
`outline-none`, which overrides it. Visually hidden text uses `mu-visually-hidden`; a control that appears on focus keeps
Tailwind's `sr-only focus-visible:not-sr-only` pair.
- Report failures with `showErrorToast` from `web/src/lib/toast.ts`. A form's own validation errors go under the field
(`Field.Error`, kept in `useFieldErrors`), not in a toast.
- Every new key in `web/src/locales/en.json` is translated into all locales; `tests/locale-resources.test.ts` fails
otherwise. A plural message is stored as `key_one`, `key_other`, … and looked up by its base key with `count`.
- Lucide icons outside a package control take a size class that sets box and stroke together: `mu-icon-xs` (12px),
`mu-icon-sm` (14px) or `mu-icon` (16px). No Tailwind sizes on 12–16px icons and no `strokeWidth`.
## Database And Proto Rules
-21
View File
@@ -1,21 +0,0 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/index.css",
"baseColor": "zinc",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
+2 -2
View File
@@ -9,8 +9,8 @@
<link rel="icon" type="image/svg+xml" href="/favicon.svg?v=bird-blue" />
<link rel="manifest" href="/site.webmanifest?v=celadon" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#faf9f5" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#1d1f23" />
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#fafafa" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#0f0f0f" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
+2 -3
View File
@@ -17,7 +17,7 @@
"test:coverage": "vitest run --coverage"
},
"dependencies": {
"@base-ui/react": "^1.7.0",
"@base-ui/react": "1.9.0",
"@connectrpc/connect": "^2.1.1",
"@connectrpc/connect-web": "^2.1.1",
"@github/relative-time-element": "^5.0.0",
@@ -27,6 +27,7 @@
"@tanstack/react-query": "^5.100.9",
"@tanstack/react-query-devtools": "^5.100.9",
"@usememos/editor": "26.11.0",
"@usememos/ui": "26.11.7",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"copy-to-clipboard": "^4.0.2",
@@ -44,7 +45,6 @@
"pele": "1.13.0",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"react-hot-toast": "^2.6.0",
"react-i18next": "^17.0.11",
"react-leaflet": "^5.0.0",
"react-leaflet-cluster": "^4.1.3",
@@ -69,7 +69,6 @@
"@vitejs/plugin-react": "^6.0.1",
"babel-plugin-react-compiler": "1.0.0",
"jsdom": "^29.1.1",
"tw-animate-css": "^1.4.0",
"typescript": "^7.0.2",
"vite": "^8.0.11",
"vitest": "^4.1.5"
+44 -51
View File
@@ -12,8 +12,8 @@ importers:
.:
dependencies:
'@base-ui/react':
specifier: ^1.7.0
version: 1.7.0(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
specifier: 1.9.0
version: 1.9.0(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
'@connectrpc/connect':
specifier: ^2.1.1
version: 2.1.1(@bufbuild/protobuf@2.12.0(patch_hash=9d60cec35402ba36bc21a72fefc68ccef8db0acb883504cc47c05a00a0029f8c))
@@ -41,6 +41,9 @@ importers:
'@usememos/editor':
specifier: 26.11.0
version: 26.11.0(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
'@usememos/ui':
specifier: 26.11.7
version: 26.11.7(@base-ui/react@1.9.0(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(lucide-react@1.34.0(react@19.2.6))(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@@ -92,9 +95,6 @@ importers:
react-dom:
specifier: ^19.2.6
version: 19.2.6(react@19.2.6)
react-hot-toast:
specifier: ^2.6.0
version: 2.6.0(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
react-i18next:
specifier: ^17.0.11
version: 17.0.11(i18next@26.3.6(typescript@7.0.2))(react-dom@19.2.6(react@19.2.6))(react@19.2.6)(typescript@7.0.2)
@@ -162,9 +162,6 @@ importers:
jsdom:
specifier: ^29.1.1
version: 29.1.1
tw-animate-css:
specifier: ^1.4.0
version: 1.4.0
typescript:
specifier: ^7.0.2
version: 7.0.2
@@ -278,8 +275,8 @@ packages:
resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}
engines: {node: '>=6.9.0'}
'@base-ui/react@1.7.0':
resolution: {integrity: sha512-j+8QjX44C32jrXD/qyEAGpFr70FRpGL2CY61mQd9nBPWN737CK0xxD1ceJ055rW4RtdvFDT1e7otzdlfxvsYug==}
'@base-ui/react@1.9.0':
resolution: {integrity: sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ==}
engines: {node: '>=14.0.0'}
peerDependencies:
'@date-fns/tz': ^1.2.0
@@ -295,8 +292,8 @@ packages:
date-fns:
optional: true
'@base-ui/utils@0.3.2':
resolution: {integrity: sha512-oWy1aq/I2GmYjpl4PhEAhzflF8VPGKgZeq0xAWTbfD5KBWyxcN0ZP2+WHSUm/5Z6lVMBDLReLcoXwSYoRc/zNQ==}
'@base-ui/utils@0.5.0':
resolution: {integrity: sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A==}
peerDependencies:
'@types/react': ^17 || ^18 || ^19
react: ^17 || ^18 || ^19
@@ -962,6 +959,14 @@ packages:
react-dom:
optional: true
'@usememos/ui@26.11.7':
resolution: {integrity: sha512-DwDZMoBSNLuPb841L9E6P9++URgAeoekKIRgqdPzDqZt7/gZsp8TtuaF6pkuQabC4yvXU4VsnPmU4/O0iwrB7g==}
peerDependencies:
'@base-ui/react': 1.9.0
lucide-react: '>=1.0.0'
react: '>=18'
react-dom: '>=18'
'@vitejs/plugin-react@6.0.1':
resolution: {integrity: sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -1165,11 +1170,6 @@ packages:
gl-matrix@3.4.4:
resolution: {integrity: sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==}
goober@2.1.18:
resolution: {integrity: sha512-2vFqsaDVIT9Gz7N6kAL++pLpp41l3PfDuusHcjnGLfR6+huZkl6ziX+zgVC3ZxpqWhzH6pyDdGrCeDhMIvwaxw==}
peerDependencies:
csstype: ^3.0.10
graceful-fs@4.2.11:
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
@@ -1416,13 +1416,6 @@ packages:
peerDependencies:
react: ^19.2.6
react-hot-toast@2.6.0:
resolution: {integrity: sha512-bH+2EBMZ4sdyou/DPrfgIouFpcRLCJ+HoCA32UoAYHn6T3Ur5yfcDCeSr5mwldl6pFOsiocmrXMuoCJ1vV8bWg==}
engines: {node: '>=10'}
peerDependencies:
react: '>=16'
react-dom: '>=16'
react-i18next@17.0.11:
resolution: {integrity: sha512-cDtkXgxjuFTWUH6V+aQn1Ve5vDiUztCNPWW5GtSHDccsgRXO1nE6QFWCEmc1KAutrb3OUv87wFShJL5RhUwPXg==}
peerDependencies:
@@ -1487,8 +1480,8 @@ packages:
resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
engines: {node: '>=0.10.0'}
reselect@5.2.0:
resolution: {integrity: sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw==}
reselect@5.3.0:
resolution: {integrity: sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==}
resolve-protobuf-schema@2.1.0:
resolution: {integrity: sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==}
@@ -1578,9 +1571,6 @@ packages:
tslib@2.8.1:
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
tw-animate-css@1.4.0:
resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==}
typescript@7.0.2:
resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==}
engines: {node: '>=16.20.0'}
@@ -1604,6 +1594,11 @@ packages:
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
use-sync-external-store@1.7.0:
resolution: {integrity: sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
uuid@11.1.0:
resolution: {integrity: sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==}
hasBin: true
@@ -1859,26 +1854,26 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
'@base-ui/react@1.7.0(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)':
'@base-ui/react@1.9.0(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)':
dependencies:
'@babel/runtime': 7.29.2
'@base-ui/utils': 0.3.2(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
'@babel/runtime': 7.29.7
'@base-ui/utils': 0.5.0(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
'@floating-ui/react-dom': 2.1.9(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
'@floating-ui/utils': 0.2.12
react: 19.2.6
react-dom: 19.2.6(react@19.2.6)
use-sync-external-store: 1.6.0(react@19.2.6)
use-sync-external-store: 1.7.0(react@19.2.6)
optionalDependencies:
'@types/react': 19.2.14
'@base-ui/utils@0.3.2(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)':
'@base-ui/utils@0.5.0(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)':
dependencies:
'@babel/runtime': 7.29.2
'@babel/runtime': 7.29.7
'@floating-ui/utils': 0.2.12
react: 19.2.6
react-dom: 19.2.6(react@19.2.6)
reselect: 5.2.0
use-sync-external-store: 1.6.0(react@19.2.6)
reselect: 5.3.0
use-sync-external-store: 1.7.0(react@19.2.6)
optionalDependencies:
'@types/react': 19.2.14
@@ -2378,6 +2373,13 @@ snapshots:
react: 19.2.6
react-dom: 19.2.6(react@19.2.6)
'@usememos/ui@26.11.7(@base-ui/react@1.9.0(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(lucide-react@1.34.0(react@19.2.6))(react-dom@19.2.6(react@19.2.6))(react@19.2.6)':
dependencies:
'@base-ui/react': 1.9.0(@types/react@19.2.14)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
lucide-react: 1.34.0(react@19.2.6)
react: 19.2.6
react-dom: 19.2.6(react@19.2.6)
'@vitejs/plugin-react@6.0.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.0)(@babel/runtime@7.29.7)(rolldown@1.0.0-rc.18)(vite@8.0.11(@types/node@24.12.2)(jiti@2.6.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.0.11(@types/node@24.12.2)(jiti@2.6.1))':
dependencies:
'@rolldown/pluginutils': 1.0.0-rc.7
@@ -2545,10 +2547,6 @@ snapshots:
gl-matrix@3.4.4: {}
goober@2.1.18(csstype@3.2.3):
dependencies:
csstype: 3.2.3
graceful-fs@4.2.11: {}
html-encoding-sniffer@6.0.0:
@@ -2761,13 +2759,6 @@ snapshots:
react: 19.2.6
scheduler: 0.27.0
react-hot-toast@2.6.0(react-dom@19.2.6(react@19.2.6))(react@19.2.6):
dependencies:
csstype: 3.2.3
goober: 2.1.18(csstype@3.2.3)
react: 19.2.6
react-dom: 19.2.6(react@19.2.6)
react-i18next@17.0.11(i18next@26.3.6(typescript@7.0.2))(react-dom@19.2.6(react@19.2.6))(react@19.2.6)(typescript@7.0.2):
dependencies:
'@babel/runtime': 7.29.2
@@ -2820,7 +2811,7 @@ snapshots:
require-from-string@2.0.2: {}
reselect@5.2.0: {}
reselect@5.3.0: {}
resolve-protobuf-schema@2.1.0:
dependencies:
@@ -2907,8 +2898,6 @@ snapshots:
tslib@2.8.1:
optional: true
tw-animate-css@1.4.0: {}
typescript@7.0.2:
optionalDependencies:
'@typescript/typescript-aix-ppc64': 7.0.2
@@ -2946,6 +2935,10 @@ snapshots:
dependencies:
react: 19.2.6
use-sync-external-store@1.7.0(react@19.2.6):
dependencies:
react: 19.2.6
uuid@11.1.0: {}
vite@8.0.11(@types/node@24.12.2)(jiti@2.6.1):
@@ -1,5 +1,5 @@
import { Tooltip } from "@usememos/ui";
import { memo } from "react";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { getChipClassName } from "./cellStyles";
import type { CalendarDayCell } from "./types";
@@ -52,12 +52,12 @@ export const CalendarCell = memo(({ day, maxCount, tooltipText, onClick }: Calen
}
return (
<Tooltip>
<TooltipTrigger render={button} />
<TooltipContent side="top">
<Tooltip.Root>
<Tooltip.Trigger render={button} />
<Tooltip.Popup side="top">
<p>{tooltipText}</p>
</TooltipContent>
</Tooltip>
</Tooltip.Popup>
</Tooltip.Root>
);
});
@@ -9,7 +9,13 @@ import type { MonthCalendarProps } from "./types";
import { calculateMaxCount, getTooltipText } from "./utils";
/** The type of a weekday column label, shared by every month grid. */
export const WEEKDAY_LABEL_CLASSES = "text-2xs font-medium uppercase tracking-[0.04em] text-muted-foreground/50";
/**
* Seven 28px columns, the sidebar's one control height, so day cells land on whole pixels; the
* leftover width goes into the column gaps, which keeps the first and last columns on the rails.
*/
const CALENDAR_GRID_CLASSES = "grid grid-cols-[repeat(7,28px)] justify-between gap-y-1";
/** Weekday initials: caption weight in muted ink, so they sit under the day numbers rather than beside them. */
export const WEEKDAY_LABEL_CLASSES = "mu-caption text-mu-ink-muted";
/** Localized weekday labels starting on the instance's first day of the week. */
export const useWeekdayLabels = (weekStartDayOffset: number) => {
@@ -46,9 +52,9 @@ export const MonthCalendar = memo(({ month, data, selectedDate, onClick, timeBas
});
return (
<div className="flex flex-col" role="group" aria-label={`Calendar for ${month}`}>
<div className="flex flex-col" role="group" aria-label={t("common.calendar-for-month", { month })}>
{/* Every day button already announces its full date, so the initials are decoration. */}
<div className="mb-1.5 grid grid-cols-7 gap-1" aria-hidden="true">
<div className={cn("mb-1", CALENDAR_GRID_CLASSES)} aria-hidden="true">
{weekDays.map((label, index) => (
<div key={index} className={cn("flex h-5 items-center justify-center", WEEKDAY_LABEL_CLASSES)}>
{Array.from(label)[0]}
@@ -56,7 +62,7 @@ export const MonthCalendar = memo(({ month, data, selectedDate, onClick, timeBas
))}
</div>
<div className="grid grid-cols-7 gap-1">
<div className={CALENDAR_GRID_CLASSES}>
{days.map((day) => (
<CalendarCell
key={day.date}
@@ -3,28 +3,28 @@ import type { CalendarDayCell } from "./types";
import { type ActivityLevel, getActivityLevel } from "./utils";
/**
* The square chip inside a cell carries every visual. `max-w-[30px]` caps it so a wider
* container spends its surplus on hit area rather than row height; the 224px rail's ~25px
* columns sit below the cap and are unaffected.
* The square chip inside a cell carries every visual. The grid's columns are 28px (see
* CALENDAR_GRID_CLASSES), so the chip is a 28px square; `max-w-7` keeps it there should a
* wider container ever hand the cell more.
*/
const CHIP_BASE =
"relative flex aspect-square w-full max-w-[30px] items-center justify-center rounded-md text-center text-xs font-normal leading-none tracking-[-0.01em] tabular-nums transition-[background-color,color,filter,box-shadow] duration-150 ease-out";
"relative flex aspect-square w-full max-w-7 items-center justify-center rounded-mu-md text-center mu-caption tabular-nums transition-[background-color,color,filter,box-shadow] duration-150 ease-out";
/** Hover reads off the cell (`group/day`), not the chip, so the whole column responds to the pointer. */
const INTERACTIVE_CHIP =
"group-hover/day:brightness-[0.97] group-focus-visible/day:ring-2 group-focus-visible/day:ring-ring/40 group-focus-visible/day:ring-inset";
"group-hover/day:brightness-[0.97] group-focus-visible/day:outline-2 group-focus-visible/day:outline-solid group-focus-visible/day:-outline-offset-2 group-focus-visible/day:outline-mu-focus";
const OUTSIDE_MONTH_CHIP = "bg-transparent text-muted-foreground/25";
const EMPTY_CHIP = "bg-transparent text-foreground/75 group-hover/day:bg-muted/40";
const OUTSIDE_MONTH_CHIP = "bg-transparent text-mu-ink-muted/25";
const EMPTY_CHIP = "bg-transparent text-mu-ink/75 group-hover/day:bg-mu-well/40";
/** A picked day is a checked filter like a view or tag row: it takes the accent, not a ring. */
const SELECTED_CHIP = "z-10 bg-primary font-medium text-primary-foreground";
const SELECTED_CHIP = "z-10 bg-mu-primary text-mu-on-primary";
/** Primary-tinted activity levels; the small chip can carry a stronger wash than a full day cell. */
const INTENSITY_TINTS: Record<Exclude<ActivityLevel, 0>, string> = {
1: "bg-primary/12 text-foreground/75",
2: "bg-primary/22 text-foreground/80",
3: "bg-primary/34 text-foreground/80",
4: "bg-primary/48 text-foreground/85",
1: "bg-mu-primary/12 text-mu-ink/75",
2: "bg-mu-primary/22 text-mu-ink/80",
3: "bg-mu-primary/34 text-mu-ink/80",
4: "bg-mu-primary/48 text-mu-ink/85",
};
/**
@@ -32,11 +32,11 @@ const INTENSITY_TINTS: Record<Exclude<ActivityLevel, 0>, string> = {
* because excerpts and photos sit on top. Kept beside the chip's so the two cannot drift.
*/
export const DAY_CELL_FILLS: Record<ActivityLevel, string> = {
0: "bg-card hover:bg-muted/40",
1: "bg-primary/8 hover:bg-primary/12",
2: "bg-primary/16 hover:bg-primary/20",
3: "bg-primary/26 hover:bg-primary/30",
4: "bg-primary/38 hover:bg-primary/42",
0: "bg-mu-surface hover:bg-mu-hover",
1: "bg-mu-primary/8 hover:bg-mu-primary/12",
2: "bg-mu-primary/16 hover:bg-mu-primary/20",
3: "bg-mu-primary/26 hover:bg-mu-primary/30",
4: "bg-mu-primary/38 hover:bg-mu-primary/42",
};
const getFillClass = (day: CalendarDayCell, maxCount: number): string => {
+56 -43
View File
@@ -1,4 +1,4 @@
import { useDirection } from "@base-ui/react/direction-provider";
import { Button, Drawer, Tooltip } from "@usememos/ui";
import {
ArchiveIcon,
ArrowRightIcon,
@@ -25,9 +25,6 @@ import { MemoDetailSidebar } from "@/components/MemoDetailSidebar";
import MemoDisplaySettingMenu from "@/components/MemoDisplaySettingMenu";
import { DEFAULT_SETTING_SECTION, SETTINGS_SECTIONS } from "@/components/Settings/settingSections";
import StatisticsView from "@/components/StatisticsView";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { type AttachmentSection, type InboxFilter, useAppSidebar } from "@/contexts/AppSidebarContext";
import { useAuth } from "@/contexts/AuthContext";
import { useGlobalMemoEditor } from "@/contexts/GlobalMemoEditorContext";
@@ -45,7 +42,7 @@ import { User_Role, UserNotification_Status } from "@/types/proto/api/user_servi
import { useTranslate } from "@/utils/i18n";
import CommonSidebarContent from "./CommonSidebarContent";
import { getSidebarRouteKind } from "./routes";
import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_FOCUS_CLASSES, SidebarRowIconSlot, sidebarRowStateClasses } from "./SidebarRow";
import SidebarRow, { SIDEBAR_ROW_CLASSES, SidebarRowIconSlot, sidebarRowStateClasses } from "./SidebarRow";
import SidebarSection, { SIDEBAR_SECTION_STACK_CLASSES } from "./SidebarSection";
import SpaceSwitcher from "./SpaceSwitcher";
import {
@@ -62,12 +59,12 @@ const NewMemoAction = ({ onClick }: { onClick: () => void }) => {
const label = t("editor.new-memo");
return (
<Tooltip>
<TooltipTrigger render={<Button variant="outline" size="icon-compact" onClick={onClick} aria-label={label} data-new-memo-trigger />}>
<SquarePenIcon className="size-4" strokeWidth={1.8} />
</TooltipTrigger>
<TooltipContent side="bottom">{label}</TooltipContent>
</Tooltip>
<Tooltip.Root>
<Tooltip.Trigger
render={<Button variant="neutral" onClick={onClick} aria-label={label} data-new-memo-trigger icon={<SquarePenIcon />} />}
/>
<Tooltip.Popup side="bottom">{label}</Tooltip.Popup>
</Tooltip.Root>
);
};
@@ -307,16 +304,18 @@ const NavPill = ({ label, icon: Icon, to, onClick, active = false, expanded = fa
"aria-current": active ? ("page" as const) : undefined,
className: cn(
sidebarSurfaceVariants({ role: "navPill" }),
SIDEBAR_ROW_FOCUS_CLASSES,
"mu-focus",
sidebarRowStateClasses(active ? "current" : "idle"),
// The one pill with an open label gives way first, so the row always ends on the rail.
expanded && "min-w-0 shrink",
className,
),
};
return (
<Tooltip disabled={expanded}>
<TooltipTrigger render={to ? <Link to={to} {...props} /> : <button type="button" {...props} />}>
<Tooltip.Root disabled={expanded}>
<Tooltip.Trigger render={to ? <Link to={to} {...props} /> : <button type="button" {...props} />}>
<span className={SIDEBAR_NAV_LEADING_SLOT_CLASSES} aria-hidden="true">
<Icon className="size-4 opacity-75" strokeWidth={1.8} />
<Icon className="mu-icon" />
</span>
{/* The control carries its own aria-label; this text is decoration whether or not it is open. */}
<span
@@ -327,14 +326,14 @@ const NavPill = ({ label, icon: Icon, to, onClick, active = false, expanded = fa
)}
>
<span className="flex min-w-0 items-center overflow-hidden">
<span data-sidebar-label className="shrink-0 truncate text-[12px] leading-5">
<span data-sidebar-label className="min-w-0 truncate mu-body">
{label}
</span>
</span>
</span>
</TooltipTrigger>
<TooltipContent side="bottom">{label}</TooltipContent>
</Tooltip>
</Tooltip.Trigger>
<Tooltip.Popup side="bottom">{label}</Tooltip.Popup>
</Tooltip.Root>
);
};
@@ -352,9 +351,15 @@ const GlobalNavigation = () => {
const navigationPath = (pathname: string) => collectionNavigationPath(pathname, location, currentUser?.username);
return (
<TooltipProvider>
<nav className={cn("@container flex h-7 items-center gap-1", SIDEBAR_RAIL_CLASSES)} aria-label="Primary">
<div ref={timelineRef} className={cn("flex shrink-0 items-center rounded-md", timelineActive && sidebarRowStateClasses("current"))}>
<Tooltip.Provider>
<nav
className={cn("@container mu-s-md flex h-(--mu-row-height) items-center gap-1", SIDEBAR_RAIL_CLASSES)}
aria-label={t("common.primary-navigation")}
>
<div
ref={timelineRef}
className={cn("flex min-w-0 items-center rounded-mu-md", timelineActive && sidebarRowStateClasses("current"))}
>
<NavPill
to={navigationPath(ROUTES.HOME)}
label={t("common.timeline")}
@@ -377,7 +382,7 @@ const GlobalNavigation = () => {
))}
<NavPill label={t("common.search")} icon={SearchIcon} onClick={() => setQuickFindOpen(true)} className="ms-auto" />
</nav>
</TooltipProvider>
</Tooltip.Provider>
);
};
@@ -387,36 +392,35 @@ const AppSidebar = ({ className }: { className?: string }) => {
const { setMobileOpen } = useAppSidebar();
const { canOpen: canCompose, openEditor } = useGlobalMemoEditor();
return (
<aside className={cn("flex h-full w-full select-none flex-col bg-sidebar text-sidebar-foreground", className)}>
<aside className={cn("mu-compact flex h-full w-full select-none flex-col bg-mu-canvas text-mu-ink-muted", className)}>
<div data-sidebar-header className={cn("flex h-13 shrink-0 items-center justify-between gap-2", SIDEBAR_RAIL_CLASSES)}>
<SpaceSwitcher className="min-w-0" size="header" />
{canCompose && <NewMemoAction onClick={openEditor} />}
</div>
<GlobalNavigation />
<div className="mx-3 mt-2 border-t border-border/70" />
<div className="mx-3 mt-2 border-t border-mu-line/70" />
<div className={cn("min-h-0 flex-1 overflow-y-auto overflow-x-hidden pt-2 pb-3 [scrollbar-width:thin]", SIDEBAR_RAIL_CLASSES)}>
<RouteSidebarContent />
</div>
{!currentUser && (
<footer className="shrink-0 border-t border-border/70">
<footer className="shrink-0 border-t border-mu-line/70">
<Link
to={ROUTES.AUTH}
onClick={() => setMobileOpen(false)}
className={cn(
sidebarSurfaceVariants({ role: "account" }),
"group text-[13px] font-medium text-foreground transition-colors hover:bg-sidebar-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/50",
"group mu-label text-mu-ink transition-colors hover:bg-mu-hover mu-focus",
)}
>
<span className={SIDEBAR_LEADING_SLOT_CLASSES}>
<UserRoundIcon className="me-auto size-4 text-muted-foreground" strokeWidth={1.8} />
<UserRoundIcon className="mu-icon me-auto text-mu-ink-muted" />
</span>
<span data-sidebar-label className="min-w-0 flex-1 truncate">
{t("common.sign-in-to-memos")}
</span>
<ArrowRightIcon
data-sidebar-trailing
className="size-3.5 shrink-0 text-muted-foreground/60 transition-transform group-hover:translate-x-0.5 rtl:rotate-180 rtl:group-hover:-translate-x-0.5"
strokeWidth={1.8}
className="mu-icon-sm shrink-0 text-mu-ink-muted/60 transition-transform group-hover:translate-x-0.5 rtl:rotate-180 rtl:group-hover:-translate-x-0.5"
/>
</Link>
</footer>
@@ -426,30 +430,39 @@ const AppSidebar = ({ className }: { className?: string }) => {
};
export const MobileAppHeader = () => {
const t = useTranslate();
const { setMobileOpen } = useAppSidebar();
return (
<header className="sticky top-0 z-20 flex h-12 w-full shrink-0 items-center justify-start gap-1 border-b border-border/70 bg-background/90 px-2 backdrop-blur-md md:hidden">
<Button variant="ghost" size="icon" onClick={() => setMobileOpen(true)} aria-label="Open navigation" data-mobile-navigation-trigger>
<MenuIcon className="size-[18px]" />
</Button>
<header className="sticky top-0 z-20 flex h-12 w-full shrink-0 items-center justify-start gap-1 border-b border-mu-line/70 bg-mu-canvas/90 px-2 backdrop-blur-md md:hidden">
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
variant="ghost"
onClick={() => setMobileOpen(true)}
aria-label={t("common.open-navigation")}
data-mobile-navigation-trigger
icon={<MenuIcon />}
/>
}
/>
<Tooltip.Popup side="bottom">{t("common.open-navigation")}</Tooltip.Popup>
</Tooltip.Root>
<SpaceSwitcher className="max-w-[12rem]" size="md" />
</header>
);
};
export const MobileAppSidebar = () => {
const direction = useDirection();
const t = useTranslate();
const { mobileOpen, setMobileOpen, completeMobileClose } = useAppSidebar();
return (
<Sheet open={mobileOpen} onOpenChange={setMobileOpen} onOpenChangeComplete={completeMobileClose}>
<SheetContent
side={direction === "rtl" ? "right" : "left"}
className="w-[min(18rem,calc(100vw-2rem))] gap-0 border-border p-0 shadow-2xl [&>[data-slot=sheet-close]]:sr-only"
>
<SheetTitle className="sr-only">Navigation</SheetTitle>
<Drawer.Root side="start" open={mobileOpen} onOpenChange={setMobileOpen} onOpenChangeComplete={completeMobileClose}>
<Drawer.Popup variant="bare" closeLabel={t("common.close")} className="w-72 max-w-[calc(100%-2rem)]">
<Drawer.Title className="mu-visually-hidden">{t("common.navigation")}</Drawer.Title>
<AppSidebar />
</SheetContent>
</Sheet>
</Drawer.Popup>
</Drawer.Root>
);
};
@@ -54,8 +54,7 @@ const CommonSidebarContent = () => {
<span className="min-w-0 flex-1 truncate">{t(resource.labelKey)}</span>
<ExternalLinkIcon
aria-hidden="true"
className="size-3 shrink-0 text-muted-foreground/50 transition-colors group-hover:text-foreground/70"
strokeWidth={1.8}
className="mu-icon-xs shrink-0 text-mu-ink-muted/50 transition-colors group-hover:text-mu-ink/70"
/>
</a>
))}
@@ -1,11 +1,7 @@
import { Button, Dialog, Textarea, Toggle, ToggleGroup, Tooltip } from "@usememos/ui";
import { CornerDownLeftIcon, SearchIcon } from "lucide-react";
import { type ChangeEvent, type FormEvent, type KeyboardEvent, useEffect, useId, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { getFilterSearch, isSearchFilter, type MemoFilter, useMemoFilterContext } from "@/contexts/MemoFilterContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
@@ -148,81 +144,88 @@ const QuickFindDialog = () => {
};
return (
<Dialog open={quickFindOpen} onOpenChange={setQuickFindOpen}>
<DialogContent
size="lg"
backdrop="subtle"
className="top-[12vh]! translate-y-0! overflow-hidden border-border/70 p-0! shadow-xl sm:top-[16vh]! [&>div:first-child]:gap-0!"
showCloseButton={false}
<Dialog.Root open={quickFindOpen} onOpenChange={setQuickFindOpen}>
{/* Anchored near the top, not centered, so switching modes grows the panel downward instead of shifting it. */}
<Dialog.Popup
variant="bare"
sheet={false}
className="w-lg self-start mt-[max(0px,calc(12vh-var(--mu-space-6)))] sm:mt-[max(0px,calc(16vh-var(--mu-space-6)))]"
>
<DialogTitle className="sr-only">{t("common.search")}</DialogTitle>
<DialogDescription className="sr-only">
<Dialog.Title className="mu-visually-hidden">{t("common.search")}</Dialog.Title>
<Dialog.Description className="mu-visually-hidden">
{t("common.search")} {scopeLabel}
</DialogDescription>
</Dialog.Description>
<form onSubmit={handleSubmit}>
<div className="flex items-center justify-between gap-3 border-b border-border/50 px-4 py-2">
<span className="min-w-0 truncate text-xs text-muted-foreground" title={scopeLabel}>
<div className="flex items-center justify-between gap-3 border-b border-mu-line/50 px-4 py-2">
<span className="min-w-0 truncate mu-caption text-mu-ink-muted" title={scopeLabel}>
{compactScopeLabel}
</span>
<Tabs value={mode} onValueChange={(value) => setMode(value as QuickFindMode)} size="sm" className="shrink-0">
<TabsList
aria-label={t("search.mode")}
// Arrow navigation keeps focus on the tabs; clicking a mode focuses its field.
onKeyDownCapture={() => setAutoFocusField(false)}
onClickCapture={() => setAutoFocusField(true)}
>
{(["text", "cel"] as const).map((value) => (
<TabsTrigger key={value} value={value}>
{value === "cel" ? t("search.expression-mode") : t("search.text")}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<ToggleGroup
size="sm"
className="shrink-0"
aria-label={t("search.mode")}
value={[mode]}
onValueChange={([next]: string[]) => next && setMode(next as QuickFindMode)}
// Keyboard choices keep focus on the switch; clicking a mode focuses its field.
onKeyDownCapture={() => setAutoFocusField(false)}
onClickCapture={() => setAutoFocusField(true)}
>
{(["text", "cel"] as const).map((value) => (
<Toggle key={value} value={value}>
{value === "cel" ? t("search.expression-mode") : t("search.text")}
</Toggle>
))}
</ToggleGroup>
</div>
{mode === "cel" ? (
<div className="space-y-3 p-4">
<Textarea
{...fieldProps}
rows={3}
className="field-sizing-fixed max-h-[40dvh] resize-y font-mono text-sm leading-6"
className="field-sizing-fixed max-h-[40dvh] resize-y font-mono"
placeholder={'"work" in tags && !content.contains("GitHub")'}
aria-label={t("search.expression")}
aria-describedby={hintId}
/>
<div className="flex items-end justify-between gap-3">
<div className="min-w-0 space-y-1 text-xs text-muted-foreground">
<div className="min-w-0 space-y-1 mu-caption text-mu-ink-muted">
<p id={hintId}>{t("search.keyboard-hint")}</p>
<a
href="https://usememos.com/docs/usage/shortcuts#filter-expression-syntax"
target="_blank"
rel="noopener noreferrer"
className="inline-block underline underline-offset-2 hover:text-foreground"
className="inline-block underline underline-offset-2 hover:text-mu-ink"
>
{t("search.syntax-help")}
</a>
</div>
<Button type="submit" size="sm" className="shrink-0">
<Button variant="primary" type="submit" size="sm" className="shrink-0">
{t("common.search")}
</Button>
</div>
</div>
) : (
<div className="flex h-[52px] shrink-0 items-center gap-2.5 px-4">
<SearchIcon className="size-[17px] shrink-0 text-muted-foreground" strokeWidth={1.8} />
<Input
<SearchIcon className="mu-icon size-[17px] shrink-0 text-mu-ink-muted" />
{/* The dialog's own field, focused whenever it is open: the caret marks focus, as in a
command palette, so it draws no outline around the borderless header. */}
<input
{...fieldProps}
className="h-10 border-0 bg-transparent px-0 !text-[14px] focus-visible:outline-offset-2"
className="h-10 min-w-0 flex-1 bg-transparent mu-body outline-none placeholder:text-mu-ink-muted"
placeholder={`${t("common.search")} ${compactScopeLabel}`}
aria-label={`${t("common.search")} ${scopeLabel}`}
/>
<Button type="submit" variant="quiet" size="icon-compact" aria-label={t("common.search")}>
<CornerDownLeftIcon className="size-3.5" />
</Button>
<Tooltip.Root>
<Tooltip.Trigger
render={<Button type="submit" variant="ghost" size="sm" aria-label={t("common.search")} icon={<CornerDownLeftIcon />} />}
/>
<Tooltip.Popup>{t("common.search")}</Tooltip.Popup>
</Tooltip.Root>
</div>
)}
</form>
</DialogContent>
</Dialog>
</Dialog.Popup>
</Dialog.Root>
);
};
@@ -42,13 +42,13 @@ interface Props {
const INDICATORS = {
line: {
base: "h-full w-0.5 transition-colors",
dragging: "bg-primary/70",
rest: "bg-transparent group-hover:bg-border group-focus-visible:bg-primary/70",
dragging: "bg-mu-primary/70",
rest: "bg-transparent group-hover:bg-mu-line group-focus-visible:bg-mu-primary/70",
},
grip: {
base: "h-8 w-1 rounded-full transition-[background-color,opacity] duration-150",
dragging: "bg-primary/70 opacity-100",
rest: "bg-muted-foreground/50 opacity-0 group-hover:opacity-100 group-focus-visible:bg-primary/70 group-focus-visible:opacity-100",
dragging: "bg-mu-primary/70 opacity-100",
rest: "bg-mu-ink-muted/50 opacity-0 group-hover:opacity-100 group-focus-visible:bg-mu-primary/70 group-focus-visible:opacity-100",
},
} as const;
+24 -15
View File
@@ -1,8 +1,7 @@
import type { LucideIcon } from "lucide-react";
import type { ReactNode } from "react";
import { FOCUS_VISIBLE_OUTLINE_CLASSES } from "@/components/ui/focus";
import { cn } from "@/lib/utils";
import { SIDEBAR_LEADING_SLOT_CLASSES, sidebarSurfaceVariants } from "./sidebar-layout";
import { SCOPE_PANEL_ICON_CLASSES, SIDEBAR_LEADING_SLOT_CLASSES, sidebarSurfaceVariants } from "./sidebar-layout";
/**
* The rail's row rhythm — height, type scale, radius, padding, gap. Every list in the
@@ -13,20 +12,19 @@ import { SIDEBAR_LEADING_SLOT_CLASSES, sidebarSurfaceVariants } from "./sidebar-
*/
export const SIDEBAR_ROW_BOX_CLASSES = `${sidebarSurfaceVariants({ role: "row" })} group transition-colors`;
/** Goes on whichever element in a row actually takes focus. */
export const SIDEBAR_ROW_FOCUS_CLASSES = FOCUS_VISIBLE_OUTLINE_CLASSES;
export const SIDEBAR_ROW_CLASSES = `${SIDEBAR_ROW_BOX_CLASSES} mu-focus`;
export const SIDEBAR_ROW_CLASSES = `${SIDEBAR_ROW_BOX_CLASSES} ${SIDEBAR_ROW_FOCUS_CLASSES}`;
export const SIDEBAR_ROW_ICON_CLASSES = "me-auto size-4 shrink-0 opacity-75 group-data-checked:text-primary group-data-checked:opacity-100";
const SIDEBAR_ROW_COUNT_CLASSES = "text-2xs tabular-nums text-muted-foreground/60 group-data-checked:text-primary";
export const SIDEBAR_ROW_ICON_CLASSES =
// The md row's 16px icon at the md stroke, beside its 14px label, in the row's own muted ink.
"mu-icon me-auto shrink-0 group-data-checked:text-mu-primary";
const SIDEBAR_ROW_COUNT_CLASSES = "mu-caption tabular-nums text-mu-ink-muted group-data-checked:text-mu-primary";
/**
* The focusable body of a split row — rows whose box is a wrapper carrying other controls
* put their label layout and focus ring here. The gap must stay equal to the box's own
* `gap-1` or slot alignment breaks between one-control and split rows.
*/
export const SIDEBAR_ROW_LABEL_CLASSES = `flex h-full min-w-0 flex-1 items-center gap-1 text-start ${SIDEBAR_ROW_FOCUS_CLASSES}`;
export const SIDEBAR_ROW_LABEL_CLASSES = `flex h-full min-w-0 flex-1 items-center gap-1 text-start mu-focus`;
/**
* Fixed leading slot: a 20px column begins on the artwork rail. Small glyphs pin to its
@@ -36,7 +34,7 @@ export const SIDEBAR_ROW_LABEL_CLASSES = `flex h-full min-w-0 flex-1 items-cente
export const SIDEBAR_ROW_SLOT_CLASSES = SIDEBAR_LEADING_SLOT_CLASSES;
/** A slot that is itself a control (disclosure, row menu): same box plus the hover chip. */
export const SIDEBAR_ROW_SLOT_BUTTON_CLASSES = `${SIDEBAR_ROW_SLOT_CLASSES} relative rounded hover:bg-sidebar-accent after:absolute after:-inset-0.5 after:content-[''] ${SIDEBAR_ROW_FOCUS_CLASSES}`;
export const SIDEBAR_ROW_SLOT_BUTTON_CLASSES = `${SIDEBAR_ROW_SLOT_CLASSES} relative rounded hover:bg-mu-hover after:absolute after:-inset-0.5 after:content-[''] mu-focus`;
/** Trailing rail for counts, wide enough that digits align down the list. */
export const SIDEBAR_ROW_COUNT_RAIL_CLASSES = `${SIDEBAR_ROW_COUNT_CLASSES} min-w-[3ch] shrink-0 text-end`;
@@ -44,7 +42,17 @@ export const SIDEBAR_ROW_COUNT_RAIL_CLASSES = `${SIDEBAR_ROW_COUNT_CLASSES} min-
/** The standard icon-in-slot pairing, so every list renders its glyphs identically. */
export const SidebarRowIconSlot = ({ icon: Icon }: { icon: LucideIcon }) => (
<span className={SIDEBAR_ROW_SLOT_CLASSES} aria-hidden="true">
<Icon className={SIDEBAR_ROW_ICON_CLASSES} strokeWidth={1.8} />
<Icon className={SIDEBAR_ROW_ICON_CLASSES} />
</span>
);
/**
* The scope panel's leading icon (see sidebar-layout): links, actions and submenu triggers in
* the panel share the 20px leading slot with the sidebar rows above them.
*/
export const ScopePanelRowIcon = ({ icon: Icon, className }: { icon: LucideIcon; className?: string }) => (
<span className={SIDEBAR_LEADING_SLOT_CLASSES} aria-hidden="true">
<Icon className={cn(SCOPE_PANEL_ICON_CLASSES, className)} />
</span>
);
@@ -56,15 +64,16 @@ export const SidebarRowIconSlot = ({ icon: Icon }: { icon: LucideIcon }) => (
*/
export type SidebarRowState = "idle" | "current" | "checked";
const SIDEBAR_ROW_HOVER_CLASSES = "hover:bg-sidebar-accent/65 hover:text-foreground";
const SIDEBAR_ROW_HOVER_CLASSES = "hover:bg-mu-hover/65 hover:text-mu-ink";
export const sidebarRowStateClasses = (state: SidebarRowState = "idle") => {
if (state === "current") return "bg-sidebar-accent font-medium text-sidebar-accent-foreground";
// Selection never changes weight (the type rules), so labels do not shift: fill and color carry it.
if (state === "current") return "bg-mu-hover text-mu-ink";
if (state === "checked") {
// The mark hangs in the rail's 12px inset so the label stays on its rail.
return `relative font-medium text-foreground ${SIDEBAR_ROW_HOVER_CLASSES} before:absolute before:inset-y-1.5 before:-start-3 before:w-0.5 before:rounded-e-full before:bg-primary before:content-['']`;
return `relative text-mu-ink ${SIDEBAR_ROW_HOVER_CLASSES} before:absolute before:inset-y-1.5 before:-start-3 before:w-0.5 before:rounded-e-full before:bg-mu-primary before:content-['']`;
}
return `text-muted-foreground ${SIDEBAR_ROW_HOVER_CLASSES}`;
return `text-mu-ink-muted ${SIDEBAR_ROW_HOVER_CLASSES}`;
};
/** Goes on the row box so the icon slot and count rail inside it can take the checked colour. */
@@ -3,8 +3,6 @@ import SidebarSectionHeader from "./SidebarSectionHeader";
export const SIDEBAR_SECTION_STACK_CLASSES = "flex flex-col gap-3";
export const SIDEBAR_SECTION_CONTENT_CLASSES = "flex flex-col gap-0.5";
// Section actions are the kit's quiet `icon-sm` buttons; only their glyph is section-specific.
export const SIDEBAR_SECTION_ACTION_ICON_CLASSES = "size-3.5";
interface Props {
label?: ReactNode;
@@ -7,7 +7,9 @@ interface Props {
const SidebarSectionHeader = ({ children, action }: Props) => (
<div className="mb-0.5 flex h-6 min-w-0 items-center justify-between gap-2">
<h2 className="min-w-0 truncate ps-2 text-2xs font-normal uppercase tracking-wide text-muted-foreground/55 select-none">{children}</h2>
{/* Sentence case at the small label weight: it reads apart from the 400-weight muted rows by
weight and space, not by capitals or a size below the type scale. */}
<h2 className="min-w-0 truncate ps-2 mu-label-sm text-mu-ink-muted select-none">{children}</h2>
{action}
</div>
);
+134 -144
View File
@@ -1,13 +1,5 @@
import {
ArrowLeftIcon,
AstroidIcon,
ChevronsUpDownIcon,
CompassIcon,
HouseIcon,
LoaderCircleIcon,
type LucideIcon,
PlusIcon,
} from "lucide-react";
import { Button, menuClasses, Popover, Select, Spinner, Tooltip } from "@usememos/ui";
import { ArrowLeftIcon, AstroidIcon, ChevronsUpDownIcon, CompassIcon, HouseIcon, type LucideIcon, PlusIcon } from "lucide-react";
import { useRef, useState } from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import CreateSpaceDialog from "@/components/CreateSpaceDialog";
@@ -17,9 +9,6 @@ import SpaceMark from "@/components/SpaceMark";
import SpaceSelectItem from "@/components/SpaceSelectItem";
import UserAvatar from "@/components/UserAvatar";
import UserMenu from "@/components/UserMenu";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger } from "@/components/ui/select";
import { useSpaceContext } from "@/contexts/SpaceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useUser } from "@/hooks/useUserQueries";
@@ -27,8 +16,9 @@ import { extractSpaceUidFromName } from "@/lib/space-display";
import { cn } from "@/lib/utils";
import { buildCollectionPath, getCreatorSwitchPath, getSpaceSwitchPath, ROUTES } from "@/router/routes";
import { useTranslate } from "@/utils/i18n";
import { ScopePanelRowIcon } from "./SidebarRow";
import SidebarSectionHeader from "./SidebarSectionHeader";
import { sidebarSurfaceVariants } from "./sidebar-layout";
import { SCOPE_PANEL_ROW_CLASSES, SIDEBAR_LEADING_SLOT_CLASSES, sidebarSurfaceVariants } from "./sidebar-layout";
/** One half of the Home/Explore segmented control; the current half is raised. */
const BrowseLink = ({ to, current, icon: Icon, label }: { to: string; current: boolean; icon: LucideIcon; label: string }) => (
@@ -36,12 +26,12 @@ const BrowseLink = ({ to, current, icon: Icon, label }: { to: string; current: b
to={to}
aria-current={current ? "page" : undefined}
className={cn(
"flex h-7 min-w-0 items-center gap-1.5 rounded-sm px-1.5 text-ui font-medium hover:bg-background/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",
current && "bg-background ring-1 ring-border shadow-sm hover:bg-background",
"flex h-(--mu-row-height) min-w-0 items-center gap-1.5 rounded-mu-sm px-1.5 mu-label hover:bg-mu-canvas/60 mu-focus",
current && "bg-mu-canvas shadow-mu-key hover:bg-mu-canvas",
)}
>
<span className="flex size-5 shrink-0 items-center justify-center">
<Icon aria-hidden="true" className="size-3.5" strokeWidth={1.8} />
<span className={SIDEBAR_LEADING_SLOT_CLASSES}>
<Icon aria-hidden="true" className="mu-icon" />
</span>
<span className="min-w-0 truncate">{label}</span>
</Link>
@@ -96,13 +86,13 @@ function SpaceSwitcher({ className, size = "md" }: { className?: string; size?:
return (
<>
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger
<Popover.Root open={open} onOpenChange={handleOpenChange}>
<Popover.Trigger
ref={triggerRef}
aria-label={`${t("space.switch")}: ${triggerLabel}`}
title={triggerLabel}
className={cn(
"memos-brand-trigger text-start transition-colors hover:bg-sidebar-accent/65 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/40",
"memos-brand-trigger text-start transition-colors hover:bg-mu-hover/65 mu-focus",
sidebarSurfaceVariants({ role: size === "header" ? "headerBrand" : "mobileBrand" }),
className,
)}
@@ -121,7 +111,7 @@ function SpaceSwitcher({ className, size = "md" }: { className?: string; size?:
<svg
aria-hidden="true"
viewBox="0 0 10 20"
className="h-5 w-2.5 shrink-0 text-muted-foreground/35"
className="h-5 w-2.5 shrink-0 text-mu-ink-muted/35"
fill="none"
stroke="currentColor"
strokeWidth={1.25}
@@ -141,141 +131,141 @@ function SpaceSwitcher({ className, size = "md" }: { className?: string; size?:
)}
<ChevronsUpDownIcon
aria-hidden="true"
className={cn("shrink-0 text-muted-foreground/70", size === "header" ? "size-3" : "size-3.5")}
strokeWidth={1.8}
className={cn(size === "header" ? "mu-icon-xs" : "mu-icon-sm", "shrink-0 text-mu-ink-muted/70")}
/>
</PopoverTrigger>
<PopoverContent
</Popover.Trigger>
{/* A list of rows beside the sidebar, at its 28px row height. */}
<Popover.Popup
variant="list"
align="start"
positionMethod="fixed"
side="bottom"
sideOffset={4}
className="w-[min(15rem,calc(100vw-1rem))] max-h-[min(27rem,calc(100dvh-5rem))] overflow-y-auto p-0"
className="mu-compact w-[min(15rem,calc(100vw-1rem))] max-h-[min(27rem,calc(100dvh-5rem))] overflow-y-auto"
style={menuWidth ? { width: `${menuWidth}px` } : undefined}
>
{/* Guests have one collection, Explore, so they only get a way back to it from a creator. */}
{(currentUser || isOtherCreator) && (
<div className="flex flex-col p-1">
{isOtherCreator ? (
<Link
to={returnPath}
className="flex h-7 items-center gap-1.5 rounded-sm px-2 text-ui hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
>
<span className="flex size-5 shrink-0 items-center justify-center">
<ArrowLeftIcon aria-hidden="true" className="size-3.5 rtl:rotate-180" strokeWidth={1.8} />
</span>
{t("memo.back-to", { source: t(currentUser ? "common.home" : "common.explore") })}
</Link>
) : (
currentUser && (
<>
<div className="flex flex-col">
{isOtherCreator ? (
<Link to={returnPath} className={SCOPE_PANEL_ROW_CLASSES}>
<ScopePanelRowIcon icon={ArrowLeftIcon} className="rtl:rotate-180" />
{t("memo.back-to", { source: t(currentUser ? "common.home" : "common.explore") })}
</Link>
) : (
currentUser && (
<>
<SidebarSectionHeader>{t("common.browse")}</SidebarSectionHeader>
<nav aria-label={t("common.browse")} className="grid grid-cols-2 gap-0.5 rounded-mu-md bg-mu-well p-0.5">
<BrowseLink
to={getCreatorSwitchPath(location, currentUser.username, currentUser.username)}
current={Boolean(creatorUsername)}
icon={HouseIcon}
label={t("common.home")}
/>
<BrowseLink
to={getCreatorSwitchPath(location, undefined, currentUser.username)}
current={!creatorUsername}
icon={CompassIcon}
label={t("common.explore")}
/>
</nav>
</>
)
)}
{currentUser && (
<>
<SidebarSectionHeader>{t("common.browse")}</SidebarSectionHeader>
<nav aria-label={t("common.browse")} className="grid grid-cols-2 gap-0.5 rounded-md bg-muted p-0.5">
<BrowseLink
to={getCreatorSwitchPath(location, currentUser.username, currentUser.username)}
current={Boolean(creatorUsername)}
icon={HouseIcon}
label={t("common.home")}
/>
<BrowseLink
to={getCreatorSwitchPath(location, undefined, currentUser.username)}
current={!creatorUsername}
icon={CompassIcon}
label={t("common.explore")}
/>
</nav>
</>
)
)}
{currentUser && (
<>
<div className="mt-1">
<SidebarSectionHeader
action={
!isOtherCreator && (
<Button
variant="ghost"
size="icon-sm"
aria-label={t("space.create")}
title={t("space.create")}
onClick={() => {
setOpen(false);
setCreateOpen(true);
}}
className="me-[3px] text-muted-foreground hover:text-foreground"
>
<PlusIcon className="size-3.5" strokeWidth={1.8} />
</Button>
)
}
<div className="mt-1">
<SidebarSectionHeader
action={
!isOtherCreator && (
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
variant="ghost"
size="xs"
aria-label={t("space.create")}
onClick={() => {
setOpen(false);
setCreateOpen(true);
}}
className="me-[3px]"
icon={<PlusIcon />}
/>
}
/>
<Tooltip.Popup>{t("space.create")}</Tooltip.Popup>
</Tooltip.Root>
)
}
>
{t("space.spaces")}
</SidebarSectionHeader>
</div>
<Select.Root
value={selectedSpaceName ?? "all"}
items={[
{ value: "all", label: allSpacesLabel },
...spaces.map((space) => ({ value: space.name, label: space.title })),
...(selectedSpaceName && !spaces.some((space) => space.name === selectedSpaceName)
? [{ value: selectedSpaceName, label: spaceLabel }]
: []),
]}
onValueChange={(value) => {
if (value !== null) navigate(getSpaceSwitchPath(location, value === "all" ? undefined : value));
}}
>
{t("space.spaces")}
</SidebarSectionHeader>
</div>
<Select
value={selectedSpaceName ?? "all"}
onValueChange={(value) => {
if (value !== null) navigate(getSpaceSwitchPath(location, value === "all" ? undefined : value));
}}
>
<SelectTrigger
size="sm"
aria-label={t("space.switch")}
title={selectedSpaceName ? spaceLabel : allSpacesLabel}
// The border takes 1px of the row inset; the gap matches the panel rows.
className="w-full text-ui shadow-none data-[size=sm]:gap-1.5 data-[size=sm]:ps-[7px]"
>
{selectedSpaceName ? (
<SpaceMark icon={selectedSpace?.icon} size="sm" />
) : (
<span className="flex size-5 shrink-0 items-center justify-center">
<AstroidIcon className="size-3.5 text-muted-foreground" strokeWidth={1.8} />
</span>
)}
<span className="min-w-0 flex-1 truncate text-start">{selectedSpaceName ? spaceLabel : allSpacesLabel}</span>
</SelectTrigger>
<SelectContent
className="max-h-64 w-(--anchor-width) min-w-0 max-w-[calc(100vw-2rem)]"
align="start"
positionMethod="fixed"
>
<SelectItem value="all">
<span className="flex items-center gap-2">
<AstroidIcon className="size-4" />
{/* The current Space is switched in place, so the picker is a ghost row, not a key. */}
<Select.Trigger
variant="ghost"
aria-label={t("space.switch")}
title={selectedSpaceName ? spaceLabel : allSpacesLabel}
className="w-full"
>
{selectedSpaceName ? <SpaceMark icon={selectedSpace?.icon} size="sm" /> : <ScopePanelRowIcon icon={AstroidIcon} />}
<Select.Value />
</Select.Trigger>
<Select.Popup
className="max-h-64 w-(--anchor-width) min-w-0 max-w-[calc(100vw-2rem)]"
align="start"
positionMethod="fixed"
>
<Select.Item value="all" icon={<AstroidIcon />}>
{allSpacesLabel}
</span>
</SelectItem>
{spaces.map((space) => {
const uid = extractSpaceUidFromName(space.name);
return (
<SpaceSelectItem
key={space.name}
value={space.name}
label={duplicateSpaceTitles.has(space.title) ? `${space.title} (${uid})` : space.title}
icon={space.icon}
/>
);
})}
{isLoadingSpaces && (
<SelectItem value="loading" disabled>
<LoaderCircleIcon className="size-4 animate-spin" />
{t("space.loading")}
</SelectItem>
)}
{isSpacesError && spaces.length === 0 && (
<SelectItem value="error" disabled>
{t("space.load-error")}
</SelectItem>
)}
</SelectContent>
</Select>
</>
)}
</div>
</Select.Item>
{spaces.map((space) => {
const uid = extractSpaceUidFromName(space.name);
return (
<SpaceSelectItem
key={space.name}
value={space.name}
label={duplicateSpaceTitles.has(space.title) ? `${space.title} (${uid})` : space.title}
icon={space.icon}
/>
);
})}
{isLoadingSpaces && (
<Select.Item value="loading" disabled icon={<Spinner size="sm" label={t("space.loading")} />}>
{t("space.loading")}
</Select.Item>
)}
{isSpacesError && spaces.length === 0 && (
<Select.Item value="error" disabled>
{t("space.load-error")}
</Select.Item>
)}
</Select.Popup>
</Select.Root>
</>
)}
</div>
<div role="separator" className={menuClasses().separator} />
</>
)}
<UserMenu onClose={() => setOpen(false)} />
</PopoverContent>
</Popover>
</Popover.Popup>
</Popover.Root>
<CreateSpaceDialog open={createOpen} onOpenChange={setCreateOpen} onCreated={selectSpace} />
</>
);
+24 -34
View File
@@ -1,15 +1,6 @@
import { Button, Menu, Tooltip } from "@usememos/ui";
import { HashIcon, ListTreeIcon, MoreHorizontalIcon } from "lucide-react";
import { forwardRef, useMemo } from "react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
import { useLocalStorage, useOverflowTitle } from "@/hooks";
import { cn } from "@/lib/utils";
@@ -22,7 +13,7 @@ import {
sidebarRowStateAttributes,
sidebarRowStateClasses,
} from "./SidebarRow";
import SidebarSection, { SIDEBAR_SECTION_ACTION_ICON_CLASSES } from "./SidebarSection";
import SidebarSection from "./SidebarSection";
interface Props {
tagCount: Record<string, number>;
@@ -38,8 +29,8 @@ const TagPath = forwardRef<HTMLSpanElement, { tag: string }>(({ tag }, ref) => {
<span ref={ref} className="min-w-0 flex-1 truncate text-start">
{segments.map((segment, index) => (
<span key={`${segment}-${index}`}>
{index > 0 && <span className="px-0.5 text-muted-foreground/40">/</span>}
<span className={index === segments.length - 1 ? "text-current" : "text-muted-foreground/75"}>{segment}</span>
{index > 0 && <span className="px-0.5 text-mu-ink-muted/40">/</span>}
<span className={index === segments.length - 1 ? "text-current" : "text-mu-ink-muted/75"}>{segment}</span>
</span>
))}
</span>
@@ -105,28 +96,27 @@ const TagsSection = ({ tagCount, onSelect, scope }: Props) => {
<SidebarSection
label={t("common.tags")}
action={
<DropdownMenu>
<Tooltip>
<TooltipTrigger render={<span className="inline-flex" />}>
<DropdownMenuTrigger
aria-label={`${t("common.tags")}: ${t("common.more")}`}
render={<Button variant="quiet" size="icon-sm" />}
>
<MoreHorizontalIcon className={SIDEBAR_SECTION_ACTION_ICON_CLASSES} strokeWidth={1.8} />
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent side="top">{t("common.more")}</TooltipContent>
</Tooltip>
<DropdownMenuContent align="end" sideOffset={4} size="sm" className="w-44">
<DropdownMenuGroup>
<DropdownMenuLabel className="text-muted-foreground">{t("common.tags")}</DropdownMenuLabel>
<DropdownMenuCheckboxItem checked={treeMode} onCheckedChange={setTreeMode} closeOnClick indicator="end">
<ListTreeIcon className="text-muted-foreground" strokeWidth={1.8} />
<Menu.Root modal={false} size="sm">
<Tooltip.Root>
<Tooltip.Trigger
render={
<Menu.Trigger
aria-label={`${t("common.tags")}: ${t("common.more")}`}
render={<Button variant="ghost" size="xs" icon={<MoreHorizontalIcon />} />}
/>
}
/>
<Tooltip.Popup side="top">{t("common.more")}</Tooltip.Popup>
</Tooltip.Root>
<Menu.Popup align="end" className="w-44">
<Menu.Group>
<Menu.GroupLabel>{t("common.tags")}</Menu.GroupLabel>
<Menu.CheckboxItem checked={treeMode} onCheckedChange={setTreeMode} closeOnClick icon={<ListTreeIcon />}>
{t("common.tree-mode")}
</DropdownMenuCheckboxItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
</Menu.CheckboxItem>
</Menu.Group>
</Menu.Popup>
</Menu.Root>
}
>
{treeMode ? (
+27 -23
View File
@@ -1,12 +1,10 @@
import { useQueryClient } from "@tanstack/react-query";
import { Button, Menu, Tooltip } from "@usememos/ui";
import { MoreHorizontalIcon, PlusIcon } from "lucide-react";
import { useState } from "react";
import toast from "react-hot-toast";
import { useLocation, useNavigate } from "react-router-dom";
import ConfirmDialog from "@/components/ConfirmDialog";
import MemoViewIcon from "@/components/MemoViewIcon";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { userServiceClient } from "@/connect";
import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
@@ -14,6 +12,7 @@ import useCurrentUser from "@/hooks/useCurrentUser";
import { useMemoViews, userKeys } from "@/hooks/useUserQueries";
import { handleError } from "@/lib/error";
import { getMemoViewId, isMemoCollectionRoute } from "@/lib/memo-views";
import { showErrorToast, toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { getCollectionHomePath, ROUTES } from "@/router/routes";
import type { MemoView } from "@/types/proto/api/user_service_pb";
@@ -27,12 +26,12 @@ import SidebarRow, {
sidebarRowStateAttributes,
sidebarRowStateClasses,
} from "./SidebarRow";
import SidebarSection, { SIDEBAR_SECTION_ACTION_ICON_CLASSES } from "./SidebarSection";
import SidebarSection from "./SidebarSection";
/** The row's ⋯ menu: a trailing slot control that stays hidden until the row is engaged. */
const VIEW_MENU_TRIGGER_CLASSES = cn(
SIDEBAR_ROW_SLOT_BUTTON_CLASSES,
"text-muted-foreground transition-opacity md:opacity-0 md:group-hover/view:opacity-100 md:focus-visible:opacity-100 data-popup-open:opacity-100",
"text-mu-ink-muted transition-opacity md:opacity-0 md:group-hover/view:opacity-100 md:focus-visible:opacity-100 data-popup-open:opacity-100",
);
const ViewsSection = ({ manageActive = false }: { manageActive?: boolean }) => {
@@ -63,9 +62,9 @@ const ViewsSection = ({ manageActive = false }: { manageActive?: boolean }) => {
await userServiceClient.deleteMemoView({ name: deleteTarget.name });
await queryClient.invalidateQueries({ queryKey: userKeys.memoViews(currentUser?.name) });
if (selectedMemoView === getMemoViewId(deleteTarget.name)) setMemoView(undefined);
toast.success(t("setting.memo-view.delete-success", { title: deleteTarget.title }));
toast.add({ title: t("setting.memo-view.delete-success", { title: deleteTarget.title }), type: "success" });
} catch (error: unknown) {
handleError(error, toast.error, { context: "Delete memo view" });
handleError(error, showErrorToast, { context: "Delete memo view" });
} finally {
setDeleteTarget(undefined);
}
@@ -77,9 +76,14 @@ const ViewsSection = ({ manageActive = false }: { manageActive?: boolean }) => {
action={
!manageActive &&
(memoViews.length > 0 || isError) && (
<Button variant="quiet" size="icon-sm" onClick={handleCreate} aria-label={t("setting.memo-view.create")}>
<PlusIcon className={SIDEBAR_SECTION_ACTION_ICON_CLASSES} strokeWidth={1.8} />
</Button>
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button variant="ghost" size="xs" onClick={handleCreate} aria-label={t("setting.memo-view.create")} icon={<PlusIcon />} />
}
/>
<Tooltip.Popup>{t("setting.memo-view.create")}</Tooltip.Popup>
</Tooltip.Root>
)
}
>
@@ -98,12 +102,12 @@ const ViewsSection = ({ manageActive = false }: { manageActive?: boolean }) => {
>
<button type="button" onClick={() => handleView(id)} aria-pressed={active || undefined} className={SIDEBAR_ROW_LABEL_CLASSES}>
<span className={SIDEBAR_ROW_SLOT_CLASSES} aria-hidden="true">
<MemoViewIcon icon={memoView.icon} className={cn(SIDEBAR_ROW_ICON_CLASSES, "text-base")} />
<MemoViewIcon icon={memoView.icon} className={cn(SIDEBAR_ROW_ICON_CLASSES, "text-sm")} />
</span>
<span className="min-w-0 flex-1 truncate">{memoView.title}</span>
</button>
<DropdownMenu>
<DropdownMenuTrigger
<Menu.Root modal={false} size="sm">
<Menu.Trigger
nativeButton={false}
render={
<span
@@ -114,22 +118,22 @@ const ViewsSection = ({ manageActive = false }: { manageActive?: boolean }) => {
/>
}
>
<MoreHorizontalIcon className="size-3.5" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={2} size="sm">
<DropdownMenuItem
<MoreHorizontalIcon className="mu-icon-sm" />
</Menu.Trigger>
<Menu.Popup align="end">
<Menu.Item
onClick={() => {
navigate(ROUTES.VIEWS, { state: { memoView } });
setMobileOpen(false);
}}
>
{t("common.edit")}
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={() => setDeleteTarget(memoView)}>
</Menu.Item>
<Menu.Item onClick={() => setDeleteTarget(memoView)} danger>
{t("common.delete")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</Menu.Item>
</Menu.Popup>
</Menu.Root>
</div>
);
})}
@@ -141,7 +145,7 @@ const ViewsSection = ({ manageActive = false }: { manageActive?: boolean }) => {
confirmLabel={t("common.delete")}
cancelLabel={t("common.cancel")}
onConfirm={handleDelete}
confirmVariant="destructive"
confirmVariant="danger"
/>
</SidebarSection>
);
@@ -1,11 +1,13 @@
import { menuClasses } from "@usememos/ui";
import { cva } from "class-variance-authority";
/**
* The sidebar is drawn on one shared rail: inset surfaces start 12px from the shell,
* visible artwork starts at 20px, and first-level labels start at 44px. The full-bleed
* footer action pads its content directly onto those same rails. Rows reserve a 20px
* artwork column. Compact navigation is a 28px square like the header's compose control,
* with 6px padding around each glyph and a 6px gap before its label.
* artwork column. The sidebar carries the package's `mu-compact`, so its md rows and
* controls are 28px tall: rows read their height and radius from the md row variables,
* and compact navigation is a 28px square like the header's compose control.
*/
export const SIDEBAR_RAIL_CLASSES = "px-3";
// Content rows reserve 20px so 16px icons and 20px marks share a stable label rail.
@@ -23,15 +25,23 @@ export const SIDEBAR_NAV_LEADING_SLOT_CLASSES = "flex size-4 shrink-0 items-cent
export const sidebarSurfaceVariants = cva("min-w-0 items-center", {
variants: {
role: {
row: "flex h-7 w-full gap-1 rounded-md px-2 text-ui",
navPill: "relative flex h-7 shrink-0 rounded-md px-1.5",
headerBrand: "flex h-9 max-w-full gap-2 rounded-md px-2",
mobileBrand: "flex h-9 max-w-full gap-1.5 rounded-md px-1",
row: "mu-s-md flex h-(--mu-row-height) w-full gap-1 rounded-(--mu-row-radius) px-2 mu-body",
navPill: "mu-s-md relative flex h-(--mu-row-height) shrink-0 rounded-(--mu-row-radius) px-1.5",
headerBrand: "flex h-9 max-w-full gap-2 rounded-mu-md px-2",
mobileBrand: "flex h-9 max-w-full gap-1.5 rounded-mu-md px-1",
account: "flex h-9 w-full gap-1 rounded-none px-5",
accountCollapsed: "ms-3 flex size-9 rounded-md p-2",
accountCollapsed: "ms-3 flex size-9 rounded-mu-md p-2",
},
},
defaultVariants: {
role: "row",
},
});
/**
* The scope panel that opens from the sidebar title is a list Popover with `mu-compact`, so its
* rows are the package's menu rows at 28px. Each keeps a 20px leading slot, so icons, the avatar
* and Space marks share one column; a Popover sets no highlight, so the rows add their own hover.
*/
export const SCOPE_PANEL_ROW_CLASSES = `${menuClasses().item} transition-colors hover:bg-mu-hover data-popup-open:bg-mu-hover aria-[current=page]:bg-mu-hover mu-focus`;
export const SCOPE_PANEL_ICON_CLASSES = "mu-icon text-mu-ink-muted";
-116
View File
@@ -1,116 +0,0 @@
import {
BinaryIcon,
BookIcon,
FileArchiveIcon,
FileAudioIcon,
FileEditIcon,
FileIcon,
FileTextIcon,
FileVideo2Icon,
SheetIcon,
} from "lucide-react";
import React, { useState } from "react";
import { cn } from "@/lib/utils";
import { Attachment } from "@/types/proto/api/attachment_service_pb";
import { getAttachmentThumbnailUrl, getAttachmentType, getAttachmentUrl } from "@/utils/attachment";
import SquareDiv from "./kit/SquareDiv";
import PreviewImageDialog from "./PreviewImageDialog";
interface Props {
attachment: Attachment;
className?: string;
strokeWidth?: number;
}
const AttachmentIcon = (props: Props) => {
const { attachment } = props;
const [previewImage, setPreviewImage] = useState<{ open: boolean; index: number }>({
open: false,
index: 0,
});
const resourceType = getAttachmentType(attachment);
const attachmentUrl = getAttachmentUrl(attachment);
const className = cn("w-full h-auto", props.className);
const strokeWidth = props.strokeWidth;
const previewResource = () => {
window.open(attachmentUrl);
};
const handleImageClick = () => {
setPreviewImage({ open: true, index: 0 });
};
if (resourceType === "image/*") {
return (
<>
<SquareDiv className={cn(className, "flex items-center justify-center overflow-clip")}>
<img
className="min-w-full min-h-full object-cover"
src={getAttachmentThumbnailUrl(attachment)}
onClick={handleImageClick}
onError={(e) => {
// Fallback to original image if thumbnail fails
const target = e.target as HTMLImageElement;
if (target.src.includes("?thumbnail=true")) {
console.warn("Thumbnail failed, falling back to original image:", attachmentUrl);
target.src = attachmentUrl;
}
}}
decoding="async"
loading="lazy"
/>
</SquareDiv>
<PreviewImageDialog
open={previewImage.open}
onOpenChange={(open) => setPreviewImage((prev) => ({ ...prev, open }))}
items={[
{
id: attachment.name,
kind: "image",
sourceUrl: attachmentUrl,
posterUrl: getAttachmentThumbnailUrl(attachment),
filename: attachment.filename,
attachments: [attachment],
},
]}
initialIndex={previewImage.index}
/>
</>
);
}
const getAttachmentIcon = () => {
switch (resourceType) {
case "video/*":
return <FileVideo2Icon strokeWidth={strokeWidth} className="w-full h-auto" />;
case "audio/*":
return <FileAudioIcon strokeWidth={strokeWidth} className="w-full h-auto" />;
case "text/*":
return <FileTextIcon strokeWidth={strokeWidth} className="w-full h-auto" />;
case "application/epub+zip":
return <BookIcon strokeWidth={strokeWidth} className="w-full h-auto" />;
case "application/pdf":
return <BookIcon strokeWidth={strokeWidth} className="w-full h-auto" />;
case "application/msword":
return <FileEditIcon strokeWidth={strokeWidth} className="w-full h-auto" />;
case "application/msexcel":
return <SheetIcon strokeWidth={strokeWidth} className="w-full h-auto" />;
case "application/zip":
return <FileArchiveIcon onClick={previewResource} strokeWidth={strokeWidth} className="w-full h-auto" />;
case "application/x-java-archive":
return <BinaryIcon strokeWidth={strokeWidth} className="w-full h-auto" />;
default:
return <FileIcon strokeWidth={strokeWidth} className="w-full h-auto" />;
}
};
return (
<div onClick={previewResource} className={cn(className, "max-w-16 opacity-50")}>
{getAttachmentIcon()}
</div>
);
};
export default React.memo(AttachmentIcon);
@@ -15,7 +15,7 @@ const AttachmentThumb = ({ item, className }: { item: AttachmentLibraryListItem;
if (type === "image/*" || isMotion) {
return (
<div className={cn("overflow-hidden rounded-xl bg-muted/35", className)}>
<div className={cn("overflow-hidden rounded-mu-xl bg-mu-well/35", className)}>
<img
src={getAttachmentThumbnailUrl(item.attachment)}
alt={item.attachment.filename}
@@ -29,18 +29,18 @@ const AttachmentThumb = ({ item, className }: { item: AttachmentLibraryListItem;
if (type === "video/*") {
return (
<div className={cn("relative overflow-hidden rounded-xl bg-muted/35", className)}>
<div className={cn("relative overflow-hidden rounded-mu-xl bg-mu-well/35", className)}>
<VideoPoster sourceUrl={item.sourceUrl} alt={item.attachment.filename} className="h-full w-full object-cover" />
<span className="absolute bottom-2 right-2 inline-flex h-7 w-7 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm">
<PlayIcon className="h-3.5 w-3.5 fill-current" />
<span className="absolute bottom-2 right-2 inline-flex h-7 w-7 items-center justify-center rounded-full bg-mu-canvas/85 text-mu-ink">
<PlayIcon className="mu-icon-sm fill-current" />
</span>
</div>
);
}
return (
<div className={cn("flex items-center justify-center rounded-xl bg-muted/45 text-muted-foreground", className)}>
{type === "audio/*" ? <FileAudioIcon className="h-5 w-5" /> : <FileIcon className="h-5 w-5" />}
<div className={cn("flex items-center justify-center rounded-mu-xl bg-mu-well/45 text-mu-ink-muted", className)}>
{type === "audio/*" ? <FileAudioIcon className="mu-icon h-5 w-5" /> : <FileIcon className="mu-icon h-5 w-5" />}
</div>
);
};
@@ -51,14 +51,14 @@ export const AttachmentDocumentRows = ({ items, creators }: { items: AttachmentL
{items.map((item) => (
<article
key={item.attachment.name}
className="flex items-center gap-2.5 rounded-[18px] border border-border/60 bg-background/90 p-3 shadow-sm shadow-black/[0.02]"
className="flex items-center gap-2.5 rounded-[18px] border border-mu-line/60 bg-mu-canvas/90 p-3"
>
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-muted/45 text-muted-foreground">
<FileIcon className="h-4.5 w-4.5" />
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-mu-lg bg-mu-well/45 text-mu-ink-muted">
<FileIcon className="mu-icon h-4.5 w-4.5" />
</div>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-foreground" title={item.attachment.filename}>
<div className="truncate mu-label text-mu-ink" title={item.attachment.filename}>
{item.attachment.filename}
</div>
<div className="mt-0.5 flex flex-wrap items-center gap-1.5">
@@ -79,17 +79,14 @@ export const AttachmentAudioRows = ({ items, creators }: { items: AttachmentLibr
return (
<div className="space-y-2.5">
{items.map((item) => (
<article
key={item.attachment.name}
className="rounded-[18px] border border-border/60 bg-background/90 p-2.5 shadow-sm shadow-black/[0.02]"
>
<article key={item.attachment.name} className="rounded-[18px] border border-mu-line/60 bg-mu-canvas/90 p-2.5">
<AudioAttachmentItem
filename={item.attachment.filename}
sourceUrl={item.sourceUrl}
mimeType={item.attachment.type}
size={Number(item.attachment.size)}
/>
<div className="mt-2.5 flex items-center justify-between gap-2 border-t border-border/60 px-0.5 pt-2.5">
<div className="mt-2.5 flex items-center justify-between gap-2 border-t border-mu-line/60 px-0.5 pt-2.5">
<div className="min-w-0 flex flex-wrap items-center gap-1.5">
<AttachmentMetadataLine className="min-w-0 max-w-full" items={[item.createdLabel]} />
<AttachmentCreator creatorName={item.attachment.creator} user={creators?.get(item.attachment.creator)} />
@@ -109,12 +106,12 @@ export const AttachmentUnusedRows = ({ items, creators }: { items: AttachmentLib
{items.map((item) => (
<article
key={item.attachment.name}
className="flex items-center gap-2.5 rounded-[18px] border border-warning/30 bg-warning/5 p-3 shadow-sm shadow-black/[0.02]"
className="flex items-center gap-2.5 rounded-[18px] border border-mu-warning/30 bg-mu-warning-soft p-3"
>
<AttachmentThumb item={item} className="h-10 w-10 shrink-0" />
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-foreground" title={item.attachment.filename}>
<div className="truncate mu-label text-mu-ink" title={item.attachment.filename}>
{item.attachment.filename}
</div>
<div className="mt-0.5 flex flex-wrap items-center gap-1.5">
@@ -124,7 +121,7 @@ export const AttachmentUnusedRows = ({ items, creators }: { items: AttachmentLib
</div>
</div>
<AttachmentOpenButton className="text-warning/90 hover:text-warning" href={item.sourceUrl} />
<AttachmentOpenButton className="text-mu-warning/90 hover:text-mu-warning" href={item.sourceUrl} />
</article>
))}
</div>
@@ -41,15 +41,15 @@ const AttachmentLibraryEmptyState = ({ className, tab }: AttachmentLibraryEmptyS
return (
<div
className={cn(
"flex min-h-[18rem] flex-col items-center justify-center rounded-[28px] border border-dashed border-border/70 bg-background/80 px-6 py-16 text-center",
"flex min-h-[18rem] flex-col items-center justify-center rounded-[28px] border border-dashed border-mu-line/70 bg-mu-canvas/80 px-6 py-16 text-center",
className,
)}
>
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-muted/45 text-muted-foreground">
<Icon className="h-7 w-7" />
<div className="flex h-16 w-16 items-center justify-center rounded-full bg-mu-well/45 text-mu-ink-muted">
<Icon className="mu-icon size-7" />
</div>
<div className="mt-5 text-sm font-medium text-foreground">{t(titleKey)}</div>
<p className="mt-2 max-w-sm text-sm leading-6 text-muted-foreground">{t(descriptionKey)}</p>
<div className="mt-5 mu-label text-mu-ink">{t(titleKey)}</div>
<p className="mt-2 max-w-sm mu-body text-mu-ink-muted">{t(descriptionKey)}</p>
</div>
);
};
@@ -1,9 +1,8 @@
import { Badge, buttonClasses, Tooltip } from "@usememos/ui";
import { ExternalLinkIcon } from "lucide-react";
import { Link, useLocation } from "react-router-dom";
import { createMemoNavigationState } from "@/components/MemoView/navigation";
import UserAvatar from "@/components/UserAvatar";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { extractUsernameFromName } from "@/lib/resource-names";
import { cn } from "@/lib/utils";
import { getCreatorHomePath } from "@/router/routes";
@@ -39,7 +38,7 @@ export const AttachmentCreator = ({ creatorName, user }: AttachmentCreatorProps)
return (
<Link
to={getCreatorHomePath(username)}
className="inline-flex min-w-0 max-w-full items-center gap-1.5 rounded-sm text-xs text-muted-foreground hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
className="inline-flex min-w-0 max-w-full items-center gap-1.5 rounded-mu-sm mu-caption text-mu-ink-muted hover:text-mu-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-mu-focus"
viewTransition
>
<UserAvatar className="size-4" avatarUrl={user?.avatarUrl} name={displayName} />
@@ -58,13 +57,13 @@ export const AttachmentMetadataLine = ({ className, items }: AttachmentMetadataL
return (
<div
className={cn(
"flex items-center gap-1.5 overflow-x-auto whitespace-nowrap text-xs text-muted-foreground [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
"flex items-center gap-1.5 overflow-x-auto whitespace-nowrap mu-caption text-mu-ink-muted [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
className,
)}
>
{visibleItems.map((item, index) => (
<span key={`${item}-${index}`} className="contents">
{index > 0 && <span className="shrink-0 text-muted-foreground/50">•</span>}
{index > 0 && <span className="shrink-0 text-mu-ink-muted/50">•</span>}
<span className="shrink-0">{item}</span>
</span>
))}
@@ -80,18 +79,14 @@ export const AttachmentSourceChip = ({
const t = useTranslate();
if (!memoName) {
return (
<Badge variant="warning" shape="pill" className="px-1.5 py-0.5 text-[11px]">
{t(unlinkedLabelKey)}
</Badge>
);
return <Badge tone="warning">{t(unlinkedLabelKey)}</Badge>;
}
return (
<Link
to={`/${memoName}`}
state={createMemoNavigationState(`${location.pathname}${location.search}`)}
className="inline-flex max-w-full items-center truncate rounded-full border border-border/60 bg-muted/30 px-1.5 py-0.5 text-[11px] text-muted-foreground hover:bg-muted/50"
className="inline-flex max-w-full items-center truncate rounded-full border border-mu-line/60 bg-mu-well/30 px-1.5 py-0.5 mu-caption text-mu-ink-muted hover:bg-mu-hover"
>
<span className="truncate">{t("attachment-library.labels.memo")}</span>
</Link>
@@ -102,14 +97,21 @@ export const AttachmentOpenButton = ({ className, href }: AttachmentOpenButtonPr
const t = useTranslate();
return (
<Button
render={<a href={href} target="_blank" rel="noreferrer" />}
variant="ghost"
size="icon"
className={cn("size-7 shrink-0 rounded-full text-muted-foreground hover:text-foreground", className)}
>
<ExternalLinkIcon className="h-3.5 w-3.5" />
<span className="sr-only">{t("attachment-library.actions.open")}</span>
</Button>
<Tooltip.Root>
<Tooltip.Trigger
render={
<a
href={href}
target="_blank"
rel="noreferrer"
className={cn(buttonClasses({ variant: "ghost", size: "sm", iconOnly: true }), "shrink-0", className)}
aria-label={t("attachment-library.actions.open")}
>
<ExternalLinkIcon className="mu-icon" />
</a>
}
/>
<Tooltip.Popup>{t("attachment-library.actions.open")}</Tooltip.Popup>
</Tooltip.Root>
);
};
@@ -1,5 +1,4 @@
import { LoaderCircleIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Button, Skeleton } from "@usememos/ui";
import { useTranslate } from "@/utils/i18n";
interface AttachmentLibraryErrorStateProps {
@@ -11,24 +10,16 @@ interface AttachmentLibrarySkeletonGridProps {
count?: number;
}
interface AttachmentLibraryUnusedPanelProps {
count: number;
isDeleting: boolean;
isExpanded: boolean;
onDelete: () => void;
onToggle: () => void;
}
export const AttachmentLibrarySkeletonGrid = ({ count = 8 }: AttachmentLibrarySkeletonGridProps) => {
return (
<div className="grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-3 xl:grid-cols-4">
{Array.from({ length: count }).map((_, index) => (
<div key={index} className="overflow-hidden rounded-[20px] border border-border/60 bg-background/90">
<div className="aspect-[5/4] animate-pulse bg-muted/50" />
<div key={index} className="overflow-hidden rounded-[20px] border border-mu-line/60 bg-mu-canvas/90">
<Skeleton className="aspect-[5/4] h-auto" />
<div className="space-y-2.5 p-3">
<div className="h-4 w-2/3 animate-pulse rounded bg-muted/50" />
<div className="h-3 w-1/2 animate-pulse rounded bg-muted/40" />
<div className="h-7 w-full animate-pulse rounded bg-muted/40" />
<Skeleton width="66%" height={16} />
<Skeleton width="50%" height={12} />
<Skeleton height={28} />
</div>
</div>
))}
@@ -40,38 +31,11 @@ export const AttachmentLibraryErrorState = ({ error, onRetry }: AttachmentLibrar
const t = useTranslate();
return (
<div className="rounded-[20px] border border-destructive/30 bg-destructive/5 p-6 text-center">
<p className="text-sm text-muted-foreground">{error?.message ?? t("attachment-library.errors.load")}</p>
<Button className="mt-4 rounded-full" onClick={onRetry}>
<div className="p-6 text-center" role="alert">
<p className="mu-body text-mu-ink-muted">{error?.message ?? t("attachment-library.errors.load")}</p>
<Button variant="primary" className="mt-4" onClick={onRetry}>
{t("attachment-library.actions.retry")}
</Button>
</div>
);
};
export const AttachmentLibraryUnusedPanel = ({ count, isDeleting, isExpanded, onDelete, onToggle }: AttachmentLibraryUnusedPanelProps) => {
const t = useTranslate();
return (
<div className="rounded-2xl border border-warning/30 bg-warning/5 p-4">
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div className="min-w-0">
<div className="text-sm font-medium text-foreground">
{t("attachment-library.unused.title")} ({count})
</div>
<p className="mt-1 text-sm text-muted-foreground">{t("attachment-library.unused.description")}</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button type="button" variant="outline" className="rounded-full border-warning/40 bg-background/80 px-3" onClick={onToggle}>
{isExpanded ? t("common.close") : t("attachment-library.labels.unused")}
</Button>
<Button variant="destructive" className="rounded-full" onClick={onDelete} disabled={isDeleting}>
{isDeleting ? <LoaderCircleIcon className="h-4 w-4 animate-spin" /> : null}
{t("resource.delete-all-unused")}
</Button>
</div>
</div>
</div>
);
};
@@ -1,8 +1,7 @@
import { Toggle, ToggleGroup } from "@usememos/ui";
import { FileAudioIcon, FileStackIcon, ImageIcon } from "lucide-react";
import type { ComponentType } from "react";
import { Button } from "@/components/ui/button";
import type { AttachmentLibraryStats, AttachmentLibraryTab } from "@/hooks/useAttachmentLibrary";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
interface AttachmentLibraryToolbarProps {
@@ -27,36 +26,21 @@ const AttachmentLibraryToolbar = ({ activeTab, onTabChange, stats }: AttachmentL
return (
<div className="-mx-1 overflow-x-auto px-1 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<div className="flex min-w-max items-center gap-1.5">
<ToggleGroup
aria-label={t("common.attachments")}
value={[activeTab]}
onValueChange={([next]: string[]) => next && onTabChange(next as AttachmentLibraryTab)}
>
{TAB_CONFIG.map((tab) => {
const Icon = tab.icon;
const isActive = activeTab === tab.key;
return (
<Button
key={tab.key}
type="button"
variant="ghost"
className={cn(
"h-9 rounded-md px-2.5 text-sm font-medium sm:px-3",
isActive ? "bg-muted/60 text-foreground shadow-none" : "text-muted-foreground hover:bg-muted/40 hover:text-foreground",
)}
onClick={() => onTabChange(tab.key)}
>
<Icon className="h-4 w-4" />
<span>{t(`attachment-library.tabs.${tab.labelKey}`)}</span>
<span
className={cn(
"rounded-full px-1.5 py-0.5 text-[11px]",
isActive ? "bg-background text-muted-foreground" : "bg-muted/50 text-muted-foreground",
)}
>
{tab.count(stats)}
</span>
</Button>
<Toggle key={tab.key} value={tab.key} icon={<Icon />}>
{t(`attachment-library.tabs.${tab.labelKey}`)}
<span className="ms-1 tabular-nums text-mu-ink-muted">{tab.count(stats)}</span>
</Toggle>
);
})}
</div>
</ToggleGroup>
</div>
);
};
@@ -1,6 +1,6 @@
import { Badge } from "@usememos/ui";
import { PlayIcon } from "lucide-react";
import MotionPhotoPreview from "@/components/MotionPhotoPreview";
import { Badge } from "@/components/ui/badge";
import VideoPoster from "@/components/VideoPoster";
import type { AttachmentLibraryMediaItem, AttachmentLibraryMonthGroup } from "@/hooks/useAttachmentLibrary";
import { cn } from "@/lib/utils";
@@ -21,9 +21,9 @@ const AttachmentMediaCard = ({ item, creator, onPreview }: { item: AttachmentLib
?.value.durationSeconds;
return (
<article className="overflow-hidden rounded-[20px] border border-border/60 bg-background/90 shadow-sm shadow-black/[0.03]">
<article className="overflow-hidden rounded-[20px] border border-mu-line/60 bg-mu-canvas/90">
<div className="relative block w-full cursor-pointer text-left" onClick={onPreview}>
<div className="relative aspect-[5/4] overflow-hidden bg-muted/40">
<div className="relative aspect-[5/4] overflow-hidden bg-mu-well/40">
{item.kind === "video" ? (
<>
<VideoPoster
@@ -35,11 +35,11 @@ const AttachmentMediaCard = ({ item, creator, onPreview }: { item: AttachmentLib
<div className="absolute inset-0 bg-linear-to-t from-black/35 via-black/5 to-transparent" />
<span
className={cn(
"absolute bottom-2.5 right-2.5 inline-flex h-8 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm backdrop-blur-sm",
videoDuration === undefined ? "w-8" : "gap-1.5 px-2.5 text-[11px] font-medium tabular-nums",
"absolute bottom-2.5 right-2.5 inline-flex h-8 items-center justify-center rounded-full bg-mu-canvas/85 text-mu-ink backdrop-blur-sm",
videoDuration === undefined ? "w-8" : "gap-1.5 px-2.5 mu-label-sm tabular-nums",
)}
>
<PlayIcon className="h-3.5 w-3.5 fill-current" />
<PlayIcon className="mu-icon-sm fill-current" />
{videoDuration !== undefined && <span>{formatMediaDuration(videoDuration)}</span>}
</span>
</>
@@ -61,15 +61,11 @@ const AttachmentMediaCard = ({ item, creator, onPreview }: { item: AttachmentLib
<div className="flex flex-col gap-2 p-3">
<div className="flex items-start justify-between gap-2">
<div className="min-w-0 truncate text-sm font-medium leading-5 text-foreground" title={item.filename}>
<div className="min-w-0 truncate mu-label text-mu-ink" title={item.filename}>
{item.filename}
</div>
{item.kind === "motion" && (
<Badge variant="outline" className="rounded-full border-border/60 bg-background/70 px-1.5 py-0.5 text-[11px]">
{t("attachment-library.labels.live")}
</Badge>
)}
{item.kind === "motion" && <Badge tone="outline">{t("attachment-library.labels.live")}</Badge>}
</div>
<AttachmentMetadataLine
@@ -92,8 +88,8 @@ const AttachmentMediaGrid = ({ groups, creators, onPreview }: AttachmentMediaGri
{groups.map((group) => (
<section key={group.key} className="space-y-2.5 sm:space-y-3">
<div className="flex items-center gap-2.5">
<div className="text-xs font-medium uppercase tracking-[0.24em] text-muted-foreground">{group.label}</div>
<div className="h-px flex-1 bg-border/70" />
<div className="mu-label-sm uppercase tracking-[0.24em] text-mu-ink-muted">{group.label}</div>
<div className="h-px flex-1 bg-mu-line/70" />
</div>
<div className="grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-3 xl:grid-cols-4">
@@ -1,6 +1,6 @@
export { AttachmentAudioRows, AttachmentDocumentRows, AttachmentUnusedRows } from "./AttachmentFileRows";
export { default as AttachmentLibraryEmptyState } from "./AttachmentLibraryEmptyState";
export { AttachmentMetadataLine, AttachmentOpenButton, AttachmentSourceChip } from "./AttachmentLibraryPrimitives";
export { AttachmentLibraryErrorState, AttachmentLibrarySkeletonGrid, AttachmentLibraryUnusedPanel } from "./AttachmentLibraryStates";
export { AttachmentLibraryErrorState, AttachmentLibrarySkeletonGrid } from "./AttachmentLibraryStates";
export { default as AttachmentLibraryToolbar } from "./AttachmentLibraryToolbar";
export { default as AttachmentMediaGrid } from "./AttachmentMediaGrid";
+15 -14
View File
@@ -1,3 +1,4 @@
import { Skeleton } from "@usememos/ui";
import { ArrowRightIcon, CompassIcon } from "lucide-react";
import { Link } from "react-router-dom";
import { useInstance } from "@/contexts/InstanceContext";
@@ -17,7 +18,7 @@ interface Props {
}
export const AuthChip = ({ children }: { children: React.ReactNode }) => (
<span className="inline-flex w-fit items-center gap-1.5 rounded-full border border-border bg-accent/50 px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
<span className="inline-flex w-fit items-center gap-1.5 rounded-full border border-mu-line bg-mu-hover/50 px-2.5 py-0.5 mu-label-sm uppercase tracking-widest text-mu-ink-muted">
{children}
</span>
);
@@ -35,24 +36,24 @@ export const AuthEmptyState = ({
children?: React.ReactNode;
}) => (
<div className="flex flex-col items-center py-2 text-center">
<div className="mb-3 flex h-11 w-11 items-center justify-center rounded-full bg-accent text-muted-foreground">{icon}</div>
<p className="text-sm font-medium text-foreground">{title}</p>
<p className="mt-1 text-sm text-muted-foreground">{description}</p>
<div className="mb-3 flex h-11 w-11 items-center justify-center rounded-full bg-mu-hover text-mu-ink-muted">{icon}</div>
<p className="mu-label text-mu-ink">{title}</p>
<p className="mt-1 mu-body text-mu-ink-muted">{description}</p>
{children}
</div>
);
// "Already have an account? Sign in" style prompt for hopping between auth pages.
export const AuthLinkPrompt = ({ prompt, to, label }: { prompt: string; to: string; label: string }) => (
<p className="mt-5 text-center text-sm text-muted-foreground">
<p className="mt-5 text-center mu-body text-mu-ink-muted">
{prompt}{" "}
<Link to={to} className="text-primary hover:underline" viewTransition>
<Link to={to} className="text-mu-accent hover:underline" viewTransition>
{label}
</Link>
</p>
);
export const AuthOptionsLoading = () => <div className="h-9 w-full animate-pulse rounded-md bg-muted/60" aria-hidden="true" />;
export const AuthOptionsLoading = () => <Skeleton height={32} />;
const AuthPageLayout = ({ chip, title, subtitle, hideExplore, children }: Props) => {
const t = useTranslate();
@@ -62,22 +63,22 @@ const AuthPageLayout = ({ chip, title, subtitle, hideExplore, children }: Props)
return (
<div className="min-h-svh w-full flex flex-col items-center px-4 py-4 sm:py-8">
<div className="w-full grow flex flex-col justify-center items-center">
<div className="w-90 max-w-full rounded-xl border border-border bg-card p-7 shadow-sm">
<div className="w-90 max-w-full rounded-mu-xl border border-mu-line bg-mu-surface p-7">
<MemosLogo size="lg" className="mb-8" />
{chip && <div className="mb-2">{chip}</div>}
<h1 className="text-lg font-semibold tracking-tight text-foreground">{title}</h1>
{subtitle && <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>}
<h1 className="mu-heading text-mu-ink">{title}</h1>
{subtitle && <p className="mt-1 mu-body text-mu-ink-muted">{subtitle}</p>}
<div className="mt-6 w-full">{children}</div>
{showExplore && (
<div className="-mx-7 -mb-7 mt-6 rounded-b-xl border-t border-border bg-background/60">
<div className="-mx-7 -mb-7 mt-6 rounded-b-mu-xl border-t border-mu-line bg-mu-canvas/60">
<Link
to={ROUTES.EXPLORE}
className="group flex items-center justify-center gap-2 px-7 py-3 text-[13px] text-muted-foreground transition-colors hover:text-foreground"
className="group flex items-center justify-center gap-2 px-7 py-3 mu-caption text-mu-ink-muted transition-colors hover:text-mu-ink"
viewTransition
>
<CompassIcon className="h-3.5 w-3.5" />
<CompassIcon className="mu-icon-sm" />
{t("auth.explore-public-memos")}
<ArrowRightIcon className="-ms-1 h-3.5 w-3.5 opacity-0 transition-all group-hover:ms-0 group-hover:opacity-100 rtl:rotate-180" />
<ArrowRightIcon className="mu-icon-sm -ms-1 opacity-0 transition-all group-hover:ms-0 group-hover:opacity-100 rtl:rotate-180" />
</Link>
</div>
)}
@@ -1,3 +1,4 @@
import { Skeleton } from "@usememos/ui";
import { memo, useState } from "react";
import {
type CalendarDayCell as CalendarDayCellData,
@@ -6,7 +7,6 @@ import {
getTooltipText,
} from "@/components/ActivityCalendar";
import UserAvatar from "@/components/UserAvatar";
import { FOCUS_VISIBLE_OUTLINE_CLASSES } from "@/components/ui/focus";
import { useResolvedUser, useResolvedUsersByNames } from "@/contexts/MentionResolutionContext";
import type { MemoTimeBasis } from "@/contexts/ViewContext";
import { cn } from "@/lib/utils";
@@ -80,7 +80,7 @@ export interface CalendarDayCellProps {
corner?: "ss" | "se" | "es" | "ee";
}
const CORNER_CLASSES = { ss: "rounded-ss-lg", se: "rounded-se-lg", es: "rounded-es-lg", ee: "rounded-ee-lg" } as const;
const CORNER_CLASSES = { ss: "rounded-ss-mu-lg", se: "rounded-se-mu-lg", es: "rounded-es-mu-lg", ee: "rounded-ee-mu-lg" } as const;
/**
* Today and the open day share one object, the way Notion Calendar marks dates: a 22px
@@ -88,17 +88,17 @@ const CORNER_CLASSES = { ss: "rounded-ss-lg", se: "rounded-se-lg", es: "rounded-
* primary fill, the open day a quiet foreground wash, and when today is open the primary
* badge sits inside a grey halo rather than stacking a second shape.
*/
const BADGE = "inline-flex h-[22px] min-w-[22px] items-center justify-center rounded-md px-[5px]";
const TODAY_BADGE = `${BADGE} bg-primary text-primary-foreground`;
const OPEN_BADGE = `${BADGE} bg-foreground/10 text-foreground`;
const BADGE = "inline-flex h-[22px] min-w-[22px] items-center justify-center rounded-mu-md px-[5px]";
const TODAY_BADGE = `${BADGE} bg-mu-primary text-mu-on-primary`;
const OPEN_BADGE = `${BADGE} bg-mu-ink/10 text-mu-ink`;
/** Negative margin keeps the badge where it was; only the halo grows outward. */
const OPEN_TODAY_HALO = "-m-[3px] inline-flex rounded-[9px] bg-foreground/10 p-[3px]";
const OPEN_TODAY_HALO = "-m-[3px] inline-flex rounded-[9px] bg-mu-ink/10 p-[3px]";
const getNumeralClass = (day: CalendarDayCellData, count: number): string => {
if (day.isToday) return TODAY_BADGE;
if (day.isSelected) return OPEN_BADGE;
if (!day.isCurrentMonth) return "text-muted-foreground/40";
return count > 0 ? "text-foreground" : "text-muted-foreground/70";
if (!day.isCurrentMonth) return "text-mu-ink-muted/40";
return count > 0 ? "text-mu-ink" : "text-mu-ink-muted/70";
};
const NO_IMAGES: CalendarDaySummary["images"] = [];
@@ -145,7 +145,7 @@ const DayMark = ({
);
}
return (
<span className="flex flex-col gap-[3px] text-muted-foreground/45 transition-colors group-hover/day:text-muted-foreground">
<span className="flex flex-col gap-[3px] text-mu-ink-muted/45 transition-colors group-hover/day:text-mu-ink-muted">
<span className="h-0.5 w-4 rounded-full bg-current" />
<span className="h-0.5 w-2.5 rounded-full bg-current" />
</span>
@@ -178,17 +178,7 @@ export const CalendarDayCell = memo(
const markPhoto = layout.mark ? summary?.images.find((image) => !failedImages.includes(image.thumbnailUrl)) : undefined;
const author = useResolvedUser(excerpt?.creator ?? "", { enabled: showAuthor && Boolean(excerpt) });
const showSkeleton = pending && !summary && day.isCurrentMonth && day.count > 0;
const numeral = (
<span
className={cn(
"text-ui leading-none tabular-nums tracking-[-0.01em]",
day.isSelected ? "font-medium" : "font-normal",
getNumeralClass(day, count),
)}
>
{day.label}
</span>
);
const numeral = <span className={cn("mu-caption tabular-nums", getNumeralClass(day, count))}>{day.label}</span>;
return (
<CalendarLink
@@ -198,14 +188,14 @@ export const CalendarDayCell = memo(
aria-label={getTooltipText(count, day.date, t, timeBasis)}
aria-current={day.isSelected ? "page" : undefined}
className={cn(
"group/day relative flex min-h-14 min-w-0 flex-col overflow-hidden border-border/70 px-1.5 py-2 text-start no-underline transition-colors sm:px-3 sm:min-h-20 md:min-h-[5.5rem]",
"group/day relative flex min-h-14 min-w-0 flex-col overflow-hidden border-mu-line/70 px-1.5 py-2 text-start no-underline transition-colors sm:px-3 sm:min-h-20 md:min-h-[5.5rem]",
layout.slim && "sm:px-2",
!isLastColumn && "border-e",
!isLastRow && "border-b",
corner && CORNER_CLASSES[corner],
FOCUS_VISIBLE_OUTLINE_CLASSES,
"mu-focus",
// The open day keeps its heat tint; its numeral badge is the selection mark.
day.isCurrentMonth ? DAY_CELL_FILLS[level] : "bg-muted/25 hover:bg-muted/45",
day.isCurrentMonth ? DAY_CELL_FILLS[level] : "bg-mu-well/25 hover:bg-mu-hover",
)}
>
{/* The date starts on the text axis like every line below it. */}
@@ -215,7 +205,7 @@ export const CalendarDayCell = memo(
{showSkeleton && layout.textLines > 0 && (
<span aria-hidden="true" className="mt-1 flex h-[18px] items-center">
<span className="h-2 w-2/3 animate-pulse rounded-sm bg-muted" />
<Skeleton width="66%" height={8} />
</span>
)}
@@ -234,10 +224,10 @@ export const CalendarDayCell = memo(
{excerpt && (
<span
className={cn(
"overflow-hidden whitespace-pre-line break-words text-ui leading-[18px] [display:-webkit-box] [-webkit-box-orient:vertical]",
"text-muted-foreground transition-colors group-hover/day:text-foreground",
day.isSelected && "text-foreground",
excerpt.isCode && "font-mono text-xs",
"overflow-hidden whitespace-pre-line break-words mu-caption [display:-webkit-box] [-webkit-box-orient:vertical]",
"text-mu-ink-muted transition-colors group-hover/day:text-mu-ink",
day.isSelected && "text-mu-ink",
excerpt.isCode && "font-mono mu-caption",
)}
style={{ WebkitLineClamp: textLines }}
>
@@ -261,7 +251,7 @@ export const CalendarDayCell = memo(
alt=""
loading="lazy"
decoding="async"
className="size-9 shrink-0 rounded-md object-cover"
className="size-9 shrink-0 rounded-mu-md object-cover"
onError={() => setFailedImages((failed) => [...failed, image.thumbnailUrl])}
/>
))}
@@ -116,7 +116,7 @@ export const CalendarGrid = ({
floor that keeps the date and a short excerpt visible on short windows. */}
<div
ref={cellsRef}
className="grid auto-rows-fr grid-cols-7 overflow-hidden rounded-lg border border-border/70 bg-card md:[grid-auto-rows:9rem] xl:min-h-0 xl:flex-1 xl:[grid-auto-rows:minmax(5.5rem,1fr)]"
className="grid auto-rows-fr grid-cols-7 overflow-hidden rounded-mu-lg border border-mu-line/70 bg-mu-surface md:[grid-auto-rows:9rem] xl:min-h-0 xl:flex-1 xl:[grid-auto-rows:minmax(5.5rem,1fr)]"
>
{days.map((day, index) => (
<CalendarDayCell
@@ -1,8 +1,7 @@
import { Button, buttonClasses } from "@usememos/ui";
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
import { useLocation, useNavigate } from "react-router-dom";
import { buttonVariants } from "@/components/ui/button";
import { addMonths } from "@/lib/calendar-utils";
import { cn } from "@/lib/utils";
import { collectionPathForLocation } from "@/router/routes";
import { useTranslate } from "@/utils/i18n";
import { CalendarLink } from "./CalendarLink";
@@ -36,32 +35,33 @@ export const CalendarHeader = ({ month, monthLabel, today, activeDate, closable
const navigate = useNavigate();
const { pathname, search } = useLocation();
const todayOpen = activeDate === today;
const iconControlClassName = cn(buttonVariants({ variant: "quiet", size: "icon-compact" }));
const iconControlClassName = buttonClasses({ variant: "ghost", size: "sm", iconOnly: true });
return (
// The title's text starts on the grid's text axis (border + cell padding); the month
// controls sit at the trailing edge so they never move as the title's width changes.
<header className="flex h-9 shrink-0 items-center ps-px">
<MonthPicker month={month} monthLabel={monthLabel} today={today} />
<div className="ms-auto flex items-center gap-0.5">
<div className="ms-auto flex items-center gap-0.5 pointer-coarse:gap-4">
<CalendarLink to={buildCalendarPath(addMonths(month, -1))} aria-label={t("common.previous-month")} className={iconControlClassName}>
<ChevronLeftIcon className="rtl:rotate-180" strokeWidth={1.75} />
<ChevronLeftIcon className="mu-icon rtl:rotate-180" />
</CalendarLink>
<CalendarLink to={buildCalendarPath(addMonths(month, 1))} aria-label={t("common.next-month")} className={iconControlClassName}>
<ChevronRightIcon className="rtl:rotate-180" strokeWidth={1.75} />
<ChevronRightIcon className="mu-icon rtl:rotate-180" />
</CalendarLink>
{/* Today is a toggle, so it is a button that navigates; the search keeps the filter query.
Its pressed state is the quiet variant's accent fill, keyed off aria-pressed. */}
<button
type="button"
<Button
variant="ghost"
size="sm"
aria-pressed={todayOpen}
className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "ms-1.5")}
className="ms-1.5"
onClick={() =>
navigate({ pathname: collectionPathForLocation(getTodayPath(month, activeDate, today, closable), pathname), search })
}
>
{t("common.today")}
</button>
</Button>
</div>
</header>
);
@@ -163,13 +163,11 @@ export const CalendarView = ({ month, date }: CalendarViewProps) => {
</MentionResolutionProvider>
{error && <MemoListError error={error} onRetry={refetch} />}
{isEmptyMonth && md && (
<p className="mt-2 shrink-0 text-center text-ui text-muted-foreground">
{t("calendar.no-memos-in-month", { month: monthLabel })}
</p>
<p className="mt-2 shrink-0 text-center mu-caption text-mu-ink-muted">{t("calendar.no-memos-in-month", { month: monthLabel })}</p>
)}
{activeDate && !md && (
<section aria-label={dateLabel} className="mt-4 flex w-full flex-col">
<header className="mb-3 border-b border-border/70 pb-3">
<header className="mb-3 border-b border-mu-line/70 pb-3">
<h2 className={MEMO_PANEL_TITLE_CLASS}>{dateLabel}</h2>
</header>
{list}
+27 -29
View File
@@ -1,8 +1,7 @@
import { Button, buttonClasses, Popover } from "@usememos/ui";
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { buttonVariants } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
import { CalendarLink } from "./CalendarLink";
@@ -18,8 +17,9 @@ export interface MonthPickerProps {
const MONTHS = Array.from({ length: 12 }, (_, index) => index + 1);
const TEXT_CONTROL_CLASSES = cn(buttonVariants({ variant: "quiet", size: "sm" }));
const ICON_CONTROL_CLASSES = cn(buttonVariants({ variant: "quiet", size: "icon-compact" }));
const TEXT_CONTROL_CLASSES = buttonClasses({ variant: "ghost", size: "sm" });
// md, so the 20px heading line fits the control.
const TITLE_CONTROL_CLASSES = buttonClasses({ variant: "ghost", size: "md" });
/**
* The month title is the trigger; the popup is a year stepper over the twelve months, the
@@ -45,32 +45,30 @@ export const MonthPicker = ({ month, monthLabel, today }: MonthPickerProps) => {
);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
aria-label={t("calendar.select-month")}
className={cn(TEXT_CONTROL_CLASSES, "text-base font-semibold tracking-tight text-foreground")}
>
{monthLabel}
</PopoverTrigger>
<PopoverContent align="start" sideOffset={6} className="w-60 p-2">
<Popover.Root open={open} onOpenChange={setOpen}>
{/* The month is the calendar page's title, so it is the page heading as well as the trigger. */}
<h1 className="min-w-0">
<Popover.Trigger aria-label={t("calendar.select-month")} className={cn(TITLE_CONTROL_CLASSES, "mu-heading text-mu-ink")}>
{monthLabel}
</Popover.Trigger>
</h1>
<Popover.Popup align="start" className="w-60">
<div className="mb-1 flex items-center">
<button
type="button"
<Button
variant="ghost"
size="sm"
aria-label={t("calendar.previous-year")}
className={ICON_CONTROL_CLASSES}
icon={<ChevronLeftIcon className="mu-icon rtl:rotate-180" />}
onClick={() => setYear((value) => value - 1)}
>
<ChevronLeftIcon className="rtl:rotate-180" strokeWidth={1.75} />
</button>
<span className="flex-1 text-center text-ui font-medium tabular-nums text-foreground">{year}</span>
<button
type="button"
/>
<span className="flex-1 text-center mu-label-sm tabular-nums text-mu-ink">{year}</span>
<Button
variant="ghost"
size="sm"
aria-label={t("calendar.next-year")}
className={ICON_CONTROL_CLASSES}
icon={<ChevronRightIcon className="mu-icon rtl:rotate-180" />}
onClick={() => setYear((value) => value + 1)}
>
<ChevronRightIcon className="rtl:rotate-180" strokeWidth={1.75} />
</button>
/>
</div>
<div className="grid grid-cols-3 gap-0.5">
{MONTHS.map((value) => {
@@ -82,18 +80,18 @@ export const MonthPicker = ({ month, monthLabel, today }: MonthPickerProps) => {
key={key}
to={buildCalendarPath(key)}
aria-current={isShown ? "page" : undefined}
className={cn(TEXT_CONTROL_CLASSES, "relative text-foreground", isShown && "font-medium")}
className={cn(TEXT_CONTROL_CLASSES, "relative text-mu-ink")}
onClick={() => setOpen(false)}
>
{monthShortLabels[value - 1]}
{isCurrent && (
<span aria-hidden="true" className="absolute bottom-1 left-1/2 size-1 -translate-x-1/2 rounded-full bg-primary" />
<span aria-hidden="true" className="absolute bottom-1 left-1/2 size-1 -translate-x-1/2 rounded-full bg-mu-primary" />
)}
</CalendarLink>
);
})}
</div>
</PopoverContent>
</Popover>
</Popover.Popup>
</Popover.Root>
);
};
@@ -1,11 +1,9 @@
import { Button, Dialog, Field, Input } from "@usememos/ui";
import { useState } from "react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useFieldErrors } from "@/hooks/useFieldErrors";
import { useUpdateUser } from "@/hooks/useUserQueries";
import { handleError } from "@/lib/error";
import { showErrorToast, toast } from "@/lib/toast";
import { User } from "@/types/proto/api/user_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -18,6 +16,7 @@ interface Props {
function ChangeMemberPasswordDialog({ open, onOpenChange, user, onSuccess }: Props) {
const t = useTranslate();
const fieldErrors = useFieldErrors<"newPassword" | "newPasswordAgain">();
const { mutateAsync: updateUser } = useUpdateUser();
const [newPassword, setNewPassword] = useState("");
const [newPasswordAgain, setNewPasswordAgain] = useState("");
@@ -27,6 +26,7 @@ function ChangeMemberPasswordDialog({ open, onOpenChange, user, onSuccess }: Pro
};
const handleNewPasswordChanged = (e: React.ChangeEvent<HTMLInputElement>) => {
fieldErrors.clear("newPassword");
const text = e.target.value as string;
setNewPassword(text);
};
@@ -34,18 +34,19 @@ function ChangeMemberPasswordDialog({ open, onOpenChange, user, onSuccess }: Pro
const handleNewPasswordAgainChanged = (e: React.ChangeEvent<HTMLInputElement>) => {
const text = e.target.value as string;
setNewPasswordAgain(text);
fieldErrors.clear("newPasswordAgain");
};
const handleSaveBtnClick = async () => {
if (!user) return;
if (newPassword === "" || newPasswordAgain === "") {
toast.error(t("message.fill-all"));
fieldErrors.set(newPassword === "" ? "newPassword" : "newPasswordAgain", t("message.fill-all"));
return;
}
if (newPassword !== newPasswordAgain) {
toast.error(t("message.new-password-not-match"));
fieldErrors.set("newPasswordAgain", t("message.new-password-not-match"));
setNewPasswordAgain("");
return;
}
@@ -58,11 +59,11 @@ function ChangeMemberPasswordDialog({ open, onOpenChange, user, onSuccess }: Pro
},
updateMask: ["password"],
});
toast(t("message.password-changed"));
toast.add({ title: t("message.password-changed") });
onSuccess?.();
onOpenChange(false);
} catch (error: unknown) {
await handleError(error, toast.error, {
await handleError(error, showErrorToast, {
context: "Change member password",
});
}
@@ -71,16 +72,14 @@ function ChangeMemberPasswordDialog({ open, onOpenChange, user, onSuccess }: Pro
if (!user) return null;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>
{t("setting.account.change-password")} ({user.displayName})
</DialogTitle>
</DialogHeader>
<Dialog.Root open={open} onOpenChange={onOpenChange}>
<Dialog.Popup closeLabel={t("common.close")}>
<Dialog.Title>
{t("setting.account.change-password")} ({user.displayName})
</Dialog.Title>
<div className="flex flex-col gap-4">
<div className="grid gap-2">
<Label htmlFor="newPassword">{t("auth.new-password")}</Label>
<Field.Root invalid={!!fieldErrors.errors.newPassword}>
<Field.Label>{t("auth.new-password")}</Field.Label>
<Input
id="newPassword"
type="password"
@@ -88,9 +87,10 @@ function ChangeMemberPasswordDialog({ open, onOpenChange, user, onSuccess }: Pro
value={newPassword}
onChange={handleNewPasswordChanged}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="newPasswordAgain">{t("auth.repeat-new-password")}</Label>
{fieldErrors.errors.newPassword && <Field.Error match>{fieldErrors.errors.newPassword}</Field.Error>}
</Field.Root>
<Field.Root invalid={!!fieldErrors.errors.newPasswordAgain}>
<Field.Label>{t("auth.repeat-new-password")}</Field.Label>
<Input
id="newPasswordAgain"
type="password"
@@ -98,16 +98,19 @@ function ChangeMemberPasswordDialog({ open, onOpenChange, user, onSuccess }: Pro
value={newPasswordAgain}
onChange={handleNewPasswordAgainChanged}
/>
</div>
{fieldErrors.errors.newPasswordAgain && <Field.Error match>{fieldErrors.errors.newPasswordAgain}</Field.Error>}
</Field.Root>
</div>
<DialogFooter>
<Dialog.Footer>
<Button variant="ghost" onClick={handleCloseBtnClick}>
{t("common.cancel")}
</Button>
<Button onClick={handleSaveBtnClick}>{t("common.save")}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Button variant="primary" onClick={handleSaveBtnClick}>
{t("common.save")}
</Button>
</Dialog.Footer>
</Dialog.Popup>
</Dialog.Root>
);
}
+9 -8
View File
@@ -1,6 +1,6 @@
import { Button } from "@usememos/ui";
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
@@ -54,17 +54,18 @@ const ClampedSection = ({ enabled, children }: ClampedSectionProps) => {
{children}
</div>
{collapsed && (
<div className="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-linear-to-t from-card from-0% via-card/60 via-40% to-transparent to-100%" />
<div className="pointer-events-none absolute inset-x-0 bottom-0 h-12 bg-linear-to-t from-mu-surface from-0% via-mu-surface/60 via-40% to-transparent to-100%" />
)}
</div>
{clamped && (
<Button variant="quiet" size="sm" onClick={() => setExpanded((prev) => !prev)}>
<Button
variant="ghost"
size="sm"
aria-expanded={!collapsed}
iconEnd={collapsed ? <ChevronDownIcon /> : <ChevronUpIcon />}
onClick={() => setExpanded((prev) => !prev)}
>
{t(collapsed ? "memo.show-more" : "memo.show-less")}
{collapsed ? (
<ChevronDownIcon className="size-3.5" strokeWidth={1.8} />
) : (
<ChevronUpIcon className="size-3.5" strokeWidth={1.8} />
)}
</Button>
)}
</>
+2 -2
View File
@@ -48,7 +48,7 @@ const t = useTranslate();
confirmLabel={t("common.delete")}
cancelLabel={t("common.cancel")}
onConfirm={handleDelete}
confirmVariant="destructive"
confirmVariant="danger"
/>;
```
@@ -63,7 +63,7 @@ const t = useTranslate();
| `confirmLabel` | `string` | Yes | Non-empty localized action text (1–2 words) |
| `cancelLabel` | `string` | Yes | Localized cancel label |
| `onConfirm` | `() => void | Promise<void>` | Yes | Sync or async handler; resolve = close, reject = stay open |
| `confirmVariant` | `"default" | "destructive"` | No | Defaults to `"default"`; use `"destructive"` for irreversible actions |
| `confirmVariant` | `"primary" | "danger"` | No | Defaults to `"primary"`; use `"danger"` for irreversible actions |
## Benefits vs Previous Implementation
+13 -15
View File
@@ -1,6 +1,5 @@
import { AlertDialog, Button } from "@usememos/ui";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
export interface ConfirmDialogProps {
open: boolean;
@@ -10,9 +9,10 @@ export interface ConfirmDialogProps {
confirmLabel: string;
cancelLabel: string;
onConfirm: () => void | Promise<void>;
confirmVariant?: "default" | "destructive";
confirmVariant?: "primary" | "danger";
}
/** Confirms an action; it closes only through its buttons, and stays open while the action runs. */
export default function ConfirmDialog({
open,
onOpenChange,
@@ -21,7 +21,7 @@ export default function ConfirmDialog({
confirmLabel,
cancelLabel,
onConfirm,
confirmVariant = "default",
confirmVariant = "primary",
}: ConfirmDialogProps) {
const [loading, setLoading] = React.useState(false);
@@ -39,21 +39,19 @@ export default function ConfirmDialog({
};
return (
<Dialog open={open} onOpenChange={(o: boolean) => !loading && onOpenChange(o)}>
<DialogContent size="sm">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
{description ? <DialogDescription>{description}</DialogDescription> : null}
</DialogHeader>
<DialogFooter>
<AlertDialog.Root open={open} onOpenChange={(o: boolean) => !loading && onOpenChange(o)}>
<AlertDialog.Popup>
<AlertDialog.Title>{title}</AlertDialog.Title>
{description ? <AlertDialog.Description>{description}</AlertDialog.Description> : null}
<AlertDialog.Footer>
<Button variant="ghost" disabled={loading} onClick={() => onOpenChange(false)}>
{cancelLabel}
</Button>
<Button variant={confirmVariant} disabled={loading} onClick={handleConfirm} data-loading={loading}>
<Button variant={confirmVariant} loading={loading} loadingLabel={confirmLabel} onClick={handleConfirm}>
{confirmLabel}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</AlertDialog.Footer>
</AlertDialog.Popup>
</AlertDialog.Root>
);
}
+43 -41
View File
@@ -1,16 +1,12 @@
import { Button, Dialog, Field, Fieldset, Input, Radio, RadioGroup, Textarea } from "@usememos/ui";
import copy from "copy-to-clipboard";
import React, { useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Textarea } from "@/components/ui/textarea";
import { userServiceClient } from "@/connect";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useFieldErrors } from "@/hooks/useFieldErrors";
import useLoading from "@/hooks/useLoading";
import { handleError } from "@/lib/error";
import { showErrorToast, toast } from "@/lib/toast";
import { CreatePersonalAccessTokenResponse } from "@/types/proto/api/user_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -27,6 +23,7 @@ interface State {
function CreateAccessTokenDialog({ open, onOpenChange, onSuccess }: Props) {
const t = useTranslate();
const fieldErrors = useFieldErrors<"description">();
const currentUser = useCurrentUser();
const [state, setState] = useState({
description: "",
@@ -59,6 +56,7 @@ function CreateAccessTokenDialog({ open, onOpenChange, onSuccess }: Props) {
};
const handleDescriptionInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
fieldErrors.clear("description");
setPartialState({
description: e.target.value,
});
@@ -72,7 +70,7 @@ function CreateAccessTokenDialog({ open, onOpenChange, onSuccess }: Props) {
const handleSaveBtnClick = async () => {
if (!state.description) {
toast.error(t("message.description-is-required"));
fieldErrors.set("description", t("message.description-is-required"));
return;
}
@@ -92,7 +90,7 @@ function CreateAccessTokenDialog({ open, onOpenChange, onSuccess }: Props) {
onOpenChange(false);
}
} catch (error: unknown) {
handleError(error, toast.error, {
handleError(error, showErrorToast, {
context: "Create access token",
onError: () => requestState.setError(),
});
@@ -102,7 +100,7 @@ function CreateAccessTokenDialog({ open, onOpenChange, onSuccess }: Props) {
const handleCopyToken = () => {
if (!createdToken) return;
copy(createdToken);
toast.success(t("message.copied"));
toast.add({ title: t("message.copied"), type: "success" });
};
useEffect(() => {
@@ -115,24 +113,22 @@ function CreateAccessTokenDialog({ open, onOpenChange, onSuccess }: Props) {
}, [open]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>{t("setting.access-token.create-dialog.create-access-token")}</DialogTitle>
</DialogHeader>
<Dialog.Root open={open} onOpenChange={onOpenChange}>
<Dialog.Popup closeLabel={t("common.close")}>
<Dialog.Title>{t("setting.access-token.create-dialog.create-access-token")}</Dialog.Title>
{createdToken ? (
<div className="flex flex-col gap-4">
<div className="grid gap-2">
<Label>{t("setting.access-token.token")}</Label>
<Textarea value={createdToken} readOnly rows={3} className="font-mono text-xs" />
</div>
<Field.Root>
<Field.Label>{t("setting.access-token.token")}</Field.Label>
<Textarea value={createdToken} readOnly rows={3} className="font-mono" />
</Field.Root>
</div>
) : (
<div className="flex flex-col gap-4">
<div className="grid gap-2">
<Label htmlFor="description">
{t("setting.access-token.create-dialog.description")} <span className="text-destructive">*</span>
</Label>
<Field.Root invalid={!!fieldErrors.errors.description}>
<Field.Label>
{t("setting.access-token.create-dialog.description")} <span className="text-mu-danger">*</span>
</Field.Label>
<Input
id="description"
type="text"
@@ -140,43 +136,49 @@ function CreateAccessTokenDialog({ open, onOpenChange, onSuccess }: Props) {
value={state.description}
onChange={handleDescriptionInputChange}
/>
</div>
<div className="grid gap-2">
<Label>
{t("setting.access-token.create-dialog.expiration")} <span className="text-destructive">*</span>
</Label>
<RadioGroup value={state.expiration.toString()} onValueChange={handleRoleInputChange} className="flex flex-row gap-4">
{fieldErrors.errors.description && <Field.Error match>{fieldErrors.errors.description}</Field.Error>}
</Field.Root>
<Field.Root>
<Fieldset.Root
render={<RadioGroup value={state.expiration.toString()} onValueChange={handleRoleInputChange} orientation="horizontal" />}
>
<Fieldset.Legend>
{t("setting.access-token.create-dialog.expiration")} <span className="text-mu-danger">*</span>
</Fieldset.Legend>
{expirationOptions.map((option) => (
<div key={option.value} className="flex items-center space-x-2">
<RadioGroupItem value={option.value.toString()} id={`expiration-${option.value}`} />
<Label htmlFor={`expiration-${option.value}`}>{option.label}</Label>
</div>
<Field.Item key={option.value}>
<Field.Label>
<Radio value={option.value.toString()} /> {option.label}
</Field.Label>
</Field.Item>
))}
</RadioGroup>
</div>
</Fieldset.Root>
</Field.Root>
</div>
)}
<DialogFooter>
<Dialog.Footer>
{createdToken ? (
<>
<Button variant="ghost" onClick={handleCopyToken}>
{t("common.copy")}
</Button>
<Button onClick={() => onOpenChange(false)}>{t("common.close")}</Button>
<Button variant="primary" onClick={() => onOpenChange(false)}>
{t("common.close")}
</Button>
</>
) : (
<>
<Button variant="ghost" disabled={requestState.isLoading} onClick={() => onOpenChange(false)}>
{t("common.cancel")}
</Button>
<Button disabled={requestState.isLoading} onClick={handleSaveBtnClick}>
<Button variant="primary" disabled={requestState.isLoading} onClick={handleSaveBtnClick}>
{t("common.create")}
</Button>
</>
)}
</DialogFooter>
</DialogContent>
</Dialog>
</Dialog.Footer>
</Dialog.Popup>
</Dialog.Root>
);
}
@@ -1,15 +1,11 @@
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { Button, Dialog, Field, Input, Select } from "@usememos/ui";
import { type ReactNode, useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { identityProviderServiceClient } from "@/connect";
import { absolutifyLink } from "@/lib/browser";
import { handleError } from "@/lib/error";
import { showErrorToast, toast } from "@/lib/toast";
import {
FieldMapping,
FieldMappingSchema,
@@ -219,10 +215,10 @@ function buildDialogStateFromProvider(identityProvider: IdentityProvider) {
function FormSection({ title, description, children }: { title: string; description?: string; children: ReactNode }) {
return (
<section className="space-y-4 rounded-lg border bg-muted/20 p-4">
<section className="space-y-4 rounded-mu-lg border bg-mu-well/20 p-4">
<div className="space-y-1">
<h3 className="text-sm font-semibold text-foreground">{title}</h3>
{description ? <p className="text-xs text-muted-foreground">{description}</p> : null}
<h3 className="mu-label text-mu-ink">{title}</h3>
{description ? <p className="mu-caption text-mu-ink-muted">{description}</p> : null}
</div>
<div className="space-y-4">{children}</div>
</section>
@@ -243,14 +239,14 @@ function FormField({
return (
// flex gap, not space-y: fields wrap Select triggers, whose focus guards would otherwise
// pick up the stack's margin and shift the field while the popup is open (see ui/popup.ts).
<div className="flex flex-col gap-2">
<Label>
<Field.Root>
<Field.Label>
{label}
{required ? <span className="text-destructive">*</span> : null}
</Label>
{required ? <span className="text-mu-danger">*</span> : null}
</Field.Label>
{children}
{description ? <p className="text-xs text-muted-foreground">{description}</p> : null}
</div>
{description ? <Field.Description>{description}</Field.Description> : null}
</Field.Root>
);
}
@@ -352,7 +348,7 @@ function CreateIdentityProviderDialog({ open, onOpenChange, identityProvider, on
}),
}),
});
toast.success(t("setting.sso.sso-created", { name: basicInfo.title }));
toast.add({ title: t("setting.sso.sso-created", { name: basicInfo.title }), type: "success" });
} else {
await identityProviderServiceClient.updateIdentityProvider({
identityProvider: create(IdentityProviderSchema, {
@@ -372,11 +368,11 @@ function CreateIdentityProviderDialog({ open, onOpenChange, identityProvider, on
}),
updateMask: create(FieldMaskSchema, { paths: ["title", "identifier_filter", "config"] }),
});
toast.success(t("setting.sso.sso-updated", { name: basicInfo.title }));
toast.add({ title: t("setting.sso.sso-updated", { name: basicInfo.title }), type: "success" });
}
} catch (error: unknown) {
setIsSubmitting(false);
await handleError(error, toast.error, {
await handleError(error, showErrorToast, {
context: isCreating ? "Create identity provider" : "Update identity provider",
});
return;
@@ -404,51 +400,53 @@ function CreateIdentityProviderDialog({ open, onOpenChange, identityProvider, on
};
return (
<Dialog open={open} onOpenChange={handleDialogClose}>
<DialogContent size="2xl">
<DialogHeader>
<DialogTitle>{t(isCreating ? "setting.sso.create-sso" : "setting.sso.update-sso")}</DialogTitle>
<DialogDescription>
{t(isCreating ? "setting.sso.create-sso-description" : "setting.sso.update-sso-description")}
</DialogDescription>
</DialogHeader>
<Dialog.Root open={open} onOpenChange={handleDialogClose}>
<Dialog.Popup closeLabel={t("common.close")} style={{ "--mu-dialog-width": "42rem" } as React.CSSProperties}>
<Dialog.Title>{t(isCreating ? "setting.sso.create-sso" : "setting.sso.update-sso")}</Dialog.Title>
<Dialog.Description>
{t(isCreating ? "setting.sso.create-sso-description" : "setting.sso.update-sso-description")}
</Dialog.Description>
<div className="space-y-4">
<FormSection title={t("setting.sso.basic-settings")} description={t("setting.sso.basic-settings-description")}>
{isCreating ? (
<div className="grid gap-4 md:grid-cols-2">
<FormField label={t("common.type")} required>
<Select
<Select.Root
value={String(type)}
items={identityProviderTypeOptions}
onValueChange={(value) => setType(Number(value) as IdentityProvider_Type)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<Select.Trigger>
<Select.Value />
</Select.Trigger>
<Select.Popup>
{identityProviderTypeOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
<Select.Item key={option.value} value={option.value}>
{option.label}
</SelectItem>
</Select.Item>
))}
</SelectContent>
</Select>
</Select.Popup>
</Select.Root>
</FormField>
<FormField label={t("setting.sso.template")} required description={t("setting.sso.template-description")}>
<Select value={selectedTemplate} items={templateOptions} onValueChange={setSelectedTemplate}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<Select.Root
value={selectedTemplate}
items={templateOptions}
onValueChange={(value) => value !== null && setSelectedTemplate(value)}
>
<Select.Trigger>
<Select.Value />
</Select.Trigger>
<Select.Popup>
{templateOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
<Select.Item key={option.value} value={option.value}>
{option.label}
</SelectItem>
</Select.Item>
))}
</SelectContent>
</Select>
</Select.Popup>
</Select.Root>
</FormField>
</div>
) : null}
@@ -458,7 +456,7 @@ function CreateIdentityProviderDialog({ open, onOpenChange, identityProvider, on
<FormField label={t("setting.sso.provider-id")} required description={t("setting.sso.provider-id-description")}>
<Input
className="font-mono"
placeholder="e.g. github, okta-corp"
placeholder={t("setting.sso.provider-id-placeholder")}
maxLength={32}
value={basicInfo.identifier}
onChange={(e) =>
@@ -502,10 +500,10 @@ function CreateIdentityProviderDialog({ open, onOpenChange, identityProvider, on
{type === IdentityProvider_Type.OAUTH2 ? (
<>
<FormSection title={t("setting.sso.oauth-configuration")} description={t("setting.sso.oauth-configuration-description")}>
<div className="rounded-md border bg-background px-3 py-3">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{t("setting.sso.redirect-url")}</p>
<p className="mt-2 break-all font-mono text-xs text-foreground sm:text-sm">{absolutifyLink("/auth/callback")}</p>
<p className="mt-2 text-xs text-muted-foreground">{t("setting.sso.redirect-url-description")}</p>
<div className="rounded-mu-md border bg-mu-canvas px-3 py-3">
<p className="mu-label-sm uppercase tracking-wide text-mu-ink-muted">{t("setting.sso.redirect-url")}</p>
<p className="mt-2 break-all font-mono mu-caption text-mu-ink">{absolutifyLink("/auth/callback")}</p>
<p className="mt-2 mu-caption text-mu-ink-muted">{t("setting.sso.redirect-url-description")}</p>
</div>
<div className="grid gap-4 md:grid-cols-2">
@@ -610,16 +608,16 @@ function CreateIdentityProviderDialog({ open, onOpenChange, identityProvider, on
) : null}
</div>
<DialogFooter>
<Dialog.Footer>
<Button variant="ghost" onClick={handleCloseBtnClick} disabled={isSubmitting}>
{t("common.cancel")}
</Button>
<Button onClick={handleConfirmBtnClick} disabled={!allowConfirmAction()}>
<Button variant="primary" onClick={handleConfirmBtnClick} disabled={!allowConfirmAction()}>
{t(isCreating ? "common.create" : "common.update")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</Dialog.Footer>
</Dialog.Popup>
</Dialog.Root>
);
}
+33 -40
View File
@@ -1,17 +1,13 @@
import { Code, ConnectError } from "@connectrpc/connect";
import { Button, Dialog, Field, Input, Textarea } from "@usememos/ui";
import { ChevronDownIcon } from "lucide-react";
import { type FormEvent, useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import { v4 as uuidv4 } from "uuid";
import SpaceIconPicker from "@/components/SpaceIconPicker";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useCreateSpace } from "@/hooks/useSpaceQueries";
import { handleError } from "@/lib/error";
import { showErrorToast, toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import type { Space, Space_Icon } from "@/types/proto/api/space_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -70,11 +66,11 @@ function CreateSpaceDialog({ open, onOpenChange, onCreated, note }: Props) {
setSpaceUidConflict(true);
setShowCustomId(true);
}
handleError(error, toast.error, { context: "Create space" });
handleError(error, showErrorToast, { context: "Create space" });
return;
}
toast.success(t("space.create-success"));
toast.add({ title: t("space.create-success"), type: "success" });
onOpenChange(false);
onCreated?.(space);
};
@@ -87,15 +83,15 @@ function CreateSpaceDialog({ open, onOpenChange, onCreated, note }: Props) {
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent size="sm">
<Dialog.Root open={open} onOpenChange={handleOpenChange}>
<Dialog.Popup closeLabel={t("common.close")}>
<form className="flex flex-col gap-4" onSubmit={handleSubmit}>
<DialogHeader>
<DialogTitle>{t("space.create")}</DialogTitle>
<DialogDescription>{t("space.create-description")}</DialogDescription>
</DialogHeader>
<div className="grid gap-2">
<Label htmlFor="space-title">{t("common.name")}</Label>
<Dialog.Title>{t("space.create")}</Dialog.Title>
<Dialog.Description>{t("space.create-description")}</Dialog.Description>
<div className="flex flex-col gap-1">
<label htmlFor="space-title" className="mu-label">
{t("common.name")}
</label>
<div className="flex items-center gap-2">
<SpaceIconPicker value={icon} onChange={setIcon} disabled={createSpace.isPending} />
<Input
@@ -108,8 +104,8 @@ function CreateSpaceDialog({ open, onOpenChange, onCreated, note }: Props) {
/>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="space-description">{t("common.description")}</Label>
<Field.Root>
<Field.Label>{t("common.description")}</Field.Label>
<Textarea
id="space-description"
value={description}
@@ -117,23 +113,23 @@ function CreateSpaceDialog({ open, onOpenChange, onCreated, note }: Props) {
placeholder={t("space.description-placeholder")}
className="min-h-20 resize-none"
/>
</div>
</Field.Root>
<div>
<Button
type="button"
variant="ghost"
size="sm"
className="-mx-2 px-2 text-muted-foreground"
className="-mx-2"
aria-expanded={showCustomId}
aria-controls="space-custom-uid"
onClick={() => setShowCustomId((visible) => (hasSpaceUidError ? true : !visible))}
icon={<ChevronDownIcon className={cn("transition-transform", showCustomId && "rotate-180")} />}
>
<ChevronDownIcon className={cn("transition-transform", showCustomId && "rotate-180")} />
{t("space.custom-id-toggle")}
</Button>
{showCustomId && (
<div id="space-custom-uid" className="mt-2 grid gap-2 rounded-md border bg-muted/30 p-3">
<Label htmlFor="space-uid">{t("space.custom-id-label")}</Label>
<Field.Root id="space-custom-uid" className="mt-2" invalid={hasSpaceUidError}>
<Field.Label>{t("space.custom-id-label")}</Field.Label>
<Input
id="space-uid"
value={spaceUid}
@@ -144,32 +140,29 @@ function CreateSpaceDialog({ open, onOpenChange, onCreated, note }: Props) {
maxLength={36}
autoComplete="off"
spellCheck={false}
aria-invalid={hasSpaceUidError}
aria-describedby="space-uid-help"
className="font-mono text-xs aria-invalid:border-destructive"
className="font-mono"
/>
<p
id="space-uid-help"
role={hasSpaceUidError ? "alert" : undefined}
className={cn("text-xs leading-5", hasSpaceUidError ? "text-destructive" : "text-muted-foreground")}
>
{t(!isSpaceUidValid ? "space.custom-id-invalid" : spaceUidConflict ? "space.custom-id-conflict" : "space.custom-id-help")}
</p>
</div>
<Field.Description>{t("space.custom-id-help")}</Field.Description>
{hasSpaceUidError && (
<Field.Error match role="alert">
{t(!isSpaceUidValid ? "space.custom-id-invalid" : "space.custom-id-conflict")}
</Field.Error>
)}
</Field.Root>
)}
</div>
<p className="text-xs text-muted-foreground">{note ?? t("space.creator-admin-note")}</p>
<DialogFooter>
<p className="mu-caption text-mu-ink-muted">{note ?? t("space.creator-admin-note")}</p>
<Dialog.Footer>
<Button type="button" variant="ghost" disabled={createSpace.isPending} onClick={() => onOpenChange(false)}>
{t("common.cancel")}
</Button>
<Button type="submit" disabled={!title.trim() || hasSpaceUidError || createSpace.isPending}>
<Button variant="primary" type="submit" disabled={!title.trim() || hasSpaceUidError || createSpace.isPending}>
{t("common.create")}
</Button>
</DialogFooter>
</Dialog.Footer>
</form>
</DialogContent>
</Dialog>
</Dialog.Popup>
</Dialog.Root>
);
}
+58 -52
View File
@@ -1,16 +1,13 @@
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { Button, Dialog, Field, Fieldset, Input, Radio, RadioGroup } from "@usememos/ui";
import { useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { userServiceClient } from "@/connect";
import { isFieldManaged, useManagedResource } from "@/hooks/useConfigurationQueries";
import { useFieldErrors } from "@/hooks/useFieldErrors";
import useLoading from "@/hooks/useLoading";
import { handleError } from "@/lib/error";
import { showErrorToast, toast } from "@/lib/toast";
import { User, User_Role, UserSchema } from "@/types/proto/api/user_service_pb";
import { useTranslate } from "@/utils/i18n";
import ManagedByConfigurationChip from "./Settings/ManagedByConfigurationChip";
@@ -24,6 +21,7 @@ interface Props {
function CreateUserDialog({ open, onOpenChange, user: initialUser, onSuccess }: Props) {
const t = useTranslate();
const fieldErrors = useFieldErrors<"username" | "password">();
const [user, setUser] = useState(
create(UserSchema, initialUser ? { name: initialUser.name, username: initialUser.username, role: initialUser.role } : {}),
);
@@ -49,7 +47,7 @@ function CreateUserDialog({ open, onOpenChange, user: initialUser, onSuccess }:
const handleConfirm = async () => {
if (isCreating && (!user.username || !user.password)) {
toast.error("Username and password cannot be empty");
fieldErrors.set(!user.username ? "username" : "password", t("setting.member.username-password-required"));
return;
}
@@ -57,7 +55,7 @@ function CreateUserDialog({ open, onOpenChange, user: initialUser, onSuccess }:
requestState.setLoading();
if (isCreating) {
await userServiceClient.createUser({ user });
toast.success("Create user successfully");
toast.add({ title: t("setting.member.create-success"), type: "success" });
} else {
const updateMask = [];
if (user.username !== initialUser?.username) {
@@ -71,13 +69,13 @@ function CreateUserDialog({ open, onOpenChange, user: initialUser, onSuccess }:
}
const userToUpdate = create(UserSchema, { ...user, name: initialUser?.name ?? user.name });
await userServiceClient.updateUser({ user: userToUpdate, updateMask: create(FieldMaskSchema, { paths: updateMask }) });
toast.success("Update user successfully");
toast.add({ title: t("setting.member.update-success"), type: "success" });
}
requestState.setFinish();
onSuccess?.();
onOpenChange(false);
} catch (error: unknown) {
handleError(error, toast.error, {
handleError(error, showErrorToast, {
context: isCreating ? "Create user" : "Update user",
onError: () => requestState.setError(),
});
@@ -85,76 +83,84 @@ function CreateUserDialog({ open, onOpenChange, user: initialUser, onSuccess }:
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>{`${isCreating ? t("common.create") : t("common.edit")} ${t("common.user")}`}</DialogTitle>
{managed ? (
<div className="flex">
<ManagedByConfigurationChip resource={managed} />
</div>
) : null}
</DialogHeader>
<Dialog.Root open={open} onOpenChange={onOpenChange}>
<Dialog.Popup closeLabel={t("common.close")}>
<Dialog.Title>{`${isCreating ? t("common.create") : t("common.edit")} ${t("common.user")}`}</Dialog.Title>
{managed ? (
<div className="flex">
<ManagedByConfigurationChip resource={managed} />
</div>
) : null}
<div className="flex flex-col gap-4">
<div className="grid gap-2">
<Label htmlFor="username">{t("common.username")}</Label>
<Field.Root invalid={!!fieldErrors.errors.username}>
<Field.Label>{t("common.username")}</Field.Label>
<Input
id="username"
type="text"
placeholder={t("common.username")}
disabled={isFieldManaged(managed, "username")}
value={user.username}
onChange={(e) =>
onChange={(e) => (
fieldErrors.clear("username"),
setPartialUser({
username: e.target.value,
})
}
)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="password">{t("common.password")}</Label>
{fieldErrors.errors.username && <Field.Error match>{fieldErrors.errors.username}</Field.Error>}
</Field.Root>
<Field.Root invalid={!!fieldErrors.errors.password}>
<Field.Label>{t("common.password")}</Field.Label>
<Input
id="password"
type="password"
placeholder={t("common.password")}
autoComplete="off"
value={user.password}
onChange={(e) =>
onChange={(e) => (
fieldErrors.clear("password"),
setPartialUser({
password: e.target.value,
})
}
)}
/>
</div>
<div className="grid gap-2">
<Label>{t("common.role")}</Label>
<RadioGroup
disabled={isFieldManaged(managed, "role")}
value={String(user.role)}
onValueChange={(value) => setPartialUser({ role: Number(value) as User_Role })}
className="flex flex-row gap-4"
{fieldErrors.errors.password && <Field.Error match>{fieldErrors.errors.password}</Field.Error>}
</Field.Root>
<Field.Root>
<Fieldset.Root
render={
<RadioGroup
disabled={isFieldManaged(managed, "role")}
value={String(user.role)}
onValueChange={(value) => setPartialUser({ role: Number(value) as User_Role })}
orientation="horizontal"
/>
}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value={String(User_Role.USER)} id="user" />
<Label htmlFor="user">{t("setting.member.user")}</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value={String(User_Role.ADMIN)} id="admin" />
<Label htmlFor="admin">{t("setting.member.admin")}</Label>
</div>
</RadioGroup>
</div>
<Fieldset.Legend>{t("common.role")}</Fieldset.Legend>
<Field.Item>
<Field.Label>
<Radio value={String(User_Role.USER)} /> {t("setting.member.user")}
</Field.Label>
</Field.Item>
<Field.Item>
<Field.Label>
<Radio value={String(User_Role.ADMIN)} /> {t("setting.member.admin")}
</Field.Label>
</Field.Item>
</Fieldset.Root>
</Field.Root>
</div>
<DialogFooter>
<Dialog.Footer>
<Button variant="ghost" disabled={requestState.isLoading} onClick={() => onOpenChange(false)}>
{t("common.cancel")}
</Button>
<Button disabled={requestState.isLoading} onClick={handleConfirm}>
<Button variant="primary" disabled={requestState.isLoading} onClick={handleConfirm}>
{t("common.confirm")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</Dialog.Footer>
</Dialog.Popup>
</Dialog.Root>
);
}
+70 -56
View File
@@ -1,17 +1,15 @@
import { create } from "@bufbuild/protobuf";
import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { Button, Dialog, Field, Input, Tooltip } from "@usememos/ui";
import copy from "copy-to-clipboard";
import { CheckIcon, CopyIcon, EyeIcon } from "lucide-react";
import React, { useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { userServiceClient } from "@/connect";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useFieldErrors } from "@/hooks/useFieldErrors";
import useLoading from "@/hooks/useLoading";
import { handleError } from "@/lib/error";
import { showErrorToast } from "@/lib/toast";
import { useTranslate } from "@/utils/i18n";
interface Props {
@@ -28,6 +26,7 @@ interface State {
function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Props) {
const t = useTranslate();
const fieldErrors = useFieldErrors<"displayName" | "url">();
const currentUser = useCurrentUser();
const isCreating = webhookName === undefined;
const [state, setState] = useState<State>({ displayName: "", url: "" });
@@ -65,10 +64,12 @@ function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Pro
}, [open, isCreating]);
const handleTitleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
fieldErrors.clear("displayName");
setState((prev) => ({ ...prev, displayName: e.target.value }));
};
const handleUrlInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
fieldErrors.clear("url");
setState((prev) => ({ ...prev, url: e.target.value }));
};
@@ -86,7 +87,7 @@ function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Pro
setRevealedSecret(signingSecret);
secretState.setFinish();
} catch (error: unknown) {
handleError(error, toast.error, { context: "Reveal signing secret", onError: () => secretState.setError() });
handleError(error, showErrorToast, { context: "Reveal signing secret", onError: () => secretState.setError() });
}
};
@@ -107,7 +108,7 @@ function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Pro
handleCopySecret(secret);
secretState.setFinish();
} catch (error: unknown) {
handleError(error, toast.error, { context: "Generate signing secret", onError: () => secretState.setError() });
handleError(error, showErrorToast, { context: "Generate signing secret", onError: () => secretState.setError() });
}
};
@@ -121,12 +122,12 @@ function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Pro
const handleSaveBtnClick = async () => {
if (!state.displayName || !state.url) {
toast.error(t("message.fill-all-required-fields"));
fieldErrors.set(!state.displayName ? "displayName" : "url", t("message.fill-all-required-fields"));
return;
}
if (!currentUser) {
toast.error("User not authenticated");
showErrorToast(t("message.not-signed-in"));
return;
}
@@ -163,7 +164,7 @@ function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Pro
onOpenChange(false);
requestState.setFinish();
} catch (error: unknown) {
handleError(error, toast.error, {
handleError(error, showErrorToast, {
context: webhookName ? "Update webhook" : "Create webhook",
onError: () => requestState.setError(),
});
@@ -172,22 +173,27 @@ function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Pro
const renderSecretField = (secret: string) => (
<div className="flex items-center gap-2">
<Input readOnly type="text" value={secret} className="flex-1 font-mono text-xs" />
<Button
type="button"
variant="outline"
size="icon"
onClick={() => handleCopySecret(secret)}
aria-label={t("setting.webhook.create-dialog.copy-secret")}
>
{secretCopied ? <CheckIcon className="h-4 w-4 text-success" /> : <CopyIcon className="h-4 w-4" />}
</Button>
<Input readOnly type="text" value={secret} className="flex-1 font-mono" />
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
type="button"
variant="neutral"
onClick={() => handleCopySecret(secret)}
aria-label={t("setting.webhook.create-dialog.copy-secret")}
icon={secretCopied ? <CheckIcon /> : <CopyIcon />}
/>
}
/>
<Tooltip.Popup>{t("setting.webhook.create-dialog.copy-secret")}</Tooltip.Popup>
</Tooltip.Root>
</div>
);
const renderSigningSecret = () => {
if (isCreating) {
return <span className="text-xs text-muted-foreground">{t("setting.webhook.create-dialog.signing-secret-auto-note")}</span>;
return <Field.Description>{t("setting.webhook.create-dialog.signing-secret-auto-note")}</Field.Description>;
}
if (revealedSecret !== undefined) {
return renderSecretField(revealedSecret);
@@ -195,9 +201,15 @@ function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Pro
if (hasExistingSecret) {
return (
<div className="flex items-center gap-2">
<span className="flex-1 text-xs text-muted-foreground">{t("setting.webhook.create-dialog.signing-secret-configured")}</span>
<Button type="button" variant="outline" size="sm" onClick={handleRevealSecret} disabled={secretState.isLoading}>
<EyeIcon className="mr-1 h-3.5 w-3.5" />
<span className="flex-1 mu-caption text-mu-ink-muted">{t("setting.webhook.create-dialog.signing-secret-configured")}</span>
<Button
type="button"
variant="neutral"
size="sm"
onClick={handleRevealSecret}
disabled={secretState.isLoading}
icon={<EyeIcon />}
>
{t("setting.webhook.create-dialog.reveal-secret")}
</Button>
</div>
@@ -205,8 +217,8 @@ function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Pro
}
return (
<div className="flex items-center gap-2">
<span className="flex-1 text-xs text-muted-foreground">{t("setting.webhook.create-dialog.signing-secret-not-configured")}</span>
<Button type="button" variant="outline" size="sm" onClick={handleGenerateSecret} disabled={secretState.isLoading}>
<span className="flex-1 mu-caption text-mu-ink-muted">{t("setting.webhook.create-dialog.signing-secret-not-configured")}</span>
<Button type="button" variant="neutral" onClick={handleGenerateSecret} disabled={secretState.isLoading}>
{t("setting.webhook.create-dialog.generate-secret")}
</Button>
</div>
@@ -214,25 +226,23 @@ function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Pro
};
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>
{isCreating ? t("setting.webhook.create-dialog.create-webhook") : t("setting.webhook.create-dialog.edit-webhook")}
</DialogTitle>
</DialogHeader>
<Dialog.Root open={open} onOpenChange={handleOpenChange}>
<Dialog.Popup closeLabel={t("common.close")}>
<Dialog.Title>
{isCreating ? t("setting.webhook.create-dialog.create-webhook") : t("setting.webhook.create-dialog.edit-webhook")}
</Dialog.Title>
{createdSecret !== undefined ? (
<div className="grid gap-2">
<Label>{t("setting.webhook.create-dialog.signing-secret")}</Label>
<span className="text-xs text-muted-foreground">{t("setting.webhook.create-dialog.signing-secret-created-note")}</span>
<Field.Root>
<Field.Label>{t("setting.webhook.create-dialog.signing-secret")}</Field.Label>
<Field.Description>{t("setting.webhook.create-dialog.signing-secret-created-note")}</Field.Description>
{renderSecretField(createdSecret)}
</div>
</Field.Root>
) : (
<div className="flex flex-col gap-4">
<div className="grid gap-2">
<Label htmlFor="displayName">
{t("setting.webhook.create-dialog.title")} <span className="text-destructive">*</span>
</Label>
<Field.Root invalid={!!fieldErrors.errors.displayName}>
<Field.Label>
{t("setting.webhook.create-dialog.title")} <span className="text-mu-danger">*</span>
</Field.Label>
<Input
id="displayName"
type="text"
@@ -240,11 +250,12 @@ function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Pro
value={state.displayName}
onChange={handleTitleInputChange}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="url">
{t("setting.webhook.create-dialog.payload-url")} <span className="text-destructive">*</span>
</Label>
{fieldErrors.errors.displayName && <Field.Error match>{fieldErrors.errors.displayName}</Field.Error>}
</Field.Root>
<Field.Root invalid={!!fieldErrors.errors.url}>
<Field.Label>
{t("setting.webhook.create-dialog.payload-url")} <span className="text-mu-danger">*</span>
</Field.Label>
<Input
id="url"
type="text"
@@ -252,29 +263,32 @@ function CreateWebhookDialog({ open, onOpenChange, webhookName, onSuccess }: Pro
value={state.url}
onChange={handleUrlInputChange}
/>
</div>
<div className="grid gap-2">
<Label>{t("setting.webhook.create-dialog.signing-secret")}</Label>
{fieldErrors.errors.url && <Field.Error match>{fieldErrors.errors.url}</Field.Error>}
</Field.Root>
<Field.Root>
<Field.Label>{t("setting.webhook.create-dialog.signing-secret")}</Field.Label>
{renderSigningSecret()}
</div>
</Field.Root>
</div>
)}
<DialogFooter>
<Dialog.Footer>
{createdSecret !== undefined ? (
<Button onClick={() => handleOpenChange(false)}>{t("common.close")}</Button>
<Button variant="primary" onClick={() => handleOpenChange(false)}>
{t("common.close")}
</Button>
) : (
<>
<Button variant="ghost" disabled={requestState.isLoading} onClick={() => onOpenChange(false)}>
{t("common.cancel")}
</Button>
<Button disabled={requestState.isLoading} onClick={handleSaveBtnClick}>
<Button variant="primary" disabled={requestState.isLoading} onClick={handleSaveBtnClick}>
{isCreating ? t("common.create") : t("common.save")}
</Button>
</>
)}
</DialogFooter>
</DialogContent>
</Dialog>
</Dialog.Footer>
</Dialog.Popup>
</Dialog.Root>
);
}
+7 -8
View File
@@ -1,5 +1,4 @@
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Field, Input } from "@usememos/ui";
import { useTranslate } from "@/utils/i18n";
interface Props {
@@ -18,8 +17,8 @@ const CredentialFields = ({ idPrefix, username, password, passwordAutoComplete,
return (
<>
<div className="flex flex-col gap-1.5">
<Label htmlFor={`${idPrefix}-username`}>{t("common.username")}</Label>
<Field.Root>
<Field.Label>{t("common.username")}</Field.Label>
<Input
id={`${idPrefix}-username`}
type="text"
@@ -32,9 +31,9 @@ const CredentialFields = ({ idPrefix, username, password, passwordAutoComplete,
onChange={(e) => onUsernameChange(e.target.value)}
required
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor={`${idPrefix}-password`}>{t("common.password")}</Label>
</Field.Root>
<Field.Root>
<Field.Label>{t("common.password")}</Field.Label>
<Input
id={`${idPrefix}-password`}
type="password"
@@ -47,7 +46,7 @@ const CredentialFields = ({ idPrefix, username, password, passwordAutoComplete,
onChange={(e) => onPasswordChange(e.target.value)}
required
/>
</div>
</Field.Root>
</>
);
};
+2 -2
View File
@@ -12,13 +12,13 @@ interface Props {
function CustomIcon({ icon, className, fallback = AstroidIcon }: Props) {
if (icon?.value.case === "emoji" && icon.value.value) {
return (
<span aria-hidden className={cn("inline-flex shrink-0 items-center justify-center leading-none", className)}>
<span aria-hidden className={cn("mu-icon inline-flex shrink-0 items-center justify-center leading-none", className)}>
{icon.value.value}
</span>
);
}
const IconComponent = getCustomSymbol(icon?.value.case === "lucide" ? icon.value.value : "", fallback);
return <IconComponent aria-hidden className={cn("shrink-0", className)} strokeWidth={1.8} />;
return <IconComponent aria-hidden className={cn("mu-icon shrink-0", className)} />;
}
export default CustomIcon;
+99 -96
View File
@@ -1,14 +1,10 @@
import { AstroidIcon, type LucideIcon, RotateCcwIcon, SearchIcon } from "lucide-react";
import { type KeyboardEvent, useId, useRef, useState } from "react";
import { Button, Combobox, Popover, Toggle, ToggleGroup } from "@usememos/ui";
import { AstroidIcon, type LucideIcon, RotateCcwIcon } from "lucide-react";
import { useRef, useState } from "react";
import CustomIcon from "@/components/CustomIcon";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import type { CustomIconValue } from "@/lib/custom-icons";
import { CUSTOM_SYMBOLS, customIconsEqual } from "@/lib/custom-icons";
import { SPACE_EMOJI } from "@/lib/space-emoji";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
import { FULLY_QUALIFIED_EMOJI } from "@/utils/tag-unicode-data";
@@ -24,11 +20,20 @@ const symbolLabels: Record<string, string> = {
"map-pin": "Location",
"notebook-pen": "Notebook",
};
const symbols = Object.keys(CUSTOM_SYMBOLS).map((name) => ({
interface IconOption {
label: string;
icon: CustomIconValue;
}
const GRID_COLUMNS = 8;
const symbols: IconOption[] = Object.keys(CUSTOM_SYMBOLS).map((name) => ({
label: symbolLabels[name] ?? name.replaceAll("-", " ").replace(/^./, (char) => char.toUpperCase()),
icon: { value: { case: "lucide", value: name } } satisfies CustomIconValue,
}));
const emojis = SPACE_EMOJI.map(([emoji, label]) => ({ label, icon: { value: { case: "emoji", value: emoji } } satisfies CustomIconValue }));
const emojis: IconOption[] = SPACE_EMOJI.map(([emoji, label]) => ({
label,
icon: { value: { case: "emoji", value: emoji } } satisfies CustomIconValue,
}));
interface Props {
value?: CustomIconValue;
@@ -40,15 +45,12 @@ interface Props {
function CustomIconPicker({ value, onChange, disabled, label, fallback = AstroidIcon }: Props) {
const t = useTranslate();
const id = useId();
const [open, setOpen] = useState(false);
const [tab, setTab] = useState("icons");
const [query, setQuery] = useState("");
const [focusedIndex, setFocusedIndex] = useState(0);
const searchRef = useRef<HTMLInputElement>(null);
const gridRef = useRef<HTMLDivElement>(null);
const search = query.trim().toLowerCase();
const options: { label: string; icon: CustomIconValue }[] = (tab === "icons" ? symbols : emojis).filter(
const options: IconOption[] = (tab === "icons" ? symbols : emojis).filter(
(option) => option.label.toLowerCase().includes(search) || option.icon.value.value?.includes(search),
);
const customEmoji = query.trim() || (value?.value.case === "emoji" ? value.value.value : "");
@@ -58,6 +60,8 @@ function CustomIconPicker({ value, onChange, disabled, label, fallback = Astroid
icon: { value: { case: "emoji", value: customEmoji } },
});
}
const rows: IconOption[][] = [];
for (let index = 0; index < options.length; index += GRID_COLUMNS) rows.push(options.slice(index, index + GRID_COLUMNS));
const select = (icon?: CustomIconValue) => {
onChange(icon);
@@ -66,22 +70,10 @@ function CustomIconPicker({ value, onChange, disabled, label, fallback = Astroid
const changeTab = (next: string) => {
setTab(next);
setQuery("");
setFocusedIndex(0);
};
const moveFocus = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
const offsets: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -8, ArrowDown: 8 };
let next = index;
if (event.key in offsets) next = Math.max(0, Math.min(options.length - 1, index + offsets[event.key]));
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = options.length - 1;
else return;
event.preventDefault();
setFocusedIndex(next);
gridRef.current?.querySelectorAll<HTMLButtonElement>("button")[next]?.focus();
};
return (
<Popover
<Popover.Root
open={open}
onOpenChange={(next) => {
if (next) {
@@ -90,87 +82,98 @@ function CustomIconPicker({ value, onChange, disabled, label, fallback = Astroid
setOpen(next);
}}
>
<PopoverTrigger
<Popover.Trigger
render={
<Button type="button" variant="outline" size="icon" className="size-8 p-0" disabled={disabled} aria-label={label} title={label} />
<Button
type="button"
variant="neutral"
disabled={disabled}
aria-label={label}
title={label}
icon={<CustomIcon icon={value} fallback={fallback} className="size-5 text-xl" />}
/>
}
>
<CustomIcon icon={value} fallback={fallback} className="size-5 text-xl" />
</PopoverTrigger>
<PopoverContent align="start" className="w-[290px] max-w-[calc(100vw-2rem)] p-2" aria-label={label} initialFocus={searchRef}>
<Tabs value={tab} onValueChange={changeTab} size="sm">
<TabsList className="mb-2" aria-label={t("space.icon.kind")}>
{(["icons", "emoji"] as const).map((name) => (
<TabsTrigger key={name} id={`${id}-${name}`} value={name} aria-controls={`${id}-panel`} className="flex-1">
{t(`space.icon.${name}`)}
</TabsTrigger>
))}
</TabsList>
</Tabs>
<div id={`${id}-panel`} role="tabpanel" aria-labelledby={`${id}-${tab}`}>
<div className="relative mb-2">
<SearchIcon aria-hidden className="pointer-events-none absolute start-2 top-2 size-4 text-muted-foreground" />
<Input
/>
<Popover.Popup align="start" className="w-[306px] max-w-[calc(100vw-2rem)]" aria-label={label} initialFocus={searchRef}>
<ToggleGroup
size="sm"
aria-label={t("space.icon.kind")}
value={[tab]}
onValueChange={([next]: string[]) => next && changeTab(next)}
>
{(["icons", "emoji"] as const).map((name) => (
<Toggle key={name} value={name}>
{t(`space.icon.${name}`)}
</Toggle>
))}
</ToggleGroup>
<div>
{/* The rows are filtered here (labels and the glyph itself, plus a pasted emoji), so the
combobox's own filter is off and it only drives the 2-D highlight and Enter. */}
<Combobox.Root
items={options}
filter={null}
inline
grid
autoHighlight
value={value ? { label: "", icon: value } : null}
isItemEqualToValue={(item: IconOption, current: IconOption) => customIconsEqual(item.icon, current.icon)}
itemToStringLabel={(item: IconOption) => item.label}
onValueChange={(item: IconOption | null) => {
if (item) select(item.icon);
}}
inputValue={query}
onInputValueChange={(next, { reason }) => {
// Picking a cell would write its label into the search; the popup closes instead.
if (reason === "input-change" || reason === "input-clear") setQuery(next);
}}
onOpenChange={(next, { reason }) => {
if (!next && reason === "escape-key") setOpen(false);
}}
>
<Combobox.Input
ref={searchRef}
value={query}
className="ps-8 text-sm"
className="mb-1"
aria-label={t(tab === "icons" ? "space.icon.search-icons" : "space.icon.search-emoji")}
placeholder={t(tab === "icons" ? "space.icon.search-icons" : "space.icon.search-emoji")}
onChange={(event) => {
setQuery(event.target.value);
setFocusedIndex(0);
}}
onKeyDown={(event) => {
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
if (event.key === "Enter") {
event.preventDefault();
if (options[0]) select(options[0].icon);
} else if (event.key === "ArrowDown" && options.length) {
event.preventDefault();
setFocusedIndex(0);
gridRef.current?.querySelector<HTMLButtonElement>("button")?.focus();
}
}}
/>
</div>
<div className="max-h-56 overflow-y-auto overscroll-contain" ref={gridRef}>
{options.length ? (
<div className="grid grid-cols-8 gap-0.5">
{options.map((option, index) => (
<Button
key={`${option.icon.value.case}:${option.icon.value.value}`}
type="button"
variant="ghost"
size="icon"
aria-label={option.label}
title={option.label}
aria-pressed={customIconsEqual(value, option.icon)}
tabIndex={index === Math.min(focusedIndex, options.length - 1) ? 0 : -1}
onFocus={() => setFocusedIndex(index)}
onKeyDown={(event) => moveFocus(event, index)}
onClick={() => select(option.icon)}
className={cn("rounded-md", customIconsEqual(value, option.icon) && "bg-accent ring-1 ring-inset ring-primary/40")}
>
<CustomIcon icon={option.icon} className={tab === "emoji" ? "size-5 text-xl" : "size-4"} />
</Button>
))}
</div>
) : (
<p role="status" className="py-8 text-center text-xs text-muted-foreground">
{t("space.icon.no-results")}
</p>
)}
</div>
{tab === "emoji" && <p className="px-1 pt-2 text-xs leading-4 text-muted-foreground">{t("space.icon.emoji-help")}</p>}
<Combobox.Empty>{t("space.icon.no-results")}</Combobox.Empty>
{/* The list's own padding keeps highlighted cells clear of its scroll edge; the negative
margin lines the cells up with the search box as before. */}
<Combobox.List aria-label={t(`space.icon.${tab === "icons" ? "icons" : "emoji"}`)} className="-mx-1">
{rows.map((row) => (
<Combobox.Row key={`${row[0].icon.value.case}:${row[0].icon.value.value}`}>
{row.map((option) => (
<Combobox.Item
key={`${option.icon.value.case}:${option.icon.value.value}`}
value={option}
aria-label={option.label}
title={option.label}
>
<CustomIcon icon={option.icon} className={tab === "emoji" ? "size-5 text-xl" : undefined} />
</Combobox.Item>
))}
</Combobox.Row>
))}
</Combobox.List>
</Combobox.Root>
{tab === "emoji" && <p className="px-1 pt-2 mu-caption text-mu-ink-muted">{t("space.icon.emoji-help")}</p>}
</div>
<div className="mt-2 border-t pt-1.5">
<Button type="button" variant="quiet" size="sm" className="w-full justify-start" disabled={!value} onClick={() => select()}>
<RotateCcwIcon aria-hidden className="size-3.5" />
<Button
type="button"
variant="ghost"
size="sm"
className="w-full justify-start"
disabled={!value}
onClick={() => select()}
icon={<RotateCcwIcon aria-hidden />}
>
{t("space.icon.reset")}
</Button>
</div>
</PopoverContent>
</Popover>
</Popover.Popup>
</Popover.Root>
);
}
+9 -3
View File
@@ -1,6 +1,7 @@
import dayjs from "dayjs";
import toast from "react-hot-toast";
import { showErrorToast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
// must be compatible with JS Date.parse(), we use ISO 8601 (almost)
const DATE_TIME_FORMAT = "YYYY-MM-DD HH:mm:ss";
@@ -16,10 +17,15 @@ interface Props {
}
const DateTimeInput: React.FC<Props> = ({ value, onChange }) => {
const t = useTranslate();
return (
<input
type="datetime-local"
className={cn("px-1 bg-transparent rounded text-xs transition-all", "border-transparent outline-none focus:border-border", "border")}
className={cn(
"px-1 bg-transparent rounded mu-caption transition-all",
"border-transparent outline-none focus:border-mu-line",
"border",
)}
defaultValue={formatDate(value)}
onBlur={(e) => {
const inputValue = e.target.value;
@@ -30,7 +36,7 @@ const DateTimeInput: React.FC<Props> = ({ value, onChange }) => {
if (!isNaN(date.getTime())) {
onChange(date);
} else {
toast.error("Invalid datetime format. Use format: 2023-12-31 23:59:59");
showErrorToast(t("message.invalid-datetime"));
e.target.value = formatDate(value);
}
}
+22 -27
View File
@@ -1,7 +1,8 @@
import { Button } from "@usememos/ui";
import { AlertCircle, RefreshCw } from "lucide-react";
import { Component, type ErrorInfo, type ReactNode } from "react";
import { useRouteError } from "react-router-dom";
import { Button } from "./ui/button";
import { translate } from "@/utils/i18n";
interface Props {
children: ReactNode;
@@ -39,27 +40,24 @@ export class ErrorBoundary extends Component<Props, State> {
}
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<div className="flex items-center justify-center min-h-screen bg-mu-canvas">
<div className="max-w-md w-full p-6 space-y-4">
<div className="flex items-center gap-3 text-destructive">
<AlertCircle className="w-8 h-8" />
<h1 className="text-2xl font-bold">Something went wrong</h1>
<div className="flex items-center gap-3 text-mu-danger">
<AlertCircle className="mu-icon w-8 h-8" />
<h1 className="mu-heading">{translate("error.title")}</h1>
</div>
<p className="text-foreground/70">
An unexpected error occurred. This could be due to a network issue or a problem with the application.
</p>
<p className="text-mu-ink/70">{translate("error.description")}</p>
{this.state.error && (
<details className="bg-muted p-3 rounded-md text-sm">
<summary className="cursor-pointer font-medium mb-2">Error details</summary>
<pre className="whitespace-pre-wrap break-words text-xs text-foreground/60">{this.state.error.message}</pre>
<details className="bg-mu-well p-3 rounded-mu-md mu-body">
<summary className="cursor-pointer font-medium mb-2">{translate("error.details")}</summary>
<pre className="whitespace-pre-wrap break-words mu-caption text-mu-ink/60">{this.state.error.message}</pre>
</details>
)}
<Button onClick={this.handleReset} className="w-full gap-2">
<RefreshCw className="w-4 h-4" />
Reload Application
<Button variant="primary" onClick={this.handleReset} className="w-full" icon={<RefreshCw />}>
{translate("error.reload")}
</Button>
</div>
</div>
@@ -75,27 +73,24 @@ export function ChunkLoadErrorFallback() {
const error = useRouteError() as Error | undefined;
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<div className="flex items-center justify-center min-h-screen bg-mu-canvas">
<div className="max-w-md w-full p-6 space-y-4">
<div className="flex items-center gap-3 text-destructive">
<AlertCircle className="w-8 h-8" />
<h1 className="text-2xl font-bold">Something went wrong</h1>
<div className="flex items-center gap-3 text-mu-danger">
<AlertCircle className="mu-icon w-8 h-8" />
<h1 className="mu-heading">{translate("error.title")}</h1>
</div>
<p className="text-foreground/70">
An unexpected error occurred. This could be due to a network issue or an application update. Reloading usually fixes it.
</p>
<p className="text-mu-ink/70">{translate("error.description-update")}</p>
{error?.message && (
<details className="bg-muted p-3 rounded-md text-sm">
<summary className="cursor-pointer font-medium mb-2">Error details</summary>
<pre className="whitespace-pre-wrap break-words text-xs text-foreground/60">{error.message}</pre>
<details className="bg-mu-well p-3 rounded-mu-md mu-body">
<summary className="cursor-pointer font-medium mb-2">{translate("error.details")}</summary>
<pre className="whitespace-pre-wrap break-words mu-caption text-mu-ink/60">{error.message}</pre>
</details>
)}
<Button onClick={() => window.location.reload()} className="w-full gap-2">
<RefreshCw className="w-4 h-4" />
Reload Application
<Button variant="primary" onClick={() => window.location.reload()} className="w-full" icon={<RefreshCw />}>
{translate("error.reload")}
</Button>
</div>
</div>
+2 -3
View File
@@ -1,6 +1,7 @@
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
/** The wordmark keeps its own lettering scale: it is the brand mark set as text, not app text. */
const TEXT_SCALE = { sm: "text-base", md: "text-lg", lg: "text-2xl", hero: "text-[2rem]" } as const;
interface Props {
@@ -17,9 +18,7 @@ interface Props {
* brand wordmark's weight and spacing in the theme's serif stack; the exact face is not required.
*/
const IdentityLabel = ({ mark, label, size = "md", collapsed, wrap, className }: Props) => (
<span
className={cn("flex min-w-0 items-center text-foreground", size === "hero" ? "gap-3" : size === "lg" ? "gap-2.5" : "gap-2", className)}
>
<span className={cn("flex min-w-0 items-center text-mu-ink", size === "hero" ? "gap-3" : size === "lg" ? "gap-2.5" : "gap-2", className)}>
{mark}
{!collapsed && (
<span
@@ -1,9 +1,8 @@
import { LoaderIcon } from "lucide-react";
import { Button } from "@usememos/ui";
import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "react-hot-toast";
import { useSearchParams } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { handleError } from "@/lib/error";
import { showErrorToast } from "@/lib/toast";
import { IdentityProvider } from "@/types/proto/api/idp_service_pb";
import { AUTH_AUTO_SIGN_IN_PARAM } from "@/utils/auth-redirect";
import { useTranslate } from "@/utils/i18n";
@@ -41,7 +40,7 @@ const IdentityProviderButtons = ({ identityProviderList, redirectTarget, autoSig
} catch (error) {
pendingRef.current = false;
setPendingProvider(undefined);
handleError(error, toast.error, {
handleError(error, showErrorToast, {
context: "Failed to initiate OAuth flow",
fallbackMessage: "Failed to initiate sign-in. Please try again.",
});
@@ -83,14 +82,12 @@ const IdentityProviderButtons = ({ identityProviderList, redirectTarget, autoSig
{identityProviderList.map((identityProvider) => (
<Button
key={identityProvider.name}
variant="outline"
variant="neutral"
disabled={Boolean(pendingProvider)}
aria-busy={pendingProvider?.name === identityProvider.name}
loading={pendingProvider?.name === identityProvider.name}
loadingLabel={t("auth.continue-with", { provider: identityProvider.title })}
onClick={() => void handleSignInWithIdentityProvider(identityProvider)}
>
{pendingProvider?.name === identityProvider.name && (
<LoaderIcon className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden="true" />
)}
{t("auth.continue-with", { provider: identityProvider.title })}
</Button>
))}
+38 -42
View File
@@ -1,10 +1,10 @@
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { CheckIcon, MessageCircleIcon, TrashIcon, XIcon } from "lucide-react";
import toast from "react-hot-toast";
import UserAvatar from "@/components/UserAvatar";
import useNavigateTo from "@/hooks/useNavigateTo";
import { useArchiveNotification, useDeleteNotification } from "@/hooks/useUserQueries";
import { handleError } from "@/lib/error";
import { showErrorToast, toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { UserNotification, UserNotification_Status } from "@/types/proto/api/user_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -25,38 +25,38 @@ function MemoCommentMessage({ notification }: Props) {
try {
await archiveNotification.mutateAsync(notification.name);
if (!silence) {
toast.success(t("message.archived-successfully"));
toast.add({ title: t("message.archived-successfully"), type: "success" });
}
} catch (error) {
handleError(error, toast.error, { context: "Archive notification" });
handleError(error, showErrorToast, { context: "Archive notification" });
}
};
const handleDeleteMessage = async () => {
try {
await deleteNotification.mutateAsync(notification.name);
toast.success(t("message.deleted-successfully"));
toast.add({ title: t("message.deleted-successfully"), type: "success" });
} catch (error) {
handleError(error, toast.error, { context: "Delete notification" });
handleError(error, showErrorToast, { context: "Delete notification" });
}
};
if (!commentPayload) {
return (
<div className="w-full px-5 py-4 border-b border-border/60 last:border-b-0 bg-destructive/[0.04] group">
<div className="w-full px-5 py-4 border-b border-mu-line/60 last:border-b-0 group">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center shrink-0 ring-1 ring-destructive/20">
<XIcon className="w-5 h-5 text-destructive" strokeWidth={2} />
<div className="w-10 h-10 rounded-full bg-mu-danger-soft flex items-center justify-center shrink-0">
<XIcon className="mu-icon w-5 h-5 text-mu-danger" />
</div>
<span className="text-sm text-destructive/80 font-medium">{t("inbox.failed-to-load")}</span>
<span className="mu-label text-mu-danger/80">{t("inbox.failed-to-load")}</span>
</div>
<button
onClick={handleDeleteMessage}
className="p-1.5 hover:bg-destructive/15 rounded-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
className="p-1.5 hover:bg-mu-danger-soft rounded-mu-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
title={t("common.delete")}
>
<TrashIcon className="w-4 h-4 text-destructive/70 hover:text-destructive transition-colors" strokeWidth={2} />
<TrashIcon className="mu-icon text-mu-danger/70 hover:text-mu-danger transition-colors" />
</button>
</div>
</div>
@@ -75,83 +75,79 @@ function MemoCommentMessage({ notification }: Props) {
return (
<div
className={cn(
"w-full px-5 py-4 border-b border-border/60 last:border-b-0 transition-all duration-200 group relative",
isUnread ? "bg-primary/[0.03] hover:bg-primary/[0.05]" : "hover:bg-muted/30",
"w-full px-5 py-4 border-b border-mu-line/60 last:border-b-0 transition-all duration-200 group relative",
isUnread ? "bg-mu-primary/[0.03] hover:bg-mu-primary/[0.05]" : "hover:bg-mu-hover",
)}
>
{isUnread && <div className="absolute left-0 top-0 bottom-0 w-0.5 bg-gradient-to-b from-primary to-primary/60" />}
{isUnread && <div className="absolute left-0 top-0 bottom-0 w-0.5 bg-gradient-to-b from-mu-primary to-mu-primary/60" />}
<div className="flex items-start gap-3">
<div className="relative shrink-0">
<UserAvatar
className="w-10 h-10 ring-1 ring-border/40"
avatarUrl={sender?.avatarUrl}
name={sender?.displayName || sender?.username}
/>
<UserAvatar className="w-10 h-10" avatarUrl={sender?.avatarUrl} name={sender?.displayName || sender?.username} />
<div
className={cn(
"absolute -bottom-1 -right-1 w-5 h-5 rounded-full border-2 border-background flex items-center justify-center shadow-md transition-all",
isUnread ? "bg-primary text-primary-foreground" : "bg-muted/80 text-muted-foreground",
"absolute -bottom-1 -right-1 w-5 h-5 rounded-full border-2 border-mu-canvas flex items-center justify-center shadow-mu-pop transition-all",
isUnread ? "bg-mu-primary text-mu-on-primary" : "bg-mu-well/80 text-mu-ink-muted",
)}
>
<MessageCircleIcon className="w-2.5 h-2.5" strokeWidth={2.5} />
<MessageCircleIcon className="mu-icon-xs w-2.5 h-2.5" />
</div>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-3 mb-1">
<div className="flex items-center gap-1.5 flex-wrap min-w-0">
<span className="font-semibold text-sm text-foreground/95">{sender?.displayName || sender?.username}</span>
<span className="text-sm text-muted-foreground/80">commented on your memo</span>
<span className="text-xs text-muted-foreground/60">
<span className="mu-label text-mu-ink/95">{sender?.displayName || sender?.username}</span>
<span className="mu-body text-mu-ink-muted/80">{t("inbox.commented-on-memo")}</span>
<span className="mu-caption text-mu-ink-muted/60">
{notification.createTime &&
timestampDate(notification.createTime)?.toLocaleDateString([], { month: "short", day: "numeric" })}{" "}
at{" "}
{notification.createTime &&
timestampDate(notification.createTime)?.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
t("common.date-at-time", {
date: timestampDate(notification.createTime).toLocaleDateString([], { month: "short", day: "numeric" }),
time: timestampDate(notification.createTime).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
})}
</span>
</div>
<div className="flex items-center gap-1 shrink-0">
{isUnread ? (
<button
onClick={() => handleArchiveMessage()}
className="p-1.5 hover:bg-primary/10 rounded-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
className="p-1.5 hover:bg-mu-primary/10 rounded-mu-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
title={t("common.archive")}
>
<CheckIcon className="w-4 h-4 text-muted-foreground hover:text-primary transition-colors" strokeWidth={2} />
<CheckIcon className="mu-icon text-mu-ink-muted hover:text-mu-primary transition-colors" />
</button>
) : (
<button
onClick={handleDeleteMessage}
className="p-1.5 hover:bg-destructive/10 rounded-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
className="p-1.5 hover:bg-mu-danger-soft rounded-mu-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
title={t("common.delete")}
>
<TrashIcon className="w-4 h-4 text-muted-foreground hover:text-destructive transition-colors" strokeWidth={2} />
<TrashIcon className="mu-icon text-mu-ink-muted hover:text-mu-danger transition-colors" />
</button>
)}
</div>
</div>
<div className="pl-3 border-l-2 border-muted-foreground/20 mb-3">
<p className="text-sm text-foreground/60 line-clamp-1 leading-relaxed">
<span className="text-xs text-muted-foreground/50 font-medium mr-2 uppercase tracking-wide">Original:</span>
{commentPayload.relatedMemoSnippet || <span className="italic text-muted-foreground/40">Empty memo</span>}
<div className="pl-3 border-l-2 border-mu-ink-muted/20 mb-3">
<p className="mu-body text-mu-ink/60 line-clamp-1">
<span className="mu-label-sm text-mu-ink-muted/50 mr-2 uppercase tracking-wide">{t("inbox.original")}</span>
{commentPayload.relatedMemoSnippet || <span className="italic text-mu-ink-muted/40">{t("inbox.empty-memo")}</span>}
</p>
</div>
<button
type="button"
onClick={handleNavigateToMemo}
className="w-full p-2 text-left sm:p-3 rounded-lg bg-gradient-to-br from-primary/[0.06] to-primary/[0.03] hover:from-primary/[0.1] hover:to-primary/[0.06] cursor-pointer border border-primary/30 hover:border-primary/50 transition-all duration-200 group/comment shadow-sm hover:shadow"
className="w-full p-2 text-left sm:p-3 rounded-mu-lg bg-gradient-to-br from-mu-primary/[0.06] to-mu-primary/[0.03] hover:from-mu-primary/[0.1] hover:to-mu-primary/[0.06] cursor-pointer border border-mu-primary/30 hover:border-mu-primary/50 transition-all duration-200 group/comment shadow-mu-key hover:shadow"
>
<div className="flex items-start gap-2">
<div className="w-5 h-5 flex items-center justify-center shrink-0">
<MessageCircleIcon className="w-4 h-4 text-primary" />
<MessageCircleIcon className="mu-icon text-mu-primary" />
</div>
<div className="flex-1 min-w-0">
<p className="text-xs text-primary/60 font-semibold mb-1 uppercase tracking-wider">Comment</p>
<p className="text-sm text-foreground/90 line-clamp-2">
{commentPayload.memoSnippet || <span className="italic text-muted-foreground/50">Empty comment</span>}
<p className="mu-label-sm text-mu-primary/60 mb-1 uppercase tracking-wider">{t("inbox.comment-heading")}</p>
<p className="mu-body text-mu-ink/90 line-clamp-2">
{commentPayload.memoSnippet || <span className="italic text-mu-ink-muted/50">{t("inbox.empty-comment")}</span>}
</p>
</div>
</div>
+41 -43
View File
@@ -1,10 +1,10 @@
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { AtSignIcon, CheckIcon, MessageSquareIcon, TrashIcon, XIcon } from "lucide-react";
import toast from "react-hot-toast";
import UserAvatar from "@/components/UserAvatar";
import useNavigateTo from "@/hooks/useNavigateTo";
import { useArchiveNotification, useDeleteNotification } from "@/hooks/useUserQueries";
import { handleError } from "@/lib/error";
import { showErrorToast, toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { UserNotification, UserNotification_Status } from "@/types/proto/api/user_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -25,38 +25,38 @@ function MemoMentionMessage({ notification }: Props) {
try {
await archiveNotification.mutateAsync(notification.name);
if (!silence) {
toast.success(t("message.archived-successfully"));
toast.add({ title: t("message.archived-successfully"), type: "success" });
}
} catch (error) {
handleError(error, toast.error, { context: "Archive notification" });
handleError(error, showErrorToast, { context: "Archive notification" });
}
};
const handleDeleteMessage = async () => {
try {
await deleteNotification.mutateAsync(notification.name);
toast.success(t("message.deleted-successfully"));
toast.add({ title: t("message.deleted-successfully"), type: "success" });
} catch (error) {
handleError(error, toast.error, { context: "Delete notification" });
handleError(error, showErrorToast, { context: "Delete notification" });
}
};
if (!mentionPayload) {
return (
<div className="w-full px-5 py-4 border-b border-border/60 last:border-b-0 bg-destructive/[0.04] group">
<div className="w-full px-5 py-4 border-b border-mu-line/60 last:border-b-0 group">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center shrink-0 ring-1 ring-destructive/20">
<XIcon className="w-5 h-5 text-destructive" strokeWidth={2} />
<div className="w-10 h-10 rounded-full bg-mu-danger-soft flex items-center justify-center shrink-0">
<XIcon className="mu-icon w-5 h-5 text-mu-danger" />
</div>
<span className="text-sm text-destructive/80 font-medium">{t("inbox.failed-to-load")}</span>
<span className="mu-label text-mu-danger/80">{t("inbox.failed-to-load")}</span>
</div>
<button
onClick={handleDeleteMessage}
className="p-1.5 hover:bg-destructive/15 rounded-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
className="p-1.5 hover:bg-mu-danger-soft rounded-mu-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
title={t("common.delete")}
>
<TrashIcon className="w-4 h-4 text-destructive/70 hover:text-destructive transition-colors" strokeWidth={2} />
<TrashIcon className="mu-icon text-mu-danger/70 hover:text-mu-danger transition-colors" />
</button>
</div>
</div>
@@ -77,68 +77,66 @@ function MemoMentionMessage({ notification }: Props) {
return (
<div
className={cn(
"w-full px-5 py-4 border-b border-border/60 last:border-b-0 transition-all duration-200 group relative",
isUnread ? "bg-primary/[0.03] hover:bg-primary/[0.05]" : "hover:bg-muted/30",
"w-full px-5 py-4 border-b border-mu-line/60 last:border-b-0 transition-all duration-200 group relative",
isUnread ? "bg-mu-primary/[0.03] hover:bg-mu-primary/[0.05]" : "hover:bg-mu-hover",
)}
>
{isUnread && <div className="absolute left-0 top-0 bottom-0 w-0.5 bg-gradient-to-b from-primary to-primary/60" />}
{isUnread && <div className="absolute left-0 top-0 bottom-0 w-0.5 bg-gradient-to-b from-mu-primary to-mu-primary/60" />}
<div className="flex items-start gap-3">
<div className="relative shrink-0">
<UserAvatar
className="w-10 h-10 ring-1 ring-border/40"
avatarUrl={sender?.avatarUrl}
name={sender?.displayName || sender?.username}
/>
<UserAvatar className="w-10 h-10" avatarUrl={sender?.avatarUrl} name={sender?.displayName || sender?.username} />
<div
className={cn(
"absolute -bottom-1 -right-1 w-5 h-5 rounded-full border-2 border-background flex items-center justify-center shadow-md transition-all",
isUnread ? "bg-primary text-primary-foreground" : "bg-muted/80 text-muted-foreground",
"absolute -bottom-1 -right-1 w-5 h-5 rounded-full border-2 border-mu-canvas flex items-center justify-center shadow-mu-pop transition-all",
isUnread ? "bg-mu-primary text-mu-on-primary" : "bg-mu-well/80 text-mu-ink-muted",
)}
>
<AtSignIcon className="w-2.5 h-2.5" strokeWidth={2.5} />
<AtSignIcon className="mu-icon-xs w-2.5 h-2.5" />
</div>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-3 mb-1">
<div className="flex items-center gap-1.5 flex-wrap min-w-0">
<span className="font-semibold text-sm text-foreground/95">{sender?.displayName || sender?.username}</span>
<span className="text-sm text-muted-foreground/80">mentioned you {isCommentMention ? "in a comment" : "in a memo"}</span>
<span className="text-xs text-muted-foreground/60">
<span className="mu-label text-mu-ink/95">{sender?.displayName || sender?.username}</span>
<span className="mu-body text-mu-ink-muted/80">
{isCommentMention ? t("inbox.mentioned-in-comment") : t("inbox.mentioned-in-memo")}
</span>
<span className="mu-caption text-mu-ink-muted/60">
{notification.createTime &&
timestampDate(notification.createTime)?.toLocaleDateString([], { month: "short", day: "numeric" })}{" "}
at{" "}
{notification.createTime &&
timestampDate(notification.createTime)?.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
t("common.date-at-time", {
date: timestampDate(notification.createTime).toLocaleDateString([], { month: "short", day: "numeric" }),
time: timestampDate(notification.createTime).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
})}
</span>
</div>
<div className="flex items-center gap-1 shrink-0">
{isUnread ? (
<button
onClick={() => handleArchiveMessage()}
className="p-1.5 hover:bg-primary/10 rounded-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
className="p-1.5 hover:bg-mu-primary/10 rounded-mu-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
title={t("common.archive")}
>
<CheckIcon className="w-4 h-4 text-muted-foreground hover:text-primary transition-colors" strokeWidth={2} />
<CheckIcon className="mu-icon text-mu-ink-muted hover:text-mu-primary transition-colors" />
</button>
) : (
<button
onClick={handleDeleteMessage}
className="p-1.5 hover:bg-destructive/10 rounded-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
className="p-1.5 hover:bg-mu-danger-soft rounded-mu-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
title={t("common.delete")}
>
<TrashIcon className="w-4 h-4 text-muted-foreground hover:text-destructive transition-colors" strokeWidth={2} />
<TrashIcon className="mu-icon text-mu-ink-muted hover:text-mu-danger transition-colors" />
</button>
)}
</div>
</div>
{mentionPayload.relatedMemo && (
<div className="pl-3 border-l-2 border-muted-foreground/20 mb-3">
<p className="text-sm text-foreground/60 line-clamp-1 leading-relaxed">
<span className="text-xs text-muted-foreground/50 font-medium mr-2 uppercase tracking-wide">Memo:</span>
{mentionPayload.relatedMemoSnippet || <span className="italic text-muted-foreground/40">Empty memo</span>}
<div className="pl-3 border-l-2 border-mu-ink-muted/20 mb-3">
<p className="mu-body text-mu-ink/60 line-clamp-1">
<span className="mu-label-sm text-mu-ink-muted/50 mr-2 uppercase tracking-wide">{t("inbox.memo-label")}</span>
{mentionPayload.relatedMemoSnippet || <span className="italic text-mu-ink-muted/40">{t("inbox.empty-memo")}</span>}
</p>
</div>
)}
@@ -146,18 +144,18 @@ function MemoMentionMessage({ notification }: Props) {
<button
type="button"
onClick={handleNavigate}
className="w-full p-2 text-left sm:p-3 rounded-lg bg-gradient-to-br from-primary/[0.06] to-primary/[0.03] hover:from-primary/[0.1] hover:to-primary/[0.06] cursor-pointer border border-primary/30 hover:border-primary/50 transition-all duration-200 group/comment shadow-sm hover:shadow"
className="w-full p-2 text-left sm:p-3 rounded-mu-lg bg-gradient-to-br from-mu-primary/[0.06] to-mu-primary/[0.03] hover:from-mu-primary/[0.1] hover:to-mu-primary/[0.06] cursor-pointer border border-mu-primary/30 hover:border-mu-primary/50 transition-all duration-200 group/comment shadow-mu-key hover:shadow"
>
<div className="flex items-start gap-2">
<div className="w-5 h-5 flex items-center justify-center shrink-0">
<MessageSquareIcon className="w-4 h-4 text-primary" />
<MessageSquareIcon className="mu-icon text-mu-primary" />
</div>
<div className="flex-1 min-w-0">
<p className="text-xs text-primary/60 font-semibold mb-1 uppercase tracking-wider">
{isCommentMention ? "Comment" : "Memo"}
<p className="mu-label-sm text-mu-primary/60 mb-1 uppercase tracking-wider">
{isCommentMention ? t("inbox.comment-heading") : t("inbox.memo-heading")}
</p>
<p className="text-sm text-foreground/90 line-clamp-2">
{mentionPayload.memoSnippet || <span className="italic text-muted-foreground/50">Empty memo</span>}
<p className="mu-body text-mu-ink/90 line-clamp-2">
{mentionPayload.memoSnippet || <span className="italic text-mu-ink-muted/50">{t("inbox.empty-memo")}</span>}
</p>
</div>
</div>
@@ -1,16 +1,16 @@
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { Button } from "@usememos/ui";
import { CheckIcon, TrashIcon, UsersIcon, XIcon } from "lucide-react";
import toast from "react-hot-toast";
import SpaceMark from "@/components/SpaceMark";
import SpaceRoleBadge from "@/components/SpaceRoleBadge";
import UserAvatar from "@/components/UserAvatar";
import { Button } from "@/components/ui/button";
import { useSpaceContext } from "@/contexts/SpaceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useAcceptSpaceInvitation, useDeclineSpaceInvitation } from "@/hooks/useSpaceQueries";
import { useArchiveNotification, useDeleteNotification } from "@/hooks/useUserQueries";
import { handleError } from "@/lib/error";
import { extractSpaceUidFromName } from "@/lib/space-display";
import { showErrorToast, toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import {
UserNotification,
@@ -40,38 +40,38 @@ function SpaceInvitationMessage({ notification }: Props) {
try {
await archiveNotification.mutateAsync(notification.name);
if (!silence) {
toast.success(t("message.archived-successfully"));
toast.add({ title: t("message.archived-successfully"), type: "success" });
}
} catch (error) {
handleError(error, toast.error, { context: "Archive notification" });
handleError(error, showErrorToast, { context: "Archive notification" });
}
};
const handleDeleteMessage = async () => {
try {
await deleteNotification.mutateAsync(notification.name);
toast.success(t("message.deleted-successfully"));
toast.add({ title: t("message.deleted-successfully"), type: "success" });
} catch (error) {
handleError(error, toast.error, { context: "Delete notification" });
handleError(error, showErrorToast, { context: "Delete notification" });
}
};
if (!payload || !space) {
return (
<div className="w-full px-5 py-4 border-b border-border/60 last:border-b-0 bg-destructive/[0.04] group">
<div className="w-full px-5 py-4 border-b border-mu-line/60 last:border-b-0 group">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-destructive/15 flex items-center justify-center shrink-0 ring-1 ring-destructive/20">
<XIcon className="w-5 h-5 text-destructive" strokeWidth={2} />
<div className="w-10 h-10 rounded-full bg-mu-danger-soft flex items-center justify-center shrink-0">
<XIcon className="mu-icon w-5 h-5 text-mu-danger" />
</div>
<span className="text-sm text-destructive/80 font-medium">{t("inbox.failed-to-load")}</span>
<span className="mu-label text-mu-danger/80">{t("inbox.failed-to-load")}</span>
</div>
<button
onClick={handleDeleteMessage}
className="p-1.5 hover:bg-destructive/15 rounded-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
className="p-1.5 hover:bg-mu-danger-soft rounded-mu-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
title={t("common.delete")}
>
<TrashIcon className="w-4 h-4 text-destructive/70 hover:text-destructive transition-colors" strokeWidth={2} />
<TrashIcon className="mu-icon text-mu-danger/70 hover:text-mu-danger transition-colors" />
</button>
</div>
</div>
@@ -87,18 +87,18 @@ function SpaceInvitationMessage({ notification }: Props) {
const handleAccept = async () => {
try {
await acceptInvitation.mutateAsync({ name: payload.spaceInvitation });
toast.success(t("setting.spaces.accept-success", { space: spaceLabel }));
toast.add({ title: t("setting.spaces.accept-success", { space: spaceLabel }), type: "success" });
} catch (error) {
handleError(error, toast.error, { context: "Accept space invitation" });
handleError(error, showErrorToast, { context: "Accept space invitation" });
}
};
const handleDecline = async () => {
try {
await declineInvitation.mutateAsync({ name: payload.spaceInvitation });
toast.success(t("setting.spaces.decline-success"));
toast.add({ title: t("setting.spaces.decline-success"), type: "success" });
} catch (error) {
handleError(error, toast.error, { context: "Decline space invitation" });
handleError(error, showErrorToast, { context: "Decline space invitation" });
}
};
@@ -109,83 +109,79 @@ function SpaceInvitationMessage({ notification }: Props) {
return (
<div
className={cn(
"w-full px-5 py-4 border-b border-border/60 last:border-b-0 transition-all duration-200 group relative",
isUnread ? "bg-primary/[0.03] hover:bg-primary/[0.05]" : "hover:bg-muted/30",
"w-full px-5 py-4 border-b border-mu-line/60 last:border-b-0 transition-all duration-200 group relative",
isUnread ? "bg-mu-primary/[0.03] hover:bg-mu-primary/[0.05]" : "hover:bg-mu-hover",
)}
>
{isUnread && <div className="absolute left-0 top-0 bottom-0 w-0.5 bg-gradient-to-b from-primary to-primary/60" />}
{isUnread && <div className="absolute left-0 top-0 bottom-0 w-0.5 bg-gradient-to-b from-mu-primary to-mu-primary/60" />}
<div className="flex items-start gap-3">
<div className="relative shrink-0">
<UserAvatar
className="w-10 h-10 ring-1 ring-border/40"
avatarUrl={sender?.avatarUrl}
name={sender?.displayName || sender?.username}
/>
<UserAvatar className="w-10 h-10" avatarUrl={sender?.avatarUrl} name={sender?.displayName || sender?.username} />
<div
className={cn(
"absolute -bottom-1 -right-1 w-5 h-5 rounded-full border-2 border-background flex items-center justify-center shadow-md transition-all",
isUnread ? "bg-primary text-primary-foreground" : "bg-muted/80 text-muted-foreground",
"absolute -bottom-1 -right-1 w-5 h-5 rounded-full border-2 border-mu-canvas flex items-center justify-center shadow-mu-pop transition-all",
isUnread ? "bg-mu-primary text-mu-on-primary" : "bg-mu-well/80 text-mu-ink-muted",
)}
>
<UsersIcon className="w-2.5 h-2.5" strokeWidth={2.5} />
<UsersIcon className="mu-icon-xs w-2.5 h-2.5" />
</div>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-3 mb-3">
<div className="flex items-center gap-1.5 flex-wrap min-w-0">
<span className="font-semibold text-sm text-foreground/95">{sender?.displayName || sender?.username}</span>
<span className="text-sm text-muted-foreground/80">{t("inbox.space-invitation")}</span>
<span className="text-xs text-muted-foreground/60">
<span className="mu-label text-mu-ink/95">{sender?.displayName || sender?.username}</span>
<span className="mu-body text-mu-ink-muted/80">{t("inbox.space-invitation")}</span>
<span className="mu-caption text-mu-ink-muted/60">
{notification.createTime &&
timestampDate(notification.createTime)?.toLocaleDateString([], { month: "short", day: "numeric" })}{" "}
at{" "}
{notification.createTime &&
timestampDate(notification.createTime)?.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
t("common.date-at-time", {
date: timestampDate(notification.createTime).toLocaleDateString([], { month: "short", day: "numeric" }),
time: timestampDate(notification.createTime).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
})}
</span>
</div>
<div className="flex items-center gap-1 shrink-0">
{isUnread ? (
<button
onClick={() => handleArchiveMessage()}
className="p-1.5 hover:bg-primary/10 rounded-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
className="p-1.5 hover:bg-mu-primary/10 rounded-mu-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
title={t("common.archive")}
>
<CheckIcon className="w-4 h-4 text-muted-foreground hover:text-primary transition-colors" strokeWidth={2} />
<CheckIcon className="mu-icon text-mu-ink-muted hover:text-mu-primary transition-colors" />
</button>
) : (
<button
onClick={handleDeleteMessage}
className="p-1.5 hover:bg-destructive/10 rounded-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
className="p-1.5 hover:bg-mu-danger-soft rounded-mu-lg transition-all duration-150 opacity-0 group-hover:opacity-100"
title={t("common.delete")}
>
<TrashIcon className="w-4 h-4 text-muted-foreground hover:text-destructive transition-colors" strokeWidth={2} />
<TrashIcon className="mu-icon text-mu-ink-muted hover:text-mu-danger transition-colors" />
</button>
)}
</div>
</div>
<div className="flex flex-col gap-3 rounded-lg border border-border/60 bg-muted/20 p-3 sm:flex-row sm:items-center">
<div className="flex flex-col gap-3 rounded-mu-lg border border-mu-line/60 bg-mu-well/20 p-3 sm:flex-row sm:items-center">
<div className="flex min-w-0 flex-1 items-center gap-3">
<SpaceMark icon={space.icon} size="lg" />
<div className="min-w-0 flex-1">
<div className="flex min-w-0 flex-wrap items-center gap-1.5">
<span className="truncate text-sm font-medium text-foreground/95">{space.title}</span>
<span className="text-xs text-muted-foreground/70">{spaceUid}</span>
<span className="truncate mu-label text-mu-ink/95">{space.title}</span>
<span className="mu-caption text-mu-ink-muted/70">{spaceUid}</span>
<SpaceRoleBadge role={payload.role} />
</div>
<p className="line-clamp-1 text-xs text-muted-foreground/80">
<p className="line-clamp-1 mu-caption text-mu-ink-muted/80">
{isPending ? space.description || t("setting.spaces.invited-to-join") : t("inbox.space-invitation-accepted")}
</p>
</div>
</div>
{isPending ? (
<div className="flex shrink-0 items-center gap-1.5">
<Button variant="outline" size="sm" disabled={isBusy} onClick={() => void handleDecline()}>
<Button variant="neutral" size="sm" disabled={isBusy} onClick={() => void handleDecline()}>
{t("setting.spaces.decline")}
</Button>
<Button size="sm" disabled={isBusy} onClick={() => void handleAccept()}>
<Button variant="primary" size="sm" disabled={isBusy} onClick={() => void handleAccept()}>
{t("setting.spaces.accept")}
</Button>
</div>
+10 -10
View File
@@ -1,5 +1,5 @@
import { Tooltip } from "@usememos/ui";
import { ExternalLinkIcon } from "lucide-react";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useTranslate } from "@/utils/i18n";
interface Props {
@@ -13,16 +13,16 @@ const LearnMore: React.FC<Props> = (props: Props) => {
const t = useTranslate();
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger render={<a className={`text-muted-foreground hover:text-primary ${className}`} href={url} target="_blank" />}>
<ExternalLinkIcon className="w-4 h-auto" />
</TooltipTrigger>
<TooltipContent>
<Tooltip.Provider>
<Tooltip.Root>
<Tooltip.Trigger render={<a className={`text-mu-ink-muted hover:text-mu-accent ${className}`} href={url} target="_blank" />}>
<ExternalLinkIcon className="mu-icon" />
</Tooltip.Trigger>
<Tooltip.Popup>
<p>{title ?? t("common.learn-more")}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</Tooltip.Popup>
</Tooltip.Root>
</Tooltip.Provider>
);
};
+55 -95
View File
@@ -1,114 +1,74 @@
import { CheckIcon, ChevronDownIcon, GlobeIcon, SearchIcon } from "lucide-react";
import { useMemo, useState } from "react";
import { Combobox, Link } from "@usememos/ui";
import { GlobeIcon } from "lucide-react";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { locales } from "@/i18n";
import { cn } from "@/lib/utils";
import { getLocaleDisplayName, localeMatchesSearch, useTranslate } from "@/utils/i18n";
const MISSING_LANGUAGE_FEEDBACK_URL =
"https://github.com/usememos/memos/issues/new?title=Missing%20language%20support&body=Please%20add%20support%20for%20this%20language%3A%0A%0A-%20Language%3A%20";
interface LocaleSearchListProps {
value: Locale;
onChange: (locale: Locale) => void;
className?: string;
}
export const LocaleSearchList = (props: LocaleSearchListProps) => {
const { value, onChange, className } = props;
const t = useTranslate();
const { i18n } = useTranslation();
const [query, setQuery] = useState("");
const filteredLocales = useMemo(
() => locales.filter((locale) => localeMatchesSearch(locale, query, i18n.language)),
[i18n.language, query],
);
return (
<div
className={cn(
"flex max-h-[min(24rem,calc(100vh-2rem))] w-[var(--anchor-width)] min-w-48 max-w-[calc(100vw-2rem)] flex-col",
className,
)}
>
<div className="relative shrink-0 p-1">
<SearchIcon className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={query}
onChange={(event) => setQuery(event.target.value)}
onKeyDown={(event) => event.stopPropagation()}
className="pl-8"
placeholder={`${t("common.search")} ${t("common.language").toLowerCase()}`}
aria-label={t("common.language")}
/>
</div>
<div className="mt-1 min-h-0 flex-1 touch-pan-y overflow-y-auto p-1" role="listbox" aria-label={t("common.language")}>
{filteredLocales.map((locale) => (
<div
key={locale}
role="option"
aria-selected={value === locale}
className={cn(
"flex h-8 w-full cursor-pointer items-center gap-2 rounded-sm px-2 text-left text-sm outline-hidden transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
value === locale && "bg-accent/60",
)}
onClick={() => onChange(locale)}
>
<span className="flex min-w-0 flex-1 items-baseline gap-1.5">
<span className="truncate">{getLocaleDisplayName(locale)}</span>
<span className="shrink-0 text-xs text-muted-foreground">{locale}</span>
</span>
{value === locale ? <CheckIcon className="size-4 shrink-0 text-primary" /> : <span className="size-4 shrink-0" />}
</div>
))}
{filteredLocales.length === 0 && (
<div className="px-2 py-6 text-center text-sm">
<a
href={MISSING_LANGUAGE_FEEDBACK_URL}
target="_blank"
rel="noreferrer"
className="text-primary underline-offset-4 hover:underline"
>
{t("locale-picker.no-language-feedback")}
</a>
</div>
)}
</div>
</div>
);
};
interface LocalePickerProps {
value: Locale;
onChange: (locale: Locale) => void;
className?: string;
}
const LocalePicker = (props: LocalePickerProps) => {
const { value, onChange, className } = props;
const [open, setOpen] = useState(false);
// Each name builds an Intl.DisplayNames, so names are resolved once each, on first use, rather than per item per render.
const localeLabels = new Map<string, string>();
const localeLabel = (locale: string): string => {
let label = localeLabels.get(locale);
if (label === undefined) {
label = getLocaleDisplayName(locale);
localeLabels.set(locale, label);
}
return label;
};
const handleChange = (locale: Locale) => {
onChange(locale);
setOpen(false);
};
/**
* Picks the interface language from the long list of locales: a Combobox, so typing a
* language's name in English, in itself or in the interface language finds it. When nothing
* matches, the list offers a link to ask for the language.
*/
const LocalePicker = ({ value, onChange, className }: LocalePickerProps) => {
const t = useTranslate();
const { i18n } = useTranslation();
// A stable filter keeps the Combobox from re-filtering every locale on each render.
const filter = useCallback((locale: string, query: string) => localeMatchesSearch(locale, query, i18n.language), [i18n.language]);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger render={<Button type="button" variant="outline" className={cn("w-full justify-between", className)} />}>
<span className="flex min-w-0 flex-1 items-center gap-2">
<GlobeIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="truncate">{getLocaleDisplayName(value)}</span>
</span>
<ChevronDownIcon className="size-4 shrink-0 text-muted-foreground" />
</PopoverTrigger>
<PopoverContent align="start" className="p-0">
<LocaleSearchList value={value} onChange={handleChange} />
</PopoverContent>
</Popover>
<Combobox.Root
items={locales}
value={value}
onValueChange={(next) => next && onChange(next as Locale)}
itemToStringLabel={localeLabel}
filter={filter}
>
<Combobox.Input
icon={<GlobeIcon />}
aria-label={t("common.language")}
triggerLabel={t("common.language")}
placeholder={`${t("common.search")} ${t("common.language").toLowerCase()}`}
className={className}
/>
<Combobox.Popup>
<Combobox.Empty>
<Link href={MISSING_LANGUAGE_FEEDBACK_URL} target="_blank" rel="noreferrer">
{t("locale-picker.no-language-feedback")}
</Link>
</Combobox.Empty>
<Combobox.List>
{(locale: Locale) => (
<Combobox.Item key={locale} value={locale}>
<span className="flex min-w-0 flex-1 items-baseline gap-1.5">
<span className="truncate">{localeLabel(locale)}</span>
<span className="shrink-0 mu-caption text-mu-ink-muted">{locale}</span>
</span>
</Combobox.Item>
)}
</Combobox.List>
</Combobox.Popup>
</Combobox.Root>
);
};
+4 -4
View File
@@ -46,12 +46,12 @@ const createFaceIcon = (face: Exclude<MapPinFace, { kind: "dot" }>, selected: bo
const html = ReactDOMServer.renderToString(
<div
aria-hidden="true"
className={cn("grid place-items-center", selected && "bg-primary/20", face.kind === "photo" ? "rounded-[11px]" : "rounded-full")}
className={cn("grid place-items-center", selected && "bg-mu-primary/20", face.kind === "photo" ? "rounded-[11px]" : "rounded-full")}
style={{ width: box, height: box }}
>
{face.kind === "photo" ? (
<span
className={cn("block rounded-md bg-primary bg-cover bg-center", FACE_EDGE)}
className={cn("block rounded-mu-md bg-mu-primary bg-cover bg-center", FACE_EDGE)}
style={{ width: side, height: side, backgroundImage: `url(${JSON.stringify(face.url)})` }}
/>
) : (
@@ -180,7 +180,7 @@ function Markers({ memos, pins, selected, onSelect }: Pick<Props, "memos" | "pin
iconCreateFunction={(cluster: { getChildCount(): number; getAllChildMarkers(): L.Marker[] }) => {
const active = cluster.getAllChildMarkers().some((marker) => selection.has(names.current.get(marker) ?? ""));
return L.divIcon({
html: `<span class="grid size-7 place-items-center rounded-full border-[1.5px] border-background bg-primary text-primary-foreground text-xs font-medium tabular-nums shadow-[0_1px_3px_rgba(15,23,42,0.35)]${active ? " outline-[4px] outline-primary/20" : ""}">${cluster.getChildCount()}</span>`,
html: `<span class="grid size-7 place-items-center rounded-full border-[1.5px] border-mu-canvas bg-mu-primary text-mu-on-primary mu-label-sm tabular-nums shadow-[0_1px_3px_rgba(15,23,42,0.35)]${active ? " outline-[4px] outline-mu-primary/20" : ""}">${cluster.getChildCount()}</span>`,
className: "",
iconSize: [28, 28],
});
@@ -229,7 +229,7 @@ export function MapCanvas(props: Props) {
minZoom={0}
zoomControl={false}
attributionControl={false}
className="map-attribution-minimal absolute! inset-0 z-0 !bg-muted"
className="map-attribution-minimal absolute! inset-0 z-0 !bg-mu-well"
>
<BasemapLayer onTileError={props.onTileError} />
<MinimalAttributionControl />
+29 -37
View File
@@ -1,17 +1,17 @@
import { create } from "@bufbuild/protobuf";
import { Button, buttonClasses } from "@usememos/ui";
import type L from "leaflet";
import { CrosshairIcon, MinusIcon, PlusIcon } from "lucide-react";
import { type CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "react-hot-toast";
import { useLocation, useNavigate } from "react-router-dom";
import { getLocationCoordinatesText } from "@/components/MemoMetadata/Location/locationHelpers";
import { MEMO_PANEL_INSET, MEMO_PANEL_WIDTH_CSS, MemoPanel, MemoPanelList, type MemoPanelSize } from "@/components/MemoPanel";
import { createMemoNavigationState } from "@/components/MemoView/navigation";
import { Button, buttonVariants } from "@/components/ui/button";
import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import useMediaQuery from "@/hooks/useMediaQuery";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { LocationSchema } from "@/types/proto/api/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -133,25 +133,20 @@ export function MapView() {
const result = await query.refetch();
if (result.data?.pages.some((page) => page.memos.some((memo) => memo.name === name && memo.location))) {
updateQuery((search) => search.set("memo", name));
} else
toast(
(toastState) => (
<span>
{t(result.isError ? "map.load-error" : "map.saved-outside-filter")}{" "}
<button
type="button"
className="underline"
onClick={() => {
toast.dismiss(toastState.id);
navigate(`/${name}`, { state: createMemoNavigationState(`${location.pathname}${location.search}`) });
}}
>
{t("map.open-memo")}
</button>
</span>
),
{ duration: 8000 },
);
} else {
const id = toast.add({
title: t(result.isError ? "map.load-error" : "map.saved-outside-filter"),
type: result.isError ? "danger" : undefined,
timeout: 8000,
actionProps: {
children: t("map.open-memo"),
onClick: () => {
toast.close(id);
navigate(`/${name}`, { state: createMemoNavigationState(`${location.pathname}${location.search}`) });
},
},
});
}
};
const heading = !singlePoint
? { title: t("map.selection") }
@@ -159,9 +154,9 @@ export function MapView() {
? splitLabel(sharedLabel)
: { title: getLocationCoordinatesText(singlePoint) };
// Floating surfaces let the basemap show through, the way Notion's and Linear's overlays do.
const surfaceClass = "rounded-lg border border-border/60 bg-background/85 shadow-xs backdrop-blur-md";
const surfaceClass = "rounded-mu-lg border border-mu-line/60 bg-mu-canvas/85 backdrop-blur-md";
// The calendar's 28px quiet square, a touch more on phones.
const toolClass = cn(buttonVariants({ variant: "quiet", size: "icon-compact" }), "size-8 md:size-7");
const toolClass = cn(buttonClasses({ variant: "ghost", size: "sm", iconOnly: true }), "size-8 md:size-7");
return (
<section
@@ -190,14 +185,11 @@ export function MapView() {
onReady={onReady}
onTileError={() => setTileError(true)}
/>
<h1 className="sr-only">{t("common.map")}</h1>
<h1 className="mu-visually-hidden">{t("common.map")}</h1>
{!query.complete && !query.isError && (
<p
role="status"
className={cn(
"absolute start-3 top-3 z-10 flex h-7 items-center px-2.5 text-xs text-muted-foreground tabular-nums",
surfaceClass,
)}
className={cn("absolute start-3 top-3 z-10 flex h-7 items-center px-2.5 mu-caption text-mu-ink-muted tabular-nums", surfaceClass)}
>
{t("map.loaded", { count: query.memos.length })}
</p>
@@ -218,7 +210,7 @@ export function MapView() {
title={t("map.zoom-in")}
onClick={() => mapRef.current?.zoomIn()}
>
<PlusIcon strokeWidth={1.75} />
<PlusIcon className="mu-icon" />
</button>
<button
type="button"
@@ -227,9 +219,9 @@ export function MapView() {
title={t("map.zoom-out")}
onClick={() => mapRef.current?.zoomOut()}
>
<MinusIcon strokeWidth={1.75} />
<MinusIcon className="mu-icon" />
</button>
<span aria-hidden="true" className="my-1 h-px w-4 bg-border/70" />
<span aria-hidden="true" className="my-1 h-px w-4 bg-mu-line/70" />
</>
)}
<button
@@ -242,13 +234,13 @@ export function MapView() {
if (mapRef.current) fitMemos(mapRef.current, query.memos);
}}
>
<CrosshairIcon strokeWidth={1.75} />
<CrosshairIcon className="mu-icon" />
</button>
</div>
)}
<div className="pointer-events-none absolute inset-x-3 bottom-8 z-10 flex flex-col items-center gap-2">
{query.isError && (
<p role="alert" className={cn("pointer-events-auto px-4 py-2 text-sm", surfaceClass)}>
<p role="alert" className={cn("pointer-events-auto px-4 py-2 mu-body", surfaceClass)}>
{t("map.load-error")}{" "}
<button type="button" className="ms-2 underline" onClick={() => void query.retry()}>
{t("search.retry")}
@@ -256,7 +248,7 @@ export function MapView() {
</p>
)}
{tileError && (
<p role="alert" className={cn("pointer-events-auto px-4 py-2 text-sm", surfaceClass)}>
<p role="alert" className={cn("pointer-events-auto px-4 py-2 mu-body", surfaceClass)}>
{t("map.tile-error")}{" "}
<button
type="button"
@@ -275,14 +267,14 @@ export function MapView() {
</div>
{query.complete && query.memos.length === 0 && !open && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center p-8">
<div className={cn("pointer-events-auto max-w-sm rounded-xl p-5 text-center", surfaceClass)}>
<div className={cn("pointer-events-auto max-w-sm rounded-mu-xl p-5 text-center", surfaceClass)}>
<h2 className="font-medium">{t(filters.length ? "map.no-results" : "map.empty")}</h2>
{/* Guests cannot add a location, so only filters get a hint for them. */}
{(filters.length > 0 || user) && (
<p className="mt-2 text-sm text-muted-foreground">{t(filters.length ? "map.no-results-hint" : "map.empty-hint")}</p>
<p className="mt-2 mu-body text-mu-ink-muted">{t(filters.length ? "map.no-results-hint" : "map.empty-hint")}</p>
)}
{filters.length > 0 && (
<Button className="mt-4" variant="outline" onClick={() => removeFilter(() => true)}>
<Button className="mt-4" variant="neutral" onClick={() => removeFilter(() => true)}>
{t("map.clear-filters")}
</Button>
)}
+35 -50
View File
@@ -1,3 +1,4 @@
import { Button } from "@usememos/ui";
import {
ApertureIcon,
CalendarArrowUpIcon,
@@ -17,7 +18,6 @@ import {
} from "lucide-react";
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { LazyLocationPicker } from "@/components/map/LazyLocationPicker";
import { Button } from "@/components/ui/button";
import i18n from "@/i18n";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
@@ -41,11 +41,11 @@ interface MediaMetadataDetailsProps {
const DetailRow = ({ icon: Icon, label, value, secondary, action }: DetailRowProps) => (
<div className="grid grid-cols-[1rem_minmax(0,1fr)_auto] gap-x-2.5 py-2.5">
<Icon className="mt-0.5 size-3.5 text-white/38" strokeWidth={1.75} aria-hidden="true" />
<Icon className="mu-icon-sm mt-0.5 text-mu-ink-muted" aria-hidden="true" />
<div className="min-w-0">
<div className="text-[11px] font-medium leading-4 text-white/45">{label}</div>
<div className="mt-0.5 break-words text-[13px] leading-5 text-white/88 tabular-nums">{value}</div>
{secondary && <div className="mt-0.5 text-[11px] leading-4 text-white/48">{secondary}</div>}
<div className="mu-label-sm text-mu-ink-muted">{label}</div>
<div className="mt-0.5 break-words mu-caption text-mu-ink tabular-nums">{value}</div>
{secondary && <div className="mt-0.5 mu-caption text-mu-ink-muted">{secondary}</div>}
</div>
{action && <div className="self-center">{action}</div>}
</div>
@@ -53,25 +53,11 @@ const DetailRow = ({ icon: Icon, label, value, secondary, action }: DetailRowPro
const DetailSection = ({ title, children }: { title: string; children: ReactNode }) => (
<section>
<h3 className="mb-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/32">{title}</h3>
<div className="divide-y divide-white/[0.07]">{children}</div>
<h3 className="mb-0.5 mu-label-sm text-mu-ink-muted">{title}</h3>
<div className="divide-y divide-mu-line">{children}</div>
</section>
);
const IconAction = ({ label, onClick, children }: { label: string; onClick: () => void; children: ReactNode }) => (
<Button
type="button"
variant="ghost"
size="icon"
title={label}
aria-label={label}
onClick={onClick}
className="inline-flex size-7 items-center justify-center rounded-full text-white/48 transition-colors hover:bg-white/[0.08] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/45"
>
{children}
</Button>
);
const MediaMetadataDetails = ({ id, item, onClose, className }: MediaMetadataDetailsProps) => {
const t = useTranslate();
const [showMap, setShowMap] = useState(false);
@@ -79,6 +65,9 @@ const MediaMetadataDetails = ({ id, item, onClose, className }: MediaMetadataDet
const copyResetTimer = useRef<number | undefined>(undefined);
const locale = i18n.language;
const details = useMemo(() => buildMediaMetadataDisplay(item.attachments, locale), [item.attachments, locale]);
const copyCoordinatesLabel = coordinatesCopied
? t("attachment-details.actions.copied")
: t("attachment-details.actions.copy-coordinates");
useEffect(() => {
setShowMap(false);
@@ -115,28 +104,29 @@ const MediaMetadataDetails = ({ id, item, onClose, className }: MediaMetadataDet
const hasCameraDetails = Boolean(details.camera || details.lens || details.exposure);
return (
// The panel sits over the photo, so it is a dark-theme scope and draws with the dark tokens whatever the app's theme.
<aside
id={id}
aria-label={t("attachment-details.title")}
data-theme="dark"
className={cn(
"absolute inset-x-0 bottom-0 z-40 flex max-h-[72vh] flex-col overflow-hidden rounded-t-2xl border-t border-white/10 bg-neutral-950/96 text-white shadow-2xl backdrop-blur-xl lg:inset-y-0 lg:left-auto lg:w-[22rem] lg:max-h-none lg:rounded-none lg:border-l lg:border-t-0 lg:bg-black/82",
"absolute inset-x-0 bottom-0 z-40 flex max-h-[72vh] flex-col overflow-hidden rounded-t-mu-2xl border-t border-mu-line bg-mu-surface/96 text-mu-ink shadow-mu-pop backdrop-blur-xl lg:inset-y-0 lg:left-auto lg:w-[22rem] lg:max-h-none lg:rounded-none lg:border-l lg:border-t-0 lg:bg-mu-surface/85",
className,
)}
>
<div className="mx-auto mt-2 h-1 w-8 rounded-full bg-white/18 lg:hidden" aria-hidden="true" />
<header className="flex shrink-0 items-center justify-between gap-3 border-b border-white/[0.08] px-4 pb-3 pt-3 lg:pt-20">
<div className="mx-auto mt-2 h-1 w-8 rounded-full bg-mu-ink-muted/40 lg:hidden" aria-hidden="true" />
<header className="flex shrink-0 items-center justify-between gap-3 border-b border-mu-line px-4 pb-3 pt-3 lg:pt-20">
<div>
<h2 className="text-sm font-medium text-white/92">{t("attachment-details.title")}</h2>
<p className="mt-0.5 max-w-[16rem] truncate text-xs text-white/42">{item.filename}</p>
<h2 className="mu-label text-mu-ink">{t("attachment-details.title")}</h2>
<p className="mt-0.5 max-w-[16rem] truncate mu-caption text-mu-ink-muted">{item.filename}</p>
</div>
<button
type="button"
<Button
variant="ghost"
onClick={onClose}
className="inline-flex size-8 items-center justify-center rounded-full text-white/55 hover:bg-white/[0.08] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/45 lg:hidden"
className="lg:hidden"
aria-label={t("attachment-details.actions.hide")}
>
<XIcon className="size-4" aria-hidden="true" />
</button>
icon={<XIcon />}
/>
</header>
<div className="overflow-y-auto px-4 pb-[max(1rem,env(safe-area-inset-bottom))] pt-4">
@@ -191,25 +181,22 @@ const MediaMetadataDetails = ({ id, item, onClose, className }: MediaMetadataDet
details.location.altitude ? `${t("attachment-details.fields.altitude")} · ${details.location.altitude}` : undefined
}
action={
<IconAction
label={coordinatesCopied ? t("attachment-details.actions.copied") : t("attachment-details.actions.copy-coordinates")}
<Button
variant="ghost"
size="sm"
title={copyCoordinatesLabel}
aria-label={copyCoordinatesLabel}
icon={coordinatesCopied ? <CheckIcon className="mu-icon-sm" /> : <CopyIcon className="mu-icon-sm" />}
onClick={() => void copyCoordinates()}
>
{coordinatesCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
</IconAction>
/>
}
/>
<button
type="button"
onClick={() => setShowMap((visible) => !visible)}
className="mt-2 inline-flex h-8 items-center gap-1.5 rounded-full border border-white/10 px-3 text-xs text-white/62 transition-colors hover:border-white/18 hover:bg-white/[0.06] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/45"
>
<MapIcon className="size-3.5" strokeWidth={1.75} aria-hidden="true" />
<Button variant="neutral" size="sm" className="mt-2" onClick={() => setShowMap((visible) => !visible)} icon={<MapIcon />}>
{showMap ? t("attachment-details.actions.hide-map") : t("attachment-details.actions.show-map")}
</button>
</Button>
{showMap && (
<LazyLocationPicker
className="mt-3 h-44 rounded-xl border-white/10"
className="mt-3 h-44 rounded-mu-xl border-mu-line"
latlng={{ lat: details.location.latitude, lng: details.location.longitude }}
readonly
/>
@@ -218,14 +205,12 @@ const MediaMetadataDetails = ({ id, item, onClose, className }: MediaMetadataDet
)}
{!details.hasSavedMetadata && (
<p className="rounded-xl border border-white/[0.07] px-3 py-2.5 text-xs leading-5 text-white/42">
{t("attachment-details.empty")}
</p>
<p className="rounded-mu-xl border border-mu-line px-3 py-2.5 mu-caption text-mu-ink-muted">{t("attachment-details.empty")}</p>
)}
{details.sourceExifOrientation !== undefined && (
<details className="group border-t border-white/[0.08] pt-3">
<summary className="cursor-pointer select-none text-[11px] font-medium text-white/42 hover:text-white/65">
<details className="group border-t border-mu-line pt-3">
<summary className="cursor-pointer select-none mu-label-sm text-mu-ink-muted hover:text-mu-ink">
{t("attachment-details.sections.technical")}
</summary>
<div className="mt-2">
@@ -1,3 +1,5 @@
import { Menu as MenuPrimitive } from "@base-ui/react/menu";
import { Button, Menu, menuClasses, Tooltip } from "@usememos/ui";
import {
ArchiveIcon,
ArchiveRestoreIcon,
@@ -16,18 +18,6 @@ import {
import { useState } from "react";
import { Link } from "react-router-dom";
import ConfirmDialog from "@/components/ConfirmDialog";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLinkItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { State } from "@/types/proto/api/common_pb";
import { useTranslate } from "@/utils/i18n";
import { createMemoNavigationState } from "../MemoView/navigation";
@@ -41,6 +31,9 @@ import type { MemoActionMenuProps } from "./types";
* A memo's Space is changed in the editor, not here. An archived memo offers
* only Restore and Delete, and a viewer only Open and Copy.
*/
/** The open link is a real link, so its row takes the package's menu row classes. */
const MENU_ROW_CLASSES = menuClasses({ size: "sm" });
const MemoActionMenu = (props: MemoActionMenuProps) => {
const { memo, parentPage, readonly } = props;
const t = useTranslate();
@@ -75,41 +68,36 @@ const MemoActionMenu = (props: MemoActionMenuProps) => {
// A comment opens in the context of its parent memo, never on its own.
const openItem = !isComment && !isInMemoDetailPage && (
<DropdownMenuLinkItem
<MenuPrimitive.LinkItem
closeOnClick
className={MENU_ROW_CLASSES.item}
render={
<Link to={`/${memo.name}`} state={parentPage !== undefined ? createMemoNavigationState(parentPage) : undefined} viewTransition />
}
>
<ArrowUpRightIcon />
{t("common.open")}
</DropdownMenuLinkItem>
<ArrowUpRightIcon className="mu-icon" />
<span className={MENU_ROW_CLASSES.label}>{t("common.open")}</span>
</MenuPrimitive.LinkItem>
);
const copySubmenu = (
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<CopyIcon />
{t("common.copy")}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<DropdownMenuItem onClick={handleCopyLink}>
<LinkIcon />
<Menu.SubmenuRoot>
<Menu.SubmenuTrigger icon={<CopyIcon />}>{t("common.copy")}</Menu.SubmenuTrigger>
<Menu.Popup>
<Menu.Item onClick={handleCopyLink} icon={<LinkIcon />}>
{t("memo.copy-link")}
</DropdownMenuItem>
<DropdownMenuItem onClick={handleCopyContent}>
<FileTextIcon />
</Menu.Item>
<Menu.Item onClick={handleCopyContent} icon={<FileTextIcon />}>
{t("memo.copy-content")}
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
</Menu.Item>
</Menu.Popup>
</Menu.SubmenuRoot>
);
const deleteItem = (
<DropdownMenuItem variant="destructive" onClick={handleDeleteMemoClick}>
<TrashIcon />
<Menu.Item onClick={handleDeleteMemoClick} icon={<TrashIcon />} danger>
{t("common.delete")}
</DropdownMenuItem>
</Menu.Item>
);
const renderItems = () => {
@@ -125,11 +113,10 @@ const MemoActionMenu = (props: MemoActionMenuProps) => {
if (isArchived) {
return (
<>
<DropdownMenuItem onClick={handleToggleMemoStatusClick}>
<ArchiveRestoreIcon />
<Menu.Item onClick={handleToggleMemoStatusClick} icon={<ArchiveRestoreIcon />}>
{t("common.restore")}
</DropdownMenuItem>
<DropdownMenuSeparator />
</Menu.Item>
<Menu.Separator />
{deleteItem}
</>
);
@@ -137,57 +124,53 @@ const MemoActionMenu = (props: MemoActionMenuProps) => {
return (
<>
<DropdownMenuItem onClick={handleEditMemoClick}>
<Edit3Icon />
<Menu.Item onClick={handleEditMemoClick} icon={<Edit3Icon />}>
{t("common.edit")}
</DropdownMenuItem>
</Menu.Item>
{/* One task action at a time: finish the open tasks, or reset a finished list. */}
{hasTaskList &&
(hasOpenTasks ? (
<DropdownMenuItem onClick={handleCheckAllTaskListItemsClick}>
<CheckCheckIcon />
<Menu.Item onClick={handleCheckAllTaskListItemsClick} icon={<CheckCheckIcon />}>
{t("memo.task-actions.check-all")}
</DropdownMenuItem>
</Menu.Item>
) : (
<DropdownMenuItem onClick={handleUncheckAllTaskListItemsClick}>
<ListRestartIcon />
<Menu.Item onClick={handleUncheckAllTaskListItemsClick} icon={<ListRestartIcon />}>
{t("memo.task-actions.uncheck-all")}
</DropdownMenuItem>
</Menu.Item>
))}
{/* A comment has no place of its own to pin or archive; it lives under its parent. */}
{!isComment && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleTogglePinMemoBtnClick}>
{memo.pinned ? <BookmarkMinusIcon /> : <BookmarkPlusIcon />}
<Menu.Separator />
<Menu.Item onClick={handleTogglePinMemoBtnClick} icon={memo.pinned ? <BookmarkMinusIcon /> : <BookmarkPlusIcon />}>
{memo.pinned ? t("common.unpin") : t("common.pin")}
</DropdownMenuItem>
<DropdownMenuItem onClick={handleToggleMemoStatusClick}>
<ArchiveIcon />
</Menu.Item>
<Menu.Item onClick={handleToggleMemoStatusClick} icon={<ArchiveIcon />}>
{t("common.archive")}
</DropdownMenuItem>
</Menu.Item>
</>
)}
<DropdownMenuSeparator />
<Menu.Separator />
{openItem}
{copySubmenu}
<DropdownMenuSeparator />
<Menu.Separator />
{deleteItem}
</>
);
};
return (
<DropdownMenu>
<DropdownMenuTrigger render={<Button variant="quiet" size="icon-sm" aria-label={t("common.more")} />}>
<MoreVerticalIcon className="size-4" strokeWidth={1.8} />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={2} size="sm">
{renderItems()}
</DropdownMenuContent>
<Menu.Root modal={false} size="sm">
<Tooltip.Root>
<Tooltip.Trigger
render={<Menu.Trigger render={<Button variant="ghost" size="sm" aria-label={t("common.more")} icon={<MoreVerticalIcon />} />} />}
/>
<Tooltip.Popup>{t("common.more")}</Tooltip.Popup>
</Tooltip.Root>
<Menu.Popup align="end">{renderItems()}</Menu.Popup>
{/* Delete confirmation dialog */}
<ConfirmDialog
@@ -198,9 +181,9 @@ const MemoActionMenu = (props: MemoActionMenuProps) => {
description={t("memo.delete-confirm-description")}
cancelLabel={t("common.cancel")}
onConfirm={confirmDeleteMemo}
confirmVariant="destructive"
confirmVariant="danger"
/>
</DropdownMenu>
</Menu.Root>
);
};
@@ -1,8 +1,7 @@
import { DownloadIcon, ImageIcon, Loader2Icon, Share2Icon } from "lucide-react";
import { useCallback, useMemo, useRef, useState } from "react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button, Dialog } from "@usememos/ui";
import { DownloadIcon, Share2Icon } from "lucide-react";
import { type CSSProperties, useCallback, useMemo, useRef, useState } from "react";
import { showErrorToast, toast } from "@/lib/toast";
import { useTranslate } from "@/utils/i18n";
import { useMemoViewContext } from "../MemoView/MemoViewContext";
import MemoShareImagePreview from "./MemoShareImagePreview";
@@ -48,9 +47,9 @@ const MemoShareImageDialog = ({ open, onOpenChange }: MemoShareImageDialogProps)
anchor.download = buildMemoShareImageFileName(memo.name);
anchor.click();
URL.revokeObjectURL(url);
toast.success(t("memo.share.image-downloaded"));
toast.add({ title: t("memo.share.image-downloaded"), type: "success" });
} catch {
toast.error(t("memo.share.image-download-failed"));
showErrorToast(t("memo.share.image-download-failed"));
} finally {
setIsRendering(false);
}
@@ -66,7 +65,7 @@ const MemoShareImageDialog = ({ open, onOpenChange }: MemoShareImageDialogProps)
const blob = await createShareBlob();
const file = new File([blob], buildMemoShareImageFileName(memo.name), { type: "image/png" });
if (typeof navigator.canShare === "function" && !navigator.canShare({ files: [file] })) {
toast.error(t("memo.share.image-share-failed"));
showErrorToast(t("memo.share.image-share-failed"));
return;
}
@@ -76,7 +75,7 @@ const MemoShareImageDialog = ({ open, onOpenChange }: MemoShareImageDialogProps)
});
} catch (error) {
if (!(error instanceof DOMException && error.name === "AbortError")) {
toast.error(t("memo.share.image-share-failed"));
showErrorToast(t("memo.share.image-share-failed"));
}
} finally {
setIsRendering(false);
@@ -87,40 +86,43 @@ const MemoShareImageDialog = ({ open, onOpenChange }: MemoShareImageDialogProps)
typeof navigator !== "undefined" && typeof navigator.share === "function" && typeof navigator.canShare === "function";
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
size="full"
className="min-h-0 overflow-hidden !gap-0 !p-0 md:w-auto md:max-w-none"
style={{ width: `${dialogWidth}px` }}
<Dialog.Root open={open} onOpenChange={onOpenChange}>
<Dialog.Popup
// The panel is as wide as the image it previews, so the width is the dialog's own.
style={{ "--mu-dialog-width": `${dialogWidth}px` } as CSSProperties}
closeLabel={t("common.close")}
>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
<DialogHeader className="shrink-0 border-b border-border/60 px-4 py-3 sm:px-5">
<DialogTitle className="flex items-center gap-2 text-base font-medium">
<ImageIcon className="h-4 w-4 text-muted-foreground" />
{t("memo.share.image-title")}
</DialogTitle>
<DialogDescription className="text-xs">{t("memo.share.image-description", { width: previewRenderWidth })}</DialogDescription>
</DialogHeader>
<Dialog.Title>{t("memo.share.image-title")}</Dialog.Title>
<Dialog.Description>{t("memo.share.image-description", { width: previewRenderWidth })}</Dialog.Description>
<div className="relative flex min-h-0 flex-1 items-start justify-center overflow-auto bg-muted/20 px-4 py-3 sm:px-5 sm:py-4">
<MemoShareImagePreview ref={previewRef} width={previewRenderWidth} />
</div>
<DialogFooter className="shrink-0 border-t border-border/60 px-4 py-3 sm:px-5">
{supportsNativeShare && (
<Button variant="quiet" onClick={handleNativeShare} disabled={isRendering}>
{isRendering ? <Loader2Icon className="mr-2 h-4 w-4 animate-spin" /> : <Share2Icon className="mr-2 h-4 w-4" />}
{t("memo.share.image-share")}
</Button>
)}
<Button variant="outline" onClick={handleDownload} disabled={isRendering}>
{isRendering ? <Loader2Icon className="mr-2 h-4 w-4 animate-spin" /> : <DownloadIcon className="mr-2 h-4 w-4" />}
{t("memo.share.image-download")}
</Button>
</DialogFooter>
<div className="flex justify-center overflow-x-auto">
<MemoShareImagePreview ref={previewRef} width={previewRenderWidth} />
</div>
</DialogContent>
</Dialog>
<Dialog.Footer>
{supportsNativeShare && (
<Button
variant="ghost"
onClick={handleNativeShare}
loading={isRendering}
loadingLabel={t("memo.share.image-share")}
icon={<Share2Icon />}
>
{t("memo.share.image-share")}
</Button>
)}
<Button
variant="neutral"
onClick={handleDownload}
loading={isRendering}
loadingLabel={t("memo.share.image-download")}
icon={<DownloadIcon />}
>
{t("memo.share.image-download")}
</Button>
</Dialog.Footer>
</Dialog.Popup>
</Dialog.Root>
);
};
@@ -25,14 +25,14 @@ const MemoShareImagePreview = forwardRef<HTMLDivElement, { width: number }>(({ w
);
return (
<div ref={ref} className="overflow-hidden rounded-xl border border-border/50 bg-background p-2 sm:p-2.5" style={{ width }}>
<div className="overflow-hidden rounded-lg border border-border/60 bg-background p-4 sm:p-5">
<div ref={ref} className="overflow-hidden rounded-mu-xl border border-mu-line/50 bg-mu-canvas p-2 sm:p-2.5" style={{ width }}>
<div className="overflow-hidden rounded-mu-lg border border-mu-line/60 bg-mu-canvas p-4 sm:p-5">
<div className="flex items-start gap-3">
<div className="flex min-w-0 items-center gap-2.5">
<UserAvatar avatarUrl={preview.avatarUrl} name={preview.displayName} className="h-8 w-8" />
<div className="min-w-0">
<div className="truncate text-[13px] font-semibold text-foreground">{preview.displayName}</div>
{preview.formattedDisplayTime && <div className="truncate text-xs text-muted-foreground">{preview.formattedDisplayTime}</div>}
<div className="truncate mu-label-sm text-mu-ink">{preview.displayName}</div>
{preview.formattedDisplayTime && <div className="truncate mu-caption text-mu-ink-muted">{preview.formattedDisplayTime}</div>}
</div>
</div>
</div>
@@ -43,7 +43,7 @@ const MemoShareImagePreview = forwardRef<HTMLDivElement, { width: number }>(({ w
content={memo.content}
attachments={memo.attachments}
compact={false}
contentClassName="text-[14px] leading-6.5 sm:text-[15px]"
contentClassName="mu-body leading-6.5 sm:text-[15px]"
/>
</div>
</div>
@@ -54,14 +54,14 @@ const MemoShareImagePreview = forwardRef<HTMLDivElement, { width: number }>(({ w
<div
key={item.id}
className={cn(
"relative overflow-hidden rounded-md border border-border/70 bg-muted/30",
"relative overflow-hidden rounded-mu-md border border-mu-line/70 bg-mu-well/30",
preview.visualItems.length === 1 ? "aspect-[4/3]" : "aspect-square",
preview.visualItems.length === 3 && index === 0 && "col-span-2 aspect-[2.2/1]",
)}
>
<img src={item.posterUrl} alt={item.filename} className="h-full w-full object-cover" loading="eager" decoding="async" />
{index === 3 && preview.visualItems.length > 4 && (
<div className="absolute inset-0 flex items-center justify-center bg-foreground/35 text-lg font-semibold text-background">
<div className="absolute inset-0 flex items-center justify-center bg-mu-ink/35 mu-title text-mu-canvas">
+{preview.visualItems.length - 4}
</div>
)}
@@ -75,7 +75,7 @@ const MemoShareImagePreview = forwardRef<HTMLDivElement, { width: number }>(({ w
{preview.footerBadges.map((badge) => (
<span
key={badge.type}
className="inline-flex rounded-full border border-border/70 bg-muted/55 px-2 py-0.5 text-[11px] text-muted-foreground"
className="inline-flex rounded-full border border-mu-line/70 bg-mu-well/55 px-2 py-0.5 mu-caption text-mu-ink-muted"
>
{badge.count} {t("common.attachments").toLowerCase()}
</span>
+11 -11
View File
@@ -1,7 +1,6 @@
import { useQueryClient } from "@tanstack/react-query";
import copy from "copy-to-clipboard";
import { useCallback } from "react";
import toast from "react-hot-toast";
import { useLocation } from "react-router-dom";
import { useInstance } from "@/contexts/InstanceContext";
import { memoKeys, useDeleteMemo, useUpdateMemo } from "@/hooks/useMemoQueries";
@@ -9,6 +8,7 @@ import useNavigateTo from "@/hooks/useNavigateTo";
import { userKeys } from "@/hooks/useUserQueries";
import { handleError } from "@/lib/error";
import { extractMemoIdFromName } from "@/lib/resource-names";
import { showErrorToast, toast } from "@/lib/toast";
import { ROUTES } from "@/router/routes";
import { State } from "@/types/proto/api/common_pb";
import type { Memo } from "@/types/proto/api/memo_service_pb";
@@ -52,11 +52,11 @@ export const useMemoActionHandlers = ({ memo, parentPage, onEdit, setDeleteDialo
},
updateMask: ["content", "update_time"],
});
toast.success(t("memo.task-actions.updated"));
toast.add({ title: t("memo.task-actions.updated"), type: "success" });
} catch (error: unknown) {
handleError(error, toast.error, {
handleError(error, showErrorToast, {
context,
fallbackMessage: "An error occurred",
fallbackMessage: t("common.error-occurred"),
});
}
},
@@ -94,11 +94,11 @@ export const useMemoActionHandlers = ({ memo, parentPage, onEdit, setDeleteDialo
},
updateMask: ["state"],
});
toast.success(message);
toast.add({ title: message, type: "success" });
} catch (error: unknown) {
handleError(error, toast.error, {
handleError(error, showErrorToast, {
context: `${isArchiving ? "Archive" : "Restore"} memo`,
fallbackMessage: "An error occurred",
fallbackMessage: t("common.error-occurred"),
});
return;
}
@@ -117,12 +117,12 @@ export const useMemoActionHandlers = ({ memo, parentPage, onEdit, setDeleteDialo
// A comment's link lands on the comment inside its parent memo, as the comment previews do.
const path = memo.parent ? `${memo.parent}#${extractMemoIdFromName(memo.name)}` : memo.name;
copy(`${host}/${path}`);
toast.success(t("message.succeed-copy-link"));
toast.add({ title: t("message.succeed-copy-link"), type: "success" });
}, [memo.name, memo.parent, t, profile.instanceUrl]);
const handleCopyContent = useCallback(() => {
copy(memo.content);
toast.success(t("message.succeed-copy-content"));
toast.add({ title: t("message.succeed-copy-content"), type: "success" });
}, [memo.content, t]);
const handleCheckAllTaskListItemsClick = useCallback(async () => {
@@ -141,10 +141,10 @@ export const useMemoActionHandlers = ({ memo, parentPage, onEdit, setDeleteDialo
try {
await deleteMemo(memo.name);
} catch (error: unknown) {
handleError(error, toast.error, { context: "Delete memo", fallbackMessage: "An error occurred" });
handleError(error, showErrorToast, { context: "Delete memo", fallbackMessage: t("common.error-occurred") });
return;
}
toast.success(t("message.deleted-successfully"));
toast.add({ title: t("message.deleted-successfully"), type: "success" });
if (memo.parent) {
queryClient.invalidateQueries({ queryKey: memoKeys.comments(memo.parent) });
queryClient.invalidateQueries({ queryKey: memoKeys.detail(memo.parent) });
+22 -18
View File
@@ -1,8 +1,8 @@
import { LoaderCircleIcon, MessageCircleIcon } from "lucide-react";
import { Button } from "@usememos/ui";
import { MessageCircleIcon } from "lucide-react";
import { forwardRef, useCallback, useImperativeHandle, useRef, useState } from "react";
import { MemoEditor, preloadMemoEditing } from "@/components/MemoEditor";
import MemoView from "@/components/MemoView";
import { Button } from "@/components/ui/button";
import useCurrentUser from "@/hooks/useCurrentUser";
import { MEMO_COMMENTS_ANCHOR_ID } from "@/lib/memo-comments";
import { extractMemoIdFromName } from "@/lib/resource-names";
@@ -67,34 +67,34 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
return (
<div ref={sectionRef} className="pt-8 pb-16 w-full" data-memo-comments-section>
<h2 id={MEMO_COMMENTS_ANCHOR_ID} className="sr-only">
<h2 id={MEMO_COMMENTS_ANCHOR_ID} className="mu-visually-hidden">
{t("memo.comment.self")}
</h2>
<div className="relative mx-auto grow w-full min-h-full flex flex-col justify-start items-start gap-y-1">
{comments.length === 0 ? (
showCreateButton && (
<div className="w-full flex flex-row justify-center items-center py-6">
<Button variant="ghost" onPointerEnter={preloadEditor} onFocus={preloadEditor} onClick={openEditor}>
<span className="text-muted-foreground">{t("memo.comment.write-a-comment")}</span>
<MessageCircleIcon className="ml-2 w-5 h-auto text-muted-foreground" />
<Button
variant="ghost"
iconEnd={<MessageCircleIcon />}
onPointerEnter={preloadEditor}
onFocus={preloadEditor}
onClick={openEditor}
>
{t("memo.comment.write-a-comment")}
</Button>
</div>
)
) : (
<div className="w-full flex flex-row justify-between items-center h-8 pl-3 mb-2">
<div className="flex flex-row justify-start items-center">
<MessageCircleIcon className="w-5 h-auto text-muted-foreground mr-1" />
<span className="text-muted-foreground text-sm">{t("memo.comment.self")}</span>
<span className="text-muted-foreground text-sm ml-1">({commentCount})</span>
<MessageCircleIcon className="mu-icon w-5 h-auto text-mu-ink-muted mr-1" />
<span className="text-mu-ink-muted mu-body">{t("memo.comment.self")}</span>
{/* The count sits beside the label as a plain number, as it does on a card's comment strip and in the sidebar. */}
<span className="text-mu-ink-muted mu-caption tabular-nums ml-1.5">{commentCount}</span>
</div>
{showCreateButton && (
<Button
variant="ghost"
className="text-muted-foreground"
onPointerEnter={preloadEditor}
onFocus={preloadEditor}
onClick={openEditor}
>
<Button variant="ghost" onPointerEnter={preloadEditor} onFocus={preloadEditor} onClick={openEditor}>
{t("memo.comment.write-a-comment")}
</Button>
)}
@@ -118,8 +118,12 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
))}
{hasMoreComments && (
<div className="w-full mt-4 flex justify-center">
<Button variant="outline" className="rounded-full px-4" onClick={onLoadMoreComments} disabled={isFetchingMoreComments}>
{isFetchingMoreComments && <LoaderCircleIcon className="h-4 w-4 animate-spin" />}
<Button
variant="neutral"
onClick={onLoadMoreComments}
loading={isFetchingMoreComments}
loadingLabel={t("resource.fetching-data")}
>
{t(isFetchingMoreComments ? "resource.fetching-data" : "memo.load-more")}
</Button>
</div>
@@ -1,3 +1,4 @@
import { Menu } from "@usememos/ui";
import copy from "copy-to-clipboard";
import {
ChevronDownIcon,
@@ -10,22 +11,26 @@ import {
Share2Icon,
} from "lucide-react";
import { useMemo, useState } from "react";
import toast from "react-hot-toast";
import { Link, useLocation } from "react-router-dom";
import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_COUNT_RAIL_CLASSES, SidebarRowIconSlot } from "@/components/AppSidebar/SidebarRow";
import SidebarRow, {
SIDEBAR_ROW_CLASSES,
SIDEBAR_ROW_COUNT_RAIL_CLASSES,
SidebarRowIconSlot,
sidebarRowStateClasses,
} from "@/components/AppSidebar/SidebarRow";
import SidebarSection, { SIDEBAR_SECTION_STACK_CLASSES } from "@/components/AppSidebar/SidebarSection";
import { extractHeadings } from "@/components/MemoEditor/view/headings";
import { getRelationBuckets, getRelationMemo } from "@/components/MemoMetadata/Relation/relationHelpers";
import { useResolvedRelationMemos } from "@/components/MemoMetadata/Relation/useResolvedRelationMemos";
import MemoParentPlaceholder, { type MemoParentStatus } from "@/components/MemoParentPlaceholder";
import { createMemoNavigationState } from "@/components/MemoView/navigation";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useAuth } from "@/contexts/AuthContext";
import { useInstance } from "@/contexts/InstanceContext";
import { useOverflowTitle } from "@/hooks";
import useCurrentUser from "@/hooks/useCurrentUser";
import { MEMO_COMMENTS_ANCHOR_ID } from "@/lib/memo-comments";
import { isMemoBlurred } from "@/lib/tag";
import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { State } from "@/types/proto/api/common_pb";
import { Memo, type MemoRelation, Visibility } from "@/types/proto/api/memo_service_pb";
@@ -73,7 +78,7 @@ const BacklinkRow = ({
return (
<Link
aria-label={`${referencedByLabel}: ${snippet}`}
className={cn(SIDEBAR_ROW_CLASSES, "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground")}
className={cn(SIDEBAR_ROW_CLASSES, sidebarRowStateClasses("idle"))}
to={`/${relatedMemo.name}`}
state={parentPage ? createMemoNavigationState(parentPage) : undefined}
title={title}
@@ -151,17 +156,17 @@ const MemoDetailSidebar = ({
const host = (profile.instanceUrl || window.location.origin).replace(/\/+$/, "");
const path = forceReadonly ? `${location.pathname}${location.search}` : `/${memo.name}`;
copy(`${host}${path.startsWith("/") ? path : `/${path}`}`);
toast.success(t("message.succeed-copy-link"));
toast.add({ title: t("message.succeed-copy-link"), type: "success" });
};
return (
<div className={cn("relative w-full select-none", SIDEBAR_SECTION_STACK_CLASSES, className)}>
<div className={cn("mu-compact relative w-full select-none", SIDEBAR_SECTION_STACK_CLASSES, className)}>
{showOnThisMemo && (
<SidebarSection label={t("memo.on-this-memo")}>
{headings.length > 1 && <MemoOutline headings={headings} memoName={memo.name} />}
{showComments && (
<a
className={cn(SIDEBAR_ROW_CLASSES, "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground")}
className={cn(SIDEBAR_ROW_CLASSES, sidebarRowStateClasses("idle"))}
href={`#${MEMO_COMMENTS_ANCHOR_ID}`}
onClick={(event) => {
if (!onCommentsOpen) return;
@@ -183,7 +188,7 @@ const MemoDetailSidebar = ({
{!parentStatus && parentMemo && (
<Link
aria-label={parentSnippet ? `${t("memo.parent-memo")}: ${parentSnippet}` : t("memo.parent-memo")}
className={cn(SIDEBAR_ROW_CLASSES, "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground")}
className={cn(SIDEBAR_ROW_CLASSES, sidebarRowStateClasses("idle"))}
to={`/${parentMemo.name}`}
state={parentPage ? createMemoNavigationState(parentPage) : undefined}
title={parentSnippet || undefined}
@@ -212,37 +217,35 @@ const MemoDetailSidebar = ({
<SidebarSection label={t("common.actions")}>
{canEdit && <SidebarRow icon={Edit3Icon} label={t("common.edit")} onClick={onEdit} />}
{canComment && <SidebarRow icon={MessageSquarePlusIcon} label={t("memo.comment.write-a-comment")} onClick={onCommentCreate} />}
<DropdownMenu>
<DropdownMenuTrigger
<Menu.Root modal={false}>
<Menu.Trigger
aria-label={t("common.share")}
className={cn(
SIDEBAR_ROW_CLASSES,
"text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground data-popup-open:bg-sidebar-accent/65 data-popup-open:text-foreground",
sidebarRowStateClasses("idle"),
"data-popup-open:bg-mu-hover/65 data-popup-open:text-mu-ink",
)}
>
<SidebarRowIconSlot icon={Share2Icon} />
<span className="min-w-0 flex-1 truncate text-start">{t("common.share")}</span>
<ChevronDownIcon className="size-3.5 shrink-0 opacity-55" strokeWidth={1.8} />
</DropdownMenuTrigger>
<DropdownMenuContent align="start" sideOffset={4} className="w-48">
<DropdownMenuItem onClick={handleCopyLink}>
<LinkIcon />
<ChevronDownIcon className="mu-icon-sm shrink-0 opacity-55" />
</Menu.Trigger>
<Menu.Popup align="start" className="w-48">
<Menu.Item onClick={handleCopyLink} icon={<LinkIcon />}>
{t("memo.copy-link")}
</DropdownMenuItem>
</Menu.Item>
{onShareImageOpen && (
<DropdownMenuItem onClick={onShareImageOpen}>
<ImageIcon />
<Menu.Item onClick={onShareImageOpen} icon={<ImageIcon />}>
{t("memo.share.open-image")}
</DropdownMenuItem>
</Menu.Item>
)}
{canManageShares && (
<DropdownMenuItem onClick={() => setSharePanelOpen(true)}>
<Share2Icon />
<Menu.Item onClick={() => setSharePanelOpen(true)} icon={<Share2Icon />}>
{t("memo.share.open-panel")}
</DropdownMenuItem>
</Menu.Item>
)}
</DropdownMenuContent>
</DropdownMenu>
</Menu.Popup>
</Menu.Root>
</SidebarSection>
{sharePanelOpen && <MemoSharePanel memoName={memo.name} open={sharePanelOpen} onClose={() => setSharePanelOpen(false)} />}
@@ -1,6 +1,6 @@
import { buttonClasses } from "@usememos/ui";
import { useEffect, useMemo, useRef, useState } from "react";
import type { HeadingItem } from "@/components/MemoEditor/view/headings";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { findAnchorTarget, findMemoContentRoot } from "@/utils/markdown-manipulation";
@@ -13,10 +13,10 @@ interface MemoOutlineProps {
const READING_LINE_OFFSET = 100;
/**
* Each heading is a quiet row: the kit's `quiet` treatment at the sidebar's 28px row height,
* Each heading is a quiet row: the package's ghost button at the sidebar's row height,
* so the section you are reading takes the accent fill through `aria-current`.
*/
const OUTLINE_ROW_CLASSES = cn(buttonVariants({ variant: "quiet", size: "sm" }), "relative w-full justify-start");
const OUTLINE_ROW_CLASSES = cn(buttonClasses({ variant: "ghost", size: "sm" }), "relative w-full justify-start");
/** Outline navigation for memo headings (h1–h4) with active-section tracking. */
const MemoOutline = ({ headings, memoName }: MemoOutlineProps) => {
@@ -84,7 +84,7 @@ const MemoOutline = ({ headings, memoName }: MemoOutlineProps) => {
<span
className={cn(
"absolute start-0.5 top-1/2 h-[13px] w-[2px] -translate-y-1/2 rounded-full transition-colors",
active ? "bg-primary" : "bg-border",
active ? "bg-mu-primary" : "bg-mu-line",
)}
/>
<span className="min-w-0 flex-1 truncate">{heading.text}</span>
@@ -1,12 +1,10 @@
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { ConnectError } from "@connectrpc/connect";
import { CheckIcon, CopyIcon, LinkIcon, Loader2Icon, Trash2Icon } from "lucide-react";
import { Button, Dialog, Select, Skeleton, Tooltip } from "@usememos/ui";
import { CheckIcon, CopyIcon, LinkIcon, Trash2Icon } from "lucide-react";
import { useMemo, useState } from "react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { getShareUrl, useCreateMemoShare, useDeleteMemoShare, useMemoShares } from "@/hooks/useMemoShareQueries";
import { showErrorToast, toast } from "@/lib/toast";
import type { MemoShare } from "@/types/proto/api/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -47,33 +45,49 @@ function ShareLinkRow({ share, memoName }: ShareLinkRowProps) {
const handleRevoke = async () => {
try {
await deleteShare.mutateAsync({ name: share.name, memoName });
toast.success(t("memo.share.revoked"));
toast.add({ title: t("memo.share.revoked"), type: "success" });
} catch (e) {
toast.error((e as ConnectError).message || t("memo.share.revoke-failed"));
showErrorToast((e as ConnectError).message || t("memo.share.revoke-failed"));
}
};
return (
<div className="flex flex-col gap-1 rounded-md border border-border p-3">
<div className="flex flex-col gap-1 rounded-mu-md border border-mu-line p-3">
<div className="flex items-center justify-between gap-2">
<span className="truncate font-mono text-xs text-muted-foreground">{url}</span>
<span className="truncate font-mono mu-caption text-mu-ink-muted">{url}</span>
<div className="flex shrink-0 items-center gap-1">
<Button variant="ghost" size="icon" className="h-7 w-7" onClick={handleCopy} title={t("memo.share.copy")}>
{copied ? <CheckIcon className="h-3.5 w-3.5 text-success" /> : <CopyIcon className="h-3.5 w-3.5" />}
</Button>
<Button
variant="ghost"
size="icon"
className="h-7 w-7 text-destructive hover:text-destructive"
onClick={handleRevoke}
disabled={deleteShare.isPending}
title={t("memo.share.revoke")}
>
<Trash2Icon className="h-3.5 w-3.5" />
</Button>
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
variant="ghost"
size="sm"
onClick={handleCopy}
aria-label={t("memo.share.copy")}
icon={copied ? <CheckIcon /> : <CopyIcon />}
/>
}
/>
<Tooltip.Popup>{t("memo.share.copy")}</Tooltip.Popup>
</Tooltip.Root>
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
variant="ghost"
size="sm"
onClick={handleRevoke}
disabled={deleteShare.isPending}
aria-label={t("memo.share.revoke")}
icon={<Trash2Icon />}
/>
}
/>
<Tooltip.Popup>{t("memo.share.revoke")}</Tooltip.Popup>
</Tooltip.Root>
</div>
</div>
<p className="text-xs text-muted-foreground">{formatExpiry(share, t)}</p>
<p className="mu-caption text-mu-ink-muted">{formatExpiry(share, t)}</p>
</div>
);
}
@@ -104,28 +118,28 @@ const MemoSharePanel = ({ open, onClose, memoName }: MemoSharePanelProps) => {
try {
await createShare.mutateAsync({ memoName, expireTime: getExpireDate(expiry) });
} catch (e) {
toast.error((e as ConnectError).message || t("memo.share.create-failed"));
showErrorToast((e as ConnectError).message || t("memo.share.create-failed"));
}
};
return (
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<LinkIcon className="h-4 w-4" />
{t("memo.share.title")}
</DialogTitle>
</DialogHeader>
<Dialog.Root open={open} onOpenChange={(v) => !v && onClose()}>
<Dialog.Popup closeLabel={t("common.close")}>
<Dialog.Title className="flex items-center gap-2">
<LinkIcon className="mu-icon" />
{t("memo.share.title")}
</Dialog.Title>
<div className="flex flex-col gap-4 py-2">
{/* Active links */}
<div className="flex flex-col gap-2">
<p className="text-sm font-medium text-muted-foreground">{t("memo.share.active-links")}</p>
<p className="mu-label text-mu-ink-muted">{t("memo.share.active-links")}</p>
{isLoading ? (
<Loader2Icon className="h-4 w-4 animate-spin text-muted-foreground" />
<div className="flex flex-col gap-2" aria-busy="true" aria-label={t("editor.blocks.loading")}>
<Skeleton height={32} />
</div>
) : shares.length === 0 ? (
<p className="text-sm text-muted-foreground">{t("memo.share.no-links")}</p>
<p className="mu-body text-mu-ink-muted">{t("memo.share.no-links")}</p>
) : (
<div className="flex flex-col gap-2">
{shares.map((share) => (
@@ -137,32 +151,31 @@ const MemoSharePanel = ({ open, onClose, memoName }: MemoSharePanelProps) => {
{/* Create new link */}
<div className="flex items-center gap-2">
<Select value={expiry} items={expiryOptions} onValueChange={(v) => setExpiry(v as ExpiryOption)}>
<SelectTrigger className="w-36">
<SelectValue />
</SelectTrigger>
<SelectContent>
<Select.Root value={expiry} items={expiryOptions} onValueChange={(v) => setExpiry(v as ExpiryOption)}>
<Select.Trigger className="w-36">
<Select.Value />
</Select.Trigger>
<Select.Popup>
{expiryOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
<Select.Item key={option.value} value={option.value}>
{option.label}
</SelectItem>
</Select.Item>
))}
</SelectContent>
</Select>
<Button onClick={handleCreate} disabled={createShare.isPending} className="flex-1">
{createShare.isPending ? (
<>
<Loader2Icon className="mr-2 h-4 w-4 animate-spin" />
{t("memo.share.creating")}
</>
) : (
t("memo.share.create-link")
)}
</Select.Popup>
</Select.Root>
<Button
variant="primary"
onClick={handleCreate}
loading={createShare.isPending}
loadingLabel={t("memo.share.creating")}
className="flex-1"
>
{t("memo.share.create-link")}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</Dialog.Popup>
</Dialog.Root>
);
};
+85 -151
View File
@@ -1,26 +1,14 @@
import { useDirection } from "@base-ui/react/direction-provider";
import { buttonClasses, Field, Popover, Select, Separator, Switch, Toggle, ToggleGroup, Tooltip } from "@usememos/ui";
import { ChevronDownIcon, Columns2Icon, Columns3Icon, InfinityIcon, type LucideIcon, Rows3Icon } from "lucide-react";
import type { ReactNode, RefObject } from "react";
import { SIDEBAR_SECTION_ACTION_ICON_CLASSES } from "@/components/AppSidebar/SidebarSection";
import { buttonVariants } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { RefObject } from "react";
import { MAX_COLUMNS_VALUES, type MemoMaxColumns, useView } from "@/contexts/ViewContext";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
interface Props {
anchor?: RefObject<HTMLElement | null>;
}
interface SettingRowProps {
label: string;
description?: string;
children: ReactNode;
}
// Keyed by the context's canonical value list, so adding a column option forces an icon and
// wording here at compile time. The i18n param is deliberately named `n`, not `count` —
// i18next would route `count` through plural-form lookup.
@@ -31,142 +19,87 @@ const LAYOUT_OPTIONS: Record<MemoMaxColumns, { icon: LucideIcon; key: "layout-li
0: { icon: InfinityIcon, key: "layout-auto" },
};
const SettingRow = ({ label, description, children }: SettingRowProps) => (
<div className="flex min-h-6 items-center justify-between gap-2">
<div className="min-w-0">
<p className="text-xs leading-4 text-foreground">{label}</p>
{description && <p className="text-[11px] leading-4 text-muted-foreground">{description}</p>}
</div>
{children}
</div>
);
function MemoDisplaySettingsContent() {
const t = useTranslate();
const direction = useDirection();
const { orderByTimeAsc, timeBasis, compactMode, maxColumns, setTimeBasis, setOrderByTimeAsc, setCompactMode, setMaxColumns } = useView();
// Multi-column grids always render compact tiles, so the toggle is shown as on and locked
// there; it only becomes a real choice at a single column.
const compactLocked = maxColumns !== 1;
const timeBasisOptions = [
{ value: "create_time", label: t("common.created-at") },
{ value: "update_time", label: t("common.last-updated-at") },
];
const sortOrderOptions = [
{ value: "desc", label: t("memo.newest-first") },
{ value: "asc", label: t("memo.oldest-first") },
];
const timeBasisOptions = { create_time: t("common.created-at"), update_time: t("common.last-updated-at") };
const sortOrderOptions = { desc: t("memo.newest-first"), asc: t("memo.oldest-first") };
return (
<div>
<section className="p-1.5">
<div
role="radiogroup"
aria-label={t("memo.layout")}
className="grid grid-cols-4 gap-0.5"
onKeyDown={(event) => {
const delta =
event.key === "ArrowRight"
? direction === "rtl"
? -1
: 1
: event.key === "ArrowLeft"
? direction === "rtl"
? 1
: -1
: event.key === "ArrowDown"
? 1
: event.key === "ArrowUp"
? -1
: 0;
if (delta === 0) return;
event.preventDefault();
const index = MAX_COLUMNS_VALUES.indexOf(maxColumns);
const next = MAX_COLUMNS_VALUES[(index + delta + MAX_COLUMNS_VALUES.length) % MAX_COLUMNS_VALUES.length];
setMaxColumns(next);
event.currentTarget.querySelector<HTMLButtonElement>(`[data-value="${next}"]`)?.focus();
}}
<div className="flex flex-col gap-3">
<ToggleGroup
size="sm"
fullWidth
aria-label={t("memo.layout")}
value={[String(maxColumns)]}
// One layout always stays chosen: pressing the chosen item again keeps it.
onValueChange={([next]) => next && setMaxColumns(Number(next) as MemoMaxColumns)}
>
{MAX_COLUMNS_VALUES.map((value) => {
const { icon: Icon, key } = LAYOUT_OPTIONS[value];
const label = t(`memo.${key}`, { n: value });
// Column counts show as a number; every option is spelled out on hover.
return (
<Tooltip.Root key={value}>
<Tooltip.Trigger
render={
<Toggle value={String(value)} aria-label={label} icon={<Icon />}>
{value > 1 ? value.toString() : label}
</Toggle>
}
/>
<Tooltip.Popup>{t(`memo.${key}-description`, { n: value })}</Tooltip.Popup>
</Tooltip.Root>
);
})}
</ToggleGroup>
{/* Selects, not segmented rows: the two labels of a pair don't fit side by side in every language. */}
<Field.Root orientation="horizontal" size="sm">
<Field.Label>{t("memo.order-by")}</Field.Label>
<Select.Root
items={timeBasisOptions}
value={timeBasis}
onValueChange={(value) => setTimeBasis(value === "update_time" ? "update_time" : "create_time")}
>
{MAX_COLUMNS_VALUES.map((value) => {
const { icon: Icon, key } = LAYOUT_OPTIONS[value];
const label = t(`memo.${key}`, { n: value });
const description = t(`memo.${key}-description`, { n: value });
const shortLabel = value > 1 ? value.toString() : label;
const active = maxColumns === value;
return (
<button
key={value}
type="button"
role="radio"
aria-checked={active}
aria-label={label}
title={description}
tabIndex={active ? 0 : -1}
data-value={value}
onClick={() => setMaxColumns(value)}
className={cn(
"flex h-6 min-w-0 items-center justify-center gap-1 rounded-sm px-1 text-[11px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
active ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-accent/50 hover:text-foreground",
)}
>
<Icon className="size-3.5 shrink-0" strokeWidth={1.8} />
<span className="truncate">{shortLabel}</span>
</button>
);
})}
</div>
</section>
<Select.Trigger className="min-w-36">
<Select.Value />
</Select.Trigger>
<Select.Popup>
<Select.Item value="create_time">{timeBasisOptions.create_time}</Select.Item>
<Select.Item value="update_time">{timeBasisOptions.update_time}</Select.Item>
</Select.Popup>
</Select.Root>
</Field.Root>
<Field.Root orientation="horizontal" size="sm">
<Field.Label>{t("memo.direction")}</Field.Label>
<Select.Root
items={sortOrderOptions}
value={orderByTimeAsc ? "asc" : "desc"}
onValueChange={(value) => setOrderByTimeAsc(value === "asc")}
>
<Select.Trigger className="min-w-36">
<Select.Value />
</Select.Trigger>
<Select.Popup>
<Select.Item value="desc">{sortOrderOptions.desc}</Select.Item>
<Select.Item value="asc">{sortOrderOptions.asc}</Select.Item>
</Select.Popup>
</Select.Root>
</Field.Root>
<section className="space-y-1 border-t border-border/60 px-2.5 py-2">
<SettingRow label={t("memo.order-by")}>
<Select
value={timeBasis}
items={timeBasisOptions}
onValueChange={(value) => setTimeBasis(value === "update_time" ? "update_time" : "create_time")}
>
<SelectTrigger size="xs" className="w-32" aria-label={t("memo.order-by")}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{timeBasisOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</SettingRow>
<SettingRow label={t("memo.direction")}>
<Select
value={orderByTimeAsc ? "asc" : "desc"}
items={sortOrderOptions}
onValueChange={(value) => setOrderByTimeAsc(value === "asc")}
>
<SelectTrigger size="xs" className="w-32" aria-label={t("memo.direction")}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{sortOrderOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</SettingRow>
</section>
<Separator />
<section className="space-y-1 border-t border-border/60 px-2.5 py-2">
<SettingRow label={t("memo.compact-mode")} description={compactLocked ? t("memo.grid-compact-hint") : undefined}>
<Switch
aria-label={t("memo.compact-mode")}
checked={compactLocked || compactMode}
onCheckedChange={setCompactMode}
disabled={compactLocked}
/>
</SettingRow>
</section>
<Field.Root orientation="horizontal" size="sm">
<Field.Label>{t("memo.compact-mode")}</Field.Label>
{/* Wraps inside the width the controls set, so the hint never widens the popup. */}
{compactLocked && <Field.Description className="w-0 min-w-full">{t("memo.grid-compact-hint")}</Field.Description>}
<Switch checked={compactLocked || compactMode} onCheckedChange={setCompactMode} disabled={compactLocked} />
</Field.Root>
</div>
);
}
@@ -176,27 +109,28 @@ function MemoDisplaySettingMenu({ anchor }: Props) {
const label = `${t("common.timeline")} · ${t("memo.view-options")}`;
return (
<Popover>
<Tooltip>
<TooltipTrigger
<Popover.Root>
<Tooltip.Root>
<Tooltip.Trigger
render={
<PopoverTrigger
<Popover.Trigger
aria-label={label}
className={cn(
buttonVariants({ variant: "quiet", size: "icon-compact" }),
"w-auto rounded-s-none px-1.5 hover:bg-sidebar-accent data-popup-open:[&_svg]:rotate-180",
buttonClasses({ variant: "ghost", iconOnly: true }),
"w-auto rounded-s-none px-1.5 hover:bg-mu-hover data-popup-open:[&_svg]:rotate-180",
)}
/>
}
>
<ChevronDownIcon className={cn(SIDEBAR_SECTION_ACTION_ICON_CLASSES, "transition-transform")} strokeWidth={1.8} />
</TooltipTrigger>
<TooltipContent side="bottom">{label}</TooltipContent>
</Tooltip>
<PopoverContent anchor={anchor} align="start" sideOffset={6} aria-label={label} className="w-56 p-0">
<ChevronDownIcon className="mu-icon-sm transition-transform" />
</Tooltip.Trigger>
<Tooltip.Popup side="bottom">{label}</Tooltip.Popup>
</Tooltip.Root>
{/* Grows to fit long translations such as "Automatisch" instead of truncating them; the full-width group then shares the room from its labels' natural widths. */}
<Popover.Popup anchor={anchor} align="start" aria-label={label} className="w-max min-w-(--mu-popover-width)">
<MemoDisplaySettingsContent />
</PopoverContent>
</Popover>
</Popover.Popup>
</Popover.Root>
);
}
+8 -3
View File
@@ -1,4 +1,4 @@
import { Suspense, useState } from "react";
import { type ReactNode, Suspense, useState } from "react";
import { useAuth } from "@/contexts/AuthContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useMemoByName, useUpdateMemo } from "@/hooks/useMemoQueries";
@@ -76,6 +76,8 @@ export interface MemoEditingProps {
className?: string;
/** Inside a card that is the frame already: no background, border or padding of its own outside focus mode. */
frameless?: boolean;
/** Leads the timestamp row, before the time: the card's creator while it edits in place. */
timestampLead?: ReactNode;
/**
* Marks the instance as hosted: a host (the global composer dialog) presents the
* editor in the focus-mode layout and owns that frame. The editor mounts straight
@@ -166,8 +168,11 @@ const MemoEditorDraft = ({ draft, ...editing }: MemoEditorDraftProps) => {
// placeholder line and the toolbar's height, so the page below does not move when the
// session takes its place.
const fallback = editing.frameless ? null : (
<div aria-hidden className={cn("flex w-full flex-col gap-2 rounded-lg border border-border/70 bg-card px-4 py-3", editing.className)}>
<div className="w-full text-base leading-6 text-muted-foreground">{editing.placeholder ?? " "}</div>
<div
aria-hidden
className={cn("flex w-full flex-col gap-2 rounded-mu-lg border border-mu-line/70 bg-mu-surface px-4 py-3", editing.className)}
>
<div className="w-full text-base leading-6 text-mu-ink-muted">{editing.placeholder ?? " "}</div>
<div className="h-9 w-full" />
</div>
);
@@ -1,9 +1,9 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "react-hot-toast";
import { useAuth } from "@/contexts/AuthContext";
import { useInstance } from "@/contexts/InstanceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useSourceMode } from "@/hooks/useSourceMode";
import { showErrorToast, toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import { InstanceSetting_Key } from "@/types/proto/api/instance_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -45,6 +45,7 @@ export const EditSession: React.FC<EditSessionProps> = ({
className,
draftKey,
frameless,
timestampLead,
memo,
parentMemoName,
suggestions = [],
@@ -157,15 +158,15 @@ export const EditSession: React.FC<EditSessionProps> = ({
const text = (await transcriptionService.transcribeFile(localFile.file)).trim();
if (!text) {
dispatch(actions.addLocalFile(localFile));
toast.error(t("editor.audio-recorder.transcribe-empty"));
showErrorToast(t("editor.audio-recorder.transcribe-empty"));
return;
}
insertTranscribedText(text);
toast.success(t("editor.audio-recorder.transcribe-success"));
toast.add({ title: t("editor.audio-recorder.transcribe-success"), type: "success" });
} catch (error) {
console.error(error);
toast.error(errorService.getErrorMessage(error) || t("editor.audio-recorder.transcribe-error"));
showErrorToast(errorService.getErrorMessage(error) || t("editor.audio-recorder.transcribe-error"));
dispatch(actions.addLocalFile(localFile));
} finally {
setIsTranscribingAudio(false);
@@ -188,7 +189,7 @@ export const EditSession: React.FC<EditSessionProps> = ({
onRecordingEmpty: (mode) => {
if (mode === "transcribe") {
setIsTranscribingAudio(false);
toast.error(t("editor.audio-recorder.transcribe-empty"));
showErrorToast(t("editor.audio-recorder.transcribe-empty"));
}
setIsAudioRecorderOpen(false);
},
@@ -213,7 +214,7 @@ export const EditSession: React.FC<EditSessionProps> = ({
}
if (audioRecorder.status === "error" || audioRecorder.status === "unsupported") {
toast.error(audioRecorder.error || t("editor.audio-recorder.error-description"));
showErrorToast(audioRecorder.error || t("editor.audio-recorder.error-description"));
setIsAudioRecorderOpen(false);
}
}, [isAudioRecorderOpen, audioRecorder.error, audioRecorder.status, t]);
@@ -338,10 +339,12 @@ export const EditSession: React.FC<EditSessionProps> = ({
<div
ref={editorContainerRef}
className={cn(
"group relative w-full flex flex-col justify-between items-start gap-2",
// A card that is the frame already supplies the background, border and padding; a
// session floating over the page in focus mode always brings its own.
(!frameless || isFocusMode) && "bg-card px-4 py-3 rounded-lg border border-border/70",
"group w-full flex flex-col justify-between items-start gap-2",
// A card that is the frame already supplies the background, border and padding, and
// positions the Markdown tag in its own corner; a session floating over the page in
// focus mode always brings its own. The bottom is 16px like the sides: the toolbar's
// hard edge needs more room than the text's soft top.
(!frameless || isFocusMode) && "relative bg-mu-surface px-4 pt-3 pb-4 rounded-mu-lg border border-mu-line/70",
isFocusMode && cn(FOCUS_MODE_STYLES.container.base, FOCUS_MODE_STYLES.container.spacing),
!isFocusMode && className,
)}
@@ -349,8 +352,8 @@ export const EditSession: React.FC<EditSessionProps> = ({
{isSourceMode && (
<span
className={cn(
"pointer-events-none absolute end-0 top-0 rounded-es-lg rounded-se-lg border-s border-b border-border/70 bg-muted/40 px-1.5 py-1 select-none font-mono text-[10px] font-medium leading-3 text-muted-foreground [text-box:trim-both_cap_alphabetic]",
isFocusMode && "border-border py-px leading-none",
"pointer-events-none absolute end-0 top-0 rounded-es-mu-lg rounded-se-mu-lg border-s border-b border-mu-line/70 bg-mu-well/40 flex h-5 items-center px-1.5 select-none mu-label-xs font-mono text-mu-ink-muted",
isFocusMode && "border-mu-line",
)}
aria-label={t("editor.markdown-mode")}
>
@@ -362,7 +365,8 @@ export const EditSession: React.FC<EditSessionProps> = ({
Focus mode always shows the memo's time ("Now" before it has one) and adds
the button that leaves the current frame — minimize inline, close when hosted. */}
{(showTimestamp || isFocusMode) && (
<div className={cn("flex w-full items-center", isFocusMode ? "h-10" : "h-6")}>
<div className={cn("flex w-full items-center gap-1.5", isFocusMode ? "h-10" : "h-6")}>
{timestampLead}
<TimestampPopover />
{isFocusMode && (
<div className="ms-auto -me-2">
@@ -84,7 +84,7 @@ const Editor = forwardRef(function Editor(props: EditorProps, ref: React.Forward
data-focus-mode={isFocusMode || undefined}
data-source-mode={mode === "source" || undefined}
>
<div className={cn("memo-editor-scroller w-full text-base", isFocusMode && "min-h-0 flex-1")}>
<div className={cn("memo-editor-scroller w-full text-base leading-6", isFocusMode && "min-h-0 flex-1")}>
<MemoMarkdown
editorRef={editorRef}
value={value}
@@ -1,21 +1,12 @@
import { buttonClasses, Menu } from "@usememos/ui";
import { CheckIcon, ChevronDownIcon, PlusIcon, XIcon } from "lucide-react";
import SpaceIcon from "@/components/SpaceIcon";
import SpaceMark from "@/components/SpaceMark";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import VisibilityIcon from "@/components/VisibilityIcon";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useSpaces } from "@/hooks/useSpaceQueries";
import { extractSpaceUidFromName, getDuplicateSpaceTitles } from "@/lib/space-display";
import { cn } from "@/lib/utils";
import type { Space_Icon } from "@/types/proto/api/space_service_pb";
import { useTranslate } from "@/utils/i18n";
import { getAssignableVisibilityOptions, getVisibilityOption } from "@/utils/memo";
@@ -51,15 +42,18 @@ const AudienceMenu = ({ value, onChange, space, onSpaceChange, disabled }: Audie
];
return (
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant="quiet" size="sm" className="min-w-0 max-w-64 shrink gap-1 text-muted-foreground" disabled={disabled} />}
<Menu.Root modal={false} size="sm">
{/* The trigger starts with an icon (a space mark or the lock) inside a span, so it takes the
package's icon-side padding itself; its gaps are the md icon gap, like a Button's. */}
<Menu.Trigger
className={cn(buttonClasses({ variant: "ghost", size: "md" }), "min-w-0 max-w-64 shrink ps-(--mu-row-padding-icon)")}
disabled={disabled}
title={summary}
aria-label={summary}
>
{onSpaceChange && space && (
<>
<span className="flex min-w-0 max-w-32 items-center gap-1 sm:max-w-40">
<span className="flex min-w-0 max-w-32 items-center gap-1.5 sm:max-w-40">
<SpaceIcon icon={selectedSpace?.icon} size={14} />
<span className="truncate">{destination}</span>
</span>
@@ -68,89 +62,88 @@ const AudienceMenu = ({ value, onChange, space, onSpaceChange, disabled }: Audie
</span>
</>
)}
<span className="flex shrink-0 items-center gap-1">
<VisibilityIcon visibility={value} className="size-3.5 text-current" />
<span className="flex shrink-0 items-center gap-1.5">
<VisibilityIcon visibility={value} className="text-current" />
<span>{visibilityLabel}</span>
</span>
<ChevronDownIcon className="size-3 opacity-50" strokeWidth={1.8} />
</DropdownMenuTrigger>
<DropdownMenuContent align="start" size="sm" className="w-56" aria-label={t("common.visibility")}>
<ChevronDownIcon className="mu-icon-sm" />
</Menu.Trigger>
<Menu.Popup align="start" className="w-56" aria-label={t("common.visibility")}>
{/* Two lines per audience: the description is the only place the app explains who can
read a memo, and translations run long. The menu's fixed width makes long copy wrap
instead of widening it; icon and check stay on the title's line. */}
{visibilityOptions.map((option) => (
<DropdownMenuItem key={option.value} onClick={() => onChange(option.value)}>
<span aria-hidden className="flex h-4.5 w-5 shrink-0 items-center justify-center self-start">
<VisibilityIcon visibility={option.value} className="size-3.5" />
</span>
<span className="flex min-w-0 flex-1 flex-col">
<span>{t(option.labelKey)}</span>
<span className="text-xs text-muted-foreground">{t(option.descriptionKey, { space: destination })}</span>
</span>
<span aria-hidden className="ms-auto flex h-4.5 w-3.5 shrink-0 items-center justify-center self-start">
{option.value === value && <CheckIcon className="size-3.5" />}
</span>
</DropdownMenuItem>
))}
<Menu.RadioGroup value={value} onValueChange={(next) => onChange(next)}>
{visibilityOptions.map((option) => (
<Menu.RadioItem
key={option.value}
value={option.value}
closeOnClick
icon={<VisibilityIcon visibility={option.value} />}
description={t(option.descriptionKey, { space: destination })}
>
{t(option.labelKey)}
</Menu.RadioItem>
))}
</Menu.RadioGroup>
{showSpaceRow && onSpaceChange && (
<>
<DropdownMenuSeparator />
<DropdownMenuSub>
<DropdownMenuSubTrigger title={space ? destination : undefined}>
{space ? (
<>
<Menu.Separator />
<Menu.SubmenuRoot>
<Menu.SubmenuTrigger
title={space ? destination : undefined}
icon={
space ? (
<SpaceMark icon={selectedSpace?.icon} size="sm" />
<span className="min-w-0 flex-1 truncate">{destination}</span>
</>
) : (
<>
) : (
<span
aria-hidden
className="flex size-5 shrink-0 items-center justify-center rounded-[5px] border border-dashed border-muted-foreground/45"
className="flex size-5 shrink-0 items-center justify-center rounded-[5px] border border-dashed border-mu-ink-muted/45"
>
<PlusIcon className="size-3" strokeWidth={2} />
<PlusIcon className="mu-icon-xs" />
</span>
<span className="flex-1 text-muted-foreground">{t("space.add-to")}</span>
</>
)}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-56">
)
}
>
{space ? destination : <span className="text-mu-ink-muted">{t("space.add-to")}</span>}
</Menu.SubmenuTrigger>
<Menu.Popup className="w-56">
{spaceChoices.map((item) => {
const selected = item.name === space;
const removeLabel = t("space.remove-from", { space: item.label });
return (
<DropdownMenuItem
<Menu.Item
key={item.name}
title={selected ? removeLabel : item.label}
aria-label={selected ? removeLabel : item.label}
onClick={() => onSpaceChange(selected ? undefined : item.name)}
icon={<SpaceMark icon={item.icon} size="sm" />}
// The selected Space is its own off switch: a check at rest, an ✕ under the
// pointer or keyboard, and always an ✕ on touch, which has no hover.
shortcut={
selected ? (
<span aria-hidden className="flex size-3.5 items-center justify-center">
<CheckIcon className="mu-icon-sm in-data-highlighted:hidden pointer-coarse:hidden" />
<XIcon className="mu-icon-sm hidden in-data-highlighted:block pointer-coarse:block" />
</span>
) : undefined
}
>
<SpaceMark icon={item.icon} size="sm" />
<span className="min-w-0 flex-1 truncate">{item.label}</span>
{/* The selected Space is its own off switch: a check at rest, an ✕ under the
pointer or keyboard, and always an ✕ on touch, which has no hover. */}
{selected && (
<span aria-hidden className="ms-auto flex size-3.5 shrink-0 items-center justify-center">
<CheckIcon className="size-3.5 in-data-highlighted:hidden pointer-coarse:hidden" />
<XIcon className="hidden size-3.5 in-data-highlighted:block pointer-coarse:block" />
</span>
)}
</DropdownMenuItem>
{item.label}
</Menu.Item>
);
})}
{isPending && <DropdownMenuItem disabled>{t("space.loading")}</DropdownMenuItem>}
{isPending && <Menu.Item disabled>{t("space.loading")}</Menu.Item>}
{isError && (
<DropdownMenuItem closeOnClick={false} onClick={() => void refetch()}>
<span className="text-destructive">{t("space.load-error")}</span>
<span className="ms-auto text-muted-foreground">{t("search.retry")}</span>
</DropdownMenuItem>
<Menu.Item closeOnClick={false} onClick={() => void refetch()} shortcut={t("search.retry")}>
<span className="text-mu-danger">{t("space.load-error")}</span>
</Menu.Item>
)}
</DropdownMenuSubContent>
</DropdownMenuSub>
</Menu.Popup>
</Menu.SubmenuRoot>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</Menu.Popup>
</Menu.Root>
);
};
@@ -1,8 +1,6 @@
import { CheckIcon, CornerDownLeftIcon, LoaderIcon } from "lucide-react";
import type { FC } from "react";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { Button, Tooltip } from "@usememos/ui";
import { CheckIcon } from "lucide-react";
import { type FC, useId } from "react";
import { type Location, Visibility } from "@/types/proto/api/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { primaryModifierGlyph } from "@/utils/platform";
@@ -12,17 +10,6 @@ import type { EditorToolbarProps } from "../types";
import AudienceMenu from "./AudienceMenu";
import InsertMenu from "./InsertMenu";
/**
* Save shortcut as key caps, shown in the commit button's tooltip rather than on
* the button itself so the primary action reads as a plain verb.
*/
const ShortcutKeys: FC = () => (
<kbd className="inline-flex items-center gap-px rounded-[4px] bg-primary-foreground/20 px-1 py-0.5 font-sans text-2xs leading-none font-medium">
{primaryModifierGlyph()}
<CornerDownLeftIcon className="size-2.5" strokeWidth={2.5} />
</kbd>
);
export const EditorToolbar: FC<EditorToolbarProps> = ({
onSave,
onCancel,
@@ -74,45 +61,51 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({
dispatch(actions.setMetadata({ space: next, ...(!next && visibility === Visibility.SPACE ? { visibility: Visibility.PRIVATE } : {}) }));
};
const blockedReasonId = useId();
const commitButton = justSaved ? (
<Button size="sm" disabled>
<Button variant="primary" iconEnd={<CheckIcon />} disabled>
{t("editor.saved")}
<CheckIcon className="size-3.5" strokeWidth={2.5} />
</Button>
) : blockedMessage ? (
// A disabled button fires no pointer events, so a focusable wrapper hosts the tooltip.
<Tooltip>
<TooltipTrigger render={<span className="inline-flex" tabIndex={0} aria-label={blockedMessage} />}>
<Button size="sm" disabled>
{commitLabel}
</Button>
</TooltipTrigger>
<TooltipContent side="top">{blockedMessage}</TooltipContent>
</Tooltip>
// The disabled button stays focusable; its tooltip and its description say why it can't save.
<Tooltip.Root>
<Tooltip.Trigger render={<Button variant="primary" disabled focusableWhenDisabled aria-describedby={blockedReasonId} />}>
{commitLabel}
</Tooltip.Trigger>
<Tooltip.Popup side="top">{blockedMessage}</Tooltip.Popup>
<span id={blockedReasonId} className="mu-visually-hidden">
{blockedMessage}
</span>
</Tooltip.Root>
) : (
// The same trigger stays mounted through the save so the button keeps focus;
// only its tooltip is switched off. Both modifiers save (see
// buildEditorExtensions), so both are announced.
<Tooltip disabled={isSaving}>
<TooltipTrigger render={<Button size="sm" onClick={onSave} disabled={isSaving} aria-keyshortcuts="Meta+Enter Control+Enter" />}>
{/* While saving, a spinner covers the label in the same grid cell so the button keeps its width. */}
<span className="grid place-items-center">
<span className={cn("col-start-1 row-start-1", isSaving && "invisible")}>{commitLabel}</span>
<LoaderIcon className={cn("col-start-1 row-start-1 size-3.5 animate-spin", !isSaving && "invisible")} strokeWidth={2.5} />
</span>
</TooltipTrigger>
<TooltipContent side="top">
<span className="flex items-center gap-1.5">
{commitLabel}
<ShortcutKeys />
</span>
</TooltipContent>
</Tooltip>
<Tooltip.Root disabled={isSaving}>
<Tooltip.Trigger
render={
<Button
variant="primary"
onClick={onSave}
loading={isSaving}
loadingLabel={commitLabel}
aria-keyshortcuts="Meta+Enter Control+Enter"
/>
}
>
{commitLabel}
</Tooltip.Trigger>
{/* The save shortcut shows in the tooltip, so the primary action reads as a plain verb. */}
<Tooltip.Popup side="top" shortcut={`${primaryModifierGlyph()} Enter`}>
{commitLabel}
</Tooltip.Popup>
</Tooltip.Root>
);
return (
// Every control on this rail is 28px, the same box as the sidebar's compose control and nav pills.
<div className="flex w-full min-w-0 flex-row items-center justify-between gap-1">
// md controls with mu-compact: 14px labels and 16px icons at 28px, the sidebar's height.
// The menus they open are portaled outside, so they stay sm.
<div className="mu-compact flex w-full min-w-0 flex-row items-center justify-between gap-1">
<div className="flex min-w-0 flex-1 flex-row items-center justify-start gap-1">
<InsertMenu
isUploading={isUploading}
@@ -136,7 +129,7 @@ export const EditorToolbar: FC<EditorToolbarProps> = ({
<div className="flex shrink-0 flex-row items-center justify-end gap-1">
{onCancel && (
<Button variant="quiet" size="sm" onClick={onCancel} disabled={committing}>
<Button variant="ghost" onClick={onCancel} disabled={committing}>
{t("common.cancel")}
</Button>
)}
@@ -1,18 +1,10 @@
import { Button, Menu, Spinner, Tooltip } from "@usememos/ui";
import { uniqBy } from "lodash-es";
import { CodeXmlIcon, ImageIcon, LinkIcon, LoaderIcon, MapPinIcon, Maximize2Icon, MicIcon, PaperclipIcon, PlusIcon } from "lucide-react";
import { CodeXmlIcon, ImageIcon, LinkIcon, MapPinIcon, Maximize2Icon, MicIcon, PaperclipIcon, PlusIcon } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { LinkMemoDialog, LocationDialog } from "@/components/MemoMetadata";
import type { MapPoint } from "@/components/map/types";
import { useReverseGeocoding } from "@/components/map/useReverseGeocoding";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useDebouncedEffect } from "@/hooks";
import type { MemoRelation } from "@/types/proto/api/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -141,40 +133,46 @@ const InsertMenu = (props: InsertMenuProps) => {
return (
<>
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant="outline" size="icon-compact" disabled={insertionDisabled} aria-label={t("common.add")} />}
>
{isUploading ? (
<LoaderIcon className="size-4 animate-spin" strokeWidth={1.8} />
) : (
<PlusIcon className="size-4" strokeWidth={1.8} />
)}
</DropdownMenuTrigger>
<DropdownMenuContent align="start" size="sm">
<Menu.Root modal={false} size="sm">
<Tooltip.Root>
<Tooltip.Trigger
render={
<Menu.Trigger
render={
<Button
variant="neutral"
size="md"
disabled={insertionDisabled}
aria-label={t("common.add")}
icon={isUploading ? <Spinner label={t("editor.blocks.loading")} /> : <PlusIcon />}
/>
}
/>
}
/>
<Tooltip.Popup>{t("common.add")}</Tooltip.Popup>
</Tooltip.Root>
<Menu.Popup align="start">
{insertItems.map((item) => (
<DropdownMenuItem key={item.key} onClick={item.onClick} disabled={props.isSaving}>
<item.icon />
<Menu.Item key={item.key} onClick={item.onClick} disabled={props.isSaving} icon={<item.icon />}>
{item.label}
</DropdownMenuItem>
</Menu.Item>
))}
{/* How the composer presents itself. Focus mode is absent when a host owns the
editor's presentation; Markdown mode (the editor's source mode) only changes how
the text is edited, so every composer has it. Checked while on, with a corner
label in the composer. The code glyph says this mode shows the markup. */}
<DropdownMenuSeparator />
<Menu.Separator />
{viewToggles && (
<DropdownMenuItem onClick={viewToggles.onToggleFocusMode}>
<Maximize2Icon />
<Menu.Item onClick={viewToggles.onToggleFocusMode} icon={<Maximize2Icon />}>
{t("editor.focus-mode")}
</DropdownMenuItem>
</Menu.Item>
)}
<DropdownMenuCheckboxItem checked={sourceMode.isSourceMode} onCheckedChange={sourceMode.onToggle} closeOnClick indicator="end">
<CodeXmlIcon />
<Menu.CheckboxItem checked={sourceMode.isSourceMode} onCheckedChange={sourceMode.onToggle} closeOnClick icon={<CodeXmlIcon />}>
{t("editor.markdown-mode")}
</DropdownMenuCheckboxItem>
</DropdownMenuContent>
</DropdownMenu>
</Menu.CheckboxItem>
</Menu.Popup>
</Menu.Root>
{/* Hidden file input */}
<input
@@ -1,8 +1,7 @@
import { AudioWaveformIcon, LoaderCircleIcon, SquareIcon, XIcon } from "lucide-react";
import { Button, Spinner, Tooltip } from "@usememos/ui";
import { AudioWaveformIcon, SquareIcon, XIcon } from "lucide-react";
import type { FC } from "react";
import { formatAudioTime } from "@/components/MemoMetadata/Attachment/attachmentHelpers";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
import { useAudioWaveform } from "../hooks/useAudioWaveform";
@@ -34,64 +33,70 @@ export const AudioRecorderPanel: FC<AudioRecorderPanelProps> = ({
return (
<div
className={cn(
"flex w-full items-center justify-between gap-2 rounded-lg border border-border bg-muted/30 px-2.5 py-1.5",
"dark:bg-muted/20",
"flex w-full items-center justify-between gap-2 rounded-mu-lg border border-mu-line bg-mu-well/30 px-2.5 py-1.5",
"dark:bg-mu-well/20",
)}
>
<div className="flex min-w-0 flex-1 items-center gap-2">
{isRequestingPermission || isTranscribing ? (
<LoaderCircleIcon className="size-3.5 shrink-0 animate-spin text-muted-foreground" aria-hidden />
) : null}
<span className="sr-only">{srStatusText}</span>
{isRequestingPermission || isTranscribing ? <Spinner size="sm" aria-hidden className="shrink-0 text-mu-ink-muted" /> : null}
<span className="mu-visually-hidden">{srStatusText}</span>
<VoiceWaveform levels={waveformLevels} className="max-w-[200px] overflow-hidden" />
<span className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground">
<span className="shrink-0 font-mono mu-caption tabular-nums text-mu-ink-muted">
{isTranscribing ? t("editor.audio-recorder.transcribing") : formatAudioTime(elapsedSeconds)}
</span>
</div>
<div className="flex shrink-0 items-center gap-1 border-s border-border/60 ps-2">
<Button
type="button"
variant="ghost"
size="icon"
className="rounded-full"
onClick={onCancel}
disabled={isTranscribing}
aria-label={t("common.cancel")}
>
<XIcon className="size-4" />
</Button>
{canTranscribe && (
<Tooltip>
<TooltipTrigger render={<span className="-ms-2 inline-flex" />}>
<div className="flex shrink-0 items-center gap-1 border-s border-mu-line/60 ps-2">
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
type="button"
variant="ghost"
size="icon"
className="rounded-full"
onClick={onTranscribe}
disabled={isTranscribeDisabled}
aria-label={t("editor.audio-recorder.transcribe")}
>
<AudioWaveformIcon className="size-4" />
</Button>
</TooltipTrigger>
<TooltipContent side="top">
onClick={onCancel}
disabled={isTranscribing}
aria-label={t("common.cancel")}
icon={<XIcon />}
/>
}
/>
<Tooltip.Popup side="top">{t("common.cancel")}</Tooltip.Popup>
</Tooltip.Root>
{canTranscribe && (
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
type="button"
variant="ghost"
onClick={onTranscribe}
disabled={isTranscribeDisabled}
focusableWhenDisabled
aria-label={t("editor.audio-recorder.transcribe")}
icon={<AudioWaveformIcon />}
/>
}
/>
<Tooltip.Popup side="top">
<p>{t("editor.audio-recorder.transcribe")}</p>
</TooltipContent>
</Tooltip>
</Tooltip.Popup>
</Tooltip.Root>
)}
<Button
type="button"
variant="destructive"
size="icon"
className="rounded-full"
onClick={onStop}
disabled={isRequestingPermission || isTranscribing}
aria-label={t("editor.audio-recorder.stop")}
>
<SquareIcon className="size-4" />
</Button>
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
type="button"
variant="primary"
onClick={onStop}
disabled={isRequestingPermission || isTranscribing}
aria-label={t("editor.audio-recorder.stop")}
icon={<SquareIcon />}
/>
}
/>
<Tooltip.Popup side="top">{t("editor.audio-recorder.stop")}</Tooltip.Popup>
</Tooltip.Root>
</div>
</div>
);
@@ -1,7 +1,7 @@
import { buttonClasses } from "@usememos/ui";
import { isEqual } from "lodash-es";
import { ListTodoIcon, ZapIcon } from "lucide-react";
import { type RefObject, useEffect, useId, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { MAX_MEMO_SUGGESTIONS, type MemoSuggestion, type SuggestionItem } from "@/lib/memo-suggestions";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
@@ -23,9 +23,9 @@ export function SuggestionsBar({
const labelId = useId();
if (!suggestions.length) return null;
return (
<div role="group" aria-labelledby={labelId} className="flex w-full items-start gap-2 text-ui">
<span id={labelId} className="inline-flex h-6 shrink-0 items-center gap-1.5 text-muted-foreground/70">
<ZapIcon className="size-3.5" aria-hidden />
<div role="group" aria-labelledby={labelId} className="flex w-full items-start gap-2 mu-caption">
<span id={labelId} className="inline-flex h-6 shrink-0 items-center gap-1.5 text-mu-ink-muted/70">
<ZapIcon className="mu-icon-sm" aria-hidden />
{t("editor.suggestions")}
</span>
<div className="flex min-w-0 flex-1 flex-wrap gap-1.5">
@@ -36,8 +36,8 @@ export function SuggestionsBar({
disabled={disabled}
aria-label={suggestion.accessibleLabel ?? suggestion.label}
className={cn(
buttonVariants({ variant: "quiet", size: "sm" }),
"h-6 max-w-full gap-1 border border-dashed border-muted-foreground/30 px-1.5 text-muted-foreground hover:border-muted-foreground/50 has-[>svg]:px-1.5",
buttonClasses({ variant: "ghost", size: "sm" }),
"h-6 max-w-full gap-1 border border-dashed border-mu-ink-muted/30 px-1.5 text-mu-ink-muted hover:border-mu-ink-muted/50 has-[>svg]:px-1.5",
)}
onClick={() => onAccept(suggestion.id)}
>
@@ -1,13 +1,14 @@
import { Button, Tooltip } from "@usememos/ui";
import { Minimize2Icon, XIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useTranslate } from "@/utils/i18n";
import { FOCUS_MODE_STYLES } from "../constants";
import type { FocusModeExitButtonProps, FocusModeOverlayProps } from "../types";
export function FocusModeOverlay({ isActive, onToggle }: FocusModeOverlayProps) {
const t = useTranslate();
if (!isActive) return null;
return <div className={FOCUS_MODE_STYLES.backdrop} onClick={onToggle} aria-label="Exit focus mode" />;
return <div className={FOCUS_MODE_STYLES.backdrop} onClick={onToggle} aria-label={t("editor.exit-focus-mode")} />;
}
/** Leaves the frame the editor sits in: minimizes inline focus mode, or closes a host-owned frame. */
@@ -17,8 +18,9 @@ export function FocusModeExitButton({ action, onExit }: FocusModeExitButtonProps
const Icon = action === "close" ? XIcon : Minimize2Icon;
return (
<Button variant="quiet" size="icon-compact" aria-label={label} title={label} onClick={onExit}>
<Icon className="size-4" strokeWidth={1.8} />
</Button>
<Tooltip.Root>
<Tooltip.Trigger render={<Button variant="ghost" size="sm" aria-label={label} onClick={onExit} icon={<Icon />} />} />
<Tooltip.Popup>{label}</Tooltip.Popup>
</Tooltip.Root>
);
}
@@ -1,6 +1,6 @@
import { Popover } from "@usememos/ui";
import { type FC, useId, useRef, useState } from "react";
import { MEMO_TIME_CONTROL_CLASSES } from "@/components/MemoView/constants";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import i18n from "@/i18n";
import { useTranslate } from "@/utils/i18n";
import { useEditorContext, useEditorSelector } from "../state";
@@ -45,14 +45,14 @@ const TimestampInput: FC<{
return (
<div className="space-y-1">
<label htmlFor={id} className="text-xs font-medium text-muted-foreground">
<label htmlFor={id} className="mu-label-sm text-mu-ink-muted">
{label}
{value !== initialValue.current && <span className="text-primary ml-0.5">*</span>}
{value !== initialValue.current && <span className="text-mu-primary ml-0.5">*</span>}
</label>
<input
id={id}
type="text"
className="block w-full rounded-md border border-border bg-background px-2 py-1 text-sm font-mono data-[invalid=true]:border-destructive"
className="block w-full rounded-mu-md border border-mu-line bg-mu-canvas px-2 py-1 mu-body font-mono data-[invalid=true]:border-mu-danger"
data-invalid={invalid}
aria-invalid={invalid}
placeholder={DATETIME_FORMAT}
@@ -77,12 +77,12 @@ export const TimestampPopover: FC = () => {
const createTime = useEditorSelector((s) => s.timestamps.createTime);
const updateTime = useEditorSelector((s) => s.timestamps.updateTime);
if (!createTime) return <span className="shrink-0 whitespace-nowrap text-ui text-muted-foreground select-none">{nowLabel()}</span>;
if (!createTime) return <span className="shrink-0 whitespace-nowrap mu-caption text-mu-ink-muted select-none">{nowLabel()}</span>;
return (
<Popover>
<PopoverTrigger render={<button type="button" className={MEMO_TIME_CONTROL_CLASSES} />}>{formatDate(createTime)}</PopoverTrigger>
<PopoverContent align="start" className="w-auto p-2 pt-1 space-y-1">
<Popover.Root>
<Popover.Trigger render={<button type="button" className={MEMO_TIME_CONTROL_CLASSES} />}>{formatDate(createTime)}</Popover.Trigger>
<Popover.Popup align="start" className="w-auto">
<TimestampInput
label={t("common.created-at")}
date={createTime}
@@ -93,7 +93,7 @@ export const TimestampPopover: FC = () => {
date={updateTime}
onChange={(d) => dispatch(actions.setTimestamps({ updateTime: d }))}
/>
</PopoverContent>
</Popover>
</Popover.Popup>
</Popover.Root>
);
};
@@ -24,7 +24,7 @@ export const VoiceWaveform: FC<VoiceWaveformProps> = ({ levels, className }) =>
return (
<span
key={`bar-${i}`}
className="w-[2px] shrink-0 rounded-full bg-muted-foreground transition-[height,opacity] duration-75 ease-out"
className="w-[2px] shrink-0 rounded-full bg-mu-ink-muted transition-[height,opacity] duration-75 ease-out"
style={{ height: `${h}px`, opacity }}
/>
);
@@ -1,7 +1,7 @@
export const FOCUS_MODE_STYLES = {
backdrop: "fixed inset-0 bg-overlay/20 backdrop-blur-sm z-overlay",
backdrop: "fixed inset-0 bg-mu-overlay backdrop-blur-sm z-(--mu-layer-overlay)",
container: {
base: "fixed z-50 w-auto max-w-3xl mx-auto shadow-2xl border-border h-auto overflow-y-auto pt-2 pb-4 sm:px-6",
base: "fixed z-50 w-auto max-w-3xl mx-auto shadow-mu-pop border-mu-line h-auto overflow-y-auto pt-2 pb-4 sm:px-6",
spacing: "top-2 left-2 right-2 bottom-2 sm:top-4 sm:left-4 sm:right-4 sm:bottom-4 md:top-8 md:left-8 md:right-8 md:bottom-8",
},
/** The view transition name the session's frame carries while focus mode toggles (see editor.css). */
+38 -20
View File
@@ -22,11 +22,11 @@
flex: 1 0 auto;
}
& .memo-editor-root {
caret-color: var(--foreground);
caret-color: var(--mu-ink);
outline: none;
}
& .memo-editor-root ::selection {
background: var(--accent);
background: var(--mu-selection);
}
}
@@ -40,7 +40,7 @@
animation-duration: 280ms;
animation-timing-function: cubic-bezier(0.2, 0, 0, 1);
overflow: clip;
border-radius: var(--radius);
border-radius: var(--mu-radius-lg);
}
::view-transition-old(memo-focus-mode),
::view-transition-new(memo-focus-mode) {
@@ -90,7 +90,7 @@
left: 0;
width: 2px;
border-radius: 999px;
background: var(--primary);
background: var(--mu-primary);
}
.memo-upload-anchor-rail::after {
@@ -99,9 +99,9 @@
left: -3px;
width: 8px;
height: 8px;
border: 2px solid var(--card);
border: 2px solid var(--mu-surface);
border-radius: 999px;
background: var(--primary);
background: var(--mu-primary);
content: "";
transform: translateY(-50%);
}
@@ -110,16 +110,16 @@
display: inline-flex;
align-items: center;
gap: 0.375rem;
border-radius: calc(var(--radius) - 2px);
background: color-mix(in oklab, var(--primary) 8%, transparent);
border-radius: var(--mu-radius-md);
background: color-mix(in oklab, var(--mu-primary) 8%, transparent);
padding: 0.25rem 0.5rem;
color: var(--primary);
color: var(--mu-primary);
font-weight: 500;
}
.memo-upload-anchor[data-status="failed"] .memo-upload-anchor-badge {
background: color-mix(in oklab, var(--destructive) 8%, transparent);
color: var(--destructive);
background: color-mix(in oklab, var(--mu-danger) 8%, transparent);
color: var(--mu-danger);
}
.memo-upload-anchor-spinner {
@@ -137,16 +137,16 @@
}
.memo-upload-anchor-action {
border-radius: calc(var(--radius) - 2px);
border-radius: var(--mu-radius-md);
padding: 0.25rem 0.5rem;
color: var(--muted-foreground);
color: var(--mu-ink-muted);
font-weight: 500;
}
.memo-upload-anchor-action:hover,
.memo-upload-anchor-action:focus-visible {
background: var(--accent);
color: var(--accent-foreground);
background: var(--mu-hover);
color: var(--mu-ink);
outline: none;
}
@@ -156,16 +156,34 @@
}
}
/* The editor portals its own UI outside the composer. Match the app's floating
surfaces here without changing document typography or package internals. */
/* The editor portals its own UI outside the composer. Its menus, toolbars and cards take the
@usememos/ui popup surface and its tooltips the package's tooltip, so they line up with the
app's own popups, without changing document typography or package internals. */
.mbe-ui:is(.mbe-menu, .mbe-toolbar, .mbe-image-toolbar, .mbe-link-card, .mbe-input-popover) {
@apply rounded-lg border-border/70 bg-popover text-popover-foreground text-ui font-normal leading-5 tracking-normal shadow-float;
border: 0;
border-radius: var(--mu-radius-xl);
background: var(--mu-surface);
box-shadow: var(--mu-shadow-pop);
color: var(--mu-ink);
font: 400 13px / 18px var(--mu-font-sans);
letter-spacing: 0;
}
.mbe-ui.mbe-menu {
@apply p-1.5;
padding: var(--mu-space-1);
}
.mbe-ui.mbe-tooltip {
@apply max-w-[min(16rem,calc(100vw-1rem))] whitespace-normal rounded-md border border-border/70 bg-popover px-2 py-1 text-xs font-normal leading-4 tracking-normal text-popover-foreground text-pretty [overflow-wrap:anywhere] shadow-md;
max-width: min(var(--mu-tooltip-width), calc(100vw - 1rem));
padding: var(--mu-space-1) var(--mu-space-2);
border: 0;
border-radius: var(--mu-radius-md);
background: var(--mu-primary);
box-shadow: none;
color: var(--mu-on-primary);
font: 500 13px / 18px var(--mu-font-sans);
letter-spacing: 0;
white-space: normal;
text-wrap: pretty;
overflow-wrap: anywhere;
}
@@ -1,6 +1,6 @@
import { ConnectError } from "@connectrpc/connect";
import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "react-hot-toast";
import { showErrorToast, toast } from "@/lib/toast";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import { useTranslate } from "@/utils/i18n";
import { transcriptionService } from "../services";
@@ -23,15 +23,15 @@ export const useAttachmentTranscription = (onText: (text: string) => void) => {
const text = (await transcriptionService.transcribeAttachment(attachment, controller.signal)).trim();
if (controller.signal.aborted) return;
if (!text) {
toast.error(t("editor.audio-recorder.transcribe-empty"));
showErrorToast(t("editor.audio-recorder.transcribe-empty"));
return;
}
onText(text);
toast.success(t("editor.audio-recorder.transcribe-success"));
toast.add({ title: t("editor.audio-recorder.transcribe-success"), type: "success" });
} catch (error) {
if (!controller.signal.aborted) {
// Server errors explain themselves; download and network failures get the translated fallback.
toast.error((error instanceof ConnectError && error.rawMessage) || t("editor.audio-recorder.transcribe-error"));
showErrorToast((error instanceof ConnectError && error.rawMessage) || t("editor.audio-recorder.transcribe-error"));
}
} finally {
request.current = undefined;
@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from "react";
import { useTranslate } from "@/utils/i18n";
import type { LocalFile } from "../types/attachment";
import { useBlobUrls } from "./useBlobUrls";
@@ -54,6 +55,7 @@ function createRecordedFile(blob: Blob, mimeType: string): File {
* caller.
*/
export const useAudioRecorder = (options: UseAudioRecorderOptions) => {
const t = useTranslate();
const [status, setStatus] = useState<AudioRecorderStatus>("idle");
const [elapsedSeconds, setElapsedSeconds] = useState(0);
const [error, setError] = useState<string | undefined>(undefined);
@@ -105,7 +107,7 @@ export const useAudioRecorder = (options: UseAudioRecorderOptions) => {
if (!isSupported) {
setStatus("unsupported");
setError("Audio recording is not supported in this browser.");
setError(t("editor.recording-unsupported"));
return;
}
@@ -129,7 +131,7 @@ export const useAudioRecorder = (options: UseAudioRecorderOptions) => {
typeof MediaRecorder === "undefined"
) {
setStatus("unsupported");
setError("Audio recording is not supported in this browser.");
setError(t("editor.recording-unsupported"));
return;
}
@@ -219,7 +221,7 @@ export const useAudioRecorder = (options: UseAudioRecorderOptions) => {
error instanceof DOMException && (error.name === "NotAllowedError" || error.name === "PermissionDeniedError");
setStatus("error");
setError(permissionDenied ? "Microphone permission was denied." : "Failed to start audio recording.");
setError(permissionDenied ? t("editor.microphone-denied") : t("editor.recording-failed"));
resetRecorderRefs();
}
};
@@ -1,7 +1,7 @@
import { uniqBy } from "lodash-es";
import { type RefObject, useCallback, useEffect, useRef, useState } from "react";
import { toast } from "react-hot-toast";
import { v4 as uuidv4 } from "uuid";
import { showErrorToast } from "@/lib/toast";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import { isImage } from "@/utils/attachment";
import { useTranslate } from "@/utils/i18n";
@@ -187,7 +187,7 @@ export const useInlineImageUpload = (editorRef: RefObject<EditorController | nul
if (job.entries.some((entry) => !entry.attachment)) {
editorRef.current?.updateUploadAnchor(descriptorFor(job, "failed"));
toast.error(errorService.getErrorMessage(lastError) || t("editor.insert-menu.image-upload-failed"));
showErrorToast(errorService.getErrorMessage(lastError) || t("editor.insert-menu.image-upload-failed"));
return;
}
@@ -1,12 +1,12 @@
import { Code, ConnectError } from "@connectrpc/connect";
import { useQueryClient } from "@tanstack/react-query";
import { useCallback } from "react";
import { toast } from "react-hot-toast";
import { useNewMemo } from "@/contexts/NewMemoContext";
import { attachmentKeys } from "@/hooks/useAttachmentQueries";
import { memoDetailQueryOptions, useCreateMemo, useUpdateMemo } from "@/hooks/useMemoQueries";
import { userKeys } from "@/hooks/useUserQueries";
import { handleError } from "@/lib/error";
import { showErrorToast, toast } from "@/lib/toast";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import type { Visibility } from "@/types/proto/api/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -59,7 +59,7 @@ export function useMemoSave({
if (state.ui.justSaved) return;
const { valid, reason, detail } = validationService.canSave(state);
if (!valid) {
toast.error(reason ? t(reason, detail ? { url: detail } : undefined) : t("editor.validation.cannot-save"));
showErrorToast(reason ? t(reason, detail ? { url: detail } : undefined) : t("editor.validation.cannot-save"));
return;
}
@@ -116,7 +116,7 @@ export function useMemoSave({
);
if (!result.hasChanges) {
toast.error(t("editor.no-changes-detected"));
showErrorToast(t("editor.no-changes-detected"));
onCancel?.();
return;
}
@@ -125,7 +125,7 @@ export function useMemoSave({
discardDraft();
// A moved memo may leave the feed it was edited in; say where it went.
if (result.moved) {
toast.success(t("memo.moved"));
toast.add({ title: t("memo.moved"), type: "success" });
}
// Hosts that close after saving (edit, comment) hold a brief "Saved"
@@ -160,7 +160,7 @@ export function useMemoSave({
void queryClient.invalidateQueries({ queryKey: attachmentKeys.lists() });
void queryClient.invalidateQueries({ queryKey: userKeys.stats() });
}
handleError(error, toast.error, {
handleError(error, showErrorToast, {
context: "Failed to save memo",
fallbackMessage: errorService.getErrorMessage(error),
});
@@ -1,4 +1,5 @@
import { getQuotaExceededMessage } from "@/lib/error";
import { translate } from "@/utils/i18n";
export const errorService = {
getErrorMessage(error: unknown): string {
@@ -8,18 +9,18 @@ export const errorService = {
}
if (error && typeof error === "object" && "rawMessage" in error) {
return (error as { rawMessage?: string }).rawMessage || "An error occurred";
return (error as { rawMessage?: string }).rawMessage || translate("common.error-occurred");
}
// Handle ConnectError or errors with details property
if (error && typeof error === "object" && "details" in error) {
return (error as { details?: string }).details || "An error occurred";
return (error as { details?: string }).details || translate("common.error-occurred");
}
if (error instanceof Error) {
return error.message;
}
return "An unknown error occurred";
return translate("common.unknown-error");
},
};
@@ -1,3 +1,4 @@
import type { ReactNode } from "react";
import type { MemoSuggestion } from "@/lib/memo-suggestions";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import type { Location, Memo, Visibility } from "@/types/proto/api/memo_service_pb";
@@ -12,6 +13,8 @@ export interface EditSessionProps {
draftKey: string;
/** Inside a card that is the frame already: no background, border or padding of its own outside focus mode. */
frameless?: boolean;
/** Leads the timestamp row, before the time: the card's creator while it edits in place. */
timestampLead?: ReactNode;
placeholder?: string;
/** Existing memo to edit; the session starts from it and persists no draft. */
memo?: Memo;
@@ -41,17 +41,17 @@ const LinkMetadataCard = ({ url, fallback, enabled = true }: LinkMetadataCardPro
target="_blank"
rel="noopener noreferrer"
className={cn(
"group my-0 mb-2 flex w-full max-w-full overflow-hidden rounded-md border border-border bg-muted/20 text-foreground no-underline transition-colors",
"hover:border-primary/35 hover:bg-accent/20",
"group my-0 mb-2 flex w-full max-w-full overflow-hidden rounded-mu-md border border-mu-line bg-mu-well/20 text-mu-ink no-underline transition-colors",
"hover:border-mu-primary/35 hover:bg-mu-hover/20",
)}
>
<span className="flex min-w-0 flex-1 flex-col gap-0.5 px-2.5 py-2 sm:gap-1 sm:px-3 sm:py-2.5">
{hostname && <span className="truncate text-[11px] leading-4 text-muted-foreground sm:text-xs">{hostname}</span>}
{title && <span className="line-clamp-2 text-sm font-medium leading-5 text-foreground">{title}</span>}
{description && <span className="line-clamp-1 text-xs leading-4 text-muted-foreground sm:line-clamp-2">{description}</span>}
{hostname && <span className="truncate mu-caption text-mu-ink-muted">{hostname}</span>}
{title && <span className="line-clamp-2 mu-label text-mu-ink">{title}</span>}
{description && <span className="line-clamp-1 mu-caption text-mu-ink-muted sm:line-clamp-2">{description}</span>}
</span>
{image && !imageFailed && (
<span className="flex w-24 shrink-0 items-center border-s border-border/70 bg-muted/40 sm:w-40">
<span className="flex w-24 shrink-0 items-center border-s border-mu-line/70 bg-mu-well/40 sm:w-40">
<span className="aspect-[1.91/1] w-full overflow-hidden">
<img
src={image}
@@ -113,7 +113,7 @@ const MemoContentViewImpl = (props: MemoContentViewProps) => {
};
return (
<div className={`w-full flex flex-col justify-start items-start text-foreground ${className || ""}`}>
<div className={`w-full flex flex-col justify-start items-start text-mu-ink ${className || ""}`}>
<div
ref={contentRef}
data-memo-content
+12 -8
View File
@@ -1,3 +1,4 @@
import { Button, Tooltip } from "@usememos/ui";
import dayjs from "dayjs";
import { isEqual } from "lodash-es";
import {
@@ -18,7 +19,6 @@ import {
import type { ReactNode } from "react";
import { useLocation } from "react-router-dom";
import MemoViewIcon from "@/components/MemoViewIcon";
import { Button } from "@/components/ui/button";
import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { type FilterFactor, getMemoFilterKey, type MemoFilter, useMemoFilterContext } from "@/contexts/MemoFilterContext";
import useCurrentUser from "@/hooks/useCurrentUser";
@@ -102,17 +102,18 @@ interface FilterChipProps {
/** One chip for anything narrowing the list, so a view, a tag and a day are announced the same way. */
const FilterChip = ({ icon: Icon, customIcon, label, onRemove, onEdit }: FilterChipProps) => {
const t = useTranslate();
const body = (
<>
{customIcon ?? (Icon && <Icon className="w-3.5 h-3.5 text-muted-foreground shrink-0" />)}
<span className={cn("text-foreground/80 truncate", onEdit ? "font-mono text-xs max-w-64" : "font-medium max-w-32")}>{label}</span>
{customIcon ?? (Icon && <Icon className="mu-icon-sm text-mu-ink-muted shrink-0" />)}
<span className={cn("text-mu-ink/80 truncate", onEdit ? "font-mono mu-caption max-w-64" : "font-medium max-w-32")}>{label}</span>
</>
);
return (
<div
className={cn(
"group inline-flex min-w-0 max-w-full items-center gap-1.5 h-7 px-2.5",
"bg-accent/50 hover:bg-accent border border-border/50 rounded-full text-sm transition-all duration-200 hover:shadow-sm",
"bg-mu-hover/50 hover:bg-mu-hover border border-mu-line/50 rounded-full mu-body transition-all duration-200 hover:shadow-mu-key",
)}
>
{onEdit ? (
@@ -129,9 +130,12 @@ const FilterChip = ({ icon: Icon, customIcon, label, onRemove, onEdit }: FilterC
body
)}
<span className="ml-0.5 -mr-1">
<Button variant="ghost" size="icon-sm" onClick={onRemove} aria-label="Remove filter">
<XIcon className="w-3 h-3" />
</Button>
<Tooltip.Root>
<Tooltip.Trigger
render={<Button variant="ghost" size="xs" onClick={onRemove} aria-label={t("memo.filters.remove")} icon={<XIcon />} />}
/>
<Tooltip.Popup>{t("memo.filters.remove")}</Tooltip.Popup>
</Tooltip.Root>
</span>
</div>
);
@@ -164,7 +168,7 @@ const MemoFilters = ({ className }: { className?: string }) => {
const view = memoViews.find((item) => getMemoViewId(item.name) === memoView);
return view?.title
? {
customIcon: <MemoViewIcon icon={view.icon} className="size-3.5 text-sm text-muted-foreground" />,
customIcon: <MemoViewIcon icon={view.icon} className="mu-icon-sm text-sm text-mu-ink-muted" />,
label: view.title,
}
: null;
@@ -17,7 +17,7 @@ const AttachmentCard = ({ attachment, onClick, className }: AttachmentCardProps)
<img
src={getAttachmentThumbnailUrl(attachment)}
alt={attachment.filename}
className={cn("w-full h-full object-cover rounded-lg cursor-pointer", className)}
className={cn("w-full h-full object-cover rounded-mu-lg cursor-pointer", className)}
onClick={onClick}
onError={(e) => {
const target = e.currentTarget;
@@ -32,11 +32,11 @@ const AttachmentCard = ({ attachment, onClick, className }: AttachmentCardProps)
}
if (attachmentType === "video/*") {
return <video src={sourceUrl} className={cn("w-full h-full object-cover rounded-lg", className)} controls preload="none" />;
return <video src={sourceUrl} className={cn("w-full h-full object-cover rounded-mu-lg", className)} controls preload="none" />;
}
if (attachmentType === "audio/*") {
return <audio src={sourceUrl} className={cn("w-full rounded-lg", className)} controls preload="none" />;
return <audio src={sourceUrl} className={cn("w-full rounded-mu-lg", className)} controls preload="none" />;
}
return null;
@@ -1,3 +1,4 @@
import { Button, Tooltip } from "@usememos/ui";
import {
ChevronDownIcon,
ChevronUpIcon,
@@ -5,7 +6,6 @@ import {
FileIcon,
FileTextIcon,
ImagePlusIcon,
LoaderIcon,
PauseIcon,
PlayIcon,
XIcon,
@@ -15,14 +15,13 @@ import type { AttachmentItem, LocalFile } from "@/components/MemoEditor/edit/typ
import { getAudioRecordingTimeLabel, toAttachmentItems } from "@/components/MemoEditor/edit/types/attachment";
import MetadataSection, {
METADATA_ROW_BOX_CLASSES,
METADATA_ROW_CONTENT_TEXT_CLASSES,
METADATA_ROW_CONTROLS_CLASSES,
METADATA_ROW_SLOT_BUTTON_CLASSES,
METADATA_ROW_SLOT_CLASSES,
METADATA_ROW_TEXT_CLASSES,
MetadataRowDetail,
} from "@/components/MemoMetadata/MetadataSection";
import PreviewImageDialog from "@/components/PreviewImageDialog";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import { formatFileSize, getFileTypeLabel } from "@/utils/format";
@@ -60,6 +59,7 @@ const AttachmentItemActions: FC<{
canMoveUp?: boolean;
canMoveDown?: boolean;
}> = ({ transcriptionAction, placementAction, onRemove, onMoveUp, onMoveDown, canMoveUp = true, canMoveDown = true }) => {
const t = useTranslate();
const stopPropagation = (event: MouseEvent) => {
event.stopPropagation();
};
@@ -68,77 +68,94 @@ const AttachmentItemActions: FC<{
<div className={METADATA_ROW_CONTROLS_CLASSES}>
{transcriptionAction && (
<Button
variant="quiet"
variant="ghost"
size="sm"
disabled={transcriptionAction.disabled}
loading={transcriptionAction.busy}
loadingLabel={transcriptionAction.label}
onClick={(event) => {
stopPropagation(event);
transcriptionAction.onClick();
}}
icon={<FileTextIcon />}
>
{transcriptionAction.busy ? <LoaderIcon className="size-3.5 animate-spin" /> : <FileTextIcon className="size-3.5" />}
{transcriptionAction.label}
</Button>
)}
{placementAction && (
<Button
variant="quiet"
variant="ghost"
size="sm"
onClick={(event) => {
stopPropagation(event);
placementAction.onClick();
}}
disabled={placementAction.disabled}
icon={<ImagePlusIcon />}
>
<ImagePlusIcon className="size-3.5" strokeWidth={1.8} />
{placementAction.label}
</Button>
)}
{onMoveUp && (
<Button
variant="quiet"
size="icon-sm"
onClick={(event) => {
stopPropagation(event);
onMoveUp();
}}
disabled={!canMoveUp}
title="Move up"
aria-label="Move attachment up"
>
<ChevronUpIcon className="size-3.5" strokeWidth={1.8} />
</Button>
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
variant="ghost"
size="xs"
onClick={(event) => {
stopPropagation(event);
onMoveUp();
}}
disabled={!canMoveUp}
aria-label={t("editor.attachments.move-up")}
icon={<ChevronUpIcon />}
/>
}
/>
<Tooltip.Popup>{t("editor.attachments.move-up")}</Tooltip.Popup>
</Tooltip.Root>
)}
{onMoveDown && (
<Button
variant="quiet"
size="icon-sm"
onClick={(event) => {
stopPropagation(event);
onMoveDown();
}}
disabled={!canMoveDown}
title="Move down"
aria-label="Move attachment down"
>
<ChevronDownIcon className="size-3.5" strokeWidth={1.8} />
</Button>
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
variant="ghost"
size="xs"
onClick={(event) => {
stopPropagation(event);
onMoveDown();
}}
disabled={!canMoveDown}
aria-label={t("editor.attachments.move-down")}
icon={<ChevronDownIcon />}
/>
}
/>
<Tooltip.Popup>{t("editor.attachments.move-down")}</Tooltip.Popup>
</Tooltip.Root>
)}
{onRemove && (
<Button
variant="quiet"
size="icon-sm"
onClick={(event) => {
stopPropagation(event);
onRemove();
}}
title="Remove"
aria-label="Remove attachment"
>
<XIcon className="size-3.5" strokeWidth={1.8} />
</Button>
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
variant="ghost"
size="xs"
onClick={(event) => {
stopPropagation(event);
onRemove();
}}
aria-label={t("editor.attachments.remove")}
icon={<XIcon />}
/>
}
/>
<Tooltip.Popup>{t("editor.attachments.remove")}</Tooltip.Popup>
</Tooltip.Root>
)}
</div>
);
@@ -171,7 +188,7 @@ const AttachmentItemCard: FC<{
const { category, filename, thumbnailUrl, mimeType, size, sourceUrl, isVoiceNote, audioMeta } = item;
const audioRef = useRef<HTMLAudioElement>(null);
const [isPlaying, setIsPlaying] = useState(false);
const fileTypeLabel = item.category === "motion" ? "Live Photo" : getFileTypeLabel(mimeType);
const fileTypeLabel = item.category === "motion" ? t("attachment-library.labels.live-photo") : getFileTypeLabel(mimeType);
const isPreviewable = category === "image" || category === "video" || category === "motion";
const recordingTimeLabel = isVoiceNote ? getAudioRecordingTimeLabel(filename) : undefined;
const titleLabel =
@@ -200,7 +217,7 @@ const AttachmentItemCard: FC<{
return (
<div className={METADATA_ROW_BOX_CLASSES} aria-busy={isUploadingInline || undefined}>
<div className={cn(METADATA_ROW_SLOT_CLASSES, "relative overflow-hidden rounded-[5px] bg-muted/40")}>
<div className={cn(METADATA_ROW_SLOT_CLASSES, "relative overflow-hidden rounded-[5px] bg-mu-well/40")}>
{(category === "image" || category === "motion") && thumbnailUrl ? (
<div
onClick={(event) => {
@@ -208,7 +225,7 @@ const AttachmentItemCard: FC<{
onPreview?.();
}}
className={cn("size-full overflow-hidden", isPreviewable ? "cursor-pointer" : "cursor-default")}
aria-label={`Preview ${filename}`}
aria-label={t("common.preview-name", { name: filename })}
>
<img src={thumbnailUrl} alt="" className="size-full object-cover" loading="lazy" decoding="async" />
</div>
@@ -221,11 +238,7 @@ const AttachmentItemCard: FC<{
aria-pressed={isPlaying}
aria-label={isPlaying ? t("editor.audio-recorder.pause-recording") : t("editor.audio-recorder.play-recording")}
>
{isPlaying ? (
<PauseIcon className="size-3.5" strokeWidth={1.8} />
) : (
<PlayIcon className="size-3.5 translate-x-[0.5px]" strokeWidth={1.8} />
)}
{isPlaying ? <PauseIcon className="mu-icon-sm" /> : <PlayIcon className="mu-icon-sm translate-x-[0.5px]" />}
</button>
<audio
ref={audioRef}
@@ -244,23 +257,23 @@ const AttachmentItemCard: FC<{
onPreview?.();
}}
className={METADATA_ROW_SLOT_BUTTON_CLASSES}
aria-label={`Preview ${filename}`}
aria-label={t("common.preview-name", { name: filename })}
>
<PlayIcon className="size-3.5 translate-x-[0.5px]" strokeWidth={1.8} />
<PlayIcon className="mu-icon-sm translate-x-[0.5px]" />
</button>
) : category === "audio" ? (
<FileAudioIcon className="size-3.5 text-muted-foreground" strokeWidth={1.8} />
<FileAudioIcon className="mu-icon-sm text-mu-ink-muted" />
) : (
<FileIcon className="size-3.5 text-muted-foreground" strokeWidth={1.8} />
<FileIcon className="mu-icon-sm text-mu-ink-muted" />
)}
{category === "motion" && (
<span className="absolute inset-x-0 bottom-0 bg-black/70 text-center text-[7px] font-semibold uppercase tracking-wide text-white">
Live
<span className="absolute inset-x-0 bottom-0 bg-black/70 text-center text-[7px] font-medium uppercase tracking-wide text-white">
{t("attachment-library.labels.live")}
</span>
)}
</div>
<span className={METADATA_ROW_TEXT_CLASSES} title={filename}>
<span className={METADATA_ROW_CONTENT_TEXT_CLASSES} title={filename}>
{titleLabel}
</span>
@@ -1,21 +1,22 @@
import { buttonClasses } from "@usememos/ui";
import { DownloadIcon, ExternalLinkIcon, FileIcon, PlayIcon } from "lucide-react";
import type { PropsWithChildren } from "react";
import type { KeyboardEvent, PropsWithChildren } from "react";
import { useMemo } from "react";
import MotionPhotoPreview from "@/components/MotionPhotoPreview";
import { buttonVariants } from "@/components/ui/button";
import VideoPoster from "@/components/VideoPoster";
import { cn } from "@/lib/utils";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import { getAttachmentUrl, isImage } from "@/utils/attachment";
import { useTranslate } from "@/utils/i18n";
import type { AttachmentVisualItem, PreviewMediaItem } from "@/utils/media-item";
import { buildAttachmentVisualItems } from "@/utils/media-item";
import {
METADATA_ROW_BOX_CLASSES,
METADATA_ROW_CLASSES,
METADATA_ROW_CONTENT_TEXT_CLASSES,
METADATA_ROW_CONTROLS_CLASSES,
METADATA_ROW_HINT_CLASSES,
METADATA_ROW_LABEL_CLASSES,
METADATA_ROW_TEXT_CLASSES,
MetadataRowDetail,
MetadataRowIconSlot,
} from "../MetadataSection";
@@ -47,8 +48,23 @@ const VisualTile = ({
overlayLabel,
children,
}: PropsWithChildren<{ className?: string; onPreview?: () => void; overlayLabel?: string }>) => {
// A div, not a <button>: tiles hold block media. When it opens the viewer it takes the button
// role and keys, so keyboard users reach it too; its name comes from the media's alt text.
const interactive = onPreview
? {
role: "button",
tabIndex: 0,
onClick: onPreview,
onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => {
// Only the tile's own keys: a motion photo's Live badge inside it is a control too.
if (event.target !== event.currentTarget || (event.key !== "Enter" && event.key !== " ")) return;
event.preventDefault();
onPreview();
},
}
: undefined;
return (
<div className={cn(VISUAL_TILE_BUTTON_CLASS, className)} onClick={onPreview}>
<div className={cn(VISUAL_TILE_BUTTON_CLASS, className)} {...interactive}>
<div className={MEDIA_HOVER_SURFACE_CLASS}>
{children}
<div className={MEDIA_HOVER_GRADIENT_CLASS} aria-hidden />
@@ -61,7 +77,7 @@ const VisualTile = ({
const VideoPlayBadge = ({ className, children }: PropsWithChildren<{ className?: string }>) => (
<div
className={cn(
"pointer-events-none absolute flex items-center justify-center rounded-full bg-background/80 text-foreground/70 shadow-sm backdrop-blur-sm",
"pointer-events-none absolute flex items-center justify-center rounded-full bg-mu-canvas/80 text-mu-ink/70 backdrop-blur-sm",
className,
)}
>
@@ -88,7 +104,7 @@ const CollageVisualItem = ({
<VideoPoster sourceUrl={item.sourceUrl} posterUrl={item.posterUrl} alt={item.filename} className={COVER_MEDIA_CLASS} />
{!overlayLabel && (
<VideoPlayBadge className={COLLAGE_VIDEO_PLAY_BADGE_CLASS}>
<PlayIcon className="h-3.5 w-3.5 fill-current" />
<PlayIcon className="mu-icon-sm fill-current" />
</VideoPlayBadge>
)}
</>
@@ -131,7 +147,7 @@ const SingleVisualItem = ({ item, onPreview }: { item: VisualItem; onPreview?: (
containerClassName="max-w-full"
posterClassName={cn(NATURAL_MEDIA_CLASS, "object-contain")}
videoClassName={SINGLE_MOTION_VIDEO_CLASS}
badgeClassName="left-2 top-2 px-2 py-0.5 text-[10px]"
badgeClassName="left-2 top-2 px-2 py-0.5 mu-caption"
/>
</VisualTile>
);
@@ -143,7 +159,7 @@ const SingleVisualItem = ({ item, onPreview }: { item: VisualItem; onPreview?: (
<VideoPoster sourceUrl={item.sourceUrl} posterUrl={item.posterUrl} alt={item.filename} className={COVER_MEDIA_CLASS} />
<div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/35 via-black/5 to-transparent" />
<VideoPlayBadge className="bottom-3 right-3 h-9 w-9">
<PlayIcon className="h-4 w-4 fill-current" />
<PlayIcon className="mu-icon fill-current" />
</VideoPlayBadge>
</div>
</VisualTile>
@@ -213,48 +229,61 @@ const isServedHere = (url: string) => {
* the same edge as every other row's at rest.
*/
const DocumentRow = ({ attachment }: { attachment: Attachment }) => {
const t = useTranslate();
const { fileTypeLabel, fileSizeLabel } = getAttachmentMetadata(attachment);
const url = getAttachmentUrl(attachment);
const body = (
<>
<MetadataRowIconSlot icon={FileIcon} />
<span className={METADATA_ROW_TEXT_CLASSES}>{attachment.filename}</span>
<span className={METADATA_ROW_CONTENT_TEXT_CLASSES}>{attachment.filename}</span>
<MetadataRowDetail parts={[fileTypeLabel, fileSizeLabel]} />
</>
);
if (!isServedHere(url)) {
return (
<a href={url} target="_blank" rel="noreferrer" title={`Open ${attachment.filename}`} className={METADATA_ROW_CLASSES}>
<a
href={url}
target="_blank"
rel="noreferrer"
title={t("common.open-name", { name: attachment.filename })}
className={METADATA_ROW_CLASSES}
>
{body}
<ExternalLinkIcon aria-hidden="true" className={METADATA_ROW_HINT_CLASSES} strokeWidth={1.8} />
<ExternalLinkIcon aria-hidden="true" className={METADATA_ROW_HINT_CLASSES} />
</a>
);
}
if (!opensInline(attachment.type)) {
return (
<a href={url} download title={`Download ${attachment.filename}`} className={METADATA_ROW_CLASSES}>
<a href={url} download title={t("common.download-name", { name: attachment.filename })} className={METADATA_ROW_CLASSES}>
{body}
<DownloadIcon aria-hidden="true" className={METADATA_ROW_HINT_CLASSES} strokeWidth={1.8} />
<DownloadIcon aria-hidden="true" className={METADATA_ROW_HINT_CLASSES} />
</a>
);
}
return (
<div className={METADATA_ROW_BOX_CLASSES}>
<a href={url} target="_blank" rel="noreferrer" title={`Open ${attachment.filename}`} className={METADATA_ROW_LABEL_CLASSES}>
<a
href={url}
target="_blank"
rel="noreferrer"
title={t("common.open-name", { name: attachment.filename })}
className={METADATA_ROW_LABEL_CLASSES}
>
{body}
</a>
<div className={METADATA_ROW_CONTROLS_CLASSES}>
<a
href={url}
download
title="Download"
aria-label={`Download ${attachment.filename}`}
className={buttonVariants({ variant: "quiet", size: "icon-sm" })}
title={t("common.download")}
aria-label={t("common.download-name", { name: attachment.filename })}
className={buttonClasses({ variant: "ghost", size: "xs", iconOnly: true })}
>
<DownloadIcon className="size-3.5" strokeWidth={1.8} />
<DownloadIcon className="mu-icon-sm" />
</a>
</div>
</div>
@@ -1,16 +1,16 @@
import { Button, buttonClasses, Dialog, Tooltip } from "@usememos/ui";
import { DownloadIcon, Maximize2Icon, PauseIcon, PlayIcon, RotateCcwIcon, RotateCwIcon } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Button, buttonVariants } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { formatFileSize, getFileTypeLabel } from "@/utils/format";
import { useTranslate } from "@/utils/i18n";
import {
METADATA_ROW_BOX_CLASSES,
METADATA_ROW_CONTENT_TEXT_CLASSES,
METADATA_ROW_HINT_CLASSES,
METADATA_ROW_ICON_CLASSES,
METADATA_ROW_LABEL_CLASSES,
METADATA_ROW_SLOT_BUTTON_CLASSES,
METADATA_ROW_TEXT_CLASSES,
MetadataRowDetail,
} from "../MetadataSection";
import { formatAudioTime, toggleAudioPlayback } from "./attachmentHelpers";
@@ -19,7 +19,7 @@ const AUDIO_PLAYBACK_RATES = [0.5, 0.75, 1, 1.5, 2] as const;
const UNKNOWN_DURATION_LABEL = "--:--";
const SKIP_SECONDS = 10;
const OPEN_PLAYER_CLASSES = cn(METADATA_ROW_LABEL_CLASSES, "cursor-pointer");
const DOWNLOAD_CLASSES = buttonVariants({ variant: "quiet", size: "icon" });
const DOWNLOAD_CLASSES = buttonClasses({ variant: "ghost", iconOnly: true });
const getDurationLabel = (duration: number): string => (duration > 0 ? formatAudioTime(duration) : UNKNOWN_DURATION_LABEL);
@@ -36,11 +36,12 @@ interface AudioProgressBarProps {
}
const AudioProgressBar = ({ filename, currentTime, duration, onSeek }: AudioProgressBarProps) => {
const t = useTranslate();
const progressPercent = duration > 0 ? (currentTime / duration) * 100 : 0;
return (
<div className="relative flex h-4 w-full items-center">
<div className="absolute inset-x-0 h-1 rounded-full bg-muted" />
<div className="absolute start-0 h-1 rounded-full bg-primary/60" style={{ width: `${Math.min(progressPercent, 100)}%` }} />
<div className="absolute inset-x-0 h-1 rounded-full bg-mu-well" />
<div className="absolute start-0 h-1 rounded-full bg-mu-primary/60" style={{ width: `${Math.min(progressPercent, 100)}%` }} />
<input
type="range"
min={0}
@@ -48,16 +49,16 @@ const AudioProgressBar = ({ filename, currentTime, duration, onSeek }: AudioProg
step={0.1}
value={Math.min(currentTime, duration || 0)}
onChange={(e) => onSeek(Number(e.target.value))}
aria-label={`Seek ${filename}`}
aria-label={t("audio-player.seek", { name: filename })}
className="relative z-10 h-4 w-full cursor-pointer appearance-none bg-transparent outline-none disabled:cursor-default
[&::-webkit-slider-runnable-track]:h-1 [&::-webkit-slider-runnable-track]:rounded-full
[&::-webkit-slider-runnable-track]:bg-transparent
[&::-webkit-slider-thumb]:mt-[-4px] [&::-webkit-slider-thumb]:size-3 [&::-webkit-slider-thumb]:appearance-none
[&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:border [&::-webkit-slider-thumb]:border-border
[&::-webkit-slider-thumb]:bg-background [&::-webkit-slider-thumb]:shadow-xs
[&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:border [&::-webkit-slider-thumb]:border-mu-line
[&::-webkit-slider-thumb]:bg-mu-canvas [&::-webkit-slider-thumb]:shadow-mu-key
[&::-moz-range-track]:h-1 [&::-moz-range-track]:rounded-full [&::-moz-range-track]:bg-transparent
[&::-moz-range-thumb]:size-3 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border
[&::-moz-range-thumb]:border-border [&::-moz-range-thumb]:bg-background"
[&::-moz-range-thumb]:border-mu-line [&::-moz-range-thumb]:bg-mu-canvas"
disabled={duration === 0}
/>
</div>
@@ -78,6 +79,7 @@ interface AudioAttachmentItemProps {
* playback carries on when the dialog closes and the row's glyph always reflects it.
*/
const AudioAttachmentItem = ({ filename, sourceUrl, mimeType, size }: AudioAttachmentItemProps) => {
const t = useTranslate();
const audioRef = useRef<HTMLAudioElement>(null);
const [isPlaying, setIsPlaying] = useState(false);
const [duration, setDuration] = useState(0);
@@ -149,13 +151,13 @@ const AudioAttachmentItem = ({ filename, sourceUrl, mimeType, size }: AudioAttac
aria-pressed={isPlaying}
aria-label={playbackLabel}
>
<PlaybackIcon className={METADATA_ROW_ICON_CLASSES} strokeWidth={1.8} />
<PlaybackIcon className={METADATA_ROW_ICON_CLASSES} />
</button>
{/* The name opens the player; an open glyph takes the detail rail's place once the row is engaged. */}
<button type="button" className={OPEN_PLAYER_CLASSES} onClick={() => handlePlayerOpenChange(true)} title={filename}>
<span className={METADATA_ROW_TEXT_CLASSES}>{filename}</span>
<span className={METADATA_ROW_CONTENT_TEXT_CLASSES}>{filename}</span>
<MetadataRowDetail parts={[duration > 0 ? getDurationLabel(duration) : undefined, fileTypeLabel, fileSizeLabel]} />
<Maximize2Icon aria-hidden="true" className={METADATA_ROW_HINT_CLASSES} strokeWidth={1.8} />
<Maximize2Icon aria-hidden="true" className={METADATA_ROW_HINT_CLASSES} />
</button>
</div>
@@ -174,16 +176,14 @@ const AudioAttachmentItem = ({ filename, sourceUrl, mimeType, size }: AudioAttac
}}
/>
<Dialog open={playerOpen} onOpenChange={handlePlayerOpenChange}>
<DialogContent size="sm">
<DialogHeader>
<DialogTitle>{filename}</DialogTitle>
<DialogDescription>{[fileTypeLabel, fileSizeLabel].filter(Boolean).join(" · ")}</DialogDescription>
</DialogHeader>
<Dialog.Root open={playerOpen} onOpenChange={handlePlayerOpenChange}>
<Dialog.Popup closeLabel={t("common.close")}>
<Dialog.Title>{filename}</Dialog.Title>
<Dialog.Description>{[fileTypeLabel, fileSizeLabel].filter(Boolean).join(" · ")}</Dialog.Description>
<div className="flex flex-col gap-1">
<AudioProgressBar filename={filename} currentTime={currentTime} duration={duration} onSeek={handleSeek} />
<div className="flex items-center justify-between text-2xs tabular-nums text-muted-foreground/60">
<div className="flex items-center justify-between mu-caption tabular-nums text-mu-ink-muted/60">
<span>{formatAudioTime(currentTime)}</span>
<span>{getDurationLabel(duration)}</span>
</div>
@@ -192,29 +192,57 @@ const AudioAttachmentItem = ({ filename, sourceUrl, mimeType, size }: AudioAttac
{/* One 32px rail: download at the start, transport in the middle, speed at the end. */}
<div className="grid grid-cols-[1fr_auto_1fr] items-center">
<div className="flex justify-start">
<a href={sourceUrl} download className={DOWNLOAD_CLASSES} aria-label={`Download ${filename}`}>
<DownloadIcon className="size-4" strokeWidth={1.8} />
<a href={sourceUrl} download className={DOWNLOAD_CLASSES} aria-label={t("common.download-name", { name: filename })}>
<DownloadIcon className="mu-icon" />
</a>
</div>
<div className="flex items-center gap-1">
<Button variant="quiet" size="icon" onClick={() => skip(-SKIP_SECONDS)} aria-label={`Back ${SKIP_SECONDS} seconds`}>
<RotateCcwIcon className="size-4" strokeWidth={1.8} />
</Button>
<Button size="icon" onClick={togglePlayback} aria-label={playbackLabel}>
<PlaybackIcon className="size-4" strokeWidth={2} />
</Button>
<Button variant="quiet" size="icon" onClick={() => skip(SKIP_SECONDS)} aria-label={`Forward ${SKIP_SECONDS} seconds`}>
<RotateCwIcon className="size-4" strokeWidth={1.8} />
</Button>
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
variant="ghost"
onClick={() => skip(-SKIP_SECONDS)}
aria-label={t("audio-player.back", { seconds: SKIP_SECONDS })}
icon={<RotateCcwIcon />}
/>
}
/>
<Tooltip.Popup>{t("audio-player.back", { seconds: SKIP_SECONDS })}</Tooltip.Popup>
</Tooltip.Root>
<Tooltip.Root>
<Tooltip.Trigger
render={<Button variant="primary" onClick={togglePlayback} aria-label={playbackLabel} icon={<PlaybackIcon />} />}
/>
<Tooltip.Popup>{playbackLabel}</Tooltip.Popup>
</Tooltip.Root>
<Tooltip.Root>
<Tooltip.Trigger
render={
<Button
variant="ghost"
onClick={() => skip(SKIP_SECONDS)}
aria-label={t("audio-player.forward", { seconds: SKIP_SECONDS })}
icon={<RotateCwIcon />}
/>
}
/>
<Tooltip.Popup>{t("audio-player.forward", { seconds: SKIP_SECONDS })}</Tooltip.Popup>
</Tooltip.Root>
</div>
<div className="flex justify-end">
<Button variant="quiet" size="sm" onClick={handlePlaybackRateChange} aria-label={`Playback speed ${playbackRate}x`}>
<Button
variant="ghost"
size="sm"
onClick={handlePlaybackRateChange}
aria-label={t("audio-player.speed", { rate: playbackRate })}
>
{playbackRate}x
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</Dialog.Popup>
</Dialog.Root>
</>
);
};
@@ -1,15 +1,11 @@
import { FOCUS_VISIBLE_OUTLINE_CLASSES } from "@/components/ui/focus";
import { cn } from "@/lib/utils";
/**
* Tailwind class bundles for attachment visual tiles (`VisualTile`, collage, single image/video).
* Hover uses `group/media` on {@link MEDIA_HOVER_SURFACE_CLASS} so scale/gradient track the media surface, not the outer button chrome.
*/
export const VISUAL_TILE_BUTTON_CLASS = cn(
"relative block overflow-hidden rounded-md border border-border/70 bg-muted/30 p-0 text-left outline-none transition-colors",
FOCUS_VISIBLE_OUTLINE_CLASSES,
);
// No `outline-none`: as a utility it would override `mu-focus` and hide the keyboard outline.
export const VISUAL_TILE_BUTTON_CLASS =
"relative block overflow-hidden rounded-mu-md border border-mu-line/70 bg-mu-well/30 p-0 text-left transition-colors mu-focus";
export const MEDIA_HOVER_SURFACE_CLASS = "group/media relative h-full min-h-0 w-full overflow-hidden";
@@ -31,8 +27,8 @@ export const VISUAL_Z = {
overflowMask: "z-[3]",
} as const;
export const MEDIA_HOVER_GRADIENT_CLASS = `pointer-events-none absolute inset-0 ${VISUAL_Z.gradient} bg-gradient-to-t from-foreground/15 via-transparent to-transparent opacity-0 transition-opacity group-hover/media:opacity-100`;
export const MEDIA_HOVER_GRADIENT_CLASS = `pointer-events-none absolute inset-0 ${VISUAL_Z.gradient} bg-gradient-to-t from-mu-ink/15 via-transparent to-transparent opacity-0 transition-opacity group-hover/media:opacity-100`;
export const COLLAGE_VIDEO_PLAY_BADGE_CLASS = `bottom-2 right-2 ${VISUAL_Z.badge} h-7 w-7 bg-background/80 text-foreground/70`;
export const COLLAGE_VIDEO_PLAY_BADGE_CLASS = `bottom-2 right-2 ${VISUAL_Z.badge} h-7 w-7 bg-mu-canvas/80 text-mu-ink/70`;
export const OVERFLOW_TILE_OVERLAY_CLASS = `pointer-events-none absolute inset-0 ${VISUAL_Z.overflowMask} flex items-center justify-center bg-black/45 text-2xl font-semibold text-white backdrop-blur-[2px]`;
export const OVERFLOW_TILE_OVERLAY_CLASS = `pointer-events-none absolute inset-0 ${VISUAL_Z.overflowMask} flex items-center justify-center bg-black/45 mu-heading text-white backdrop-blur-[2px]`;
@@ -1,12 +1,7 @@
import { Button, Dialog, Field, Input, Textarea } from "@usememos/ui";
import type { LocationState } from "@/components/MemoEditor/edit/types/insertMenu";
import { LazyLocationPicker } from "@/components/map/LazyLocationPicker";
import type { MapPoint } from "@/components/map/types";
import { Button } from "@/components/ui/button";
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { VisuallyHidden } from "@/components/ui/visually-hidden";
import { useTranslate } from "@/utils/i18n";
interface LocationDialogProps {
@@ -34,80 +29,63 @@ export const LocationDialog = ({
const { placeholder, position, latInput, lngInput } = state;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[min(28rem,calc(100vw-2rem))] p-0!" showCloseButton={false}>
<VisuallyHidden>
<DialogClose />
</VisuallyHidden>
<VisuallyHidden>
<DialogTitle>{t("tooltip.select-location")}</DialogTitle>
</VisuallyHidden>
<VisuallyHidden>
<DialogDescription>Select a location on the map or enter coordinates manually</DialogDescription>
</VisuallyHidden>
<Dialog.Root open={open} onOpenChange={onOpenChange}>
<Dialog.Popup variant="bare" sheet={false} className="w-md">
<Dialog.Title className="mu-visually-hidden">{t("tooltip.select-location")}</Dialog.Title>
<Dialog.Description className="mu-visually-hidden">{t("map.location-description")}</Dialog.Description>
<div className="flex flex-col">
<div className="w-full h-64 overflow-hidden rounded-t-md bg-muted/30">
<div className="w-full h-64 overflow-hidden rounded-t-mu-md bg-mu-well/30">
{open && <LazyLocationPicker className="h-full" latlng={position} onChange={onPositionChange} />}
</div>
<div className="w-full flex flex-col p-3 gap-3">
<div className="grid grid-cols-2 gap-3">
<div className="grid gap-1">
<Label htmlFor="memo-location-lat" className="text-xs uppercase tracking-wide text-muted-foreground">
Lat
</Label>
<Field.Root>
<Field.Label>{t("map.latitude")}</Field.Label>
<Input
id="memo-location-lat"
placeholder="Lat"
type="number"
step="any"
min="-90"
max="90"
value={latInput}
onChange={(e) => onUpdateCoordinate("lat", e.target.value)}
className="h-9"
/>
</div>
<div className="grid gap-1">
<Label htmlFor="memo-location-lng" className="text-xs uppercase tracking-wide text-muted-foreground">
Lng
</Label>
</Field.Root>
<Field.Root>
<Field.Label>{t("map.longitude")}</Field.Label>
<Input
id="memo-location-lng"
placeholder="Lng"
type="number"
step="any"
min="-180"
max="180"
value={lngInput}
onChange={(e) => onUpdateCoordinate("lng", e.target.value)}
className="h-9"
/>
</div>
</Field.Root>
</div>
<div className="grid gap-1">
<Label htmlFor="memo-location-placeholder" className="text-xs uppercase tracking-wide text-muted-foreground">
{t("tooltip.select-location")}
</Label>
<Field.Root>
<Field.Label>{t("tooltip.select-location")}</Field.Label>
<Textarea
id="memo-location-placeholder"
placeholder="Choose a position first."
placeholder={t("map.place-placeholder")}
value={placeholder}
disabled={!position}
onChange={(e) => onPlaceholderChange(e.target.value)}
className="min-h-16"
/>
</div>
</Field.Root>
<div className="w-full flex items-center justify-end gap-2">
<Button variant="ghost" onClick={onCancel}>
{t("common.close")}
</Button>
<Button onClick={onConfirm} disabled={!position || placeholder.trim().length === 0}>
<Button variant="primary" onClick={onConfirm} disabled={!position || placeholder.trim().length === 0}>
{t("common.confirm")}
</Button>
</div>
</div>
</div>
</DialogContent>
</Dialog>
</Dialog.Popup>
</Dialog.Root>
);
};
@@ -8,6 +8,7 @@ import {
MetadataRowRemoveControl,
} from "@/components/MemoMetadata/MetadataSection";
import type { Location } from "@/types/proto/api/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { getLocationCoordinatesText, getLocationDisplayText } from "./locationHelpers";
interface LocationDisplayEditorProps {
@@ -17,6 +18,7 @@ interface LocationDisplayEditorProps {
/** The draft's location as one metadata row; the remove control shows once the row is engaged. */
const LocationDisplayEditor: FC<LocationDisplayEditorProps> = ({ location, onRemove }) => {
const t = useTranslate();
const displayText = getLocationDisplayText(location);
return (
@@ -26,7 +28,7 @@ const LocationDisplayEditor: FC<LocationDisplayEditorProps> = ({ location, onRem
{displayText}
</span>
<MetadataRowDetail parts={[getLocationCoordinatesText(location)]} />
{onRemove && <MetadataRowRemoveControl label="Remove location" onClick={onRemove} />}
{onRemove && <MetadataRowRemoveControl label={t("editor.remove-location")} onClick={onRemove} />}
</div>
);
};
@@ -1,8 +1,8 @@
import { Popover } from "@usememos/ui";
import { MapPinIcon } from "lucide-react";
import { useState } from "react";
import { METADATA_ROW_CLASSES, METADATA_ROW_TEXT_CLASSES, MetadataRowIconSlot } from "@/components/MemoMetadata/MetadataSection";
import { LazyLocationPicker } from "@/components/map/LazyLocationPicker";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import type { Location } from "@/types/proto/api/memo_service_pb";
import { getLocationCoordinatesText, getLocationDisplayText } from "./locationHelpers";
@@ -21,25 +21,19 @@ const LocationDisplayView = ({ location }: LocationDisplayViewProps) => {
const displayText = getLocationDisplayText(location);
return (
<Popover open={popoverOpen} onOpenChange={setPopoverOpen}>
<PopoverTrigger render={<button type="button" title={displayText} className={METADATA_ROW_CLASSES} />}>
<Popover.Root open={popoverOpen} onOpenChange={setPopoverOpen}>
<Popover.Trigger render={<button type="button" title={displayText} className={METADATA_ROW_CLASSES} />}>
<MetadataRowIconSlot icon={MapPinIcon} />
<span className={METADATA_ROW_TEXT_CLASSES}>{displayText}</span>
</PopoverTrigger>
<PopoverContent align="start" className="w-80 max-w-[calc(100vw-2rem)] overflow-hidden rounded-xl p-0">
{popoverOpen && (
<LazyLocationPicker
latlng={{ lat: location.latitude, lng: location.longitude }}
readonly
className="h-52 rounded-none border-0 shadow-none"
/>
)}
<div className="space-y-1 px-3 py-2.5">
{location.placeholder.trim() && <p className="wrap-anywhere text-sm font-medium">{displayText}</p>}
<p className="text-2xs tabular-nums text-muted-foreground">{getLocationCoordinatesText(location, 6)}</p>
</Popover.Trigger>
<Popover.Popup align="start" className="w-80" aria-label={displayText}>
{popoverOpen && <LazyLocationPicker latlng={{ lat: location.latitude, lng: location.longitude }} readonly className="h-52" />}
<div className="space-y-1">
{location.placeholder.trim() && <p className="wrap-anywhere mu-label">{displayText}</p>}
<p className="mu-caption tabular-nums text-mu-ink-muted">{getLocationCoordinatesText(location, 6)}</p>
</div>
</PopoverContent>
</Popover>
</Popover.Popup>
</Popover.Root>
);
};
@@ -1,7 +1,7 @@
import { Button, Tooltip } from "@usememos/ui";
import { type LucideIcon, XIcon } from "lucide-react";
import type { PropsWithChildren, ReactNode } from "react";
import { Button } from "@/components/ui/button";
import { FOCUS_VISIBLE_OUTLINE_CLASSES } from "@/components/ui/focus";
import { SIDEBAR_LEADING_SLOT_CLASSES } from "@/components/AppSidebar/sidebar-layout";
import { cn } from "@/lib/utils";
/**
@@ -11,12 +11,12 @@ import { cn } from "@/lib/utils";
* sit on a card rather than the sidebar surface.
*/
export const METADATA_ROW_BOX_CLASSES =
"group/row relative flex h-7 w-full min-w-0 items-center gap-1 rounded-md px-2 text-start text-ui text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground";
"group/row relative flex h-7 w-full min-w-0 items-center gap-1 rounded-mu-md px-2 text-start mu-caption text-mu-ink-muted transition-colors hover:bg-mu-hover hover:text-mu-ink";
/** A row that is itself the control: the box, the focus outline, and the quiet "on" fill while pressed or holding a popup open. */
export const METADATA_ROW_CLASSES = cn(
METADATA_ROW_BOX_CLASSES,
"aria-pressed:bg-accent aria-pressed:text-accent-foreground data-popup-open:bg-accent data-popup-open:text-accent-foreground",
FOCUS_VISIBLE_OUTLINE_CLASSES,
"aria-pressed:bg-mu-hover aria-pressed:text-mu-ink data-popup-open:bg-mu-hover data-popup-open:text-mu-ink",
"mu-focus",
);
/**
* The compact row: 24px instead of 28px, for a list that previews rather than edits (the
@@ -24,12 +24,19 @@ export const METADATA_ROW_CLASSES = cn(
*/
export const METADATA_COMPACT_ROW_CLASSES = cn(METADATA_ROW_CLASSES, "h-6");
/** The focusable body of a split row; its gap must equal the box's `gap-1`. */
export const METADATA_ROW_LABEL_CLASSES = `flex h-full min-w-0 flex-1 items-center gap-1 text-start ${FOCUS_VISIBLE_OUTLINE_CLASSES}`;
export const METADATA_ROW_SLOT_CLASSES = "flex size-5 shrink-0 items-center justify-center";
export const METADATA_ROW_ICON_CLASSES = "me-auto size-4 shrink-0 opacity-75";
/** The row's text column: foreground ink, truncating. */
export const METADATA_ROW_TEXT_CLASSES = "min-w-0 flex-1 truncate text-foreground";
export const METADATA_ROW_DETAIL_CLASSES = "shrink-0 text-2xs tabular-nums text-muted-foreground/60";
export const METADATA_ROW_LABEL_CLASSES = "flex h-full min-w-0 flex-1 items-center gap-1 text-start mu-focus";
/** The same 20px leading column the sidebar's rows reserve, so glyphs share one rail across both. */
export const METADATA_ROW_SLOT_CLASSES = SIDEBAR_LEADING_SLOT_CLASSES;
export const METADATA_ROW_ICON_CLASSES = "mu-icon-sm me-auto shrink-0";
/**
* The row's text column, truncating. It inherits the row's muted ink: a reference, a place or a
* comment describes the memo, so it reads a step below the memo's own words and darkens with the
* row on hover.
*/
export const METADATA_ROW_TEXT_CLASSES = "min-w-0 flex-1 truncate";
/** An attachment is content, not a description, so its row text keeps the memo's ink. */
export const METADATA_ROW_CONTENT_TEXT_CLASSES = cn(METADATA_ROW_TEXT_CLASSES, "text-mu-ink");
export const METADATA_ROW_DETAIL_CLASSES = "shrink-0 mu-caption tabular-nums text-mu-ink-muted";
/**
* A slot that is itself a control (play, disclosure): the same box and glyph as any other
* slot, so it reads like its siblings at rest. The glyph darkens under the pointer and
@@ -37,8 +44,8 @@ export const METADATA_ROW_DETAIL_CLASSES = "shrink-0 text-2xs tabular-nums text-
*/
export const METADATA_ROW_SLOT_BUTTON_CLASSES = cn(
METADATA_ROW_SLOT_CLASSES,
"relative cursor-pointer rounded transition-colors hover:text-foreground hover:[&>svg]:opacity-100 aria-pressed:text-primary aria-pressed:[&>svg]:opacity-100 after:absolute after:-inset-0.5 after:content-['']",
FOCUS_VISIBLE_OUTLINE_CLASSES,
"relative cursor-pointer rounded transition-colors hover:text-mu-ink aria-pressed:text-mu-primary after:absolute after:-inset-0.5 after:content-['']",
"mu-focus",
);
/*
@@ -58,7 +65,7 @@ export const METADATA_ROW_CONTROLS_CLASSES = cn(
);
/** A glyph hinting at what engaging the row does (download, open), overlaid where the detail rail was. */
export const METADATA_ROW_HINT_CLASSES = cn(
"absolute end-2 size-4 opacity-0 transition-opacity",
"mu-icon-sm absolute end-2 opacity-0 transition-opacity",
"md:group-hover/row:opacity-75 md:group-focus-within/row:opacity-75",
);
/** The detail rail gives way to whatever overlays it. */
@@ -76,7 +83,7 @@ export const METADATA_ROW_LIST_CLASSES = "-mx-2 flex w-[calc(100%+1rem)] flex-co
/** The standard glyph-in-slot pairing, so every row draws its glyph identically. */
export const MetadataRowIconSlot = ({ icon: Icon }: { icon: LucideIcon }) => (
<span className={METADATA_ROW_SLOT_CLASSES} aria-hidden="true">
<Icon className={METADATA_ROW_ICON_CLASSES} strokeWidth={1.8} />
<Icon className={METADATA_ROW_ICON_CLASSES} />
</span>
);
@@ -90,7 +97,7 @@ export const MetadataRowDetail = ({ parts }: { parts: Array<string | undefined>
<span className={DETAIL_RAIL_CLASSES}>
{shown.map((part, index) => (
<span key={part} className="flex items-center gap-1">
{index > 0 && <span className="text-muted-foreground/40">·</span>}
{index > 0 && <span className="text-mu-ink-muted/40">·</span>}
<span>{part}</span>
</span>
))}
@@ -101,9 +108,10 @@ export const MetadataRowDetail = ({ parts }: { parts: Array<string | undefined>
/** An editable row's remove control, in the trailing overlay. */
export const MetadataRowRemoveControl = ({ label, onClick }: { label: string; onClick: () => void }) => (
<div className={METADATA_ROW_CONTROLS_CLASSES}>
<Button variant="quiet" size="icon-sm" onClick={onClick} title="Remove" aria-label={label}>
<XIcon className="size-3.5" strokeWidth={1.8} />
</Button>
<Tooltip.Root>
<Tooltip.Trigger render={<Button variant="ghost" size="xs" onClick={onClick} aria-label={label} icon={<XIcon />} />} />
<Tooltip.Popup>{label}</Tooltip.Popup>
</Tooltip.Root>
</div>
);
@@ -117,16 +125,16 @@ interface MetadataSectionProps extends PropsWithChildren {
}
/**
* A quiet titled list: a 24px header (20px when compact) with an uppercase title on the text edge, then
* rows whose leading glyph lands on that same edge. No box or band, so the list recedes
* behind the memo's own content.
* A quiet titled list: a 24px header (20px when compact) with a sentence-case title on the text
* edge in the sidebar's section-header style, its count beside it, then rows whose leading glyph
* lands on that same edge. No box or band, so the list recedes behind the memo's own content.
*/
const MetadataSection = ({ title, count, action, density = "default", children }: MetadataSectionProps) => (
<section className="w-full" aria-label={title}>
<div className={cn("flex min-w-0 items-center justify-between gap-2", density === "compact" ? "h-5" : "mb-0.5 h-6")}>
<h3 className="flex min-w-0 items-center gap-1.5 text-2xs font-normal uppercase tracking-wide text-muted-foreground/55 select-none">
<h3 className="flex min-w-0 items-center gap-1.5 mu-label-sm text-mu-ink-muted select-none">
<span className="truncate">{title}</span>
{count != null && <span className="tabular-nums text-muted-foreground/60">{count}</span>}
{count != null && <span className="mu-caption tabular-nums">{count}</span>}
</h3>
{action && <div className="-me-2 shrink-0">{action}</div>}
</div>
@@ -1,9 +1,7 @@
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { Dialog, Input } from "@usememos/ui";
import { LinkIcon } from "lucide-react";
import { MemoPreview } from "@/components/MemoPreview";
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { VisuallyHidden } from "@/components/ui/visually-hidden";
import { cn } from "@/lib/utils";
import type { Memo } from "@/types/proto/api/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -32,33 +30,24 @@ export const LinkMemoDialog = ({
const t = useTranslate();
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[min(28rem,calc(100vw-2rem))] p-0!" showCloseButton={false}>
<VisuallyHidden>
<DialogClose />
</VisuallyHidden>
<VisuallyHidden>
<DialogTitle>{t("tooltip.link-memo")}</DialogTitle>
</VisuallyHidden>
<VisuallyHidden>
<DialogDescription>Search and select a memo to link</DialogDescription>
</VisuallyHidden>
<Dialog.Root open={open} onOpenChange={onOpenChange}>
<Dialog.Popup variant="bare" sheet={false} className="w-md">
<Dialog.Title className="mu-visually-hidden">{t("tooltip.link-memo")}</Dialog.Title>
<Dialog.Description className="mu-visually-hidden">{t("tooltip.link-memo-description")}</Dialog.Description>
<div className="flex flex-col">
<div className="p-3">
<Input
aria-label={t("reference.search-placeholder")}
placeholder={t("reference.search-placeholder")}
value={searchText}
onChange={(e) => onSearchChange(e.target.value)}
className="!text-sm h-9"
autoFocus
/>
</div>
<div className="border-t border-border" />
<div className="border-t border-mu-line" />
<div className="max-h-[320px] overflow-y-auto">
{filteredMemos.length === 0 ? (
<div className="py-8 text-center text-sm text-muted-foreground">
{isFetching ? "Loading..." : t("reference.no-memos-found")}
</div>
<div className="py-8 text-center mu-body text-mu-ink-muted">{isFetching ? "Loading..." : t("reference.no-memos-found")}</div>
) : (
filteredMemos.map((memo) => {
const alreadyLinked = isAlreadyLinked(memo.name);
@@ -66,14 +55,14 @@ export const LinkMemoDialog = ({
<div
key={memo.name}
className={cn(
"flex cursor-pointer items-start border-b border-border last:border-b-0 px-3 py-2.5 hover:bg-accent/50 transition-colors",
"flex cursor-pointer items-start border-b border-mu-line last:border-b-0 px-3 py-2.5 hover:bg-mu-hover/50 transition-colors",
alreadyLinked && "opacity-40 cursor-default",
)}
onClick={() => !alreadyLinked && onSelectMemo(memo)}
>
<div className="w-full flex flex-col gap-1">
<div className="flex items-center gap-1.5 text-sm text-muted-foreground select-none">
{alreadyLinked && <LinkIcon className="w-3 h-3 shrink-0" />}
<div className="flex items-center gap-1.5 mu-body text-mu-ink-muted select-none">
{alreadyLinked && <LinkIcon className="mu-icon-xs shrink-0" />}
<span>{memo.createTime && timestampDate(memo.createTime).toLocaleString()}</span>
</div>
<MemoPreview name={memo.name} content={memo.content} attachments={memo.attachments} showMemoId />
@@ -84,7 +73,7 @@ export const LinkMemoDialog = ({
)}
</div>
</div>
</DialogContent>
</Dialog>
</Dialog.Popup>
</Dialog.Root>
);
};
@@ -43,7 +43,7 @@ const RelationListEditor: FC<RelationListEditorProps> = ({ relations, onRelation
return (
<div key={memo.name} className={METADATA_ROW_BOX_CLASSES}>
<RelationRow memo={memo} parentPage={parentPage} variant="label" />
<MetadataRowRemoveControl label="Remove relation" onClick={() => handleDeleteRelation(memo.name)} />
<MetadataRowRemoveControl label={t("editor.remove-relation")} onClick={() => handleDeleteRelation(memo.name)} />
</div>
);
})}
@@ -3,6 +3,7 @@ import type { ReactNode } from "react";
import { Link } from "react-router-dom";
import { createMemoNavigationState } from "@/components/MemoView/navigation";
import type { MemoRelation_MemoRef } from "@/types/proto/api/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { METADATA_ROW_CLASSES, METADATA_ROW_LABEL_CLASSES, METADATA_ROW_TEXT_CLASSES, MetadataRowIconSlot } from "../MetadataSection";
interface RelationRowProps {
@@ -19,17 +20,22 @@ interface RelationRowProps {
}
/** One related memo as a metadata row: a glyph in the leading slot and the snippet. */
const RelationRow = ({ memo, parentPage, icon = LinkIcon, variant = "row", trailing }: RelationRowProps) => (
<Link
className={variant === "row" ? METADATA_ROW_CLASSES : METADATA_ROW_LABEL_CLASSES}
to={`/${memo.name}`}
state={parentPage ? createMemoNavigationState(parentPage) : undefined}
viewTransition
>
<MetadataRowIconSlot icon={icon} />
<span className={METADATA_ROW_TEXT_CLASSES}>{memo.snippet || <span className="italic text-muted-foreground/60">No content</span>}</span>
{trailing}
</Link>
);
const RelationRow = ({ memo, parentPage, icon = LinkIcon, variant = "row", trailing }: RelationRowProps) => {
const t = useTranslate();
return (
<Link
className={variant === "row" ? METADATA_ROW_CLASSES : METADATA_ROW_LABEL_CLASSES}
to={`/${memo.name}`}
state={parentPage ? createMemoNavigationState(parentPage) : undefined}
viewTransition
>
<MetadataRowIconSlot icon={icon} />
<span className={METADATA_ROW_TEXT_CLASSES}>
{memo.snippet || <span className="italic text-mu-ink-muted/60">{t("common.no-content")}</span>}
</span>
{trailing}
</Link>
);
};
export default RelationRow;

Some files were not shown because too many files have changed in this diff Show More