Skip to content

armgit / memos

Public Imported from GitHub
0

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

feat(web): replace CodeMirror and react-markdown with @usememos/editor (#6466)

Johnny5cfe9c09ddb5
diff --git a/web/package.json b/web/package.json
index d46c713a1..64d1d3e21 100644
--- a/web/package.json
+++ b/web/package.json
@@ -18,21 +18,14 @@
},
"dependencies": {
"@base-ui/react": "^1.7.0",
- "@codemirror/autocomplete": "^6.20.3",
- "@codemirror/commands": "^6.11.0",
- "@codemirror/lang-markdown": "^6.5.2",
- "@codemirror/language": "^6.12.4",
- "@codemirror/state": "^6.7.2",
- "@codemirror/view": "^6.43.10",
"@connectrpc/connect": "^2.1.1",
"@connectrpc/connect-web": "^2.1.1",
"@github/relative-time-element": "^5.0.0",
- "@lezer/highlight": "^1.2.3",
- "@lezer/markdown": "^1.7.2",
"@maplibre/maplibre-gl-leaflet": "^0.1.4",
"@tailwindcss/vite": "^4.2.4",
"@tanstack/react-query": "^5.100.9",
"@tanstack/react-query-devtools": "^5.100.9",
+ "@usememos/editor": "26.10.5",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"copy-to-clipboard": "^4.0.2",
@@ -51,7 +44,6 @@
"mdast-util-gfm": "^3.1.0",
"mermaid": "^11.14.0",
"micromark-extension-gfm": "^3.0.0",
- "micromark-util-decode-string": "^2.0.1",
"micromark-util-normalize-identifier": "^2.0.1",
"react": "^19.2.6",
"react-dom": "^19.2.6",
@@ -59,14 +51,11 @@
"react-i18next": "^17.0.11",
"react-leaflet": "^5.0.0",
"react-leaflet-cluster": "^4.1.3",
- "react-markdown": "^10.1.0",
"react-router-dom": "^7.15.0",
- "rehype-katex": "^7.0.1",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
"remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1",
- "remark-math": "^6.0.0",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"tailwind-merge": "^3.5.0",
diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml
index 1588af96c..3878397dd 100644
--- a/web/pnpm-lock.yaml
+++ b/web/pnpm-lock.yaml
@@ -14,24 +14,6 @@ importers:
'@base-ui/react':
specifier: ^1.7.0
- '@codemirror/autocomplete':
- specifier: ^6.20.3
- version: 6.20.3
- '@codemirror/commands':
- specifier: ^6.11.0
- version: 6.11.0
- '@codemirror/lang-markdown':
- specifier: ^6.5.2
- version: 6.5.2
- '@codemirror/language':
- specifier: ^6.12.4
- version: 6.12.4
- '@codemirror/state':
- specifier: ^6.7.2
- version: 6.7.2
- '@codemirror/view':
- specifier: ^6.43.10
- version: 6.43.10
'@connectrpc/connect':
specifier: ^2.1.1
version: 2.1.1(@bufbuild/[email protected](patch_hash=9d60cec35402ba36bc21a72fefc68ccef8db0acb883504cc47c05a00a0029f8c))
@@ -41,12 +23,6 @@ importers:
'@github/relative-time-element':
specifier: ^5.0.0
version: 5.0.0
- '@lezer/highlight':
- specifier: ^1.2.3
- version: 1.2.3
- '@lezer/markdown':
- specifier: ^1.7.2
- version: 1.7.2
'@maplibre/maplibre-gl-leaflet':
specifier: ^0.1.4
@@ -59,6 +35,9 @@ importers:
'@tanstack/react-query-devtools':
specifier: ^5.100.9
+ '@usememos/editor':
+ specifier: 26.10.5
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@@ -113,9 +92,6 @@ importers:
micromark-extension-gfm:
specifier: ^3.0.0
version: 3.0.0
- micromark-util-decode-string:
- specifier: ^2.0.1
- version: 2.0.1
micromark-util-normalize-identifier:
specifier: ^2.0.1
version: 2.0.1
@@ -137,15 +113,9 @@ importers:
react-leaflet-cluster:
specifier: ^4.1.3
- react-markdown:
- specifier: ^10.1.0
- version: 10.1.0(@types/[email protected])([email protected])
react-router-dom:
specifier: ^7.15.0
- rehype-katex:
- specifier: ^7.0.1
- version: 7.0.1
rehype-raw:
specifier: ^7.0.0
version: 7.0.0
@@ -158,9 +128,6 @@ importers:
remark-gfm:
specifier: ^4.0.1
version: 4.0.1
- remark-math:
- specifier: ^6.0.0
- version: 6.0.0
remark-parse:
specifier: ^11.0.0
version: 11.0.0
@@ -465,36 +432,6 @@ packages:
'@chevrotain/[email protected]':
resolution: {integrity: sha512-lB59uJoaGIfOOL9knQqQRfhl9g7x8/wqFkp13zTdkRu1huG9kg6IJs1O8hqj9rs6h7orGxHJUKb+mX3rPbWGhA==}
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==}
-
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-/K4Rl5BN0OtTiPWmJCdqODu38XnDMsDxKY5rgrPnCkutPTJf2wVbkoixLfealF5Kwse/s8P8M5jAiURiwSwnFA==}
-
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==}
-
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==}
-
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==}
-
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==}
-
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==}
-
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==}
-
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-U3RiPX62Wl/Gx4ftQ7UxLlloSfsFTQqKa+7vFBYteZGCzkp6oBqcsD7iSwniWRGobCAmDcwZSY+Six3+3ztdfg==}
-
- '@codemirror/[email protected]':
- resolution: {integrity: sha512-vVWLvd4fKWYN/pMcwUrg6dWeublxmSz+V+52ZjW3h64IVN9cRUYLk5Km4JDT9vifxAFfDtNOIFxKYENthcolJQ==}
-
'@connectrpc/[email protected]':
resolution: {integrity: sha512-J8317Q2MaFRCT1jzVR1o06bZhDIBmU0UAzWx6xOIXzOq8+k71/+k7MUF7AwcBUX+34WIvbm5syRgC5HXQA8fOg==}
peerDependencies:
@@ -600,27 +537,6 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
- '@lezer/[email protected]':
- resolution: {integrity: sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==}
-
- '@lezer/[email protected]':
- resolution: {integrity: sha512-YJE78Wcg+zX8f10hiHWQ4Az48Qr/c13eId0VtRQYLBpxHDmDeSrXIlkbl+fJGW42rWC/uoUco9mhBZeVWP/A1g==}
-
- '@lezer/[email protected]':
- resolution: {integrity: sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==}
-
- '@lezer/[email protected]':
- resolution: {integrity: sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==}
-
- '@lezer/[email protected]':
- resolution: {integrity: sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==}
-
- '@lezer/[email protected]':
- resolution: {integrity: sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==}
-
- '@lezer/[email protected]':
- resolution: {integrity: sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ==}
-
'@mapbox/[email protected]':
resolution: {integrity: sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg==}
engines: {node: '>= 22'}
@@ -657,9 +573,6 @@ packages:
'@maplibre/[email protected]':
resolution: {integrity: sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw==}
- '@marijn/[email protected]':
- resolution: {integrity: sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==}
-
'@mermaid-js/[email protected]':
resolution: {integrity: sha512-gxK9ZX2+Fex5zu8LhRQoMeMPEHbc73UKZ0FQ54YrQtUxE1VVhMwzeNtKRPAu5aXks4FasbMe4xB4bWrmq6Jlxw==}
@@ -1054,9 +967,6 @@ packages:
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
- '@types/[email protected]':
- resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}
-
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
@@ -1066,9 +976,6 @@ packages:
resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}
- '@types/[email protected]':
- resolution: {integrity: sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg==}
-
resolution: {integrity: sha512-TbAd9DaPGSnzp6QvtYngntMZgcRk+igFELwR2N99XZn7RXUdKgsXMR+28bUO0rPsWp8MIu/f47luLIQuSLYv/w==}
@@ -1098,9 +1005,6 @@ packages:
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
- '@types/[email protected]':
- resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}
-
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
@@ -1231,6 +1135,17 @@ packages:
'@upsetjs/[email protected]':
resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==}
+ '@usememos/[email protected]':
+ resolution: {integrity: sha512-bqb3NauLyG9Z4YNusgHQI3IOiksR42aLpZCcE0ltDZEYq6j/fuUO2AKEROiYIu5T9b0sWYNQwy3yjHltAGlhmA==}
+ peerDependencies:
+ react: '>=18'
+ react-dom: '>=18'
+ peerDependenciesMeta:
+ react:
+ optional: true
+ react-dom:
+ optional: true
+
'@vitejs/[email protected]':
resolution: {integrity: sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -1326,18 +1241,9 @@ packages:
resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==}
-
- resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==}
-
resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==}
- resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==}
-
resolution: {integrity: sha512-PvVJm3oGqrveUVW2Vt/eZGeiAIsJszYweUcYwcskg9e+IubNYKKD+rHHem7A6XVO22eDAL+inxNIGAzZ/VIWlA==}
peerDependencies:
@@ -1384,9 +1290,6 @@ packages:
resolution: {integrity: sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==}
- resolution: {integrity: sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==}
-
resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}
engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}
@@ -1627,9 +1530,6 @@ packages:
resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==}
-
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
@@ -1675,21 +1575,9 @@ packages:
resolution: {integrity: sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==}
- resolution: {integrity: sha512-N+LqofjR2zuzTjCPzyDUdSshy4Ma6li7p/c3pA78uTwzFgENbgbUrm2ugwsOdcjI1muO+o6Dgzp9p8WHtn/39Q==}
-
- resolution: {integrity: sha512-zJfpXq44yff2hmE0XmwEOzdWin5xwH+QIhMLOScpX91e/NSGPsAzNCvLQDIEPyO2TXi+lBmU6hjLIhV8MwP2kw==}
-
- resolution: {integrity: sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw==}
-
resolution: {integrity: sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg==}
- resolution: {integrity: sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g==}
-
resolution: {integrity: sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==}
@@ -1699,18 +1587,9 @@ packages:
resolution: {integrity: sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg==}
- resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}
-
resolution: {integrity: sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA==}
- resolution: {integrity: sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A==}
-
- resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}
-
resolution: {integrity: sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==}
@@ -1728,9 +1607,6 @@ packages:
resolution: {integrity: sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==}
- resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
-
resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==}
@@ -1750,9 +1626,6 @@ packages:
resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==}
-
resolution: {integrity: sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==}
@@ -1760,18 +1633,6 @@ packages:
resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==}
-
- resolution: {integrity: sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==}
-
- resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==}
-
- resolution: {integrity: sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==}
-
resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}
engines: {node: '>=12'}
@@ -1971,18 +1832,6 @@ packages:
resolution: {integrity: sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==}
- resolution: {integrity: sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w==}
-
- resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==}
-
- resolution: {integrity: sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==}
-
- resolution: {integrity: sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==}
-
resolution: {integrity: sha512-MbgeFca0hLYIEx/2zGsszCSEJJ1JSCdiY5xQxRcLDDGa8EPvlLPupJ4DSajbMPAnC0je8jfb9TiUATnxxrHUog==}
@@ -2028,9 +1877,6 @@ packages:
resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==}
- resolution: {integrity: sha512-lvEqd+fHjATVs+2v/8kg9i5Q0AP2k85H0WUOwpIVvUML8BapsMvh1XAogmQjOCsLpoKRCVQqEkQBB3NhVBcsOg==}
-
resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==}
@@ -2121,9 +1967,6 @@ packages:
resolution: {integrity: sha512-61A5ThoTiDG/C8s8UMZwSorAGwMJ0ERVGj2OjoW5pAalsNOg15+iQiPzrLJ4jhZ1HJzmC2PIHT2oEiH3R5fzNA==}
- resolution: {integrity: sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==}
-
resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
@@ -2227,12 +2070,6 @@ packages:
react: ^19.0.0
react-dom: ^19.0.0
- resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}
- peerDependencies:
- '@types/react': '>=18'
- react: '>=18'
-
resolution: {integrity: sha512-VcrVg64Fo8nwBvDscajG8gRTLIuTC6N50nb22l2HOOV4PTOHgoGp8mUjy9wLiHYoYTSYI36tUnXZgasSRFZorQ==}
engines: {node: '>=20.0.0'}
@@ -2258,9 +2095,6 @@ packages:
resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-OiM2wrZ/wuhKkigASodFoo8wimG3H12LWQaH8qSPVJn9apWKFSH3YOCtbKpBorTVw/eI7cuT21XBbvwEswbIOA==}
-
resolution: {integrity: sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==}
@@ -2273,9 +2107,6 @@ packages:
resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}
- resolution: {integrity: sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==}
-
resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}
@@ -2342,22 +2173,10 @@ packages:
resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==}
- resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}
-
resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==}
-
- resolution: {integrity: sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==}
-
- resolution: {integrity: sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==}
-
resolution: {integrity: sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==}
@@ -2441,18 +2260,12 @@ packages:
resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}
- resolution: {integrity: sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ==}
-
resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==}
resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}
- resolution: {integrity: sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q==}
-
resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}
@@ -2590,9 +2403,6 @@ packages:
resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==}
- resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
-
resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
engines: {node: '>=18'}
@@ -2852,86 +2662,6 @@ snapshots:
'@chevrotain/[email protected]': {}
- '@codemirror/[email protected]':
- dependencies:
- '@codemirror/language': 6.12.4
- '@codemirror/state': 6.7.2
- '@codemirror/view': 6.43.10
- '@lezer/common': 1.5.2
-
- '@codemirror/[email protected]':
- dependencies:
- '@codemirror/language': 6.12.4
- '@codemirror/state': 6.7.2
- '@codemirror/view': 6.43.10
- '@lezer/common': 1.5.2
-
- '@codemirror/[email protected]':
- dependencies:
- '@codemirror/autocomplete': 6.20.3
- '@codemirror/language': 6.12.4
- '@codemirror/state': 6.7.2
- '@lezer/common': 1.5.2
- '@lezer/css': 1.3.6
-
- '@codemirror/[email protected]':
- dependencies:
- '@codemirror/autocomplete': 6.20.3
- '@codemirror/lang-css': 6.3.1
- '@codemirror/lang-javascript': 6.2.5
- '@codemirror/language': 6.12.4
- '@codemirror/state': 6.7.2
- '@codemirror/view': 6.43.10
- '@lezer/common': 1.5.2
- '@lezer/css': 1.3.6
- '@lezer/html': 1.3.13
-
- '@codemirror/[email protected]':
- dependencies:
- '@codemirror/autocomplete': 6.20.3
- '@codemirror/language': 6.12.4
- '@codemirror/lint': 6.9.7
- '@codemirror/state': 6.7.2
- '@codemirror/view': 6.43.10
- '@lezer/common': 1.5.2
- '@lezer/javascript': 1.5.4
-
- '@codemirror/[email protected]':
- dependencies:
- '@codemirror/autocomplete': 6.20.3
- '@codemirror/lang-html': 6.4.12
- '@codemirror/language': 6.12.4
- '@codemirror/state': 6.7.2
- '@codemirror/view': 6.43.10
- '@lezer/common': 1.5.2
- '@lezer/markdown': 1.7.2
-
- '@codemirror/[email protected]':
- dependencies:
- '@codemirror/state': 6.7.2
- '@codemirror/view': 6.43.10
- '@lezer/common': 1.5.2
- '@lezer/highlight': 1.2.3
- '@lezer/lr': 1.4.10
- style-mod: 4.1.3
-
- '@codemirror/[email protected]':
- dependencies:
- '@codemirror/state': 6.7.2
- '@codemirror/view': 6.43.10
- crelt: 1.0.7
-
- '@codemirror/[email protected]':
- dependencies:
- '@marijn/find-cluster-break': 1.0.4
-
- '@codemirror/[email protected]':
- dependencies:
- '@codemirror/state': 6.7.2
- crelt: 1.0.7
- style-mod: 4.1.3
- w3c-keyname: 2.2.8
-
'@connectrpc/[email protected](@bufbuild/[email protected](patch_hash=9d60cec35402ba36bc21a72fefc68ccef8db0acb883504cc47c05a00a0029f8c))(@connectrpc/[email protected](@bufbuild/[email protected](patch_hash=9d60cec35402ba36bc21a72fefc68ccef8db0acb883504cc47c05a00a0029f8c)))':
dependencies:
'@bufbuild/protobuf': 2.12.0(patch_hash=9d60cec35402ba36bc21a72fefc68ccef8db0acb883504cc47c05a00a0029f8c)
@@ -3029,39 +2759,6 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5
- '@lezer/[email protected]': {}
-
- '@lezer/[email protected]':
- dependencies:
- '@lezer/common': 1.5.2
- '@lezer/highlight': 1.2.3
- '@lezer/lr': 1.4.10
-
- '@lezer/[email protected]':
- dependencies:
- '@lezer/common': 1.5.2
-
- '@lezer/[email protected]':
- dependencies:
- '@lezer/common': 1.5.2
- '@lezer/highlight': 1.2.3
- '@lezer/lr': 1.4.10
-
- '@lezer/[email protected]':
- dependencies:
- '@lezer/common': 1.5.2
- '@lezer/highlight': 1.2.3
- '@lezer/lr': 1.4.10
-
- '@lezer/[email protected]':
- dependencies:
- '@lezer/common': 1.5.2
-
- '@lezer/[email protected]':
- dependencies:
- '@lezer/common': 1.5.2
- '@lezer/highlight': 1.2.3
-
'@mapbox/[email protected]': {}
'@mapbox/[email protected]': {}
@@ -3105,8 +2802,6 @@ snapshots:
'@types/geojson': 7946.0.16
pbf: 5.1.2
- '@marijn/[email protected]': {}
-
'@mermaid-js/[email protected]':
dependencies:
langium: 4.2.2
@@ -3459,10 +3154,6 @@ snapshots:
'@types/[email protected]': {}
- '@types/[email protected]':
- dependencies:
- '@types/estree': 1.0.8
-
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -3471,8 +3162,6 @@ snapshots:
dependencies:
'@types/unist': 3.0.3
- '@types/[email protected]': {}
-
dependencies:
'@types/geojson': 7946.0.16
@@ -3504,8 +3193,6 @@ snapshots:
optional: true
- '@types/[email protected]': {}
-
'@types/[email protected]': {}
'@typescript/[email protected]':
@@ -3575,6 +3262,11 @@ snapshots:
d3-selection: 3.0.0
d3-transition: 3.0.1([email protected])
+ optionalDependencies:
+ react: 19.2.6
+ react-dom: 19.2.6([email protected])
+
dependencies:
'@rolldown/pluginutils': 1.0.0-rc.7
@@ -3664,14 +3356,8 @@ snapshots:
-
-
-
dependencies:
chevrotain: 12.0.0
@@ -3713,8 +3399,6 @@ snapshots:
dependencies:
layout-base: 2.0.1
-
dependencies:
mdn-data: 2.27.1
@@ -3966,8 +3650,6 @@ snapshots:
-
dependencies:
'@types/estree': 1.0.8
@@ -3997,28 +3679,6 @@ snapshots:
- dependencies:
- '@types/hast': 3.0.4
- hastscript: 9.0.1
- web-namespaces: 2.0.1
-
- dependencies:
- '@types/hast': 3.0.4
- hast-util-from-dom: 5.0.1
- hast-util-from-html: 2.0.3
- unist-util-remove-position: 5.0.0
-
- dependencies:
- '@types/hast': 3.0.4
- devlop: 1.1.0
- hast-util-from-parse5: 8.0.3
- parse5: 7.3.0
- vfile: 6.0.3
- vfile-message: 4.0.3
-
dependencies:
'@types/hast': 3.0.4
@@ -4030,10 +3690,6 @@ snapshots:
vfile-location: 5.0.3
web-namespaces: 2.0.1
- dependencies:
- '@types/hast': 3.0.4
-
dependencies:
'@types/hast': 3.0.4
@@ -4060,26 +3716,6 @@ snapshots:
'@ungap/structured-clone': 1.3.0
unist-util-position: 5.0.0
- dependencies:
- '@types/estree': 1.0.8
- '@types/hast': 3.0.4
- '@types/unist': 3.0.3
- comma-separated-tokens: 2.0.3
- devlop: 1.1.0
- estree-util-is-identifier-name: 3.0.0
- hast-util-whitespace: 3.0.0
- mdast-util-mdx-expression: 2.0.1
- mdast-util-mdx-jsx: 3.2.0
- mdast-util-mdxjs-esm: 2.0.1
- property-information: 7.1.0
- space-separated-tokens: 2.0.2
- style-to-js: 1.1.21
- unist-util-position: 5.0.0
- vfile-message: 4.0.3
- transitivePeerDependencies:
- - supports-color
-
dependencies:
'@types/hast': 3.0.4
@@ -4090,17 +3726,6 @@ snapshots:
web-namespaces: 2.0.1
zwitch: 2.0.4
- dependencies:
- '@types/hast': 3.0.4
- '@types/unist': 3.0.3
- hast-util-is-element: 3.0.0
- unist-util-find-after: 5.0.0
-
- dependencies:
- '@types/hast': 3.0.4
-
dependencies:
'@types/hast': 3.0.4
@@ -4121,8 +3746,6 @@ snapshots:
-
@@ -4135,23 +3758,10 @@ snapshots:
-
-
- dependencies:
- is-alphabetical: 2.0.1
- is-decimal: 2.0.1
-
-
-
@@ -4393,57 +4003,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- '@types/hast': 3.0.4
- '@types/mdast': 4.0.4
- devlop: 1.1.0
- longest-streak: 3.1.0
- mdast-util-from-markdown: 2.0.3
- mdast-util-to-markdown: 2.1.2
- unist-util-remove-position: 5.0.0
- transitivePeerDependencies:
- - supports-color
-
- dependencies:
- '@types/estree-jsx': 1.0.5
- '@types/hast': 3.0.4
- '@types/mdast': 4.0.4
- devlop: 1.1.0
- mdast-util-from-markdown: 2.0.3
- mdast-util-to-markdown: 2.1.2
- transitivePeerDependencies:
- - supports-color
-
- dependencies:
- '@types/estree-jsx': 1.0.5
- '@types/hast': 3.0.4
- '@types/mdast': 4.0.4
- '@types/unist': 3.0.3
- ccount: 2.0.1
- devlop: 1.1.0
- mdast-util-from-markdown: 2.0.3
- mdast-util-to-markdown: 2.1.2
- parse-entities: 4.0.2
- stringify-entities: 4.0.4
- unist-util-stringify-position: 4.0.0
- vfile-message: 4.0.3
- transitivePeerDependencies:
- - supports-color
-
- dependencies:
- '@types/estree-jsx': 1.0.5
- '@types/hast': 3.0.4
- '@types/mdast': 4.0.4
- devlop: 1.1.0
- mdast-util-from-markdown: 2.0.3
- mdast-util-to-markdown: 2.1.2
- transitivePeerDependencies:
- - supports-color
-
dependencies:
'@types/mdast': 4.0.4
@@ -4585,16 +4144,6 @@ snapshots:
micromark-util-combine-extensions: 2.0.1
micromark-util-types: 2.0.2
- dependencies:
- '@types/katex': 0.16.8
- devlop: 1.1.0
- katex: 0.16.45
- micromark-factory-space: 2.0.1
- micromark-util-character: 2.1.1
- micromark-util-symbol: 2.0.1
- micromark-util-types: 2.0.2
-
dependencies:
micromark-util-character: 2.1.1
@@ -4732,16 +4281,6 @@ snapshots:
- dependencies:
- '@types/unist': 2.0.11
- character-entities-legacy: 3.0.0
- character-reference-invalid: 2.0.1
- decode-named-character-reference: 1.3.0
- is-alphanumerical: 2.0.1
- is-decimal: 2.0.1
- is-hexadecimal: 2.0.1
-
dependencies:
entities: 6.0.1
@@ -4838,24 +4377,6 @@ snapshots:
react: 19.2.6
react-dom: 19.2.6([email protected])
- dependencies:
- '@types/hast': 3.0.4
- '@types/mdast': 4.0.4
- '@types/react': 19.2.14
- devlop: 1.1.0
- hast-util-to-jsx-runtime: 2.3.6
- html-url-attributes: 3.0.1
- mdast-util-to-hast: 13.2.1
- react: 19.2.6
- remark-parse: 11.0.0
- remark-rehype: 11.1.2
- unified: 11.0.5
- unist-util-visit: 5.1.0
- vfile: 6.0.3
- transitivePeerDependencies:
- - supports-color
-
dependencies:
react: 19.2.6
@@ -4877,16 +4398,6 @@ snapshots:
indent-string: 4.0.0
strip-indent: 3.0.0
- dependencies:
- '@types/hast': 3.0.4
- '@types/katex': 0.16.8
- hast-util-from-html-isomorphic: 2.0.0
- hast-util-to-text: 4.0.2
- katex: 0.16.45
- unist-util-visit-parents: 6.0.2
- vfile: 6.0.3
-
dependencies:
'@types/hast': 3.0.4
@@ -4915,15 +4426,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- '@types/mdast': 4.0.4
- mdast-util-math: 3.0.0
- micromark-extension-math: 3.1.0
- unified: 11.0.5
- transitivePeerDependencies:
- - supports-color
-
dependencies:
'@types/mdast': 4.0.4
@@ -5009,25 +4511,10 @@ snapshots:
- dependencies:
- character-entities-html4: 2.1.0
- character-entities-legacy: 3.0.0
-
dependencies:
min-indent: 1.0.1
-
- dependencies:
- style-to-object: 1.0.14
-
- dependencies:
- inline-style-parser: 0.2.7
-
@@ -5115,11 +4602,6 @@ snapshots:
trough: 2.2.0
vfile: 6.0.3
- dependencies:
- '@types/unist': 3.0.3
- unist-util-is: 6.0.1
-
dependencies:
'@types/unist': 3.0.3
@@ -5128,11 +4610,6 @@ snapshots:
dependencies:
'@types/unist': 3.0.3
- dependencies:
- '@types/unist': 3.0.3
- unist-util-visit: 5.1.0
-
dependencies:
'@types/unist': 3.0.3
@@ -5232,8 +4709,6 @@ snapshots:
-
dependencies:
xml-name-validator: 5.0.0
diff --git a/web/src/components/CalendarView/dayModel.ts b/web/src/components/CalendarView/dayModel.ts
index 6636549d7..3f9e431e7 100644
--- a/web/src/components/CalendarView/dayModel.ts
+++ b/web/src/components/CalendarView/dayModel.ts
@@ -4,15 +4,14 @@ import type { Root, RootContent } from "mdast";
import { fromMarkdown } from "mdast-util-from-markdown";
import { gfmFromMarkdown } from "mdast-util-gfm";
import { gfm } from "micromark-extension-gfm";
-import { defaultUrlTransform } from "react-markdown";
import rehypeSanitize from "rehype-sanitize";
import remarkRehype from "remark-rehype";
import { unified } from "unified";
import { visit } from "unist-util-visit";
-import { SANITIZE_SCHEMA } from "@/components/MemoContent/constants";
import type { MemoTimeBasis } from "@/contexts/ViewContext";
import { getMemoSortTime } from "@/hooks/useMemoSorting";
import { ISO_DATE_FORMAT } from "@/lib/calendar-utils";
+import { SANITIZE_SCHEMA } from "@/lib/html-sanitize-schema";
import type { Memo } from "@/types/proto/api/memo_service_pb";
import { getAttachmentThumbnailUrl, getAttachmentUrl, isImage } from "@/utils/attachment";
import { classifyManagedAttachmentImageURL, extractAttachmentUIDFromName } from "@/utils/managed-attachment";
@@ -93,7 +92,8 @@ const getImageCandidates = (memo: Memo, tree: Root): string[] => {
const html = imageProcessor.runSync(tree) as HtmlRoot;
visit(html, "element", (node: Element) => {
if (node.tagName !== "img" || typeof node.properties.src !== "string") return;
- const source = defaultUrlTransform(node.properties.src);
+ // The sanitizer above already dropped any src that is not relative or https.
+ const source = node.properties.src;
if (!source) return;
const classified = classifyManagedAttachmentImageURL(source);
if (classified.kind === "invalid") return;
diff --git a/web/src/components/MemoCommentSection.tsx b/web/src/components/MemoCommentSection.tsx
index 401244394..13e73d7f0 100644
--- a/web/src/components/MemoCommentSection.tsx
+++ b/web/src/components/MemoCommentSection.tsx
@@ -47,9 +47,9 @@ const MemoCommentSection = forwardRef<MemoCommentSectionHandle, Props>(
}, []);
const focusMountedEditor = useCallback(() => {
- const codeMirrorContent = sectionRef.current?.querySelector<HTMLElement>('.cm-content[contenteditable="true"]');
+ const editorRoot = sectionRef.current?.querySelector<HTMLElement>('.memo-editor-root[contenteditable="true"]');
const fallbackInput = sectionRef.current?.querySelector<HTMLElement>("textarea, input");
- (codeMirrorContent ?? fallbackInput)?.focus();
+ (editorRoot ?? fallbackInput)?.focus();
}, []);
const openEditor = useCallback(async () => {
diff --git a/web/src/components/MemoContent/CodeBlock.tsx b/web/src/components/MemoContent/CodeBlock.tsx
deleted file mode 100644
index 66a6c37ea..000000000
--- a/web/src/components/MemoContent/CodeBlock.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-import copy from "copy-to-clipboard";
-import { escape as escapeHTML } from "lodash-es";
-import { CheckIcon, CopyIcon } from "lucide-react";
-import { isValidElement, type ReactElement, type ReactNode, useEffect, useState } from "react";
-import { useAuth } from "@/contexts/AuthContext";
-import { cn } from "@/lib/utils";
-import { getThemeWithFallback, resolveTheme } from "@/utils/theme";
-import { ensureHighlightTheme, highlightCode, isPlainTextLanguage } from "./highlight";
-import { MermaidBlock } from "./MermaidBlock";
-import type { ReactMarkdownProps } from "./markdown/types";
-import { extractCodeContent, extractLanguage } from "./utils";
-
-interface CodeBlockProps extends ReactMarkdownProps {
- children?: ReactNode;
- className?: string;
-}
-
-export const CodeBlock = ({ children, className, node: _node, ...props }: CodeBlockProps) => {
- const codeElement = isValidElement(children) ? (children as ReactElement<{ className?: string }>) : null;
- const codeClassName = codeElement?.props.className || "";
- const codeContent = extractCodeContent(children);
- const language = extractLanguage(codeClassName);
-
- // If it's a mermaid block, render with MermaidBlock component
- if (language === "mermaid") {
- return (
- <pre className="relative">
- <MermaidBlock className={cn(className)} {...props}>
- {children}
- </MermaidBlock>
- </pre>
- );
- }
-
- // Keying on the inputs remounts the block when they change, so highlight state
- // can never be shown against a different code content.
- return <HighlightedCodeBlock key={`${language}\u0000${codeContent}`} codeContent={codeContent} language={language} />;
-};
-
-interface HighlightedCodeBlockProps {
- codeContent: string;
- language: string;
-}
-
-const HighlightedCodeBlock = ({ codeContent, language }: HighlightedCodeBlockProps) => {
- const { userGeneralSetting } = useAuth();
- const [copied, setCopied] = useState(false);
- const [highlightedCode, setHighlightedCode] = useState<string>();
- const renderedCode = highlightedCode ?? escapeHTML(codeContent);
-
- const theme = getThemeWithFallback(userGeneralSetting?.theme);
- const resolvedTheme = resolveTheme(theme);
- const isDarkTheme = resolvedTheme.includes("dark");
-
- useEffect(() => {
- if (isPlainTextLanguage(language)) {
- return;
- }
-
- void ensureHighlightTheme(isDarkTheme);
- }, [isDarkTheme, language]);
-
- useEffect(() => {
- if (isPlainTextLanguage(language)) {
- // The escaped fallback already is the final output; skip the async round-trip.
- return;
- }
-
- let cancelled = false;
-
- void highlightCode(codeContent, language)
- .then((value) => {
- if (!cancelled) {
- setHighlightedCode(value);
- }
- })
- .catch(() => {
- // Keep the escaped plain-text fallback when a language chunk cannot load.
- });
-
- return () => {
- cancelled = true;
- };
- }, [codeContent, language]);
-
- const handleCopy = async () => {
- try {
- // Try native clipboard API first (requires HTTPS or localhost)
- if (navigator.clipboard && window.isSecureContext) {
- await navigator.clipboard.writeText(codeContent);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- } else {
- // Fallback to copy-to-clipboard library for non-secure contexts
- const success = await copy(codeContent);
- if (success) {
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- } else {
- console.error("Failed to copy code");
- }
- }
- } catch (err) {
- // If native API fails, try fallback
- console.warn("Native clipboard failed, using fallback:", err);
- const success = await copy(codeContent);
- if (success) {
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- } else {
- console.error("Failed to copy code:", err);
- }
- }
- };
-
- return (
- <pre className="relative my-0 mb-2 rounded-lg border border-border bg-muted/20 overflow-hidden">
- {/* Header with language label and copy button */}
- <div className="flex items-center justify-between px-2 py-1 border-b border-border bg-muted/30">
- <span className="text-xs text-foreground select-none">{language || "text"}</span>
- <button
- onClick={handleCopy}
- className={cn(
- "inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs",
- "transition-colors duration-200",
- "hover:bg-accent active:scale-95",
- copied ? "text-primary" : "text-muted-foreground hover:text-foreground",
- )}
- aria-label={copied ? "Copied" : "Copy code"}
- title={copied ? "Copied!" : "Copy code"}
- >
- {copied ? (
- <>
- <CheckIcon className="w-3.5 h-3.5" />
- <span>Copied</span>
- </>
- ) : (
- <>
- <CopyIcon className="w-3.5 h-3.5" />
- <span>Copy</span>
- </>
- )}
- </button>
- </div>
-
- {/* Code content */}
- <div className="overflow-x-auto">
- <code
- className={cn("block px-3 py-2 text-sm leading-relaxed", `language-${language}`)}
- dangerouslySetInnerHTML={{ __html: renderedCode }}
- />
- </div>
- </pre>
- );
-};
diff --git a/web/src/components/MemoContent/MarkdownRenderContext.tsx b/web/src/components/MemoContent/MarkdownRenderContext.tsx
deleted file mode 100644
index 8f906aa31..000000000
--- a/web/src/components/MemoContent/MarkdownRenderContext.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { createContext, useContext, useMemo } from "react";
-
-interface MarkdownRenderContextValue {
- blockDepth: number;
-}
-
-export const rootMarkdownRenderContext: MarkdownRenderContextValue = {
- blockDepth: 0,
-};
-
-export const MarkdownRenderContext = createContext<MarkdownRenderContextValue>(rootMarkdownRenderContext);
-
-export const useMarkdownRenderContext = () => {
- return useContext(MarkdownRenderContext);
-};
-
-export const NestedMarkdownRenderContext = ({ children }: { children: React.ReactNode }) => {
- const { blockDepth } = useMarkdownRenderContext();
- const value = useMemo<MarkdownRenderContextValue>(() => ({ blockDepth: blockDepth + 1 }), [blockDepth]);
-
- return <MarkdownRenderContext.Provider value={value}>{children}</MarkdownRenderContext.Provider>;
-};
diff --git a/web/src/components/MemoContent/MathMarkdownRenderer.tsx b/web/src/components/MemoContent/MathMarkdownRenderer.tsx
deleted file mode 100644
index 4400a71d6..000000000
--- a/web/src/components/MemoContent/MathMarkdownRenderer.tsx
+++ /dev/null
@@ -1,14 +0,0 @@
-import "katex/dist/katex.min.css";
-import rehypeKatex from "rehype-katex";
-import { remarkCurrencySafeMath } from "@/utils/remark-plugins/remark-currency-safe-math";
-import { MemoMarkdownRendererCore, type MemoMarkdownRendererProps } from "./MemoMarkdownRenderer";
-
-const MathMarkdownRenderer = (props: MemoMarkdownRendererProps) => (
- <MemoMarkdownRendererCore
- {...props}
- mathRemarkPlugins={[remarkCurrencySafeMath]}
- mathRehypePlugins={[[rehypeKatex, { throwOnError: false, strict: false }]]}
- />
-);
-
-export default MathMarkdownRenderer;
diff --git a/web/src/components/MemoContent/MemoMarkdownRenderer.tsx b/web/src/components/MemoContent/MemoMarkdownRenderer.tsx
deleted file mode 100644
index 6e17a373a..000000000
--- a/web/src/components/MemoContent/MemoMarkdownRenderer.tsx
+++ /dev/null
@@ -1,214 +0,0 @@
-import type { Element } from "hast";
-import { type ComponentProps, memo, type ReactNode, Suspense } from "react";
-import type { Components } from "react-markdown";
-import ReactMarkdown from "react-markdown";
-import { buildRehypePlugins, buildRemarkPlugins } from "@/components/MemoContent/pipeline";
-import { isMentionElement, isTagElement, isTaskListItemElement } from "@/types/markdown";
-import type { Attachment } from "@/types/proto/api/attachment_service_pb";
-import { lazyWithReload } from "@/utils/lazy";
-import { resolveManagedAttachmentImageSource } from "@/utils/managed-attachment";
-import { CodeBlock } from "./CodeBlock";
-import { memoUrlTransform } from "./constants";
-import { MarkdownRenderContext, rootMarkdownRenderContext } from "./MarkdownRenderContext";
-import { Mention } from "./Mention";
-import {
- AnchorLink,
- Blockquote,
- Details,
- Heading,
- HorizontalRule,
- Image,
- InlineCode,
- Link,
- List,
- ListItem,
- Paragraph,
- Summary,
-} from "./markdown";
-import { hasMathSyntax } from "./math";
-import { Table, TableBody, TableCell, TableHead, TableHeaderCell, TableRow } from "./Table";
-import { Tag } from "./Tag";
-import { TaskListItem } from "./TaskListItem";
-import { TrustedIframe } from "./TrustedIframe";
-
-export interface MemoMarkdownRendererProps {
- content: string;
- attachments?: Attachment[];
- resolvedMentionUsernames: Set<string>;
- /** Resource name of the memo (e.g. `memos/abc123`), used to target footnote links at the detail page. */
- memoName?: string;
- /** Collection page that opened the memo detail. */
- parentPage?: string;
- /** Whether the memo is rendered as a collapsed feed card. */
- compact?: boolean;
-}
-
-type RemarkPlugins = NonNullable<ComponentProps<typeof ReactMarkdown>["remarkPlugins"]>;
-type RehypePlugins = NonNullable<ComponentProps<typeof ReactMarkdown>["rehypePlugins"]>;
-
-interface MemoMarkdownRendererCoreProps extends MemoMarkdownRendererProps {
- /** Math plugins injected by MathMarkdownRenderer; the remark ones must run before remarkGfm. */
- mathRemarkPlugins?: RemarkPlugins;
- mathRehypePlugins?: RehypePlugins;
-}
-
-const MathMarkdownRenderer = lazyWithReload(() => import("./MathMarkdownRenderer"));
-
-function getMentionUsername(node: Element, children?: ReactNode): string {
- const dataMention = node.properties?.["data-mention"];
- if (typeof dataMention === "string" && dataMention !== "") {
- return dataMention;
- }
-
- const camelDataMention = (node.properties as Record<string, unknown> | undefined)?.dataMention;
- if (typeof camelDataMention === "string" && camelDataMention !== "") {
- return camelDataMention;
- }
-
- const text = Array.isArray(children) ? children.join("") : children;
- if (typeof text === "string" && text.startsWith("@")) {
- return text.slice(1);
- }
-
- return "";
-}
-
-export const MemoMarkdownRendererCore = ({
- content,
- attachments = [],
- resolvedMentionUsernames,
- memoName,
- parentPage,
- compact,
- mathRemarkPlugins = [],
- mathRehypePlugins = [],
-}: MemoMarkdownRendererCoreProps) => {
- const markdownComponents: Components = {
- input: ({ node, ...inputProps }) => {
- if (node && isTaskListItemElement(node)) {
- return <TaskListItem {...inputProps} node={node} />;
- }
- return <input {...inputProps} />;
- },
- span: ({ node, ...spanProps }) => {
- if (node && isMentionElement(node)) {
- const username = getMentionUsername(node, spanProps.children);
- return <Mention {...spanProps} node={node} data-mention={username} resolved={resolvedMentionUsernames.has(username)} />;
- }
- if (node && isTagElement(node)) {
- return <Tag {...spanProps} node={node} />;
- }
- return <span {...spanProps} />;
- },
- h1: ({ children, ...props }) => (
- <Heading level={1} {...props}>
- {children}
- </Heading>
- ),
- h2: ({ children, ...props }) => (
- <Heading level={2} {...props}>
- {children}
- </Heading>
- ),
- h3: ({ children, ...props }) => (
- <Heading level={3} {...props}>
- {children}
- </Heading>
- ),
- h4: ({ children, ...props }) => (
- <Heading level={4} {...props}>
- {children}
- </Heading>
- ),
- h5: ({ children, ...props }) => (
- <Heading level={5} {...props}>
- {children}
- </Heading>
- ),
- h6: ({ children, ...props }) => (
- <Heading level={6} {...props}>
- {children}
- </Heading>
- ),
- p: ({ children, ...props }) => <Paragraph {...props}>{children}</Paragraph>,
- blockquote: ({ children, ...props }) => <Blockquote {...props}>{children}</Blockquote>,
- details: Details,
- summary: Summary,
- hr: (props) => <HorizontalRule {...props} />,
- ul: ({ children, ...props }) => <List {...props}>{children}</List>,
- ol: ({ children, ...props }) => (
- <List ordered {...props}>
- {children}
- </List>
- ),
- li: ({ children, ...props }) => <ListItem {...props}>{children}</ListItem>,
- a: ({ children, href, ...props }) => {
- // In-page anchors (footnote refs/backrefs, heading links) navigate within the memo rather
- // than opening a new tab; everything else is treated as an external link.
- if (typeof href === "string" && href.startsWith("#")) {
- return (
- <AnchorLink href={href} memoName={memoName} parentPage={parentPage} compact={compact} {...props}>
- {children}
- </AnchorLink>
- );
- }
- return (
- <Link href={href} {...props}>
- {children}
- </Link>
- );
- },
- code: ({ children, ...props }) => <InlineCode {...props}>{children}</InlineCode>,
- iframe: TrustedIframe,
- img: ({ src, ...props }) => <Image {...props} src={resolveManagedAttachmentImageSource(src, attachments)} />,
- pre: CodeBlock,
- table: ({ children, ...props }) => <Table {...props}>{children}</Table>,
- thead: ({ children, ...props }) => <TableHead {...props}>{children}</TableHead>,
- tbody: ({ children, ...props }) => <TableBody {...props}>{children}</TableBody>,
- tr: ({ children, ...props }) => <TableRow {...props}>{children}</TableRow>,
- th: ({ children, ...props }) => <TableHeaderCell {...props}>{children}</TableHeaderCell>,
- td: ({ children, ...props }) => <TableCell {...props}>{children}</TableCell>,
- };
-
- return (
- <MarkdownRenderContext.Provider value={rootMarkdownRenderContext}>
- <ReactMarkdown
- remarkPlugins={buildRemarkPlugins(mathRemarkPlugins)}
- rehypePlugins={buildRehypePlugins(mathRehypePlugins)}
- urlTransform={memoUrlTransform}
- components={markdownComponents}
- >
- {content}
- </ReactMarkdown>
- </MarkdownRenderContext.Provider>
- );
-};
-
-const MemoMarkdownRendererComponent = (props: MemoMarkdownRendererProps) => {
- if (!hasMathSyntax(props.content)) {
- return <MemoMarkdownRendererCore {...props} />;
- }
-
- return (
- <Suspense fallback={<MemoMarkdownRendererCore {...props} />}>
- <MathMarkdownRenderer {...props} />
- </Suspense>
- );
-};
-
-const haveEqualResolvedMentions = (left: Set<string>, right: Set<string>) => {
- if (left === right) return true;
- if (left.size !== right.size) return false;
- return Array.from(left).every((username) => right.has(username));
-};
-
-export const MemoMarkdownRenderer = memo(
- MemoMarkdownRendererComponent,
- (previous, next) =>
- previous.content === next.content &&
- previous.attachments === next.attachments &&
- previous.memoName === next.memoName &&
- previous.parentPage === next.parentPage &&
- previous.compact === next.compact &&
- haveEqualResolvedMentions(previous.resolvedMentionUsernames, next.resolvedMentionUsernames),
-);
diff --git a/web/src/components/MemoContent/Mention.tsx b/web/src/components/MemoContent/Mention.tsx
deleted file mode 100644
index 59f6b0102..000000000
--- a/web/src/components/MemoContent/Mention.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import type { Element } from "hast";
-import { mentionStyles } from "@/lib/markdownStyles";
-import { cn } from "@/lib/utils";
-import { getCreatorHomePath } from "@/router/routes";
-
-interface MentionProps extends React.HTMLAttributes<HTMLSpanElement> {
- node?: Element;
- "data-mention"?: string;
- children?: React.ReactNode;
- resolved?: boolean;
-}
-
-export const Mention: React.FC<MentionProps> = ({
- "data-mention": dataMention,
- children,
- className,
- node: _node,
- resolved = false,
- ...props
-}) => {
- const username = dataMention || "";
-
- if (!resolved) {
- return (
- <span data-mention={username} title={`@${username}`} className={className} {...props}>
- {children}
- </span>
- );
- }
-
- return (
- <a
- href={getCreatorHomePath(username)}
- className={cn(mentionStyles.base, "hover:underline", className)}
- data-mention={username}
- title={`@${username}`}
- {...props}
- >
- {children}
- </a>
- );
-};
diff --git a/web/src/components/MemoContent/MentionResolutionContext.tsx b/web/src/components/MemoContent/MentionResolutionContext.tsx
index c18cadcdf..0974aa72f 100644
--- a/web/src/components/MemoContent/MentionResolutionContext.tsx
+++ b/web/src/components/MemoContent/MentionResolutionContext.tsx
@@ -1,9 +1,9 @@
import { useQueries } from "@tanstack/react-query";
import { createContext, type ReactNode, useContext, useMemo } from "react";
import { userDetailQueryOptions, useUsersByUsernames } from "@/hooks/useUserQueries";
+import { extractMentionUsernames } from "@/lib/memo-markdown";
import { extractUsernameFromName } from "@/lib/resource-names";
import type { User } from "@/types/proto/api/user_service_pb";
-import { extractMentionUsernames } from "@/utils/mention-extraction";
interface UserResolutionContextValue {
mentionUsernamesByContent: ReadonlyMap<string, string[]>;
diff --git a/web/src/components/MemoContent/MermaidBlock.tsx b/web/src/components/MemoContent/MermaidBlock.tsx
deleted file mode 100644
index 993e6b06b..000000000
--- a/web/src/components/MemoContent/MermaidBlock.tsx
+++ /dev/null
@@ -1,108 +0,0 @@
-import { useEffect, useMemo, useState } from "react";
-import { useAuth } from "@/contexts/AuthContext";
-import { cn } from "@/lib/utils";
-import { getThemeWithFallback, resolveTheme, setupSystemThemeListener } from "@/utils/theme";
-import { extractCodeContent } from "./utils";
-
-interface MermaidBlockProps {
- children?: React.ReactNode;
- className?: string;
-}
-
-type MermaidTheme = "default" | "dark";
-
-const toMermaidTheme = (appTheme: string): MermaidTheme => (appTheme === "default-dark" ? "dark" : "default");
-
-const formatErrorMessage = (err: unknown): string => {
- const msg = err instanceof Error ? err.message : "Failed to render diagram";
- if (/no diagram type detected/i.test(msg)) {
- return `${msg} — check that the diagram type is valid (e.g. sequenceDiagram, classDiagram, erDiagram)`;
- }
- return msg;
-};
-
-export const MermaidBlock = ({ children, className }: MermaidBlockProps) => {
- const { userGeneralSetting } = useAuth();
- const [svg, setSvg] = useState<string>("");
- const [error, setError] = useState<string>("");
- const [systemThemeChange, setSystemThemeChange] = useState(0);
-
- const codeContent = extractCodeContent(children);
- const themePreference = getThemeWithFallback(userGeneralSetting?.theme);
- const currentTheme = useMemo(() => resolveTheme(themePreference), [themePreference, systemThemeChange]);
-
- // Re-resolve theme when OS preference changes (only relevant when using "system" theme)
- useEffect(() => {
- if (themePreference !== "system") return;
- return setupSystemThemeListener(() => setSystemThemeChange((n) => n + 1));
- }, [themePreference]);
-
- // Render diagram when content or theme changes
- useEffect(() => {
- if (!codeContent) {
- setSvg("");
- setError("");
- return;
- }
-
- let cancelled = false;
-
- const renderDiagram = async () => {
- try {
- const { default: mermaid } = await import("mermaid");
- // Text is measured against the final glyphs, so webfonts must be loaded
- // first. The Font Loading API is absent in some environments (jsdom).
- await document.fonts?.ready;
- if (cancelled) return;
-
- mermaid.initialize({
- startOnLoad: false,
- theme: toMermaidTheme(currentTheme),
- securityLevel: "strict",
- // Mermaid measures labels in a detached element at body level, but the
- // rendered SVG lands inside a <pre> (monospace). "inherit" resolves to
- // different fonts in those two places, sizing boxes too small for the
- // final glyphs — pin the font so measurement and display agree.
- fontFamily: getComputedStyle(document.body).fontFamily || "sans-serif",
- suppressErrorRendering: true,
- });
-
- const id = `mermaid-${Math.random().toString(36).substring(7)}`;
- const { svg: renderedSvg } = await mermaid.render(id, codeContent);
- if (cancelled) return;
-
- setSvg(renderedSvg);
- setError("");
- } catch (err) {
- if (cancelled) return;
- console.error("Failed to render mermaid diagram:", err);
- setSvg("");
- setError(formatErrorMessage(err));
- }
- };
-
- renderDiagram();
-
- return () => {
- cancelled = true;
- };
- }, [codeContent, currentTheme]);
-
- if (error) {
- return (
- <div className="w-full">
- <div className="text-sm text-destructive mb-2 whitespace-normal break-words">Mermaid Error: {error}</div>
- <code className="block language-mermaid whitespace-pre text-sm">{codeContent}</code>
- </div>
- );
- }
-
- if (!svg) return null;
-
- return (
- <div
- className={cn("mermaid-diagram w-full flex justify-center items-center my-0 mb-2 overflow-x-auto", className)}
- dangerouslySetInnerHTML={{ __html: svg }}
- />
- );
-};
diff --git a/web/src/components/MemoContent/Table.tsx b/web/src/components/MemoContent/Table.tsx
deleted file mode 100644
index b079e44a2..000000000
--- a/web/src/components/MemoContent/Table.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-import { cn } from "@/lib/utils";
-import { NestedMarkdownRenderContext } from "./MarkdownRenderContext";
-import type { ReactMarkdownProps } from "./markdown/types";
-
-interface TableProps extends React.HTMLAttributes<HTMLTableElement>, ReactMarkdownProps {
- children: React.ReactNode;
-}
-
-export const Table = ({ children, className, node: _node, ...props }: TableProps) => {
- return (
- <div className="my-0 mb-2 w-full overflow-x-auto rounded-lg border border-border bg-muted/20">
- <table className={cn("w-full border-collapse text-sm", className)} {...props}>
- {children}
- </table>
- </div>
- );
-};
-
-interface TableHeadProps extends React.HTMLAttributes<HTMLTableSectionElement>, ReactMarkdownProps {
- children: React.ReactNode;
-}
-
-export const TableHead = ({ children, className, node: _node, ...props }: TableHeadProps) => {
- return (
- <thead className={cn("border-b border-border bg-muted/30", className)} {...props}>
- {children}
- </thead>
- );
-};
-
-interface TableBodyProps extends React.HTMLAttributes<HTMLTableSectionElement>, ReactMarkdownProps {
- children: React.ReactNode;
-}
-
-export const TableBody = ({ children, className, node: _node, ...props }: TableBodyProps) => {
- return (
- <tbody className={cn("divide-y divide-border", className)} {...props}>
- {children}
- </tbody>
- );
-};
-
-interface TableRowProps extends React.HTMLAttributes<HTMLTableRowElement>, ReactMarkdownProps {
- children: React.ReactNode;
-}
-
-export const TableRow = ({ children, className, node: _node, ...props }: TableRowProps) => {
- return (
- <tr className={cn("transition-colors hover:bg-accent/20", className)} {...props}>
- {children}
- </tr>
- );
-};
-
-interface TableHeaderCellProps extends React.ThHTMLAttributes<HTMLTableCellElement>, ReactMarkdownProps {
- children: React.ReactNode;
-}
-
-export const TableHeaderCell = ({ children, className, node: _node, ...props }: TableHeaderCellProps) => {
- return (
- <th className={cn("px-2 py-1 text-left align-middle text-sm font-medium text-muted-foreground", className)} {...props}>
- <NestedMarkdownRenderContext>{children}</NestedMarkdownRenderContext>
- </th>
- );
-};
-
-interface TableCellProps extends React.TdHTMLAttributes<HTMLTableCellElement>, ReactMarkdownProps {
- children: React.ReactNode;
-}
-
-export const TableCell = ({ children, className, node: _node, ...props }: TableCellProps) => {
- return (
- <td className={cn("px-2 py-1 text-left align-middle text-sm", className)} {...props}>
- <NestedMarkdownRenderContext>{children}</NestedMarkdownRenderContext>
- </td>
- );
-};
diff --git a/web/src/components/MemoContent/Tag.tsx b/web/src/components/MemoContent/Tag.tsx
deleted file mode 100644
index c8f9558af..000000000
--- a/web/src/components/MemoContent/Tag.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import type { Element } from "hast";
-import { useLocation } from "react-router-dom";
-import { useAuth } from "@/contexts/AuthContext";
-import { type MemoFilter, stringifyFilters, useMemoFilterContext } from "@/contexts/MemoFilterContext";
-import useNavigateTo from "@/hooks/useNavigateTo";
-import { colorToHex } from "@/lib/color";
-import { tagStyles } from "@/lib/markdownStyles";
-import { findTagMetadata } from "@/lib/tag";
-import { cn } from "@/lib/utils";
-import { Routes } from "@/router";
-import { useMemoViewContext } from "../MemoView/MemoViewContext";
-import { isMemoResourcePath, withMemoFilter } from "../MemoView/navigation";
-
-interface TagProps extends React.HTMLAttributes<HTMLSpanElement> {
- node?: Element; // AST node from react-markdown
- "data-tag"?: string;
- children?: React.ReactNode;
-}
-
-export const Tag: React.FC<TagProps> = ({ "data-tag": dataTag, children, className, style, node: _node, ...props }) => {
- const { parentPage } = useMemoViewContext();
- const location = useLocation();
- const navigateTo = useNavigateTo();
- const { getFiltersByFactor, removeFilter, addFilter } = useMemoFilterContext();
- const { userTagsSetting } = useAuth();
-
- const tag = dataTag || "";
-
- // Custom color from user tag metadata. Dynamic hex values must use inline styles
- // because Tailwind can't scan dynamically constructed class names.
- // Text uses a darkened variant (40% color + black) for contrast on light backgrounds.
- const metadata = userTagsSetting ? findTagMetadata(tag, userTagsSetting) : undefined;
- const bgHex = colorToHex(metadata?.backgroundColor);
- const tagStyle: React.CSSProperties | undefined = bgHex
- ? {
- borderColor: bgHex,
- color: `color-mix(in srgb, ${bgHex} 60%, black)`,
- backgroundColor: `color-mix(in srgb, ${bgHex} 15%, transparent)`,
- ...style,
- }
- : style;
-
- const handleTagClick = (e: React.MouseEvent) => {
- e.stopPropagation();
-
- // If the tag is clicked in a memo detail page, we should navigate to the memo list page.
- if (isMemoResourcePath(location.pathname)) {
- navigateTo(withMemoFilter(parentPage || Routes.HOME, stringifyFilters([{ factor: "tagSearch", value: tag }])));
- return;
- }
-
- const isActive = getFiltersByFactor("tagSearch").some((filter: MemoFilter) => filter.value === tag);
- if (isActive) {
- removeFilter((f: MemoFilter) => f.factor === "tagSearch" && f.value === tag);
- } else {
- // Remove all existing tag filters first, then add the new one
- removeFilter((f: MemoFilter) => f.factor === "tagSearch");
- addFilter({
- factor: "tagSearch",
- value: tag,
- });
- }
- };
-
- return (
- <span
- className={cn(tagStyles.base, "cursor-pointer transition-opacity hover:opacity-75", !bgHex && tagStyles.defaultColor, className)}
- style={tagStyle}
- data-tag={tag}
- {...props}
- onClick={handleTagClick}
- >
- {children}
- </span>
- );
-};
diff --git a/web/src/components/MemoContent/TaskListItem.tsx b/web/src/components/MemoContent/TaskListItem.tsx
deleted file mode 100644
index 22254290f..000000000
--- a/web/src/components/MemoContent/TaskListItem.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { useRef } from "react";
-import { Checkbox } from "@/components/ui/checkbox";
-import { useUpdateMemo } from "@/hooks/useMemoQueries";
-import { toggleTaskAtIndex } from "@/utils/markdown-manipulation";
-import { useMemoViewContext, useMemoViewDerived } from "../MemoView/MemoViewContext";
-import { TASK_LIST_ITEM_CLASS } from "./constants";
-import type { ReactMarkdownProps } from "./markdown/types";
-
-interface TaskListItemProps extends React.InputHTMLAttributes<HTMLInputElement>, ReactMarkdownProps {
- checked?: boolean;
-}
-
-export const TaskListItem: React.FC<TaskListItemProps> = ({ checked, node: _node, ...props }) => {
- const { memo } = useMemoViewContext();
- const { readonly } = useMemoViewDerived();
- const checkboxRef = useRef<HTMLButtonElement>(null);
- const { mutate: updateMemo } = useUpdateMemo();
-
- const handleChange = async (newChecked: boolean) => {
- // Don't update if readonly or no memo
- if (readonly || !memo) {
- return;
- }
-
- // Find the task index by walking up the DOM
- const listItem = checkboxRef.current?.closest("li.task-list-item");
- if (!listItem) {
- return;
- }
-
- // Get task index from data attribute, or calculate by counting
- const taskIndexStr = listItem.getAttribute("data-task-index");
- let taskIndex = 0;
-
- if (taskIndexStr !== null) {
- taskIndex = parseInt(taskIndexStr);
- } else {
- // Fallback: Calculate index by counting all task list items in the entire memo
- // We need to search from the root memo content container, not just the nearest list
- // to ensure nested tasks are counted in document order
- let searchRoot = listItem.closest("[data-memo-content]");
-
- // If memo content container not found, search from document body
- if (!searchRoot) {
- searchRoot = document.body;
- }
-
- const allTaskItems = searchRoot.querySelectorAll(`li.${TASK_LIST_ITEM_CLASS}`);
- for (let i = 0; i < allTaskItems.length; i++) {
- if (allTaskItems[i] === listItem) {
- taskIndex = i;
- break;
- }
- }
- }
-
- // Update memo content using the string manipulation utility
- const newContent = toggleTaskAtIndex(memo.content, taskIndex, newChecked);
- updateMemo({
- update: {
- name: memo.name,
- content: newContent,
- },
- updateMask: ["content", "update_time"],
- });
- };
-
- // Override the disabled prop from remark-gfm (which defaults to true).
- // `checked` is undefined for unchecked tasks; Base UI locks controlled/uncontrolled
- // mode at mount, so coerce to boolean to keep the checkbox always controlled.
- return (
- <Checkbox ref={checkboxRef} checked={Boolean(checked)} disabled={readonly} onCheckedChange={handleChange} className={props.className} />
- );
-};
diff --git a/web/src/components/MemoContent/TrustedIframe.ts b/web/src/components/MemoContent/TrustedIframe.ts
deleted file mode 100644
index 65d9e657a..000000000
--- a/web/src/components/MemoContent/TrustedIframe.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { createElement } from "react";
-import { cn } from "@/lib/utils";
-import { isTrustedIframeSrc } from "./constants";
-
-export const TrustedIframe = (props: React.ComponentProps<"iframe">) => {
- if (typeof props.src !== "string" || !isTrustedIframeSrc(props.src)) {
- return null;
- }
-
- return createElement("iframe", {
- ...props,
- className: cn("max-w-full rounded-lg border border-border", props.className),
- });
-};
diff --git a/web/src/components/MemoContent/enhance.ts b/web/src/components/MemoContent/enhance.ts
new file mode 100644
index 000000000..2814ab279
--- /dev/null
+++ b/web/src/components/MemoContent/enhance.ts
@@ -0,0 +1,54 @@
+import { type Block, type Editor, inlineText } from "@usememos/editor";
+
+/** App UI mounted into the read-only editor's DOM with a portal. */
+export type Island = { key: string; target: HTMLElement; href: string };
+
+let islandCounter = 0;
+/** Stable portal keys per target element, so a second pass does not remount mounted islands. */
+const islandKeys = new WeakMap<HTMLElement, string>();
+const islandKey = (target: HTMLElement): string => {
+ let key = islandKeys.get(target);
+ if (!key) {
+ key = `island-${++islandCounter}`;
+ islandKeys.set(target, key);
+ }
+ return key;
+};
+
+/** The URL a paragraph consists of, when it is nothing but one bare web link: `https://…` written as its own text. */
+function bareLinkOf(block: Block): string | undefined {
+ if (block.type !== "paragraph" || block.content.length === 0) return undefined;
+ const href = block.content[0].link;
+ // Only web links have metadata to preview; `tel:`/`sms:`/`mailto:` hand off to another app.
+ if (!href || !/^https?:\/\//i.test(href)) return undefined;
+ if (!block.content.every((span) => span.link === href && !span.image)) return undefined;
+ return inlineText(block.content) === href ? href : undefined;
+}
+
+const blockElement = (root: HTMLElement, blockId: string) => root.querySelector<HTMLElement>(`[data-block-id="${CSS.escape(blockId)}"]`);
+
+/**
+ * The places in the read-only editor's DOM where memos' own UI takes over: a link card
+ * in place of a paragraph that is one bare link, which needs the page's details from the
+ * memos server. Everything else the view shows comes from the editor. Safe to run
+ * repeatedly: targets keep their keys, and only new targets are prepared.
+ */
+export function findIslands(editor: Editor, root: HTMLElement, linkPreviewEnabled: boolean): Island[] {
+ const islands: Island[] = [];
+ for (const block of editor.state.doc.blocks) {
+ const href = linkPreviewEnabled ? bareLinkOf(block) : undefined;
+ const target = href ? blockElement(root, block.id) : null;
+ if (!href || !target) continue;
+ if (!target.hasAttribute("data-link-preview")) {
+ target.setAttribute("data-link-preview", "");
+ target.replaceChildren();
+ }
+ islands.push({ key: islandKey(target), target, href });
+ }
+ return islands;
+}
+
+/** Whether two passes produced the same islands, so React can skip a render. */
+export const sameIslands = (a: readonly Island[], b: readonly Island[]): boolean =>
+ a.length === b.length &&
+ a.every((island, index) => island.key === b[index].key && island.target === b[index].target && island.href === b[index].href);
diff --git a/web/src/components/MemoContent/headings.ts b/web/src/components/MemoContent/headings.ts
new file mode 100644
index 000000000..8a0c5bf31
--- /dev/null
+++ b/web/src/components/MemoContent/headings.ts
@@ -0,0 +1,44 @@
+import { inlineText } from "@usememos/editor";
+import { RESERVED_MEMO_COMMENTS_ANCHOR_IDS } from "@/lib/memo-comments";
+import { parseMemoMarkdown } from "@/lib/memo-markdown";
+import { createUniqueSlugGenerator, slugify } from "@/utils/markdown-manipulation";
+
+/** Anchor used for headings with no slugifiable characters (emoji- or punctuation-only titles). */
+const FALLBACK_HEADING_SLUG = "heading";
+
+export interface HeadingItem {
+ text: string;
+ level: 1 | 2 | 3 | 4;
+ slug: string;
+}
+
+/**
+ * The anchor of every heading, in document order. This is the single place a heading
+ * anchor is decided: the memo view gives these to the editor as element ids
+ * (`headingIds`) and the outline links to them, so an outline link always has somewhere
+ * to land. Every heading consumes a slug, including h5/h6 and titles that slugify to
+ * nothing, because duplicate suffixes depend on how many headings came before.
+ */
+export function headingSlugs(headings: readonly { readonly text: string }[]): string[] {
+ const makeUniqueSlug = createUniqueSlugGenerator(RESERVED_MEMO_COMMENTS_ANCHOR_IDS);
+ return headings.map(({ text }) => makeUniqueSlug(slugify(text.trim()) || FALLBACK_HEADING_SLUG));
+}
+
+/**
+ * Every heading is ATX (up to three spaces, then 1–6 `#` and a space); setext is disabled.
+ * Content matching neither cannot produce a heading, which lets the common short memo skip
+ * the parse below. False positives (a `#` inside a code fence) only cost the parse.
+ */
+const MAYBE_HAS_HEADING = /^[ \t]{0,3}#{1,6}[ \t]/m;
+
+/** h1–h4 headings for outline navigation, read the way the memo view reads the memo. */
+export function extractHeadings(markdown: string): HeadingItem[] {
+ if (!MAYBE_HAS_HEADING.test(markdown)) return [];
+ const headings = parseMemoMarkdown(markdown).blocks.flatMap((block) =>
+ block.type === "heading" ? [{ text: inlineText(block.content).trim(), level: block.level }] : [],
+ );
+ const slugs = headingSlugs(headings);
+ return headings.flatMap((heading, index) =>
+ heading.level <= 4 && heading.text ? [{ text: heading.text, level: heading.level as HeadingItem["level"], slug: slugs[index]! }] : [],
+ );
+}
diff --git a/web/src/components/MemoContent/index.tsx b/web/src/components/MemoContent/index.tsx
index ec09a76ef..8390197b7 100644
--- a/web/src/components/MemoContent/index.tsx
+++ b/web/src/components/MemoContent/index.tsx
@@ -1,53 +1,195 @@
-import { memo, useRef } from "react";
+import type { Editor } from "@usememos/editor";
+import { MarkdownEditor } from "@usememos/editor/react";
+import "@usememos/editor/style.css";
+import { memo, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
+import { createPortal } from "react-dom";
+import { useNavigate } from "react-router-dom";
+import { useAuth } from "@/contexts/AuthContext";
import { useContentSearchTerms } from "@/contexts/MemoFilterContext";
+import { useLinkPreviewEnabled } from "@/contexts/ViewContext";
+import { useNearViewport } from "@/hooks/useNearViewport";
+import { markdownStyles } from "@/lib/markdownStyles";
+import {
+ MEMO_EDITOR_THEME,
+ MEMO_MARKDOWN,
+ memoEditorLabels,
+ memoExtensions,
+ memoMentionOptions,
+ memoResolveUrl,
+ memoTagOptions,
+} from "@/lib/memo-markdown";
import { cn } from "@/lib/utils";
-import { MemoMarkdownRenderer } from "./MemoMarkdownRenderer";
+import { getCreatorHomePath } from "@/router/routes";
+import { useTranslate } from "@/utils/i18n";
+import { findAnchorTarget } from "@/utils/markdown-manipulation";
+import { createMemoNavigationState } from "../MemoView/navigation";
+import { findIslands, type Island, sameIslands } from "./enhance";
+import { headingSlugs } from "./headings";
+import LinkMetadataCard from "./LinkMetadataCard";
import { useResolvedMentionUsernames } from "./MentionResolutionContext";
import type { MemoContentProps } from "./types";
import { useSearchMatchHighlight } from "./useSearchMatchHighlight";
+import { useTagNavigation } from "./useTagNavigation";
-// Stateless markdown renderer. Truncation is not this component's concern — compact cards
-// are bounded by ClampedSection around the whole memo body; `compact` here only informs
-// the renderer (e.g. footnote links navigate to the detail page instead of scrolling,
-// since a collapsed card may hide the target).
+// A memo with a Mermaid diagram draws it in the page's color scheme; the editor keeps drawn
+// diagrams, so a new scheme needs a new editor to draw them again.
+const MERMAID_FENCE = /^ {0,3}(?:`{3,}|~{3,})[ \t]*mermaid\b/im;
+const subscribeColorScheme = (onChange: () => void) => {
+ const observer = new MutationObserver(onChange);
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["style"] });
+ return () => observer.disconnect();
+};
+const getColorScheme = () => document.documentElement.style.colorScheme;
+
+const LinkPreview = ({ href }: { href: string }) => {
+ const { ref, isNearViewport } = useNearViewport<HTMLAnchorElement>();
+ const fallback = (
+ <a ref={ref} href={href} target="_blank" rel="noopener noreferrer" className={markdownStyles.link}>
+ {href}
+ </a>
+ );
+ return <LinkMetadataCard url={href} fallback={fallback} enabled={isNearViewport} />;
+};
+
+/**
+ * A memo's content, shown by the same Markdown editor the composer uses, read-only. Owners
+ * can tick task items: each tick reports the new Markdown, in which only that item's
+ * `[ ]` or `[x]` changed. Truncation is not this component's concern — compact cards are
+ * bounded by ClampedSection around the whole memo body; `compact` only tells in-memo
+ * anchor links to open the detail page, since a collapsed card may hide their target.
+ */
const MemoContent = (props: MemoContentProps) => {
- const { className, contentClassName, content, attachments, onClick, onDoubleClick } = props;
+ const { className, contentClassName, content, attachments, memoName, parentPage, compact, onTaskToggle, onClick, onDoubleClick } = props;
+ const t = useTranslate();
+ const navigate = useNavigate();
+ const { userTagsSetting } = useAuth();
+ const labels = useMemo(() => memoEditorLabels(t), [t]);
+ const linkPreviewEnabled = useLinkPreviewEnabled();
const resolvedMentionUsernames = useResolvedMentionUsernames(content);
+ const navigateToTag = useTagNavigation(parentPage);
// Whatever the page's search matched is painted here, without altering the rendered tree.
const contentRef = useRef<HTMLDivElement>(null);
useSearchMatchHighlight(contentRef, useContentSearchTerms());
+ const [editor, setEditor] = useState<Editor | null>(null);
+ const colorScheme = useSyncExternalStore(subscribeColorScheme, getColorScheme, () => "");
+ const editorKey = MERMAID_FENCE.test(content) ? colorScheme : undefined;
+ const [islands, setIslands] = useState<Island[]>([]);
+
+ // Tag colors and resolved mentions come from outside the document: the decorations
+ // read them here, and the editor decorates again when they change.
+ const decorationState = useRef({ resolvedMentionUsernames, userTagsSetting });
+ decorationState.current = { resolvedMentionUsernames, userTagsSetting };
+ const extensions = useMemo(
+ () =>
+ memoExtensions({
+ tags: memoTagOptions(() => decorationState.current.userTagsSetting),
+ mentions: memoMentionOptions((username) => decorationState.current.resolvedMentionUsernames.has(username)),
+ }),
+ [],
+ );
+ // Redecorate only when what the decorations read actually changed: a new editor already
+ // decorates with the current values, and a resolution that comes back equal is a no-op.
+ const mentionKey = [...resolvedMentionUsernames].sort().join(" ");
+ const decorated = useRef({ mentionKey, userTagsSetting });
+ useEffect(() => {
+ const changed = decorated.current.mentionKey !== mentionKey || decorated.current.userTagsSetting !== userTagsSetting;
+ decorated.current = { mentionKey, userTagsSetting };
+ if (changed) editor?.redecorate();
+ }, [editor, mentionKey, userTagsSetting]);
+
+ const resolveUrl = useMemo(() => memoResolveUrl(attachments), [attachments]);
+
+ // Mount memos' own UI after every render of the editor's blocks: on load, on a new
+ // value, and when a ticked task item or new image URLs re-render blocks.
+ useEffect(() => {
+ if (!editor || editor.isDestroyed) return;
+ const root = editor.root;
+ let frame: number | null = null;
+ const update = () => {
+ frame = null;
+ if (editor.isDestroyed) return;
+ const next = findIslands(editor, root, linkPreviewEnabled);
+ setIslands((previous) => (sameIslands(previous, next) ? previous : next));
+ };
+ update();
+ const observer = new MutationObserver(() => {
+ frame ??= requestAnimationFrame(update);
+ });
+ observer.observe(root, { childList: true });
+ return () => {
+ observer.disconnect();
+ if (frame !== null) cancelAnimationFrame(frame);
+ };
+ }, [editor, content, linkPreviewEnabled, resolveUrl]);
+
+ // In-memo anchors scroll within this memo; a collapsed card may hide the target, so it opens the detail page.
+ const handleLinkClick = ({ href }: { href: string }) => {
+ if (!href.startsWith("#")) return false;
+ const id = decodeURIComponent(href.slice(1));
+ const target = !compact && id && contentRef.current ? findAnchorTarget(contentRef.current, id) : null;
+ if (target) {
+ target.scrollIntoView({ behavior: "smooth", block: "center" });
+ } else if (memoName) {
+ navigate(`/${memoName}${href}`, { state: parentPage ? createMemoNavigationState(parentPage) : undefined });
+ }
+ return true;
+ };
+
+ const handleClick = (event: React.MouseEvent) => {
+ const target = event.target as HTMLElement;
+ const tag = target.closest<HTMLElement>(".mbe-tag")?.dataset.tag;
+ if (tag) {
+ event.stopPropagation();
+ navigateToTag(tag);
+ return;
+ }
+ const mention = target.closest<HTMLElement>(".mbe-mention[data-resolved]")?.dataset.mention;
+ if (mention) {
+ event.stopPropagation();
+ navigate(getCreatorHomePath(mention));
+ }
+ };
return (
<div className={`w-full flex flex-col justify-start items-start text-foreground ${className || ""}`}>
<div
ref={contentRef}
data-memo-content
- data-memo-name={props.memoName}
+ data-memo-name={memoName}
className={cn(
"relative w-full max-w-full wrap-break-word text-base leading-6",
- "[&>*:first-child]:mt-0 [&>*:last-child]:mb-0",
+ // Tags filter the list when clicked here; the composer shows them the same, without the click.
+ "[&_.mbe-tag]:cursor-pointer [&_.mbe-tag]:transition-opacity [&_.mbe-tag:hover]:opacity-75",
+ "[&_.mbe-mention[data-resolved]]:cursor-pointer [&_.mbe-mention[data-resolved]:hover]:underline",
"[&_.katex-display]:max-w-full",
"[&_.katex-display]:overflow-x-auto",
"[&_.katex-display]:overflow-y-hidden",
- // Footnotes: quiet GitHub-style footer — thin separator, smaller muted text, unobtrusive links.
- "[&_.footnotes]:mt-4 [&_.footnotes]:border-t [&_.footnotes]:border-border [&_.footnotes]:pt-2",
- "[&_.footnotes]:text-sm [&_.footnotes]:text-muted-foreground",
- // GitHub renders footnote ref/backref links without an underline (underline on hover only).
- "[&_[data-footnote-ref]]:no-underline [&_[data-footnote-ref]:hover]:underline",
- "[&_.data-footnote-backref]:no-underline [&_.data-footnote-backref:hover]:underline",
contentClassName,
)}
+ onClick={handleClick}
onMouseUp={onClick}
onDoubleClick={onDoubleClick}
>
- <MemoMarkdownRenderer
- content={content}
- attachments={attachments}
- resolvedMentionUsernames={resolvedMentionUsernames}
- memoName={props.memoName}
- parentPage={props.parentPage}
- compact={Boolean(props.compact)}
+ <MarkdownEditor
+ key={editorKey}
+ ref={setEditor}
+ value={content}
+ onChange={onTaskToggle}
+ editable={false}
+ taskToggle={Boolean(onTaskToggle)}
+ toolbar={false}
+ slashMenu={false}
+ markdown={MEMO_MARKDOWN}
+ extensions={extensions}
+ theme={MEMO_EDITOR_THEME}
+ labels={labels}
+ resolveUrl={resolveUrl}
+ referrerPolicy="no-referrer"
+ headingIds={headingSlugs}
+ onLinkClick={handleLinkClick}
+ className="memo-content-root"
/>
+ {islands.map((island) => createPortal(<LinkPreview href={island.href} />, island.target, island.key))}
</div>
</div>
);
diff --git a/web/src/components/MemoContent/markdown/AnchorLink.tsx b/web/src/components/MemoContent/markdown/AnchorLink.tsx
deleted file mode 100644
index b4cd27d24..000000000
--- a/web/src/components/MemoContent/markdown/AnchorLink.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { Link } from "react-router-dom";
-import { markdownStyles } from "@/lib/markdownStyles";
-import { cn } from "@/lib/utils";
-import { findAnchorTarget } from "@/utils/markdown-manipulation";
-import { createMemoNavigationState } from "../../MemoView/navigation";
-import type { ReactMarkdownProps } from "./types";
-
-interface AnchorLinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement>, ReactMarkdownProps {
- href: string;
- /** Resource name of the enclosing memo (e.g. `memos/abc123`), when known. */
- memoName?: string;
- /** Collection page that rendered the enclosing memo. */
- parentPage?: string;
- /** Whether the memo is rendered as a collapsed feed card. */
- compact?: boolean;
- children: React.ReactNode;
-}
-
-/**
- * Renders in-page anchors (footnote references/backrefs, heading links — any `href="#…"`).
- *
- * When the target lives in a fully-rendered memo (detail, share, preview, expanded feed card),
- * we scroll to it within that memo's own container — scoped so duplicate footnote ids across a
- * feed can't send us to the wrong memo. When the memo is a collapsed feed card the footnote is
- * below the fold, so we fall back to navigating to the memo detail page (with the hash), where
- * MemoDetail scrolls the target into view.
- */
-export const AnchorLink = ({ href, memoName, parentPage, compact, children, className, node: _node, ...props }: AnchorLinkProps) => {
- const handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
- if (compact) return; // Let the link navigate to the detail page.
- const id = decodeURIComponent(href.slice(1));
- if (!id) return;
- // Scope the lookup to this memo's own container so duplicate footnote ids elsewhere in a feed
- // can't steal the scroll.
- const root = event.currentTarget.closest("[data-memo-content]");
- const target = root && findAnchorTarget(root, id);
- if (target) {
- event.preventDefault();
- target.scrollIntoView({ behavior: "smooth", block: "center" });
- }
- };
-
- const classes = cn(markdownStyles.link, className);
-
- if (memoName) {
- return (
- <Link
- to={`/${memoName}${href}`}
- state={parentPage ? createMemoNavigationState(parentPage) : undefined}
- onClick={handleClick}
- className={classes}
- {...props}
- >
- {children}
- </Link>
- );
- }
-
- return (
- <a href={href} onClick={handleClick} className={classes} {...props}>
- {children}
- </a>
- );
-};
diff --git a/web/src/components/MemoContent/markdown/Blockquote.tsx b/web/src/components/MemoContent/markdown/Blockquote.tsx
deleted file mode 100644
index c2abd6960..000000000
--- a/web/src/components/MemoContent/markdown/Blockquote.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import { markdownStyles } from "@/lib/markdownStyles";
-import { cn } from "@/lib/utils";
-import { NestedMarkdownRenderContext } from "../MarkdownRenderContext";
-import type { ReactMarkdownProps } from "./types";
-
-interface BlockquoteProps extends React.BlockquoteHTMLAttributes<HTMLQuoteElement>, ReactMarkdownProps {
- children: React.ReactNode;
-}
-
-/**
- * Blockquote component with left border accent
- */
-export const Blockquote = ({ children, className, node: _node, ...props }: BlockquoteProps) => {
- return (
- <blockquote className={cn(markdownStyles.blockquote, className)} {...props}>
- <NestedMarkdownRenderContext>{children}</NestedMarkdownRenderContext>
- </blockquote>
- );
-};
diff --git a/web/src/components/MemoContent/markdown/Details.tsx b/web/src/components/MemoContent/markdown/Details.tsx
deleted file mode 100644
index 98691464f..000000000
--- a/web/src/components/MemoContent/markdown/Details.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import { ChevronRightIcon } from "lucide-react";
-import { markdownStyles } from "@/lib/markdownStyles";
-import { cn } from "@/lib/utils";
-import { NestedMarkdownRenderContext } from "../MarkdownRenderContext";
-import type { ReactMarkdownProps } from "./types";
-
-interface DetailsProps extends React.DetailsHTMLAttributes<HTMLDetailsElement>, ReactMarkdownProps {}
-interface SummaryProps extends React.HTMLAttributes<HTMLElement>, ReactMarkdownProps {}
-
-export const Details = ({ children, className, node: _node, ...props }: DetailsProps) => (
- <details className={cn(markdownStyles.details, className)} {...props}>
- <NestedMarkdownRenderContext>{children}</NestedMarkdownRenderContext>
- </details>
-);
-
-export const Summary = ({ children, className, node: _node, ...props }: SummaryProps) => (
- <summary className={cn(markdownStyles.summary, className)} {...props}>
- <ChevronRightIcon aria-hidden="true" className={markdownStyles.disclosureIcon} />
- {children}
- </summary>
-);
diff --git a/web/src/components/MemoContent/markdown/Heading.tsx b/web/src/components/MemoContent/markdown/Heading.tsx
deleted file mode 100644
index 734564503..000000000
--- a/web/src/components/MemoContent/markdown/Heading.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { headingClass } from "@/lib/markdownStyles";
-import { cn } from "@/lib/utils";
-import type { ReactMarkdownProps } from "./types";
-
-interface HeadingProps extends React.HTMLAttributes<HTMLHeadingElement>, ReactMarkdownProps {
- level: 1 | 2 | 3 | 4 | 5 | 6;
- children: React.ReactNode;
-}
-
-/**
- * Heading component for h1-h6 elements.
- * Renders semantic heading levels with consistent styling.
- * Anchor IDs are assigned by the rehypeHeadingId plugin.
- */
-export const Heading = ({ level, children, className, node: _node, ...props }: HeadingProps) => {
- const Component = `h${level}` as const;
-
- return (
- <Component className={cn(headingClass(level), className)} {...props}>
- {children}
- </Component>
- );
-};
diff --git a/web/src/components/MemoContent/markdown/HorizontalRule.tsx b/web/src/components/MemoContent/markdown/HorizontalRule.tsx
deleted file mode 100644
index 5e5dc61df..000000000
--- a/web/src/components/MemoContent/markdown/HorizontalRule.tsx
+++ /dev/null
@@ -1,12 +0,0 @@
-import { markdownStyles } from "@/lib/markdownStyles";
-import { cn } from "@/lib/utils";
-import type { ReactMarkdownProps } from "./types";
-
-interface HorizontalRuleProps extends React.HTMLAttributes<HTMLHRElement>, ReactMarkdownProps {}
-
-/**
- * Horizontal rule separator
- */
-export const HorizontalRule = ({ className, node: _node, ...props }: HorizontalRuleProps) => {
- return <hr className={cn(markdownStyles.horizontalRule, className)} {...props} />;
-};
diff --git a/web/src/components/MemoContent/markdown/Image.tsx b/web/src/components/MemoContent/markdown/Image.tsx
deleted file mode 100644
index 6c896bdad..000000000
--- a/web/src/components/MemoContent/markdown/Image.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { markdownStyles } from "@/lib/markdownStyles";
-import { cn } from "@/lib/utils";
-import type { ReactMarkdownProps } from "./types";
-
-interface ImageProps extends React.ImgHTMLAttributes<HTMLImageElement>, ReactMarkdownProps {}
-
-/**
- * Image component for markdown images
- * Responsive with rounded corners
- */
-export const Image = ({ className, alt, node: _node, height, width, style, ...props }: ImageProps) => {
- return (
- <img
- className={cn(markdownStyles.image, !height && "h-auto", className)}
- alt={alt}
- style={{ height: height ? `${height}px` : undefined, width: width ? `${width}px` : undefined, ...style }}
- {...props}
- loading="lazy"
- decoding="async"
- referrerPolicy="no-referrer"
- />
- );
-};
diff --git a/web/src/components/MemoContent/markdown/InlineCode.tsx b/web/src/components/MemoContent/markdown/InlineCode.tsx
deleted file mode 100644
index 87458c739..000000000
--- a/web/src/components/MemoContent/markdown/InlineCode.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import { markdownStyles } from "@/lib/markdownStyles";
-import { cn } from "@/lib/utils";
-import type { ReactMarkdownProps } from "./types";
-
-interface InlineCodeProps extends React.HTMLAttributes<HTMLElement>, ReactMarkdownProps {
- children: React.ReactNode;
-}
-
-/**
- * Inline code component with background and monospace font
- */
-export const InlineCode = ({ children, className, node: _node, ...props }: InlineCodeProps) => {
- return (
- <code className={cn(markdownStyles.inlineCode, className)} {...props}>
- {children}
- </code>
- );
-};
diff --git a/web/src/components/MemoContent/markdown/Link.tsx b/web/src/components/MemoContent/markdown/Link.tsx
deleted file mode 100644
index 460caa622..000000000
--- a/web/src/components/MemoContent/markdown/Link.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import { markdownStyles } from "@/lib/markdownStyles";
-import { cn } from "@/lib/utils";
-import type { ReactMarkdownProps } from "./types";
-
-interface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement>, ReactMarkdownProps {
- children: React.ReactNode;
-}
-
-/**
- * Link component for external links
- * Opens in new tab with security attributes
- */
-export const Link = ({ children, className, href, node: _node, ...props }: LinkProps) => {
- return (
- <a href={href} target="_blank" rel="noopener noreferrer" className={cn(markdownStyles.link, className)} {...props}>
- {children}
- </a>
- );
-};
diff --git a/web/src/components/MemoContent/markdown/List.tsx b/web/src/components/MemoContent/markdown/List.tsx
deleted file mode 100644
index 3115dbf15..000000000
--- a/web/src/components/MemoContent/markdown/List.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import { Children, cloneElement, isValidElement, type ReactElement, type ReactNode } from "react";
-import { markdownStyles } from "@/lib/markdownStyles";
-import { cn } from "@/lib/utils";
-import { TASK_LIST_CLASS, TASK_LIST_ITEM_CLASS } from "../constants";
-import { NestedMarkdownRenderContext } from "../MarkdownRenderContext";
-import type { ReactMarkdownProps } from "./types";
-
-interface TaskListChildProps {
- children?: ReactNode;
- node?: {
- tagName?: string;
- properties?: {
- type?: unknown;
- };
- };
- type?: string;
-}
-
-const isCheckboxInput = (child: ReactNode): child is ReactElement<TaskListChildProps> => {
- return (
- isValidElement<TaskListChildProps>(child) && (child.props.type === "checkbox" || child.props.node?.properties?.type === "checkbox")
- );
-};
-
-const isParagraphElement = (child: ReactNode): child is ReactElement<TaskListChildProps> => {
- return isValidElement<TaskListChildProps>(child) && (child.type === "p" || child.props.node?.tagName === "p");
-};
-
-const splitTaskListItemChildren = (children: ReactNode) => {
- let checkbox: ReactNode;
- const content: ReactNode[] = [];
-
- Children.toArray(children).forEach((child) => {
- if (!checkbox && isCheckboxInput(child)) {
- checkbox = child;
- return;
- }
-
- if (!checkbox && isParagraphElement(child)) {
- const paragraphChildren: ReactNode[] = [];
-
- Children.toArray(child.props.children).forEach((paragraphChild) => {
- if (!checkbox && isCheckboxInput(paragraphChild)) {
- checkbox = paragraphChild;
- return;
- }
- paragraphChildren.push(paragraphChild);
- });
-
- if (checkbox) {
- if (paragraphChildren.length > 0) {
- content.push(cloneElement(child, undefined, ...paragraphChildren));
- }
- return;
- }
- }
-
- content.push(child);
- });
-
- return { checkbox, content };
-};
-
-interface ListProps extends React.HTMLAttributes<HTMLUListElement | HTMLOListElement>, ReactMarkdownProps {
- ordered?: boolean;
- children: React.ReactNode;
-}
-
-/**
- * List component for both regular and task lists (GFM)
- * Detects task lists via the "contains-task-list" class added by remark-gfm
- */
-export const List = ({ ordered, children, className, node: _node, ...domProps }: ListProps) => {
- const Component = ordered ? "ol" : "ul";
- const isTaskList = className?.includes(TASK_LIST_CLASS);
- const listClass = isTaskList ? markdownStyles.taskList : ordered ? markdownStyles.orderedList : markdownStyles.bulletList;
-
- return (
- <Component className={cn(listClass, className)} {...domProps}>
- {children}
- </Component>
- );
-};
-
-interface ListItemProps extends React.LiHTMLAttributes<HTMLLIElement>, ReactMarkdownProps {
- children: React.ReactNode;
-}
-
-/**
- * List item component for both regular and task list items
- * Detects task items via the "task-list-item" class added by remark-gfm
- */
-export const ListItem = ({ children, className, node: _node, ...domProps }: ListItemProps) => {
- const isTaskListItem = className?.includes(TASK_LIST_ITEM_CLASS);
-
- if (isTaskListItem) {
- const { checkbox, content } = splitTaskListItemChildren(children);
-
- return (
- <li className={cn(markdownStyles.taskListItem, className)} {...domProps}>
- <NestedMarkdownRenderContext>
- {checkbox}
- <div className={markdownStyles.taskItemContent}>{content}</div>
- </NestedMarkdownRenderContext>
- </li>
- );
- }
-
- return (
- <li className={cn(markdownStyles.listItem, className)} {...domProps}>
- <NestedMarkdownRenderContext>{children}</NestedMarkdownRenderContext>
- </li>
- );
-};
diff --git a/web/src/components/MemoContent/markdown/Paragraph.tsx b/web/src/components/MemoContent/markdown/Paragraph.tsx
deleted file mode 100644
index 497fae645..000000000
--- a/web/src/components/MemoContent/markdown/Paragraph.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import type { Element } from "hast";
-import { useLinkPreviewEnabled } from "@/contexts/ViewContext";
-import { useNearViewport } from "@/hooks/useNearViewport";
-import { markdownStyles } from "@/lib/markdownStyles";
-import { cn } from "@/lib/utils";
-import LinkMetadataCard from "../LinkMetadataCard";
-import { useMarkdownRenderContext } from "../MarkdownRenderContext";
-import type { ReactMarkdownProps } from "./types";
-
-interface ParagraphProps extends React.HTMLAttributes<HTMLParagraphElement>, ReactMarkdownProps {
- children: React.ReactNode;
-}
-
-interface DeferredLinkPreviewProps extends React.HTMLAttributes<HTMLParagraphElement> {
- children: React.ReactNode;
- href: string;
-}
-
-export function getSingleLinkHref(node?: Element): string | undefined {
- if (!node || node.tagName !== "p") {
- return undefined;
- }
-
- const meaningfulChildren = node.children.filter((child) => {
- return !(child.type === "text" && child.value.trim() === "");
- });
-
- if (meaningfulChildren.length !== 1) {
- return undefined;
- }
-
- const onlyChild = meaningfulChildren[0];
- if (onlyChild.type !== "element" || onlyChild.tagName !== "a") {
- return undefined;
- }
-
- const href = onlyChild.properties?.href;
- // Only web links have metadata to preview; `tel:`/`sms:`/`mailto:` hand off to another app.
- if (typeof href !== "string" || !/^https?:\/\//i.test(href)) {
- return undefined;
- }
-
- const meaningfulLinkChildren = onlyChild.children.filter((child) => {
- return !(child.type === "text" && child.value.trim() === "");
- });
-
- if (meaningfulLinkChildren.length !== 1) {
- return undefined;
- }
-
- const onlyLinkChild = meaningfulLinkChildren[0];
- return onlyLinkChild.type === "text" && onlyLinkChild.value === href ? href : undefined;
-}
-
-const DeferredLinkPreview = ({ children, className, href, ...props }: DeferredLinkPreviewProps) => {
- const { ref: viewportRef, isNearViewport } = useNearViewport<HTMLParagraphElement>();
- const fallback = (
- <p ref={viewportRef} className={cn(markdownStyles.paragraph, className)} {...props}>
- {children}
- </p>
- );
-
- return <LinkMetadataCard url={href} fallback={fallback} enabled={isNearViewport} />;
-};
-
-export const Paragraph = ({ children, className, node, ...props }: ParagraphProps) => {
- const { blockDepth } = useMarkdownRenderContext();
- const linkPreviewEnabled = useLinkPreviewEnabled();
- const href = blockDepth === 0 && linkPreviewEnabled ? getSingleLinkHref(node) : undefined;
-
- if (href) {
- return (
- <DeferredLinkPreview href={href} className={className} {...props}>
- {children}
- </DeferredLinkPreview>
- );
- }
-
- return (
- <p className={cn(markdownStyles.paragraph, className)} {...props}>
- {children}
- </p>
- );
-};
diff --git a/web/src/components/MemoContent/markdown/README.md b/web/src/components/MemoContent/markdown/README.md
deleted file mode 100644
index 69342053c..000000000
--- a/web/src/components/MemoContent/markdown/README.md
+++ /dev/null
@@ -1,25 +0,0 @@
-# Markdown Components
-
-Small React components used by `MemoMarkdownRenderer` to style HTML emitted by `react-markdown`.
-
-## Responsibilities
-
-- Keep element styling local to each semantic HTML element.
-- Strip the `node` prop from DOM output through `ReactMarkdownProps`.
-- Preserve existing markdown behavior while avoiding structural fixes in CSS.
-
-## Collapsible Sections
-
-`Details` and `Summary` preserve native disclosure behavior and authored `open` attributes. Styling uses theme tokens and
-direct-child selectors so nested indicators follow only their own disclosure. Contents enter `NestedMarkdownRenderContext`
-to keep bare links inline, consistent with other nested Markdown blocks.
-
-## Task Lists
-
-GFM task lists are normalized before rendering by `remarkSplitMixedTaskLists`.
-
-- Mixed task/bullet lists are split into separate lists so regular bullets keep bullets.
-- Single-block split items are rendered as tight list items, preventing accidental `<p>` wrappers.
-- `ListItem` uses a two-column grid: checkbox/control in the first column and a single task-body wrapper in the second.
-- Task text, emphasis, links, tags, and nested content stay inside the body wrapper so inline markdown does not become separate grid items.
-- Loose task items keep paragraph structure inside the task-body wrapper.
diff --git a/web/src/components/MemoContent/markdown/index.ts b/web/src/components/MemoContent/markdown/index.ts
deleted file mode 100644
index 7a0617d4a..000000000
--- a/web/src/components/MemoContent/markdown/index.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-export { AnchorLink } from "./AnchorLink";
-export { Blockquote } from "./Blockquote";
-export { Details, Summary } from "./Details";
-export { Heading } from "./Heading";
-export { HorizontalRule } from "./HorizontalRule";
-export { Image } from "./Image";
-export { InlineCode } from "./InlineCode";
-export { Link } from "./Link";
-export { List, ListItem } from "./List";
-export { Paragraph } from "./Paragraph";
diff --git a/web/src/components/MemoContent/markdown/types.ts b/web/src/components/MemoContent/markdown/types.ts
deleted file mode 100644
index b50d4fcc3..000000000
--- a/web/src/components/MemoContent/markdown/types.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import type { Element } from "hast";
-
-/**
- * Props passed by react-markdown to custom components
- * Includes the AST node for advanced use cases
- */
-export interface ReactMarkdownProps {
- node?: Element;
-}
diff --git a/web/src/components/MemoContent/math.ts b/web/src/components/MemoContent/math.ts
deleted file mode 100644
index 0ee0632e5..000000000
--- a/web/src/components/MemoContent/math.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-const stripCode = (content: string): string =>
- content
- .replace(/```[\s\S]*?```/g, "")
- .replace(/~~~[\s\S]*?~~~/g, "")
- .replace(/`(?:\\.|[^`\n])*`/g, "");
-
-// This is only a loading heuristic; remark-math remains the source of truth for
-// parsing. Any unescaped dollar outside code triggers the math chunk: a false
-// positive merely loads it, whereas mirroring remark-math's grammar here risks
-// false negatives that would silently render real math as raw dollars.
-export const hasMathSyntax = (content: string): boolean => /(^|[^\\])\$/.test(stripCode(content));
diff --git a/web/src/components/MemoContent/pipeline.ts b/web/src/components/MemoContent/pipeline.ts
deleted file mode 100644
index 543b4e106..000000000
--- a/web/src/components/MemoContent/pipeline.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import type { Element, Root as HastRoot } from "hast";
-import rehypeRaw from "rehype-raw";
-import rehypeSanitize from "rehype-sanitize";
-import remarkBreaks from "remark-breaks";
-import remarkGfm from "remark-gfm";
-import remarkParse from "remark-parse";
-import remarkRehype from "remark-rehype";
-import { type PluggableList, unified } from "unified";
-import { visit } from "unist-util-visit";
-import { getHeadingText, isHeadingElement, rehypeHeadingId } from "@/utils/rehype-plugins/rehype-heading-id";
-import { remarkDisableSetext } from "@/utils/remark-plugins/remark-disable-setext";
-import { remarkPreserveType } from "@/utils/remark-plugins/remark-preserve-type";
-import { remarkSplitMixedTaskLists } from "@/utils/remark-plugins/remark-split-mixed-task-lists";
-import { remarkMemoSyntax } from "@/utils/remark-plugins/remark-tag";
-import { SANITIZE_SCHEMA } from "./constants";
-
-/**
- * The memo markdown pipeline, in one place. The renderer and the outline both build from these,
- * so anything that changes which headings exist or what they read as — disabling setext,
- * unwrapping raw HTML, sanitizing away elements — applies to both or neither.
- */
-export const buildRemarkPlugins = (mathRemarkPlugins: PluggableList = []): PluggableList => [
- remarkDisableSetext,
- ...mathRemarkPlugins,
- remarkGfm,
- remarkSplitMixedTaskLists,
- remarkMemoSyntax,
- remarkBreaks,
- remarkPreserveType,
-];
-
-export const buildRehypePlugins = (mathRehypePlugins: PluggableList = []): PluggableList => [
- rehypeRaw,
- [rehypeSanitize, SANITIZE_SCHEMA],
- rehypeHeadingId,
- ...mathRehypePlugins,
-];
-
-export interface HeadingItem {
- text: string;
- level: 1 | 2 | 3 | 4;
- slug: string;
-}
-
-/**
- * Screen-reader-only headings are generated scaffolding, not memo content — remark-rehype labels
- * the footnote section with one. They are rendered (and keep an anchor) but stay out of the outline.
- */
-function isVisuallyHidden(node: Element): boolean {
- const className = node.properties?.className;
- return Array.isArray(className) && className.includes("sr-only");
-}
-
-/**
- * Every heading is either ATX (up to three spaces, then 1–6 `#` and a space) or written as raw
- * HTML — setext is disabled, and no plugin in the chain invents one. Content matching neither
- * cannot produce a heading, which lets the common short memo skip the parse below. False
- * positives (a `#` inside a code fence) only cost the work we would otherwise have done anyway.
- */
-const MAYBE_HAS_HEADING = /^[ \t]{0,3}#{1,6}[ \t]|<h[1-6][\s/>]/im;
-
-/**
- * Extract h1–h4 headings for outline navigation by running the memo through the same pipeline
- * the renderer uses and reading the ids `rehypeHeadingId` assigned. The slugs are the rendered
- * ids rather than a second guess at them, so an outline link always has somewhere to land.
- *
- * Math plugins are left out: they are lazy-loaded for bundle size, and the only heading text they
- * change is `$…$` delimiters, which slugify strips either way.
- */
-export function extractHeadings(markdown: string): HeadingItem[] {
- if (!MAYBE_HAS_HEADING.test(markdown)) return [];
-
- const processor = unified()
- .use(remarkParse)
- .use(buildRemarkPlugins())
- // rehype-raw needs the raw HTML kept in the tree, exactly as react-markdown configures it.
- .use(remarkRehype, { allowDangerousHtml: true })
- .use(buildRehypePlugins());
-
- const tree = processor.runSync(processor.parse(markdown)) as HastRoot;
- const headings: HeadingItem[] = [];
-
- visit(tree, "element", (node: Element) => {
- if (!isHeadingElement(node) || isVisuallyHidden(node)) return;
-
- const level = Number(node.tagName.slice(1));
- if (level > 4) return;
-
- const text = getHeadingText(node);
- const slug = typeof node.properties?.id === "string" ? node.properties.id : "";
- if (!text || !slug) return;
-
- headings.push({ text, level: level as 1 | 2 | 3 | 4, slug });
- });
-
- return headings;
-}
diff --git a/web/src/components/MemoContent/types.ts b/web/src/components/MemoContent/types.ts
index 304596c84..db530e49f 100644
--- a/web/src/components/MemoContent/types.ts
+++ b/web/src/components/MemoContent/types.ts
@@ -5,12 +5,17 @@ export interface MemoContentProps {
content: string;
/** Attachments bound to this memo, used to resolve managed image URLs in share/S3 modes. */
attachments?: Attachment[];
- /** Resource name of the memo (e.g. `memos/abc123`). Enables footnote links to target the memo detail page. */
+ /** Resource name of the memo (e.g. `memos/abc123`). Lets in-memo anchor links open the memo detail page. */
memoName?: string;
/** Collection page that rendered the memo, preserved when an inline link opens its detail page. */
parentPage?: string;
- /** The card renders collapsed (ClampedSection), so footnote links navigate instead of scrolling. */
+ /** The card renders collapsed (ClampedSection), so in-memo anchor links navigate instead of scrolling. */
compact?: boolean;
+ /**
+ * Lets the viewer tick task items, for a memo they can manage. Called with the new
+ * Markdown, in which only the ticked item's `[ ]` or `[x]` changed.
+ */
+ onTaskToggle?: (content: string) => void;
className?: string;
contentClassName?: string;
onClick?: (e: React.MouseEvent) => void;
diff --git a/web/src/components/MemoContent/useTagNavigation.ts b/web/src/components/MemoContent/useTagNavigation.ts
new file mode 100644
index 000000000..acb8b47ef
--- /dev/null
+++ b/web/src/components/MemoContent/useTagNavigation.ts
@@ -0,0 +1,31 @@
+import { useLocation } from "react-router-dom";
+import { type MemoFilter, stringifyFilters, useMemoFilterContext } from "@/contexts/MemoFilterContext";
+import useNavigateTo from "@/hooks/useNavigateTo";
+import { Routes } from "@/router";
+import { isMemoResourcePath, withMemoFilter } from "../MemoView/navigation";
+
+/**
+ * What clicking a tag in a memo does. On a memo detail page it opens the collection the
+ * memo came from, filtered by the tag. In a list it toggles the tag as the one tag filter.
+ */
+export function useTagNavigation(parentPage: string | undefined): (tag: string) => void {
+ const location = useLocation();
+ const navigateTo = useNavigateTo();
+ const { getFiltersByFactor, removeFilter, addFilter } = useMemoFilterContext();
+
+ return (tag: string) => {
+ if (isMemoResourcePath(location.pathname)) {
+ navigateTo(withMemoFilter(parentPage || Routes.HOME, stringifyFilters([{ factor: "tagSearch", value: tag }])));
+ return;
+ }
+
+ const isActive = getFiltersByFactor("tagSearch").some((filter: MemoFilter) => filter.value === tag);
+ if (isActive) {
+ removeFilter((f: MemoFilter) => f.factor === "tagSearch" && f.value === tag);
+ } else {
+ // Remove all existing tag filters first, then add the new one
+ removeFilter((f: MemoFilter) => f.factor === "tagSearch");
+ addFilter({ factor: "tagSearch", value: tag });
+ }
+ };
+}
diff --git a/web/src/components/MemoContent/utils.ts b/web/src/components/MemoContent/utils.ts
deleted file mode 100644
index 0e1d4a6c8..000000000
--- a/web/src/components/MemoContent/utils.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { isValidElement, type ReactElement, type ReactNode } from "react";
-
-/**
- * Extracts code content from a react-markdown code element.
- * Handles the nested structure where code is passed as children.
- *
- * @param children - The children prop from react-markdown (typically a code element)
- * @returns The extracted code content as a string with trailing newline removed
- */
-export const extractCodeContent = (children: ReactNode): string => {
- const codeElement = isValidElement(children) ? (children as ReactElement<{ children?: ReactNode }>) : null;
- return String(codeElement?.props.children || "").replace(/\n$/, "");
-};
-
-/**
- * Extracts the language identifier from a code block's className.
- * react-markdown uses the format "language-xxx" for code blocks.
- *
- * @param className - The className string from a code element
- * @returns The language identifier, or empty string if none found
- */
-export const extractLanguage = (className: string): string => {
- const match = /language-(\w+)/.exec(className);
- return match ? match[1] : "";
-};
diff --git a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
index a7fdd8d28..c1cf37a74 100644
--- a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
+++ b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
@@ -14,7 +14,7 @@ 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 SidebarSection, { SIDEBAR_SECTION_STACK_CLASSES } from "@/components/AppSidebar/SidebarSection";
-import { extractHeadings } from "@/components/MemoContent/pipeline";
+import { extractHeadings } from "@/components/MemoContent/headings";
import { getRelationBuckets, getRelationMemo } from "@/components/MemoMetadata/Relation/relationHelpers";
import { useResolvedRelationMemos } from "@/components/MemoMetadata/Relation/useResolvedRelationMemos";
import MemoParentPlaceholder, { type MemoParentStatus } from "@/components/MemoParentPlaceholder";
diff --git a/web/src/components/MemoDetailSidebar/MemoOutline.tsx b/web/src/components/MemoDetailSidebar/MemoOutline.tsx
index 7a298c5df..c70c87fc9 100644
--- a/web/src/components/MemoDetailSidebar/MemoOutline.tsx
+++ b/web/src/components/MemoDetailSidebar/MemoOutline.tsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState } from "react";
-import type { HeadingItem } from "@/components/MemoContent/pipeline";
+import type { HeadingItem } from "@/components/MemoContent/headings";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { findAnchorTarget, findMemoContentRoot } from "@/utils/markdown-manipulation";
diff --git a/web/src/components/MemoEditor/Editor/controller.ts b/web/src/components/MemoEditor/Editor/controller.ts
index ed3dabfcf..84134be33 100644
--- a/web/src/components/MemoEditor/Editor/controller.ts
+++ b/web/src/components/MemoEditor/Editor/controller.ts
@@ -1,113 +1,139 @@
-import { isolateHistory } from "@codemirror/commands";
-import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
-import { EditorSelection, type EditorState } from "@codemirror/state";
-import { EditorView } from "@codemirror/view";
+import { type Block, containerContent, type Editor, getBlock, inlineText, type Position, type Widget } from "@usememos/editor";
+import { collectTags } from "@/lib/memo-markdown";
import { isCompleteTagValue } from "@/utils/tag-grammar";
-import type { EditorController, FormattingController } from "../types/editorController";
-import { findMarkdownTagMatches } from "./markdownTagRanges";
-import {
- cancelUploadAnchor,
- createUploadAnchor,
- getUploadAnchorPosition,
- removeUploadAnchorEffect,
- setUploadAnchor,
-} from "./uploadAnchors";
+import type { EditorController } from "../types/editorController";
+import { renderUploadAnchor } from "./uploadAnchors";
-const isEmptyDoc = (state: EditorState) => state.doc.toString().trim() === "";
+/** The live editor, or null before it mounts and after it is destroyed. */
+type EditorGetter = () => Editor | null;
-/** Block padding for insertMarkdown: ensure the inserted text is its own block. */
-function blockPad(before: string, after: string): { prefix: string; suffix: string } {
- const prefix = before.length === 0 || before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n";
- const suffix = after.length === 0 || after.startsWith("\n\n") ? "" : after.startsWith("\n") ? "\n" : "\n\n";
- return { prefix, suffix };
-}
+const live = (getEditor: EditorGetter): Editor | null => {
+ const editor = getEditor();
+ return editor && !editor.isDestroyed ? editor : null;
+};
+
+/** The text of the block (or table cell) holding `position`. */
+const textAt = (editor: Editor, position: Position): string => {
+ const content = containerContent(getBlock(editor.state.doc, position.blockId), position.cell);
+ return content ? inlineText(content) : "";
+};
+
+/** An empty paragraph, which an inserted block should replace rather than follow. */
+const isEmptyParagraph = (block: Block): boolean => block.type === "paragraph" && inlineText(block.content) === "";
+
+/**
+ * Inserts Markdown as its own blocks at `position`. In an empty paragraph it
+ * takes the paragraph's place, as a paste would, so no empty line is left
+ * above the inserted content.
+ */
+const insertBlocks = (editor: Editor, markdown: string, position: Position): void => {
+ if (isEmptyParagraph(getBlock(editor.state.doc, position.blockId))) {
+ editor.setSelection({ anchor: position, focus: position });
+ editor.commands.insertMarkdown(markdown, { block: true });
+ } else {
+ editor.commands.insertMarkdown(markdown, { at: position, block: true });
+ }
+};
+
+/**
+ * EditorController over a @usememos/editor instance. Every method reads the
+ * live editor when called, so the controller can be handed out before the
+ * editor mounts, and calls after it is destroyed do nothing. The editor does
+ * not emit a change for a replaced document, so `onReplace` reports it.
+ */
+export function createController(getEditor: EditorGetter, onReplace: (markdown: string) => void): EditorController {
+ const anchors = new Map<string, Widget>();
+ const currentTags = (editor: Editor) => collectTags(editor.state.doc.blocks);
+
+ const takeAnchor = (id: string): Widget | undefined => {
+ const widget = anchors.get(id);
+ anchors.delete(id);
+ return widget && !widget.isRemoved ? widget : undefined;
+ };
-export function createController(view: EditorView, formatting: FormattingController): EditorController {
- const currentTags = () => findMarkdownTagMatches(view.state, 0, view.state.doc.length).map((match) => match.value);
return {
- focus: () => view.focus(),
- hasFocus: () => view.hasFocus,
- isEmpty: () => isEmptyDoc(view.state),
- getMarkdown: () => view.state.doc.toString(),
- getTags: currentTags,
- hasChecklist: () => {
- let found = false;
- const tree = ensureSyntaxTree(view.state, view.state.doc.length) ?? syntaxTree(view.state);
- tree.iterate({
- enter: (node) => {
- if (node.name === "Task") found = true;
- if (found) return false;
- },
- });
- return found;
+ focus: () => live(getEditor)?.focus(),
+ hasFocus: () => live(getEditor)?.hasFocus() ?? false,
+ isEmpty: () => (live(getEditor)?.getMarkdown() ?? "").trim() === "",
+ getMarkdown: () => getEditor()?.getMarkdown() ?? "",
+ setMarkdown: (markdown) => {
+ const editor = live(getEditor);
+ if (!editor) return;
+ editor.setMarkdown(markdown);
+ onReplace(markdown);
},
+ insertMarkdown: (markdown) => {
+ const editor = live(getEditor);
+ if (!editor || !markdown) return;
+ // Insert at the caret without consuming the selection: callers live outside
+ // the editor (attachment list, audio recorder), and replacing the range
+ // would delete text the user merely had highlighted.
+ insertBlocks(editor, markdown, editor.getSelection().focus);
+ editor.commands.focus();
+ editor.commands.scrollIntoView();
+ },
+ getTags: () => {
+ const editor = live(getEditor);
+ return editor ? currentTags(editor) : [];
+ },
+ hasChecklist: () => live(getEditor)?.state.doc.blocks.some((block) => block.type === "listItem" && block.listType === "task") ?? false,
insertTag: (tag) => {
- if (!isCompleteTagValue(tag) || view.compositionStarted || currentTags().includes(tag)) return false;
- const { doc, selection } = view.state;
- const { head } = selection.main;
+ const editor = live(getEditor);
+ if (!editor || !isCompleteTagValue(tag) || editor.isComposing || currentTags(editor).includes(tag)) return false;
// Like insertMarkdown, keep highlighted text and insert at the active end.
// Honor the chosen Markdown context, including code, instead of relocating it.
- const prefix = head > 0 && !/\s/.test(doc.sliceString(head - 1, head)) ? " " : "";
- const hasFollowingSpace = /^[ \t]$/.test(doc.sliceString(head, head + 1));
- const insert = `${prefix}#${tag}${hasFollowingSpace ? "" : " "}`;
- view.dispatch({
- changes: { from: head, insert },
+ const head = editor.getSelection().focus;
+ const text = textAt(editor, head);
+ const prefix = head.offset > 0 && !/\s/.test(text[head.offset - 1] ?? "") ? " " : "";
+ const hasFollowingSpace = /^[ \t]$/.test(text[head.offset] ?? "");
+ editor.setSelection({ anchor: head, focus: head });
+ editor.commands.insertText(`${prefix}#${tag}${hasFollowingSpace ? "" : " "}`);
+ if (hasFollowingSpace) {
// Exactly one space follows the tag, inserted or reused; the caret lands after it.
- selection: { anchor: head + prefix.length + tag.length + 2 },
- annotations: isolateHistory.of("full"),
- userEvent: "input",
- scrollIntoView: true,
- });
- view.focus();
+ const after = editor.getSelection().focus;
+ const next = { ...after, offset: after.offset + 1 };
+ editor.setSelection({ anchor: next, focus: next });
+ }
+ editor.commands.focus();
+ editor.commands.scrollIntoView();
return true;
},
- setMarkdown: (markdown) => {
- view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: markdown } });
+ createUploadAnchor: (descriptor, position) => {
+ const editor = live(getEditor);
+ if (!editor) return;
+ takeAnchor(descriptor.id)?.remove();
+ const at = position ?? editor.getSelection().focus;
+ anchors.set(descriptor.id, editor.addWidget({ at, render: renderUploadAnchor(descriptor) }));
},
- insertMarkdown: (markdown) => {
- if (!markdown) return;
- // Insert at the caret without consuming the selection: callers live outside
- // the editor (attachment list, audio recorder), and CodeMirror keeps its
- // selection across blur, so replacing the range would delete text the user
- // merely had highlighted.
- const { head } = view.state.selection.main;
- const doc = view.state.doc.toString();
- const { prefix, suffix } = blockPad(doc.slice(0, head), doc.slice(head));
- const insert = prefix + markdown + suffix;
- view.dispatch({ changes: { from: head, insert }, selection: { anchor: head + insert.length }, scrollIntoView: true });
- view.focus();
+ updateUploadAnchor: (descriptor) => {
+ const widget = anchors.get(descriptor.id);
+ if (widget && !widget.isRemoved) widget.update(renderUploadAnchor(descriptor));
},
- createUploadAnchor: (descriptor, position) => createUploadAnchor(view, descriptor, position),
- updateUploadAnchor: (descriptor) => setUploadAnchor(view, descriptor),
resolveUploadAnchor: (id, markdown) => {
- const position = getUploadAnchorPosition(view.state, id);
- if (position === undefined) return;
- if (!markdown) {
- cancelUploadAnchor(view, id);
- return;
+ const editor = live(getEditor);
+ const widget = takeAnchor(id);
+ if (!editor || !widget) return;
+ if (markdown) {
+ const block = editor.state.doc.blocks.find((candidate) => candidate.id === widget.blockId);
+ if (block && isEmptyParagraph(block)) {
+ insertBlocks(editor, markdown, { blockId: block.id, offset: 0 });
+ } else {
+ editor.commands.insertMarkdown(markdown, { at: widget, block: true });
+ }
+ editor.commands.focus();
+ editor.commands.scrollIntoView();
}
- const doc = view.state.doc.toString();
- const { prefix, suffix } = blockPad(doc.slice(0, position), doc.slice(position));
- const insert = prefix + markdown + suffix;
- view.dispatch({
- changes: { from: position, insert },
- effects: removeUploadAnchorEffect(id),
- selection: { anchor: position + insert.length },
- scrollIntoView: true,
- });
- view.focus();
+ widget.remove();
},
- cancelUploadAnchor: (id) => cancelUploadAnchor(view, id),
- getCursor: () => view.state.selection.main.head,
- setCursor: (position: number) => {
- const cursor = Math.min(Math.max(position, 0), view.state.doc.length);
- view.dispatch({
- selection: EditorSelection.cursor(cursor),
- scrollIntoView: true,
- });
+ cancelUploadAnchor: (id) => takeAnchor(id)?.remove(),
+ getSelection: () => live(getEditor)?.selectionToJSON(),
+ setSelection: (selection) => {
+ const editor = live(getEditor);
+ if (!editor) return;
+ editor.setSelection(selection);
+ editor.commands.scrollIntoView();
},
- scrollToCursor: () => view.dispatch({ effects: EditorView.scrollIntoView(view.state.selection.main.head) }),
- selectAll: () => view.dispatch({ selection: EditorSelection.range(0, view.state.doc.length) }),
- formatting,
+ selectAll: () => live(getEditor)?.commands.selectAll(),
+ toggleTaskList: () => live(getEditor)?.commands.toggleTaskList() ?? false,
};
}
diff --git a/web/src/components/MemoEditor/Editor/editor.css b/web/src/components/MemoEditor/Editor/editor.css
index 9992f44b7..5d3ee02fb 100644
--- a/web/src/components/MemoEditor/Editor/editor.css
+++ b/web/src/components/MemoEditor/Editor/editor.css
@@ -1,122 +1,27 @@
/*
- * Scoped CodeMirror styling using the app's theme variables. The styles are
- * co-located with the component so they do not leak to other editor instances.
- *
- * Token classes (.cm-md-*) come from the tagHighlighter in theme.ts; heading
- * line classes (.cm-md-h*) from headingDecorations.ts; #tag/@mention
- * (.cm-memo-*) from tagMentionDecorations.ts; the rest are CodeMirror's own.
+ * Composer layout around @usememos/editor. Colors, fonts and block rhythm come
+ * from MEMO_EDITOR_THEME (lib/memo-markdown.ts); this file only sizes the
+ * editor in the composer and styles the upload anchors it hosts as widgets.
*/
.memo-editor-content {
- & .cm-editor {
- background: transparent;
- font-size: 1rem;
+ & .memo-editor-scroller {
max-height: 50vh;
+ overflow-y: auto;
}
- &[data-focus-mode] .cm-editor {
+ &[data-focus-mode] .memo-editor-scroller {
height: 100%;
max-height: none;
}
- & .cm-editor.cm-focused {
- outline: none;
- }
- & .cm-content {
+ & .memo-editor-root {
caret-color: var(--foreground);
- font-family: inherit;
- padding: 0;
- }
- & .cm-line {
- padding-inline: 0;
- }
- & .cm-scroller {
- font-family: inherit;
- line-height: 1.5;
- overflow: auto;
- }
- & .cm-placeholder {
- color: var(--muted-foreground);
- }
-
- & .cm-dropCursor {
- border-left-color: var(--foreground);
- }
- & .cm-content::selection,
- & .cm-content ::selection {
- background: var(--accent);
- }
-
- /* Markdown tokens. Markers (#, *, fences, bullets) stay visible but muted
- (.cm-md-mark); styled text leads. */
- & .cm-md-strong {
- font-weight: 700;
- }
- & .cm-md-emphasis {
- font-style: italic;
- }
- & .cm-md-strike {
- text-decoration: line-through;
- }
- & .cm-md-code {
- font-family: var(--font-mono, monospace);
- color: var(--foreground);
- }
- & .cm-md-link {
- color: var(--primary);
- text-decoration: underline;
- }
- & .cm-md-url {
- color: var(--muted-foreground);
- }
- & .cm-md-quote {
- color: var(--muted-foreground);
- }
- & .cm-md-mark {
- color: var(--muted-foreground);
- }
-
- /* Heading lines get their type (size / weight) from headingTypeClass in
- lib/markdownStyles.ts, shared with the read-only view; headingDecorations.ts. */
-
- /* #tag / @mention decorations. */
- & .cm-memo-tag,
- & .cm-memo-mention {
- color: var(--primary);
- }
-
- /* Tag autocomplete popover — app surface, not CodeMirror defaults. */
- /* Sized like the kit's small dropdown: 13px rows, 28px tall, 2px inset. */
- & .cm-tooltip.cm-tooltip-autocomplete {
- background: var(--popover);
- color: var(--popover-foreground);
- border: 1px solid var(--border);
- border-radius: calc(var(--radius) - 4px);
- box-shadow: var(--shadow-sm);
- overflow: hidden;
- padding: 0.125rem;
- font-family: inherit;
- font-size: 0.8125rem;
- line-height: 1.125rem;
- }
- & .cm-tooltip-autocomplete > ul {
- font-family: inherit;
- }
- & .cm-tooltip-autocomplete > ul > li {
- min-height: 1.75rem;
- display: flex;
- align-items: center;
- padding: 0.25rem 0.5rem;
- border-radius: calc(var(--radius) - 6px);
+ outline: none;
}
- & .cm-tooltip-autocomplete > ul > li[aria-selected] {
+ & .memo-editor-root ::selection {
background: var(--accent);
- color: var(--accent-foreground);
- }
- & .cm-completionMatchedText {
- text-decoration: none;
- font-weight: 600;
- color: inherit;
}
}
-.cm-upload-anchor {
+
+.memo-upload-anchor {
position: relative;
display: flex;
min-height: 2.25rem;
@@ -128,7 +33,7 @@
font-size: 0.6875rem;
}
-.cm-upload-anchor-rail {
+.memo-upload-anchor-rail {
position: absolute;
inset-block: 0;
left: 0;
@@ -137,7 +42,7 @@
background: var(--primary);
}
-.cm-upload-anchor-rail::after {
+.memo-upload-anchor-rail::after {
position: absolute;
top: 50%;
left: -3px;
@@ -150,7 +55,7 @@
transform: translateY(-50%);
}
-.cm-upload-anchor-badge {
+.memo-upload-anchor-badge {
display: inline-flex;
align-items: center;
gap: 0.375rem;
@@ -161,12 +66,12 @@
font-weight: 500;
}
-.cm-upload-anchor[data-status="failed"] .cm-upload-anchor-badge {
+.memo-upload-anchor[data-status="failed"] .memo-upload-anchor-badge {
background: color-mix(in oklab, var(--destructive) 8%, transparent);
color: var(--destructive);
}
-.cm-upload-anchor-spinner {
+.memo-upload-anchor-spinner {
width: 0.75rem;
height: 0.75rem;
border: 1.5px solid currentColor;
@@ -175,27 +80,27 @@
animation: spin 1s linear infinite;
}
-.cm-upload-anchor-actions {
+.memo-upload-anchor-actions {
display: inline-flex;
gap: 0.25rem;
}
-.cm-upload-anchor-action {
+.memo-upload-anchor-action {
border-radius: calc(var(--radius) - 2px);
padding: 0.25rem 0.5rem;
color: var(--muted-foreground);
font-weight: 500;
}
-.cm-upload-anchor-action:hover,
-.cm-upload-anchor-action:focus-visible {
+.memo-upload-anchor-action:hover,
+.memo-upload-anchor-action:focus-visible {
background: var(--accent);
color: var(--accent-foreground);
outline: none;
}
@media (prefers-reduced-motion: reduce) {
- .cm-upload-anchor-spinner {
+ .memo-upload-anchor-spinner {
animation: none;
}
}
diff --git a/web/src/components/MemoEditor/Editor/extensions.ts b/web/src/components/MemoEditor/Editor/extensions.ts
index a9b8da058..a303e10d2 100644
--- a/web/src/components/MemoEditor/Editor/extensions.ts
+++ b/web/src/components/MemoEditor/Editor/extensions.ts
@@ -1,156 +1,77 @@
-import { defaultKeymap, history, historyKeymap, indentWithTab } from "@codemirror/commands";
-import { markdown } from "@codemirror/lang-markdown";
-import { indentUnit } from "@codemirror/language";
-import { Compartment, type Extension } from "@codemirror/state";
-import { placeholder as cmPlaceholder, dropCursor, EditorView, type KeyBinding, keymap } from "@codemirror/view";
-import { runFormattingCommand } from "@/components/MemoEditor/Editor/formatting";
-import type { EditorCommandId } from "@/components/MemoEditor/formatting/commands";
-import { memoMarkdownExtensions } from "@/utils/memo-markdown-extension";
-import { headingDecorations } from "./headingDecorations";
-import { liftListItem, sinkListItem } from "./listIndent";
-import { tagAutocomplete } from "./tagAutocomplete";
-import { tagMentionDecorations } from "./tagMentionDecorations";
-import { memoEditorTheme } from "./theme";
-import { uploadAnchorField } from "./uploadAnchors";
-
-// Key bindings layered below the autocomplete keymap so its completion-specific
-// keys win while the popup is open. On a list item, Tab/Shift-Tab nest /
-// outdent it (marker-aware, CommonMark-valid); elsewhere they fall through to
-// indentWithTab's plain indent. Escape blurs the editor so keyboard users keep
-// an escape hatch out of the otherwise Tab-trapping editor.
-const editorKeys: KeyBinding[] = [
- {
- key: "Escape",
- run: (view) => {
- view.contentDOM.blur();
- return true;
- },
- },
- { key: "Tab", run: sinkListItem },
- { key: "Shift-Tab", run: liftListItem },
-];
-
-const formattingKey = (key: string, command: EditorCommandId): KeyBinding => ({
- key,
- run: (view) => {
- runFormattingCommand(view, command);
- return true;
- },
-});
-
-// Familiar cross-platform Markdown formatting keys. These stay separate from
-// CodeMirror's Markdown keymap, which only handles structural Enter/Backspace.
-const formattingKeys: KeyBinding[] = [
- formattingKey("Mod-b", "bold"),
- formattingKey("Mod-i", "italic"),
- formattingKey("Shift-Mod-s", "strikethrough"),
- formattingKey("Mod-e", "code"),
- formattingKey("Mod-Alt-c", "codeBlock"),
- formattingKey("Mod-Alt-0", "paragraph"),
- formattingKey("Shift-Mod-7", "orderedList"),
- formattingKey("Shift-Mod-8", "bulletList"),
- formattingKey("Shift-Mod-9", "taskList"),
- formattingKey("Mod-Alt-1", "heading1"),
- formattingKey("Mod-Alt-2", "heading2"),
- formattingKey("Mod-Alt-3", "heading3"),
-];
+import { type Extension, fileHandler, matchToken, type SuggestionAllowContext, scanTags, suggestion } from "@usememos/editor";
+import { memoExtensions, memoMentionOptions, memoTagOptions } from "@/lib/memo-markdown";
+import type { UserSetting_TagsSetting } from "@/types/proto/api/user_service_pb";
+import type { EditorPosition } from "../types/editorController";
/** The gesture that handed files to the editor: a drop lands at a document position, a paste has none. */
-export type EditorFileOrigin = { source: "paste" } | { source: "drop"; position: number };
+export type EditorFileOrigin = { source: "paste" } | { source: "drop"; position: EditorPosition | null };
export interface EditorExtensionsOptions {
- placeholder: string;
- onChange: (markdown: string) => void;
- onFiles: (files: File[], origin: EditorFileOrigin) => void;
- onUpdate: () => void;
- onSubmit: () => void;
+ /** Known tags, read when the popup asks for items. */
getTags: () => string[];
+ onFiles: (files: File[], origin: EditorFileOrigin) => void;
+ /** The user's tag settings, read when tags are drawn, for their custom colors. */
+ getTagsSetting: () => UserSetting_TagsSetting | undefined;
+ /** Whether a mentioned username belongs to a user, read when mentions are drawn. */
+ isMentionResolved: (username: string) => boolean;
}
-export const placeholderCompartment = new Compartment();
+/**
+ * Ranks a candidate tag against the typed text (both already lower-cased).
+ * Lower sorts first; `undefined` means the candidate does not match.
+ *
+ * Nested tags are paths, so a match inside the path counts: typing `mem` has to
+ * reach `software/hosted/Memos`, which a full-path prefix test cannot do. The
+ * tiers keep that from turning into noise — a segment start outranks an
+ * incidental hit in the middle of a word.
+ */
+export const matchRank = (tag: string, typed: string): number | undefined => {
+ const index = tag.indexOf(typed);
+ if (index < 0) return undefined;
+ if (index === 0) return 0; // Full-path prefix.
+ if (tag[index - 1] === "/") return 1; // Path-segment start.
+ return 2; // Anywhere else.
+};
-function clipboardFiles(event: ClipboardEvent): File[] {
- const clipboard = event.clipboardData;
- if (!clipboard) return [];
+/** Known tags matching `query`, best first; incoming order is kept within a tier. */
+export const rankTags = (tags: readonly string[], query: string): string[] => {
+ const typed = query.toLowerCase();
+ return tags
+ .map((tag) => ({ tag, rank: matchRank(tag.toLowerCase(), typed) }))
+ .filter((candidate): candidate is { tag: string; rank: number } => candidate.rank !== undefined)
+ .sort((a, b) => a.rank - b.rank)
+ .map(({ tag }) => tag);
+};
- const itemFiles = Array.from(clipboard.items)
- .filter((item) => item.kind === "file")
- .map((item) => item.getAsFile())
- .filter((file): file is File => file !== null);
- return itemFiles.length > 0 ? itemFiles : Array.from(clipboard.files);
-}
-
-export function buildEditorExtensions({
- placeholder,
- onChange,
- onFiles,
- onUpdate,
- onSubmit,
- getTags,
-}: EditorExtensionsOptions): Extension[] {
- // Submitting must outrank defaultKeymap's own Mod-Enter (insertBlankLine): the save
- // shortcut ends the memo, it must not also edit the document. Meta and Ctrl are bound
- // explicitly (not via the platform-dependent Mod-) so Cmd+Enter and Ctrl+Enter both
- // submit everywhere, matching the historical window-level shortcut.
- const submit = () => {
- onSubmit();
- return true;
- };
- const submitKeys: KeyBinding[] = [
- { key: "Meta-Enter", run: submit },
- { key: "Ctrl-Enter", run: submit },
- ];
+/**
+ * Where the tag popup may open. Not inside code or links, where `#` is literal,
+ * and not for a bare `#` at the start of a line, which is more likely the start
+ * of a heading. Ctrl+Space still opens it there.
+ */
+export const allowTagSuggestion = ({ excluded, explicit, query, textBefore }: SuggestionAllowContext): boolean => {
+ if (excluded) return false;
+ if (explicit) return true;
+ return !(query === "" && /(^|\n)[ \t]*$/.test(textBefore));
+};
+export function buildEditorExtensions({ getTags, onFiles, getTagsSetting, isMentionResolved }: EditorExtensionsOptions): Extension[] {
return [
- // Core editing behavior. These are the pieces from CM6 setup that this memo
- // editor uses, without enabling multi-cursor selection.
- history(),
- dropCursor(),
- // Indent with spaces (markdown), matching the 2-space bullet nesting.
- indentUnit.of(" "),
- markdown({ extensions: memoMarkdownExtensions }),
- ...memoEditorTheme,
- EditorView.lineWrapping,
- // CodeMirror disables native text assistance because it is primarily a code
- // editor. Memos is a prose editor, so restore the browser behavior used by
- // the textarea editor before v0.30. Autocorrect also keeps Windows TSF input
- // out of Chrome's autocorrect-suppression path, which has dropped committed
- // text from the emoji picker.
- EditorView.contentAttributes.of({
- autocorrect: "on",
- autocapitalize: "on",
- spellcheck: "true",
- }),
- placeholderCompartment.of(cmPlaceholder(placeholder)),
- EditorView.domEventHandlers({
- paste: (event) => {
- const files = clipboardFiles(event);
- if (files.length === 0) return false;
- onFiles(files, { source: "paste" });
- return true;
- },
- drop: (event, view) => {
- const files = Array.from(event.dataTransfer?.files ?? []);
- if (files.length === 0) return false;
- const position = view.posAtCoords({ x: event.clientX, y: event.clientY }) ?? view.state.selection.main.head;
- onFiles(files, { source: "drop", position });
- return true;
- },
+ // Tags and mentions look the same as in the memo view.
+ ...memoExtensions({ tags: memoTagOptions(getTagsSetting), mentions: memoMentionOptions(isMentionResolved) }),
+ // The popup opens exactly where tags are highlighted: the matcher is built
+ // from the same scanner as tags(). A pick writes "#work/planning ".
+ suggestion({
+ name: "tags",
+ trigger: ["#", "#"],
+ match: matchToken(scanTags),
+ allow: allowTagSuggestion,
+ items: ({ query }) => rankTags(getTags(), query).map((tag) => ({ id: tag, label: `#${tag}`, value: tag })),
}),
- tagMentionDecorations,
- headingDecorations,
- uploadAnchorField,
- // tagAutocomplete must precede the editing keymap so the completion popup's
- // Enter/Escape/arrow bindings win while it is open.
- tagAutocomplete(getTags),
- // Formatting keys precede defaultKeymap so the conventional Mod-I italic
- // shortcut wins over CodeMirror's generic selectParentSyntax binding.
- keymap.of([...submitKeys, ...editorKeys, ...formattingKeys, indentWithTab, ...defaultKeymap, ...historyKeymap]),
- EditorView.updateListener.of((u) => {
- if (u.docChanged) onChange(u.state.doc.toString());
- // Toolbar active-state depends only on the doc and selection; skip the
- // getActiveFormats tree walk on focus/viewport/measure-only updates.
- if (u.docChanged || u.selectionSet) onUpdate();
+ // Pasted files join the attachment list (a paste carries no placement
+ // gesture); dropped files land where they were dropped.
+ fileHandler({
+ onPaste: ({ files }) => onFiles(files, { source: "paste" }),
+ onDrop: ({ files, position }) => onFiles(files, { source: "drop", position }),
}),
];
}
diff --git a/web/src/components/MemoEditor/Editor/formatting.ts b/web/src/components/MemoEditor/Editor/formatting.ts
deleted file mode 100644
index 814b091b7..000000000
--- a/web/src/components/MemoEditor/Editor/formatting.ts
+++ /dev/null
@@ -1,398 +0,0 @@
-import { syntaxTree } from "@codemirror/language";
-import type { EditorState } from "@codemirror/state";
-import type { EditorView } from "@codemirror/view";
-import {
- type ActiveFormatState,
- type EditorCommandContext,
- type EditorCommandId,
- EMPTY_ACTIVE_FORMATS,
- toToolbarHeadingLevel,
-} from "../formatting/commands";
-import type { FormattingController } from "../types/editorController";
-import { leadingWhitespace, selectedLineNumbers } from "./listIndent";
-
-type MarkCommand = "bold" | "italic" | "strikethrough" | "code";
-type ListCommand = "bulletList" | "orderedList" | "taskList";
-
-// One row per inline mark: the markdown token plus the syntax-tree wrapper and
-// delimiter node names (verified empirically against the Lezer markdown parser:
-// StrongEmphasis/Emphasis use `EmphasisMark`, InlineCode uses `CodeMark`, and
-// GFM strikethrough uses `Strikethrough`/`StrikethroughMark`).
-// Dispatch, toggling, the delimiter guard, and active-state detection all
-// derive from this table, so adding a mark is one row here + a catalog entry.
-const MARKS: Record<MarkCommand, { token: string; wrapper: string; delimiter: string }> = {
- bold: { token: "**", wrapper: "StrongEmphasis", delimiter: "EmphasisMark" },
- italic: { token: "*", wrapper: "Emphasis", delimiter: "EmphasisMark" },
- strikethrough: { token: "~~", wrapper: "Strikethrough", delimiter: "StrikethroughMark" },
- code: { token: "`", wrapper: "InlineCode", delimiter: "CodeMark" },
-};
-const MARK_COMMANDS = Object.keys(MARKS) as MarkCommand[];
-const isMarkCommand = (command: EditorCommandId): command is MarkCommand => command in MARKS;
-const WRAPPER_TO_MARK: Record<string, MarkCommand> = Object.fromEntries(MARK_COMMANDS.map((c) => [MARKS[c].wrapper, c]));
-// A cursor inside one of these means the adjacent token characters belong to
-// real parsed markup (e.g. between the two `*` of a bold delimiter), not to a
-// dangling empty pair.
-const DELIMITER_NODES = new Set(MARK_COMMANDS.map((c) => MARKS[c].delimiter));
-// Doubled mark tokens (`****`, `~~~~`, …): what a freshly inserted empty pair
-// looks like. Markdown parses some of them as entirely different constructs
-// (`~~~~` is a bare tilde code fence), so consumers that would otherwise
-// believe that construct check here first.
-const EMPTY_MARK_PAIRS = new Set(MARK_COMMANDS.map((c) => MARKS[c].token + MARKS[c].token));
-const MAX_EMPTY_PAIR_LENGTH = Math.max(...MARK_COMMANDS.map((c) => 2 * MARKS[c].token.length));
-
-/** Whether [from, to) is exactly some mark's empty delimiter pair. */
-function isEmptyMarkPair(state: EditorState, from: number, to: number): boolean {
- return to - from <= MAX_EMPTY_PAIR_LENGTH && EMPTY_MARK_PAIRS.has(state.sliceDoc(from, to));
-}
-
-const LIST_MARKERS: Record<ListCommand, string> = { bulletList: "- ", orderedList: "1. ", taskList: "- [ ] " };
-
-// Line-mode detection shared by the list toggles and getActiveFormats so the
-// highlighted state and the toggle-off condition can never disagree. Order
-// matters: a task line also matches the bullet pattern. Markers follow
-// listIndent.ts: bullets `-*+`, ordered `1.` / `1)`, content starts after the
-// marker's trailing whitespace.
-const TASK_LINE = /^(\s*)[-*+]\s+\[[ xX]\]\s+/;
-const BULLET_LINE = /^(\s*)[-*+]\s+/;
-const ORDERED_LINE = /^(\s*)\d+[.)]\s+/;
-// ATX heading; CommonMark allows up to three leading spaces and requires
-// whitespace after the hashes — a bare `#` or a `#tag` is intentionally NOT a
-// heading. Shared with headingDecorations.ts so toolbar state and rendered
-// heading styling can't drift.
-export const HEADING_LINE = /^ {0,3}(#{1,6})\s+/;
-// Region setHeading replaces: an existing heading prefix including its leading
-// spaces, or just the leading spaces on a non-heading line (the optional group
-// makes the regex always match).
-const HEADING_PREFIX = /^ {0,3}(?:#{1,6}\s+)?/;
-
-type Tree = ReturnType<typeof syntaxTree>;
-type TreeNode = ReturnType<Tree["resolve"]>;
-
-/** The node at (pos, side) and its ancestors, innermost first. */
-function* ancestors(tree: Tree, pos: number, side: -1 | 1): Generator<TreeNode> {
- for (let n: TreeNode | null = tree.resolve(pos, side); n; n = n.parent) {
- yield n;
- }
-}
-
-/** Ranges of the direct `name` children of `node`. */
-function childRanges(node: TreeNode, name: string): { from: number; to: number }[] {
- const ranges: { from: number; to: number }[] = [];
- for (let child = node.firstChild; child; child = child.nextSibling) {
- if (child.name === name) ranges.push({ from: child.from, to: child.to });
- }
- return ranges;
-}
-
-interface LineListInfo {
- mode: ListCommand | null;
- /** Length of leading whitespace. */
- indent: number;
- /** Offset within the line where the item content starts (=== indent when mode is null). */
- markerEnd: number;
-}
-
-function lineListInfo(text: string): LineListInfo {
- const task = TASK_LINE.exec(text);
- if (task) return { mode: "taskList", indent: task[1].length, markerEnd: task[0].length };
- const bullet = BULLET_LINE.exec(text);
- if (bullet) return { mode: "bulletList", indent: bullet[1].length, markerEnd: bullet[0].length };
- const ordered = ORDERED_LINE.exec(text);
- if (ordered) return { mode: "orderedList", indent: ordered[1].length, markerEnd: ordered[0].length };
- const indent = leadingWhitespace(text);
- return { mode: null, indent, markerEnd: indent };
-}
-
-function wrapSelection(view: EditorView, token: string) {
- const { from, to } = view.state.selection.main;
- const sel = view.state.sliceDoc(from, to);
- // CommonMark cannot close an emphasis delimiter immediately after
- // whitespace. Keep selection-edge whitespace outside the mark instead of
- // producing source such as `**important **`, which renders literally.
- const edgeLeadingWhitespace = sel.match(/^\s*/)?.[0] ?? "";
- const edgeTrailingWhitespace = sel.match(/\s*$/)?.[0] ?? "";
- const contentEnd = sel.length - edgeTrailingWhitespace.length;
- const content = sel.slice(edgeLeadingWhitespace.length, contentEnd);
-
- // There is no text to mark. Preserve the existing empty-cursor behavior
- // (an editable delimiter pair), but do not replace a whitespace-only
- // selection with invalid emphasis or discard its whitespace.
- if (!content) {
- if (sel) return;
- view.dispatch({
- changes: { from, to, insert: `${token}${token}` },
- selection: { anchor: from + token.length },
- });
- return;
- }
-
- const contentStart = from + edgeLeadingWhitespace.length;
- view.dispatch({
- changes: { from, to, insert: `${edgeLeadingWhitespace}${token}${content}${token}${edgeTrailingWhitespace}` },
- selection: { anchor: contentStart + token.length, head: contentStart + token.length + content.length },
- });
-}
-
-/**
- * Delimiter child ranges of the nearest `wrapper` ancestor at the selection,
- * or null when the selection doesn't sit in one (or it has fewer than
- * `minMarks` delimiters). Shared by every toggle-off path so they all agree.
- *
- * The head probe mirrors getActiveFormats (resolve side -1) so stripping
- * fires exactly when the toolbar shows the command active. With a non-empty
- * selection, additionally probe both edges from inside the selection, so a
- * selection that includes the delimiters (the whole `**text**`) still
- * resolves into the wrapper regardless of selection direction.
- */
-function findWrappedDelimiters(
- view: EditorView,
- wrapper: string,
- delimiter: string,
- minMarks: number,
-): { from: number; to: number }[] | null {
- const { from, to, head } = view.state.selection.main;
- const tree = syntaxTree(view.state);
- const probes: [number, -1 | 1][] =
- from === to
- ? [[head, -1]]
- : [
- [head, -1],
- [from, 1],
- [to, -1],
- ];
- for (const [pos, side] of probes) {
- for (const n of ancestors(tree, pos, side)) {
- if (n.name !== wrapper) continue;
- const marks = childRanges(n, delimiter);
- if (marks.length >= minMarks) return marks;
- }
- }
- return null;
-}
-
-/**
- * Toggle an inline mark (bold/italic/strikethrough/code). When the selection
- * already sits in the corresponding mark, strip the surrounding delimiter
- * nodes instead of nesting a new pair. Deleting the actual delimiter child
- * ranges handles the differing delimiter lengths (`**` vs `` ` ``) automatically.
- */
-function toggleMark(view: EditorView, command: MarkCommand) {
- const { token, wrapper, delimiter } = MARKS[command];
- const marks = findWrappedDelimiters(view, wrapper, delimiter, 2);
- if (marks) {
- const opening = marks[0];
- const closing = marks[marks.length - 1];
- view.dispatch({
- changes: [
- { from: closing.from, to: closing.to, insert: "" },
- { from: opening.from, to: opening.to, insert: "" },
- ],
- });
- return;
- }
- // Empty pair: a cursor sitting between freshly inserted delimiters (`**|**`).
- // Markdown never parses an empty mark as that mark (bare `****` is a
- // horizontal rule, `~~~~` a tilde code fence, `` `` `` plain text), so the
- // tree probe above can't see it — check the text instead. Without this,
- // re-clicking the button keeps nesting new pairs.
- const { from, to } = view.state.selection.main;
- if (
- from === to &&
- from >= token.length &&
- to + token.length <= view.state.doc.length &&
- view.state.sliceDoc(from - token.length, to + token.length) === token + token
- ) {
- const delFrom = from - token.length;
- const delTo = to + token.length;
- // Deleting is only unsafe when the adjacent tokens belong to parsed markup
- // reaching beyond the pair itself — e.g. an italic click between the `*`s
- // of a bold delimiter would destroy that bold. A construct contained
- // entirely in the deletion range (the `~~~~` the parser reads as an empty
- // tilde fence) is just this empty pair wearing another node name.
- const tree = syntaxTree(view.state);
- const blocking = (n: TreeNode) => {
- if (!DELIMITER_NODES.has(n.name)) return false;
- const construct = n.parent ?? n;
- return construct.from < delFrom || construct.to > delTo;
- };
- if (!blocking(tree.resolve(from, -1)) && !blocking(tree.resolve(to, 1))) {
- view.dispatch({
- changes: [
- { from: delFrom, to: from, insert: "" },
- { from: to, to: delTo, insert: "" },
- ],
- });
- return;
- }
- }
- wrapSelection(view, token);
-}
-
-/**
- * Toggle a fenced code block. When the selection sits inside one, remove its
- * fence lines (keeping the content); otherwise wrap the selected lines in a
- * new ``` fence. Unclosed blocks (opening fence only) lose just that fence.
- */
-function toggleCodeBlock(view: EditorView) {
- const { state } = view;
- const { from, to } = state.selection.main;
- const marks = findWrappedDelimiters(view, "FencedCode", "CodeMark", 1);
- if (marks) {
- const openLine = state.doc.lineAt(marks[0].from);
- // Delete each fence line together with its trailing newline. When the
- // closing fence is the document's last line there is no trailing newline
- // to take, so eat the preceding one instead — unless that would overlap
- // the opening deletion (empty block at end of document).
- const openEnd = Math.min(openLine.to + 1, state.doc.length);
- const specs = [{ from: openLine.from, to: openEnd, insert: "" }];
- if (marks.length >= 2) {
- const closeLine = state.doc.lineAt(marks[marks.length - 1].from);
- const closeIsLastLine = closeLine.to === state.doc.length;
- const closeTo = closeIsLastLine ? closeLine.to : closeLine.to + 1;
- const closeFrom = closeIsLastLine && closeLine.from - 1 >= openEnd ? closeLine.from - 1 : closeLine.from;
- specs.push({ from: closeFrom, to: closeTo, insert: "" });
- }
- const changes = state.changes(specs);
- view.dispatch({ changes, selection: state.selection.map(changes) });
- return;
- }
- const lineNumbers = selectedLineNumbers(view);
- const first = state.doc.line(lineNumbers[0]);
- const last = state.doc.line(lineNumbers[lineNumbers.length - 1]);
- const fence = "```";
- // Both selection ends sit within [first.from, last.to], so they shift by
- // exactly the opening `\`\`\`\n` — keeping the selection on the content (and
- // dropping a lone cursor inside the new empty block).
- view.dispatch({
- changes: [
- { from: first.from, insert: `${fence}\n` },
- { from: last.to, insert: `\n${fence}` },
- ],
- selection: { anchor: from + fence.length + 1, head: to + fence.length + 1 },
- });
-}
-
-/**
- * Toggle/convert the list mode of the selected lines. The three list modes are
- * mutually exclusive line states: when every selected line is already in the
- * requested mode the markers are removed; otherwise lines are converted to it
- * (replacing any other list marker, preserving indentation). With a multi-line
- * selection blank lines are left alone; a single selected blank line still gets
- * a marker so the "start a list on an empty line" flow works.
- */
-function toggleListLine(view: EditorView, command: ListCommand) {
- const { state } = view;
- const lines = selectedLineNumbers(view).map((n) => state.doc.line(n));
- const nonBlank = lines.filter((line) => line.text.trim() !== "");
- const targets = lines.length === 1 || nonBlank.length === 0 ? lines : nonBlank;
- const infos = targets.map((line) => lineListInfo(line.text));
- const allOn = infos.every((info) => info.mode === command);
-
- const specs: { from: number; to: number; insert: string }[] = [];
- for (const [i, line] of targets.entries()) {
- const { mode, indent, markerEnd } = infos[i];
- if (allOn) {
- specs.push({ from: line.from + indent, to: line.from + markerEnd, insert: "" });
- } else if (mode !== command) {
- // Lines already in the requested mode keep their marker untouched (a
- // checked `- [x]` stays checked when the selection is extended).
- const marker = command === "orderedList" ? `${i + 1}. ` : LIST_MARKERS[command];
- specs.push({ from: line.from + indent, to: line.from + markerEnd, insert: marker });
- }
- }
- if (specs.length === 0) return;
- const changes = state.changes(specs);
- // Map with assoc 1 so a cursor exactly at the insertion point (empty line)
- // lands after the inserted marker instead of staying at the line start.
- view.dispatch({ changes, selection: state.selection.map(changes, 1) });
-}
-
-function setHeading(view: EditorView, level: number) {
- const line = view.state.doc.lineAt(view.state.selection.main.head);
- // Edit only the prefix region (not the whole line) so the cursor keeps its
- // place in the text instead of being flung to the line start by the mapping.
- const existing = HEADING_PREFIX.exec(line.text)?.[0].length ?? 0;
- const insert = level === 0 ? "" : `${"#".repeat(level)} `;
- const changes = view.state.changes({ from: line.from, to: line.from + existing, insert });
- view.dispatch({ changes, selection: view.state.selection.map(changes, 1) });
-}
-
-/** Unwrap the link the head sits in to its label text. True when one was found. */
-function unwrapLink(view: EditorView): boolean {
- const head = view.state.selection.main.head;
- const tree = syntaxTree(view.state);
- for (const n of ancestors(tree, head, -1)) {
- if (n.name !== "Link") continue;
- const marks = childRanges(n, "LinkMark");
- // marks[0] is `[`, marks[1] is `]` — the label sits between them.
- if (marks.length < 2) continue;
- const label = view.state.sliceDoc(marks[0].to, marks[1].from);
- const anchor = n.from + Math.max(0, Math.min(label.length, head - marks[0].to));
- view.dispatch({
- changes: { from: n.from, to: n.to, insert: label },
- selection: { anchor },
- });
- return true;
- }
- return false;
-}
-
-/** Apply one formatting verb to a CodeMirror view. Shared by the toolbar controller and keymap. */
-export function runFormattingCommand(view: EditorView, command: EditorCommandId, ctx?: EditorCommandContext): void {
- if (isMarkCommand(command)) return toggleMark(view, command);
- if (command === "codeBlock") return toggleCodeBlock(view);
- if (command === "bulletList" || command === "orderedList" || command === "taskList") {
- return toggleListLine(view, command);
- }
- if (command === "heading1") return setHeading(view, 1);
- if (command === "heading2") return setHeading(view, 2);
- if (command === "heading3") return setHeading(view, 3);
- if (command === "paragraph") return setHeading(view, 0);
- if (command === "link") {
- // Toggle: inside an existing link, unwrap it to its label.
- if (unwrapLink(view)) return;
- const { from, to } = view.state.selection.main;
- const url = ctx?.url ?? "";
- // Empty selection: the URL doubles as the label.
- const label = view.state.sliceDoc(from, to) || url;
- const insert = `[${label}](${url})`;
- view.dispatch({ changes: { from, to, insert }, selection: { anchor: from + insert.length } });
- }
-}
-
-export function createFormattingController(view: EditorView, listeners: Set<() => void>): FormattingController {
- return {
- run(command: EditorCommandId, ctx?: EditorCommandContext) {
- runFormattingCommand(view, command, ctx);
- },
- getActiveFormats(): ActiveFormatState {
- const pos = view.state.selection.main.head;
- const tree = syntaxTree(view.state);
- const active: ActiveFormatState = { ...EMPTY_ACTIVE_FORMATS };
- // Inline marks come from the syntax tree around the cursor.
- for (const n of ancestors(tree, pos, -1)) {
- const mark = WRAPPER_TO_MARK[n.name];
- if (mark) active[mark] = true;
- else if (n.name === "Link") active.link = true;
- // The isEmptyMarkPair guard: a fresh empty strikethrough pair
- // (`~~|~~`) parses as a bare tilde code fence — don't light the
- // code-block button while the cursor sits in one.
- else if (n.name === "FencedCode" && !isEmptyMarkPair(view.state, n.from, n.to)) active.codeBlock = true;
- }
- // Line modes (lists, headings) come from the same line inspection the
- // toggles use, keeping highlight and toggle behavior in lockstep.
- const line = view.state.doc.lineAt(pos).text;
- const heading = HEADING_LINE.exec(line);
- if (heading) active.headingLevel = toToolbarHeadingLevel(heading[1].length);
- const { mode } = lineListInfo(line);
- if (mode) active[mode] = true;
- return active;
- },
- subscribe(listener: () => void) {
- listeners.add(listener);
- return () => {
- listeners.delete(listener);
- };
- },
- };
-}
diff --git a/web/src/components/MemoEditor/Editor/headingDecorations.ts b/web/src/components/MemoEditor/Editor/headingDecorations.ts
deleted file mode 100644
index 921236b02..000000000
--- a/web/src/components/MemoEditor/Editor/headingDecorations.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { RangeSetBuilder } from "@codemirror/state";
-import { Decoration, type DecorationSet, EditorView } from "@codemirror/view";
-import { type HeadingLevel, headingTypeClass } from "@/lib/markdownStyles";
-import { HEADING_LINE } from "./formatting";
-import { viewportDecorations } from "./viewportDecorations";
-
-// Heading type comes from the same token as the read-only view, so a heading
-// keeps its size and weight when the memo is saved.
-const lineDecorations = ([1, 2, 3, 4, 5, 6] as const).map((level: HeadingLevel) =>
- Decoration.line({ class: `cm-md-h${level} ${headingTypeClass(level)}` }),
-);
-
-function build(view: EditorView): DecorationSet {
- const builder = new RangeSetBuilder<Decoration>();
- for (const { from, to } of view.visibleRanges) {
- const startLine = view.state.doc.lineAt(from).number;
- const endLine = view.state.doc.lineAt(to).number;
- for (let n = startLine; n <= endLine; n++) {
- const line = view.state.doc.line(n);
- const m = HEADING_LINE.exec(line.text);
- if (m) {
- builder.add(line.from, line.from, lineDecorations[m[1].length - 1]);
- }
- }
- }
- return builder.finish();
-}
-
-export const headingDecorations = viewportDecorations(build);
diff --git a/web/src/components/MemoEditor/Editor/index.tsx b/web/src/components/MemoEditor/Editor/index.tsx
index f583f93db..759c0cd11 100644
--- a/web/src/components/MemoEditor/Editor/index.tsx
+++ b/web/src/components/MemoEditor/Editor/index.tsx
@@ -1,149 +1,140 @@
-import { EditorState } from "@codemirror/state";
-import { placeholder as cmPlaceholder, EditorView } from "@codemirror/view";
-import { forwardRef, useCallback, useImperativeHandle, useLayoutEffect, useMemo, useRef } from "react";
-import { useTagCounts } from "@/hooks/useUserQueries";
+import type { Editor as MarkdownEditorInstance } from "@usememos/editor";
+import { MarkdownEditor } from "@usememos/editor/react";
+import "@usememos/editor/style.css";
+import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
+import { useDebouncedEffect } from "@/hooks";
+import { useTagCounts, useUsersByUsernames } from "@/hooks/useUserQueries";
+import { extractMentionUsernames, MEMO_EDITOR_THEME, MEMO_MARKDOWN, memoEditorLabels, memoResolveUrl } from "@/lib/memo-markdown";
import { cn } from "@/lib/utils";
+import type { Attachment } from "@/types/proto/api/attachment_service_pb";
+import type { UserSetting_TagsSetting } from "@/types/proto/api/user_service_pb";
+import { useTranslate } from "@/utils/i18n";
import type { EditorController } from "../types/editorController";
import { createController } from "./controller";
import "./editor.css";
-import { buildEditorExtensions, type EditorFileOrigin, placeholderCompartment } from "./extensions";
-import { createFormattingController } from "./formatting";
+import { buildEditorExtensions, type EditorFileOrigin } from "./extensions";
interface EditorProps {
className: string;
- initialContent: string;
- contentIsExternal?: boolean;
+ /** The document. The editor applies a value only when it is not one the editor emitted itself. */
+ value: string;
placeholder: string;
onContentChange: (content: string) => void;
- onExternalContentApplied?: (content: string) => void;
onFiles: (files: File[], origin: EditorFileOrigin) => void;
/** Invoked by the in-editor save shortcut (Cmd/Ctrl+Enter). */
onSubmit: () => void;
isFocusMode?: boolean;
+ /** The draft's attachments, so images of managed attachments show. */
+ attachments?: readonly Attachment[];
+ /** The user's tag settings, for tags in their custom colors. */
+ tagsSetting?: UserSetting_TagsSetting;
}
+const EDITOR_ATTRIBUTES = {
+ // Memos is a prose editor: keep the browser's text assistance on. Autocorrect
+ // also keeps Windows TSF input out of Chrome's autocorrect-suppression path,
+ // which has dropped committed text from the emoji picker.
+ autocorrect: "on",
+ autocapitalize: "on",
+ spellcheck: "true",
+};
+
const Editor = forwardRef(function Editor(props: EditorProps, ref: React.ForwardedRef<EditorController>) {
- const {
- className,
- initialContent,
- contentIsExternal = true,
- placeholder,
- onContentChange,
- onExternalContentApplied,
- onFiles,
- onSubmit,
- isFocusMode,
- } = props;
- const hostRef = useRef<HTMLDivElement>(null);
- const viewRef = useRef<EditorView | null>(null);
- const controllerRef = useRef<EditorController | null>(null);
- const applyingExternalContentRef = useRef(false);
- const pendingExternalContentRef = useRef<string | null>(null);
- const onChangeRef = useRef(onContentChange);
- onChangeRef.current = onContentChange;
- const onExternalContentAppliedRef = useRef(onExternalContentApplied);
- onExternalContentAppliedRef.current = onExternalContentApplied;
+ const { className, value, placeholder, onContentChange, onFiles, onSubmit, isFocusMode, attachments, tagsSetting } = props;
+ const t = useTranslate();
+ const editorRef = useRef<MarkdownEditorInstance | null>(null);
+ const onContentChangeRef = useRef(onContentChange);
+ onContentChangeRef.current = onContentChange;
const onFilesRef = useRef(onFiles);
onFilesRef.current = onFiles;
const onSubmitRef = useRef(onSubmit);
onSubmitRef.current = onSubmit;
- const placeholderRef = useRef(placeholder);
- const listenersRef = useRef(new Set<() => void>());
// A user can only author their own memos. Reuse the current-user stats query
// instead of fetching and aggregating every user's tags for autocomplete.
const { data: tagData } = useTagCounts(true);
- const tags = useMemo(() => Object.keys(tagData ?? {}), [tagData]);
- const tagsRef = useRef(tags);
- tagsRef.current = tags;
-
- const applyExternalContent = useCallback((content: string) => {
- pendingExternalContentRef.current = null;
- const controller = controllerRef.current;
- if (!controller || controller.getMarkdown() === content) return;
- applyingExternalContentRef.current = true;
- try {
- controller.setMarkdown(content);
- } finally {
- applyingExternalContentRef.current = false;
- }
- }, []);
+ const tagsRef = useRef<string[]>([]);
+ tagsRef.current = useMemo(() => Object.keys(tagData ?? {}), [tagData]);
- // useLayoutEffect (not useEffect) so the EditorView — and its placeholder —
- // mount before the browser paints. With useEffect the first painted frame
- // shows an empty host, then the placeholder pops in (a load flicker).
- useLayoutEffect(() => {
- if (!hostRef.current) return;
- const view = new EditorView({
- state: EditorState.create({
- doc: initialContent,
- extensions: buildEditorExtensions({
- placeholder,
- onChange: (md) => {
- if (!applyingExternalContentRef.current) onChangeRef.current(md);
- },
- onFiles: (files, origin) => onFilesRef.current(files, origin),
- onUpdate: () => listenersRef.current.forEach((l) => l()),
- onSubmit: () => onSubmitRef.current(),
- getTags: () => tagsRef.current,
- }),
- }),
- parent: hostRef.current,
- });
- viewRef.current = view;
- controllerRef.current = createController(view, createFormattingController(view, listenersRef.current));
- const handleCompositionEnd = () => {
- // CodeMirror may flush its final Firefox/Android DOM mutations in a
- // microtask after compositionend. Queue behind that flush before
- // replacing the document with a deferred external value.
- queueMicrotask(() => {
- if (viewRef.current !== view || view.compositionStarted) return;
- const pendingContent = pendingExternalContentRef.current;
- if (pendingContent === null) return;
- applyExternalContent(pendingContent);
- // The composition may have emitted a newer local value after this
- // deferred external value entered the store. Reassert the applied
- // external value there too.
- onExternalContentAppliedRef.current?.(pendingContent);
- });
- };
- view.contentDOM.addEventListener("compositionend", handleCompositionEnd);
- return () => {
- view.contentDOM.removeEventListener("compositionend", handleCompositionEnd);
- view.destroy();
- viewRef.current = null;
- controllerRef.current = null;
- };
- // Mount once; external sync handled below.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ const tagsSettingRef = useRef(tagsSetting);
+ tagsSettingRef.current = tagsSetting;
+ // Tag colors are drawn from the settings; draw them again when the settings change.
+ const decoratedTagsSetting = useRef(tagsSetting);
+ useEffect(() => {
+ if (decoratedTagsSetting.current === tagsSetting) return;
+ decoratedTagsSetting.current = tagsSetting;
+ editorRef.current?.redecorate();
+ }, [tagsSetting]);
- useLayoutEffect(() => {
- if (placeholderRef.current === placeholder) return;
- placeholderRef.current = placeholder;
- viewRef.current?.dispatch({ effects: placeholderCompartment.reconfigure(cmPlaceholder(placeholder)) });
- }, [placeholder]);
+ // Mentions of people who exist are drawn as in the memo view. The names are looked up
+ // once typing pauses, so a half-typed name is not; until a lookup answers, the people
+ // already found stay found.
+ const [mentionNames, setMentionNames] = useState<string[]>([]);
+ useDebouncedEffect(
+ () => {
+ const next = extractMentionUsernames(value);
+ setMentionNames((previous) => (previous.join("\n") === next.join("\n") ? previous : next));
+ },
+ 400,
+ [value],
+ );
+ const { data: mentionUsers } = useUsersByUsernames(mentionNames);
+ const resolvedMentionsRef = useRef<ReadonlySet<string>>(new Set());
+ useEffect(() => {
+ if (!mentionUsers) return;
+ const next = new Set([...mentionUsers].flatMap(([username, user]) => (user ? [username] : [])));
+ const current = resolvedMentionsRef.current;
+ if (next.size === current.size && [...next].every((username) => current.has(username))) return;
+ resolvedMentionsRef.current = next;
+ editorRef.current?.redecorate();
+ }, [mentionUsers]);
- useLayoutEffect(() => {
- if (!contentIsExternal) return;
- const view = viewRef.current;
- if (!view) return;
- if (view.compositionStarted) {
- pendingExternalContentRef.current = initialContent;
- return;
- }
- applyExternalContent(initialContent);
- }, [applyExternalContent, contentIsExternal, initialContent]);
+ const controller = useMemo(
+ () =>
+ createController(
+ () => editorRef.current,
+ (markdown) => onContentChangeRef.current(markdown),
+ ),
+ [],
+ );
+ useImperativeHandle(ref, () => controller, [controller]);
- // The controller is created in the mount layout effect above, which runs
- // before this (also layout-phase) handle, so controllerRef.current is set.
- useImperativeHandle(ref, () => controllerRef.current as EditorController, []);
+ // Created once: the editor keeps its extensions for its lifetime, so the
+ // callbacks read the latest props through refs.
+ const extensions = useMemo(
+ () =>
+ buildEditorExtensions({
+ getTags: () => tagsRef.current,
+ onFiles: (files, origin) => onFilesRef.current(files, origin),
+ getTagsSetting: () => tagsSettingRef.current,
+ isMentionResolved: (username) => resolvedMentionsRef.current.has(username),
+ }),
+ [],
+ );
+ const labels = useMemo(() => memoEditorLabels(t), [t]);
+ const resolveUrl = useMemo(() => memoResolveUrl(attachments), [attachments]);
return (
<div
className={cn("relative flex w-full flex-col items-start justify-start bg-inherit", isFocusMode && "min-h-0 flex-1", className)}
data-focus-mode={isFocusMode || undefined}
>
- <div ref={hostRef} className={cn("w-full text-base", isFocusMode && "min-h-0 flex-1")} />
+ <div className={cn("memo-editor-scroller w-full text-base", isFocusMode && "min-h-0 flex-1")}>
+ <MarkdownEditor
+ ref={editorRef}
+ value={value}
+ onChange={onContentChange}
+ onSubmit={() => onSubmitRef.current()}
+ placeholder={placeholder}
+ markdown={MEMO_MARKDOWN}
+ extensions={extensions}
+ theme={MEMO_EDITOR_THEME}
+ labels={labels}
+ attributes={EDITOR_ATTRIBUTES}
+ resolveUrl={resolveUrl}
+ referrerPolicy="no-referrer"
+ className="memo-editor-root"
+ />
+ </div>
</div>
);
});
diff --git a/web/src/components/MemoEditor/Editor/listIndent.ts b/web/src/components/MemoEditor/Editor/listIndent.ts
deleted file mode 100644
index 218025199..000000000
--- a/web/src/components/MemoEditor/Editor/listIndent.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import type { Text } from "@codemirror/state";
-import type { EditorView } from "@codemirror/view";
-
-// A list item line: leading whitespace + bullet (-, *, +) or ordered marker
-// (1. / 1)) + at least one space.
-const LIST_ITEM = /^(\s*)(?:[-*+]|\d+[.)])\s/;
-const ORDERED_ITEM = /^(\s*)(\d+)([.)])(\s+)(.*)$/;
-// The full marker prefix (indent + marker + trailing spaces); its length is the
-// column where the item's content — and therefore a nested child — begins.
-const LIST_PREFIX = /^\s*(?:[-*+]|\d+[.)])\s+/;
-
-export const leadingWhitespace = (text: string): number => text.length - text.trimStart().length;
-
-/** Unique line numbers covered by the selection, ascending (also used by formatting.ts). */
-export function selectedLineNumbers(view: EditorView): number[] {
- const { doc, selection } = view.state;
- const nums = new Set<number>();
- for (const range of selection.ranges) {
- const last = doc.lineAt(range.to).number;
- for (let n = doc.lineAt(range.from).number; n <= last; n++) {
- nums.add(n);
- }
- }
- return [...nums].sort((a, b) => a - b);
-}
-
-/** Preceding lines, nearest first, stopping at the first blank line (list end). */
-function* previousListLines(doc: Text, from: number): Generator<{ text: string; indent: number }> {
- for (let p = from - 1; p >= 1; p--) {
- const { text } = doc.line(p);
- if (text.trim() === "") return;
- yield { text, indent: leadingWhitespace(text) };
- }
-}
-
-/**
- * The number an ordered item should take at `indent`: one more than the nearest
- * preceding sibling ordered item at the same indent, else 1 (first child of a
- * new sublist). CommonMark only nests an ordered sublist whose first item is
- * `1.`, so renumbering — not just re-indenting — is what makes a nested ordered
- * list actually render as nested.
- */
-function nextOrderedNumber(doc: Text, lineNumber: number, indent: number): number {
- for (const prev of previousListLines(doc, lineNumber)) {
- if (prev.indent < indent) break; // reached the parent
- if (prev.indent === indent) {
- const ordered = ORDERED_ITEM.exec(prev.text);
- return ordered ? Number.parseInt(ordered[2], 10) + 1 : 1;
- }
- // deeper line — part of a sibling's subtree; keep scanning up
- }
- return 1;
-}
-
-/** Rewrite a list line to a new indent, renumbering it if it is an ordered item. */
-function reindented(doc: Text, lineNumber: number, text: string, indent: number): string {
- const ordered = ORDERED_ITEM.exec(text);
- if (ordered) {
- const [, , , delimiter, spaces, content] = ordered;
- return `${" ".repeat(indent)}${nextOrderedNumber(doc, lineNumber, indent)}${delimiter}${spaces}${content}`;
- }
- return " ".repeat(indent) + text.slice(leadingWhitespace(text));
-}
-
-/**
- * Tab on a list item: nest it under the preceding item by aligning its indent to
- * that item's content column (past the marker) and renumbering ordered items so
- * the nested list is CommonMark-valid. Returns false when not on a list item so
- * the caller's default Tab (plain indent) applies.
- */
-export function sinkListItem(view: EditorView): boolean {
- const { doc } = view.state;
- const changes: { from: number; to: number; insert: string }[] = [];
- for (const n of selectedLineNumbers(view)) {
- const line = doc.line(n);
- const match = LIST_ITEM.exec(line.text);
- if (!match) return false;
- const indent = match[1].length;
- let target = indent + 2; // fallback when there is no item to nest under
- for (const prev of previousListLines(doc, n)) {
- if (prev.indent > indent) continue; // deeper subtree — skip past it
- const prevPrefix = LIST_PREFIX.exec(prev.text);
- if (prevPrefix) target = prevPrefix[0].length;
- break;
- }
- if (target > indent) {
- changes.push({ from: line.from, to: line.to, insert: reindented(doc, n, line.text, target) });
- }
- }
- if (changes.length === 0) return false;
- view.dispatch({ changes, userEvent: "input.indent" });
- return true;
-}
-
-/**
- * Shift-Tab on a list item: outdent it to its parent's indent (or the margin),
- * renumbering ordered items for the new level. Returns false when not on an
- * indented list item so the default outdent applies.
- */
-export function liftListItem(view: EditorView): boolean {
- const { doc } = view.state;
- const changes: { from: number; to: number; insert: string }[] = [];
- for (const n of selectedLineNumbers(view)) {
- const line = doc.line(n);
- const match = LIST_ITEM.exec(line.text);
- if (!match) return false;
- const indent = match[1].length;
- if (indent === 0) return false;
- let target = 0;
- for (const prev of previousListLines(doc, n)) {
- if (prev.indent < indent) {
- target = LIST_ITEM.test(prev.text) ? prev.indent : 0;
- break;
- }
- }
- changes.push({ from: line.from, to: line.to, insert: reindented(doc, n, line.text, target) });
- }
- if (changes.length === 0) return false;
- view.dispatch({ changes, userEvent: "delete.dedent" });
- return true;
-}
diff --git a/web/src/components/MemoEditor/Editor/markdownTagRanges.ts b/web/src/components/MemoEditor/Editor/markdownTagRanges.ts
deleted file mode 100644
index f747278fe..000000000
--- a/web/src/components/MemoEditor/Editor/markdownTagRanges.ts
+++ /dev/null
@@ -1,337 +0,0 @@
-import { ensureSyntaxTree, syntaxTree, syntaxTreeAvailable } from "@codemirror/language";
-import type { EditorState } from "@codemirror/state";
-import { parser as markdownParser } from "@lezer/markdown";
-import { fromMarkdown } from "mdast-util-from-markdown";
-import { decodeString } from "micromark-util-decode-string";
-import { findMarkdownGFMEmailRanges, type GFMEmailSourceRange, type MarkdownSourceNode } from "@/utils/gfm-email";
-import { findMarkdownGFMURLRanges } from "@/utils/gfm-url";
-import {
- hasExactMarkdownRange,
- isValidMarkdownLinkReference,
- type MarkdownSourceRange,
- resolvedMarkdownLinkRanges,
-} from "@/utils/markdown-link";
-import { findDecodedMarkdownSourceBoundaries } from "@/utils/markdown-source-boundaries";
-import { memoMarkdownExtensions } from "@/utils/memo-markdown-extension";
-import { findMentionMatches, type MentionMatch } from "@/utils/mention-grammar";
-import { findTagMatches, type TagMatch } from "@/utils/tag-grammar";
-import { isUsernameCharacter } from "@/utils/username";
-
-interface SourceRange {
- from: number;
- to: number;
-}
-
-type MarkdownNode = MarkdownSourceNode;
-
-interface ParsedMarkdownContext {
- parsedTo: number;
- source: string;
- root: MarkdownNode;
- resolvedLinks: MarkdownSourceRange[];
- writtenURLRanges: MarkdownSourceRange[];
- emailRanges: GFMEmailSourceRange[];
- allowUnresolvedLinks: boolean;
-}
-
-const sourceParser = markdownParser.configure(memoMarkdownExtensions);
-const REFERENCE_LABEL_PREFIX = "x ";
-const REJECTED_URL_PREFIX = "x";
-const parsedContextCache = new WeakMap<EditorState, ParsedMarkdownContext>();
-let canonicalCodeCache: { source: string; ranges: SourceRange[] } | undefined;
-
-function parsedMarkdownRoot(state: EditorState, to: number): MarkdownNode {
- return (ensureSyntaxTree(state, to) ?? syntaxTree(state)).topNode as MarkdownNode;
-}
-
-function parsedMarkdownContext(state: EditorState, to: number): ParsedMarkdownContext {
- const cached = parsedContextCache.get(state);
- if (cached && cached.parsedTo >= to) return cached;
-
- const source = state.doc.toString();
- const root = parsedMarkdownRoot(state, to);
- const resolvedLinks = resolvedMarkdownLinkRanges(source, root);
- const allowUnresolvedLinks = syntaxTreeAvailable(state);
- const context = {
- parsedTo: to,
- source,
- root,
- resolvedLinks,
- writtenURLRanges: findMarkdownGFMURLRanges(source, root, resolvedLinks),
- emailRanges: findMarkdownGFMEmailRanges(source, root, resolvedLinks, allowUnresolvedLinks),
- allowUnresolvedLinks,
- };
- parsedContextCache.set(state, context);
- return context;
-}
-
-// Only these known textual containers expose their direct source gaps. Their
-// syntax children are boundaries: transparent children recurse, while links,
-// code, math, HTML syntax, escapes, entities, and future extension nodes are
-// opaque by default.
-const TEXT_CONTAINERS = new Set([
- "ATXHeading1",
- "ATXHeading2",
- "ATXHeading3",
- "ATXHeading4",
- "ATXHeading5",
- "ATXHeading6",
- "Emphasis",
- "Paragraph",
- "SetextHeading1",
- "SetextHeading2",
- "Strikethrough",
- "StrongEmphasis",
- "TableCell",
- "Task",
-]);
-
-const STRUCTURAL_CONTAINERS = new Set([
- "Blockquote",
- "BulletList",
- "Document",
- "ListItem",
- "OrderedList",
- "Table",
- "TableHeader",
- "TableRow",
-]);
-
-function addClampedRange(ranges: SourceRange[], from: number, to: number, lowerBound: number, upperBound: number): void {
- const clampedFrom = Math.max(from, lowerBound);
- const clampedTo = Math.min(to, upperBound);
- if (clampedFrom < clampedTo) ranges.push({ from: clampedFrom, to: clampedTo });
-}
-
-function collectUnresolvedReferenceLabelRanges(node: MarkdownNode, from: number, to: number, source: string, ranges: SourceRange[]): void {
- const contentFrom = node.from + 1;
- const contentTo = node.to - 1;
- if (contentFrom >= contentTo) return;
-
- // Lezer keeps an unresolved second label as one opaque LinkLabel node. Parse
- // its contents again as ordinary inline Markdown so emphasis, escapes, and
- // other syntax retain their normal boundaries after link resolution fails.
- const prefixedSource = REFERENCE_LABEL_PREFIX + source.slice(contentFrom, contentTo);
- const root = sourceParser.parse(prefixedSource).topNode as MarkdownNode;
- const resolvedLinks = resolvedMarkdownLinkRanges(prefixedSource, root);
- const writtenURLs = findMarkdownGFMURLRanges(prefixedSource, root, resolvedLinks, false).filter(
- (range) => range.from !== REFERENCE_LABEL_PREFIX.length,
- );
- const labelRanges: SourceRange[] = [];
- collectLiteralRanges(
- root,
- REFERENCE_LABEL_PREFIX.length,
- prefixedSource.length,
- prefixedSource,
- resolvedLinks,
- writtenURLs,
- true,
- labelRanges,
- );
- for (const range of labelRanges) {
- const offset = contentFrom - REFERENCE_LABEL_PREFIX.length;
- addClampedRange(ranges, range.from + offset, range.to + offset, from, to);
- }
-}
-
-function collectRejectedURLLiteralRanges(
- parent: MarkdownNode,
- node: MarkdownNode,
- from: number,
- to: number,
- source: string,
- ranges: SourceRange[],
-): void {
- const prefixedSource = REJECTED_URL_PREFIX + source.slice(node.from, node.to);
- const root = sourceParser.parse(prefixedSource).topNode as MarkdownNode;
- const resolvedLinks = resolvedMarkdownLinkRanges(prefixedSource, root);
- const urlRanges: SourceRange[] = [];
- collectLiteralRanges(
- root,
- REJECTED_URL_PREFIX.length,
- prefixedSource.length,
- prefixedSource,
- resolvedLinks,
- findMarkdownGFMURLRanges(prefixedSource, root, resolvedLinks, false),
- true,
- urlRanges,
- );
-
- const offset = node.from - REJECTED_URL_PREFIX.length;
- const projected = urlRanges.map((range) => ({ from: range.from + offset, to: range.to + offset }));
- const emphasisMarks: SourceRange[] = [];
- if (source.slice(node.from, node.to).includes("_") && source.slice(parent.from, node.from).includes("_")) {
- const insertion = node.from - parent.from;
- const contextualSource = source.slice(parent.from, node.from) + REJECTED_URL_PREFIX + source.slice(node.from, node.to);
- const contentFrom = insertion + REJECTED_URL_PREFIX.length;
- sourceParser.parse(contextualSource).iterate({
- enter(mark) {
- if (mark.name === "EmphasisMark" && mark.from >= contentFrom) {
- emphasisMarks.push({
- from: mark.from + parent.from - REJECTED_URL_PREFIX.length,
- to: mark.to + parent.from - REJECTED_URL_PREFIX.length,
- });
- }
- },
- });
- }
- for (const range of subtractRanges(projected, emphasisMarks)) {
- addClampedRange(ranges, range.from, range.to, from, to);
- }
-}
-
-function canonicalSourceKeepsCodeOpaque(source: string, node: MarkdownNode): boolean {
- if (canonicalCodeCache?.source !== source) {
- const ranges: SourceRange[] = [];
- const collectRanges = (candidate: unknown): void => {
- if (!candidate || typeof candidate !== "object") return;
- const value = candidate as {
- type?: string;
- position?: { start?: { offset?: number }; end?: { offset?: number } };
- children?: unknown[];
- };
- const from = value.position?.start?.offset;
- const to = value.position?.end?.offset;
- if (value.type === "code" && from !== undefined && to !== undefined) ranges.push({ from, to });
- value.children?.forEach(collectRanges);
- };
- collectRanges(fromMarkdown(source));
- canonicalCodeCache = { source, ranges };
- }
-
- return canonicalCodeCache.ranges.some((range) => range.from <= node.from && range.to >= node.to);
-}
-
-function collectReparsedLiteralRanges(node: MarkdownNode, from: number, to: number, source: string, ranges: SourceRange[]): void {
- const prefix = "x ";
- const prefixedSource = prefix + source.slice(node.from, node.to);
- const root = sourceParser.parse(prefixedSource).topNode as MarkdownNode;
- const resolvedLinks = resolvedMarkdownLinkRanges(prefixedSource, root);
- const reparsed: SourceRange[] = [];
- collectLiteralRanges(
- root,
- prefix.length,
- prefixedSource.length,
- prefixedSource,
- resolvedLinks,
- findMarkdownGFMURLRanges(prefixedSource, root, resolvedLinks, false),
- true,
- reparsed,
- );
- const offset = node.from - prefix.length;
- for (const range of reparsed) addClampedRange(ranges, range.from + offset, range.to + offset, from, to);
-}
-
-function collectLiteralRanges(
- node: MarkdownNode,
- from: number,
- to: number,
- source: string,
- resolvedLinks: MarkdownSourceRange[],
- writtenURLs: MarkdownSourceRange[],
- allowUnresolvedLinks: boolean,
- ranges: SourceRange[],
-): void {
- if (node.to <= from || node.from >= to) return;
-
- const unresolvedLinkLike =
- allowUnresolvedLinks && (node.name === "Link" || node.name === "Image") && !hasExactMarkdownRange(resolvedLinks, node);
- const invalidLinkReference = node.name === "LinkReference" && !isValidMarkdownLinkReference(source, node);
- const scansDirectText = TEXT_CONTAINERS.has(node.name) || unresolvedLinkLike || invalidLinkReference;
- if (!scansDirectText && !STRUCTURAL_CONTAINERS.has(node.name)) return;
-
- let cursor = node.from;
- for (let child = node.firstChild; child; child = child.nextSibling) {
- if (child.name === "Entity") {
- const spelling = source.slice(child.from, child.to);
- if (decodeString(spelling) === spelling) continue;
- }
- if (child.to <= cursor) continue;
- if (scansDirectText) addClampedRange(ranges, cursor, child.from, from, to);
- if (child.from >= cursor) {
- if (node.name === "Blockquote" && child.name === "CodeBlock" && !canonicalSourceKeepsCodeOpaque(source, child)) {
- collectReparsedLiteralRanges(child, from, to, source, ranges);
- } else if (invalidLinkReference && child.name === "LinkLabel") {
- collectUnresolvedReferenceLabelRanges(child, from, to, source, ranges);
- } else if (child.name === "URL") {
- if (!hasExactMarkdownRange(writtenURLs, child)) collectRejectedURLLiteralRanges(node, child, from, to, source, ranges);
- } else if (unresolvedLinkLike && child.name === "LinkLabel") {
- collectUnresolvedReferenceLabelRanges(child, from, to, source, ranges);
- } else {
- collectLiteralRanges(child, from, to, source, resolvedLinks, writtenURLs, allowUnresolvedLinks, ranges);
- }
- }
- cursor = Math.max(cursor, child.to);
- }
- if (scansDirectText) addClampedRange(ranges, cursor, node.to, from, to);
-}
-
-function subtractRanges(ranges: SourceRange[], opaqueRanges: SourceRange[]): SourceRange[] {
- return ranges.flatMap((range) => {
- const pieces: SourceRange[] = [];
- let cursor = range.from;
- for (const opaque of opaqueRanges) {
- if (opaque.to <= cursor || opaque.from >= range.to) continue;
- if (cursor < opaque.from) pieces.push({ from: cursor, to: Math.min(opaque.from, range.to) });
- cursor = Math.max(cursor, opaque.to);
- if (cursor >= range.to) break;
- }
- if (cursor < range.to) pieces.push({ from: cursor, to: range.to });
- return pieces;
- });
-}
-
-function mergeSourceRanges(ranges: SourceRange[]): SourceRange[] {
- const sorted = [...ranges].sort((left, right) => left.from - right.from || left.to - right.to);
- const merged: SourceRange[] = [];
- for (const range of sorted) {
- const previous = merged.at(-1);
- if (previous && range.from <= previous.to) previous.to = Math.max(previous.to, range.to);
- else merged.push({ ...range });
- }
- return merged;
-}
-
-export function literalMarkdownSourceRanges(state: EditorState, from: number, to: number): SourceRange[] {
- const ranges: SourceRange[] = [];
- const context = parsedMarkdownContext(state, to);
- collectLiteralRanges(
- context.root,
- from,
- to,
- context.source,
- context.resolvedLinks,
- context.writtenURLRanges,
- context.allowUnresolvedLinks,
- ranges,
- );
- const decodedBoundaries = findDecodedMarkdownSourceBoundaries(context.source, from, to);
- return mergeSourceRanges(
- subtractRanges(subtractRanges(subtractRanges(ranges, decodedBoundaries), context.emailRanges), context.writtenURLRanges),
- );
-}
-
-/** Find tags only in literal Markdown source exposed by the editor syntax tree. */
-export function findMarkdownTagMatches(state: EditorState, from: number, to: number): TagMatch[] {
- const matches: TagMatch[] = [];
- for (const range of literalMarkdownSourceRanges(state, from, to)) {
- const source = state.doc.sliceString(range.from, range.to);
- for (const match of findTagMatches(source)) {
- matches.push({ ...match, from: range.from + match.from, to: range.from + match.to });
- }
- }
- return matches;
-}
-
-/** Find username references only in literal Markdown source exposed by the editor syntax tree. */
-export function findMarkdownMentionMatches(state: EditorState, from: number, to: number): MentionMatch[] {
- const matches: MentionMatch[] = [];
- for (const range of literalMarkdownSourceRanges(state, from, to)) {
- const source = state.doc.sliceString(range.from, range.to);
- const runHasLeftBoundary = range.from === 0 || !isUsernameCharacter(state.doc.sliceString(range.from - 1, range.from));
- for (const match of findMentionMatches(source, runHasLeftBoundary)) {
- matches.push({ ...match, from: range.from + match.from, to: range.from + match.to });
- }
- }
- return matches;
-}
diff --git a/web/src/components/MemoEditor/Editor/tagAutocomplete.ts b/web/src/components/MemoEditor/Editor/tagAutocomplete.ts
deleted file mode 100644
index e5cafd90b..000000000
--- a/web/src/components/MemoEditor/Editor/tagAutocomplete.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { autocompletion, type CompletionContext, type CompletionResult } from "@codemirror/autocomplete";
-import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
-import type { Extension } from "@codemirror/state";
-import { findTagMatches, isTagIntroducerAt } from "@/utils/tag-grammar";
-
-/**
- * Ranks a candidate tag against the typed text (both already lower-cased).
- * Lower sorts first; `undefined` means the candidate does not match.
- *
- * Nested tags are paths, so a match inside the path counts: typing `mem` has to
- * reach `software/hosted/Memos`, which a full-path prefix test cannot do. The
- * tiers keep that from turning into noise — a segment start outranks an
- * incidental hit in the middle of a word.
- */
-const matchRank = (tag: string, typed: string): number | undefined => {
- const index = tag.indexOf(typed);
- if (index < 0) return undefined;
- if (index === 0) return 0; // Full-path prefix.
- if (tag[index - 1] === "/") return 1; // Path-segment start.
- return 2; // Anywhere else.
-};
-
-export function makeTagCompletionSource(getTags: () => string[]) {
- return (ctx: CompletionContext): CompletionResult | null => {
- // Completion is an input aid, including inside code, links, and escapes.
- // Keep tag spelling rules, but don't restrict candidates to rendered tags.
- const line = ctx.state.doc.lineAt(ctx.pos);
- const position = ctx.pos - line.from;
- const match = findTagMatches(line.text, 0, position).findLast(
- (candidate) => candidate.to === position || (candidate.to === position - 1 && line.text[position - 1] === "/"),
- );
- const bareIntroducer = isTagIntroducerAt(line.text, position - 1);
- if (!match && !bareIntroducer) return null;
-
- const from = match ? line.from + match.from + 1 : ctx.pos;
- if (!ctx.explicit) {
- const tree = ensureSyntaxTree(ctx.state, ctx.pos) ?? syntaxTree(ctx.state);
- const node = tree.resolveInner(from - 1, 1);
- // Only the opening heading marker is reserved. A later # in heading
- // text still offers tags, including a potential closing heading marker.
- if (node.name === "HeaderMark" && node.parent?.firstChild?.from === node.from) return null;
- }
-
- // A trailing slash is an unfinished child segment, not the end of input.
- const typed = (match ? match.value + (match.to < position ? "/" : "") : "").toLowerCase();
- const options = getTags()
- .map((tag) => ({ tag, rank: matchRank(tag.toLowerCase(), typed) }))
- .filter((candidate): candidate is { tag: string; rank: number } => candidate.rank !== undefined)
- // Stable sort, so tags keep their incoming order within a tier.
- .sort((a, b) => a.rank - b.rank)
- .map(({ tag }) => ({ label: tag, type: "keyword" }));
- if (options.length === 0) return null;
- // `filter: false` keeps this ranking: CodeMirror would otherwise re-filter
- // and re-score the options with its own fuzzy matcher.
- return { from, options, filter: false };
- };
-}
-
-export function tagAutocomplete(getTags: () => string[]): Extension {
- return autocompletion({
- override: [makeTagCompletionSource(getTags)],
- icons: false,
- });
-}
diff --git a/web/src/components/MemoEditor/Editor/tagMentionDecorations.ts b/web/src/components/MemoEditor/Editor/tagMentionDecorations.ts
deleted file mode 100644
index c4e5ea0ca..000000000
--- a/web/src/components/MemoEditor/Editor/tagMentionDecorations.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { RangeSetBuilder } from "@codemirror/state";
-import { Decoration, type DecorationSet, EditorView } from "@codemirror/view";
-import { findMarkdownMentionMatches, findMarkdownTagMatches } from "./markdownTagRanges";
-import { viewportDecorations } from "./viewportDecorations";
-
-const tagMark = Decoration.mark({ class: "cm-memo-tag" });
-const mentionMark = Decoration.mark({ class: "cm-memo-mention" });
-
-function build(view: EditorView): DecorationSet {
- const ranges: { from: number; to: number; deco: Decoration }[] = [];
- const visibleLines = view.visibleRanges
- .map(({ from, to }) => ({ from: view.state.doc.lineAt(from).from, to: view.state.doc.lineAt(to).to }))
- .sort((left, right) => left.from - right.from);
- const scanRanges: Array<{ from: number; to: number }> = [];
- for (const range of visibleLines) {
- const previous = scanRanges.at(-1);
- if (previous && range.from <= previous.to) previous.to = Math.max(previous.to, range.to);
- else scanRanges.push({ ...range });
- }
- for (const { from, to } of scanRanges) {
- for (const match of findMarkdownTagMatches(view.state, from, to)) {
- ranges.push({ from: match.from, to: match.to, deco: tagMark });
- }
-
- for (const match of findMarkdownMentionMatches(view.state, from, to)) {
- ranges.push({ from: match.from, to: match.to, deco: mentionMark });
- }
- }
- ranges.sort((a, b) => a.from - b.from || a.to - b.to);
- const builder = new RangeSetBuilder<Decoration>();
- for (const r of ranges) builder.add(r.from, r.to, r.deco);
- return builder.finish();
-}
-
-export const tagMentionDecorations = viewportDecorations(build);
diff --git a/web/src/components/MemoEditor/Editor/theme.ts b/web/src/components/MemoEditor/Editor/theme.ts
deleted file mode 100644
index 3b4e52ecd..000000000
--- a/web/src/components/MemoEditor/Editor/theme.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { syntaxHighlighting } from "@codemirror/language";
-import { tags as t, tagHighlighter } from "@lezer/highlight";
-
-/**
- * Map markdown syntax tokens to stable class names. ALL visual styling lives in
- * plain CSS (the `.memo-editor-content` block in `Editor/editor.css`) so the editor
- * is themed like the rest of the app — Tailwind/theme tokens in a stylesheet —
- * rather than a CodeMirror CSS-in-JS theme object. Headings (`.cm-md-h*`) and
- * `#tag`/`@mention` (`.cm-memo-*`) classes come from the decoration plugins;
- * the rest of the `.cm-*` chrome is CodeMirror's own and is styled in that CSS.
- */
-const markdownHighlighter = tagHighlighter([
- { tag: t.strong, class: "cm-md-strong" },
- { tag: t.emphasis, class: "cm-md-emphasis" },
- { tag: t.strikethrough, class: "cm-md-strike" },
- { tag: t.monospace, class: "cm-md-code" },
- { tag: t.link, class: "cm-md-link" },
- { tag: t.url, class: "cm-md-url" },
- { tag: t.quote, class: "cm-md-quote" },
- { tag: [t.processingInstruction, t.meta, t.contentSeparator], class: "cm-md-mark" },
-]);
-
-export const memoEditorTheme = [syntaxHighlighting(markdownHighlighter)];
diff --git a/web/src/components/MemoEditor/Editor/uploadAnchors.ts b/web/src/components/MemoEditor/Editor/uploadAnchors.ts
index 0a96e93c9..83172a36f 100644
--- a/web/src/components/MemoEditor/Editor/uploadAnchors.ts
+++ b/web/src/components/MemoEditor/Editor/uploadAnchors.ts
@@ -1,5 +1,4 @@
-import { type EditorState, StateEffect, StateField } from "@codemirror/state";
-import { Decoration, type DecorationSet, EditorView, WidgetType } from "@codemirror/view";
+import type { WidgetRender } from "@usememos/editor";
export type UploadAnchorStatus = "uploading" | "failed";
@@ -15,144 +14,49 @@ export interface UploadAnchorDescriptor {
onKeepAttachments?: () => void;
}
-const addUploadAnchor = StateEffect.define<{ position: number; descriptor: UploadAnchorDescriptor }>();
-const updateUploadAnchor = StateEffect.define<UploadAnchorDescriptor>();
-const removeUploadAnchor = StateEffect.define<string>();
-
-class UploadAnchorWidget extends WidgetType {
- constructor(readonly descriptor: UploadAnchorDescriptor) {
- super();
- }
-
- // Every field below is rendered by toDOM — the labels as text, the callbacks as
- // click listeners baked into the reused element — so all of them have to take
- // part in the comparison. Returning true for a descriptor that differs only in
- // its callbacks would leave the previous handlers wired to the old DOM.
- eq(other: UploadAnchorWidget): boolean {
- const [a, b] = [this.descriptor, other.descriptor];
- return (
- a.id === b.id &&
- a.status === b.status &&
- a.completed === b.completed &&
- a.total === b.total &&
- a.message === b.message &&
- a.retryLabel === b.retryLabel &&
- a.keepLabel === b.keepLabel &&
- a.onRetry === b.onRetry &&
- a.onKeepAttachments === b.onKeepAttachments
- );
- }
+const actionButton = (label: string, onClick: () => void): HTMLButtonElement => {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "memo-upload-anchor-action";
+ button.textContent = label;
+ button.addEventListener("click", onClick);
+ return button;
+};
- toDOM(): HTMLElement {
- const root = document.createElement("div");
- root.className = "cm-upload-anchor";
- root.dataset.status = this.descriptor.status;
- root.setAttribute("role", "status");
- root.setAttribute("aria-live", "polite");
+/**
+ * Renders an upload anchor into an editor widget: a rail and a badge holding
+ * the progress or failure message, plus Retry / Keep actions once it failed.
+ * The widget sits after the block the upload was started in; it is never saved
+ * and is not part of undo history.
+ */
+export const renderUploadAnchor =
+ (descriptor: UploadAnchorDescriptor): WidgetRender =>
+ (element) => {
+ element.className = "memo-upload-anchor";
+ element.dataset.status = descriptor.status;
+ element.setAttribute("role", "status");
+ element.setAttribute("aria-live", "polite");
+ element.replaceChildren();
const rail = document.createElement("span");
- rail.className = "cm-upload-anchor-rail";
- root.appendChild(rail);
+ rail.className = "memo-upload-anchor-rail";
const badge = document.createElement("span");
- badge.className = "cm-upload-anchor-badge";
- if (this.descriptor.status === "uploading") {
+ badge.className = "memo-upload-anchor-badge";
+ if (descriptor.status === "uploading") {
const spinner = document.createElement("span");
- spinner.className = "cm-upload-anchor-spinner";
+ spinner.className = "memo-upload-anchor-spinner";
spinner.setAttribute("aria-hidden", "true");
badge.appendChild(spinner);
- badge.append(this.descriptor.message);
- } else {
- badge.append(this.descriptor.message);
}
- root.appendChild(badge);
+ badge.append(descriptor.message);
+ element.append(rail, badge);
- if (this.descriptor.status === "failed") {
+ if (descriptor.status === "failed") {
const actions = document.createElement("span");
- actions.className = "cm-upload-anchor-actions";
- if (this.descriptor.onRetry) {
- const retry = document.createElement("button");
- retry.type = "button";
- retry.className = "cm-upload-anchor-action";
- retry.textContent = this.descriptor.retryLabel;
- retry.addEventListener("click", this.descriptor.onRetry);
- actions.appendChild(retry);
- }
- if (this.descriptor.onKeepAttachments) {
- const keep = document.createElement("button");
- keep.type = "button";
- keep.className = "cm-upload-anchor-action";
- keep.textContent = this.descriptor.keepLabel;
- keep.addEventListener("click", this.descriptor.onKeepAttachments);
- actions.appendChild(keep);
- }
- root.appendChild(actions);
- }
-
- return root;
- }
-
- ignoreEvent(): boolean {
- return true;
- }
-}
-
-const anchorIdOf = (value: Decoration): string | undefined =>
- value.spec.widget instanceof UploadAnchorWidget ? value.spec.widget.descriptor.id : undefined;
-
-const findAnchorPosition = (decorations: DecorationSet, id: string): number | undefined => {
- let position: number | undefined;
- decorations.between(0, Number.MAX_SAFE_INTEGER, (from, _to, value) => {
- if (anchorIdOf(value) === id) {
- position = from;
- }
- });
- return position;
-};
-
-export const uploadAnchorField = StateField.define<DecorationSet>({
- create: () => Decoration.none,
- update: (anchors, transaction) => {
- let next = anchors.map(transaction.changes);
- for (const effect of transaction.effects) {
- if (effect.is(addUploadAnchor)) {
- const position = Math.min(Math.max(effect.value.position, 0), transaction.state.doc.length);
- next = next.update({
- add: [Decoration.widget({ widget: new UploadAnchorWidget(effect.value.descriptor), side: 1, block: true }).range(position)],
- sort: true,
- });
- } else if (effect.is(updateUploadAnchor)) {
- const position = findAnchorPosition(next, effect.value.id);
- if (position === undefined) continue;
- next = next.update({
- filter: (_from, _to, value) => anchorIdOf(value) !== effect.value.id,
- add: [Decoration.widget({ widget: new UploadAnchorWidget(effect.value), side: 1, block: true }).range(position)],
- sort: true,
- });
- } else if (effect.is(removeUploadAnchor)) {
- next = next.update({
- filter: (_from, _to, value) => anchorIdOf(value) !== effect.value,
- });
- }
+ actions.className = "memo-upload-anchor-actions";
+ if (descriptor.onRetry) actions.appendChild(actionButton(descriptor.retryLabel, descriptor.onRetry));
+ if (descriptor.onKeepAttachments) actions.appendChild(actionButton(descriptor.keepLabel, descriptor.onKeepAttachments));
+ element.appendChild(actions);
}
- return next;
- },
- provide: (field) => EditorView.decorations.from(field),
-});
-
-export const createUploadAnchor = (view: EditorView, descriptor: UploadAnchorDescriptor, position?: number): void => {
- view.dispatch({ effects: addUploadAnchor.of({ position: position ?? view.state.selection.main.head, descriptor }) });
-};
-
-export const setUploadAnchor = (view: EditorView, descriptor: UploadAnchorDescriptor): void => {
- view.dispatch({ effects: updateUploadAnchor.of(descriptor) });
-};
-
-export const cancelUploadAnchor = (view: EditorView, id: string): void => {
- view.dispatch({ effects: removeUploadAnchor.of(id) });
-};
-
-export const getUploadAnchorPosition = (state: EditorState, id: string): number | undefined =>
- findAnchorPosition(state.field(uploadAnchorField, false) ?? Decoration.none, id);
-
-export const removeUploadAnchorEffect = (id: string): StateEffect<string> => removeUploadAnchor.of(id);
+ };
diff --git a/web/src/components/MemoEditor/Editor/viewportDecorations.ts b/web/src/components/MemoEditor/Editor/viewportDecorations.ts
deleted file mode 100644
index fbfee50e2..000000000
--- a/web/src/components/MemoEditor/Editor/viewportDecorations.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { syntaxTree } from "@codemirror/language";
-import { type DecorationSet, EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
-
-/**
- * A ViewPlugin that maintains viewport-scoped decorations, rebuilding when the
- * document or viewport changes. Shared by the tag/mention and heading
- * decoration plugins, which differ only in their `build` function.
- */
-export function viewportDecorations(build: (view: EditorView) => DecorationSet) {
- return ViewPlugin.fromClass(
- class {
- decorations: DecorationSet;
- constructor(view: EditorView) {
- this.decorations = build(view);
- }
- update(u: ViewUpdate) {
- if (u.docChanged || u.viewportChanged || syntaxTree(u.startState) !== syntaxTree(u.state)) {
- this.decorations = build(u.view);
- }
- }
- },
- { decorations: (v) => v.decorations },
- );
-}
diff --git a/web/src/components/MemoEditor/README.md b/web/src/components/MemoEditor/README.md
index 934f21698..623f1e71a 100644
--- a/web/src/components/MemoEditor/README.md
+++ b/web/src/components/MemoEditor/README.md
@@ -2,7 +2,7 @@
## Overview
-MemoEditor is a three-layer component. At its core is a single editor — `Editor/`, a CodeMirror 6 "decorated source" editor. It stores the memo as **raw markdown, verbatim** (no parse/serialize round-trip) and styles that source in place with CodeMirror decorations: the markers (`#`, `*`, `` ` ``, list bullets, fences) stay visible but de-emphasized while the styled text leads. There is one editor and one storage format; everything above the editor boundary talks markdown through the `EditorController` contract.
+MemoEditor is a three-layer component. At its core is a single editor — `Editor/`, built on [`@usememos/editor`](https://github.com/usememos/editor), a block editor whose storage format is standard Markdown. Markdown goes in and comes out: blocks the user did not edit are saved byte for byte, and edited blocks are written in a normalized style. The memo view (`components/MemoContent`) is the same editor, read-only, so a memo looks the same while editing and after saving. Everything above the editor boundary talks markdown through the `EditorController` contract.
## Architecture
@@ -42,23 +42,15 @@ MemoEditor/
├── hooks/ # React hooks (utilities)
│ ├── useMemoSave.ts # Save transaction, cache invalidation, and reset
│ └── useFocusMode.ts # Scroll lock and layout-stable focus presentation
-├── Editor/ # The CodeMirror 6 decorated-source editor
-│ ├── index.tsx # React wrapper: mounts the EditorView, owns the
-│ │ # controller refs, syncs initialContent in/out
-│ ├── extensions.ts # buildEditorExtensions(): assembles the CM extension set
-│ ├── theme.ts # Syntax-highlight style + editor theme (CSS-var colors)
-│ ├── tagMentionDecorations.ts# ViewPlugin that decorates #tag / @mention spans
-│ ├── markdownTagRanges.ts # Markdown syntax-tree adapter for the shared tag scanner
-│ ├── tagAutocomplete.ts # CM autocompletion source for #tag
-│ ├── uploadAnchors.ts # Widget decorations holding a slot per in-flight upload
-│ ├── formatting.ts # FormattingController impl (toggle marks, headings, lists)
-│ ├── controller.ts # EditorController impl over an EditorView
-│ └── ... # Heading/list/viewport decorations, editor.css
-├── formatting/
-│ └── commands.ts # Backend-agnostic catalog of formatting verbs
-├── Toolbar/ # EditorToolbar, FormattingToolbar, InsertMenu, AudienceMenu
+├── Editor/ # The composer, on @usememos/editor
+│ ├── index.tsx # React wrapper around <MarkdownEditor>; hands out the controller
+│ ├── extensions.ts # buildEditorExtensions(): memo syntax, #tag autocomplete, file paste/drop
+│ ├── uploadAnchors.ts # Widget rendering for in-flight upload placeholders
+│ ├── controller.ts # EditorController over the editor
+│ └── editor.css # Composer sizing and upload-anchor styles
+├── Toolbar/ # EditorToolbar, InsertMenu, AudienceMenu
├── constants.ts
-└── types/ # EditorController / FormattingController, component props,
+└── types/ # EditorController, component props,
# attachment and insert-menu types
```
@@ -72,34 +64,27 @@ A reducer (`state/reducer.ts`) drives an **external store**, not a `useReducer`
### The editor contract
-`types/editorController.ts` defines `EditorController` — document access (`getMarkdown`, `setMarkdown`, `insertMarkdown`), cursor and focus (`focus`, `hasFocus`, `isEmpty`, `getCursor`, `setCursor`, `scrollToCursor`, `selectAll`), the upload-anchor group below, plus an optional `formatting` capability. Callers outside the editor implementation use this interface exclusively and never reach into CodeMirror internals.
+`types/editorController.ts` defines `EditorController` — document access (`getMarkdown`, `setMarkdown`, `insertMarkdown`), selection and focus (`focus`, `hasFocus`, `isEmpty`, `getSelection`, `setSelection`, `selectAll`), the upload-anchor group below, and `toggleTaskList`. Callers outside the editor implementation use this interface exclusively and never reach into the editor's own API.
-`Editor/controller.ts` implements `EditorController` over a CodeMirror `EditorView`: `getMarkdown` is just `view.state.doc.toString()`, `setMarkdown` replaces the whole document, and `insertMarkdown` block-pads the insertion so it lands as its own block.
+`Editor/controller.ts` implements `EditorController` over the editor instance. Every method reads the live editor when called, so calls before mount or after destroy do nothing. `insertMarkdown` inserts after the caret's block (or in place of an empty paragraph) without consuming selected text. Selections are the editor's `SelectionJSON` (block index and offset), which survives remounting the same Markdown, so `cacheService` can restore the caret.
-`createUploadAnchor`/`updateUploadAnchor`/`resolveUploadAnchor`/`cancelUploadAnchor` drive `Editor/uploadAnchors.ts`, a `StateField` of widget decorations that hold a place in the document while an attachment uploads and carry its progress, failure message, and retry/keep affordances. `resolveUploadAnchor` replaces the anchor with the finished markdown (block-padded the same way `insertMarkdown` is); resolving with empty markdown cancels instead, as does `cancelUploadAnchor`.
+`createUploadAnchor`/`updateUploadAnchor`/`resolveUploadAnchor`/`cancelUploadAnchor` drive editor widgets (`editor.addWidget`) that hold a place after a block while an attachment uploads and carry its progress, failure message, and retry/keep affordances. Widgets are never saved and are not part of undo history. `resolveUploadAnchor` inserts the finished markdown after the widget's block; resolving with empty markdown cancels instead, as does `cancelUploadAnchor`.
-`FormattingController` (same file in `types/`) is the rich-formatting surface the focus-mode `FormattingToolbar` drives: `run(commandId, ctx?)`, `getActiveFormats()`, and `subscribe(listener)`. `Editor/formatting.ts` implements it by editing the markdown source directly — toggling inline marks (`**` and `*`) and single-backtick code delimiters, line prefixes (`-`, `1.`, and `- [ ]`, each followed by a space), and ATX heading prefixes (`#`…) — and by reading active state from the Lezer syntax tree at the caret.
+### Formatting
-### Formatting command catalog
-
-`formatting/commands.ts` is the single, editor-agnostic catalog of formatting verbs (`EDITOR_COMMANDS`, `EditorCommandId`, `ActiveFormatState`, `isCommandActive`). It is metadata only — labels (i18n keys), icons, and grouping — with no dependency on any concrete editor. The toolbar and the active-state highlighting derive everything from this catalog; `Editor/formatting.ts` supplies how each verb is applied to the live CodeMirror document. To add a verb, add one entry here (and its field on `ActiveFormatState`).
+Formatting is the editor's own: its toolbar appears over selected text (bold, italic, strikethrough, code, link), the slash menu and Markdown shortcuts change block types, and its keys cover the rest. Memos adds no formatting toolbar. The one formatting call memos makes itself is `toggleTaskList()`, for the checklist suggestion chip.
### Editor extensions
-`Editor/extensions.ts` exports `buildEditorExtensions()`, which composes the CodeMirror extension set: `@codemirror/lang-markdown` (with GFM), line wrapping, a reconfigurable placeholder, the editor theme, the `#tag`/`@mention` decoration plugin, the `#tag` autocomplete, and an update listener that pushes document changes back to the reducer via `onChange`. It also binds the save shortcut: `Meta-Enter` and `Ctrl-Enter` both call `onSubmit`, bound explicitly rather than through the platform-dependent `Mod-` so either works everywhere, and ordered ahead of `defaultKeymap`'s own `Mod-Enter` (`insertBlankLine`) so saving never also edits the document. Native CodeMirror paste/drop handlers intercept file payloads before its text insertion behavior: pasted files join the attachment list (a paste carries no placement gesture, so it never writes into the text), while dropped images are inserted inline at the drop point and other dropped files are attached. Ordinary markdown text paste/drop remains CodeMirror-owned.
+`lib/memo-markdown.ts` holds what the composer and the memo view share: the memo Markdown dialect (`breaks: true`, `setext: false`); `memoExtensions()` (math rendered with KaTeX loaded on demand, footnotes, `#tags` and `@mentions`, code highlighted with highlight.js, ```` ```mermaid ```` diagrams, and raw HTML through the sanitizer in `lib/sanitized-html.ts`); the URL policy for links and images (`memoResolveUrl`); the theme in the app's CSS variables; the translated UI labels; and the tag and mention collectors. Whatever the editor renders shows its source at the caret while editing.
-The app formatting keymap sits ahead of CodeMirror's generic `defaultKeymap`: `Mod-B`/`Mod-I` toggle bold/italic, `Mod-Shift-S` toggles strikethrough, `Mod-E` toggles inline code, `Mod-Alt-C` toggles a code block, `Mod-Alt-0` restores paragraph text, `Mod-Alt-1` through `Mod-Alt-3` select heading levels, and `Mod-Shift-7` through `Mod-Shift-9` toggle ordered, bullet, and task lists. CodeMirror's Markdown keymap remains enabled separately for structural `Enter` and `Backspace` behavior.
+`Editor/extensions.ts` adds what only the composer needs: the `#tag` autocomplete (`suggestion()` with `matchToken(scanTags)`, so the popup opens exactly where tags are highlighted; not inside code or links, and not for a bare `#` at the start of a line, which may be a heading) with items from `useTagCounts`, and a `fileHandler()`: pasted files join the attachment list, dropped images are inserted inline where they land and other dropped files are attached.
-`Editor/theme.ts` defines the decorated-source look: a `HighlightStyle` over the Lezer markdown highlight tags (headings, strong, emphasis, code, links, quotes, markers) and an `EditorView.theme`. Colors come from CSS custom properties so light/dark themes just work. This is the editor's own styling — the read-only memo view styles itself separately via `@/lib/markdownStyles`.
+Keys are the editor's own (see its README): Mod+B/I/E, Mod+Shift+S, Mod+Alt+0–3, Mod+Alt+C, Mod+Shift+7–9, Tab/Shift+Tab, and Mod+Enter / Ctrl+Enter to save. The first Escape selects the caret's block; a second Escape leaves the editor.
### Tags and mentions
-`#tag` autocomplete, decoration, and read-only rendering all use the shared scanner in `@/utils/tag-grammar`. The scanner owns tag syntax and Unicode/emoji recognition; each surface supplies only its Markdown context:
-
-- `Editor/markdownTagRanges.ts` adapts the CodeMirror syntax tree into literal-source ranges, excluding links, code, math, raw HTML syntax, escapes, and entities before calling the shared scanner.
-- `Editor/tagMentionDecorations.ts` decorates the tag matches returned by that adapter; mention recognition remains separate.
-- `Editor/tagAutocomplete.ts` scans the raw input at the cursor and offers known tags from `useTagCounts`, including inside code, links, and escapes. Bare `#` offers all tags except at an opening heading marker (manual completion still works there). Nested paths match by prefix, path segment, or substring, including an unfinished child after `/`.
-- `@/utils/remark-plugins/remark-tag` is the read-only renderer's Markdown AST adapter to the same scanner.
+Highlighting, autocomplete, `EditorController.getTags()` and the memo view all use the editor's scanners (`scanTags`, `scanMentions`), which skip code, links, images and extension tokens, so what is highlighted is what counts. `extractMentionUsernames` in `lib/memo-markdown.ts` reads mentions the same way to decide which users to resolve.
### Services
@@ -133,10 +118,10 @@ eligibility/application in `EditorSuggestions`.
Every instance is one of two things, and `onFocusModeExit` is the switch:
-- **Inline** (prop omitted) — the editor sits in page flow (Home composer, memo edit, comments) and owns its presentation. The + menu offers the view toggles: focus mode expands the editor over the page and the formatting toolbar's trailing button minimizes it back in place, while the formatting-toolbar preference governs the normal-mode layout.
-- **Hosted** (prop supplied) — a host presents the editor full-screen and owns that frame; `contexts/GlobalMemoEditorContext.tsx` is the one today. The editor mounts straight into focus mode and exits by calling back to dismiss the host, so the formatting toolbar's trailing button reads as Close rather than minimize. The + menu's view toggles are absent: focus mode is not the editor's to leave, and it already forces the formatting toolbar on.
+- **Inline** (prop omitted) — the editor sits in page flow (Home composer, memo edit, comments) and owns its presentation. The + menu offers focus mode, which expands the editor over the page; the exit button in its top row minimizes it back in place.
+- **Hosted** (prop supplied) — a host presents the editor full-screen and owns that frame; `contexts/GlobalMemoEditorContext.tsx` is the one today. The editor mounts straight into focus mode and exits by calling back to dismiss the host, so the exit button reads as Close rather than minimize. The + menu's view toggle is absent: focus mode is not the editor's to leave.
-Those toggles travel as a single optional `viewToggles` object (`types/components.ts`) down `EditorToolbar` → `InsertMenu`, so they can only appear or disappear together.
+The toggle travels as an optional `viewToggles` object (`types/components.ts`) down `EditorToolbar` → `InsertMenu`.
### Destination and visibility
diff --git a/web/src/components/MemoEditor/Toolbar/FormattingToolbar.tsx b/web/src/components/MemoEditor/Toolbar/FormattingToolbar.tsx
deleted file mode 100644
index aee4932e7..000000000
--- a/web/src/components/MemoEditor/Toolbar/FormattingToolbar.tsx
+++ /dev/null
@@ -1,172 +0,0 @@
-import {
- Heading1Icon,
- Heading2Icon,
- Heading3Icon,
- type LucideIcon,
- Minimize2Icon,
- MoreHorizontalIcon,
- TypeIcon,
- XIcon,
-} from "lucide-react";
-import { type ComponentPropsWithoutRef, forwardRef, type MouseEventHandler, type RefObject, useRef } from "react";
-import { Button } from "@/components/ui/button";
-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
-import { cn } from "@/lib/utils";
-import { useTranslate } from "@/utils/i18n";
-import {
- EDITOR_COMMANDS,
- type EditorCommand,
- type EditorCommandId,
- isCommandActive,
- type ToolbarHeadingLevel,
-} from "../formatting/commands";
-import { isCompactWidth, useEditorActiveState, useElementWidth } from "../hooks";
-import type { EditorController } from "../types";
-
-interface FormattingToolbarProps {
- controllerRef: RefObject<EditorController | null>;
- /**
- * Trailing dismiss button for the frame the editor sits in: "minimize" collapses
- * focus mode back into the page, "close" dismisses a host-owned frame. Omitted on
- * the inline normal-mode toolbar, which has no frame to leave.
- */
- exit?: { action: "minimize" | "close"; onExit: () => void };
- /** Extra classes for the host to frame the toolbar row. */
- className?: string;
-}
-
-const MARK_COMMANDS = EDITOR_COMMANDS.filter((command) => command.group === "mark");
-const BLOCK_COMMANDS = EDITOR_COMMANDS.filter((command) => command.group === "block");
-// Paragraph + headings render as a single icon dropdown (a closed set); the
-// trigger glyph reflects the current block level.
-const HEADING_COMMANDS = EDITOR_COMMANDS.filter((command) => command.group === "heading");
-const HEADING_LEVEL_ICONS: Record<ToolbarHeadingLevel, LucideIcon> = { 1: Heading1Icon, 2: Heading2Icon, 3: Heading3Icon };
-
-interface ToolbarButton {
- Icon?: LucideIcon;
- label: string;
- active: boolean;
- onClick: () => void;
-}
-
-// Command buttons must not take focus on mousedown — that blurs the editor and
-// drops the selection the command targets. The click still fires and applies the
-// format to the live selection.
-const preventFocusSteal: MouseEventHandler<HTMLButtonElement> = (event) => event.preventDefault();
-
-/**
- * Formatting toolbar: a lean inline row of the heading picker plus mark/block
- * controls, every one derived from the shared command catalog
- * (formatting/commands.ts), so adding a verb there surfaces it here automatically.
- * Groups are separated by thin vertical dividers. Responsive: below
- * COMPACT_TOOLBAR_WIDTH the block controls fold into a "more" menu while marks
- * stay inline. When the editor sits in a frame, the button that dismisses it is
- * pushed to the far edge.
- */
-export function FormattingToolbar({ controllerRef, exit, className }: FormattingToolbarProps) {
- const t = useTranslate();
- const rootRef = useRef<HTMLDivElement>(null);
- const width = useElementWidth(rootRef);
- const compact = isCompactWidth(width);
- const active = useEditorActiveState(controllerRef);
-
- const run = (id: EditorCommandId) => controllerRef.current?.formatting?.run(id);
-
- // Menus grab focus while open and hand it back to their trigger on close; send
- // it to the editor instead so the user can keep typing after a pick.
- const returnFocusToEditor = () => {
- controllerRef.current?.focus();
- return false;
- };
-
- // Map a catalog command to a toolbar button.
- const toButton = (command: EditorCommand): ToolbarButton => ({
- Icon: command.icon,
- label: t(command.labelKey),
- active: isCommandActive(active, command.id),
- onClick: () => run(command.id),
- });
-
- // Type glyph for paragraph, else the matching Hn glyph. Deeper levels (H4–H6)
- // aren't toolbar-addressable and report as null, i.e. the Type glyph.
- const HeadingGlyph = active.headingLevel === null ? TypeIcon : HEADING_LEVEL_ICONS[active.headingLevel];
- const ExitIcon = exit?.action === "close" ? XIcon : Minimize2Icon;
- const exitLabel = exit && t(exit.action === "close" ? "common.close" : "editor.exit-focus-mode");
- const markButtons = MARK_COMMANDS.map(toButton);
- const blockButtons = BLOCK_COMMANDS.map(toButton);
-
- return (
- <div
- ref={rootRef}
- className={cn("w-full flex flex-row items-center gap-0.5", className)}
- role="toolbar"
- aria-label={t("editor.format.heading")}
- >
- <DropdownMenu>
- <DropdownMenuTrigger render={<SegmentButton Icon={HeadingGlyph} label={t("editor.format.heading")} />} />
- <DropdownMenuContent align="start" size="sm" finalFocus={returnFocusToEditor}>
- {HEADING_COMMANDS.map((command) => (
- <DropdownMenuItem key={command.id} onClick={() => run(command.id)}>
- {t(command.labelKey)}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
-
- <Divider />
-
- {markButtons.map((button) => (
- <SegmentButton key={button.label} {...button} onMouseDown={preventFocusSteal} />
- ))}
-
- <Divider />
-
- {compact ? (
- <DropdownMenu>
- <DropdownMenuTrigger render={<SegmentButton Icon={MoreHorizontalIcon} label={t("editor.format.more")} />} />
- <DropdownMenuContent align="start" size="sm" finalFocus={returnFocusToEditor}>
- {blockButtons.map((button) => (
- <DropdownMenuItem key={button.label} onClick={button.onClick}>
- {button.label}
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- ) : (
- blockButtons.map((button) => <SegmentButton key={button.label} {...button} onMouseDown={preventFocusSteal} />)
- )}
-
- {exit && (
- <>
- <div className="flex-1" />
- <Button variant="quiet" size="icon-compact" aria-label={exitLabel} title={exitLabel} onClick={exit.onExit}>
- <ExitIcon className="size-4" strokeWidth={1.8} />
- </Button>
- </>
- )}
- </div>
- );
-}
-
-// Thin vertical rule between command groups (heading · marks · blocks).
-function Divider() {
- return <span aria-hidden="true" className="mx-1 h-4 w-px shrink-0 bg-border/70" />;
-}
-
-interface SegmentButtonProps extends ComponentPropsWithoutRef<"button"> {
- Icon?: LucideIcon;
- label: string;
- /** Toggle state; when set the segment gets aria-pressed and the active fill. */
- active?: boolean;
-}
-
-// The one segment element, shared by command toggles and dropdown triggers: the kit's
-// quiet 28px square, so the toolbar container stays transparent and only the verb that
-// is on carries the accent fill. Forwards ref + rest props so it also works as a Base UI
-// `render` trigger (which injects its own onClick/aria attributes).
-const SegmentButton = forwardRef<HTMLButtonElement, SegmentButtonProps>(({ Icon, label, active, ...rest }, ref) => (
- <Button ref={ref} variant="quiet" size="icon-compact" aria-label={label} aria-pressed={active} title={label} {...rest}>
- {Icon && <Icon className="size-4" strokeWidth={1.8} />}
- </Button>
-));
-SegmentButton.displayName = "SegmentButton";
diff --git a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
index 58609bfdb..e1340f23e 100644
--- a/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
+++ b/web/src/components/MemoEditor/Toolbar/InsertMenu.tsx
@@ -1,16 +1,5 @@
import { uniqBy } from "lodash-es";
-import {
- CheckIcon,
- ImageIcon,
- LinkIcon,
- LoaderIcon,
- MapPinIcon,
- Maximize2Icon,
- MicIcon,
- PaperclipIcon,
- PlusIcon,
- TypeIcon,
-} from "lucide-react";
+import { ImageIcon, LinkIcon, LoaderIcon, 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";
@@ -168,8 +157,7 @@ const InsertMenu = (props: InsertMenuProps) => {
{item.label}
</DropdownMenuItem>
))}
- {/* View toggles: focus mode + formatting-toolbar visibility. Absent
- when a host owns the editor's presentation — neither applies there. */}
+ {/* View toggle: focus mode. Absent when a host owns the editor's presentation. */}
{viewToggles && (
<>
<DropdownMenuSeparator />
@@ -177,11 +165,6 @@ const InsertMenu = (props: InsertMenuProps) => {
<Maximize2Icon />
{t("editor.focus-mode")}
</DropdownMenuItem>
- <DropdownMenuItem onClick={viewToggles.onToggleFormattingToolbar}>
- <TypeIcon />
- {t("editor.formatting-toolbar")}
- {viewToggles.isFormattingToolbarVisible && <CheckIcon className="ms-auto size-3.5" />}
- </DropdownMenuItem>
</>
)}
</DropdownMenuContent>
diff --git a/web/src/components/MemoEditor/Toolbar/index.ts b/web/src/components/MemoEditor/Toolbar/index.ts
index 334926092..02236e6fa 100644
--- a/web/src/components/MemoEditor/Toolbar/index.ts
+++ b/web/src/components/MemoEditor/Toolbar/index.ts
@@ -2,5 +2,4 @@
export { default as AudienceMenu } from "./AudienceMenu";
export { EditorToolbar } from "./EditorToolbar";
-export { FormattingToolbar } from "./FormattingToolbar";
export { default as InsertMenu } from "./InsertMenu";
diff --git a/web/src/components/MemoEditor/components/EditorContent.tsx b/web/src/components/MemoEditor/components/EditorContent.tsx
index ea4fa05d1..606a6195b 100644
--- a/web/src/components/MemoEditor/components/EditorContent.tsx
+++ b/web/src/components/MemoEditor/components/EditorContent.tsx
@@ -6,39 +6,34 @@ import type { EditorController } from "../types/editorController";
// Imported eagerly (not React.lazy): the editor is the always-present compose
// box on the home route, which is already code-split — so deferring the
-// CodeMirror bundle separately bought nothing and made the editor paint empty
+// editor bundle separately bought nothing and made the editor paint empty
// for a beat before its placeholder appeared (a visible flicker on load).
/**
- * Hosts the CodeMirror Editor behind the EditorController contract. The
- * editor serializes into state.content on every change and exposes its
- * formatting capability for the focus-mode toolbar.
+ * Hosts the Markdown Editor behind the EditorController contract. The
+ * editor writes into state.content on every change.
*/
-export const EditorContent = forwardRef<EditorController, EditorContentProps>(({ placeholder, onSubmit, onFiles }, ref) => {
+export const EditorContent = forwardRef<EditorController, EditorContentProps>(({ placeholder, onSubmit, onFiles, tagsSetting }, ref) => {
const { actions, dispatch } = useEditorContext();
const content = useEditorSelector((s) => s.content);
- const contentSource = useEditorSelector((s) => s.contentSource);
const isFocusMode = useEditorSelector((s) => s.ui.isFocusMode);
+ const attachments = useEditorSelector((s) => s.metadata.attachments);
const handleContentChange = (content: string) => {
dispatch(actions.updateContent(content));
};
- const handleExternalContentApplied = (content: string) => {
- dispatch(actions.setContent(content));
- };
-
return (
<div className="w-full flex flex-col flex-1">
<Editor
ref={ref}
className="memo-editor-content"
- initialContent={content}
- contentIsExternal={contentSource === "external"}
+ value={content}
placeholder={placeholder || ""}
isFocusMode={isFocusMode}
+ attachments={attachments}
+ tagsSetting={tagsSetting}
onContentChange={handleContentChange}
- onExternalContentApplied={handleExternalContentApplied}
onFiles={onFiles}
onSubmit={onSubmit}
/>
diff --git a/web/src/components/MemoEditor/components/EditorSuggestions.tsx b/web/src/components/MemoEditor/components/EditorSuggestions.tsx
index fb54b744c..6e38a97ec 100644
--- a/web/src/components/MemoEditor/components/EditorSuggestions.tsx
+++ b/web/src/components/MemoEditor/components/EditorSuggestions.tsx
@@ -1,6 +1,6 @@
import { isEqual } from "lodash-es";
import { ListTodoIcon, ZapIcon } from "lucide-react";
-import { type RefObject, useId, useLayoutEffect, useState } from "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";
@@ -70,9 +70,9 @@ export function EditorSuggestions({
const [hasChecklist, setHasChecklist] = useState(false);
const needsTags = suggestions.some((suggestion) => suggestion.kind === "tag");
const needsChecklist = suggestions.some((suggestion) => suggestion.kind === "checklist");
- // Read after the editor has applied restored/external content in its layout effect.
+ // Read after the editor has applied restored/external content in its own effect.
// The document scans only pay off when a tag or checklist suggestion exists.
- useLayoutEffect(() => {
+ useEffect(() => {
const controller = controllerRef.current;
if ((!needsTags && !needsChecklist) || !controller || controller.getMarkdown() !== content) return;
if (needsTags) {
@@ -121,10 +121,8 @@ export function EditorSuggestions({
applied = controller.insertTag(suggestion.tag);
break;
case "checklist": {
- if (controller.hasChecklist() || !controller.formatting) return;
- const before = controller.getMarkdown();
- controller.formatting.run("taskList");
- applied = before !== controller.getMarkdown();
+ if (controller.hasChecklist()) return;
+ applied = controller.toggleTaskList();
controller.focus();
break;
}
diff --git a/web/src/components/MemoEditor/components/FocusModeOverlay.tsx b/web/src/components/MemoEditor/components/FocusModeOverlay.tsx
index e7b5b89ff..53a1f5316 100644
--- a/web/src/components/MemoEditor/components/FocusModeOverlay.tsx
+++ b/web/src/components/MemoEditor/components/FocusModeOverlay.tsx
@@ -1,5 +1,6 @@
-import { Minimize2Icon } from "lucide-react";
+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";
@@ -9,12 +10,15 @@ export function FocusModeOverlay({ isActive, onToggle }: FocusModeOverlayProps)
return <div className={FOCUS_MODE_STYLES.backdrop} onClick={onToggle} aria-label="Exit focus mode" />;
}
-export function FocusModeExitButton({ isActive, onToggle, title }: FocusModeExitButtonProps) {
- if (!isActive) return null;
+/** Leaves the frame the editor sits in: minimizes inline focus mode, or closes a host-owned frame. */
+export function FocusModeExitButton({ action, onExit }: FocusModeExitButtonProps) {
+ const t = useTranslate();
+ const label = t(action === "close" ? "common.close" : "editor.exit-focus-mode");
+ const Icon = action === "close" ? XIcon : Minimize2Icon;
return (
- <Button variant="ghost" size="icon" className={FOCUS_MODE_STYLES.exitButton} onClick={onToggle} title={title}>
- <Minimize2Icon className="w-4 h-4" />
+ <Button variant="quiet" size="icon-compact" aria-label={label} title={label} onClick={onExit}>
+ <Icon className="size-4" strokeWidth={1.8} />
</Button>
);
}
diff --git a/web/src/components/MemoEditor/constants.ts b/web/src/components/MemoEditor/constants.ts
index 77aadd247..0b445c73e 100644
--- a/web/src/components/MemoEditor/constants.ts
+++ b/web/src/components/MemoEditor/constants.ts
@@ -5,9 +5,4 @@ export const FOCUS_MODE_STYLES = {
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",
},
transition: "transition-all duration-300 ease-in-out",
- exitButton: "absolute top-2 right-2 z-10 opacity-60 hover:opacity-100",
} as const;
-
-// localStorage key for the user's preference to show the formatting toolbar in
-// normal (non-focus) mode. Defaults to off.
-export const FORMATTING_TOOLBAR_STORAGE_KEY = "memos-editor-formatting-toolbar";
diff --git a/web/src/components/MemoEditor/formatting/commands.ts b/web/src/components/MemoEditor/formatting/commands.ts
deleted file mode 100644
index 5f9815370..000000000
--- a/web/src/components/MemoEditor/formatting/commands.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import {
- BoldIcon,
- CodeIcon,
- ItalicIcon,
- LinkIcon,
- ListIcon,
- ListOrderedIcon,
- ListTodoIcon,
- type LucideIcon,
- StrikethroughIcon,
-} from "lucide-react";
-import type { Translations } from "@/utils/i18n";
-
-/**
- * Backend-agnostic catalog of the editor's formatting verbs — metadata only, no
- * dependency on the concrete editor. Every surface that needs the verbs — the
- * focus-mode toolbar, the active-state hook, and any future `/` slash menu —
- * derives its labels, icons, and grouping from this catalog instead of
- * re-declaring them. How a verb is applied to the live editor is supplied
- * separately (Editor/formatting.ts).
- *
- * To add a formatting verb, add one entry here (and, if it's a new mark/list,
- * its field on ActiveFormatState); the toolbar and active-state pick it up.
- */
-
-export type ToolbarHeadingLevel = 1 | 2 | 3;
-
-/** Clamp a raw heading depth to the toolbar's addressable levels (H4–H6 → null). */
-export function toToolbarHeadingLevel(level: number): ToolbarHeadingLevel | null {
- return level === 1 || level === 2 || level === 3 ? level : null;
-}
-
-export type EditorCommandId =
- | "bold"
- | "italic"
- | "strikethrough"
- | "code"
- | "codeBlock"
- | "bulletList"
- | "orderedList"
- | "taskList"
- | "paragraph"
- | "heading1"
- | "heading2"
- | "heading3"
- | "link";
-
-/** Which marks/blocks are active at the current selection (toolbar highlighting). */
-export interface ActiveFormatState {
- bold: boolean;
- italic: boolean;
- strikethrough: boolean;
- code: boolean;
- codeBlock: boolean;
- bulletList: boolean;
- orderedList: boolean;
- taskList: boolean;
- link: boolean;
- headingLevel: ToolbarHeadingLevel | null;
-}
-
-export const EMPTY_ACTIVE_FORMATS: ActiveFormatState = {
- bold: false,
- italic: false,
- strikethrough: false,
- code: false,
- codeBlock: false,
- bulletList: false,
- orderedList: false,
- taskList: false,
- link: false,
- headingLevel: null,
-};
-
-export interface EditorCommandContext {
- /** Link target, read by the `link` command when adding a link. */
- url?: string;
-}
-
-/** Toolbar grouping — the toolbar builds each group by filtering on this.
- * `mark` = inline formatting, `block` = line/block-level (lists, code block). */
-export type EditorCommandGroup = "mark" | "block" | "heading" | "link";
-
-export interface EditorCommand {
- id: EditorCommandId;
- /** i18n key for label / tooltip / aria-label. */
- labelKey: Translations;
- /** Button icon. Omitted for headings/paragraph, which render as label-only dropdown items. */
- icon?: LucideIcon;
- group: EditorCommandGroup;
-}
-
-export const EDITOR_COMMANDS: EditorCommand[] = [
- {
- id: "bold",
- labelKey: "editor.format.bold",
- icon: BoldIcon,
- group: "mark",
- },
- {
- id: "italic",
- labelKey: "editor.format.italic",
- icon: ItalicIcon,
- group: "mark",
- },
- {
- id: "strikethrough",
- labelKey: "editor.format.strikethrough",
- icon: StrikethroughIcon,
- group: "mark",
- },
- {
- id: "bulletList",
- labelKey: "editor.format.bullet-list",
- icon: ListIcon,
- group: "block",
- },
- {
- id: "orderedList",
- labelKey: "editor.format.ordered-list",
- icon: ListOrderedIcon,
- group: "block",
- },
- {
- id: "taskList",
- labelKey: "editor.format.task-list",
- icon: ListTodoIcon,
- group: "block",
- },
- {
- id: "codeBlock",
- labelKey: "editor.format.code-block",
- icon: CodeIcon,
- group: "block",
- },
- {
- id: "paragraph",
- labelKey: "editor.format.paragraph",
- group: "heading",
- },
- {
- id: "heading1",
- labelKey: "editor.format.heading-1",
- group: "heading",
- },
- {
- id: "heading2",
- labelKey: "editor.format.heading-2",
- group: "heading",
- },
- {
- id: "heading3",
- labelKey: "editor.format.heading-3",
- group: "heading",
- },
- {
- id: "link",
- labelKey: "editor.format.link",
- icon: LinkIcon,
- group: "link",
- },
-];
-
-export const EDITOR_COMMANDS_BY_ID = Object.fromEntries(EDITOR_COMMANDS.map((command) => [command.id, command])) as Record<
- EditorCommandId,
- EditorCommand
->;
-
-/** Whether a given command is active for an active-format snapshot. Lets any
- * surface (toolbar, slash menu) highlight commands by reading the backend-
- * agnostic ActiveFormatState — no live-editor dependency. */
-export function isCommandActive(active: ActiveFormatState, id: EditorCommandId): boolean {
- switch (id) {
- case "paragraph":
- return active.headingLevel === null;
- case "heading1":
- return active.headingLevel === 1;
- case "heading2":
- return active.headingLevel === 2;
- case "heading3":
- return active.headingLevel === 3;
- // The remaining ids (marks, blocks, link) map 1:1 to the snapshot.
- default:
- return active[id];
- }
-}
diff --git a/web/src/components/MemoEditor/hooks/index.ts b/web/src/components/MemoEditor/hooks/index.ts
index 0bb377e1a..9cc80fa41 100644
--- a/web/src/components/MemoEditor/hooks/index.ts
+++ b/web/src/components/MemoEditor/hooks/index.ts
@@ -5,8 +5,6 @@ export { useAudioRecorder } from "./useAudioRecorder";
export { useAudioWaveform } from "./useAudioWaveform";
export { useAutoSave } from "./useAutoSave";
export { useBlobUrls } from "./useBlobUrls";
-export { useEditorActiveState } from "./useEditorActiveState";
-export { COMPACT_TOOLBAR_WIDTH, isCompactWidth, useElementWidth } from "./useElementWidth";
export { pairAppleLivePhotoFiles, toLocalFiles, useFileUpload } from "./useFileUpload";
export { useFocusMode } from "./useFocusMode";
export { splitInlineLocalFiles, useInlineImageUpload } from "./useInlineImageUpload";
diff --git a/web/src/components/MemoEditor/hooks/useEditorActiveState.ts b/web/src/components/MemoEditor/hooks/useEditorActiveState.ts
deleted file mode 100644
index 0ad1826d0..000000000
--- a/web/src/components/MemoEditor/hooks/useEditorActiveState.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { type RefObject, useEffect, useState } from "react";
-import { type ActiveFormatState, EMPTY_ACTIVE_FORMATS } from "../formatting/commands";
-import type { EditorController } from "../types/editorController";
-
-// Derive the key set from the canonical empty snapshot so a command added to
-// ActiveFormatState is compared automatically (all fields are primitives).
-const ACTIVE_FORMAT_KEYS = Object.keys(EMPTY_ACTIVE_FORMATS) as (keyof ActiveFormatState)[];
-
-function sameActiveFormats(a: ActiveFormatState, b: ActiveFormatState): boolean {
- return ACTIVE_FORMAT_KEYS.every((key) => a[key] === b[key]);
-}
-
-/**
- * Subscribes to the editor's formatting capability and recomputes which
- * marks/nodes are active whenever the selection or document changes, so toolbar
- * buttons can highlight live. Returns the empty snapshot until a formatting-
- * capable controller is available (e.g. raw mode, which has none).
- */
-export function useEditorActiveState(controllerRef: RefObject<EditorController | null>): ActiveFormatState {
- const [active, setActive] = useState<ActiveFormatState>(EMPTY_ACTIVE_FORMATS);
- useEffect(() => {
- const formatting = controllerRef.current?.formatting;
- if (!formatting) {
- return;
- }
- // Fires on every transaction; keep the previous object identity when the
- // derived snapshot is unchanged (the common case while typing) so React
- // skips the toolbar re-render.
- const recompute = () => {
- const next = formatting.getActiveFormats();
- setActive((prev) => (sameActiveFormats(prev, next) ? prev : next));
- };
- recompute();
- return formatting.subscribe(recompute);
- }, [controllerRef]);
- return active;
-}
diff --git a/web/src/components/MemoEditor/hooks/useElementWidth.ts b/web/src/components/MemoEditor/hooks/useElementWidth.ts
deleted file mode 100644
index fc6135389..000000000
--- a/web/src/components/MemoEditor/hooks/useElementWidth.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { type RefObject, useEffect, useState } from "react";
-
-/** Below this content width (px) the formatting toolbar uses its compact layout. */
-export const COMPACT_TOOLBAR_WIDTH = 380;
-
-/** Pure decision so it can be unit-tested without a DOM. Width 0 = unmeasured. */
-export function isCompactWidth(width: number): boolean {
- return width > 0 && width < COMPACT_TOOLBAR_WIDTH;
-}
-
-/**
- * Tracks an element's content-box width via ResizeObserver. Returns 0 until the
- * first measurement (or when ResizeObserver is unavailable, e.g. jsdom), which
- * isCompactWidth() treats as the full (non-compact) layout.
- */
-export function useElementWidth<T extends HTMLElement>(ref: RefObject<T | null>): number {
- const [width, setWidth] = useState(0);
- useEffect(() => {
- const element = ref.current;
- if (!element || typeof ResizeObserver === "undefined") {
- return;
- }
- const observer = new ResizeObserver((entries) => {
- setWidth(entries[0].contentRect.width);
- });
- observer.observe(element);
- setWidth(element.getBoundingClientRect().width);
- return () => observer.disconnect();
- }, [ref]);
- return width;
-}
diff --git a/web/src/components/MemoEditor/hooks/useInlineImageUpload.ts b/web/src/components/MemoEditor/hooks/useInlineImageUpload.ts
index ab1ae5d1c..33f039c5d 100644
--- a/web/src/components/MemoEditor/hooks/useInlineImageUpload.ts
+++ b/web/src/components/MemoEditor/hooks/useInlineImageUpload.ts
@@ -9,7 +9,7 @@ import { buildManagedAttachmentMarkdown, canInlineAttachment } from "@/utils/man
import { errorService, uploadService } from "../services";
import { useEditorContext } from "../state";
import type { LocalFile } from "../types/attachment";
-import type { EditorController } from "../types/editorController";
+import type { EditorController, EditorPosition } from "../types/editorController";
interface UploadEntry {
localFile: LocalFile;
@@ -202,7 +202,7 @@ export const useInlineImageUpload = (editorRef: RefObject<EditorController | nul
runJobRef.current = runJob;
const insertLocalImages = useCallback(
- (localFiles: LocalFile[], position?: number) => {
+ (localFiles: LocalFile[], position?: EditorPosition | null) => {
if (getState().ui.isLoading.saving) return;
const editor = editorRef.current;
const job = createJob(localFiles);
diff --git a/web/src/components/MemoEditor/hooks/useMemoInit.ts b/web/src/components/MemoEditor/hooks/useMemoInit.ts
index 2df5eebbb..f243a4793 100644
--- a/web/src/components/MemoEditor/hooks/useMemoInit.ts
+++ b/web/src/components/MemoEditor/hooks/useMemoInit.ts
@@ -43,7 +43,7 @@ export const useMemoInit = ({
} else {
const cachedDraft = cacheService.loadDraft(key);
if (cachedDraft.content) {
- dispatch(actions.setContent(cachedDraft.content));
+ dispatch(actions.updateContent(cachedDraft.content));
}
if (cachedDraft.attachments.length > 0) {
dispatch(actions.setMetadata({ attachments: cachedDraft.attachments }));
@@ -66,7 +66,7 @@ export const useMemoInit = ({
if (autoFocus || cachedCursor !== undefined) {
restoreCursorTimer = setTimeout(() => {
if (cachedCursor !== undefined) {
- editorRef.current?.setCursor(cachedCursor);
+ editorRef.current?.setSelection(cachedCursor);
}
if (typeof autoFocus === "function" ? autoFocus() : autoFocus) {
editorRef.current?.focus();
diff --git a/web/src/components/MemoEditor/index.tsx b/web/src/components/MemoEditor/index.tsx
index c503c8320..31dd33667 100644
--- a/web/src/components/MemoEditor/index.tsx
+++ b/web/src/components/MemoEditor/index.tsx
@@ -2,16 +2,15 @@ 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 { useLocalStorage } from "@/hooks";
import useCurrentUser from "@/hooks/useCurrentUser";
import { cn } from "@/lib/utils";
import { InstanceSetting_Key } from "@/types/proto/api/instance_service_pb";
import { useTranslate } from "@/utils/i18n";
import { convertVisibilityFromString } from "@/utils/memo";
import { canManageMemo } from "@/utils/user";
-import { AudioRecorderPanel, EditorContent, EditorMetadata, FocusModeOverlay, TimestampPopover } from "./components";
+import { AudioRecorderPanel, EditorContent, EditorMetadata, FocusModeExitButton, FocusModeOverlay, TimestampPopover } from "./components";
import { EditorSuggestions } from "./components/EditorSuggestions";
-import { FOCUS_MODE_STYLES, FORMATTING_TOOLBAR_STORAGE_KEY } from "./constants";
+import { FOCUS_MODE_STYLES } from "./constants";
import type { EditorFileOrigin } from "./Editor/extensions";
import {
splitInlineLocalFiles,
@@ -27,10 +26,10 @@ import {
} from "./hooks";
import { cacheService, errorService, transcriptionService } from "./services";
import { EditorProvider, useEditorContext, useEditorSelector } from "./state";
-import { EditorToolbar, FormattingToolbar } from "./Toolbar";
+import { EditorToolbar } from "./Toolbar";
import type { EditorViewToggles, MemoEditorProps } from "./types";
import type { LocalFile } from "./types/attachment";
-import type { EditorController } from "./types/editorController";
+import type { EditorController, EditorPosition } from "./types/editorController";
// A host that presents the editor full-screen supplies `onFocusModeExit`; its
// presence is what makes an instance hosted, so focus mode starts on and stays on.
@@ -71,18 +70,16 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
}, [isFocusMode, onFocusModeChange]);
const isSaving = useEditorSelector((s) => s.ui.isLoading.saving);
const hasTimestamp = useEditorSelector((s) => Boolean(s.timestamps.createTime));
- const { userGeneralSetting } = useAuth();
+ const { userGeneralSetting, userTagsSetting } = useAuth();
const { aiSetting, fetchSetting } = useInstance();
const [isAudioRecorderOpen, setIsAudioRecorderOpen] = useState(false);
const [isTranscribingAudio, setIsTranscribingAudio] = useState(false);
const { createBlobUrl } = useBlobUrls();
const saveMediaMetadata = userGeneralSetting?.saveMediaMetadata ?? false;
const inlineImageUpload = useInlineImageUpload(editorRef);
- // Persisted preference: also show the formatting toolbar in normal mode. Focus
- // mode always shows it regardless; this only governs the non-focus layout.
- const [isFormattingToolbarVisible, setFormattingToolbarVisible] = useLocalStorage(FORMATTING_TOOLBAR_STORAGE_KEY, false);
const memoName = memo?.name;
+ const showTimestamp = Boolean(memoName || (!memo && hasTimestamp));
// Replies are never placed independently: a comment's Space is its parent's.
// An edited top-level memo can change its Space; a new one can unless its
// host fixes the target (e.g. composing inside a Space).
@@ -146,14 +143,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
void fetchSetting(InstanceSetting_Key.AI).catch(() => undefined);
}, [currentUser, fetchSetting]);
- const insertTranscribedText = useCallback((text: string) => {
- const editor = editorRef.current;
- if (!editor) {
- return;
- }
- editor.insertMarkdown(text);
- editor.scrollToCursor();
- }, []);
+ const insertTranscribedText = useCallback((text: string) => editorRef.current?.insertMarkdown(text), []);
const { transcribeAttachment, transcribingAttachment } = useAttachmentTranscription(insertTranscribedText);
@@ -232,7 +222,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
}, [isAudioRecorderOpen, audioRecorder.error, audioRecorder.status, t]);
const rememberCursor = useCallback(() => {
- const cursor = editorRef.current?.getCursor();
+ const cursor = editorRef.current?.getSelection();
if (cursor !== undefined) {
cacheService.saveCursor(editorCacheKey, cursor);
}
@@ -254,10 +244,6 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
onCancel?.();
}, [onCancel, rememberCursor]);
- const handleToggleFormattingToolbar = useCallback(() => {
- setFormattingToolbarVisible((visible) => !visible);
- }, [setFormattingToolbarVisible]);
-
const handleStartAudioRecording = async () => {
setIsAudioRecorderOpen(true);
await audioRecorder.startRecording();
@@ -277,7 +263,7 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
* otherwise everything joins the attachment list.
*/
const handleFiles = useCallback(
- (files: File[], placement: { inline: false } | { inline: true; position?: number }) => {
+ (files: File[], placement: { inline: false } | { inline: true; position?: EditorPosition | null }) => {
if (getState().ui.isLoading.saving) return;
const localFiles = toLocalFiles(files, { createBlobUrl, saveMediaMetadata });
const { inline, attachments } = placement.inline ? splitInlineLocalFiles(localFiles) : { inline: [], attachments: localFiles };
@@ -319,15 +305,12 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
}
};
- // The + menu's view toggles only describe how an inline editor presents
- // itself, so a hosted editor offers neither: its host owns the frame, and
- // focus mode already forces the formatting toolbar on.
+ // The + menu's view toggle only describes how an inline editor presents
+ // itself, so a hosted editor does not offer it: its host owns the frame.
const viewToggles: EditorViewToggles | undefined = onFocusModeExit
? undefined
: {
onToggleFocusMode: handleToggleFocusMode,
- isFormattingToolbarVisible,
- onToggleFormattingToolbar: handleToggleFormattingToolbar,
};
const handleSave = useMemoSave({
@@ -364,25 +347,29 @@ const MemoEditorImpl: React.FC<MemoEditorProps> = ({
!isFocusMode && className,
)}
>
- {/* Formatting toolbar. Always shown in focus mode (trailing the button
- that leaves the current frame — minimize inline, close when hosted);
- in normal mode it appears only when the user toggled it on via the
- insert menu. */}
- {(isFocusMode || isFormattingToolbarVisible) && (
- <FormattingToolbar
- controllerRef={editorRef}
- exit={isFocusMode ? { action: onFocusModeExit ? "close" : "minimize", onExit: handleToggleFocusMode } : undefined}
- />
- )}
-
- {(memoName || (!memo && hasTimestamp)) && (
+ {/* Formatting is the editor's own: its toolbar appears over selected
+ text, and the slash menu and Markdown shortcuts change block types.
+ Focus mode adds the button that leaves the current frame — minimize
+ inline, close when hosted. */}
+ {(showTimestamp || isFocusMode) && (
<div className="flex h-6 w-full items-center">
- <TimestampPopover />
+ {showTimestamp && <TimestampPopover />}
+ {isFocusMode && (
+ <div className="ms-auto">
+ <FocusModeExitButton action={onFocusModeExit ? "close" : "minimize"} onExit={handleToggleFocusMode} />
+ </div>
+ )}
</div>
)}
{/* Editor content grows to fill available space in focus mode */}
- <EditorContent ref={editorRef} placeholder={placeholder} onSubmit={handleSave} onFiles={handleEditorFiles} />
+ <EditorContent
+ ref={editorRef}
+ placeholder={placeholder}
+ onSubmit={handleSave}
+ onFiles={handleEditorFiles}
+ tagsSetting={userTagsSetting}
+ />
{isAudioRecorderOpen && (audioRecorder.isBusy || isTranscribingAudio) && (
<AudioRecorderPanel
diff --git a/web/src/components/MemoEditor/services/cacheService.ts b/web/src/components/MemoEditor/services/cacheService.ts
index a152a1f65..ae67801a7 100644
--- a/web/src/components/MemoEditor/services/cacheService.ts
+++ b/web/src/components/MemoEditor/services/cacheService.ts
@@ -3,11 +3,12 @@ import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
import { type Location, LocationSchema, Visibility } from "@/types/proto/api/memo_service_pb";
+import type { EditorSelection } from "../types/editorController";
export const CACHE_DEBOUNCE_DELAY = 500;
const pendingSaves = new Map<string, number>();
-const cursors = new Map<string, number>();
+const cursors = new Map<string, EditorSelection>();
const STRUCTURED_CACHE_ENTRY_KIND = "memos.editor-cache";
const STRUCTURED_CACHE_ENTRY_VERSION = 3;
@@ -134,11 +135,11 @@ export const cacheService = {
return raw ? deserializeDraft(raw) : { content: "", attachments: [] };
},
- saveCursor(key: string, cursor: number): void {
+ saveCursor(key: string, cursor: EditorSelection): void {
cursors.set(key, cursor);
},
- loadCursor(key: string): number | undefined {
+ loadCursor(key: string): EditorSelection | undefined {
return cursors.get(key);
},
diff --git a/web/src/components/MemoEditor/state/actions.ts b/web/src/components/MemoEditor/state/actions.ts
index f106a939c..1a4369bb3 100644
--- a/web/src/components/MemoEditor/state/actions.ts
+++ b/web/src/components/MemoEditor/state/actions.ts
@@ -9,12 +9,7 @@ export const editorActions = {
updateContent: (content: string): EditorAction => ({
type: "UPDATE_CONTENT",
- payload: { content, source: "editor" },
- }),
-
- setContent: (content: string): EditorAction => ({
- type: "UPDATE_CONTENT",
- payload: { content, source: "external" },
+ payload: { content },
}),
setMetadata: (metadata: Partial<EditorState["metadata"]>): EditorAction => ({
diff --git a/web/src/components/MemoEditor/state/reducer.ts b/web/src/components/MemoEditor/state/reducer.ts
index ab94cf24b..2f2082af2 100644
--- a/web/src/components/MemoEditor/state/reducer.ts
+++ b/web/src/components/MemoEditor/state/reducer.ts
@@ -7,19 +7,17 @@ export function editorReducer(state: EditorState, action: EditorAction): EditorS
return {
...state,
content: action.payload.content,
- contentSource: "external",
metadata: action.payload.metadata,
timestamps: action.payload.timestamps,
};
case "UPDATE_CONTENT": {
- if (state.content === action.payload.content && state.contentSource === action.payload.source) {
+ if (state.content === action.payload.content) {
return state;
}
return {
...state,
content: action.payload.content,
- contentSource: action.payload.source,
};
}
diff --git a/web/src/components/MemoEditor/state/types.ts b/web/src/components/MemoEditor/state/types.ts
index 9cc20df2b..da511696b 100644
--- a/web/src/components/MemoEditor/state/types.ts
+++ b/web/src/components/MemoEditor/state/types.ts
@@ -4,11 +4,9 @@ import { Visibility } from "@/types/proto/api/memo_service_pb";
import type { LocalFile } from "../types/attachment";
export type LoadingKey = "saving" | "uploading" | "loading" | "transcribing";
-export type ContentSource = "editor" | "external";
export interface EditorState {
content: string;
- contentSource: ContentSource;
metadata: {
visibility: Visibility;
/** Destination chosen in an unscoped new-memo composer. */
@@ -45,7 +43,7 @@ export interface EditorState {
export type EditorAction =
| { type: "INIT_MEMO"; payload: { content: string; metadata: EditorState["metadata"]; timestamps: EditorState["timestamps"] } }
- | { type: "UPDATE_CONTENT"; payload: { content: string; source: ContentSource } }
+ | { type: "UPDATE_CONTENT"; payload: { content: string } }
| { type: "SET_METADATA"; payload: Partial<EditorState["metadata"]> }
| { type: "ADD_LOCAL_FILE"; payload: LocalFile }
| { type: "REMOVE_LOCAL_FILE"; payload: string }
@@ -62,7 +60,6 @@ export type EditorAction =
// Module-private template for createInitialState.
const defaultState: EditorState = {
content: "",
- contentSource: "external",
metadata: {
visibility: Visibility.PRIVATE,
attachments: [],
diff --git a/web/src/components/MemoEditor/types/components.ts b/web/src/components/MemoEditor/types/components.ts
index be3152735..556884b35 100644
--- a/web/src/components/MemoEditor/types/components.ts
+++ b/web/src/components/MemoEditor/types/components.ts
@@ -1,6 +1,7 @@
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";
+import type { UserSetting_TagsSetting } from "@/types/proto/api/user_service_pb";
import type { EditorFileOrigin } from "../Editor/extensions";
import type { AudioRecorderStatus } from "../hooks/useAudioRecorder";
import type { LocalFile } from "./attachment";
@@ -52,18 +53,16 @@ export interface EditorContentProps {
/** Invoked by the in-editor save shortcut (Cmd/Ctrl+Enter). */
onSubmit: () => void;
onFiles: (files: File[], origin: EditorFileOrigin) => void;
+ /** The user's tag settings, for tags in their custom colors. */
+ tagsSetting?: UserSetting_TagsSetting;
}
/**
* The + menu's view toggles. They change how the editor presents itself
- * inline, so a hosted editor omits the whole group and both items disappear
- * together — there is no way to offer one without the other.
+ * inline, so a hosted editor omits the whole group.
*/
export interface EditorViewToggles {
onToggleFocusMode: () => void;
- /** Whether the formatting toolbar is shown in normal mode (persisted preference). */
- isFormattingToolbarVisible: boolean;
- onToggleFormattingToolbar: () => void;
}
export interface EditorToolbarProps {
@@ -108,9 +107,9 @@ export interface FocusModeOverlayProps {
}
export interface FocusModeExitButtonProps {
- isActive: boolean;
- onToggle: () => void;
- title: string;
+ /** "minimize" collapses inline focus mode back into the page; "close" dismisses a host-owned frame. */
+ action: "minimize" | "close";
+ onExit: () => void;
}
export interface InsertMenuProps {
diff --git a/web/src/components/MemoEditor/types/editorController.ts b/web/src/components/MemoEditor/types/editorController.ts
index 032ce21ea..cf4ea4b14 100644
--- a/web/src/components/MemoEditor/types/editorController.ts
+++ b/web/src/components/MemoEditor/types/editorController.ts
@@ -1,10 +1,16 @@
+import type { Position, SelectionJSON } from "@usememos/editor";
import type { UploadAnchorDescriptor } from "../Editor/uploadAnchors";
-import type { ActiveFormatState, EditorCommandContext, EditorCommandId } from "../formatting/commands";
+
+/** A place in the document, such as where files were dropped. Valid until the document changes. */
+export type EditorPosition = Position;
+
+/** A selection that survives reloading the same Markdown, for restoring the caret across mounts. */
+export type EditorSelection = SelectionJSON;
/**
* The contract the memo editor (Editor) implements. Everything outside the
* editor implementation talks markdown through this interface and never reaches
- * for the editor's internal CodeMirror/DOM APIs.
+ * for the editor's internal APIs.
*/
export interface EditorController {
focus(): void;
@@ -15,42 +21,24 @@ export interface EditorController {
getMarkdown(): string;
/** Replace the whole document from a markdown string. */
setMarkdown(markdown: string): void;
- /** Insert markdown at the cursor as its own block. */
+ /** Insert markdown at the caret as its own block, keeping any selected text. */
insertMarkdown(markdown: string): void;
/** Actual Markdown tags, excluding code, URLs, and other literal contexts. */
getTags(): string[];
- /** Whether the document contains a parsed Markdown checklist, checked or unchecked. */
+ /** Whether the document contains a Markdown checklist item, checked or unchecked. */
hasChecklist(): boolean;
/** Insert a tag at the caret without replacing selected text, then advance the caret. Returns whether it was inserted. */
insertTag(tag: string): boolean;
- createUploadAnchor(descriptor: UploadAnchorDescriptor, position?: number): void;
+ /** Shows an upload placeholder after the block at `position` (default: the caret's block). */
+ createUploadAnchor(descriptor: UploadAnchorDescriptor, position?: EditorPosition | null): void;
updateUploadAnchor(descriptor: UploadAnchorDescriptor): void;
+ /** Replaces the placeholder with `markdown`, as blocks after its block. Empty markdown cancels it. */
resolveUploadAnchor(id: string, markdown: string): void;
cancelUploadAnchor(id: string): void;
- getCursor(): number;
- setCursor(position: number): void;
- scrollToCursor(): void;
+ getSelection(): EditorSelection | undefined;
+ setSelection(selection: EditorSelection): void;
/** Select the entire document (used by tests and select-all flows). */
selectAll(): void;
- /**
- * Rich-formatting capability driving the focus-mode FormattingToolbar.
- * Editor always sets it; the field is optional so the contract stays
- * decoupled from any one editor implementation.
- */
- formatting?: FormattingController;
-}
-
-/**
- * Rich-formatting surface, backed by the editor command catalog
- * (formatting/commands.ts). `getActiveFormats` is the sanctioned, typed place
- * editor state crosses the boundary — the editor's internal node/mark names
- * never leak out as stringly-typed `isActive(name)` calls.
- */
-export interface FormattingController {
- /** Run a catalog command (e.g. "bold", "heading2", "link"). */
- run(command: EditorCommandId, ctx?: EditorCommandContext): void;
- /** Snapshot of which marks/blocks are active at the current selection. */
- getActiveFormats(): ActiveFormatState;
- /** Register a listener fired on every transaction/selection change. Returns an unsubscribe. */
- subscribe(listener: () => void): () => void;
+ /** Turns the blocks the selection touches into task items, keeping their text. Returns whether anything changed. */
+ toggleTaskList(): boolean;
}
diff --git a/web/src/components/MemoView/MemoView.tsx b/web/src/components/MemoView/MemoView.tsx
index 3bf18aacb..f8a0898cd 100644
--- a/web/src/components/MemoView/MemoView.tsx
+++ b/web/src/components/MemoView/MemoView.tsx
@@ -73,9 +73,9 @@ const MemoView = forwardRef<MemoViewHandle, MemoViewProps>((props, ref) => {
const editorHostRef = useRef<HTMLDivElement>(null);
const focusMountedEditor = useCallback(() => {
- const codeMirrorContent = editorHostRef.current?.querySelector<HTMLElement>('.cm-content[contenteditable="true"]');
+ const editorRoot = editorHostRef.current?.querySelector<HTMLElement>('.memo-editor-root[contenteditable="true"]');
const fallbackInput = editorHostRef.current?.querySelector<HTMLElement>("textarea, input");
- (codeMirrorContent ?? fallbackInput)?.focus();
+ (editorRoot ?? fallbackInput)?.focus();
}, []);
const openEditor = useCallback(() => {
diff --git a/web/src/components/MemoView/components/MemoBody.tsx b/web/src/components/MemoView/components/MemoBody.tsx
index 669fc3e91..c51c3d1c8 100644
--- a/web/src/components/MemoView/components/MemoBody.tsx
+++ b/web/src/components/MemoView/components/MemoBody.tsx
@@ -5,6 +5,7 @@ import { AttachmentGallery, MemoMetadataRows } from "@/components/MemoMetadata";
import { separateAttachments } from "@/components/MemoMetadata/Attachment/attachmentHelpers";
import { isReferenceRelation } from "@/components/MemoMetadata/Relation/relationHelpers";
import { Button } from "@/components/ui/button";
+import { useUpdateMemo } from "@/hooks/useMemoQueries";
import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
import { filterInlineManagedAttachments } from "@/utils/managed-attachment";
@@ -30,6 +31,9 @@ const MemoBody: React.FC<MemoBodyProps> = ({ compact }) => {
const { memo, parentPage, showBlurredContent, blurred, readonly, openEditor, openPreview, toggleBlurVisibility } = useMemoViewContext();
const { handleMemoContentClick, handleMemoContentDoubleClick } = useMemoHandlers({ readonly, openEditor, openPreview });
+ const { mutate: updateMemo } = useUpdateMemo();
+ const handleTaskToggle = (content: string) =>
+ updateMemo({ update: { name: memo.name, content }, updateMask: ["content", "update_time"] });
const referencedMemos = memo.relations.filter(isReferenceRelation);
// Memoized so AttachmentListView's own useMemo chain keeps its cache across body renders.
@@ -58,6 +62,7 @@ const MemoBody: React.FC<MemoBodyProps> = ({ compact }) => {
attachments={memo.attachments}
onClick={handleMemoContentClick}
onDoubleClick={handleMemoContentDoubleClick}
+ onTaskToggle={readonly ? undefined : handleTaskToggle}
compact={Boolean(compact)}
/>
<AttachmentGallery visual={visual} onImagePreview={openPreview} />
diff --git a/web/src/components/MemoContent/highlight.ts b/web/src/lib/code-highlight.ts
similarity index 73%
rename from web/src/components/MemoContent/highlight.ts
rename to web/src/lib/code-highlight.ts
index af288062d..799890d94 100644
--- a/web/src/components/MemoContent/highlight.ts
+++ b/web/src/lib/code-highlight.ts
@@ -61,7 +61,7 @@ let corePromise: Promise<HLJSApi> | undefined;
let fullBuildPromise: Promise<HLJSApi> | undefined;
let injectedThemeKey: string | undefined;
-export const isPlainTextLanguage = (language: string): boolean => plainTextLanguages.has(language.trim().toLowerCase());
+const isPlainTextLanguage = (language: string): boolean => plainTextLanguages.has(language.trim().toLowerCase());
// The hljs theme stylesheet is a document-global singleton, so it is managed here
// (keyed by theme) rather than by each rendered code block.
@@ -117,21 +117,31 @@ const loadFullBuild = (): Promise<HLJSApi> => {
return fullBuildPromise;
};
-export const highlightCode = async (code: string, language: string): Promise<string> => {
- const normalizedLanguage = language.trim().toLowerCase();
- if (isPlainTextLanguage(normalizedLanguage)) {
- return escapeHTML(code);
- }
+/** Highlighters ready for use, by normalized language; null when the language is unknown to highlight.js. */
+const readyHighlighters = new Map<string, HLJSApi | null>();
- const canonicalLanguage =
- languageAliases[normalizedLanguage] ??
- (Object.hasOwn(commonLanguageLoaders, normalizedLanguage) ? (normalizedLanguage as CommonLanguage) : undefined);
+const canonicalLanguageOf = (normalizedLanguage: string): CommonLanguage | undefined =>
+ languageAliases[normalizedLanguage] ??
+ (Object.hasOwn(commonLanguageLoaders, normalizedLanguage) ? (normalizedLanguage as CommonLanguage) : undefined);
+/** Loads what highlighting `language` needs. Afterwards, highlightLoadedCode returns a result for it. */
+export const loadHighlighter = async (language: string): Promise<void> => {
+ const normalizedLanguage = language.trim().toLowerCase();
+ if (isPlainTextLanguage(normalizedLanguage) || readyHighlighters.has(normalizedLanguage)) return;
+ const canonicalLanguage = canonicalLanguageOf(normalizedLanguage);
const hljs = canonicalLanguage ? await loadCommonLanguage(canonicalLanguage) : await loadFullBuild();
- const languageToHighlight = canonicalLanguage ?? normalizedLanguage;
- if (!hljs.getLanguage(languageToHighlight)) {
- return escapeHTML(code);
- }
+ readyHighlighters.set(normalizedLanguage, hljs.getLanguage(canonicalLanguage ?? normalizedLanguage) ? hljs : null);
+};
- return hljs.highlight(code, { language: languageToHighlight }).value;
+/**
+ * Highlighted HTML for code whose language is loaded, the escaped code for plain text
+ * and unknown languages, or undefined while the language still has to load.
+ */
+export const highlightLoadedCode = (code: string, language: string): string | undefined => {
+ const normalizedLanguage = language.trim().toLowerCase();
+ if (isPlainTextLanguage(normalizedLanguage)) return escapeHTML(code);
+ if (!readyHighlighters.has(normalizedLanguage)) return undefined;
+ const hljs = readyHighlighters.get(normalizedLanguage);
+ if (!hljs) return escapeHTML(code);
+ return hljs.highlight(code, { language: canonicalLanguageOf(normalizedLanguage) ?? normalizedLanguage }).value;
};
diff --git a/web/src/components/MemoContent/constants.ts b/web/src/lib/html-sanitize-schema.ts
similarity index 71%
rename from web/src/components/MemoContent/constants.ts
rename to web/src/lib/html-sanitize-schema.ts
index 27620d0e3..6af27561d 100644
--- a/web/src/components/MemoContent/constants.ts
+++ b/web/src/lib/html-sanitize-schema.ts
@@ -1,10 +1,5 @@
-import { defaultUrlTransform } from "react-markdown";
import { defaultSchema } from "rehype-sanitize";
-// Class names added by remark-gfm for task lists
-export const TASK_LIST_CLASS = "contains-task-list";
-export const TASK_LIST_ITEM_CLASS = "task-list-item";
-
const TRUSTED_IFRAME_SRC_PATTERNS = [
/^https:\/\/www\.youtube\.com\/embed\/[^?#]+(?:\?.*)?$/i,
/^https:\/\/www\.youtube-nocookie\.com\/embed\/[^?#]+(?:\?.*)?$/i,
@@ -31,13 +26,13 @@ const HANDOFF_LINK_PROTOCOLS = ["tel", "sms"];
export const isTrustedIframeSrc = (src: string): boolean => TRUSTED_IFRAME_SRC_PATTERNS.some((pattern) => pattern.test(src));
/**
- * Sanitization schema for markdown HTML content.
- * Extends the default schema to allow:
- * - KaTeX marker classes used before trusted KaTeX rendering runs
- * - Mention/tag metadata generated by trusted remark plugins
- * - iframe embeds only from trusted video providers
+ * Sanitization schema for raw HTML in memos (lib/sanitized-html.ts) and for images the
+ * calendar reads from memo content. Extends the default schema to allow:
+ * - the math and tag/mention class names the previous renderer emitted
+ * - iframe embeds only from trusted providers
+ * - `tel:` and `sms:` links
*
- * This prevents XSS attacks while preserving math rendering functionality.
+ * This prevents XSS attacks from user-written HTML.
*/
export const SANITIZE_SCHEMA = {
...defaultSchema,
@@ -73,17 +68,3 @@ export const SANITIZE_SCHEMA = {
src: ["https"],
},
};
-
-/**
- * react-markdown applies its own `href` allowlist (`defaultUrlTransform`) before the sanitizer
- * runs, and it does not know about the handoff schemes above. Let those through unchanged and
- * defer everything else to the default, so `javascript:` and friends are still dropped.
- */
-export const memoUrlTransform = (url: string): string => {
- // Exact-case match, mirroring how the sanitizer compares schemes.
- const colon = url.indexOf(":");
- if (colon > 0 && HANDOFF_LINK_PROTOCOLS.includes(url.slice(0, colon))) {
- return url;
- }
- return defaultUrlTransform(url);
-};
diff --git a/web/src/lib/markdownStyles.ts b/web/src/lib/markdownStyles.ts
index ffe56aa78..abb835559 100644
--- a/web/src/lib/markdownStyles.ts
+++ b/web/src/lib/markdownStyles.ts
@@ -1,12 +1,10 @@
-import { cn } from "@/lib/utils";
-
export type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
/**
- * Per-level heading type (size / line height / weight / color), shared by the
- * read-only memo view and the editor's heading-line decorations so a heading
- * looks the same while editing and after saving. The scale stays close to the
- * 16px body: headings organize a note, they are not page titles.
+ * Per-level heading type (size / line height / weight / color). The composer and
+ * the memo view are the same Markdown editor, so a heading looks the same while
+ * editing and after saving. The scale stays close to the 16px body: headings
+ * organize a note, they are not page titles.
*/
const headingTypeClasses: Record<HeadingLevel, string> = {
1: "text-2xl/8 font-semibold",
@@ -18,86 +16,25 @@ const headingTypeClasses: Record<HeadingLevel, string> = {
};
/**
- * Read-only view spacing: more room above than below so a heading binds to the
- * content it introduces; no top margin when it opens its container.
- */
-const headingSpacingClasses: Record<HeadingLevel, string> = {
- 1: "mt-5 mb-2 first:mt-0",
- 2: "mt-5 mb-2 first:mt-0",
- 3: "mt-5 mb-1.5 first:mt-0",
- 4: "mt-4 mb-1 first:mt-0",
- 5: "mt-4 mb-1 first:mt-0",
- 6: "mt-4 mb-1 first:mt-0",
-};
-
-/**
- * Complete heading class per level, precomputed once at module load (spacing +
- * type). headingClass is a hot path — MemoContent renders it per heading on
- * every content render — so the cn() merge happens here, not per call.
- */
-const headingClasses: Record<HeadingLevel, string> = {
- 1: cn(headingSpacingClasses[1], headingTypeClasses[1]),
- 2: cn(headingSpacingClasses[2], headingTypeClasses[2]),
- 3: cn(headingSpacingClasses[3], headingTypeClasses[3]),
- 4: cn(headingSpacingClasses[4], headingTypeClasses[4]),
- 5: cn(headingSpacingClasses[5], headingTypeClasses[5]),
- 6: cn(headingSpacingClasses[6], headingTypeClasses[6]),
-};
-
-/**
- * Single source of truth for the styling of common markdown elements rendered
- * by the read-only memo view (MemoContent). Each value is a complete, standalone
- * Tailwind class string so it can be dropped onto a DOM element as-is (MemoContent
- * merges them with `cn`). The editor does not use these — it styles its raw
- * markdown source via CodeMirror decorations in `MemoEditor/Editor/theme.ts`
- * (headings excepted: see `headingTypeClass`).
- *
- * Block rhythm: every block is `my-0 mb-2` (8px between blocks, none above the
- * first), and MemoContent trims the last block's margin. Headings and the
- * horizontal rule are the only blocks with their own vertical spacing; images
- * are inline content and keep a small margin of their own.
- *
- * These are static string literals so Tailwind's JIT scanner detects them.
+ * App classes for Markdown elements, handed to the editor's `theme.classes`
+ * (lib/memo-markdown.ts) and used by the app UI that renders into memos (link
+ * cards, raw HTML). Block spacing is the editor's own. Each value is a complete,
+ * static Tailwind class string so Tailwind's JIT scanner detects it.
*/
export const markdownStyles = {
- paragraph: "my-0 mb-2 leading-6",
- // No italic: synthesized obliques render poorly for CJK text.
- blockquote: "my-0 mb-2 border-s-3 border-muted-foreground/25 ps-3 text-muted-foreground",
- // Direct-child selectors keep each nested disclosure's indicator independent.
- details: "my-0 mb-2 min-w-0 ps-5 [&[open]>summary]:mb-1 [&[open]>summary>svg]:rotate-90 [&>*:last-child]:mb-0",
- summary:
- "relative -ms-5 block cursor-pointer list-none rounded-sm ps-5 pe-1 font-normal leading-6 [overflow-wrap:anywhere] transition-colors hover:bg-muted/50 focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring motion-reduce:transition-none [&::-webkit-details-marker]:hidden",
- disclosureIcon:
- "pointer-events-none absolute start-0.5 top-1.25 size-3.5 text-muted-foreground transition-transform duration-150 motion-reduce:transition-none rtl:rotate-180",
- bulletList: "my-0 mb-2 list-outside ps-6 list-disc marker:text-muted-foreground",
- orderedList: "my-0 mb-2 list-outside ps-6 list-decimal marker:text-muted-foreground",
- // Task list indentation comes from the task item grid columns, not padding.
- taskList: "my-0 mb-2 list-outside list-none",
- // Trimming the last child keeps nested lists and loose-item paragraphs from
- // adding a gap before the next sibling item.
- listItem: "mt-0.5 leading-6 [&>*:last-child]:mb-0",
- // Shared by the read-only task item (MemoContent/markdown/List.tsx) and the
- // editor so the checkbox + text grid stays identical in both.
- taskListItem: "mt-0.5 min-w-0 leading-6 list-none grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-2 [&>[data-slot=checkbox]]:mt-1",
- taskItemContent: "min-w-0 [overflow-wrap:anywhere] [&>*:last-child]:mb-0",
// Relative size so code inside headings scales with the heading.
inlineCode: "font-mono text-[0.875em] bg-muted px-1 py-0.5 rounded-md",
link: "text-primary underline decoration-primary/50 underline-offset-2 transition-colors hover:decoration-primary",
- horizontalRule: "my-4 h-0 border-0 border-b border-border",
image: "max-w-full my-2 rounded-lg",
} as const;
-/** Complete heading class for a given level (spacing + type). */
-export const headingClass = (level: HeadingLevel): string => headingClasses[level];
-
-/** Heading type alone (no spacing), for the editor's heading-line decorations. */
+/** Heading type for a level: size, line height, weight and color. */
export const headingTypeClass = (level: HeadingLevel): string => headingTypeClasses[level];
/**
- * Tag pill styling for the read-only memo view (MemoContent/Tag.tsx). Split into
- * two tokens so the viewer can swap `defaultColor` for an inline custom color.
- * (The editor does not use these; it colors `#tag` source via the
- * `cm-memo-tag` decoration in Editor/theme.ts.)
+ * Tag pill styling for the memo view. Split into two tokens so the view can swap
+ * `defaultColor` for a custom tag color (MemoContent/enhance.ts). The composer
+ * colors tags as text instead (MemoEditor/Editor/editor.css).
*/
export const tagStyles = {
/** Shape, padding, and typography — always applied. */
@@ -107,11 +44,8 @@ export const tagStyles = {
} as const;
/**
- * `@mention` styling for the read-only memo view (MemoContent/Mention.tsx).
- * Unlike a tag this is not a pill — it is a primary-colored accent (the read-only
- * view adds `hover:underline` for its link). (The editor does not use these; it
- * colors `@mention` source via the `cm-memo-mention` decoration in
- * Editor/theme.ts.)
+ * `@mention` styling for a resolved mention in the memo view. Unlike a tag this is
+ * not a pill — it is a primary-colored accent, underlined on hover.
*/
export const mentionStyles = {
base: "text-primary underline-offset-2",
diff --git a/web/src/lib/memo-markdown.ts b/web/src/lib/memo-markdown.ts
new file mode 100644
index 000000000..f305480a2
--- /dev/null
+++ b/web/src/lib/memo-markdown.ts
@@ -0,0 +1,385 @@
+import {
+ type Block,
+ type Doc,
+ defaultResolveUrl,
+ type Extension,
+ footnotes,
+ isPlainTextBlock,
+ isTextBlock,
+ type Labels,
+ type MarkdownOptions,
+ math,
+ mentions,
+ parseMarkdown,
+ type ResolveUrl,
+ type Span,
+ type SyntaxView,
+ scanMentions,
+ scanTags,
+ type TagScanner,
+ type TagsOptions,
+ type Theme,
+ tags,
+} from "@usememos/editor";
+import { ensureHighlightTheme, highlightLoadedCode, loadHighlighter } from "@/lib/code-highlight";
+import { colorToHex } from "@/lib/color";
+import { headingTypeClass, markdownStyles, mentionStyles, tagStyles } from "@/lib/markdownStyles";
+import { findTagMetadata } from "@/lib/tag";
+import { cn } from "@/lib/utils";
+import type { Attachment } from "@/types/proto/api/attachment_service_pb";
+import type { UserSetting_TagsSetting } from "@/types/proto/api/user_service_pb";
+import type { useTranslate } from "@/utils/i18n";
+import { resolveManagedAttachmentImageSource } from "@/utils/managed-attachment";
+
+/**
+ * The memo Markdown dialect, shared by the composer and the read-only memo view
+ * so a memo reads the same while editing and after saving: a single newline is
+ * a line break, and setext headings are off, so a line
+ * followed by `---` stays a paragraph and a divider.
+ */
+export const MEMO_MARKDOWN: MarkdownOptions = { breaks: true, setext: false };
+
+type KatexModule = typeof import("katex").default;
+
+let katexModule: KatexModule | null = null;
+let katexPromise: Promise<KatexModule> | null = null;
+
+/** Loads KaTeX and its stylesheet once. */
+const loadKatex = (): Promise<KatexModule> => {
+ katexPromise ??= Promise.all([import("katex"), import("katex/dist/katex.min.css")]).then(([module]) => {
+ katexModule = module.default;
+ return katexModule;
+ });
+ return katexPromise;
+};
+
+/** Renders TeX with KaTeX, loading it the first time; the editor shows the source meanwhile. */
+const renderMath = (tex: string, element: HTMLElement, { displayMode }: { readonly displayMode: boolean }) => {
+ const render = (katex: KatexModule) => katex.render(tex, element, { displayMode, throwOnError: false, strict: false });
+ if (katexModule) return render(katexModule);
+ return loadKatex().then(render);
+};
+
+/** Editors whose code needs highlighting again once a language finishes loading. */
+const highlightedEditors = new Set<import("@usememos/editor").Editor>();
+/** Languages loading now, so each load redecorates the editors once, however many blocks wait for it. */
+const loadingLanguages = new Set<string>();
+
+/** highlight.js output as decorations: one range per highlighted span, classes and all. */
+function highlightRanges(html: string): { from: number; to: number; class: string }[] {
+ const template = document.createElement("template");
+ template.innerHTML = html;
+ const ranges: { from: number; to: number; class: string }[] = [];
+ let offset = 0;
+ const walk = (node: Node) => {
+ for (const child of node.childNodes) {
+ if (child.nodeType === Node.TEXT_NODE) {
+ offset += child.textContent?.length ?? 0;
+ } else if (child instanceof Element) {
+ const from = offset;
+ walk(child);
+ if (child.className && offset > from) ranges.push({ from, to: offset, class: child.className });
+ }
+ }
+ };
+ walk(template.content);
+ return ranges;
+}
+
+/**
+ * Syntax highlighting for code blocks with highlight.js, while editing and when read-only.
+ * A language loads the first time it is needed; the editors then highlight again.
+ */
+const codeHighlight = (): Extension => ({
+ name: "codeHighlight",
+ onCreate: ({ editor }) => {
+ highlightedEditors.add(editor);
+ return () => highlightedEditors.delete(editor);
+ },
+ codeDecorations: ({ text, language }) => {
+ if (!language.trim() || !text) return [];
+ void ensureHighlightTheme(document.documentElement.style.colorScheme === "dark");
+ const html = highlightLoadedCode(text, language);
+ if (html === undefined) {
+ const key = language.trim().toLowerCase();
+ if (!loadingLanguages.has(key)) {
+ loadingLanguages.add(key);
+ void loadHighlighter(language)
+ .then(
+ () => highlightedEditors.forEach((editor) => editor.redecorate()),
+ () => undefined,
+ )
+ .finally(() => loadingLanguages.delete(key));
+ }
+ return [];
+ }
+ return highlightRanges(html);
+ },
+});
+
+/** Mermaid diagrams for ```mermaid code blocks. The code shows until the diagram is drawn, and stays if it fails. */
+const renderMermaid: SyntaxView = (source, element) => {
+ const pre = document.createElement("pre");
+ pre.textContent = source;
+ element.appendChild(pre);
+ return (async () => {
+ const { default: mermaid } = await import("mermaid");
+ await document.fonts?.ready;
+ mermaid.initialize({
+ startOnLoad: false,
+ theme: document.documentElement.style.colorScheme === "dark" ? "dark" : "default",
+ securityLevel: "strict",
+ fontFamily: getComputedStyle(document.body).fontFamily || "sans-serif",
+ suppressErrorRendering: true,
+ });
+ try {
+ const { svg } = await mermaid.render(`mermaid-${Math.random().toString(36).slice(2)}`, source);
+ element.classList.add("mermaid-diagram");
+ element.innerHTML = svg;
+ } catch {
+ return false;
+ }
+ })();
+};
+
+type HtmlRenderer = typeof import("@/lib/sanitized-html").renderSanitizedHtml;
+let htmlRenderer: HtmlRenderer | null = null;
+let htmlRendererPromise: Promise<HtmlRenderer> | null = null;
+
+/** Raw HTML (`<details>`, `<kbd>`, trusted embeds) through memos' sanitizer, loaded the first time it is needed. */
+const renderHtml: SyntaxView = (source, element, kind) => {
+ if (htmlRenderer) return htmlRenderer(source, element, kind);
+ htmlRendererPromise ??= import("@/lib/sanitized-html").then((module) => {
+ htmlRenderer = module.renderSanitizedHtml;
+ return htmlRenderer;
+ });
+ return htmlRendererPromise.then((render) => render(source, element, kind));
+};
+
+/**
+ * A tag's custom color from the user's tag settings, as a style attribute, or undefined
+ * for the theme color. Text uses a darkened variant (60% color + black) for contrast.
+ */
+function tagColorStyle(tag: string, tagsSetting: UserSetting_TagsSetting | undefined): string | undefined {
+ const metadata = tagsSetting ? findTagMetadata(tag, tagsSetting) : undefined;
+ const bgHex = colorToHex(metadata?.backgroundColor);
+ if (!bgHex) return undefined;
+ return `border-color: ${bgHex}; color: color-mix(in srgb, ${bgHex} 60%, black); background-color: color-mix(in srgb, ${bgHex} 15%, transparent)`;
+}
+
+// `mbe-tag` is the editor's own class; the memo view finds tags by it.
+const TAG_CLASS = cn("mbe-tag", tagStyles.base);
+const DEFAULT_TAG_CLASS = cn(TAG_CLASS, tagStyles.defaultColor);
+
+/**
+ * How a #tag looks wherever a memo is shown, in the composer and the memo view alike:
+ * a pill in the theme color, or in the color the user gave the tag. `getTagsSetting`
+ * is read when a block is decorated; call `editor.redecorate()` when it changes.
+ */
+export const memoTagOptions = (getTagsSetting: () => UserSetting_TagsSetting | undefined): Pick<TagsOptions, "class" | "attributes"> => ({
+ class: (match) => (tagColorStyle(match.slice(1), getTagsSetting()) ? TAG_CLASS : DEFAULT_TAG_CLASS),
+ attributes: (match): Record<string, string> => {
+ const tag = match.slice(1);
+ const style = tagColorStyle(tag, getTagsSetting());
+ return style ? { "data-tag": tag, style } : { "data-tag": tag };
+ },
+});
+
+const RESOLVED_MENTION_CLASS = cn("mbe-mention", mentionStyles.base);
+
+/**
+ * How an @mention looks wherever a memo is shown: in the primary color when the person
+ * exists, as plain text otherwise. `isResolved` is read when a block is decorated; call
+ * `editor.redecorate()` when it changes.
+ */
+export const memoMentionOptions = (isResolved: (username: string) => boolean): Pick<TagsOptions, "class" | "attributes"> => ({
+ class: (match) => (isResolved(match.slice(1)) ? RESOLVED_MENTION_CLASS : "mbe-mention"),
+ attributes: (match): Record<string, string> => {
+ const username = match.slice(1);
+ return isResolved(username)
+ ? { "data-mention": username, "data-resolved": "", title: match }
+ : { "data-mention": username, title: match };
+ },
+});
+
+interface MemoExtensionOptions {
+ /** `tags()` class and attributes, for the memo view's pills and colors. */
+ readonly tags?: Pick<TagsOptions, "class" | "attributes">;
+ /** `mentions()` class and attributes, for links to the people who exist. */
+ readonly mentions?: Pick<TagsOptions, "class" | "attributes">;
+}
+
+/**
+ * The extensions every memo surface reads with, the composer and the memo view
+ * alike: math (KaTeX, loaded on demand), footnotes, #tags and @mentions,
+ * highlighted code, Mermaid diagrams and sanitized raw HTML. Everything the
+ * editor renders shows its source at the caret while editing.
+ */
+export const memoExtensions = (options: MemoExtensionOptions = {}): Extension[] => [
+ math({ render: renderMath }),
+ footnotes(),
+ tags(options.tags),
+ mentions(options.mentions),
+ codeHighlight(),
+ { name: "memoViews", views: { "code:mermaid": renderMermaid, html: renderHtml } },
+];
+
+/** Images load from relative URLs and https only, as memos' sanitizer allowed; anything else is dropped. */
+const isAllowedImageSource = (src: string): boolean => !/^[a-z][a-z0-9+.-]*:/i.test(src) || /^https:/i.test(src);
+
+/**
+ * memos' URL policy: managed attachment images resolve to their served URL and load
+ * from relative or https URLs only; links also allow `sms:`, which hands off to
+ * another app, beyond the editor's defaults.
+ */
+export const memoResolveUrl =
+ (attachments: readonly Attachment[] = []): ResolveUrl =>
+ (url, kind) => {
+ if (kind === "image") {
+ const resolved = resolveManagedAttachmentImageSource(url, [...attachments]) ?? url;
+ return isAllowedImageSource(resolved) ? resolved : null;
+ }
+ return /^sms:/i.test(url.trim()) ? url.trim() : defaultResolveUrl(url, kind);
+ };
+
+/**
+ * The editor's look in memos' palette. Every color is one of the app's own CSS
+ * variables, for both schemes, so the active memos theme decides; `inherit`
+ * follows the `color-scheme` memos sets on the document.
+ */
+export const MEMO_EDITOR_THEME: Theme = (() => {
+ const colors = {
+ text: "var(--foreground)",
+ muted: "var(--muted-foreground)",
+ background: "transparent",
+ accent: "var(--primary)",
+ link: "var(--primary)",
+ codeBackground: "var(--muted)",
+ border: "var(--border)",
+ popupBackground: "var(--popover)",
+ popupBorder: "var(--border)",
+ hover: "var(--accent)",
+ danger: "var(--destructive)",
+ };
+ return {
+ colorScheme: "inherit",
+ tokens: {
+ light: colors,
+ dark: colors,
+ font: "inherit",
+ mono: "var(--font-mono, ui-monospace, monospace)",
+ fontSize: 16,
+ lineHeight: 24,
+ radius: "calc(var(--radius) - 2px)",
+ blockGap: 8,
+ },
+ classes: {
+ heading: {
+ 1: headingTypeClass(1),
+ 2: headingTypeClass(2),
+ 3: headingTypeClass(3),
+ 4: headingTypeClass(4),
+ 5: headingTypeClass(5),
+ 6: headingTypeClass(6),
+ },
+ code: markdownStyles.inlineCode,
+ link: markdownStyles.link,
+ image: markdownStyles.image,
+ },
+ };
+})();
+
+/** The editor's UI strings in the user's language. */
+export const memoEditorLabels = (t: ReturnType<typeof useTranslate>): Partial<Labels> => ({
+ text: t("editor.format.paragraph"),
+ heading1: t("editor.format.heading-1"),
+ heading2: t("editor.format.heading-2"),
+ heading3: t("editor.format.heading-3"),
+ bulletList: t("editor.format.bullet-list"),
+ numberedList: t("editor.format.ordered-list"),
+ todoList: t("editor.format.task-list"),
+ task: t("editor.blocks.task"),
+ quote: t("editor.blocks.quote"),
+ code: t("editor.format.code-block"),
+ table: t("editor.blocks.table"),
+ divider: t("editor.blocks.divider"),
+ noResults: t("editor.blocks.no-results"),
+ suggestions: t("editor.suggestions"),
+ commands: t("editor.blocks.commands"),
+ loading: t("editor.blocks.loading"),
+ duplicate: t("editor.blocks.duplicate"),
+ delete: t("common.delete"),
+ bold: t("editor.format.bold"),
+ italic: t("editor.format.italic"),
+ strike: t("editor.format.strikethrough"),
+ inlineCode: t("editor.blocks.inline-code"),
+ link: t("editor.format.link"),
+ linkPlaceholder: t("editor.blocks.link-placeholder"),
+ removeLink: t("editor.blocks.remove-link"),
+ slashHint: t("editor.blocks.slash-hint"),
+ blockHandle: t("editor.blocks.block-menu"),
+ listHint: t("editor.blocks.list-hint"),
+ quoteHint: t("editor.blocks.quote"),
+ language: t("common.language"),
+ plainText: t("editor.blocks.plain-text"),
+ copyCode: t("common.copy"),
+ copied: t("message.copied"),
+ addRowAbove: t("editor.blocks.add-row-above"),
+ addRowBelow: t("editor.blocks.add-row-below"),
+ addColumnLeft: t("editor.blocks.add-column-left"),
+ addColumnRight: t("editor.blocks.add-column-right"),
+ deleteRow: t("editor.blocks.delete-row"),
+ deleteColumn: t("editor.blocks.delete-column"),
+ alignLeft: t("editor.blocks.align-left"),
+ alignCenter: t("editor.blocks.align-center"),
+ alignRight: t("editor.blocks.align-right"),
+ tableSection: t("editor.blocks.table"),
+});
+
+/** Whether a span is literal text for tags: not code, raw HTML, a link, an image, or an extension token. */
+const isLiteralSpan = (span: Span): boolean =>
+ Boolean(span.link || span.image || span.token || span.marks.includes("code") || span.marks.includes("html"));
+
+/** The inline containers of a block: its content, or every table cell. */
+function* blockContainers(block: Block): Generator<readonly Span[]> {
+ if (block.type === "table") {
+ for (const row of block.rows) for (const cell of row) yield cell;
+ return;
+ }
+ if (isTextBlock(block) && !isPlainTextBlock(block)) yield block.content;
+}
+
+/**
+ * Matches of `scan` in a document, without the trigger, in order and without
+ * duplicates. Each run of text with one format is scanned on its own, as the
+ * editor's `tags()` and `mentions()` highlighting does, so code, links and
+ * other literal text never count.
+ */
+const collectMatches = (blocks: readonly Block[], scan: TagScanner): string[] => {
+ const found = new Set<string>();
+ for (const block of blocks) {
+ for (const content of blockContainers(block)) {
+ for (const span of content) {
+ if (isLiteralSpan(span)) continue;
+ for (const range of scan(span.text, 0, span.text.length)) found.add(span.text.slice(range.from + 1, range.to));
+ }
+ }
+ }
+ return [...found];
+};
+
+/** Tags written in a document, as highlighted: `#work/project` gives `work/project`. */
+export const collectTags = (blocks: readonly Block[]): string[] => collectMatches(blocks, scanTags);
+
+// The syntax the memo extensions add (math, footnotes, and the escapes of tags and mentions), for parsing outside an editor.
+const MEMO_SYNTAX = memoExtensions().flatMap((extension) => (extension.markdown ? [extension.markdown] : []));
+
+/** Parses a memo the way the composer and the memo view read it. */
+export const parseMemoMarkdown = (markdown: string): Doc => parseMarkdown(markdown, { ...MEMO_MARKDOWN, syntax: MEMO_SYNTAX });
+
+/**
+ * Usernames a memo mentions, as the memo view highlights them: `@name` outside code,
+ * links and other literal text. Only these need resolving to profile links.
+ */
+export const extractMentionUsernames = (markdown: string): string[] =>
+ markdown.includes("@") ? collectMatches(parseMemoMarkdown(markdown).blocks, scanMentions) : [];
diff --git a/web/src/lib/sanitized-html.ts b/web/src/lib/sanitized-html.ts
new file mode 100644
index 000000000..34755b842
--- /dev/null
+++ b/web/src/lib/sanitized-html.ts
@@ -0,0 +1,110 @@
+import type { Element, Properties, Root, RootContent } from "hast";
+import rehypeRaw from "rehype-raw";
+import rehypeSanitize from "rehype-sanitize";
+import remarkBreaks from "remark-breaks";
+import remarkGfm from "remark-gfm";
+import remarkParse from "remark-parse";
+import remarkRehype from "remark-rehype";
+import { unified } from "unified";
+import { isTrustedIframeSrc, SANITIZE_SCHEMA } from "@/lib/html-sanitize-schema";
+import { markdownStyles } from "@/lib/markdownStyles";
+import { cn } from "@/lib/utils";
+
+/**
+ * Raw HTML in a memo, such as a `<details>` section or a trusted video embed,
+ * as the memo view shows it. Loaded on demand: the editor keeps an HTML block
+ * as source, and this turns that source into sanitized DOM. Markdown between
+ * the tags is rendered too, as GitHub does.
+ */
+const processor = unified()
+ .use(remarkParse)
+ .use(remarkGfm)
+ .use(remarkBreaks)
+ .use(remarkRehype, { allowDangerousHtml: true })
+ .use(rehypeRaw)
+ .use([[rehypeSanitize, SANITIZE_SCHEMA]]);
+
+const ATTRIBUTE_NAMES: Record<string, string> = {
+ className: "class",
+ htmlFor: "for",
+ acceptCharset: "accept-charset",
+ httpEquiv: "http-equiv",
+};
+
+/** The HTML attribute for a hast property name: `className` → `class`, `dataFooBar` → `data-foo-bar`, `ariaLabel` → `aria-label`. */
+const attributeName = (property: string): string => {
+ if (ATTRIBUTE_NAMES[property]) return ATTRIBUTE_NAMES[property];
+ if (/^data[A-Z]/.test(property)) return property.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
+ if (/^aria[A-Z]/.test(property)) return `aria-${property.slice(4).toLowerCase()}`;
+ return property.toLowerCase();
+};
+
+const setAttributes = (element: HTMLElement, properties: Properties | undefined) => {
+ for (const [property, value] of Object.entries(properties ?? {})) {
+ if (value === false || value === null || value === undefined) continue;
+ const attribute = attributeName(property);
+ if (value === true) element.setAttribute(attribute, "");
+ else element.setAttribute(attribute, Array.isArray(value) ? value.join(" ") : String(value));
+ }
+};
+
+/** Memo-view styling and safe defaults for the few elements that need them. */
+const finishElement = (element: HTMLElement, node: Element): HTMLElement | null => {
+ switch (node.tagName) {
+ case "a":
+ if (!element.getAttribute("href")?.startsWith("#")) {
+ element.setAttribute("target", "_blank");
+ element.setAttribute("rel", "noopener noreferrer");
+ }
+ element.className = cn(markdownStyles.link, element.className);
+ break;
+ case "img":
+ element.setAttribute("loading", "lazy");
+ element.setAttribute("decoding", "async");
+ element.setAttribute("referrerpolicy", "no-referrer");
+ element.className = cn(markdownStyles.image, element.className);
+ break;
+ case "iframe":
+ if (!isTrustedIframeSrc(element.getAttribute("src") ?? "")) return null;
+ element.className = cn("max-w-full rounded-lg border border-border", element.className);
+ break;
+ case "details":
+ element.className = cn("my-0 mb-2", element.className);
+ break;
+ case "summary":
+ element.className = cn("cursor-pointer", element.className);
+ break;
+ case "input":
+ element.setAttribute("disabled", "");
+ break;
+ }
+ return element;
+};
+
+const toDom = (node: RootContent): Node | null => {
+ if (node.type === "text") return document.createTextNode(node.value);
+ if (node.type !== "element") return null;
+ const element = document.createElement(node.tagName);
+ setAttributes(element, node.properties);
+ for (const child of node.children) {
+ const childNode = toDom(child);
+ if (childNode) element.appendChild(childNode);
+ }
+ return finishElement(element, node);
+};
+
+/**
+ * Renders raw HTML source into `target` as sanitized DOM, replacing what it held. A
+ * block is rendered as written; an inline run (`<kbd>Ctrl</kbd>`) without the
+ * paragraph Markdown would wrap it in.
+ */
+export function renderSanitizedHtml(source: string, target: HTMLElement, kind: "inline" | "block" = "block"): void {
+ const tree = processor.runSync(processor.parse(source)) as Root;
+ const nodes = tree.children.flatMap((child) => {
+ const node = toDom(child);
+ return node ? [node] : [];
+ });
+ const only = nodes.filter((node) => !(node.nodeType === Node.TEXT_NODE && !node.textContent?.trim()));
+ const unwrap = kind === "inline" && only.length === 1 && only[0] instanceof HTMLParagraphElement;
+ target.replaceChildren(...(unwrap ? Array.from(only[0].childNodes) : nodes));
+}
diff --git a/web/src/locales/ar.json b/web/src/locales/ar.json
index c3d334b0b..cf34ccaf4 100644
--- a/web/src/locales/ar.json
+++ b/web/src/locales/ar.json
@@ -182,7 +182,6 @@
},
"format": {
"code-block": "كتلة كود",
- "heading": "عنوان",
"paragraph": "فقرة",
"heading-1": "عنوان 1",
"heading-2": "عنوان 2",
@@ -193,11 +192,9 @@
"bullet-list": "قائمة نقطية",
"ordered-list": "قائمة مرقمة",
"task-list": "قائمة مهام",
- "link": "رابط",
- "more": "المزيد من خيارات التنسيق"
+ "link": "رابط"
},
"comment": "تعليق",
- "formatting-toolbar": "شريط أدوات التنسيق",
"new-memo": "مذكرة جديدة",
"saved": "تم الحفظ",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "جارٍ الحفظ",
"unsupported-attachment-image-url": "رابط صورة المرفق غير مدعوم: {{url}}",
"wait-for-upload": "انتظر حتى يكتمل التحميل"
+ },
+ "blocks": {
+ "task": "مهمة",
+ "quote": "اقتباس",
+ "table": "جدول",
+ "divider": "فاصل",
+ "no-results": "لا توجد نتائج",
+ "commands": "الأوامر",
+ "loading": "جارٍ التحميل…",
+ "duplicate": "تكرار",
+ "inline-code": "كود",
+ "link-placeholder": "الصق رابطًا أو اكتبه…",
+ "remove-link": "إزالة الرابط",
+ "slash-hint": "اكتب \"/\" لعرض الأوامر",
+ "block-menu": "فتح قائمة الكتلة",
+ "list-hint": "قائمة",
+ "plain-text": "نص",
+ "add-row-above": "إضافة صف أعلاه",
+ "add-row-below": "إضافة صف أدناه",
+ "add-column-left": "إضافة عمود إلى اليسار",
+ "add-column-right": "إضافة عمود إلى اليمين",
+ "delete-row": "حذف الصف",
+ "delete-column": "حذف العمود",
+ "align-left": "محاذاة لليسار",
+ "align-center": "توسيط",
+ "align-right": "محاذاة لليمين"
}
},
"inbox": {
diff --git a/web/src/locales/az.json b/web/src/locales/az.json
index 988247cdd..d179f977d 100644
--- a/web/src/locales/az.json
+++ b/web/src/locales/az.json
@@ -248,9 +248,7 @@
"exit-focus-mode": "Fokus rejimindən çıx",
"focus-mode": "Fokus rejimi",
"comment": "Şərh",
- "formatting-toolbar": "Formatlama paneli",
"format": {
- "heading": "Başlıq",
"paragraph": "Abzas",
"heading-1": "Başlıq 1",
"heading-2": "Başlıq 2",
@@ -262,8 +260,7 @@
"bullet-list": "Nişanlı siyahı",
"ordered-list": "Nömrəli siyahı",
"task-list": "Tapşırıq siyahısı",
- "link": "Keçid",
- "more": "Digər formatlama"
+ "link": "Keçid"
},
"insert-menu": {
"add-attachment": "Qoşma əlavə et",
@@ -306,6 +303,32 @@
"transcribe-success": "Transkripsiya əlavə edildi",
"transcribing": "Mətnə çevrilir...",
"trigger": "Audio yaz"
+ },
+ "blocks": {
+ "task": "Tapşırıq",
+ "quote": "Sitat",
+ "table": "Cədvəl",
+ "divider": "Ayırıcı",
+ "no-results": "Nəticə yoxdur",
+ "commands": "Əmrlər",
+ "loading": "Yüklənir…",
+ "duplicate": "Dublikat et",
+ "inline-code": "Kod",
+ "link-placeholder": "Keçidi yapışdırın və ya yazın…",
+ "remove-link": "Keçidi sil",
+ "slash-hint": "Əmrlər üçün \"/\" yazın",
+ "block-menu": "Blok menyusunu aç",
+ "list-hint": "Siyahı",
+ "plain-text": "mətn",
+ "add-row-above": "Yuxarıya sətir əlavə et",
+ "add-row-below": "Aşağıya sətir əlavə et",
+ "add-column-left": "Sola sütun əlavə et",
+ "add-column-right": "Sağa sütun əlavə et",
+ "delete-row": "Sətri sil",
+ "delete-column": "Sütunu sil",
+ "align-left": "Sola düzləndir",
+ "align-center": "Mərkəzə düzləndir",
+ "align-right": "Sağa düzləndir"
}
},
"inbox": {
diff --git a/web/src/locales/bg.json b/web/src/locales/bg.json
index c41aa010a..04022982b 100644
--- a/web/src/locales/bg.json
+++ b/web/src/locales/bg.json
@@ -221,7 +221,6 @@
"format": {
"code-block": "Кодов блок",
"link": "Връзка",
- "heading": "Заглавие",
"paragraph": "Абзац",
"heading-1": "Заглавие 1",
"heading-2": "Заглавие 2",
@@ -231,11 +230,9 @@
"strikethrough": "Зачеркнато",
"bullet-list": "Водещ символ списък",
"ordered-list": "Номериран списък",
- "task-list": "Списък със задачи",
- "more": "Допълнително форматиране"
+ "task-list": "Списък със задачи"
},
"comment": "Коментар",
- "formatting-toolbar": "Лента с инструменти за форматиране",
"new-memo": "Нова бележка",
"saved": "Запазена",
"validation": {
@@ -247,6 +244,32 @@
"save-in-progress": "Запазването е в процес",
"unsupported-attachment-image-url": "Неподдържан URL адрес на прикаченото изображение: {{url}}",
"wait-for-upload": "Изчакайте качването да завърши"
+ },
+ "blocks": {
+ "task": "Задача",
+ "quote": "Цитат",
+ "table": "Таблица",
+ "divider": "Разделител",
+ "no-results": "Няма резултати",
+ "commands": "Команди",
+ "loading": "Зареждане…",
+ "duplicate": "Дублиране",
+ "inline-code": "Код",
+ "link-placeholder": "Поставете или въведете връзка…",
+ "remove-link": "Премахване на връзката",
+ "slash-hint": "Въведете „/“ за команди",
+ "block-menu": "Отваряне на менюто на блока",
+ "list-hint": "Списък",
+ "plain-text": "текст",
+ "add-row-above": "Добавяне на ред отгоре",
+ "add-row-below": "Добавяне на ред отдолу",
+ "add-column-left": "Добавяне на колона вляво",
+ "add-column-right": "Добавяне на колона вдясно",
+ "delete-row": "Изтриване на реда",
+ "delete-column": "Изтриване на колоната",
+ "align-left": "Подравняване вляво",
+ "align-center": "Центриране",
+ "align-right": "Подравняване вдясно"
}
},
"inbox": {
diff --git a/web/src/locales/ca.json b/web/src/locales/ca.json
index 544a29c8e..09b485387 100644
--- a/web/src/locales/ca.json
+++ b/web/src/locales/ca.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Bloc de codi",
"link": "Enllaç",
- "heading": "Encapçalament",
"paragraph": "Paràgraf",
"heading-1": "Encapçalament 1",
"heading-2": "Encapçalament 2",
@@ -193,11 +192,9 @@
"strikethrough": "Ratllat",
"bullet-list": "Vinyeta llista",
"ordered-list": "Llista numerada",
- "task-list": "Llista de tasques pendents",
- "more": "Més format"
+ "task-list": "Llista de tasques pendents"
},
"comment": "Comentari",
- "formatting-toolbar": "Barra d'eines de format",
"new-memo": "Nova nota",
"saved": "Desada",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Desa en curs",
"unsupported-attachment-image-url": "URL d'imatge adjunta no compatible: {{url}}",
"wait-for-upload": "Espera que es completi la càrrega"
+ },
+ "blocks": {
+ "task": "Tasca",
+ "quote": "Cita",
+ "table": "Taula",
+ "divider": "Separador",
+ "no-results": "Cap resultat",
+ "commands": "Ordres",
+ "loading": "S'està carregant…",
+ "duplicate": "Duplica",
+ "inline-code": "Codi",
+ "link-placeholder": "Enganxa o escriu un enllaç…",
+ "remove-link": "Elimina l'enllaç",
+ "slash-hint": "Escriu «/» per veure les ordres",
+ "block-menu": "Obre el menú del bloc",
+ "list-hint": "Llista",
+ "plain-text": "text",
+ "add-row-above": "Afegeix una fila a sobre",
+ "add-row-below": "Afegeix una fila a sota",
+ "add-column-left": "Afegeix una columna a l'esquerra",
+ "add-column-right": "Afegeix una columna a la dreta",
+ "delete-row": "Esborra la fila",
+ "delete-column": "Esborra la columna",
+ "align-left": "Alinea a l'esquerra",
+ "align-center": "Centra",
+ "align-right": "Alinea a la dreta"
}
},
"inbox": {
diff --git a/web/src/locales/cs.json b/web/src/locales/cs.json
index 5345c4571..8e02237ba 100644
--- a/web/src/locales/cs.json
+++ b/web/src/locales/cs.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Blok kódu",
"link": "Odkaz",
- "heading": "Nadpis",
"paragraph": "Odstavec",
"heading-1": "Nadpis 1",
"heading-2": "Nadpis 2",
@@ -193,11 +192,9 @@
"strikethrough": "Přeškrtnuté",
"bullet-list": "Odrážka seznam",
"ordered-list": "Číslovaný seznam",
- "task-list": "Seznam úkolů",
- "more": "Další formátování"
+ "task-list": "Seznam úkolů"
},
"comment": "Komentář",
- "formatting-toolbar": "Panel nástrojů Formátování",
"new-memo": "Nová poznámka",
"saved": "Uloženo",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Probíhá ukládání",
"unsupported-attachment-image-url": "Nepodporovaná adresa URL obrázku přílohy: {{url}}",
"wait-for-upload": "Počkejte na dokončení nahrávání"
+ },
+ "blocks": {
+ "task": "Úkol",
+ "quote": "Citace",
+ "table": "Tabulka",
+ "divider": "Oddělovač",
+ "no-results": "Žádné výsledky",
+ "commands": "Příkazy",
+ "loading": "Načítání…",
+ "duplicate": "Duplikovat",
+ "inline-code": "Kód",
+ "link-placeholder": "Vložte nebo zadejte odkaz…",
+ "remove-link": "Odstranit odkaz",
+ "slash-hint": "Napište „/“ pro příkazy",
+ "block-menu": "Otevřít nabídku bloku",
+ "list-hint": "Seznam",
+ "plain-text": "text",
+ "add-row-above": "Přidat řádek nad",
+ "add-row-below": "Přidat řádek pod",
+ "add-column-left": "Přidat sloupec vlevo",
+ "add-column-right": "Přidat sloupec vpravo",
+ "delete-row": "Smazat řádek",
+ "delete-column": "Smazat sloupec",
+ "align-left": "Zarovnat vlevo",
+ "align-center": "Zarovnat na střed",
+ "align-right": "Zarovnat vpravo"
}
},
"inbox": {
diff --git a/web/src/locales/da.json b/web/src/locales/da.json
index 8ebf2dac2..ffa7036f0 100644
--- a/web/src/locales/da.json
+++ b/web/src/locales/da.json
@@ -221,7 +221,6 @@
"format": {
"code-block": "Kodeblok",
"link": "Forbindelse",
- "heading": "Overskrift",
"paragraph": "Afsnit",
"heading-1": "Overskrift 1",
"heading-2": "Overskrift 2",
@@ -231,11 +230,9 @@
"strikethrough": "Gennemstreget",
"bullet-list": "Punkttegn liste",
"ordered-list": "Nummereret liste",
- "task-list": "Opgaveliste",
- "more": "Mere formatering"
+ "task-list": "Opgaveliste"
},
"comment": "Kommentar",
- "formatting-toolbar": "Formateringsværktøjslinje",
"new-memo": "Nyt notat",
"saved": "Gemt",
"validation": {
@@ -247,6 +244,32 @@
"save-in-progress": "Gemning i gang",
"unsupported-attachment-image-url": "Ikke-understøttet URL til vedhæftet billede: {{url}}",
"wait-for-upload": "Vent på, at uploaden er fuldført"
+ },
+ "blocks": {
+ "task": "Opgave",
+ "quote": "Citat",
+ "table": "Tabel",
+ "divider": "Skillelinje",
+ "no-results": "Ingen resultater",
+ "commands": "Kommandoer",
+ "loading": "Indlæser…",
+ "duplicate": "Dupliker",
+ "inline-code": "Kode",
+ "link-placeholder": "Indsæt eller skriv et link…",
+ "remove-link": "Fjern link",
+ "slash-hint": "Skriv \"/\" for kommandoer",
+ "block-menu": "Åbn blokmenu",
+ "list-hint": "Liste",
+ "plain-text": "tekst",
+ "add-row-above": "Tilføj række over",
+ "add-row-below": "Tilføj række under",
+ "add-column-left": "Tilføj kolonne til venstre",
+ "add-column-right": "Tilføj kolonne til højre",
+ "delete-row": "Slet række",
+ "delete-column": "Slet kolonne",
+ "align-left": "Venstrejuster",
+ "align-center": "Centrer",
+ "align-right": "Højrejuster"
}
},
"inbox": {
diff --git a/web/src/locales/de.json b/web/src/locales/de.json
index cada1b5ac..572e2eec7 100644
--- a/web/src/locales/de.json
+++ b/web/src/locales/de.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Quellcode-Block",
"link": "Link",
- "heading": "Überschrift",
"paragraph": "Absatz",
"heading-1": "Überschrift 1",
"heading-2": "Überschrift 2",
@@ -193,11 +192,9 @@
"strikethrough": "Durchgestrichen",
"bullet-list": "Stichpunktliste",
"ordered-list": "Nummerierte Liste",
- "task-list": "Aufgabenliste",
- "more": "Weitere Formatierung"
+ "task-list": "Aufgabenliste"
},
"comment": "Kommentar",
- "formatting-toolbar": "Formatierungsleiste",
"new-memo": "Neues Memo",
"saved": "Gespeichert",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Speichern läuft",
"unsupported-attachment-image-url": "Nicht unterstützte URL für Anhangsbild: {{url}}",
"wait-for-upload": "Warten, bis der Upload abgeschlossen ist"
+ },
+ "blocks": {
+ "task": "Aufgabe",
+ "quote": "Zitat",
+ "table": "Tabelle",
+ "divider": "Trennlinie",
+ "no-results": "Keine Ergebnisse",
+ "commands": "Befehle",
+ "loading": "Wird geladen…",
+ "duplicate": "Duplizieren",
+ "inline-code": "Code",
+ "link-placeholder": "Link einfügen oder eingeben…",
+ "remove-link": "Link entfernen",
+ "slash-hint": "„/“ für Befehle eingeben",
+ "block-menu": "Blockmenü öffnen",
+ "list-hint": "Liste",
+ "plain-text": "Text",
+ "add-row-above": "Zeile oberhalb einfügen",
+ "add-row-below": "Zeile unterhalb einfügen",
+ "add-column-left": "Spalte links einfügen",
+ "add-column-right": "Spalte rechts einfügen",
+ "delete-row": "Zeile löschen",
+ "delete-column": "Spalte löschen",
+ "align-left": "Linksbündig",
+ "align-center": "Zentriert",
+ "align-right": "Rechtsbündig"
}
},
"inbox": {
diff --git a/web/src/locales/el.json b/web/src/locales/el.json
index 6ab66ac15..db6767f06 100644
--- a/web/src/locales/el.json
+++ b/web/src/locales/el.json
@@ -221,7 +221,6 @@
"format": {
"code-block": "Μπλοκ κωδικών",
"link": "Σύνδεσμος",
- "heading": "Επικεφαλίδα",
"paragraph": "Παράγραφος",
"heading-1": "Επικεφαλίδα 1",
"heading-2": "Επικεφαλίδα 2",
@@ -231,11 +230,9 @@
"strikethrough": "Διακριτή γραφή",
"bullet-list": "Λίστα με κουκκίδες",
"ordered-list": "Λίστα με αρίθμηση",
- "task-list": "Λίστα υποχρεώσεων",
- "more": "Περισσότερη μορφοποίηση"
+ "task-list": "Λίστα υποχρεώσεων"
},
"comment": "Σχόλιο",
- "formatting-toolbar": "Γραμμή εργαλείων μορφοποίησης",
"new-memo": "Νέο σημείωμα",
"saved": "Αποθηκεύτηκε",
"validation": {
@@ -247,6 +244,32 @@
"save-in-progress": "Αποθήκευση σε εξέλιξη",
"unsupported-attachment-image-url": "Μη υποστηριζόμενη διεύθυνση URL εικόνας συνημμένου: {{url}}",
"wait-for-upload": "Περιμένετε να ολοκληρωθεί η μεταφόρτωση"
+ },
+ "blocks": {
+ "task": "Εργασία",
+ "quote": "Παράθεση",
+ "table": "Πίνακας",
+ "divider": "Διαχωριστικό",
+ "no-results": "Κανένα αποτέλεσμα",
+ "commands": "Εντολές",
+ "loading": "Φόρτωση…",
+ "duplicate": "Δημιουργία αντιγράφου",
+ "inline-code": "Κώδικας",
+ "link-placeholder": "Επικολλήστε ή πληκτρολογήστε έναν σύνδεσμο…",
+ "remove-link": "Κατάργηση συνδέσμου",
+ "slash-hint": "Πληκτρολογήστε «/» για εντολές",
+ "block-menu": "Άνοιγμα μενού μπλοκ",
+ "list-hint": "Λίστα",
+ "plain-text": "κείμενο",
+ "add-row-above": "Προσθήκη γραμμής από πάνω",
+ "add-row-below": "Προσθήκη γραμμής από κάτω",
+ "add-column-left": "Προσθήκη στήλης αριστερά",
+ "add-column-right": "Προσθήκη στήλης δεξιά",
+ "delete-row": "Διαγραφή γραμμής",
+ "delete-column": "Διαγραφή στήλης",
+ "align-left": "Στοίχιση αριστερά",
+ "align-center": "Στοίχιση στο κέντρο",
+ "align-right": "Στοίχιση δεξιά"
}
},
"inbox": {
diff --git a/web/src/locales/en-GB.json b/web/src/locales/en-GB.json
index b54c1853f..cbbcb8cc8 100644
--- a/web/src/locales/en-GB.json
+++ b/web/src/locales/en-GB.json
@@ -181,9 +181,7 @@
"transcribing": "Transcribing..."
},
"comment": "Comment",
- "formatting-toolbar": "Formatting toolbar",
"format": {
- "heading": "Heading",
"paragraph": "Paragraph",
"heading-1": "Heading 1",
"heading-2": "Heading 2",
@@ -195,8 +193,7 @@
"bullet-list": "Bullet list",
"ordered-list": "Numbered list",
"task-list": "To-do list",
- "link": "Link",
- "more": "More formatting"
+ "link": "Link"
},
"new-memo": "New memo",
"saved": "Saved",
@@ -209,6 +206,32 @@
"save-in-progress": "Save in progress",
"unsupported-attachment-image-url": "Unsupported attachment image URL: {{url}}",
"wait-for-upload": "Wait for upload to complete"
+ },
+ "blocks": {
+ "task": "Task",
+ "quote": "Quote",
+ "table": "Table",
+ "divider": "Divider",
+ "no-results": "No results",
+ "commands": "Commands",
+ "loading": "Loading…",
+ "duplicate": "Duplicate",
+ "inline-code": "Code",
+ "link-placeholder": "Paste or type a link…",
+ "remove-link": "Remove link",
+ "slash-hint": "Type '/' for commands",
+ "block-menu": "Open block menu",
+ "list-hint": "List",
+ "plain-text": "text",
+ "add-row-above": "Add row above",
+ "add-row-below": "Add row below",
+ "add-column-left": "Add column left",
+ "add-column-right": "Add column right",
+ "delete-row": "Delete row",
+ "delete-column": "Delete column",
+ "align-left": "Align left",
+ "align-center": "Align centre",
+ "align-right": "Align right"
}
},
"inbox": {
diff --git a/web/src/locales/en.json b/web/src/locales/en.json
index a581e54ee..aa0172ad7 100644
--- a/web/src/locales/en.json
+++ b/web/src/locales/en.json
@@ -248,9 +248,7 @@
"exit-focus-mode": "Exit Focus Mode",
"focus-mode": "Focus Mode",
"comment": "Comment",
- "formatting-toolbar": "Formatting toolbar",
"format": {
- "heading": "Heading",
"paragraph": "Paragraph",
"heading-1": "Heading 1",
"heading-2": "Heading 2",
@@ -262,8 +260,7 @@
"bullet-list": "Bullet list",
"ordered-list": "Numbered list",
"task-list": "To-do list",
- "link": "Link",
- "more": "More formatting"
+ "link": "Link"
},
"insert-menu": {
"add-attachment": "Add attachment",
@@ -306,6 +303,32 @@
"transcribe-success": "Transcription added",
"transcribing": "Transcribing...",
"trigger": "Record audio"
+ },
+ "blocks": {
+ "task": "Task",
+ "quote": "Quote",
+ "table": "Table",
+ "divider": "Divider",
+ "no-results": "No results",
+ "commands": "Commands",
+ "loading": "Loading…",
+ "duplicate": "Duplicate",
+ "inline-code": "Code",
+ "link-placeholder": "Paste or type a link…",
+ "remove-link": "Remove link",
+ "slash-hint": "Type '/' for commands",
+ "block-menu": "Open block menu",
+ "list-hint": "List",
+ "plain-text": "text",
+ "add-row-above": "Add row above",
+ "add-row-below": "Add row below",
+ "add-column-left": "Add column left",
+ "add-column-right": "Add column right",
+ "delete-row": "Delete row",
+ "delete-column": "Delete column",
+ "align-left": "Align left",
+ "align-center": "Align center",
+ "align-right": "Align right"
}
},
"inbox": {
diff --git a/web/src/locales/es.json b/web/src/locales/es.json
index e2bc7b664..8c5f9a4bf 100644
--- a/web/src/locales/es.json
+++ b/web/src/locales/es.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Bloque de código",
"link": "Enlace",
- "heading": "Encabezado",
"paragraph": "Párrafo",
"heading-1": "Encabezado 1",
"heading-2": "Encabezado 2",
@@ -193,11 +192,9 @@
"strikethrough": "Tachado",
"bullet-list": "Lista con viñetas",
"ordered-list": "Lista numerada",
- "task-list": "Lista de tareas",
- "more": "Más formato"
+ "task-list": "Lista de tareas"
},
"comment": "Comentario",
- "formatting-toolbar": "Barra de herramientas de formato",
"new-memo": "Nuevo memo",
"saved": "Guardado",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Guardado en curso",
"unsupported-attachment-image-url": "URL de imagen de adjunto no compatible: {{url}}",
"wait-for-upload": "Esperar a que finalice la carga"
+ },
+ "blocks": {
+ "task": "Tarea",
+ "quote": "Cita",
+ "table": "Tabla",
+ "divider": "Separador",
+ "no-results": "Sin resultados",
+ "commands": "Comandos",
+ "loading": "Cargando…",
+ "duplicate": "Duplicar",
+ "inline-code": "Código",
+ "link-placeholder": "Pega o escribe un enlace…",
+ "remove-link": "Quitar enlace",
+ "slash-hint": "Escribe «/» para ver los comandos",
+ "block-menu": "Abrir menú del bloque",
+ "list-hint": "Lista",
+ "plain-text": "texto",
+ "add-row-above": "Agregar fila arriba",
+ "add-row-below": "Agregar fila abajo",
+ "add-column-left": "Agregar columna a la izquierda",
+ "add-column-right": "Agregar columna a la derecha",
+ "delete-row": "Eliminar fila",
+ "delete-column": "Eliminar columna",
+ "align-left": "Alinear a la izquierda",
+ "align-center": "Centrar",
+ "align-right": "Alinear a la derecha"
}
},
"inbox": {
diff --git a/web/src/locales/et.json b/web/src/locales/et.json
index d3f7a433a..df5f81ea3 100644
--- a/web/src/locales/et.json
+++ b/web/src/locales/et.json
@@ -221,7 +221,6 @@
"format": {
"code-block": "Koodiplokk",
"link": "Link",
- "heading": "Pealkiri",
"paragraph": "Lõik",
"heading-1": "Pealkiri 1",
"heading-2": "Pealkiri 2",
@@ -231,11 +230,9 @@
"strikethrough": "Läbikriipsutatud kiri",
"bullet-list": "Täpploend",
"ordered-list": "Numberloend",
- "task-list": "Ülesannete loend",
- "more": "Rohkem vormindust"
+ "task-list": "Ülesannete loend"
},
"comment": "Kommentaar",
- "formatting-toolbar": "Vormindamise tööriistariba",
"new-memo": "Uus memo",
"saved": "Salvestatud",
"validation": {
@@ -247,6 +244,32 @@
"save-in-progress": "Salvestamine pooleli",
"unsupported-attachment-image-url": "Toetamata manuse pildi URL: {{url}}",
"wait-for-upload": "Oota üleslaadimise lõppemist"
+ },
+ "blocks": {
+ "task": "Ülesanne",
+ "quote": "Tsitaat",
+ "table": "Tabel",
+ "divider": "Eraldaja",
+ "no-results": "Tulemusi pole",
+ "commands": "Käsud",
+ "loading": "Laadimine…",
+ "duplicate": "Dubleeri",
+ "inline-code": "Kood",
+ "link-placeholder": "Kleebi või sisesta link…",
+ "remove-link": "Eemalda link",
+ "slash-hint": "Käskude jaoks sisesta „/“",
+ "block-menu": "Ava ploki menüü",
+ "list-hint": "Loend",
+ "plain-text": "tekst",
+ "add-row-above": "Lisa rida ülespoole",
+ "add-row-below": "Lisa rida allapoole",
+ "add-column-left": "Lisa veerg vasakule",
+ "add-column-right": "Lisa veerg paremale",
+ "delete-row": "Kustuta rida",
+ "delete-column": "Kustuta veerg",
+ "align-left": "Joonda vasakule",
+ "align-center": "Joonda keskele",
+ "align-right": "Joonda paremale"
}
},
"inbox": {
diff --git a/web/src/locales/fa.json b/web/src/locales/fa.json
index c9d347b36..b516758d6 100644
--- a/web/src/locales/fa.json
+++ b/web/src/locales/fa.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "بلوک کد",
"link": "پیوست",
- "heading": "عنوان",
"paragraph": "پاراگراف",
"heading-1": "عنوان 1",
"heading-2": "عنوان 2",
@@ -193,11 +192,9 @@
"strikethrough": "خط‌خورده",
"bullet-list": "فهرست نشانه‌دار",
"ordered-list": "فهرست شماره‌دار",
- "task-list": "فهرست کارها",
- "more": "قالب‌بندی بیشتر"
+ "task-list": "فهرست کارها"
},
"comment": "نظر",
- "formatting-toolbar": "نوار ابزار قالب‌بندی",
"new-memo": "یادداشت جدید",
"saved": "ذخیره شد",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "در حال ذخیره در حال انجام است",
"unsupported-attachment-image-url": "آدرس تصویر پیوست پشتیبانی نشده: {{url}}",
"wait-for-upload": "منتظر بمانید تا آپلود کامل شود"
+ },
+ "blocks": {
+ "task": "کار",
+ "quote": "نقل‌قول",
+ "table": "جدول",
+ "divider": "جداکننده",
+ "no-results": "نتیجه‌ای یافت نشد",
+ "commands": "فرمان‌ها",
+ "loading": "در حال بارگذاری…",
+ "duplicate": "تکثیر",
+ "inline-code": "کد",
+ "link-placeholder": "پیوندی را بچسبانید یا تایپ کنید…",
+ "remove-link": "حذف پیوند",
+ "slash-hint": "برای فرمان‌ها «/» را تایپ کنید",
+ "block-menu": "باز کردن منوی بلوک",
+ "list-hint": "فهرست",
+ "plain-text": "متن",
+ "add-row-above": "افزودن ردیف در بالا",
+ "add-row-below": "افزودن ردیف در پایین",
+ "add-column-left": "افزودن ستون در چپ",
+ "add-column-right": "افزودن ستون در راست",
+ "delete-row": "حذف ردیف",
+ "delete-column": "حذف ستون",
+ "align-left": "تراز به چپ",
+ "align-center": "تراز به وسط",
+ "align-right": "تراز به راست"
}
},
"inbox": {
diff --git a/web/src/locales/fi.json b/web/src/locales/fi.json
index 204e33d92..7cd55ce44 100644
--- a/web/src/locales/fi.json
+++ b/web/src/locales/fi.json
@@ -221,7 +221,6 @@
"format": {
"code-block": "Koodilohko",
"link": "Linkki",
- "heading": "Otsikko",
"paragraph": "Kappale",
"heading-1": "Otsikko 1",
"heading-2": "Otsikko 2",
@@ -231,11 +230,9 @@
"strikethrough": "Yliviivaus",
"bullet-list": "Luettelomerkkiluettelo",
"ordered-list": "Numeroitu luettelo",
- "task-list": "Tehtävälista",
- "more": "Lisää muotoiluja"
+ "task-list": "Tehtävälista"
},
"comment": "Kommentti",
- "formatting-toolbar": "Muotoilupalkki",
"new-memo": "Uusi muistio",
"saved": "Tallennettu",
"validation": {
@@ -247,6 +244,32 @@
"save-in-progress": "Tallennus käynnissä",
"unsupported-attachment-image-url": "Liitteenä olevan kuvan URL-osoitetta ei tueta: {{url}}",
"wait-for-upload": "Odota latauksen valmistumista"
+ },
+ "blocks": {
+ "task": "Tehtävä",
+ "quote": "Lainaus",
+ "table": "Taulukko",
+ "divider": "Erotin",
+ "no-results": "Ei tuloksia",
+ "commands": "Komennot",
+ "loading": "Ladataan…",
+ "duplicate": "Monista",
+ "inline-code": "Koodi",
+ "link-placeholder": "Liitä tai kirjoita linkki…",
+ "remove-link": "Poista linkki",
+ "slash-hint": "Kirjoita ”/” nähdäksesi komennot",
+ "block-menu": "Avaa lohkovalikko",
+ "list-hint": "Luettelo",
+ "plain-text": "teksti",
+ "add-row-above": "Lisää rivi yläpuolelle",
+ "add-row-below": "Lisää rivi alapuolelle",
+ "add-column-left": "Lisää sarake vasemmalle",
+ "add-column-right": "Lisää sarake oikealle",
+ "delete-row": "Poista rivi",
+ "delete-column": "Poista sarake",
+ "align-left": "Tasaa vasemmalle",
+ "align-center": "Keskitä",
+ "align-right": "Tasaa oikealle"
}
},
"inbox": {
diff --git a/web/src/locales/fr.json b/web/src/locales/fr.json
index 24bd1f0ca..824ba9c89 100644
--- a/web/src/locales/fr.json
+++ b/web/src/locales/fr.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Bloc de code",
"link": "Lien",
- "heading": "Titre",
"paragraph": "Paragraphe",
"heading-1": "Titre 1",
"heading-2": "Titre 2",
@@ -193,11 +192,9 @@
"strikethrough": "Barré",
"bullet-list": "Liste à puces",
"ordered-list": "Liste numérotée",
- "task-list": "Liste de tâches",
- "more": "Options de mise en forme supplémentaires"
+ "task-list": "Liste de tâches"
},
"comment": "Commentaire",
- "formatting-toolbar": "Barre d'outils de mise en forme",
"new-memo": "Nouvelle note",
"saved": "Enregistrée",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Enregistrement en cours",
"unsupported-attachment-image-url": "URL d'image de pièce jointe non prise en charge : {{url}}",
"wait-for-upload": "Veuillez patienter jusqu'à la fin du chargement"
+ },
+ "blocks": {
+ "task": "Tâche",
+ "quote": "Citation",
+ "table": "Tableau",
+ "divider": "Séparateur",
+ "no-results": "Aucun résultat",
+ "commands": "Commandes",
+ "loading": "Chargement…",
+ "duplicate": "Dupliquer",
+ "inline-code": "Code",
+ "link-placeholder": "Collez ou saisissez un lien…",
+ "remove-link": "Supprimer le lien",
+ "slash-hint": "Tapez « / » pour les commandes",
+ "block-menu": "Ouvrir le menu du bloc",
+ "list-hint": "Liste",
+ "plain-text": "texte",
+ "add-row-above": "Ajouter une ligne au-dessus",
+ "add-row-below": "Ajouter une ligne en dessous",
+ "add-column-left": "Ajouter une colonne à gauche",
+ "add-column-right": "Ajouter une colonne à droite",
+ "delete-row": "Supprimer la ligne",
+ "delete-column": "Supprimer la colonne",
+ "align-left": "Aligner à gauche",
+ "align-center": "Centrer",
+ "align-right": "Aligner à droite"
}
},
"inbox": {
diff --git a/web/src/locales/gl.json b/web/src/locales/gl.json
index 054669e12..638aea7cf 100644
--- a/web/src/locales/gl.json
+++ b/web/src/locales/gl.json
@@ -182,7 +182,6 @@
},
"format": {
"code-block": "Bloque de código",
- "heading": "Título",
"paragraph": "Parágrafo",
"heading-1": "Título 1",
"heading-2": "Título 2",
@@ -193,11 +192,9 @@
"bullet-list": "Viñeta lista",
"ordered-list": "Lista numerada",
"task-list": "Lista de tarefas pendentes",
- "link": "Ligazón",
- "more": "Máis formato"
+ "link": "Ligazón"
},
"comment": "Comentario",
- "formatting-toolbar": "Barra de ferramentas de formato",
"new-memo": "Nova nota",
"saved": "Gardada",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Gardar en curso",
"unsupported-attachment-image-url": "URL da imaxe do anexo non compatible: {{url}}",
"wait-for-upload": "Agardar a que se complete a subida"
+ },
+ "blocks": {
+ "task": "Tarefa",
+ "quote": "Cita",
+ "table": "Táboa",
+ "divider": "Separador",
+ "no-results": "Sen resultados",
+ "commands": "Comandos",
+ "loading": "Cargando…",
+ "duplicate": "Duplicar",
+ "inline-code": "Código",
+ "link-placeholder": "Pega ou escribe unha ligazón…",
+ "remove-link": "Quitar ligazón",
+ "slash-hint": "Escribe «/» para ver os comandos",
+ "block-menu": "Abrir o menú do bloque",
+ "list-hint": "Lista",
+ "plain-text": "texto",
+ "add-row-above": "Engadir fila arriba",
+ "add-row-below": "Engadir fila abaixo",
+ "add-column-left": "Engadir columna á esquerda",
+ "add-column-right": "Engadir columna á dereita",
+ "delete-row": "Eliminar fila",
+ "delete-column": "Eliminar columna",
+ "align-left": "Aliñar á esquerda",
+ "align-center": "Centrar",
+ "align-right": "Aliñar á dereita"
}
},
"inbox": {
diff --git a/web/src/locales/he.json b/web/src/locales/he.json
index d7b57460f..f6645e14d 100644
--- a/web/src/locales/he.json
+++ b/web/src/locales/he.json
@@ -221,9 +221,7 @@
"any-thoughts": "יש מחשבות...",
"exit-focus-mode": "יציאה ממצב מיקוד",
"focus-mode": "מצב מיקוד",
- "formatting-toolbar": "סרגל עיצוב",
"format": {
- "heading": "כותרת",
"paragraph": "פסקה",
"heading-1": "כותרת 1",
"heading-2": "כותרת 2",
@@ -235,8 +233,7 @@
"bullet-list": "רשימת תבליטים",
"ordered-list": "רשימה ממוספרת",
"task-list": "רשימת משימות",
- "link": "קישור",
- "more": "אפשרויות עיצוב נוספות"
+ "link": "קישור"
},
"insert-menu": {
"add-attachment": "הוסף קובץ מצורף",
@@ -280,7 +277,33 @@
},
"comment": "תגובה",
"new-memo": "תזכיר חדש",
- "saved": "נשמר"
+ "saved": "נשמר",
+ "blocks": {
+ "task": "משימה",
+ "quote": "ציטוט",
+ "table": "טבלה",
+ "divider": "קו מפריד",
+ "no-results": "אין תוצאות",
+ "commands": "פקודות",
+ "loading": "טוען…",
+ "duplicate": "שכפל",
+ "inline-code": "קוד",
+ "link-placeholder": "הדבק או הקלד קישור…",
+ "remove-link": "הסר קישור",
+ "slash-hint": "הקלד \"/\" לפקודות",
+ "block-menu": "פתח תפריט בלוק",
+ "list-hint": "רשימה",
+ "plain-text": "טקסט",
+ "add-row-above": "הוסף שורה מעל",
+ "add-row-below": "הוסף שורה מתחת",
+ "add-column-left": "הוסף עמודה משמאל",
+ "add-column-right": "הוסף עמודה מימין",
+ "delete-row": "מחק שורה",
+ "delete-column": "מחק עמודה",
+ "align-left": "יישר לשמאל",
+ "align-center": "מרכז",
+ "align-right": "יישר לימין"
+ }
},
"inbox": {
"failed-to-load": "טעינת פריט מתיבת הדואר הנכנס נכשלה",
diff --git a/web/src/locales/hi.json b/web/src/locales/hi.json
index 4083a542a..e3b925ebb 100644
--- a/web/src/locales/hi.json
+++ b/web/src/locales/hi.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "कोड ब्लॉक",
"link": "लिंक",
- "heading": "हेडिंग",
"paragraph": "पैराग्राफ़",
"heading-1": "हेडिंग 1",
"heading-2": "हेडिंग 2",
@@ -193,11 +192,9 @@
"strikethrough": "स्ट्राइकथ्रू",
"bullet-list": "बुलेट लिस्ट",
"ordered-list": "नंबर वाली लिस्ट",
- "task-list": "टू-डू लिस्ट",
- "more": "और फ़ॉर्मेटिंग"
+ "task-list": "टू-डू लिस्ट"
},
"comment": "कमेंट",
- "formatting-toolbar": "फ़ॉर्मेटिंग टूलबार",
"new-memo": "नया मेमो",
"saved": "सेव किया गया",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "सेव हो रहा है",
"unsupported-attachment-image-url": "अनसपोर्टेड अटैचमेंट इमेज URL: {{url}}",
"wait-for-upload": "अपलोड पूरा होने का इंतज़ार करें"
+ },
+ "blocks": {
+ "task": "टास्क",
+ "quote": "कोट",
+ "table": "टेबल",
+ "divider": "डिवाइडर",
+ "no-results": "कोई परिणाम नहीं",
+ "commands": "कमांड",
+ "loading": "लोड हो रहा है…",
+ "duplicate": "डुप्लिकेट करें",
+ "inline-code": "कोड",
+ "link-placeholder": "लिंक पेस्ट करें या टाइप करें…",
+ "remove-link": "लिंक हटाएँ",
+ "slash-hint": "कमांड के लिए '/' टाइप करें",
+ "block-menu": "ब्लॉक मेन्यू खोलें",
+ "list-hint": "लिस्ट",
+ "plain-text": "टेक्स्ट",
+ "add-row-above": "ऊपर पंक्ति जोड़ें",
+ "add-row-below": "नीचे पंक्ति जोड़ें",
+ "add-column-left": "बाईं ओर कॉलम जोड़ें",
+ "add-column-right": "दाईं ओर कॉलम जोड़ें",
+ "delete-row": "पंक्ति हटाएँ",
+ "delete-column": "कॉलम हटाएँ",
+ "align-left": "बाएँ संरेखित करें",
+ "align-center": "बीच में संरेखित करें",
+ "align-right": "दाएँ संरेखित करें"
}
},
"inbox": {
diff --git a/web/src/locales/hr.json b/web/src/locales/hr.json
index 4a5853315..da87bd240 100644
--- a/web/src/locales/hr.json
+++ b/web/src/locales/hr.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Blok koda",
"link": "Link",
- "heading": "Naslov",
"paragraph": "Odlomak",
"heading-1": "Naslov 1",
"heading-2": "Naslov 2",
@@ -193,11 +192,9 @@
"strikethrough": "Precrtano",
"bullet-list": "Grafička oznaka popis",
"ordered-list": "Numerirani popis",
- "task-list": "Popis obaveza",
- "more": "Više formatiranja"
+ "task-list": "Popis obaveza"
},
"comment": "Komentar",
- "formatting-toolbar": "Alatna traka za oblikovanje",
"new-memo": "Novi podsjetnik",
"saved": "Spremljeno",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Spremanje u tijeku",
"unsupported-attachment-image-url": "Nepodržani URL slike privitka: {{url}}",
"wait-for-upload": "Pričekajte da se prijenos dovrši"
+ },
+ "blocks": {
+ "task": "Zadatak",
+ "quote": "Citat",
+ "table": "Tablica",
+ "divider": "Razdjelnik",
+ "no-results": "Nema rezultata",
+ "commands": "Naredbe",
+ "loading": "Učitavanje…",
+ "duplicate": "Dupliciraj",
+ "inline-code": "Kod",
+ "link-placeholder": "Zalijepi ili upiši link…",
+ "remove-link": "Ukloni link",
+ "slash-hint": "Upiši „/” za naredbe",
+ "block-menu": "Otvori izbornik bloka",
+ "list-hint": "Popis",
+ "plain-text": "tekst",
+ "add-row-above": "Dodaj redak iznad",
+ "add-row-below": "Dodaj redak ispod",
+ "add-column-left": "Dodaj stupac lijevo",
+ "add-column-right": "Dodaj stupac desno",
+ "delete-row": "Obriši redak",
+ "delete-column": "Obriši stupac",
+ "align-left": "Poravnaj lijevo",
+ "align-center": "Poravnaj po sredini",
+ "align-right": "Poravnaj desno"
}
},
"inbox": {
diff --git a/web/src/locales/hu.json b/web/src/locales/hu.json
index 6db8d45e3..1777b3b83 100644
--- a/web/src/locales/hu.json
+++ b/web/src/locales/hu.json
@@ -182,7 +182,6 @@
},
"format": {
"code-block": "Kódblokk",
- "heading": "Címsor",
"paragraph": "Bekezdés",
"heading-1": "1. címsor",
"heading-2": "2. címsor",
@@ -193,11 +192,9 @@
"bullet-list": "Felsorolás",
"ordered-list": "Számozott lista",
"task-list": "Tennivalók",
- "link": "Link",
- "more": "További formázás"
+ "link": "Link"
},
"comment": "Megjegyzés",
- "formatting-toolbar": "Formázási eszköztár",
"new-memo": "Új feljegyzés",
"saved": "Mentve",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Mentés folyamatban",
"unsupported-attachment-image-url": "Nem támogatott mellékletkép URL: {{url}}",
"wait-for-upload": "Várja meg a feltöltés befejezését"
+ },
+ "blocks": {
+ "task": "Feladat",
+ "quote": "Idézet",
+ "table": "Táblázat",
+ "divider": "Elválasztó",
+ "no-results": "Nincs találat",
+ "commands": "Parancsok",
+ "loading": "Betöltés…",
+ "duplicate": "Duplikálás",
+ "inline-code": "Kód",
+ "link-placeholder": "Illessz be vagy írj be egy linket…",
+ "remove-link": "Link eltávolítása",
+ "slash-hint": "Írd be a „/” karaktert a parancsokhoz",
+ "block-menu": "Blokkmenü megnyitása",
+ "list-hint": "Lista",
+ "plain-text": "szöveg",
+ "add-row-above": "Sor beszúrása fölé",
+ "add-row-below": "Sor beszúrása alá",
+ "add-column-left": "Oszlop beszúrása balra",
+ "add-column-right": "Oszlop beszúrása jobbra",
+ "delete-row": "Sor törlése",
+ "delete-column": "Oszlop törlése",
+ "align-left": "Balra igazítás",
+ "align-center": "Középre igazítás",
+ "align-right": "Jobbra igazítás"
}
},
"inbox": {
diff --git a/web/src/locales/id.json b/web/src/locales/id.json
index 43e74d67e..1ea98d506 100644
--- a/web/src/locales/id.json
+++ b/web/src/locales/id.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Blok Kode",
"link": "Tautan",
- "heading": "Judul",
"paragraph": "Paragraf",
"heading-1": "Judul 1",
"heading-2": "Judul 2",
@@ -193,11 +192,9 @@
"strikethrough": "Garis tengah",
"bullet-list": "Daftar poin",
"ordered-list": "Daftar bernomor",
- "task-list": "Daftar tugas",
- "more": "Pemformatan lainnya"
+ "task-list": "Daftar tugas"
},
"comment": "Komentar",
- "formatting-toolbar": "Toolbar pemformatan",
"new-memo": "Memo baru",
"saved": "Tersimpan",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Penyimpanan sedang berlangsung",
"unsupported-attachment-image-url": "URL gambar lampiran tidak didukung: {{url}}",
"wait-for-upload": "Tunggu hingga unggahan selesai"
+ },
+ "blocks": {
+ "task": "Tugas",
+ "quote": "Kutipan",
+ "table": "Tabel",
+ "divider": "Pemisah",
+ "no-results": "Tidak ada hasil",
+ "commands": "Perintah",
+ "loading": "Memuat…",
+ "duplicate": "Duplikat",
+ "inline-code": "Kode",
+ "link-placeholder": "Tempel atau ketik tautan…",
+ "remove-link": "Hapus tautan",
+ "slash-hint": "Ketik \"/\" untuk perintah",
+ "block-menu": "Buka menu blok",
+ "list-hint": "Daftar",
+ "plain-text": "teks",
+ "add-row-above": "Tambah baris di atas",
+ "add-row-below": "Tambah baris di bawah",
+ "add-column-left": "Tambah kolom di kiri",
+ "add-column-right": "Tambah kolom di kanan",
+ "delete-row": "Hapus baris",
+ "delete-column": "Hapus kolom",
+ "align-left": "Rata kiri",
+ "align-center": "Rata tengah",
+ "align-right": "Rata kanan"
}
},
"inbox": {
diff --git a/web/src/locales/it.json b/web/src/locales/it.json
index 129ce1fe4..b8d6c56ff 100644
--- a/web/src/locales/it.json
+++ b/web/src/locales/it.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Blocco di codice",
"link": "Link",
- "heading": "Intestazione",
"paragraph": "Paragrafo",
"heading-1": "Intestazione 1",
"heading-2": "Intestazione 2",
@@ -193,11 +192,9 @@
"strikethrough": "Barrato",
"bullet-list": "Elenco puntato",
"ordered-list": "Elenco numerato",
- "task-list": "Elenco delle cose da fare",
- "more": "Altre opzioni di formattazione"
+ "task-list": "Elenco delle cose da fare"
},
"comment": "Commento",
- "formatting-toolbar": "Barra degli strumenti di formattazione",
"new-memo": "Nuovo memo",
"saved": "Salvato",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Salvataggio in corso",
"unsupported-attachment-image-url": "URL immagine allegato non supportato: {{url}}",
"wait-for-upload": "Attendi il completamento del caricamento"
+ },
+ "blocks": {
+ "task": "Attività",
+ "quote": "Citazione",
+ "table": "Tabella",
+ "divider": "Divisore",
+ "no-results": "Nessun risultato",
+ "commands": "Comandi",
+ "loading": "Caricamento…",
+ "duplicate": "Duplica",
+ "inline-code": "Codice",
+ "link-placeholder": "Incolla o digita un link…",
+ "remove-link": "Rimuovi link",
+ "slash-hint": "Digita \"/\" per i comandi",
+ "block-menu": "Apri il menu del blocco",
+ "list-hint": "Elenco",
+ "plain-text": "testo",
+ "add-row-above": "Aggiungi riga sopra",
+ "add-row-below": "Aggiungi riga sotto",
+ "add-column-left": "Aggiungi colonna a sinistra",
+ "add-column-right": "Aggiungi colonna a destra",
+ "delete-row": "Elimina riga",
+ "delete-column": "Elimina colonna",
+ "align-left": "Allinea a sinistra",
+ "align-center": "Allinea al centro",
+ "align-right": "Allinea a destra"
}
},
"inbox": {
diff --git a/web/src/locales/ja.json b/web/src/locales/ja.json
index 1a29a3baf..7d0bbb231 100644
--- a/web/src/locales/ja.json
+++ b/web/src/locales/ja.json
@@ -150,7 +150,6 @@
"any-thoughts": "今思ったことは...",
"exit-focus-mode": "フォーカスを終了",
"focus-mode": "フォーカスモード",
- "formatting-toolbar": "書式ツールバー",
"no-changes-detected": "変更はありません",
"save": "保存",
"insert-menu": {
@@ -182,7 +181,6 @@
"trigger": "音声を録音する"
},
"format": {
- "heading": "見出し",
"paragraph": "段落",
"heading-1": "見出し1",
"heading-2": "見出し2",
@@ -194,8 +192,7 @@
"bullet-list": "箇条書きリスト",
"ordered-list": "番号付きリスト",
"task-list": "タスクリスト",
- "link": "リンク",
- "more": "その他の書式"
+ "link": "リンク"
},
"comment": "コメント",
"new-memo": "新しいメモ",
@@ -209,6 +206,32 @@
"save-in-progress": "保存処理中",
"unsupported-attachment-image-url": "サポートされていない添付ファイル画像のURL: {{url}}",
"wait-for-upload": "アップロードが完了するまでお待ちください"
+ },
+ "blocks": {
+ "task": "タスク",
+ "quote": "引用",
+ "table": "表",
+ "divider": "区切り線",
+ "no-results": "結果がありません",
+ "commands": "コマンド",
+ "loading": "読み込み中…",
+ "duplicate": "複製",
+ "inline-code": "コード",
+ "link-placeholder": "リンクを貼り付けまたは入力…",
+ "remove-link": "リンクを削除",
+ "slash-hint": "「/」でコマンドを表示",
+ "block-menu": "ブロックメニューを開く",
+ "list-hint": "リスト",
+ "plain-text": "テキスト",
+ "add-row-above": "上に行を追加",
+ "add-row-below": "下に行を追加",
+ "add-column-left": "左に列を追加",
+ "add-column-right": "右に列を追加",
+ "delete-row": "行を削除",
+ "delete-column": "列を削除",
+ "align-left": "左揃え",
+ "align-center": "中央揃え",
+ "align-right": "右揃え"
}
},
"inbox": {
diff --git a/web/src/locales/ka-GE.json b/web/src/locales/ka-GE.json
index 424efea89..c4edebe34 100644
--- a/web/src/locales/ka-GE.json
+++ b/web/src/locales/ka-GE.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "კოდის ბლოკი",
"link": "ლინკი",
- "heading": "სათაური",
"paragraph": "აბზაცი",
"heading-1": "სათაური 1",
"heading-2": "სათაური 2",
@@ -193,11 +192,9 @@
"strikethrough": "გადახაზვა",
"bullet-list": "პუნქტების სია",
"ordered-list": "დანომრილი სია",
- "task-list": "დავალებების სია",
- "more": "დამატებითი ფორმატირება"
+ "task-list": "დავალებების სია"
},
"comment": "კომენტარი",
- "formatting-toolbar": "ფორმატირების ხელსაწყოთა პანელი",
"new-memo": "ახალი მემო",
"saved": "შენახულია",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "შენახვა მიმდინარეობს",
"unsupported-attachment-image-url": "დანართის სურათის URL, რომელიც არ არის მხარდაჭერილი: {{url}}",
"wait-for-upload": "დაელოდეთ ატვირთვის დასრულებას"
+ },
+ "blocks": {
+ "task": "დავალება",
+ "quote": "ციტატა",
+ "table": "ცხრილი",
+ "divider": "გამყოფი",
+ "no-results": "შედეგები არ არის",
+ "commands": "ბრძანებები",
+ "loading": "იტვირთება…",
+ "duplicate": "დუბლირება",
+ "inline-code": "კოდი",
+ "link-placeholder": "ჩასვით ან აკრიფეთ ლინკი…",
+ "remove-link": "ლინკის წაშლა",
+ "slash-hint": "ბრძანებებისთვის აკრიფეთ „/“",
+ "block-menu": "ბლოკის მენიუს გახსნა",
+ "list-hint": "სია",
+ "plain-text": "ტექსტი",
+ "add-row-above": "მწკრივის დამატება ზემოთ",
+ "add-row-below": "მწკრივის დამატება ქვემოთ",
+ "add-column-left": "სვეტის დამატება მარცხნივ",
+ "add-column-right": "სვეტის დამატება მარჯვნივ",
+ "delete-row": "მწკრივის წაშლა",
+ "delete-column": "სვეტის წაშლა",
+ "align-left": "მარცხნივ სწორება",
+ "align-center": "ცენტრში სწორება",
+ "align-right": "მარჯვნივ სწორება"
}
},
"inbox": {
diff --git a/web/src/locales/ko.json b/web/src/locales/ko.json
index de69dee16..0af772a3f 100644
--- a/web/src/locales/ko.json
+++ b/web/src/locales/ko.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "코드 블록",
"link": "링크",
- "heading": "제목",
"paragraph": "단락",
"heading-1": "제목 1",
"heading-2": "제목 2",
@@ -193,11 +192,9 @@
"strikethrough": "취소선",
"bullet-list": "글머리 기호 목록",
"ordered-list": "번호 매기기 목록",
- "task-list": "할 일 목록",
- "more": "추가 서식 지정"
+ "task-list": "할 일 목록"
},
"comment": "댓글",
- "formatting-toolbar": "서식 도구 모음",
"new-memo": "새 메모",
"saved": "저장됨",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "저장 중",
"unsupported-attachment-image-url": "지원되지 않는 첨부 이미지 URL: {{url}}",
"wait-for-upload": "업로드가 완료될 때까지 기다리세요"
+ },
+ "blocks": {
+ "task": "할 일",
+ "quote": "인용",
+ "table": "표",
+ "divider": "구분선",
+ "no-results": "결과 없음",
+ "commands": "명령어",
+ "loading": "불러오는 중…",
+ "duplicate": "복제",
+ "inline-code": "코드",
+ "link-placeholder": "링크를 붙여넣거나 입력하세요…",
+ "remove-link": "링크 제거",
+ "slash-hint": "'/'를 입력해 명령어 보기",
+ "block-menu": "블록 메뉴 열기",
+ "list-hint": "목록",
+ "plain-text": "텍스트",
+ "add-row-above": "위에 행 추가",
+ "add-row-below": "아래에 행 추가",
+ "add-column-left": "왼쪽에 열 추가",
+ "add-column-right": "오른쪽에 열 추가",
+ "delete-row": "행 삭제",
+ "delete-column": "열 삭제",
+ "align-left": "왼쪽 정렬",
+ "align-center": "가운데 정렬",
+ "align-right": "오른쪽 정렬"
}
},
"inbox": {
diff --git a/web/src/locales/lt.json b/web/src/locales/lt.json
index 7b66fb61d..e7b1eb19d 100644
--- a/web/src/locales/lt.json
+++ b/web/src/locales/lt.json
@@ -221,7 +221,6 @@
"format": {
"code-block": "Kodo blokas",
"link": "Nuoroda",
- "heading": "Antraštė",
"paragraph": "Pastraipa",
"heading-1": "1 antraštė",
"heading-2": "2 antraštė",
@@ -231,11 +230,9 @@
"strikethrough": "Perbrauktas",
"bullet-list": "Ženklelių sąrašas",
"ordered-list": "Numeruotas sąrašas",
- "task-list": "Darbų sąrašas",
- "more": "Daugiau formatavimo"
+ "task-list": "Darbų sąrašas"
},
"comment": "Komentaras",
- "formatting-toolbar": "Formatavimo įrankių juosta",
"new-memo": "Naujas priminimas",
"saved": "Išsaugota",
"validation": {
@@ -247,6 +244,32 @@
"save-in-progress": "Vykdomas išsaugojimas",
"unsupported-attachment-image-url": "Nepalaikomas priedo vaizdo URL: {{url}}",
"wait-for-upload": "Palaukite, kol įkėlimas bus baigtas"
+ },
+ "blocks": {
+ "task": "Užduotis",
+ "quote": "Citata",
+ "table": "Lentelė",
+ "divider": "Skirtukas",
+ "no-results": "Rezultatų nėra",
+ "commands": "Komandos",
+ "loading": "Įkeliama…",
+ "duplicate": "Dubliuoti",
+ "inline-code": "Kodas",
+ "link-placeholder": "Įklijuokite arba įveskite nuorodą…",
+ "remove-link": "Pašalinti nuorodą",
+ "slash-hint": "Įveskite „/“, kad matytumėte komandas",
+ "block-menu": "Atidaryti bloko meniu",
+ "list-hint": "Sąrašas",
+ "plain-text": "tekstas",
+ "add-row-above": "Pridėti eilutę viršuje",
+ "add-row-below": "Pridėti eilutę apačioje",
+ "add-column-left": "Pridėti stulpelį kairėje",
+ "add-column-right": "Pridėti stulpelį dešinėje",
+ "delete-row": "Ištrinti eilutę",
+ "delete-column": "Ištrinti stulpelį",
+ "align-left": "Lygiuoti kairėje",
+ "align-center": "Lygiuoti centre",
+ "align-right": "Lygiuoti dešinėje"
}
},
"inbox": {
diff --git a/web/src/locales/lv.json b/web/src/locales/lv.json
index 3568636a9..195f555d1 100644
--- a/web/src/locales/lv.json
+++ b/web/src/locales/lv.json
@@ -221,7 +221,6 @@
"format": {
"code-block": "Koda bloks",
"link": "Saite",
- "heading": "Virsraksts",
"paragraph": "Rindkopa",
"heading-1": "1. virsraksts",
"heading-2": "2. virsraksts",
@@ -231,11 +230,9 @@
"strikethrough": "Pārsvītrojums",
"bullet-list": "Aizzīmju saraksts",
"ordered-list": "Numurēts saraksts",
- "task-list": "Uzdevumu saraksts",
- "more": "Papildu formatējums"
+ "task-list": "Uzdevumu saraksts"
},
"comment": "Komentārs",
- "formatting-toolbar": "Formatēšanas rīkjosla",
"new-memo": "Jauna piezīme",
"saved": "Saglabāts",
"validation": {
@@ -247,6 +244,32 @@
"save-in-progress": "Notiek saglabāšana",
"unsupported-attachment-image-url": "Neatbalstīts pielikuma attēla URL: {{url}}",
"wait-for-upload": "Pagaidiet, līdz augšupielāde ir pabeigta"
+ },
+ "blocks": {
+ "task": "Uzdevums",
+ "quote": "Citāts",
+ "table": "Tabula",
+ "divider": "Atdalītājs",
+ "no-results": "Nav rezultātu",
+ "commands": "Komandas",
+ "loading": "Ielādē…",
+ "duplicate": "Dublēt",
+ "inline-code": "Kods",
+ "link-placeholder": "Ielīmējiet vai ierakstiet saiti…",
+ "remove-link": "Noņemt saiti",
+ "slash-hint": "Ierakstiet “/”, lai skatītu komandas",
+ "block-menu": "Atvērt bloka izvēlni",
+ "list-hint": "Saraksts",
+ "plain-text": "teksts",
+ "add-row-above": "Pievienot rindu augšā",
+ "add-row-below": "Pievienot rindu apakšā",
+ "add-column-left": "Pievienot kolonnu pa kreisi",
+ "add-column-right": "Pievienot kolonnu pa labi",
+ "delete-row": "Dzēst rindu",
+ "delete-column": "Dzēst kolonnu",
+ "align-left": "Līdzināt pa kreisi",
+ "align-center": "Centrēt",
+ "align-right": "Līdzināt pa labi"
}
},
"inbox": {
diff --git a/web/src/locales/mr.json b/web/src/locales/mr.json
index 42031bc32..2cfaf616f 100644
--- a/web/src/locales/mr.json
+++ b/web/src/locales/mr.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "कोड ब्लॉक",
"link": "लिंक",
- "heading": "शीर्षक",
"paragraph": "परिच्छेद",
"heading-1": "शीर्षक १",
"heading-2": "शीर्षक २",
@@ -193,11 +192,9 @@
"strikethrough": "मध्यरेषांकित",
"bullet-list": "बुलेट यादी",
"ordered-list": "क्रमांकित यादी",
- "task-list": "कामांची यादी",
- "more": "अधिक स्वरूपन"
+ "task-list": "कामांची यादी"
},
"comment": "टिप्पणी",
- "formatting-toolbar": "फॉरमॅटिंग टूलबार",
"new-memo": "नवीन मेमो",
"saved": "जतन केले",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "जतन करण्याची प्रक्रिया सुरू आहे",
"unsupported-attachment-image-url": "असमर्थित संलग्नक प्रतिमेचा URL: {{url}}",
"wait-for-upload": "अपलोड पूर्ण होण्याची प्रतीक्षा करा"
+ },
+ "blocks": {
+ "task": "काम",
+ "quote": "अवतरण",
+ "table": "सारणी",
+ "divider": "विभाजक",
+ "no-results": "कोणतेही परिणाम नाहीत",
+ "commands": "आदेश",
+ "loading": "लोड होत आहे…",
+ "duplicate": "डुप्लिकेट करा",
+ "inline-code": "कोड",
+ "link-placeholder": "लिंक पेस्ट करा किंवा टाइप करा…",
+ "remove-link": "लिंक काढा",
+ "slash-hint": "आदेशांसाठी '/' टाइप करा",
+ "block-menu": "ब्लॉक मेनू उघडा",
+ "list-hint": "यादी",
+ "plain-text": "मजकूर",
+ "add-row-above": "वर ओळ जोडा",
+ "add-row-below": "खाली ओळ जोडा",
+ "add-column-left": "डावीकडे स्तंभ जोडा",
+ "add-column-right": "उजवीकडे स्तंभ जोडा",
+ "delete-row": "ओळ हटवा",
+ "delete-column": "स्तंभ हटवा",
+ "align-left": "डावीकडे संरेखित करा",
+ "align-center": "मध्यभागी संरेखित करा",
+ "align-right": "उजवीकडे संरेखित करा"
}
},
"inbox": {
diff --git a/web/src/locales/nb.json b/web/src/locales/nb.json
index 0072f1bdb..b88918ed1 100644
--- a/web/src/locales/nb.json
+++ b/web/src/locales/nb.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Kodeblokk",
"link": "Link",
- "heading": "Overskrift",
"paragraph": "Avsnitt",
"heading-1": "Overskrift 1",
"heading-2": "Overskrift 2",
@@ -193,11 +192,9 @@
"strikethrough": "Gjennomstreking",
"bullet-list": "Punkttegn liste",
"ordered-list": "Nummerert liste",
- "task-list": "Gjøremålsliste",
- "more": "Mer formatering"
+ "task-list": "Gjøremålsliste"
},
"comment": "Kommentar",
- "formatting-toolbar": "Formateringsverktøylinje",
"new-memo": "Nytt notat",
"saved": "Lagret",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Lagring pågår",
"unsupported-attachment-image-url": "Ustøttet vedleggsbilde-URL: {{url}}",
"wait-for-upload": "Vent til opplastingen er fullført"
+ },
+ "blocks": {
+ "task": "Gjøremål",
+ "quote": "Sitat",
+ "table": "Tabell",
+ "divider": "Skillelinje",
+ "no-results": "Ingen resultater",
+ "commands": "Kommandoer",
+ "loading": "Laster inn…",
+ "duplicate": "Dupliser",
+ "inline-code": "Kode",
+ "link-placeholder": "Lim inn eller skriv en link…",
+ "remove-link": "Fjern link",
+ "slash-hint": "Skriv «/» for kommandoer",
+ "block-menu": "Åpne blokkmeny",
+ "list-hint": "Liste",
+ "plain-text": "tekst",
+ "add-row-above": "Legg til rad over",
+ "add-row-below": "Legg til rad under",
+ "add-column-left": "Legg til kolonne til venstre",
+ "add-column-right": "Legg til kolonne til høyre",
+ "delete-row": "Slett rad",
+ "delete-column": "Slett kolonne",
+ "align-left": "Venstrejuster",
+ "align-center": "Midtstill",
+ "align-right": "Høyrejuster"
}
},
"inbox": {
diff --git a/web/src/locales/nl.json b/web/src/locales/nl.json
index edf77d466..14ad1bca9 100644
--- a/web/src/locales/nl.json
+++ b/web/src/locales/nl.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Codeblok",
"link": "Link",
- "heading": "Koptekst",
"paragraph": "Alinea",
"heading-1": "Koptekst 1",
"heading-2": "Koptekst 2",
@@ -193,11 +192,9 @@
"strikethrough": "Doorhalen",
"bullet-list": "Opsommingstekens",
"ordered-list": "Genummerde lijst",
- "task-list": "Takenlijst",
- "more": "Meer opmaakopties"
+ "task-list": "Takenlijst"
},
"comment": "Opmerking",
- "formatting-toolbar": "Opmaakwerkbalk",
"new-memo": "Nieuwe memo",
"saved": "Opgeslagen",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Opslaan bezig",
"unsupported-attachment-image-url": "Niet-ondersteunde URL voor bijlageafbeelding: {{url}}",
"wait-for-upload": "Wachten tot de upload is voltooid"
+ },
+ "blocks": {
+ "task": "Taak",
+ "quote": "Citaat",
+ "table": "Tabel",
+ "divider": "Scheidingslijn",
+ "no-results": "Geen resultaten",
+ "commands": "Opdrachten",
+ "loading": "Laden…",
+ "duplicate": "Dupliceren",
+ "inline-code": "Code",
+ "link-placeholder": "Plak of typ een link…",
+ "remove-link": "Link verwijderen",
+ "slash-hint": "Typ '/' voor opdrachten",
+ "block-menu": "Blokmenu openen",
+ "list-hint": "Lijst",
+ "plain-text": "tekst",
+ "add-row-above": "Rij boven invoegen",
+ "add-row-below": "Rij onder invoegen",
+ "add-column-left": "Kolom links invoegen",
+ "add-column-right": "Kolom rechts invoegen",
+ "delete-row": "Rij verwijderen",
+ "delete-column": "Kolom verwijderen",
+ "align-left": "Links uitlijnen",
+ "align-center": "Centreren",
+ "align-right": "Rechts uitlijnen"
}
},
"inbox": {
diff --git a/web/src/locales/nn.json b/web/src/locales/nn.json
index 52b90a378..2bd1d00cc 100644
--- a/web/src/locales/nn.json
+++ b/web/src/locales/nn.json
@@ -246,19 +246,16 @@
"bold": "Feit skrift",
"bullet-list": "Punktliste",
"code-block": "Kodeblokk",
- "heading": "Overskrift",
"heading-1": "Overskrift 1",
"heading-2": "Overskrift 2",
"heading-3": "Overskrift 3",
"italic": "Kursiv",
"link": "Lenkje",
- "more": "Meir formatering",
"ordered-list": "Nummerert liste",
"paragraph": "Avsnitt",
"strikethrough": "Gjennomstreking",
"task-list": "Gjeremålsliste"
},
- "formatting-toolbar": "Verktyline for formatering",
"insert-menu": {
"add-attachment": "Legg til vedlegg",
"add-location": "Legg til stad",
@@ -285,6 +282,32 @@
"save-in-progress": "Lagring går føre seg",
"unsupported-attachment-image-url": "Biletadressa til vedlegget er ikkje støtta: {{url}}",
"wait-for-upload": "Vent til opplastinga er ferdig"
+ },
+ "blocks": {
+ "task": "Gjeremål",
+ "quote": "Sitat",
+ "table": "Tabell",
+ "divider": "Skiljelinje",
+ "no-results": "Ingen resultat",
+ "commands": "Kommandoar",
+ "loading": "Lastar inn…",
+ "duplicate": "Dupliser",
+ "inline-code": "Kode",
+ "link-placeholder": "Lim inn eller skriv ei lenkje…",
+ "remove-link": "Fjern lenkje",
+ "slash-hint": "Skriv «/» for kommandoar",
+ "block-menu": "Opne blokkmeny",
+ "list-hint": "Liste",
+ "plain-text": "tekst",
+ "add-row-above": "Legg til rad over",
+ "add-row-below": "Legg til rad under",
+ "add-column-left": "Legg til kolonne til venstre",
+ "add-column-right": "Legg til kolonne til høgre",
+ "delete-row": "Slett rad",
+ "delete-column": "Slett kolonne",
+ "align-left": "Venstrejuster",
+ "align-center": "Midtstill",
+ "align-right": "Høgrejuster"
}
},
"inbox": {
diff --git a/web/src/locales/pl.json b/web/src/locales/pl.json
index 111a90cfa..fc8271f4d 100644
--- a/web/src/locales/pl.json
+++ b/web/src/locales/pl.json
@@ -151,7 +151,6 @@
"exit-focus-mode": "Wyjdź z Trybu Skupienia",
"focus-mode": "Tryb Skupienia",
"format": {
- "heading": "Nagłówek",
"paragraph": "Akapit",
"heading-1": "Nagłówek 1",
"heading-2": "Nagłówek 2",
@@ -162,7 +161,6 @@
"ordered-list": "Lista numerowana",
"task-list": "Lista zadań",
"link": "Link",
- "more": "Więcej",
"code-block": "Blok kodu",
"strikethrough": "Przekreślenie"
},
@@ -197,7 +195,6 @@
"transcribing": "Transkrypcja..."
},
"comment": "Komentarz",
- "formatting-toolbar": "Pasek narzędzi formatowania",
"new-memo": "Nowa notatka",
"saved": "Zapisano",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Zapisywanie w toku",
"unsupported-attachment-image-url": "Nieobsługiwany adres URL obrazu w załączniku: {{url}}",
"wait-for-upload": "Poczekaj na zakończenie przesyłania"
+ },
+ "blocks": {
+ "task": "Zadanie",
+ "quote": "Cytat",
+ "table": "Tabela",
+ "divider": "Separator",
+ "no-results": "Brak wyników",
+ "commands": "Polecenia",
+ "loading": "Wczytywanie…",
+ "duplicate": "Duplikuj",
+ "inline-code": "Kod",
+ "link-placeholder": "Wklej lub wpisz link…",
+ "remove-link": "Usuń link",
+ "slash-hint": "Wpisz „/”, aby wyświetlić polecenia",
+ "block-menu": "Otwórz menu bloku",
+ "list-hint": "Lista",
+ "plain-text": "tekst",
+ "add-row-above": "Dodaj wiersz powyżej",
+ "add-row-below": "Dodaj wiersz poniżej",
+ "add-column-left": "Dodaj kolumnę po lewej",
+ "add-column-right": "Dodaj kolumnę po prawej",
+ "delete-row": "Usuń wiersz",
+ "delete-column": "Usuń kolumnę",
+ "align-left": "Wyrównaj do lewej",
+ "align-center": "Wyśrodkuj",
+ "align-right": "Wyrównaj do prawej"
}
},
"inbox": {
diff --git a/web/src/locales/pt-BR.json b/web/src/locales/pt-BR.json
index 39114fea9..34c331890 100644
--- a/web/src/locales/pt-BR.json
+++ b/web/src/locales/pt-BR.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Bloco de código",
"link": "Link",
- "heading": "Título",
"paragraph": "Parágrafo",
"heading-1": "Título 1",
"heading-2": "Título 2",
@@ -193,11 +192,9 @@
"strikethrough": "Tachado",
"bullet-list": "Lista com marcadores",
"ordered-list": "Lista numerada",
- "task-list": "Lista de tarefas",
- "more": "Mais formatação"
+ "task-list": "Lista de tarefas"
},
"comment": "Comentário",
- "formatting-toolbar": "Barra de ferramentas de formatação",
"new-memo": "Novo memorando",
"saved": "Salvo",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Salvando em andamento",
"unsupported-attachment-image-url": "URL de imagem de anexo não suportada: {{url}}",
"wait-for-upload": "Aguardar a conclusão do upload"
+ },
+ "blocks": {
+ "task": "Tarefa",
+ "quote": "Citação",
+ "table": "Tabela",
+ "divider": "Divisor",
+ "no-results": "Nenhum resultado",
+ "commands": "Comandos",
+ "loading": "Carregando…",
+ "duplicate": "Duplicar",
+ "inline-code": "Código",
+ "link-placeholder": "Cole ou digite um link…",
+ "remove-link": "Remover link",
+ "slash-hint": "Digite \"/\" para ver os comandos",
+ "block-menu": "Abrir menu do bloco",
+ "list-hint": "Lista",
+ "plain-text": "texto",
+ "add-row-above": "Adicionar linha acima",
+ "add-row-below": "Adicionar linha abaixo",
+ "add-column-left": "Adicionar coluna à esquerda",
+ "add-column-right": "Adicionar coluna à direita",
+ "delete-row": "Excluir linha",
+ "delete-column": "Excluir coluna",
+ "align-left": "Alinhar à esquerda",
+ "align-center": "Centralizar",
+ "align-right": "Alinhar à direita"
}
},
"inbox": {
diff --git a/web/src/locales/pt-PT.json b/web/src/locales/pt-PT.json
index 27065bbd3..e2c56cfb7 100644
--- a/web/src/locales/pt-PT.json
+++ b/web/src/locales/pt-PT.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Bloco de código",
"link": "Link",
- "heading": "Título",
"paragraph": "Parágrafo",
"heading-1": "Título 1",
"heading-2": "Título 2",
@@ -193,11 +192,9 @@
"strikethrough": "Tachado",
"bullet-list": "Lista com marcadores",
"ordered-list": "Lista numerada",
- "task-list": "Lista de tarefas",
- "more": "Mais formatação"
+ "task-list": "Lista de tarefas"
},
"comment": "Comentário",
- "formatting-toolbar": "Barra de ferramentas de formatação",
"new-memo": "Novo memorando",
"saved": "Salvo",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Guardar em andamento",
"unsupported-attachment-image-url": "URL de imagem de anexo não suportado: {{url}}",
"wait-for-upload": "Aguardar conclusão do upload"
+ },
+ "blocks": {
+ "task": "Tarefa",
+ "quote": "Citação",
+ "table": "Tabela",
+ "divider": "Divisor",
+ "no-results": "Nenhum resultado",
+ "commands": "Comandos",
+ "loading": "A carregar…",
+ "duplicate": "Duplicar",
+ "inline-code": "Código",
+ "link-placeholder": "Cole ou escreva um link…",
+ "remove-link": "Remover link",
+ "slash-hint": "Escreva \"/\" para ver os comandos",
+ "block-menu": "Abrir menu do bloco",
+ "list-hint": "Lista",
+ "plain-text": "texto",
+ "add-row-above": "Adicionar linha acima",
+ "add-row-below": "Adicionar linha abaixo",
+ "add-column-left": "Adicionar coluna à esquerda",
+ "add-column-right": "Adicionar coluna à direita",
+ "delete-row": "Eliminar linha",
+ "delete-column": "Eliminar coluna",
+ "align-left": "Alinhar à esquerda",
+ "align-center": "Centrar",
+ "align-right": "Alinhar à direita"
}
},
"inbox": {
diff --git a/web/src/locales/ro.json b/web/src/locales/ro.json
index 368c8df14..3f2bb5aac 100644
--- a/web/src/locales/ro.json
+++ b/web/src/locales/ro.json
@@ -221,7 +221,6 @@
"format": {
"code-block": "Bloc de cod",
"link": "Legătură",
- "heading": "Titlu",
"paragraph": "Paragraf",
"heading-1": "Titlu 1",
"heading-2": "Titlu 2",
@@ -231,11 +230,9 @@
"strikethrough": "Tăiat cu o linie",
"bullet-list": "Marcator listă",
"ordered-list": "Listă numerotată",
- "task-list": "Listă de activități",
- "more": "Mai multe formatări"
+ "task-list": "Listă de activități"
},
"comment": "Comentariu",
- "formatting-toolbar": "Bara de instrumente de formatare",
"new-memo": "Memo nou",
"saved": "Salvat",
"validation": {
@@ -247,6 +244,32 @@
"save-in-progress": "Salvare în curs",
"unsupported-attachment-image-url": "Adresa URL a imaginii atașate neacceptată: {{url}}",
"wait-for-upload": "Așteptați finalizarea încărcării"
+ },
+ "blocks": {
+ "task": "Sarcină",
+ "quote": "Citat",
+ "table": "Tabel",
+ "divider": "Separator",
+ "no-results": "Niciun rezultat",
+ "commands": "Comenzi",
+ "loading": "Se încarcă…",
+ "duplicate": "Duplică",
+ "inline-code": "Cod",
+ "link-placeholder": "Lipește sau tastează un link…",
+ "remove-link": "Elimină linkul",
+ "slash-hint": "Tastează „/” pentru comenzi",
+ "block-menu": "Deschide meniul blocului",
+ "list-hint": "Listă",
+ "plain-text": "text",
+ "add-row-above": "Adaugă rând deasupra",
+ "add-row-below": "Adaugă rând dedesubt",
+ "add-column-left": "Adaugă coloană la stânga",
+ "add-column-right": "Adaugă coloană la dreapta",
+ "delete-row": "Șterge rândul",
+ "delete-column": "Șterge coloana",
+ "align-left": "Aliniază la stânga",
+ "align-center": "Centrează",
+ "align-right": "Aliniază la dreapta"
}
},
"inbox": {
diff --git a/web/src/locales/ru.json b/web/src/locales/ru.json
index 5a9a43bd7..b9a7bc424 100644
--- a/web/src/locales/ru.json
+++ b/web/src/locales/ru.json
@@ -180,9 +180,7 @@
"transcribe-success": "Транскрипция добавлена",
"transcribing": "Расшифровка..."
},
- "formatting-toolbar": "Панель форматирования",
"format": {
- "heading": "Заголовок",
"paragraph": "Абзац",
"heading-1": "Заголовок 1",
"heading-2": "Заголовок 2",
@@ -194,8 +192,7 @@
"bullet-list": "Маркированный список",
"ordered-list": "Нумерованный список",
"task-list": "Список задач",
- "link": "Ссылка",
- "more": "Другие параметры форматирования"
+ "link": "Ссылка"
},
"validation": {
"cannot-save": "Невозможно сохранить",
@@ -209,7 +206,33 @@
},
"comment": "Комментарий",
"new-memo": "Новая заметка",
- "saved": "Сохранено"
+ "saved": "Сохранено",
+ "blocks": {
+ "task": "Задача",
+ "quote": "Цитата",
+ "table": "Таблица",
+ "divider": "Разделитель",
+ "no-results": "Ничего не найдено",
+ "commands": "Команды",
+ "loading": "Загрузка…",
+ "duplicate": "Дублировать",
+ "inline-code": "Код",
+ "link-placeholder": "Вставьте или введите ссылку…",
+ "remove-link": "Удалить ссылку",
+ "slash-hint": "Введите «/» для вызова команд",
+ "block-menu": "Открыть меню блока",
+ "list-hint": "Список",
+ "plain-text": "текст",
+ "add-row-above": "Добавить строку выше",
+ "add-row-below": "Добавить строку ниже",
+ "add-column-left": "Добавить столбец слева",
+ "add-column-right": "Добавить столбец справа",
+ "delete-row": "Удалить строку",
+ "delete-column": "Удалить столбец",
+ "align-left": "Выровнять по левому краю",
+ "align-center": "Выровнять по центру",
+ "align-right": "Выровнять по правому краю"
+ }
},
"inbox": {
"failed-to-load": "Не удалось загрузить элемент уведомления",
diff --git a/web/src/locales/sk.json b/web/src/locales/sk.json
index df3e02860..f42ddd95b 100644
--- a/web/src/locales/sk.json
+++ b/web/src/locales/sk.json
@@ -221,7 +221,6 @@
"format": {
"code-block": "Blok kódu",
"link": "Odkaz",
- "heading": "Nadpis",
"paragraph": "Odsek",
"heading-1": "Nadpis 1",
"heading-2": "Nadpis 2",
@@ -231,11 +230,9 @@
"strikethrough": "Prečiarknuté",
"bullet-list": "Odrážka zoznam",
"ordered-list": "Číslovaný zoznam",
- "task-list": "Zoznam úloh",
- "more": "Ďalšie formátovanie"
+ "task-list": "Zoznam úloh"
},
"comment": "Komentár",
- "formatting-toolbar": "Panel s nástrojmi Formátovanie",
"new-memo": "Nová poznámka",
"saved": "Uložené",
"validation": {
@@ -247,6 +244,32 @@
"save-in-progress": "Prebieha ukladanie",
"unsupported-attachment-image-url": "Nepodporovaná URL adresa obrázka prílohy: {{url}}",
"wait-for-upload": "Počkajte na dokončenie nahrávania"
+ },
+ "blocks": {
+ "task": "Úloha",
+ "quote": "Citácia",
+ "table": "Tabuľka",
+ "divider": "Oddeľovač",
+ "no-results": "Žiadne výsledky",
+ "commands": "Príkazy",
+ "loading": "Načítava sa…",
+ "duplicate": "Duplikovať",
+ "inline-code": "Kód",
+ "link-placeholder": "Vložte alebo zadajte odkaz…",
+ "remove-link": "Odstrániť odkaz",
+ "slash-hint": "Napíšte „/“ pre príkazy",
+ "block-menu": "Otvoriť ponuku bloku",
+ "list-hint": "Zoznam",
+ "plain-text": "text",
+ "add-row-above": "Pridať riadok nad",
+ "add-row-below": "Pridať riadok pod",
+ "add-column-left": "Pridať stĺpec vľavo",
+ "add-column-right": "Pridať stĺpec vpravo",
+ "delete-row": "Odstrániť riadok",
+ "delete-column": "Odstrániť stĺpec",
+ "align-left": "Zarovnať doľava",
+ "align-center": "Zarovnať na stred",
+ "align-right": "Zarovnať doprava"
}
},
"inbox": {
diff --git a/web/src/locales/sl.json b/web/src/locales/sl.json
index 9bdd0bcab..2c6e27f87 100644
--- a/web/src/locales/sl.json
+++ b/web/src/locales/sl.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Kodni blok",
"link": "Povezava",
- "heading": "Naslov",
"paragraph": "Odstavek",
"heading-1": "Naslov 1",
"heading-2": "Naslov 2",
@@ -193,11 +192,9 @@
"strikethrough": "Prečrtano",
"bullet-list": "Označena črka seznam",
"ordered-list": "Oštevilčen seznam",
- "task-list": "Seznam opravil",
- "more": "Več oblikovanja"
+ "task-list": "Seznam opravil"
},
"comment": "Komentar",
- "formatting-toolbar": "Orodna vrstica za oblikovanje",
"new-memo": "Nov zapisek",
"saved": "Shranjeno",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Shranjevanje v teku",
"unsupported-attachment-image-url": "URL nepodprte slike priloge: {{url}}",
"wait-for-upload": "Počakajte, da se nalaganje zaključi"
+ },
+ "blocks": {
+ "task": "Opravilo",
+ "quote": "Citat",
+ "table": "Tabela",
+ "divider": "Ločilo",
+ "no-results": "Ni rezultatov",
+ "commands": "Ukazi",
+ "loading": "Nalaganje…",
+ "duplicate": "Podvoji",
+ "inline-code": "Koda",
+ "link-placeholder": "Prilepi ali vnesi povezavo…",
+ "remove-link": "Odstrani povezavo",
+ "slash-hint": "Vnesi »/« za ukaze",
+ "block-menu": "Odpri meni bloka",
+ "list-hint": "Seznam",
+ "plain-text": "besedilo",
+ "add-row-above": "Dodaj vrstico zgoraj",
+ "add-row-below": "Dodaj vrstico spodaj",
+ "add-column-left": "Dodaj stolpec levo",
+ "add-column-right": "Dodaj stolpec desno",
+ "delete-row": "Izbriši vrstico",
+ "delete-column": "Izbriši stolpec",
+ "align-left": "Poravnaj levo",
+ "align-center": "Poravnaj na sredino",
+ "align-right": "Poravnaj desno"
}
},
"inbox": {
diff --git a/web/src/locales/sr.json b/web/src/locales/sr.json
index 5c6200c8a..889c174c1 100644
--- a/web/src/locales/sr.json
+++ b/web/src/locales/sr.json
@@ -221,7 +221,6 @@
"format": {
"code-block": "Блок кода",
"link": "Линк",
- "heading": "Наслов",
"paragraph": "Пасус",
"heading-1": "Наслов 1",
"heading-2": "Наслов 2",
@@ -231,11 +230,9 @@
"strikethrough": "Прецртано",
"bullet-list": "Табла листа",
"ordered-list": "Нумерисана листа",
- "task-list": "Листа обавеза",
- "more": "Више форматирања"
+ "task-list": "Листа обавеза"
},
"comment": "Коментар",
- "formatting-toolbar": "Трака са алаткама за форматирање",
"new-memo": "Нова белешка",
"saved": "Сачувано",
"validation": {
@@ -247,6 +244,32 @@
"save-in-progress": "Чување у току",
"unsupported-attachment-image-url": "Неподржана URL адреса слике прилога: {{url}}",
"wait-for-upload": "Сачекај да се отпремање заврши"
+ },
+ "blocks": {
+ "task": "Задатак",
+ "quote": "Цитат",
+ "table": "Табела",
+ "divider": "Разделник",
+ "no-results": "Нема резултата",
+ "commands": "Команде",
+ "loading": "Учитавање…",
+ "duplicate": "Дуплирај",
+ "inline-code": "Код",
+ "link-placeholder": "Налепите или унесите линк…",
+ "remove-link": "Уклони линк",
+ "slash-hint": "Унесите „/“ за команде",
+ "block-menu": "Отвори мени блока",
+ "list-hint": "Листа",
+ "plain-text": "текст",
+ "add-row-above": "Додај ред изнад",
+ "add-row-below": "Додај ред испод",
+ "add-column-left": "Додај колону лево",
+ "add-column-right": "Додај колону десно",
+ "delete-row": "Избриши ред",
+ "delete-column": "Избриши колону",
+ "align-left": "Поравнај лево",
+ "align-center": "Поравнај по средини",
+ "align-right": "Поравнај десно"
}
},
"inbox": {
diff --git a/web/src/locales/sv.json b/web/src/locales/sv.json
index 67ba295eb..35ebda85a 100644
--- a/web/src/locales/sv.json
+++ b/web/src/locales/sv.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Kodblock",
"link": "Länk",
- "heading": "Rubrik",
"paragraph": "Stycke",
"heading-1": "Rubrik 1",
"heading-2": "Rubrik 2",
@@ -193,11 +192,9 @@
"strikethrough": "Genomstruken",
"bullet-list": "Punkt lista",
"ordered-list": "Numrerad lista",
- "task-list": "Att-göra-lista",
- "more": "Mer formatering"
+ "task-list": "Att-göra-lista"
},
"comment": "Kommentar",
- "formatting-toolbar": "Formateringsverktygsfältet",
"new-memo": "Nytt memo",
"saved": "Sparat",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Spara pågår",
"unsupported-attachment-image-url": "Bild-URL för bilaga som inte stöds: {{url}}",
"wait-for-upload": "Vänta tills uppladdningen är klar"
+ },
+ "blocks": {
+ "task": "Uppgift",
+ "quote": "Citat",
+ "table": "Tabell",
+ "divider": "Avdelare",
+ "no-results": "Inga resultat",
+ "commands": "Kommandon",
+ "loading": "Läser in…",
+ "duplicate": "Duplicera",
+ "inline-code": "Kod",
+ "link-placeholder": "Klistra in eller skriv en länk…",
+ "remove-link": "Ta bort länk",
+ "slash-hint": "Skriv ”/” för kommandon",
+ "block-menu": "Öppna blockmeny",
+ "list-hint": "Lista",
+ "plain-text": "text",
+ "add-row-above": "Lägg till rad ovanför",
+ "add-row-below": "Lägg till rad nedanför",
+ "add-column-left": "Lägg till kolumn till vänster",
+ "add-column-right": "Lägg till kolumn till höger",
+ "delete-row": "Radera rad",
+ "delete-column": "Radera kolumn",
+ "align-left": "Vänsterjustera",
+ "align-center": "Centrera",
+ "align-right": "Högerjustera"
}
},
"inbox": {
diff --git a/web/src/locales/th.json b/web/src/locales/th.json
index e28acd137..033f62827 100644
--- a/web/src/locales/th.json
+++ b/web/src/locales/th.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "บล็อกโค้ด",
"link": "ลิงก์",
- "heading": "หัวข้อ",
"paragraph": "ย่อหน้า",
"heading-1": "หัวข้อ 1",
"heading-2": "หัวข้อ 2",
@@ -193,11 +192,9 @@
"strikethrough": "ขีดฆ่า",
"bullet-list": "รายการแบบมีจุดนำหน้า",
"ordered-list": "รายการแบบมีหมายเลข",
- "task-list": "รายการสิ่งที่ต้องทำ",
- "more": "การจัดรูปแบบเพิ่มเติม"
+ "task-list": "รายการสิ่งที่ต้องทำ"
},
"comment": "ความคิดเห็น",
- "formatting-toolbar": "แถบเครื่องมือจัดรูปแบบ",
"new-memo": "บันทึกใหม่",
"saved": "บันทึกแล้ว",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "กำลังบันทึก",
"unsupported-attachment-image-url": "URL รูปภาพไฟล์แนบไม่รองรับ: {{url}}",
"wait-for-upload": "รอจนกว่าการอัปโหลดจะเสร็จสมบูรณ์"
+ },
+ "blocks": {
+ "task": "งาน",
+ "quote": "คำพูดอ้างอิง",
+ "table": "ตาราง",
+ "divider": "เส้นคั่น",
+ "no-results": "ไม่พบผลลัพธ์",
+ "commands": "คำสั่ง",
+ "loading": "กำลังโหลด…",
+ "duplicate": "ทำสำเนา",
+ "inline-code": "โค้ด",
+ "link-placeholder": "วางหรือพิมพ์ลิงก์…",
+ "remove-link": "ลบลิงก์",
+ "slash-hint": "พิมพ์ \"/\" เพื่อดูคำสั่ง",
+ "block-menu": "เปิดเมนูบล็อก",
+ "list-hint": "รายการ",
+ "plain-text": "ข้อความ",
+ "add-row-above": "เพิ่มแถวด้านบน",
+ "add-row-below": "เพิ่มแถวด้านล่าง",
+ "add-column-left": "เพิ่มคอลัมน์ทางซ้าย",
+ "add-column-right": "เพิ่มคอลัมน์ทางขวา",
+ "delete-row": "ลบแถว",
+ "delete-column": "ลบคอลัมน์",
+ "align-left": "จัดชิดซ้าย",
+ "align-center": "จัดกึ่งกลาง",
+ "align-right": "จัดชิดขวา"
}
},
"inbox": {
diff --git a/web/src/locales/tr.json b/web/src/locales/tr.json
index 4bcc02f2b..f8f4d49c1 100644
--- a/web/src/locales/tr.json
+++ b/web/src/locales/tr.json
@@ -177,9 +177,7 @@
"exit-focus-mode": "Odak modundan çık",
"focus-mode": "Odak modu",
"comment": "Yorum yap",
- "formatting-toolbar": "Biçimlendirme araç çubuğu",
"format": {
- "heading": "Başlık",
"paragraph": "Paragraf",
"heading-1": "Başlık 1",
"heading-2": "Başlık 2",
@@ -191,8 +189,7 @@
"bullet-list": "Madde işaretli liste",
"ordered-list": "Numaralı liste",
"task-list": "Yapılacaklar listesi",
- "link": "Bağlantı",
- "more": "Diğer biçimlendirme seçenekleri"
+ "link": "Bağlantı"
},
"insert-menu": {
"add-attachment": "Ek ekle",
@@ -235,6 +232,32 @@
"transcribe-error": "Ses metne dönüştürülemedi",
"transcribe-success": "Transkripsiyon eklendi",
"transcribing": "Metne dönüştürülüyor..."
+ },
+ "blocks": {
+ "task": "Görev",
+ "quote": "Alıntı",
+ "table": "Tablo",
+ "divider": "Ayırıcı",
+ "no-results": "Sonuç yok",
+ "commands": "Komutlar",
+ "loading": "Yükleniyor…",
+ "duplicate": "Çoğalt",
+ "inline-code": "Kod",
+ "link-placeholder": "Bağlantı yapıştırın veya yazın…",
+ "remove-link": "Bağlantıyı kaldır",
+ "slash-hint": "Komutlar için \"/\" yazın",
+ "block-menu": "Blok menüsünü aç",
+ "list-hint": "Liste",
+ "plain-text": "metin",
+ "add-row-above": "Üste satır ekle",
+ "add-row-below": "Alta satır ekle",
+ "add-column-left": "Sola sütun ekle",
+ "add-column-right": "Sağa sütun ekle",
+ "delete-row": "Satırı sil",
+ "delete-column": "Sütunu sil",
+ "align-left": "Sola hizala",
+ "align-center": "Ortala",
+ "align-right": "Sağa hizala"
}
},
"inbox": {
diff --git a/web/src/locales/uk.json b/web/src/locales/uk.json
index 8801b712b..eab6b3359 100644
--- a/web/src/locales/uk.json
+++ b/web/src/locales/uk.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Блок коду",
"link": "Посилання",
- "heading": "Заголовок",
"paragraph": "Абзац",
"heading-1": "Заголовок 1",
"heading-2": "Заголовок 2",
@@ -193,11 +192,9 @@
"strikethrough": "Закреслений текст",
"bullet-list": "Маркований список список",
"ordered-list": "Нумерований список",
- "task-list": "Список справ",
- "more": "Додаткове форматування"
+ "task-list": "Список справ"
},
"comment": "Коментар",
- "formatting-toolbar": "Панель інструментів форматування",
"new-memo": "Нова нотатка",
"saved": "Збережено",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Виконується збереження",
"unsupported-attachment-image-url": "Непідтримувана URL-адреса вкладеного зображення: {{url}}",
"wait-for-upload": "Зачекайте завершення завантаження"
+ },
+ "blocks": {
+ "task": "Завдання",
+ "quote": "Цитата",
+ "table": "Таблиця",
+ "divider": "Роздільник",
+ "no-results": "Нічого не знайдено",
+ "commands": "Команди",
+ "loading": "Завантаження…",
+ "duplicate": "Дублювати",
+ "inline-code": "Код",
+ "link-placeholder": "Вставте або введіть посилання…",
+ "remove-link": "Видалити посилання",
+ "slash-hint": "Введіть «/» для виклику команд",
+ "block-menu": "Відкрити меню блоку",
+ "list-hint": "Список",
+ "plain-text": "текст",
+ "add-row-above": "Додати рядок вище",
+ "add-row-below": "Додати рядок нижче",
+ "add-column-left": "Додати стовпець ліворуч",
+ "add-column-right": "Додати стовпець праворуч",
+ "delete-row": "Видалити рядок",
+ "delete-column": "Видалити стовпець",
+ "align-left": "Вирівняти ліворуч",
+ "align-center": "Вирівняти по центру",
+ "align-right": "Вирівняти праворуч"
}
},
"inbox": {
diff --git a/web/src/locales/vi.json b/web/src/locales/vi.json
index 65b3e004d..d4e7b80a0 100644
--- a/web/src/locales/vi.json
+++ b/web/src/locales/vi.json
@@ -183,7 +183,6 @@
"format": {
"code-block": "Khối mã",
"link": "Liên kết",
- "heading": "Tiêu đề",
"paragraph": "Đoạn văn",
"heading-1": "Tiêu đề 1",
"heading-2": "Tiêu đề 2",
@@ -193,11 +192,9 @@
"strikethrough": "Gạch ngang",
"bullet-list": "Danh sách gạch đầu dòng",
"ordered-list": "Danh sách đánh số",
- "task-list": "Danh sách việc cần làm",
- "more": "Định dạng khác"
+ "task-list": "Danh sách việc cần làm"
},
"comment": "Bình luận",
- "formatting-toolbar": "Thanh công cụ định dạng",
"new-memo": "Ghi chú mới",
"saved": "Đã lưu",
"validation": {
@@ -209,6 +206,32 @@
"save-in-progress": "Đang lưu",
"unsupported-attachment-image-url": "URL ảnh đính kèm không được hỗ trợ: {{url}}",
"wait-for-upload": "Chờ quá trình tải lên hoàn tất"
+ },
+ "blocks": {
+ "task": "Việc cần làm",
+ "quote": "Trích dẫn",
+ "table": "Bảng",
+ "divider": "Đường phân cách",
+ "no-results": "Không có kết quả",
+ "commands": "Lệnh",
+ "loading": "Đang tải…",
+ "duplicate": "Nhân bản",
+ "inline-code": "Mã",
+ "link-placeholder": "Dán hoặc nhập liên kết…",
+ "remove-link": "Xóa liên kết",
+ "slash-hint": "Nhập \"/\" để xem lệnh",
+ "block-menu": "Mở menu khối",
+ "list-hint": "Danh sách",
+ "plain-text": "văn bản",
+ "add-row-above": "Thêm hàng phía trên",
+ "add-row-below": "Thêm hàng phía dưới",
+ "add-column-left": "Thêm cột bên trái",
+ "add-column-right": "Thêm cột bên phải",
+ "delete-row": "Xóa hàng",
+ "delete-column": "Xóa cột",
+ "align-left": "Căn trái",
+ "align-center": "Căn giữa",
+ "align-right": "Căn phải"
}
},
"inbox": {
diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.json
index cfb55d851..59a4be240 100644
--- a/web/src/locales/zh-Hans.json
+++ b/web/src/locales/zh-Hans.json
@@ -181,9 +181,7 @@
"any-thoughts": "此刻的想法...",
"exit-focus-mode": "退出聚焦模式",
"focus-mode": "聚焦模式",
- "formatting-toolbar": "格式工具栏",
"format": {
- "heading": "标题",
"paragraph": "正文",
"heading-1": "一级标题",
"heading-2": "二级标题",
@@ -195,8 +193,7 @@
"bullet-list": "无序列表",
"ordered-list": "有序列表",
"task-list": "任务列表",
- "link": "链接",
- "more": "更多格式"
+ "link": "链接"
},
"new-memo": "新建备忘录",
"no-changes-detected": "未检测到更改",
@@ -240,7 +237,33 @@
"trigger": "录制音频"
},
"comment": "评论",
- "saved": "已保存"
+ "saved": "已保存",
+ "blocks": {
+ "task": "任务",
+ "quote": "引用",
+ "table": "表格",
+ "divider": "分割线",
+ "no-results": "无结果",
+ "commands": "命令",
+ "loading": "加载中…",
+ "duplicate": "创建副本",
+ "inline-code": "代码",
+ "link-placeholder": "粘贴或输入链接…",
+ "remove-link": "移除链接",
+ "slash-hint": "输入“/”调出命令",
+ "block-menu": "打开块菜单",
+ "list-hint": "列表",
+ "plain-text": "文本",
+ "add-row-above": "在上方插入行",
+ "add-row-below": "在下方插入行",
+ "add-column-left": "在左侧插入列",
+ "add-column-right": "在右侧插入列",
+ "delete-row": "删除行",
+ "delete-column": "删除列",
+ "align-left": "左对齐",
+ "align-center": "居中对齐",
+ "align-right": "右对齐"
+ }
},
"inbox": {
"failed-to-load": "加载失败",
diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.json
index 12b840a1f..c35e615cc 100644
--- a/web/src/locales/zh-Hant.json
+++ b/web/src/locales/zh-Hant.json
@@ -229,9 +229,7 @@
"any-thoughts": "任何想法...",
"exit-focus-mode": "退出專注模式",
"focus-mode": "專注模式",
- "formatting-toolbar": "格式工具列",
"format": {
- "heading": "標題",
"paragraph": "段落",
"heading-1": "標題 1",
"heading-2": "標題 2",
@@ -243,8 +241,7 @@
"bullet-list": "項目符號清單",
"ordered-list": "編號清單",
"task-list": "待辦清單",
- "link": "連結",
- "more": "更多格式"
+ "link": "連結"
},
"insert-menu": {
"add-attachment": "新增附件",
@@ -288,7 +285,33 @@
"trigger": "錄製音訊"
},
"comment": "評論",
- "saved": "已儲存"
+ "saved": "已儲存",
+ "blocks": {
+ "task": "任務",
+ "quote": "引用",
+ "table": "表格",
+ "divider": "分隔線",
+ "no-results": "沒有結果",
+ "commands": "指令",
+ "loading": "載入中…",
+ "duplicate": "建立副本",
+ "inline-code": "程式碼",
+ "link-placeholder": "貼上或輸入連結…",
+ "remove-link": "移除連結",
+ "slash-hint": "輸入「/」叫出指令",
+ "block-menu": "開啟區塊選單",
+ "list-hint": "清單",
+ "plain-text": "文字",
+ "add-row-above": "在上方插入列",
+ "add-row-below": "在下方插入列",
+ "add-column-left": "在左側插入欄",
+ "add-column-right": "在右側插入欄",
+ "delete-row": "刪除列",
+ "delete-column": "刪除欄",
+ "align-left": "靠左對齊",
+ "align-center": "置中對齊",
+ "align-right": "靠右對齊"
+ }
},
"inbox": {
"failed-to-load": "載入失敗",
diff --git a/web/src/types/markdown.ts b/web/src/types/markdown.ts
deleted file mode 100644
index 956c334c2..000000000
--- a/web/src/types/markdown.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import type { Data, Element as HastElement } from "hast";
-
-export interface TagNode {
- type: "tagNode";
- value: string;
- data: TagNodeData;
-}
-
-export interface MentionNode {
- type: "mentionNode";
- value: string;
- data: MentionNodeData;
-}
-
-export interface TagNodeData {
- hName: "span";
- hProperties: TagNodeProperties;
- hChildren: Array<{ type: "text"; value: string }>;
-}
-
-export interface MentionNodeData {
- hName: "span";
- hProperties: MentionNodeProperties;
- hChildren: Array<{ type: "text"; value: string }>;
-}
-
-export interface TagNodeProperties {
- className: string;
- "data-tag": string;
-}
-
-export interface MentionNodeProperties {
- className: string;
- "data-mention": string;
-}
-
-export interface ExtendedData extends Data {
- mdastType?: string;
-}
-
-export function hasExtendedData(node: unknown): node is { data: ExtendedData } {
- return typeof node === "object" && node !== null && "data" in node && typeof (node as { data: unknown }).data === "object";
-}
-
-export function isTagElement(node: HastElement): boolean {
- if (hasExtendedData(node) && node.data.mdastType === "tagNode") {
- return true;
- }
-
- const dataTag = node.properties?.["data-tag"];
- if (typeof dataTag === "string" && dataTag !== "") {
- return true;
- }
-
- const className = node.properties?.className;
- if (Array.isArray(className) && className.includes("tag")) {
- return true;
- }
- if (typeof className === "string" && className.split(/\s+/).includes("tag")) {
- return true;
- }
-
- return false;
-}
-
-export function isMentionElement(node: HastElement): boolean {
- if (hasExtendedData(node) && node.data.mdastType === "mentionNode") {
- return true;
- }
-
- const dataMention = node.properties?.["data-mention"];
- if (typeof dataMention === "string" && dataMention !== "") {
- return true;
- }
-
- const className = node.properties?.className;
- if (Array.isArray(className) && className.includes("mention")) {
- return true;
- }
- if (typeof className === "string" && className.split(/\s+/).includes("mention")) {
- return true;
- }
-
- return false;
-}
-
-export function isTaskListItemElement(node: HastElement): boolean {
- const type = node.properties?.type;
- return typeof type === "string" && type === "checkbox";
-}
diff --git a/web/src/utils/gfm-email.ts b/web/src/utils/gfm-email.ts
deleted file mode 100644
index ee8fda0e9..000000000
--- a/web/src/utils/gfm-email.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-import { parser as markdownParser } from "@lezer/markdown";
-import { decodeString } from "micromark-util-decode-string";
-import { isValidMarkdownLinkReference, resolvedMarkdownLinkRanges } from "@/utils/markdown-link";
-import { decodedMarkdownCharacterReferenceAt } from "@/utils/markdown-source-boundaries";
-import { memoMarkdownExtensions } from "@/utils/memo-markdown-extension";
-
-export interface GFMEmailSourceRange {
- from: number;
- to: number;
- value: string;
-}
-
-export interface MarkdownSourceNode {
- readonly name: string;
- readonly from: number;
- readonly to: number;
- readonly firstChild: MarkdownSourceNode | null;
- readonly nextSibling: MarkdownSourceNode | null;
-}
-
-interface MarkdownSourceRange {
- from: number;
- to: number;
-}
-
-const DOMAIN_AT_START = /^@(?:[A-Za-z0-9_-]+\.)+[A-Za-z0-9_-]*[A-Za-z0-9]/;
-const REFERENCE_LABEL_PREFIX = "x ";
-const sourceParser = markdownParser.configure(memoMarkdownExtensions);
-
-const TEXT_CONTAINERS = new Set([
- "ATXHeading1",
- "ATXHeading2",
- "ATXHeading3",
- "ATXHeading4",
- "ATXHeading5",
- "ATXHeading6",
- "Emphasis",
- "Paragraph",
- "SetextHeading1",
- "SetextHeading2",
- "Strikethrough",
- "StrongEmphasis",
- "TableCell",
- "Task",
-]);
-
-const STRUCTURAL_CONTAINERS = new Set([
- "Blockquote",
- "BulletList",
- "Document",
- "ListItem",
- "OrderedList",
- "Table",
- "TableHeader",
- "TableRow",
-]);
-
-function isLocalChar(char: string): boolean {
- return /[A-Za-z0-9._+-]/.test(char);
-}
-
-function isASCIIPunctuation(char: string): boolean {
- const code = char.charCodeAt(0);
- return (
- (code >= 0x21 && code <= 0x2f) || (code >= 0x3a && code <= 0x40) || (code >= 0x5b && code <= 0x60) || (code >= 0x7b && code <= 0x7e)
- );
-}
-
-interface EmailProjection {
- value: string;
- starts: number[];
- ends: number[];
-}
-
-function projectEmailText(source: string, lowerBound: number, upperBound: number): EmailProjection {
- let value = "";
- const starts: number[] = [];
- const ends: number[] = [];
- for (let cursor = lowerBound; cursor < upperBound; ) {
- if (source[cursor] === "\\" && cursor + 1 < upperBound && isASCIIPunctuation(source[cursor + 1])) {
- value += source[cursor + 1];
- starts.push(cursor);
- ends.push(cursor + 2);
- cursor += 2;
- continue;
- }
-
- const reference = decodedMarkdownCharacterReferenceAt(source, cursor, upperBound);
- if (reference) {
- value += reference.value;
- for (let index = 0; index < reference.value.length; index++) {
- starts.push(cursor);
- ends.push(reference.to);
- }
- cursor = reference.to;
- continue;
- }
-
- const codePoint = source.codePointAt(cursor);
- const character = codePoint === undefined ? "" : String.fromCodePoint(codePoint);
- value += character;
- for (let index = 0; index < character.length; index++) {
- starts.push(cursor);
- ends.push(cursor + character.length);
- }
- cursor += character.length;
- }
- return { value, starts, ends };
-}
-
-function matchEmailAt(source: string, at: number, lowerBound: number, upperBound: number): GFMEmailSourceRange | undefined {
- let start = at;
- while (start > lowerBound) {
- if (!isLocalChar(source[start - 1])) break;
- start--;
- }
- if (start === at) return undefined;
-
- const domain = source.slice(at, upperBound).match(DOMAIN_AT_START)?.[0];
- if (!domain) return undefined;
- const end = at + domain.length;
- if (end < upperBound && (source[end] === "-" || source[end] === "_")) return undefined;
- return { from: start, to: end, value: source.slice(start, end) };
-}
-
-/** Find extended GFM email autolinks inside one parsed text-source run. */
-export function findGFMEmailMatches(source: string, lowerBound = 0, upperBound = source.length): GFMEmailSourceRange[] {
- const projection = projectEmailText(source, lowerBound, upperBound);
- const matches: GFMEmailSourceRange[] = [];
- for (let cursor = 0; cursor < projection.value.length; ) {
- const at = projection.value.indexOf("@", cursor);
- if (at < 0) break;
- const match = matchEmailAt(projection.value, at, cursor, projection.value.length);
- if (!match) {
- cursor = at + 1;
- continue;
- }
- matches.push({
- from: projection.starts[match.from],
- to: projection.ends[match.to - 1],
- value: match.value,
- });
- cursor = match.to;
- }
- return matches;
-}
-
-/** Whether a Lezer URL node is an email candidate rather than a written URL. */
-export function isGFMEmailURLSource(source: string): boolean {
- return source.includes("@") && !/^(?:https?:\/\/|www\.)/.test(source);
-}
-
-/**
- * Find canonical GFM email ranges within Lezer textual containers. Email URL
- * nodes and backslash escapes stay in the same text run so parser splits
- * cannot shorten the decoded GFM 0.29 match; links, code, math, and other
- * syntax remain opaque.
- */
-export function findMarkdownGFMEmailRanges(
- source: string,
- root: MarkdownSourceNode,
- resolvedLinks: MarkdownSourceRange[],
- allowUnresolvedLinks: boolean,
-): GFMEmailSourceRange[] {
- const ranges: GFMEmailSourceRange[] = [];
-
- const collectUnresolvedReferenceLabel = (node: MarkdownSourceNode): void => {
- const contentFrom = node.from + 1;
- const contentTo = node.to - 1;
- if (contentFrom >= contentTo) return;
-
- const prefixedSource = REFERENCE_LABEL_PREFIX + source.slice(contentFrom, contentTo);
- const root = sourceParser.parse(prefixedSource).topNode as MarkdownSourceNode;
- const offset = contentFrom - REFERENCE_LABEL_PREFIX.length;
- for (const range of findMarkdownGFMEmailRanges(prefixedSource, root, resolvedMarkdownLinkRanges(prefixedSource, root), true)) {
- const from = range.from + offset;
- const to = range.to + offset;
- if (from >= contentFrom && to <= contentTo) ranges.push({ from, to, value: range.value });
- }
- };
-
- const collect = (node: MarkdownSourceNode) => {
- const linkLike = node.name === "Link" || node.name === "Image";
- const resolvedLink = linkLike && resolvedLinks.some((range) => range.from === node.from && range.to === node.to);
- if (resolvedLink || (linkLike && !allowUnresolvedLinks)) return;
-
- const invalidLinkReference = node.name === "LinkReference" && !isValidMarkdownLinkReference(source, node);
- const scansDirectText = TEXT_CONTAINERS.has(node.name) || linkLike || invalidLinkReference;
- if (!scansDirectText && !STRUCTURAL_CONTAINERS.has(node.name)) return;
-
- let cursor = node.from;
- for (let child = node.firstChild; child; child = child.nextSibling) {
- const spelling = source.slice(child.from, child.to);
- const staysInTextRun =
- scansDirectText &&
- (child.name === "Escape" ||
- (child.name === "Entity" && decodeString(spelling) !== spelling) ||
- (child.name === "URL" && isGFMEmailURLSource(spelling)));
- if (staysInTextRun) continue;
-
- if (scansDirectText && cursor < child.from) ranges.push(...findGFMEmailMatches(source, cursor, child.from));
- if ((linkLike || invalidLinkReference) && child.name === "LinkLabel") {
- collectUnresolvedReferenceLabel(child);
- } else {
- collect(child);
- }
- cursor = child.to;
- }
- if (scansDirectText && cursor < node.to) ranges.push(...findGFMEmailMatches(source, cursor, node.to));
- };
-
- collect(root);
- return ranges.sort((left, right) => left.from - right.from || left.to - right.to);
-}
diff --git a/web/src/utils/gfm-url.ts b/web/src/utils/gfm-url.ts
deleted file mode 100644
index 9bbb0c106..000000000
--- a/web/src/utils/gfm-url.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import { decodeString } from "micromark-util-decode-string";
-import type { MarkdownSourceNode } from "@/utils/gfm-email";
-import { hasExactMarkdownRange, isValidMarkdownLinkReference, type MarkdownSourceRange } from "@/utils/markdown-link";
-
-export interface GFMURLSourceRange {
- from: number;
- to: number;
-}
-
-const UNICODE_ALPHANUMERIC = /[\p{L}\p{N}]/u;
-const UNICODE_SEPARATOR = /\p{Z}/u;
-const TRAILING_PUNCTUATION = new Set(["!", '"', "'", "*", ",", ".", ":", ";", "?", "_", "~"]);
-
-function prefixEnd(source: string, from: number): number | undefined {
- if (source.startsWith("https://", from)) return from + "https://".length;
- if (source.startsWith("http://", from)) return from + "http://".length;
- if (source.startsWith("www.", from)) return from + "www.".length;
- return undefined;
-}
-
-function domainCharacterSize(source: string, offset: number): number {
- const char = String.fromCodePoint(source.codePointAt(offset) ?? 0);
- return char === "_" || char === "-" || char === "." || UNICODE_ALPHANUMERIC.test(char) ? char.length : 0;
-}
-
-function hasValidDomain(source: string, from: number, to: number): boolean {
- while (to > from && source[to - 1] === ".") to--;
- const segments = source.slice(from, to).split(".");
- return segments.length >= 2 && segments.every(Boolean) && !segments.at(-2)?.includes("_") && !segments.at(-1)?.includes("_");
-}
-
-function trimGFMURLTail(source: string, from: number, to: number): number {
- const path = source.slice(from, to);
- let openParentheses = 0;
- let closeParentheses = 0;
- for (const character of path) {
- if (character === "(") openParentheses++;
- else if (character === ")") closeParentheses++;
- }
-
- while (to > from) {
- const entity = source.slice(from, to).match(/&[A-Za-z]+;$/)?.[0];
- if (entity) {
- to -= entity.length;
- continue;
- }
-
- const character = source[to - 1];
- if (character === ")" && closeParentheses > openParentheses) {
- closeParentheses--;
- to--;
- continue;
- }
- if (character === "]" || TRAILING_PUNCTUATION.has(character)) {
- to--;
- continue;
- }
- break;
- }
- return to;
-}
-
-/** Return the complete source range of a lowercase written GFM URL at `from`. */
-export function writtenGFMURLSourceRange(source: string, from: number, upperBound = source.length): GFMURLSourceRange | undefined {
- const domainFrom = prefixEnd(source, from);
- if (domainFrom === undefined || domainFrom >= upperBound) return undefined;
-
- let domainTo = domainFrom;
- while (domainTo < upperBound) {
- const size = domainCharacterSize(source, domainTo);
- if (size === 0) break;
- domainTo += size;
- }
- if (!hasValidDomain(source, domainFrom, domainTo)) return undefined;
-
- let to = domainTo;
- while (to < upperBound) {
- const character = String.fromCodePoint(source.codePointAt(to) ?? 0);
- const code = source.charCodeAt(to);
- if (source[to] === "<" || (code >= 0x09 && code <= 0x0d) || UNICODE_SEPARATOR.test(character)) break;
- to += character.length;
- }
- return { from, to: trimGFMURLTail(source, from, to) };
-}
-
-/** Whether a complete source spelling is a written GFM URL. */
-export function isWrittenGFMURLSource(source: string): boolean {
- return writtenGFMURLSourceRange(source, 0)?.to === source.length;
-}
-
-function hasWrittenURLBoundary(source: string, from: number, contextFrom: number, allowInitialBOM: boolean): boolean {
- if (from === contextFrom) return true;
- if (allowInitialBOM && contextFrom === 0 && from === 1 && source[0] === "\uFEFF") return true;
- const previous = source[from - 1];
- const code = source.charCodeAt(from - 1);
- return (code >= 0x09 && code <= 0x0d) || previous === " " || previous === "(" || previous === "*" || previous === "_" || previous === "~";
-}
-
-/** Return a written GFM URL only when it starts in a valid source context. */
-export function writtenGFMURLSourceRangeAt(
- source: string,
- from: number,
- contextFrom: number,
- upperBound = source.length,
- allowInitialBOM = true,
-): GFMURLSourceRange | undefined {
- if (!hasWrittenURLBoundary(source, from, contextFrom, allowInitialBOM)) return undefined;
- return writtenGFMURLSourceRange(source, from, upperBound);
-}
-
-/** Find written GFM URLs in one already-classified literal source run. */
-export function findWrittenGFMURLRanges(
- source: string,
- lowerBound = 0,
- upperBound = source.length,
- contextFrom = lowerBound,
- opaqueRanges: GFMURLSourceRange[] = [],
- allowInitialBOM = true,
-): GFMURLSourceRange[] {
- const ranges: GFMURLSourceRange[] = [];
- let opaqueIndex = 0;
- for (let offset = contextFrom; offset < upperBound; ) {
- while (opaqueIndex < opaqueRanges.length && opaqueRanges[opaqueIndex].to <= offset) opaqueIndex++;
- const opaque = opaqueRanges[opaqueIndex];
- if (opaque && opaque.from <= offset && opaque.to > offset) {
- offset = opaque.to;
- continue;
- }
-
- if (offset >= lowerBound) {
- const range = writtenGFMURLSourceRangeAt(source, offset, contextFrom, upperBound, allowInitialBOM);
- if (range) {
- ranges.push(range);
- offset = range.to;
- continue;
- }
- }
-
- offset++;
- }
- return ranges;
-}
-
-const URL_SOURCE_CONTAINERS = new Set([
- "ATXHeading1",
- "ATXHeading2",
- "ATXHeading3",
- "ATXHeading4",
- "ATXHeading5",
- "ATXHeading6",
- "Paragraph",
- "SetextHeading1",
- "SetextHeading2",
- "TableCell",
- "Task",
-]);
-
-const URL_PREFIX_OPAQUE_NODES = new Set([
- "Autolink",
- "BlockMath",
- "Comment",
- "Escape",
- "HTMLBlock",
- "HTMLTag",
- "InlineCode",
- "InlineMath",
- "ProcessingInstruction",
-]);
-
-function opaqueURLPrefixRanges(source: string, container: MarkdownSourceNode, resolvedLinks: MarkdownSourceRange[]): GFMURLSourceRange[] {
- const ranges: GFMURLSourceRange[] = [];
-
- const collect = (node: MarkdownSourceNode): void => {
- for (let child = node.firstChild; child; child = child.nextSibling) {
- const resolvedLinkLike = (child.name === "Link" || child.name === "Image") && hasExactMarkdownRange(resolvedLinks, child);
- const knownEntity =
- child.name === "Entity" && decodeString(source.slice(child.from, child.to)) !== source.slice(child.from, child.to);
- if (resolvedLinkLike || knownEntity || URL_PREFIX_OPAQUE_NODES.has(child.name)) {
- ranges.push({ from: child.from, to: child.to });
- } else {
- collect(child);
- }
- }
- };
-
- collect(container);
- return ranges.sort((left, right) => left.from - right.from || left.to - right.to);
-}
-
-/** Find canonical written GFM URLs using Markdown syntax for bracket context. */
-export function findMarkdownGFMURLRanges(
- source: string,
- root: MarkdownSourceNode,
- resolvedLinks: MarkdownSourceRange[],
- allowInitialBOM = true,
-): GFMURLSourceRange[] {
- const ranges: GFMURLSourceRange[] = [];
-
- const collect = (node: MarkdownSourceNode): void => {
- const invalidLinkReference = node.name === "LinkReference" && !isValidMarkdownLinkReference(source, node);
- if (URL_SOURCE_CONTAINERS.has(node.name) || invalidLinkReference) {
- ranges.push(
- ...findWrittenGFMURLRanges(
- source,
- node.from,
- node.to,
- node.from,
- opaqueURLPrefixRanges(source, node, resolvedLinks),
- allowInitialBOM,
- ),
- );
- return;
- }
- for (let child = node.firstChild; child; child = child.nextSibling) collect(child);
- };
-
- collect(root);
- return ranges.sort((left, right) => left.from - right.from || left.to - right.to);
-}
diff --git a/web/src/utils/markdown-link.ts b/web/src/utils/markdown-link.ts
deleted file mode 100644
index fa18c4cf2..000000000
--- a/web/src/utils/markdown-link.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { fromMarkdown } from "mdast-util-from-markdown";
-import { decodeString } from "micromark-util-decode-string";
-import { normalizeIdentifier } from "micromark-util-normalize-identifier";
-import type { MarkdownSourceNode } from "@/utils/gfm-email";
-
-export interface MarkdownSourceRange {
- from: number;
- to: number;
-}
-
-function childrenOf(node: MarkdownSourceNode): MarkdownSourceNode[] {
- const children: MarkdownSourceNode[] = [];
- for (let child = node.firstChild; child; child = child.nextSibling) children.push(child);
- return children;
-}
-
-function normalizeLabel(source: string): string {
- return normalizeIdentifier(decodeString(source).replaceAll("\0", "�"));
-}
-
-function labelValue(source: string, node: MarkdownSourceNode): string {
- return normalizeLabel(source.slice(node.from + 1, node.to - 1));
-}
-
-function linkTextValue(source: string, marks: MarkdownSourceNode[]): string {
- return normalizeLabel(source.slice(marks[0].to, marks[1].from));
-}
-
-/** Validate a Lezer reference definition against the CommonMark parser. */
-export function isValidMarkdownLinkReference(source: string, node: MarkdownSourceNode): boolean {
- if (node.name !== "LinkReference") return false;
- return fromMarkdown(source.slice(node.from, node.to)).children.some((child) => child.type === "definition");
-}
-
-/**
- * Return only links that CommonMark actually resolves. Lezer also emits Link
- * nodes for unresolved reference labels and incomplete inline-link attempts;
- * those spellings remain ordinary text to the Markdown renderer.
- */
-export function resolvedMarkdownLinkRanges(source: string, root: MarkdownSourceNode): MarkdownSourceRange[] {
- const definitions = new Set<string>();
-
- const collectDefinitions = (node: MarkdownSourceNode): void => {
- if (node.name === "LinkReference") {
- const label = childrenOf(node).find((child) => child.name === "LinkLabel");
- if (label && isValidMarkdownLinkReference(source, node)) definitions.add(labelValue(source, label));
- return;
- }
- for (let child = node.firstChild; child; child = child.nextSibling) collectDefinitions(child);
- };
- collectDefinitions(root);
-
- const ranges: MarkdownSourceRange[] = [];
- const collectLinks = (node: MarkdownSourceNode): void => {
- if (node.name === "Link" || node.name === "Image") {
- const children = childrenOf(node);
- const marks = children.filter((child) => child.name === "LinkMark");
- if (marks.length < 2) return;
-
- const labelClose = marks[1].to;
- const isCompleteInlineLink = source[labelClose] === "(" && node.to > labelClose && source[node.to - 1] === ")";
- const referenceLabel = children.find((child) => child.name === "LinkLabel" && child.from >= labelClose);
- const identifier =
- referenceLabel && referenceLabel.to - referenceLabel.from > 2 ? labelValue(source, referenceLabel) : linkTextValue(source, marks);
-
- if (isCompleteInlineLink || definitions.has(identifier)) {
- ranges.push({ from: node.from, to: node.to });
- return;
- }
- for (const child of children) collectLinks(child);
- return;
- }
- for (let child = node.firstChild; child; child = child.nextSibling) collectLinks(child);
- };
- collectLinks(root);
- return ranges.sort((left, right) => left.from - right.from || left.to - right.to);
-}
-
-export function hasExactMarkdownRange(ranges: MarkdownSourceRange[], node: MarkdownSourceNode): boolean {
- return ranges.some((range) => range.from === node.from && range.to === node.to);
-}
diff --git a/web/src/utils/markdown-manipulation.ts b/web/src/utils/markdown-manipulation.ts
index 9534abfc5..afb81e665 100644
--- a/web/src/utils/markdown-manipulation.ts
+++ b/web/src/utils/markdown-manipulation.ts
@@ -12,8 +12,6 @@ interface TaskInfo {
checked: boolean;
}
-export const ORIGINAL_HEADING_ID_ATTRIBUTE = "data-original-heading-id";
-
// Extract all task list items from markdown using AST parsing
// This correctly ignores task-like patterns inside code blocks
function extractTasksFromAst(markdown: string): TaskInfo[] {
@@ -37,41 +35,6 @@ function extractTasksFromAst(markdown: string): TaskInfo[] {
return tasks;
}
-export function toggleTaskAtLine(markdown: string, lineNumber: number, checked: boolean): string {
- const lines = markdown.split("\n");
-
- if (lineNumber < 0 || lineNumber >= lines.length) {
- return markdown;
- }
-
- const line = lines[lineNumber];
-
- // Match bullet and numbered tasks, retaining any trailing carriage return.
- const taskPattern = /^(\s*(?:[-*+]|\d+[.)])\s+)\[([ xX])\](\s+.*)$/s;
- const match = line.match(taskPattern);
-
- if (!match) {
- return markdown;
- }
-
- const [, prefix, , suffix] = match;
- const newCheckmark = checked ? "x" : " ";
- lines[lineNumber] = `${prefix}[${newCheckmark}]${suffix}`;
-
- return lines.join("\n");
-}
-
-export function toggleTaskAtIndex(markdown: string, taskIndex: number, checked: boolean): string {
- const tasks = extractTasksFromAst(markdown);
-
- if (taskIndex < 0 || taskIndex >= tasks.length) {
- return markdown;
- }
-
- const task = tasks[taskIndex];
- return toggleTaskAtLine(markdown, task.lineNumber, checked);
-}
-
export function getTaskLineNumber(markdown: string, taskIndex: number): number {
const tasks = extractTasksFromAst(markdown);
@@ -131,12 +94,6 @@ export function findAnchorTarget(root: ParentNode, fragment: string): Element |
const direct = root.querySelector(`#${CSS.escape(fragment)}`);
if (direct) return direct;
- // Reserved page anchors can force an author-supplied heading id to be suffixed. Keep
- // historical links working by resolving the original id recorded by the heading plugin.
- for (const heading of root.querySelectorAll(`[${ORIGINAL_HEADING_ID_ATTRIBUTE}]`)) {
- if (heading.getAttribute(ORIGINAL_HEADING_ID_ATTRIBUTE) === fragment) return heading;
- }
-
const slugCounts = new Map<string, number>();
for (const heading of root.querySelectorAll("h1, h2, h3, h4, h5, h6")) {
const baseSlug = legacySlugify(heading.textContent ?? "");
diff --git a/web/src/utils/markdown-source-boundaries.ts b/web/src/utils/markdown-source-boundaries.ts
deleted file mode 100644
index b4ded982e..000000000
--- a/web/src/utils/markdown-source-boundaries.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { decodeString } from "micromark-util-decode-string";
-
-export interface MarkdownSourceBoundary {
- from: number;
- to: number;
- type: "Entity" | "Escape";
-}
-
-export interface DecodedMarkdownCharacterReference {
- to: number;
- value: string;
-}
-
-const CHARACTER_REFERENCE_AT_START = /^&(?:#[0-9]{1,7}|#[xX][0-9A-Fa-f]{1,6}|[A-Za-z0-9]{1,31});/;
-
-function isASCIIPunctuation(character: string): boolean {
- const code = character.charCodeAt(0);
- return (
- (code >= 0x21 && code <= 0x2f) || (code >= 0x3a && code <= 0x40) || (code >= 0x5b && code <= 0x60) || (code >= 0x7b && code <= 0x7e)
- );
-}
-
-/** Decode one complete CommonMark character reference starting at `from`. */
-export function decodedMarkdownCharacterReferenceAt(
- source: string,
- from: number,
- to = source.length,
-): DecodedMarkdownCharacterReference | undefined {
- if (source[from] !== "&") return undefined;
- const spelling = source.slice(from, Math.min(to, from + 35)).match(CHARACTER_REFERENCE_AT_START)?.[0];
- if (!spelling) return undefined;
- const value = decodeString(spelling);
- return value === spelling ? undefined : { to: from + spelling.length, value };
-}
-
-/** Find source spellings that Markdown decodes and therefore cannot join tags. */
-export function findDecodedMarkdownSourceBoundaries(source: string, from = 0, to = source.length): MarkdownSourceBoundary[] {
- const ranges: MarkdownSourceBoundary[] = [];
- for (let cursor = from; cursor < to; ) {
- if (source[cursor] === "\\" && cursor + 1 < to && isASCIIPunctuation(source[cursor + 1])) {
- ranges.push({ from: cursor, to: cursor + 2, type: "Escape" });
- cursor += 2;
- continue;
- }
-
- const reference = decodedMarkdownCharacterReferenceAt(source, cursor, to);
- if (reference) {
- ranges.push({ from: cursor, to: reference.to, type: "Entity" });
- cursor = reference.to;
- continue;
- }
-
- const codePoint = source.codePointAt(cursor);
- cursor += codePoint !== undefined && codePoint > 0xffff ? 2 : 1;
- }
- return ranges;
-}
diff --git a/web/src/utils/memo-markdown-extension.ts b/web/src/utils/memo-markdown-extension.ts
deleted file mode 100644
index 02b214dbc..000000000
--- a/web/src/utils/memo-markdown-extension.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { GFM, type MarkdownConfig, type MarkdownExtension } from "@lezer/markdown";
-
-function openingMathFenceSize(line: { text: string; pos: number }): number | undefined {
- let end = line.pos;
- while (line.text.charCodeAt(end) === 0x24) end++;
- const size = end - line.pos;
- if (size < 2 || line.text.indexOf("$", end) >= 0) return undefined;
- return size;
-}
-
-function isClosingMathFence(line: { text: string; pos: number; skipSpace(from: number): number }, openingSize: number): boolean {
- let end = line.pos;
- while (line.text.charCodeAt(end) === 0x24) end++;
- return end - line.pos >= openingSize && line.skipSpace(end) === line.text.length;
-}
-
-function isWhitespace(character: number): boolean {
- return character < 0 || /\p{White_Space}/u.test(String.fromCharCode(character));
-}
-
-function isDigit(character: number): boolean {
- return character >= 0x30 && character <= 0x39;
-}
-
-const mathExtension: MarkdownConfig = {
- defineNodes: ["InlineMath", "MathMark", { name: "BlockMath", block: true }],
- parseBlock: [
- {
- name: "BlockMath",
- parse(context, line) {
- const openingSize = openingMathFenceSize(line);
- if (!openingSize) return false;
-
- const from = context.lineStart + line.pos;
- // This is the same scope guard used by Lezer's fenced-code parser. It
- // keeps an unclosed math block inside its current list or blockquote.
- const activeDepth = context.depth;
- while (context.nextLine() && (line as typeof line & { depth: number }).depth >= activeDepth) {
- if (isClosingMathFence(line, openingSize)) {
- context.nextLine();
- break;
- }
- }
- context.addElement(context.elt("BlockMath", from, context.prevLineEnd()));
- return true;
- },
- endLeaf(_context, line) {
- return openingMathFenceSize(line) !== undefined;
- },
- before: "FencedCode",
- },
- ],
- parseInline: [
- {
- name: "InlineMath",
- parse(context, next, position) {
- if (next !== 0x24) return -1;
-
- let openingEnd = position + 1;
- while (context.char(openingEnd) === 0x24) openingEnd++;
- const openingSize = openingEnd - position;
- if (openingSize === 1 && isWhitespace(context.char(openingEnd))) return openingEnd;
-
- for (let cursor = openingEnd; cursor < context.end; ) {
- if (context.char(cursor) !== 0x24) {
- cursor++;
- continue;
- }
- let closingEnd = cursor + 1;
- while (context.char(closingEnd) === 0x24) closingEnd++;
- const closingSize = closingEnd - cursor;
- if (closingSize === openingSize) {
- if (openingSize === 1 && (isWhitespace(context.char(cursor - 1)) || isDigit(context.char(closingEnd)))) return openingEnd;
- return context.addElement(
- context.elt("InlineMath", position, closingEnd, [
- context.elt("MathMark", position, openingEnd),
- context.elt("MathMark", cursor, closingEnd),
- ]),
- );
- }
- cursor = closingEnd;
- }
- // An unmatched opener is ordinary text. Consume the complete run so
- // a later dollar cannot reinterpret its tail as a shorter opener.
- return openingEnd;
- },
- after: "Escape",
- },
- ],
-};
-
-/** GFM plus the opaque dollar-math nodes understood by the memo renderer. */
-export const memoMarkdownExtensions: MarkdownExtension = [GFM, mathExtension];
diff --git a/web/src/utils/mention-extraction.ts b/web/src/utils/mention-extraction.ts
deleted file mode 100644
index c21bd2888..000000000
--- a/web/src/utils/mention-extraction.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { extractMentionUsernames } from "@/utils/remark-plugins/remark-tag";
diff --git a/web/src/utils/mention-grammar.ts b/web/src/utils/mention-grammar.ts
deleted file mode 100644
index 0e43599ff..000000000
--- a/web/src/utils/mention-grammar.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { isUsernameCharacter, isValidUsername } from "@/utils/username";
-
-export interface MentionMatch {
- from: number;
- to: number;
- username: string;
-}
-
-function hasLeftBoundary(source: string, position: number, runHasLeftBoundary: boolean): boolean {
- if (position === 0) return runHasLeftBoundary;
- return !isUsernameCharacter(source[position - 1]);
-}
-
-/** Find username references in one eligible literal Markdown source run. */
-export function findMentionMatches(source: string, runHasLeftBoundary = true): MentionMatch[] {
- const matches: MentionMatch[] = [];
- for (let position = 0; position < source.length; ) {
- if (source[position] !== "@" || !hasLeftBoundary(source, position, runHasLeftBoundary)) {
- position++;
- continue;
- }
-
- let end = position + 1;
- while (end < source.length && isUsernameCharacter(source[end])) end++;
- const username = source.slice(position + 1, end);
- if (isValidUsername(username)) {
- matches.push({ from: position, to: end, username });
- }
- position = end === position + 1 ? position + 1 : end;
- }
- return matches;
-}
diff --git a/web/src/utils/rehype-plugins/rehype-heading-id.ts b/web/src/utils/rehype-plugins/rehype-heading-id.ts
deleted file mode 100644
index 5cb4bf31a..000000000
--- a/web/src/utils/rehype-plugins/rehype-heading-id.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import type { Element, Root } from "hast";
-import { visit } from "unist-util-visit";
-import { RESERVED_MEMO_COMMENTS_ANCHOR_IDS } from "@/lib/memo-comments";
-import { createUniqueSlugGenerator, ORIGINAL_HEADING_ID_ATTRIBUTE, slugify } from "@/utils/markdown-manipulation";
-
-/** Anchor used for headings with no slugifiable characters (emoji- or punctuation-only titles). */
-const FALLBACK_HEADING_SLUG = "heading";
-
-export const isHeadingElement = (node: Element): boolean => /^h[1-6]$/.test(node.tagName);
-
-/** Rendered text of a heading: element children contribute their text, everything else nothing. */
-export function getHeadingText(node: Element): string {
- let text = "";
- for (const child of node.children) {
- if (child.type === "text") {
- text += child.value;
- } else if (child.type === "element") {
- text += getHeadingText(child);
- }
- }
- return text;
-}
-
-/**
- * Rehype plugin that adds unique slugified `id` attributes to heading elements. This is the
- * single place a heading anchor is decided: the memo outline reads these ids back off the tree
- * rather than deriving its own, so an outline link always has somewhere to land.
- *
- * Every heading consumes a slug — including h5/h6 and titles that slugify to nothing — because
- * the duplicate suffixes depend on how many headings came before.
- */
-export const rehypeHeadingId = () => {
- return (tree: Root) => {
- // Reserve ids supplied by the source or generated by remark-rehype before assigning any new
- // ones. Otherwise an earlier markdown heading can take `footnote-label`, forcing the linked
- // screen-reader footnote label to be renamed without updating its aria-describedby references.
- const existingIds = new Set<string>(RESERVED_MEMO_COMMENTS_ANCHOR_IDS);
- visit(tree, "element", (node: Element) => {
- if (!isHeadingElement(node)) return;
- const existingId = typeof node.properties?.id === "string" ? node.properties.id : "";
- if (existingId) existingIds.add(existingId);
- });
-
- const makeUniqueSlug = createUniqueSlugGenerator(existingIds);
- const claimedExistingIds = new Set<string>(RESERVED_MEMO_COMMENTS_ANCHOR_IDS);
-
- visit(tree, "element", (node: Element) => {
- if (!isHeadingElement(node)) return;
-
- node.properties = node.properties || {};
- const existingId = typeof node.properties.id === "string" ? node.properties.id : "";
- // An id that is already there is linked to from somewhere — remark-rehype points each
- // footnote reference's aria-describedby at its generated label. Keep it, and reserve it so a
- // later heading cannot be given the same slug.
- if (existingId && !claimedExistingIds.has(existingId)) {
- claimedExistingIds.add(existingId);
- node.properties.id = existingId;
- } else {
- const nextId = makeUniqueSlug(existingId || slugify(getHeadingText(node)) || FALLBACK_HEADING_SLUG);
- if (existingId && nextId !== existingId) {
- node.properties[ORIGINAL_HEADING_ID_ATTRIBUTE] = existingId;
- }
- node.properties.id = nextId;
- }
- });
- };
-};
diff --git a/web/src/utils/remark-plugins/remark-currency-safe-math.ts b/web/src/utils/remark-plugins/remark-currency-safe-math.ts
deleted file mode 100644
index dc1650554..000000000
--- a/web/src/utils/remark-plugins/remark-currency-safe-math.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import remarkMath from "remark-math";
-
-type MicromarkCode = number | null;
-type MicromarkState = (code: MicromarkCode) => MicromarkState | undefined;
-
-interface MicromarkEffects {
- consume: (code: number) => undefined;
- [key: string]: unknown;
-}
-
-type MathTokenizer = (this: unknown, effects: MicromarkEffects, ok: MicromarkState, nok: MicromarkState) => MicromarkState;
-
-interface MathTextConstruct {
- tokenize: MathTokenizer;
-}
-
-interface MathSyntaxExtension {
- text?: Record<number, MathTextConstruct | MathTextConstruct[] | undefined>;
-}
-
-interface RemarkMathData {
- micromarkExtensions?: MathSyntaxExtension[];
-}
-
-const DOLLAR_SIGN = 0x24;
-const ASCII_ZERO = 0x30;
-const ASCII_NINE = 0x39;
-
-const isWhitespace = (code: MicromarkCode): boolean => code !== null && (code < 0 || /\p{White_Space}/u.test(String.fromCodePoint(code)));
-
-const isAsciiDigit = (code: MicromarkCode): boolean => code !== null && code >= ASCII_ZERO && code <= ASCII_NINE;
-
-/**
- * Keep remark-math's exact-run and escape behavior while applying Pandoc-style
- * ambiguity guards to single-dollar inline math: no whitespace after an opener
- * or before a closer, and no ASCII digit immediately after a closer. A failed
- * guarded `ok` rolls the attempt back so a later dollar can open valid math.
- */
-const withCurrencySafeBoundaries = (tokenize: MathTokenizer): MathTokenizer =>
- function currencySafeMathText(effects, ok, nok) {
- let openingSize = 0;
- let readingOpening = true;
- let afterOpening: MicromarkCode = null;
- let previousCode: MicromarkCode = null;
- let beforePreviousCode: MicromarkCode = null;
- const trackedEffects = Object.create(effects) as MicromarkEffects;
- trackedEffects.consume = (code) => {
- if (readingOpening && code === DOLLAR_SIGN) {
- openingSize++;
- } else if (readingOpening) {
- readingOpening = false;
- afterOpening = code;
- }
-
- beforePreviousCode = previousCode;
- previousCode = code;
- return effects.consume(code);
- };
-
- const guardedOk: MicromarkState = (nextCode) => {
- if (openingSize !== 1) return ok(nextCode);
-
- if (isWhitespace(afterOpening) || isWhitespace(beforePreviousCode) || isAsciiDigit(nextCode)) {
- return nok(nextCode);
- }
-
- return ok(nextCode);
- };
-
- return tokenize.call(this, trackedEffects, guardedOk, nok);
- };
-
-/** remark-math with currency-safe boundaries for single-dollar inline math. */
-export function remarkCurrencySafeMath(this: unknown): void {
- remarkMath.call(this);
-
- const data = (this as { data: () => RemarkMathData }).data();
- const mathExtension = data.micromarkExtensions?.at(-1);
- const mathText = mathExtension?.text?.[DOLLAR_SIGN];
- if (!mathText || Array.isArray(mathText)) {
- throw new Error("remark-math did not register its inline math tokenizer");
- }
-
- mathText.tokenize = withCurrencySafeBoundaries(mathText.tokenize);
-}
diff --git a/web/src/utils/remark-plugins/remark-disable-setext.ts b/web/src/utils/remark-plugins/remark-disable-setext.ts
deleted file mode 100644
index 4a2d1a7b0..000000000
--- a/web/src/utils/remark-plugins/remark-disable-setext.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-export function remarkDisableSetext(this: unknown) {
- const data = (this as { data: () => Record<string, unknown> }).data();
-
- add("micromarkExtensions", {
- disable: {
- null: ["setextUnderline"],
- },
- });
-
- function add(field: string, value: unknown) {
- const list = data[field] ? (data[field] as unknown[]) : (data[field] = []);
- list.push(value);
- }
-}
diff --git a/web/src/utils/remark-plugins/remark-preserve-type.ts b/web/src/utils/remark-plugins/remark-preserve-type.ts
deleted file mode 100644
index 98791bca9..000000000
--- a/web/src/utils/remark-plugins/remark-preserve-type.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import type { Root } from "mdast";
-import { visit } from "unist-util-visit";
-import type { ExtendedData } from "@/types/markdown";
-
-const STANDARD_NODE_TYPES = new Set(["text", "root", "paragraph", "heading", "list", "listItem"]);
-
-export const remarkPreserveType = () => {
- return (tree: Root) => {
- visit(tree, (node) => {
- if (STANDARD_NODE_TYPES.has(node.type)) {
- return;
- }
-
- if (!node.data) {
- node.data = {};
- }
-
- const data = node.data as ExtendedData;
- data.mdastType = node.type;
- });
- };
-};
diff --git a/web/src/utils/remark-plugins/remark-split-mixed-task-lists.ts b/web/src/utils/remark-plugins/remark-split-mixed-task-lists.ts
deleted file mode 100644
index 4a1d9a99e..000000000
--- a/web/src/utils/remark-plugins/remark-split-mixed-task-lists.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import type { List, ListItem, Root } from "mdast";
-import type { Parent } from "unist";
-
-const isTaskItem = (item: ListItem): boolean => typeof item.checked === "boolean";
-
-const isSingleBlockItem = (item: ListItem): boolean => item.children.length <= 1;
-
-const hasLooseBlockItem = (item: ListItem): boolean => !isSingleBlockItem(item) && Boolean(item.spread);
-
-const normalizeSplitListItems = (items: ListItem[]): ListItem[] =>
- items.map((item) => (isSingleBlockItem(item) ? { ...item, spread: false } : item));
-
-const splitMixedList = (list: List): List[] => {
- const hasTaskItem = list.children.some(isTaskItem);
- const hasRegularItem = list.children.some((item) => !isTaskItem(item));
-
- if (!hasTaskItem || !hasRegularItem) {
- return [list];
- }
-
- const groups: Array<{ isTaskGroup: boolean; items: ListItem[] }> = [];
- for (const item of list.children) {
- const isTaskGroup = isTaskItem(item);
- const previousGroup = groups.at(-1);
-
- if (previousGroup && previousGroup.isTaskGroup === isTaskGroup) {
- previousGroup.items.push(item);
- } else {
- groups.push({ isTaskGroup, items: [item] });
- }
- }
-
- return groups.map(({ items }) => {
- const children = normalizeSplitListItems(items);
- return {
- ...list,
- children,
- spread: children.some(hasLooseBlockItem),
- };
- });
-};
-
-const splitMixedTaskListsInParent = (parent: Parent): void => {
- for (let index = 0; index < parent.children.length; index++) {
- const child = parent.children[index];
-
- if ("children" in child && Array.isArray(child.children)) {
- splitMixedTaskListsInParent(child as Parent);
- }
-
- if (child.type !== "list") {
- continue;
- }
-
- const splitLists = splitMixedList(child as List);
- if (splitLists.length > 1) {
- parent.children.splice(index, 1, ...splitLists);
- index += splitLists.length - 1;
- }
- }
-};
-
-export const remarkSplitMixedTaskLists = () => {
- return (tree: Root) => {
- splitMixedTaskListsInParent(tree);
- };
-};
diff --git a/web/src/utils/remark-plugins/remark-tag.ts b/web/src/utils/remark-plugins/remark-tag.ts
deleted file mode 100644
index 862624c68..000000000
--- a/web/src/utils/remark-plugins/remark-tag.ts
+++ /dev/null
@@ -1,781 +0,0 @@
-import { parser as markdownParser } from "@lezer/markdown";
-import type { Link, Root, Text } from "mdast";
-import { fromMarkdown } from "mdast-util-from-markdown";
-import { gfmFromMarkdown } from "mdast-util-gfm";
-import { gfm } from "micromark-extension-gfm";
-import { decodeString } from "micromark-util-decode-string";
-import type { Node as UnistNode } from "unist";
-import type { MentionNode, MentionNodeData, TagNode, TagNodeData } from "@/types/markdown";
-import { findMarkdownGFMEmailRanges, type GFMEmailSourceRange, type MarkdownSourceNode } from "@/utils/gfm-email";
-import { findMarkdownGFMURLRanges } from "@/utils/gfm-url";
-import { hasExactMarkdownRange, resolvedMarkdownLinkRanges } from "@/utils/markdown-link";
-import { decodedMarkdownCharacterReferenceAt, findDecodedMarkdownSourceBoundaries } from "@/utils/markdown-source-boundaries";
-import { memoMarkdownExtensions } from "@/utils/memo-markdown-extension";
-import { findMentionMatches } from "@/utils/mention-grammar";
-import { findTagMatches } from "@/utils/tag-grammar";
-import { isUsernameCharacter } from "@/utils/username";
-
-type Segment =
- | { type: "text"; value: string }
- | { type: "tag"; source: string; value: string }
- | { type: "mention"; source: string; value: string };
-
-interface SourceRange {
- from: number;
- to: number;
- type: "Entity" | "Escape" | "LineEnding" | "Opaque";
-}
-
-interface MarkdownSourceContext {
- boundaries: SourceRange[];
- emailRanges: GFMEmailSourceRange[];
- emphasisRanges: Array<{ from: number; to: number; delimiterWidth: 1 | 2 }>;
- linkRanges: Array<{ from: number; to: number }>;
- syntaxLinkRanges: Array<{ from: number; to: number }>;
-}
-
-interface LiteralRun {
- source: string;
- sourceFrom: number;
- valueFrom: number;
-}
-
-interface SourceSpan {
- from: number;
- to: number;
-}
-
-const sourceParser = markdownParser.configure(memoMarkdownExtensions);
-const TRANSPARENT_PARENT_TYPES = new Set([
- "blockquote",
- "delete",
- "emphasis",
- "heading",
- "list",
- "listItem",
- "paragraph",
- "root",
- "strong",
- "table",
- "tableCell",
- "tableRow",
-]);
-
-function distinctRanges<T extends SourceSpan>(values: T[], discriminator: (value: T) => string = () => ""): T[] {
- const seen = new Set<string>();
- return values.filter((value) => {
- const key = `${value.from}:${value.to}:${discriminator(value)}`;
- if (seen.has(key)) return false;
- seen.add(key);
- return true;
- });
-}
-
-function markdownSourceContext(source: string): MarkdownSourceContext {
- const ranges: SourceRange[] = [];
- const emphasisRanges: Array<{ from: number; to: number; delimiterWidth: 1 | 2 }> = [];
- const linkRanges: Array<{ from: number; to: number }> = [];
- const syntaxLinkRanges: Array<{ from: number; to: number }> = [];
- const tree = sourceParser.parse(source);
- const sourceRoot = tree.topNode as MarkdownSourceNode;
- const resolvedLinks = resolvedMarkdownLinkRanges(source, sourceRoot);
- const emailRanges = findMarkdownGFMEmailRanges(source, sourceRoot, resolvedLinks, true);
- // Micromark has already consumed the one permitted document BOM before the
- // source reaches this reconciler, so a remaining BOM is ordinary text.
- const writtenURLRanges = findMarkdownGFMURLRanges(source, sourceRoot, resolvedLinks, false);
- linkRanges.push(...writtenURLRanges);
- ranges.push(...writtenURLRanges.map((range) => ({ ...range, type: "Opaque" as const })));
- const decodedBoundaries = findDecodedMarkdownSourceBoundaries(source);
- tree.iterate({
- enter(node) {
- if (node.name === "Escape" || node.name === "Entity") {
- ranges.push({ from: node.from, to: node.to, type: node.name });
- return false;
- }
- if (node.name === "InlineMath" || node.name === "BlockMath") {
- ranges.push({ from: node.from, to: node.to, type: "Opaque" });
- return false;
- }
- if (node.name === "InlineCode") {
- ranges.push({ from: node.from, to: node.to, type: "Opaque" });
- return false;
- }
- if (node.name === "EmphasisMark") {
- ranges.push({ from: node.from, to: node.to, type: "Opaque" });
- return false;
- }
- if (node.name === "Emphasis" || node.name === "StrongEmphasis") {
- emphasisRanges.push({ from: node.from, to: node.to, delimiterWidth: node.name === "StrongEmphasis" ? 2 : 1 });
- }
- if (node.name === "Link" || node.name === "Image" || node.name === "Autolink") {
- if (node.name !== "Autolink" && !hasExactMarkdownRange(resolvedLinks, node.node as MarkdownSourceNode)) return;
- linkRanges.push({ from: node.from, to: node.to });
- syntaxLinkRanges.push({ from: node.from, to: node.to });
- ranges.push({ from: node.from, to: node.to, type: "Opaque" });
- return false;
- }
- },
- });
- ranges.push(
- ...decodedBoundaries.filter(
- (boundary) => !ranges.some((range) => range.type === "Opaque" && range.from <= boundary.from && range.to >= boundary.to),
- ),
- );
-
- const projectUnresolvedSecondLabels = (node: MarkdownSourceNode): void => {
- const unresolvedLinkLike = (node.name === "Link" || node.name === "Image") && !hasExactMarkdownRange(resolvedLinks, node);
- if (unresolvedLinkLike) {
- for (let child = node.firstChild; child; child = child.nextSibling) {
- if (child.name !== "LinkLabel" || child.to - child.from <= 2) continue;
-
- const contentFrom = child.from + 1;
- const contentTo = child.to - 1;
- const prefix = "x ";
- const nested = markdownSourceContext(prefix + source.slice(contentFrom, contentTo));
- const offset = contentFrom - prefix.length;
- const project = <T extends { from: number; to: number }>(ranges: T[]): T[] =>
- ranges
- .filter((range) => range.from >= prefix.length && range.to <= prefix.length + contentTo - contentFrom)
- .map((range) => ({ ...range, from: range.from + offset, to: range.to + offset }));
-
- const excludedSyntheticBoundaryURLs = nested.linkRanges.filter(
- (range) =>
- range.from === prefix.length &&
- !nested.syntaxLinkRanges.some((syntaxRange) => syntaxRange.from === range.from && syntaxRange.to === range.to),
- );
- const isExcludedSyntheticBoundaryURL = (range: { from: number; to: number }) =>
- excludedSyntheticBoundaryURLs.some((excluded) => excluded.from === range.from && excluded.to === range.to);
-
- ranges.push(...project(nested.boundaries.filter((range) => !isExcludedSyntheticBoundaryURL(range))));
- emphasisRanges.push(...project(nested.emphasisRanges));
- linkRanges.push(...project(nested.linkRanges.filter((range) => !isExcludedSyntheticBoundaryURL(range))));
- syntaxLinkRanges.push(...project(nested.syntaxLinkRanges));
- }
- }
- for (let child = node.firstChild; child; child = child.nextSibling) projectUnresolvedSecondLabels(child);
- };
- projectUnresolvedSecondLabels(sourceRoot);
-
- const projectRejectedURLNodes = (parent: MarkdownSourceNode): void => {
- if (
- parent.name === "Autolink" ||
- parent.name === "LinkReference" ||
- ((parent.name === "Link" || parent.name === "Image") && hasExactMarkdownRange(resolvedLinks, parent))
- ) {
- return;
- }
- for (let node = parent.firstChild; node; node = node.nextSibling) {
- if (node.name !== "URL") {
- projectRejectedURLNodes(node);
- continue;
- }
-
- const coveredByCanonicalURL = writtenURLRanges.some((range) => range.from <= node.from && range.to >= node.to);
- const coveredByEmail = emailRanges.some((range) => range.from <= node.from && range.to >= node.to);
- if (!coveredByCanonicalURL && !coveredByEmail) {
- const prefix = "x";
- const nestedSource = prefix + source.slice(node.from, node.to);
- const nested = markdownSourceContext(nestedSource);
- const offset = node.from - prefix.length;
- const project = <T extends { from: number; to: number }>(values: T[]): T[] =>
- values
- .filter((range) => range.from >= prefix.length && range.to <= nestedSource.length)
- .map((range) => ({ ...range, from: range.from + offset, to: range.to + offset }));
-
- ranges.push(...project(nested.boundaries));
- emailRanges.push(...project(nested.emailRanges));
- emphasisRanges.push(...project(nested.emphasisRanges));
- linkRanges.push(...project(nested.linkRanges));
- syntaxLinkRanges.push(...project(nested.syntaxLinkRanges));
-
- if (source.slice(node.from, node.to).includes("_") && source.slice(parent.from, node.from).includes("_")) {
- const insertion = node.from - parent.from;
- const contextualSource = source.slice(parent.from, node.from) + prefix + source.slice(node.from, node.to);
- const contentFrom = insertion + prefix.length;
- sourceParser.parse(contextualSource).iterate({
- enter(mark) {
- if (mark.name === "EmphasisMark" && mark.from >= contentFrom) {
- ranges.push({
- from: mark.from + parent.from - prefix.length,
- to: mark.to + parent.from - prefix.length,
- type: "Opaque",
- });
- }
- },
- });
- }
- }
- }
- };
- projectRejectedURLNodes(sourceRoot);
-
- for (const match of source.matchAll(/\r\n?|\n/g)) {
- const lineEndingTo = match.index + match[0].length;
- if (!ranges.some((range) => range.type === "Opaque" && range.from < lineEndingTo && range.to > match.index)) {
- ranges.push({ from: match.index, to: lineEndingTo, type: "LineEnding" });
- }
- }
- return {
- boundaries: distinctRanges(ranges, (range) => range.type).sort((left, right) => left.from - right.from || left.to - right.to),
- emailRanges: distinctRanges(emailRanges, (range) => range.value),
- emphasisRanges: distinctRanges(emphasisRanges, (range) => String(range.delimiterWidth)).sort(
- (left, right) => left.to - left.from - (right.to - right.from) || left.from - right.from,
- ),
- linkRanges: distinctRanges(linkRanges).sort((left, right) => left.from - right.from || left.to - right.to),
- syntaxLinkRanges: distinctRanges(syntaxLinkRanges).sort((left, right) => left.from - right.from || left.to - right.to),
- };
-}
-
-/**
- * Map original-source literal runs to the decoded mdast text value. Markdown
- * escapes and character references are omitted from the runs and therefore
- * remain hard lexer boundaries.
- */
-function literalRunsForTextNode(
- value: string,
- span: SourceSpan | undefined,
- source: string,
- boundaries: SourceRange[],
-): LiteralRun[] | undefined {
- if (!span) return undefined;
- const { from: start, to: end } = span;
-
- const runs: LiteralRun[] = [];
- let sourceCursor = start;
- let valueCursor = 0;
- let maySkipContainerPrefix = false;
-
- const decodeBoundary = (spelling: string, type: SourceRange["type"]): string => {
- if (type !== "LineEnding") return decodeString(spelling).replaceAll("\0", "�");
- return /^(?:\r\n?|\n)/.test(spelling) ? "\n" : "";
- };
-
- const addRun = (runEnd: number, mayOmitTrailingWhitespace = false): boolean => {
- let runStart = sourceCursor;
- let runSource = source.slice(runStart, runEnd);
- if (!runSource) return true;
-
- let decodedRun = runSource.replaceAll("\0", "�");
- if (!value.startsWith(decodedRun, valueCursor)) {
- if (mayOmitTrailingWhitespace) {
- let trimmedEnd = runEnd;
- while (trimmedEnd > runStart && (source[trimmedEnd - 1] === " " || source[trimmedEnd - 1] === "\t")) trimmedEnd--;
- runSource = source.slice(runStart, trimmedEnd);
- decodedRun = runSource.replaceAll("\0", "�");
- if (value.startsWith(decodedRun, valueCursor)) {
- if (runSource) runs.push({ source: runSource, sourceFrom: runStart, valueFrom: valueCursor });
- valueCursor += decodedRun.length;
- maySkipContainerPrefix = false;
- return true;
- }
- }
- if (!maySkipContainerPrefix) return false;
- let aligned = false;
- while (runStart < runEnd && (source[runStart] === " " || source[runStart] === "\t" || source[runStart] === ">")) {
- runStart++;
- runSource = source.slice(runStart, runEnd);
- decodedRun = runSource.replaceAll("\0", "�");
- if (value.startsWith(decodedRun, valueCursor)) {
- aligned = true;
- break;
- }
- }
- if (!aligned) return false;
- }
-
- if (runSource) runs.push({ source: runSource, sourceFrom: runStart, valueFrom: valueCursor });
- valueCursor += decodedRun.length;
- maySkipContainerPrefix = false;
- return true;
- };
-
- for (const boundary of boundaries) {
- const boundaryFrom = Math.max(boundary.from, start);
- const boundaryTo = Math.min(boundary.to, end);
- if (boundaryFrom >= boundaryTo) continue;
-
- const fullBoundarySource = source.slice(boundary.from, boundary.to);
- const fullDecodedBoundary = decodeBoundary(fullBoundarySource, boundary.type);
- if (boundary.type === "Entity" && fullDecodedBoundary === fullBoundarySource) {
- // Lezer recognizes the shape of unknown named references. Micromark
- // leaves those names literal, so they are not syntax boundaries.
- continue;
- }
-
- const boundarySource = source.slice(boundaryFrom, boundaryTo);
- const decodedBoundary = decodeBoundary(boundarySource, boundary.type);
-
- if (!addRun(boundaryFrom, boundary.type === "LineEnding")) return undefined;
- sourceCursor = boundaryTo;
- if (boundary.type === "LineEnding") {
- const rawLineEnding = boundarySource.match(/^(?:\r\n?|\n)/)?.[0] ?? "";
- if (rawLineEnding && value.startsWith(rawLineEnding, valueCursor)) {
- valueCursor += rawLineEnding.length;
- } else if (rawLineEnding && value.startsWith("\n", valueCursor)) {
- valueCursor++;
- } else if (rawLineEnding) {
- return undefined;
- }
- maySkipContainerPrefix = true;
- continue;
- }
- // remark-gfm sometimes preserves escape/entity source inside a permissive
- // literal link. Prefer that complete raw spelling: a decoded entity such
- // as `&` can otherwise be a misleading prefix of `&amp;`.
- const rawBoundary = boundarySource.replaceAll("\0", "�");
- if (value.startsWith(rawBoundary, valueCursor)) {
- valueCursor += rawBoundary.length;
- } else {
- if (!value.startsWith(decodedBoundary, valueCursor)) return undefined;
- valueCursor += decodedBoundary.length;
- }
- }
-
- if (!addRun(end)) return undefined;
- return runs;
-}
-
-function segmentsForTextNode(
- value: string,
- span: SourceSpan | undefined,
- source: string,
- boundaries: SourceRange[],
-): Segment[] | undefined {
- const runs = literalRunsForTextNode(value, span, source, boundaries);
- if (!runs) return undefined;
-
- const matches = runs
- .flatMap((run) => [
- ...findTagMatches(run.source).map((match) => ({
- type: "tag" as const,
- from: run.valueFrom + match.from,
- to: run.valueFrom + match.to,
- source: run.source.slice(match.from, match.to),
- value: match.value,
- })),
- ...findMentionMatches(run.source, run.sourceFrom === 0 || !isUsernameCharacter(source[run.sourceFrom - 1])).map((match) => ({
- type: "mention" as const,
- from: run.valueFrom + match.from,
- to: run.valueFrom + match.to,
- source: run.source.slice(match.from, match.to),
- value: match.username,
- })),
- ])
- .sort((left, right) => left.from - right.from || left.to - right.to);
- if (matches.length === 0) return [{ type: "text", value }];
-
- const segments: Segment[] = [];
- let cursor = 0;
- for (const match of matches) {
- if (match.from < cursor) continue;
- if (cursor < match.from) segments.push({ type: "text", value: value.slice(cursor, match.from) });
- segments.push({ type: match.type, source: match.source, value: match.value });
- cursor = match.to;
- }
- if (cursor < value.length) segments.push({ type: "text", value: value.slice(cursor) });
- return segments;
-}
-
-function createTagNode(tagValue: string, source: string): TagNode {
- const data: TagNodeData = {
- hName: "span",
- hProperties: {
- className: "tag",
- "data-tag": tagValue,
- },
- hChildren: [{ type: "text", value: source }],
- };
-
- return {
- type: "tagNode",
- value: tagValue,
- data,
- } as TagNode;
-}
-
-function createMentionNode(username: string, source: string): MentionNode {
- const data: MentionNodeData = {
- hName: "span",
- hProperties: {
- className: "mention",
- "data-mention": username,
- },
- hChildren: [{ type: "text", value: source }],
- };
-
- return {
- type: "mentionNode",
- value: username,
- data,
- } as MentionNode;
-}
-
-type ParentNode = UnistNode & { children: UnistNode[] };
-
-function isParentNode(node: UnistNode): node is ParentNode {
- return Array.isArray((node as { children?: unknown }).children);
-}
-
-function positionedSpan(node: UnistNode): SourceSpan | undefined {
- const from = node.position?.start.offset;
- const to = node.position?.end.offset;
- return from === undefined || to === undefined ? undefined : { from, to };
-}
-
-function nodeSpan(node: UnistNode, recoveredSpans: WeakMap<UnistNode, SourceSpan>): SourceSpan | undefined {
- return positionedSpan(node) ?? recoveredSpans.get(node);
-}
-
-function isCoveredBySourceRange(
- node: UnistNode,
- ranges: Array<{ from: number; to: number }>,
- recoveredSpans: WeakMap<UnistNode, SourceSpan>,
-): boolean {
- const span = nodeSpan(node, recoveredSpans);
- return !!span && ranges.some((range) => range.from <= span.from && range.to >= span.to);
-}
-
-function isWrittenGFMLink(node: ParentNode, context: MarkdownSourceContext, recoveredSpans: WeakMap<UnistNode, SourceSpan>): boolean {
- return isCoveredBySourceRange(node, context.linkRanges, recoveredSpans);
-}
-
-function isLiteralEmailLink(node: UnistNode, context: MarkdownSourceContext, recoveredSpans: WeakMap<UnistNode, SourceSpan>): boolean {
- return (
- node.type === "link" &&
- (node as Link).url.startsWith("mailto:") &&
- !isCoveredBySourceRange(node, context.syntaxLinkRanges, recoveredSpans)
- );
-}
-
-function decodedMarkdownText(source: string): string {
- return decodeString(source).replaceAll("\0", "�");
-}
-
-function mergeAdjacentTextNodes(parent: ParentNode, source: string, recoveredSpans: WeakMap<UnistNode, SourceSpan>): void {
- for (let index = 0; index + 1 < parent.children.length; ) {
- const left = parent.children[index];
- const right = parent.children[index + 1];
- if (left.type !== "text" || right.type !== "text") {
- index++;
- continue;
- }
-
- const leftSpan = nodeSpan(left, recoveredSpans);
- const rightSpan = nodeSpan(right, recoveredSpans);
- if (!leftSpan || !rightSpan || leftSpan.to !== rightSpan.from) {
- index++;
- continue;
- }
-
- const mergedSpan = { from: leftSpan.from, to: rightSpan.to };
- const merged = { type: "text", value: decodedMarkdownText(source.slice(mergedSpan.from, mergedSpan.to)) } as Text;
- recoveredSpans.set(merged, mergedSpan);
- parent.children.splice(index, 2, merged);
- }
-}
-
-function decodedSourceProjection(source: string, from: number, to: number): { value: string; starts: number[]; ends: number[] } {
- let value = "";
- const starts: number[] = [];
- const ends: number[] = [];
-
- const append = (raw: string, decoded: string, tokenFrom: number, tokenTo: number) => {
- const normalized = decoded.replaceAll("\0", "�");
- value += normalized;
- for (let index = 0; index < normalized.length; index++) {
- starts.push(raw.length === normalized.length ? tokenFrom + index : tokenFrom);
- ends.push(raw.length === normalized.length ? tokenFrom + index + 1 : tokenTo);
- }
- };
-
- for (let cursor = from; cursor < to; ) {
- if (source[cursor] === "\\" && cursor + 1 < to) {
- const raw = source.slice(cursor, cursor + 2);
- const decoded = decodeString(raw);
- if (decoded !== raw) {
- append(raw, decoded, cursor, cursor + 2);
- cursor += 2;
- continue;
- }
- }
-
- const reference = decodedMarkdownCharacterReferenceAt(source, cursor, to);
- if (reference) {
- append(source.slice(cursor, reference.to), reference.value, cursor, reference.to);
- cursor = reference.to;
- continue;
- }
-
- const codePoint = source.codePointAt(cursor);
- const size = codePoint !== undefined && codePoint > 0xffff ? 2 : 1;
- const raw = source.slice(cursor, Math.min(to, cursor + size));
- append(raw, raw, cursor, cursor + raw.length);
- cursor += raw.length;
- }
-
- return { value, starts, ends };
-}
-
-function recoverTextSpans(
- parent: ParentNode,
- source: string,
- context: MarkdownSourceContext,
- recoveredSpans: WeakMap<UnistNode, SourceSpan>,
-): void {
- const parentSpan = nodeSpan(parent, recoveredSpans);
- if (!parentSpan) return;
-
- for (let index = 0; index < parent.children.length; index++) {
- const child = parent.children[index];
- if (child.type !== "text" || nodeSpan(child, recoveredSpans)) continue;
-
- const textNode = child as Text;
- let lowerBound = parentSpan.from;
- for (let previous = index - 1; previous >= 0; previous--) {
- const span = nodeSpan(parent.children[previous], recoveredSpans);
- if (span) {
- lowerBound = span.to;
- break;
- }
- }
- let upperBound = parentSpan.to;
- for (let next = index + 1; next < parent.children.length; next++) {
- const span = nodeSpan(parent.children[next], recoveredSpans);
- if (span) {
- upperBound = span.from;
- break;
- }
- }
-
- // Positionless nodes are a remark-gfm recovery artifact. Locate their
- // decoded value monotonically inside the surrounding structural source;
- // Markdown delimiters remain in the projection and therefore outside the
- // recovered span.
- const projection = decodedSourceProjection(source, lowerBound, upperBound);
- for (let indexInProjection = projection.value.indexOf(textNode.value); indexInProjection >= 0; ) {
- const lastIndex = indexInProjection + textNode.value.length - 1;
- const span = {
- from: projection.starts[indexInProjection] ?? lowerBound,
- to: projection.ends[lastIndex] ?? projection.starts[indexInProjection] ?? lowerBound,
- };
- if (literalRunsForTextNode(textNode.value, span, source, context.boundaries)) {
- recoveredSpans.set(child, span);
- break;
- }
- indexInProjection = projection.value.indexOf(textNode.value, indexInProjection + 1);
- }
- }
-}
-
-function synthesizeGFMEmailLinks(
- parent: ParentNode,
- source: string,
- context: MarkdownSourceContext,
- recoveredSpans: WeakMap<UnistNode, SourceSpan>,
-): void {
- for (let index = 0; index < parent.children.length; index++) {
- const child = parent.children[index];
- if (child.type !== "text") continue;
-
- const span = nodeSpan(child, recoveredSpans);
- if (!span) continue;
- const emailRanges = context.emailRanges.filter((range) => span.from <= range.from && span.to >= range.to);
- if (emailRanges.length === 0) continue;
-
- const replacement: UnistNode[] = [];
- let cursor = span.from;
- for (const range of emailRanges) {
- if (cursor < range.from) {
- const text = { type: "text", value: decodedMarkdownText(source.slice(cursor, range.from)) } as Text;
- recoveredSpans.set(text, { from: cursor, to: range.from });
- replacement.push(text);
- }
-
- const value = range.value;
- const text = { type: "text", value } as Text;
- const link = { type: "link", title: null, url: `mailto:${value}`, children: [text] } as Link;
- recoveredSpans.set(text, range);
- recoveredSpans.set(link, range);
- replacement.push(link as UnistNode);
- cursor = range.to;
- }
- if (cursor < span.to) {
- const text = { type: "text", value: decodedMarkdownText(source.slice(cursor, span.to)) } as Text;
- recoveredSpans.set(text, { from: cursor, to: span.to });
- replacement.push(text);
- }
-
- parent.children.splice(index, 1, ...replacement);
- index += replacement.length - 1;
- }
-}
-
-function reconcileUnderscoreEmailEmphasis(
- parent: ParentNode,
- source: string,
- context: MarkdownSourceContext,
- recoveredSpans: WeakMap<UnistNode, SourceSpan>,
-): void {
- for (const range of context.emphasisRanges) {
- const delimiter = "_".repeat(range.delimiterWidth);
- if (
- source.slice(range.from, range.from + range.delimiterWidth) !== delimiter ||
- source.slice(range.to - range.delimiterWidth, range.to) !== delimiter
- ) {
- continue;
- }
- const innerFrom = range.from + range.delimiterWidth;
- const innerTo = range.to - range.delimiterWidth;
- if (
- !context.emailRanges.some(
- (emailRange) =>
- emailRange.from >= innerFrom &&
- emailRange.to <= innerTo &&
- [...source.slice(innerFrom, emailRange.from)].every((character) => character === "_"),
- )
- ) {
- continue;
- }
-
- const firstIndex = parent.children.findIndex((child) => {
- const span = nodeSpan(child, recoveredSpans);
- return !!span && span.from <= range.from && span.to >= innerFrom;
- });
- if (firstIndex < 0) continue;
- const lastIndex = parent.children.findIndex((child, index) => {
- const span = nodeSpan(child, recoveredSpans);
- return index >= firstIndex && !!span && span.from <= innerTo && span.to >= range.to;
- });
- if (lastIndex <= firstIndex) continue;
-
- const first = parent.children[firstIndex];
- const last = parent.children[lastIndex];
- const firstSpan = nodeSpan(first, recoveredSpans);
- const lastSpan = nodeSpan(last, recoveredSpans);
- if (first.type !== "text" || last.type !== "text" || !firstSpan || !lastSpan) continue;
-
- const textNode = (from: number, to: number): Text => {
- const text = { type: "text", value: decodedMarkdownText(source.slice(from, to)) } as Text;
- recoveredSpans.set(text, { from, to });
- return text;
- };
- const emphasisChildren: UnistNode[] = [];
- if (innerFrom < firstSpan.to) emphasisChildren.push(textNode(innerFrom, Math.min(firstSpan.to, innerTo)));
- emphasisChildren.push(...parent.children.slice(firstIndex + 1, lastIndex));
- if (lastSpan.from < innerTo) emphasisChildren.push(textNode(Math.max(lastSpan.from, innerFrom), innerTo));
-
- const emphasis = { type: range.delimiterWidth === 2 ? "strong" : "emphasis", children: emphasisChildren } as ParentNode;
- recoveredSpans.set(emphasis, range);
- const replacement: UnistNode[] = [];
- if (firstSpan.from < range.from) replacement.push(textNode(firstSpan.from, range.from));
- replacement.push(emphasis);
- if (range.to < lastSpan.to) replacement.push(textNode(range.to, lastSpan.to));
- parent.children.splice(firstIndex, lastIndex - firstIndex + 1, ...replacement);
- }
-}
-
-/**
- * remark-gfm accepts links beyond written GFM and can split or de-position the
- * surrounding text. Reconcile that drift before scanning so original source
- * ranges, rather than incidental mdast child boundaries, define literal runs.
- */
-function reconcileTextNodes(
- parent: ParentNode,
- source: string,
- context: MarkdownSourceContext,
- recoveredSpans: WeakMap<UnistNode, SourceSpan>,
-): void {
- for (let index = 0; index < parent.children.length; index++) {
- const child = parent.children[index];
-
- if (isParentNode(child) && TRANSPARENT_PARENT_TYPES.has(child.type)) {
- reconcileTextNodes(child, source, context, recoveredSpans);
- } else if (
- child.type === "link" &&
- isParentNode(child) &&
- (isLiteralEmailLink(child, context, recoveredSpans) || !isWrittenGFMLink(child, context, recoveredSpans))
- ) {
- // Rebuild literal emails from canonical source ranges, and unwrap only
- // remark-gfm's broader URL forms. Written GFM URL links stay opaque.
- const span = nodeSpan(child, recoveredSpans);
- if (span) {
- const textNode = { type: "text", value: decodedMarkdownText(source.slice(span.from, span.to)) } as Text;
- recoveredSpans.set(textNode, span);
- parent.children.splice(index, 1, textNode);
- } else {
- parent.children.splice(index, 1, ...child.children);
- }
- index--;
- }
- }
-
- mergeAdjacentTextNodes(parent, source, recoveredSpans);
- recoverTextSpans(parent, source, context, recoveredSpans);
- mergeAdjacentTextNodes(parent, source, recoveredSpans);
- synthesizeGFMEmailLinks(parent, source, context, recoveredSpans);
- reconcileUnderscoreEmailEmphasis(parent, source, context, recoveredSpans);
-}
-
-function transformMemoTextNodes(
- parent: ParentNode,
- source: string,
- context: MarkdownSourceContext,
- recoveredSpans: WeakMap<UnistNode, SourceSpan>,
-): void {
- for (let index = 0; index < parent.children.length; index++) {
- const child = parent.children[index];
-
- if (child.type === "text") {
- const textNode = child as Text;
- const segments = segmentsForTextNode(textNode.value, nodeSpan(textNode, recoveredSpans), source, context.boundaries);
- if (!segments || segments.every((segment) => segment.type === "text")) continue;
-
- const newNodes = segments.map((segment) => {
- if (segment.type === "tag") return createTagNode(segment.value, segment.source);
- if (segment.type === "mention") return createMentionNode(segment.value, segment.source);
- return { type: "text", value: segment.value } as Text;
- });
- parent.children.splice(index, 1, ...(newNodes as UnistNode[]));
- index += newNodes.length - 1;
- continue;
- }
-
- if (isParentNode(child) && TRANSPARENT_PARENT_TYPES.has(child.type)) {
- transformMemoTextNodes(child, source, context, recoveredSpans);
- }
- }
-}
-
-type VFileLike = { value?: string | Uint8Array };
-
-function transformMemoSyntax(tree: Root, rawSource: string): void {
- const source = rawSource.startsWith("\uFEFF") ? rawSource.slice(1) : rawSource;
- const context = markdownSourceContext(source);
- const recoveredSpans = new WeakMap<UnistNode, SourceSpan>();
- reconcileTextNodes(tree as ParentNode, source, context, recoveredSpans);
- transformMemoTextNodes(tree as ParentNode, source, context, recoveredSpans);
-}
-
-/** Transform Memos inline source syntaxes after GFM and math parsing. */
-export const remarkMemoSyntax = () => {
- return (tree: Root, file: VFileLike) => {
- transformMemoSyntax(tree, typeof file.value === "string" ? file.value : "");
- };
-};
-
-/** Extract exact mention candidates with the same Markdown rules used for rendering. */
-export function extractMentionUsernames(source: string): string[] {
- const tree = fromMarkdown(source, {
- extensions: [gfm()],
- mdastExtensions: [gfmFromMarkdown()],
- });
- transformMemoSyntax(tree, source);
-
- const usernames: string[] = [];
- const collect = (node: UnistNode): void => {
- if (node.type === "mentionNode") usernames.push((node as MentionNode).value);
- if (isParentNode(node)) node.children.forEach(collect);
- };
- collect(tree);
- return Array.from(new Set(usernames));
-}
diff --git a/web/src/utils/tag-grammar.ts b/web/src/utils/tag-grammar.ts
index e1ff19471..9549e5889 100644
--- a/web/src/utils/tag-grammar.ts
+++ b/web/src/utils/tag-grammar.ts
@@ -173,7 +173,7 @@ function scanSegment(source: string, from: number, limit: number): SegmentMatch
* Scan one tag candidate beginning at `from`.
*
* Offsets are UTF-16 offsets so callers can use them directly with Markdown
- * source positions and CodeMirror ranges.
+ * source positions and editor offsets.
*/
export function scanTagAt(source: string, from: number, limit = source.length): TagMatch | undefined {
if (!isTagIntroducerAt(source, from, limit)) return undefined;
diff --git a/web/tests/editor-controller.test.ts b/web/tests/editor-controller.test.ts
deleted file mode 100644
index 1a4eea61c..000000000
--- a/web/tests/editor-controller.test.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import { history, redo, undo } from "@codemirror/commands";
-import { markdown } from "@codemirror/lang-markdown";
-import { EditorState } from "@codemirror/state";
-import { EditorView } from "@codemirror/view";
-import { describe, expect, it } from "vitest";
-import { createController } from "@/components/MemoEditor/Editor/controller";
-import { memoMarkdownExtensions } from "@/utils/memo-markdown-extension";
-
-function view(doc = "") {
- return new EditorView({ state: EditorState.create({ doc }) });
-}
-
-describe("source editor controller", () => {
- it("round-trips markdown verbatim, including previously-lossy inputs", () => {
- const v = view();
- const c = createController(v, {} as never);
- for (const md of ["![a](x.png)", "Title\n===", "1. a\n 1. b\n 1. c", "a&nbsp;b"]) {
- c.setMarkdown(md);
- expect(c.getMarkdown()).toBe(md);
- }
- });
-
- it("reports emptiness on whitespace", () => {
- const c = createController(view(" \n "), {} as never);
- expect(c.isEmpty()).toBe(true);
- });
-
- it("inserts markdown as its own block", () => {
- const v = view("alpha");
- const c = createController(v, {} as never);
- v.dispatch({ selection: { anchor: 5 } });
- c.insertMarkdown("beta");
- expect(c.getMarkdown()).toBe("alpha\n\nbeta");
- });
-
- it("captures and restores the cursor", () => {
- const v = view("alpha beta");
- const c = createController(v, {} as never);
- v.dispatch({ selection: { anchor: 7 } });
-
- expect(c.getCursor()).toBe(7);
-
- c.setCursor(99);
- expect(c.getCursor()).toBe(10);
- });
-});
-
-function setup(doc: string) {
- const v = new EditorView({
- state: EditorState.create({ doc, extensions: [markdown({ extensions: memoMarkdownExtensions }), history()] }),
- });
- return { v, c: createController(v, {} as never) };
-}
-
-describe("suggested tag insertion", () => {
- it("inserts an undoable tag at the selection head without replacing highlighted text", () => {
- const { v, c } = setup("alpha beta");
- v.dispatch({ selection: { anchor: 1, head: 5 } });
- expect(c.insertTag("work")).toBe(true);
- expect(c.getMarkdown()).toBe("alpha #work beta");
- expect(v.state.selection.main).toMatchObject({ anchor: 12, head: 12 });
- expect(c.getTags()).toEqual(["work"]);
- expect(undo(v)).toBe(true);
- expect(c.getMarkdown()).toBe("alpha beta");
- expect(redo(v)).toBe(true);
- expect(c.getTags()).toEqual(["work"]);
- v.destroy();
- });
-
- it("inserts successive tags at the caret and isolates each click in history", () => {
- const { v, c } = setup("A note\n\n#work");
- c.setCursor(c.getMarkdown().length);
- c.insertTag("release");
- c.insertTag("planning");
- expect(c.getMarkdown()).toBe("A note\n\n#work #release #planning ");
- undo(v);
- expect(c.getMarkdown()).toBe("A note\n\n#work #release ");
- v.destroy();
- });
-
- it.each([
- ["", 0, "#work ", 6],
- ["alpha beta", 0, "#work alpha beta", 6],
- ["alpha beta", 6, "alpha #work beta", 12],
- ["alphabeta", 5, "alpha #work beta", 12],
- ["alpha\nnext", 5, "alpha #work \nnext", 12],
- ["alpha beta", 10, "alpha beta #work ", 17],
- ])("inserts inline at position %s / %i with natural spacing", (doc, cursor, expected, nextCursor) => {
- const { v, c } = setup(doc);
- c.setCursor(cursor);
- c.insertTag("work");
- expect(c.getMarkdown()).toBe(expected);
- expect(c.getCursor()).toBe(nextCursor);
- v.destroy();
- });
-
- it("honors a cursor inside an unfinished code block instead of moving the tag elsewhere", () => {
- const doc = "```js\nconst x = 1";
- const { v, c } = setup(doc);
- c.setCursor(doc.length);
- expect(c.insertTag("work")).toBe(true);
- expect(c.getMarkdown()).toBe(`${doc} #work `);
- expect(c.getTags()).toEqual([]);
- undo(v);
- expect(c.getMarkdown()).toBe(doc);
- v.destroy();
- });
-
- it("recognizes actual tags, excluding code, links, URLs, escapes, and nested parent names", () => {
- const { v, c } = setup("`#work` [#work](/url) https://example.com/#work \\#work\n\n#work/project");
- expect(c.getTags()).toEqual(["work/project"]);
- c.setCursor(c.getMarkdown().length);
- expect(c.insertTag("work")).toBe(true);
- expect(c.insertTag("work")).toBe(false);
- expect(c.insertTag("two words")).toBe(false);
- expect(c.getTags()).toEqual(["work/project", "work"]);
- v.destroy();
- });
-});
-
-describe("checklist detection", () => {
- it.each([
- ["- [ ] Task", true],
- ["- [X] Done", true],
- ["- Parent\n - [ ] Nested", true],
- ["Note\n\n- [x] Done", true],
- ["```\n- [ ] Example\n```", false],
- ["`- [ ] Example`", false],
- [" - [ ] Indented code", false],
- ["\\- [ ] Escaped", false],
- ["<pre>\n- [ ] HTML\n</pre>", false],
- ["- Plain list", false],
- ])("recognizes rendered tasks in %s", (doc, expected) => {
- const { v, c } = setup(doc);
- expect(c.hasChecklist()).toBe(expected);
- v.destroy();
- });
-});
diff --git a/web/tests/editor-controller.test.tsx b/web/tests/editor-controller.test.tsx
new file mode 100644
index 000000000..a8eccb4e6
--- /dev/null
+++ b/web/tests/editor-controller.test.tsx
@@ -0,0 +1,160 @@
+import { render } from "@testing-library/react";
+import { createRef } from "react";
+import { describe, expect, it, vi } from "vitest";
+import Editor from "@/components/MemoEditor/Editor";
+import type { UploadAnchorDescriptor } from "@/components/MemoEditor/Editor/uploadAnchors";
+import type { EditorController } from "@/components/MemoEditor/types/editorController";
+
+vi.mock("@/hooks/useUserQueries", () => ({
+ useTagCounts: () => ({ data: {} }),
+ useUsersByUsernames: () => ({ data: undefined }),
+}));
+
+function setup(value = "") {
+ const ref = createRef<EditorController>();
+ const onContentChange = vi.fn();
+ const utils = render(
+ <Editor
+ ref={ref}
+ className="x"
+ value={value}
+ placeholder="memo"
+ onContentChange={onContentChange}
+ onFiles={vi.fn()}
+ onSubmit={vi.fn()}
+ />,
+ );
+ return { ...utils, c: ref.current as EditorController, onContentChange };
+}
+
+/** Puts the caret at the end of block `block`. */
+function caretAtEnd(c: EditorController, block: number, offset: number) {
+ c.setSelection({ anchor: { block, offset }, focus: { block, offset } });
+}
+
+const descriptor = (id: string, overrides: Partial<UploadAnchorDescriptor> = {}): UploadAnchorDescriptor => ({
+ id,
+ status: "uploading",
+ completed: 0,
+ total: 1,
+ message: "Uploading images 0/1",
+ retryLabel: "Retry",
+ keepLabel: "Cancel",
+ ...overrides,
+});
+
+describe("editor controller", () => {
+ it("round-trips markdown verbatim", () => {
+ const { c } = setup();
+ for (const md of ["![a](x.png)", "Title\n===", "1. a\n 1. b\n 1. c", "a&nbsp;b", "# Title\n\n- a\n 1. b"]) {
+ c.setMarkdown(md);
+ expect(c.getMarkdown()).toBe(md);
+ }
+ });
+
+ it("reports emptiness on whitespace", () => {
+ const { c } = setup(" ");
+ expect(c.isEmpty()).toBe(true);
+ });
+
+ it("inserts markdown after the caret's block, keeping the text", () => {
+ const { c } = setup("alpha");
+ caretAtEnd(c, 0, 5);
+ c.insertMarkdown("beta");
+ expect(c.getMarkdown()).toBe("alpha\n\nbeta");
+ });
+
+ it("inserts markdown in place of an empty paragraph", () => {
+ const { c } = setup("");
+ c.insertMarkdown("![photo](/file/attachments/photo)");
+ // The caret stays in an empty paragraph below the image.
+ expect(c.getMarkdown().trimEnd()).toBe("![photo](/file/attachments/photo)");
+ });
+
+ it("captures and restores the selection as JSON", () => {
+ const { c } = setup("alpha beta");
+ caretAtEnd(c, 0, 7);
+ expect(c.getSelection()).toEqual({ anchor: { block: 0, offset: 7 }, focus: { block: 0, offset: 7 } });
+ caretAtEnd(c, 0, 99);
+ expect(c.getSelection()?.focus.offset).toBe(10);
+ });
+});
+
+describe("suggested tag insertion", () => {
+ it.each([
+ ["alpha beta", 0, "#work alpha beta"],
+ ["alpha beta", 6, "alpha #work beta"],
+ ["alphabeta", 5, "alpha #work beta"],
+ // A space that ends a paragraph is not saved.
+ ["alpha beta", 10, "alpha beta #work"],
+ ])("inserts inline into %s at %i with natural spacing", (doc, offset, expected) => {
+ const { c } = setup(doc);
+ caretAtEnd(c, 0, offset);
+ expect(c.insertTag("work")).toBe(true);
+ expect(c.getMarkdown()).toBe(expected);
+ expect(c.getTags()).toEqual(["work"]);
+ });
+
+ it("recognizes actual tags, excluding code, links, URLs, escapes, and nested parent names", () => {
+ const { c } = setup("`#work` [#work](/url) https://example.com/#work \\#work\n\n#work/project");
+ expect(c.getTags()).toEqual(["work/project"]);
+ caretAtEnd(c, 1, "#work/project".length);
+ expect(c.insertTag("work")).toBe(true);
+ expect(c.insertTag("work")).toBe(false);
+ expect(c.insertTag("two words")).toBe(false);
+ expect(c.getTags()).toEqual(["work/project", "work"]);
+ });
+});
+
+describe("checklist detection", () => {
+ it.each([
+ ["- [ ] Task", true],
+ ["- [X] Done", true],
+ ["- Parent\n - [ ] Nested", true],
+ ["Note\n\n- [x] Done", true],
+ ["```\n- [ ] Example\n```", false],
+ ["`- [ ] Example`", false],
+ [" - [ ] Indented code", false],
+ ["\\- [ ] Escaped", false],
+ ["<pre>\n- [ ] HTML\n</pre>", false],
+ ["- Plain list", false],
+ ])("recognizes tasks in %s", (doc, expected) => {
+ const { c } = setup(doc);
+ expect(c.hasChecklist()).toBe(expected);
+ });
+});
+
+describe("upload anchors", () => {
+ it("shows an anchor after the caret's block and resolves it into an image block", () => {
+ const { c, container } = setup("alpha");
+ caretAtEnd(c, 0, 5);
+ c.createUploadAnchor(descriptor("upload-one"));
+ expect(container.querySelector(".memo-upload-anchor")).toHaveTextContent("Uploading images 0/1");
+ expect(c.getMarkdown()).toBe("alpha");
+
+ c.resolveUploadAnchor("upload-one", "![photo](/file/attachments/photo)");
+ expect(c.getMarkdown()).toBe("alpha\n\n![photo](/file/attachments/photo)");
+ expect(container.querySelector(".memo-upload-anchor")).toBeNull();
+ });
+
+ it("cancels an anchor without touching the document", () => {
+ const { c, container } = setup("alpha");
+ c.createUploadAnchor(descriptor("upload-two"));
+ c.cancelUploadAnchor("upload-two");
+ expect(container.querySelector(".memo-upload-anchor")).toBeNull();
+ expect(c.getMarkdown()).toBe("alpha");
+ });
+
+ it("rewires failure actions when the anchor updates", () => {
+ const { c, container } = setup("alpha");
+ const stale = vi.fn();
+ const fresh = vi.fn();
+ c.createUploadAnchor(descriptor("upload-three", { status: "failed", onRetry: stale }));
+ c.updateUploadAnchor(descriptor("upload-three", { status: "failed", message: "Retrying soon", onRetry: fresh }));
+
+ expect(container.querySelector(".memo-upload-anchor")).toHaveTextContent("Retrying soon");
+ container.querySelector<HTMLButtonElement>(".memo-upload-anchor-action")?.click();
+ expect(fresh).toHaveBeenCalledTimes(1);
+ expect(stale).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/tests/editor-decorations.test.ts b/web/tests/editor-decorations.test.ts
deleted file mode 100644
index fb8a30ad2..000000000
--- a/web/tests/editor-decorations.test.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-import { markdown } from "@codemirror/lang-markdown";
-import { forceParsing } from "@codemirror/language";
-import { EditorState } from "@codemirror/state";
-import { EditorView } from "@codemirror/view";
-import { describe, expect, it } from "vitest";
-import { findMarkdownMentionMatches, findMarkdownTagMatches } from "@/components/MemoEditor/Editor/markdownTagRanges";
-import { tagMentionDecorations } from "@/components/MemoEditor/Editor/tagMentionDecorations";
-import { memoMarkdownExtensions } from "@/utils/memo-markdown-extension";
-
-function countClass(doc: string, cls: string): number {
- const view = new EditorView({
- state: EditorState.create({ doc, extensions: [markdown({ extensions: memoMarkdownExtensions }), tagMentionDecorations] }),
- parent: document.body,
- });
- forceParsing(view, view.state.doc.length, 1000);
- const n = view.dom.querySelectorAll(`.${cls}`).length;
- view.destroy();
- return n;
-}
-
-describe("tag/mention decorations", () => {
- it("decorates #tags", () => expect(countClass("a #todo and #work/sub b", "cm-memo-tag")).toBe(2));
- it("does not require a left boundary", () => expect(countClass("hello#tag 中文#标签", "cm-memo-tag")).toBe(2));
- it("keeps apostrophes only inside XID words", () => {
- const source = "#tag's #сім'я #O’Brien '#quoted' #users' #'missing";
- const state = EditorState.create({ doc: source, extensions: [markdown({ extensions: memoMarkdownExtensions })] });
- expect(findMarkdownTagMatches(state, 0, source.length).map(({ source, value }) => ({ source, value }))).toEqual([
- { source: "tag's", value: "tag's" },
- { source: "сім'я", value: "сім'я" },
- { source: "O’Brien", value: "O’Brien" },
- { source: "quoted", value: "quoted" },
- { source: "users", value: "users" },
- ]);
- });
- it("uses emitted spans for ignored characters and emoji", () =>
- expect(countClass("#A‍B #́foo #foo/́bar #👩‍💻 #️⃣ ##️⃣", "cm-memo-tag")).toBe(5));
- it("keeps maximal valid prefixes and adjacent tags", () =>
- expect(countClass("#book/ #book//fiction #first#second ##tag", "cm-memo-tag")).toBe(5));
- it("does not cross formatting syntax boundaries", () => expect(countClass("#_foo_ **#urgent**", "cm-memo-tag")).toBe(1));
- it("does not decorate tags in opaque Markdown source", () =>
- expect(
- countClass("`#code` [#label](https://example.com/#link) https://example.com/#url \\#escaped &#35;entity #ok", "cm-memo-tag"),
- ).toBe(1));
- it("keeps unknown character-reference shapes in literal tag source", () =>
- expect(countClass("#R&bogus;D #Q&amp;&bogus;D", "cm-memo-tag")).toBe(2));
- it("supplements decoded source boundaries hidden by broad parser nodes", () => {
- expect(countClass("+http://x.m/#u&#35;#v +http://x.m/#w\\|", "cm-memo-tag")).toBe(3);
- expect(countClass("#a&CounterClockwiseContourIntegral;b#c", "cm-memo-tag")).toBe(2);
- });
- it.each([
- ".https://a.b/`#code` #tail",
- ".https://a.b/[#link](/x) #tail",
- ".https://a.b/![#image](/x) #tail",
- ".https://a.b/$#math$ #tail",
- ])("reparses opaque syntax swallowed by a rejected URL node: %s", (source) => expect(countClass(source, "cm-memo-tag")).toBe(1));
- it("projects emphasis closed inside a rejected URL node", () => {
- const source = "_[http://x.m/#v_>";
- const state = EditorState.create({ doc: source, extensions: [markdown({ extensions: memoMarkdownExtensions })] });
- expect(findMarkdownTagMatches(state, 0, source.length)).toEqual([{ from: 13, to: 15, source: "v", value: "v" }]);
- });
- it("coalesces literal source across a rejected URL node", () => {
- for (const [source, value] of [
- ["#http://x.y/", "http"],
- ["#www.x.y/", "www"],
- ["#b-www.x.y/", "b-www"],
- ]) {
- const state = EditorState.create({ doc: source, extensions: [markdown({ extensions: memoMarkdownExtensions })] });
- expect(findMarkdownTagMatches(state, 0, source.length).map((match) => match.value)).toEqual([value]);
- }
- });
- it("treats a rejected link reference definition as ordinary text", () => {
- expect(countClass("[#-]:(", "cm-memo-tag")).toBe(1);
- expect(countClass("[#use][bad]\n\n[bad]:(", "cm-memo-tag")).toBe(1);
- expect(countClass("[#[email protected]]:(", "cm-memo-tag")).toBe(0);
- expect(countClass("[ https://example.com/#hidden]:(", "cm-memo-tag")).toBe(0);
- });
- it("follows CommonMark tab expansion inside blockquotes", () => {
- expect(countClass(">\t #a", "cm-memo-tag")).toBe(1);
- expect(countClass(" >\t #a", "cm-memo-tag")).toBe(1);
- expect(countClass(" >\t #a", "cm-memo-tag")).toBe(1);
- expect(countClass("- >\t #a", "cm-memo-tag")).toBe(1);
- expect(countClass(">\t #a", "cm-memo-tag")).toBe(0);
- });
- it.each(["- [ ] #a", "- [x] #a", "- [ ] #a\n #b"])("decorates tags in a GFM task item: %s", (source) =>
- expect(countClass(source, "cm-memo-tag")).toBe(source.includes("#b") ? 2 : 1));
- it("keeps GFM URLs and emails opaque in task items", () =>
- expect(countClass("- [ ] https://example.com/#url #[email protected] #tag", "cm-memo-tag")).toBe(1));
- it("keeps the exact value and range before an unknown entity semicolon", () => {
- const source = "#R&bogus;D";
- const state = EditorState.create({ doc: source, extensions: [markdown({ extensions: memoMarkdownExtensions })] });
-
- expect(findMarkdownTagMatches(state, 0, source.length)).toEqual([{ from: 0, to: 8, source: "R&bogus", value: "R&bogus" }]);
- });
- it("decorates tags inside unresolved link-like source", () =>
- expect(countClass("[#tag][missing] [#other](unterminated", "cm-memo-tag")).toBe(2));
- it("decorates tags in both labels when a reference does not resolve", () => {
- expect(countClass("[x][#two]", "cm-memo-tag")).toBe(1);
- expect(countClass("[#one][#two]", "cm-memo-tag")).toBe(2);
- expect(countClass("[x][**#two**]", "cm-memo-tag")).toBe(1);
- expect(countClass("[#x][#_foo_]", "cm-memo-tag")).toBe(1);
- });
- it.each([
- "[#[email protected]][missing]",
- "[#[email protected]](unterminated",
- "![#[email protected]][missing]",
- "[x][_#[email protected]_]",
- "![x][_#[email protected]_]",
- ])("keeps GFM emails opaque inside unresolved link-like source: %s", (source) => expect(countClass(source, "cm-memo-tag")).toBe(0));
- it("reparses all Markdown boundaries in unresolved second labels", () => {
- expect(countClass("[x][<#[email protected]>] ![x][<https://example.com/#foo>]", "cm-memo-tag")).toBe(0);
- expect(countClass("[x][\\#escaped #real] ![x][&#35;escaped #other]", "cm-memo-tag")).toBe(2);
- expect(countClass("[x][#R&amp;D #real]", "cm-memo-tag")).toBe(2);
- expect(countClass("[x][https://example.com/#foo] ![x][https://example.com/#bar]", "cm-memo-tag")).toBe(2);
- });
- it.each(["\n", "\r", "\r\n"])("deduplicates a %j boundary in an unresolved second label", (lineEnding) =>
- expect(countClass(`[#a][${lineEnding}]${lineEnding}${lineEnding}[#a]: /x`, "cm-memo-tag")).toBe(1));
- it("keeps resolved reference and inline links opaque", () =>
- expect(countClass("[#reference][known] [#inline](/path)\n\n[known]: /path", "cm-memo-tag")).toBe(0));
- it.each([
- "[a [#link](x) b][missing]",
- "[a ![#image](x) b][missing]",
- ])("keeps a resolved child opaque inside an unresolved outer link: %s", (source) => expect(countClass(source, "cm-memo-tag")).toBe(0));
- it("fails closed while a distant reference definition is not parsed yet", () => {
- const source = `[#hidden][known]\n\n${"x".repeat(120_000)}\n\n[known]: /path`;
- const state = EditorState.create({ doc: source, extensions: [markdown({ extensions: memoMarkdownExtensions })] });
-
- expect(findMarkdownTagMatches(state, 0, 18)).toEqual([]);
- });
- it("uses CommonMark identifier normalization when resolving reference links", () => {
- expect(countClass("[#hidden][ẞ]\n\n[SS]: /path", "cm-memo-tag")).toBe(0);
- expect(countClass("[#hidden][a\0b]\n\n[a�b]: /path", "cm-memo-tag")).toBe(0);
- expect(countClass("[#visible][\u00a0ref]\n\n[ref]: /path", "cm-memo-tag")).toBe(1);
- });
- it("follows written-GFM URL domain boundaries", () =>
- expect(
- countClass("https://example.COM/#hidden https://a_b.foo.example/路径#also-hidden https://foo_bar.example/#visible", "cm-memo-tag"),
- ).toBe(1));
- it("keeps written GFM URLs with Unicode domains opaque", () =>
- expect(
- countClass(
- "https://點看.com/#hidden www.點看.com/#also-hidden https://a_b.點看.com/#still-hidden " +
- "https://foo_bar.點看/#visible https://點看.com_/#suffix hellohttps://點看.com/#joined",
- "cm-memo-tag",
- ),
- ).toBe(3));
- it("uses GFM protocol and www boundaries for Unicode domains", () =>
- expect(
- countClass(
- "1https://點看.com/#digit .https://點看.com/#punctuation ]www.點看.com/#www " +
- "中https://點看.com/#unicode hellohttps://點看.com/#joined",
- "cm-memo-tag",
- ),
- ).toBe(5));
- it("keeps URLs blocked by unbalanced brackets tag-eligible", () =>
- expect(
- countClass(
- "[https://點看.com/#protocol\n\n[www.點看.com/#www\n\n\\[https://點看.com/#escaped\n\n\\[www.點看.com/#escaped-www",
- "cm-memo-tag",
- ),
- ).toBe(4));
- it("keeps a URL later in unresolved bracket text opaque", () =>
- expect(countClass("[text https://點看.com/#inside\n\n[more https://example.com/#ascii", "cm-memo-tag")).toBe(0));
- it.each([
- "[ https://example.com/#hidden]",
- "[x https://example.com/#hidden]",
- "![ https://example.com/#hidden]",
- ])("follows GFM URL boundaries inside unresolved bracket text: %s", (source) => expect(countClass(source, "cm-memo-tag")).toBe(0));
- it("uses one explicit separator class for written URLs", () =>
- expect(
- countClass(
- "https://點看.com/\u00a0#nbsp https://點看.com/\u2003#em-space https://點看.com/\u000b#vertical-tab " +
- "https://點看.com/\u2028#line-separator https://點看.com/\u2029#paragraph-separator https://點看.com/\u0085#nel-hidden",
- "cm-memo-tag",
- ),
- ).toBe(5));
- it.each([
- "`[` https://example.com/#hidden",
- "$[$ https://example.com/#hidden",
- '<span data-x="[">x</span> https://example.com/#hidden',
- "<https://x.example/[> https://example.com/#hidden",
- ])("ignores brackets in earlier opaque syntax when classifying a URL: %s", (source) => expect(countClass(source, "cm-memo-tag")).toBe(0));
- it("keeps the complete suffix of a recognized GFM URL opaque", () => {
- expect(countClass("http://example.com#z", "cm-memo-tag")).toBe(0);
- expect(countClass("https://foo.example_/#visible", "cm-memo-tag")).toBe(1);
- expect(countClass("\uFEFFhttp://example.com#hidden #shown", "cm-memo-tag")).toBe(1);
- expect(countClass("before\n\n\uFEFFhttp://example.com#shown", "cm-memo-tag")).toBe(1);
- expect(countClass("\uFEFF\uFEFFhttp://example.com#shown", "cm-memo-tag")).toBe(1);
- });
- it.each([
- ])("follows complete GFM email ranges: %s", (doc) => expect(countClass(doc, "cm-memo-tag")).toBe(1));
- it("decodes escapes while reconciling repeated and adjacent GFM email ranges", () => {
- expect(countClass("#foo\\[email protected] #next\\[email protected]", "cm-memo-tag")).toBe(0);
- expect(countClass("#foo\\[email protected] #next\\[email protected]", "cm-memo-mention")).toBe(0);
- expect(countClass("[email protected]@baz.example [email protected][email protected]", "cm-memo-mention")).toBe(0);
- });
- it.each([
- "#foo&#46;[email protected]",
- "#foo&period;[email protected]",
- "#foo&#64;example.com",
- ])("decodes known entities before reconciling a GFM email: %s", (source) => expect(countClass(source, "cm-memo-tag")).toBe(0));
- it("keeps invalid email suffixes tag-eligible and slash-separated locals visible", () => {
- expect(countClass("#foo/[email protected]_", "cm-memo-tag")).toBe(1);
- expect(countClass("#next/[email protected]", "cm-memo-mention")).toBe(0);
- });
- it("does not decorate inline or block dollar math", () =>
- expect(countClass("$#inline$\n\n$$\n#block\n$$\n\n#ok", "cm-memo-tag")).toBe(1));
- it("treats dollar signs after an inline opener as math delimiters even when preceded by a backslash", () => {
- expect(countClass("$#math\\$", "cm-memo-tag")).toBe(0);
- expect(countClass("$\\$#tag$", "cm-memo-tag")).toBe(1);
- });
- it("does not retry inside an unmatched dollar run", () => expect(countClass("$$#tag$", "cm-memo-tag")).toBe(1));
- it.each(["$$\n#block", "$$meta\n#block"])("keeps unclosed flow math opaque: %s", (doc) => expect(countClass(doc, "cm-memo-tag")).toBe(0));
- it("keeps flow math scoped to its list or blockquote", () => {
- expect(countClass("> $$\n> #math\noutside #tag", "cm-memo-tag")).toBe(1);
- expect(countClass("- $$\n #math\noutside #tag", "cm-memo-tag")).toBe(1);
- });
- it("matches flow fence lengths and rejects dollar signs in metadata", () => {
- expect(countClass("$$$\n#math\n$$$\n#ok", "cm-memo-tag")).toBe(1);
- expect(countClass("$$meta$x\n#tag", "cm-memo-tag")).toBe(1);
- });
- it("allows flow math to interrupt a paragraph", () => expect(countClass("text\n$$\n#math", "cm-memo-tag")).toBe(0));
- it("does not let same-line math hide following text", () => expect(countClass("$$#inline$$\n#ok", "cm-memo-tag")).toBe(1));
- it("allows ordinary text between inline HTML tags", () => expect(countClass("<span>#inside</span>", "cm-memo-tag")).toBe(1));
- it("decorates writable username references", () =>
- expect(countClass("@alice @Alice-2 @1alice @a--b @123 @123-456", "cm-memo-mention")).toBe(6));
- it("rejects invalid username shapes", () => expect(countClass("@-alice @alice- @álîçé", "cm-memo-mention")).toBe(0));
- it("applies mention boundaries to source text", () =>
- expect(countClass("hello@alice foo-@bob foo_@carol 中文@dave (@erin) @frank@grace", "cm-memo-mention")).toBe(4));
- it("decorates mentions in transparent formatting", () => expect(countClass("**@Alice** ~~@bob~~ _@carol_", "cm-memo-mention")).toBe(3));
- it("keeps mentions in opaque Markdown source undecorated", () =>
- expect(
- countClass("`@code` [@link](/x) ![@image](/x) https://example.com/@url $@math$ \\@escaped &#64;entity @ok", "cm-memo-mention"),
- ).toBe(1));
- it("keeps GFM emails opaque and does not cross their source boundary", () =>
- expect(countClass("@[email protected] [email protected]@bob @ok", "cm-memo-mention")).toBe(1));
- it("returns the exact mention source range and username", () => {
- const source = "x @Alice-2.";
- const state = EditorState.create({ doc: source, extensions: [markdown({ extensions: memoMarkdownExtensions })] });
-
- expect(findMarkdownMentionMatches(state, 0, source.length)).toEqual([{ from: 2, to: 10, username: "Alice-2" }]);
- });
-});
diff --git a/web/tests/editor-formatting.test.ts b/web/tests/editor-formatting.test.ts
deleted file mode 100644
index 176774192..000000000
--- a/web/tests/editor-formatting.test.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { markdown } from "@codemirror/lang-markdown";
-import { EditorSelection, EditorState } from "@codemirror/state";
-import { EditorView } from "@codemirror/view";
-import { GFM } from "@lezer/markdown";
-import { describe, expect, it } from "vitest";
-import { createFormattingController } from "@/components/MemoEditor/Editor/formatting";
-
-function setup(doc: string, from: number, to: number) {
- const view = new EditorView({
- state: EditorState.create({ doc, extensions: [markdown({ extensions: [GFM] })], selection: EditorSelection.range(from, to) }),
- });
- return { view, f: createFormattingController(view, new Set()) };
-}
-
-describe("formatting controller", () => {
- it("wraps selection in bold and reports active", () => {
- const { view, f } = setup("hello world", 0, 5);
- f.run("bold");
- expect(view.state.doc.toString()).toBe("**hello** world");
- view.dispatch({ selection: { anchor: 3 } });
- expect(f.getActiveFormats().bold).toBe(true);
- });
-
- it("prefixes a heading and reports its level", () => {
- const { view, f } = setup("Title", 0, 0);
- f.run("heading1");
- expect(view.state.doc.toString()).toBe("# Title");
- view.dispatch({ selection: { anchor: 3 } });
- expect(f.getActiveFormats().headingLevel).toBe(1);
- });
-
- it("toggles a bullet list line", () => {
- const { view, f } = setup("item", 0, 0);
- f.run("bulletList");
- expect(view.state.doc.toString()).toBe("- item");
- f.run("bulletList");
- expect(view.state.doc.toString()).toBe("item");
- });
-
- it("unbolds when already bold", () => {
- const { view, f } = setup("**hello** world", 4, 4); // cursor inside bold
- f.run("bold");
- expect(view.state.doc.toString()).toBe("hello world");
- });
-
- it("unwraps italic when already italic", () => {
- const { view, f } = setup("*hi* there", 2, 2);
- f.run("italic");
- expect(view.state.doc.toString()).toBe("hi there");
- });
-
- it("unwraps inline code when already code", () => {
- const { view, f } = setup("`code` here", 3, 3);
- f.run("code");
- expect(view.state.doc.toString()).toBe("code here");
- });
-
- it("toggles strikethrough and reports it active", () => {
- const { view, f } = setup("obsolete text", 0, 8);
-
- f.run("strikethrough");
-
- expect(view.state.doc.toString()).toBe("~~obsolete~~ text");
- expect(f.getActiveFormats().strikethrough).toBe(true);
-
- f.run("strikethrough");
- expect(view.state.doc.toString()).toBe("obsolete text");
- });
-
- it("toggles a fenced code block and reports it active", () => {
- const { view, f } = setup("first\nsecond", 0, 12);
-
- f.run("codeBlock");
-
- expect(view.state.doc.toString()).toBe("```\nfirst\nsecond\n```");
- expect(f.getActiveFormats().codeBlock).toBe(true);
-
- f.run("codeBlock");
- expect(view.state.doc.toString()).toBe("first\nsecond");
- });
-});
diff --git a/web/tests/editor-heading-decorations.test.ts b/web/tests/editor-heading-decorations.test.ts
deleted file mode 100644
index da23cefb6..000000000
--- a/web/tests/editor-heading-decorations.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { markdown } from "@codemirror/lang-markdown";
-import { EditorState } from "@codemirror/state";
-import { EditorView } from "@codemirror/view";
-import { describe, expect, it } from "vitest";
-import { headingDecorations } from "@/components/MemoEditor/Editor/headingDecorations";
-
-function hasClass(doc: string, cls: string): boolean {
- const view = new EditorView({ state: EditorState.create({ doc, extensions: [markdown(), headingDecorations] }), parent: document.body });
- const found = view.dom.querySelector(`.${cls}`) !== null;
- view.destroy();
- return found;
-}
-
-describe("heading line decorations require a space", () => {
- it("styles '# Title' as h1", () => expect(hasClass("# Title", "cm-md-h1")).toBe(true));
- it("styles '### x' as h3", () => expect(hasClass("### x", "cm-md-h3")).toBe(true));
- it("does NOT style a bare '#'", () => expect(hasClass("#", "cm-md-h1")).toBe(false));
- it("does NOT style '#tag' (no space)", () => expect(hasClass("#tag", "cm-md-h1")).toBe(false));
-});
diff --git a/web/tests/editor-keys.test.ts b/web/tests/editor-keys.test.ts
deleted file mode 100644
index 2a1249a04..000000000
--- a/web/tests/editor-keys.test.ts
+++ /dev/null
@@ -1,185 +0,0 @@
-import { EditorState } from "@codemirror/state";
-import { EditorView } from "@codemirror/view";
-import React from "react";
-import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it } from "vitest";
-import { MemoMarkdownRenderer } from "@/components/MemoContent/MemoMarkdownRenderer";
-import { buildEditorExtensions } from "@/components/MemoEditor/Editor/extensions";
-
-function makeView(doc: string, onSubmit: () => void = () => {}) {
- return new EditorView({
- state: EditorState.create({
- doc,
- extensions: buildEditorExtensions({
- placeholder: "",
- onChange: () => {},
- onFiles: () => {},
- onUpdate: () => {},
- onSubmit,
- getTags: () => [],
- }),
- }),
- parent: document.body,
- });
-}
-
-function press(view: EditorView, key: string, opts: KeyboardEventInit = {}) {
- view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...opts }));
-}
-
-function mod(opts: KeyboardEventInit = {}): KeyboardEventInit {
- return /Mac/.test(navigator.platform) ? { ...opts, metaKey: true } : { ...opts, ctrlKey: true };
-}
-
-/** Place the cursor on the given 1-based line, then press Tab/Shift-Tab. */
-function tabOnLine(view: EditorView, lineNumber: number, shiftKey = false) {
- const line = view.state.doc.line(lineNumber);
- view.dispatch({ selection: { anchor: line.to } });
- press(view, "Tab", { shiftKey });
-}
-
-describe("editor key bindings", () => {
- it("Cmd+Enter submits without inserting a blank line", () => {
- let submitted = 0;
- const view = makeView("hello", () => {
- submitted += 1;
- });
- view.dispatch({ selection: { anchor: 5 } });
- press(view, "Enter", { metaKey: true });
- // The save shortcut must outrank defaultKeymap's Mod-Enter (insertBlankLine).
- expect(submitted).toBe(1);
- expect(view.state.doc.toString()).toBe("hello");
- view.destroy();
- });
-
- it("Ctrl+Enter also submits without editing the document", () => {
- let submitted = 0;
- const view = makeView("hello", () => {
- submitted += 1;
- });
- press(view, "Enter", { ctrlKey: true });
- expect(submitted).toBe(1);
- expect(view.state.doc.toString()).toBe("hello");
- view.destroy();
- });
-
- it("plain Enter still inserts a newline", () => {
- const view = makeView("hello");
- view.dispatch({ selection: { anchor: 5 } });
- press(view, "Enter");
- expect(view.state.doc.toString()).toBe("hello\n");
- view.destroy();
- });
-
- it.each([
- ["bold", "b", {}, "**text**"],
- ["italic", "i", {}, "*text*"],
- ["strikethrough", "s", { shiftKey: true }, "~~text~~"],
- ["inline code", "e", {}, "`text`"],
- ["code block", "c", { altKey: true }, "```\ntext\n```"],
- ["ordered list", "7", { shiftKey: true }, "1. text"],
- ["bullet list", "8", { shiftKey: true }, "- text"],
- ["task list", "9", { shiftKey: true }, "- [ ] text"],
- ["heading 1", "1", { altKey: true }, "# text"],
- ["heading 2", "2", { altKey: true }, "## text"],
- ["heading 3", "3", { altKey: true }, "### text"],
- ])("applies %s with its formatting shortcut", (_name, key, modifiers, expected) => {
- const view = makeView("text");
- view.dispatch({ selection: { anchor: 0, head: 4 } });
-
- press(view, key, mod(modifiers));
-
- expect(view.state.doc.toString()).toBe(expected);
- view.destroy();
- });
-
- it("keeps selected trailing whitespace outside a bold mark", () => {
- const view = makeView("23, lemo ");
- view.dispatch({ selection: { anchor: 0, head: 9 } });
-
- press(view, "b", mod());
-
- // `**23, lemo **` is not valid GFM emphasis: its closing delimiter follows
- // whitespace and is rendered literally. The trailing space belongs after
- // the closing delimiter instead.
- expect(view.state.doc.toString()).toBe("**23, lemo** ");
- view.destroy();
- });
-
- it("converts a heading to a paragraph with Mod-Alt-0", () => {
- const view = makeView("## text");
- view.dispatch({ selection: { anchor: 4 } });
-
- press(view, "0", mod({ altKey: true }));
-
- expect(view.state.doc.toString()).toBe("text");
- view.destroy();
- });
-
- it("uses Mod-I for italic instead of CodeMirror's select-parent-syntax command", () => {
- const view = makeView("plain");
- view.dispatch({ selection: { anchor: 0, head: 5 } });
-
- press(view, "i", mod());
-
- expect(view.state.doc.toString()).toBe("*plain*");
- expect(view.state.selection.main).toMatchObject({ from: 1, to: 6 });
- view.destroy();
- });
-
- it("Tab indents a non-list line by two spaces", () => {
- const view = makeView("hello");
- view.dispatch({ selection: { anchor: 0 } });
- press(view, "Tab");
- expect(view.state.doc.toString()).toBe(" hello");
- view.destroy();
- });
-
- it("Escape blurs the editor (keyboard escape hatch)", () => {
- const view = makeView("x");
- view.focus();
- expect(view.hasFocus).toBe(true);
- press(view, "Escape");
- expect(view.hasFocus).toBe(false);
- view.destroy();
- });
-
- it("Tab nests an ordered item: marker-aligned indent + renumbered to 1", () => {
- const view = makeView("1. a\n2. b");
- tabOnLine(view, 2);
- // 3-space indent (past "1. ") AND renumbered 2 -> 1 so CommonMark nests it.
- expect(view.state.doc.toString()).toBe("1. a\n 1. b");
- view.destroy();
- });
-
- it("Tab nests a bullet item to two spaces", () => {
- const view = makeView("- a\n- b");
- tabOnLine(view, 2);
- expect(view.state.doc.toString()).toBe("- a\n - b");
- view.destroy();
- });
-
- it("Shift-Tab outdents a nested list item back to its parent level", () => {
- const view = makeView("1. a\n 2. b");
- tabOnLine(view, 2, true);
- expect(view.state.doc.toString()).toBe("1. a\n2. b");
- view.destroy();
- });
-
- it("Tab-nested ordered lists render nested in the display (no flat siblings)", () => {
- const view = makeView("1. a\n2. b\n3. c");
- tabOnLine(view, 2); // nest b under a
- tabOnLine(view, 3); // nest c under a ...
- tabOnLine(view, 3); // ... then under b
- const md = view.state.doc.toString();
- view.destroy();
- // Each nested level renumbers to 1, which is what CommonMark requires to
- // nest an ordered sublist (a 2./3. start can't interrupt the parent line).
- expect(md).toBe("1. a\n 1. b\n 1. c");
- // remark-gfm (the display) now reads this as three nested ordered lists.
- const html = renderToStaticMarkup(
- React.createElement(MemoMarkdownRenderer, { content: md, resolvedMentionUsernames: new Set<string>() }),
- );
- expect((html.match(/<ol/g) ?? []).length).toBe(3);
- });
-});
diff --git a/web/tests/editor-suggestions.test.tsx b/web/tests/editor-suggestions.test.tsx
index 0501ebe9f..8433346f4 100644
--- a/web/tests/editor-suggestions.test.tsx
+++ b/web/tests/editor-suggestions.test.tsx
@@ -1,4 +1,4 @@
-import { act, fireEvent, render, screen } from "@testing-library/react";
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { useRef } from "react";
import { describe, expect, it, vi } from "vitest";
import { EditorContent } from "@/components/MemoEditor/components/EditorContent";
@@ -9,7 +9,10 @@ import { getMemoSuggestions, type MemoSuggestion } from "@/lib/memo-suggestions"
import { Visibility } from "@/types/proto/api/memo_service_pb";
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
-vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }) }));
+vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }), useUsersByUsernames: () => ({ data: undefined }) }));
+
+/** A caret at `offset` in block `block`. */
+const caret = (block: number, offset: number) => ({ anchor: { block, offset }, focus: { block, offset } });
let editor: ReturnType<typeof useEditorContext>;
let controller: React.RefObject<EditorController | null>;
@@ -35,7 +38,7 @@ function composer(suggestions = candidates, content = "A note", space?: string)
}
describe("editor suggestions", () => {
- it.each(["", " \n\t "])("shows suggestions only after writing content, and hides them when cleared: %j", (content) => {
+ it.each(["", " \n\t "])("shows suggestions only after writing content, and hides them when cleared: %j", async (content) => {
render(composer(candidates, content));
expect(screen.queryByRole("group")).not.toBeInTheDocument();
act(() => controller.current?.setMarkdown("A thought"));
@@ -44,7 +47,7 @@ describe("editor suggestions", () => {
expect(screen.queryByRole("group")).not.toBeInTheDocument();
});
- it("uses a payload-agnostic bar with dashed buttons", () => {
+ it("uses a payload-agnostic bar with dashed buttons", async () => {
const onAccept = vi.fn();
render(<SuggestionsBar suggestions={[{ id: "future:example", label: "Example" }]} disabled={false} onAccept={onAccept} />);
const chip = screen.getByRole("button", { name: "Example" });
@@ -53,29 +56,29 @@ describe("editor suggestions", () => {
expect(onAccept).toHaveBeenCalledWith("future:example");
});
- it("shows at most three and fills the vacated slot after acceptance", () => {
+ it("shows at most three and fills the vacated slot after acceptance", async () => {
render(composer());
expect(screen.getAllByRole("button")).toHaveLength(3);
expect(screen.queryByRole("button", { name: "common.add #later" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "common.add #work" }));
- expect(editor.getState().content).toBe("#work A note");
+ await waitFor(() => expect(editor.getState().content).toBe("#work A note"));
expect(screen.queryByRole("button", { name: "common.add #work" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "common.add #later" })).toBeInTheDocument();
expect(controller.current?.hasFocus()).toBe(true);
});
- it("inserts at the remembered caret when a chip takes focus", () => {
+ it("inserts at the remembered caret when a chip takes focus", async () => {
render(composer(candidates, "Before after"));
- act(() => controller.current?.setCursor(7));
+ act(() => controller.current?.setSelection(caret(0, 7)));
const chip = screen.getByRole("button", { name: "common.add #work" });
act(() => chip.focus());
fireEvent.click(chip);
- expect(editor.getState().content).toBe("Before #work after");
- expect(controller.current?.getCursor()).toBe(13);
+ await waitFor(() => expect(editor.getState().content).toBe("Before #work after"));
+ expect(controller.current?.getSelection()?.focus.offset).toBe(13);
expect(controller.current?.hasFocus()).toBe(true);
});
- it("hides tags in restored and manually edited content, but not inside code", () => {
+ it("hides tags in restored and manually edited content, but not inside code", async () => {
render(composer(candidates, "#work\n\n`#release`"));
expect(screen.queryByRole("button", { name: "common.add #work" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "common.add #release" })).toBeInTheDocument();
@@ -83,7 +86,7 @@ describe("editor suggestions", () => {
expect(screen.queryByRole("button", { name: "common.add #release" })).not.toBeInTheDocument();
});
- it("retains acceptance across removal and context changes, then clears it for a fresh draft", () => {
+ it("retains acceptance across removal and context changes, then clears it for a fresh draft", async () => {
const result = render(composer());
fireEvent.click(screen.getByRole("button", { name: "common.add #work" }));
act(() => controller.current?.setMarkdown("A note"));
@@ -96,7 +99,7 @@ describe("editor suggestions", () => {
expect(screen.getByRole("button", { name: "common.add #work" })).toBeInTheDocument();
});
- it("leaves accepted text intact when context changes and prevents insertion during save", () => {
+ it("leaves accepted text intact when context changes and prevents insertion during save", async () => {
const result = render(composer());
fireEvent.click(screen.getByRole("button", { name: "common.add #work" }));
result.rerender(composer([candidates[1]]));
@@ -108,7 +111,7 @@ describe("editor suggestions", () => {
expect(controller.current?.getMarkdown()).toBe("#work A note");
});
- it("hides the whole row when nothing applies", () => {
+ it("hides the whole row when nothing applies", async () => {
render(composer([], "A note"));
expect(screen.queryByRole("group")).not.toBeInTheDocument();
});
@@ -119,56 +122,56 @@ const publicAudience: MemoSuggestion = { id: "visibility:PUBLIC", kind: "visibil
const spaceAudience: MemoSuggestion = { id: "visibility:SPACE", kind: "visibility", visibility: Visibility.SPACE, source: "view" };
describe("checklist and visibility acceptance", () => {
- it("formats the remembered cursor line and retains acceptance after removal", () => {
- render(composer([checklist], "First\nSecond"));
- act(() => controller.current?.setCursor(8));
+ it("formats the remembered cursor block and retains acceptance after removal", async () => {
+ render(composer([checklist], "First\n\nSecond"));
+ act(() => controller.current?.setSelection(caret(1, 1)));
const chip = screen.getByRole("button", { name: "editor.format.task-list" });
act(() => chip.focus());
fireEvent.click(chip);
- expect(editor.getState().content).toBe("First\n- [ ] Second");
+ await waitFor(() => expect(editor.getState().content).toBe("First\n\n- [ ] Second"));
expect(controller.current?.hasFocus()).toBe(true);
expect(screen.queryByRole("group")).not.toBeInTheDocument();
- act(() => controller.current?.setMarkdown("First\nSecond"));
+ act(() => controller.current?.setMarkdown("First\n\nSecond"));
expect(screen.queryByRole("group")).not.toBeInTheDocument();
act(() => editor.dispatch(editor.actions.reset()));
act(() => controller.current?.setMarkdown("Fresh thought"));
expect(screen.getByRole("button", { name: "editor.format.task-list" })).toBeInTheDocument();
});
- it("converts selected lines while preserving their text", () => {
+ it("converts selected lines while preserving their text", async () => {
render(composer([checklist], "First\n- Second"));
act(() => controller.current?.selectAll());
fireEvent.click(screen.getByRole("button", { name: "editor.format.task-list" }));
- expect(editor.getState().content).toBe("- [ ] First\n- [ ] Second");
+ await waitFor(() => expect(editor.getState().content).toBe("- [ ] First\n- [ ] Second"));
});
- it.each(["- [ ] Task", "- [x] Done", "- Parent\n - [ ] Nested"])("hides an existing checklist: %s", (content) => {
+ it.each(["- [ ] Task", "- [x] Done", "- Parent\n - [ ] Nested"])("hides an existing checklist: %s", async (content) => {
render(composer([checklist], content));
expect(screen.queryByRole("group")).not.toBeInTheDocument();
act(() => controller.current?.setMarkdown("A note"));
expect(screen.getByRole("button", { name: "editor.format.task-list" })).toBeInTheDocument();
});
- it("ignores checklist syntax inside code and reacts to manual insertion", () => {
+ it("ignores checklist syntax inside code and reacts to manual insertion", async () => {
render(composer([checklist], "```\n- [ ] Example\n```"));
expect(screen.getByRole("button", { name: "editor.format.task-list" })).toBeInTheDocument();
act(() => controller.current?.setMarkdown("- [ ] Real task"));
expect(screen.queryByRole("group")).not.toBeInTheDocument();
});
- it("changes visibility only on acceptance, keeps text intact, and remembers the choice", () => {
+ it("changes visibility only on acceptance, keeps text intact, and remembers the choice", async () => {
render(composer([publicAudience]));
expect(editor.getState().metadata.visibility).toBe(Visibility.PRIVATE);
fireEvent.click(screen.getByRole("button", { name: "memo.visibility.public" }));
expect(editor.getState().metadata.visibility).toBe(Visibility.PUBLIC);
- expect(editor.getState().content).toBe("A note");
+ await waitFor(() => expect(editor.getState().content).toBe("A note"));
expect(controller.current?.hasFocus()).toBe(true);
expect(screen.queryByRole("group")).not.toBeInTheDocument();
act(() => editor.dispatch(editor.actions.setMetadata({ visibility: Visibility.PRIVATE })));
expect(screen.queryByRole("group")).not.toBeInTheDocument();
});
- it("hides an already selected audience and reacts to manual changes", () => {
+ it("hides an already selected audience and reacts to manual changes", async () => {
render(composer([publicAudience]));
act(() => editor.dispatch(editor.actions.setMetadata({ visibility: Visibility.PUBLIC })));
expect(screen.queryByRole("group")).not.toBeInTheDocument();
@@ -176,7 +179,7 @@ describe("checklist and visibility acceptance", () => {
expect(screen.getByRole("button", { name: "memo.visibility.public" })).toBeInTheDocument();
});
- it("requires actual Space placement to offer Space visibility", () => {
+ it("requires actual Space placement to offer Space visibility", async () => {
const result = render(composer([spaceAudience]));
expect(screen.queryByRole("group")).not.toBeInTheDocument();
result.rerender(composer([spaceAudience], "A note", "spaces/team"));
@@ -188,7 +191,7 @@ describe("checklist and visibility acceptance", () => {
expect(editor.getState().metadata.visibility).toBe(Visibility.SPACE);
});
- it("shares the three-chip limit across kinds after filtering fulfilled suggestions", () => {
+ it("shares the three-chip limit across kinds after filtering fulfilled suggestions", async () => {
render(composer([...candidates.slice(0, 2), checklist, publicAudience], "#work A note"));
expect(screen.getAllByRole("button")).toHaveLength(3);
expect(screen.getByRole("button", { name: "common.add #release" })).toBeInTheDocument();
@@ -196,7 +199,7 @@ describe("checklist and visibility acceptance", () => {
expect(screen.getByRole("button", { name: "memo.visibility.public" })).toBeInTheDocument();
});
- it("hides all kinds in an empty draft and prevents acceptance while saving", () => {
+ it("hides all kinds in an empty draft and prevents acceptance while saving", async () => {
render(composer([checklist, publicAudience], ""));
expect(screen.queryByRole("group")).not.toBeInTheDocument();
act(() => controller.current?.setMarkdown("A note"));
@@ -205,7 +208,7 @@ describe("checklist and visibility acceptance", () => {
expect(chip).toBeDisabled();
fireEvent.click(chip);
}
- expect(editor.getState().content).toBe("A note");
+ await waitFor(() => expect(editor.getState().content).toBe("A note"));
expect(editor.getState().metadata.visibility).toBe(Visibility.PRIVATE);
});
});
diff --git a/web/tests/editor-tag-autocomplete.test.ts b/web/tests/editor-tag-autocomplete.test.ts
index 6162a926b..85481bfa7 100644
--- a/web/tests/editor-tag-autocomplete.test.ts
+++ b/web/tests/editor-tag-autocomplete.test.ts
@@ -1,181 +1,60 @@
-import { acceptCompletion, CompletionContext, completionStatus, currentCompletions } from "@codemirror/autocomplete";
-import { markdown } from "@codemirror/lang-markdown";
-import { EditorState } from "@codemirror/state";
-import { EditorView } from "@codemirror/view";
-import { waitFor } from "@testing-library/react";
+import { matchToken, type SuggestionAllowContext, scanTags } from "@usememos/editor";
import { describe, expect, it } from "vitest";
-import { buildEditorExtensions } from "@/components/MemoEditor/Editor/extensions";
-import { makeTagCompletionSource } from "@/components/MemoEditor/Editor/tagAutocomplete";
-import { memoMarkdownExtensions } from "@/utils/memo-markdown-extension";
+import { allowTagSuggestion, rankTags } from "@/components/MemoEditor/Editor/extensions";
-function complete(doc: string, pos: number, tags: string[], explicit = false) {
- const source = makeTagCompletionSource(() => tags);
- const state = EditorState.create({ doc, extensions: [markdown({ extensions: memoMarkdownExtensions })] });
- return source(new CompletionContext(state, pos, explicit));
-}
+const match = matchToken(scanTags);
-describe("tag autocomplete", () => {
- it("offers known tags after one character", () => {
- expect(complete("#t", 2, ["thoughts", "today", "work"])?.options.map((o) => o.label)).toEqual(["thoughts", "today"]);
- });
-
- it.each(["hello #", "hello#", "## heading #", "> text #", "- [ ] #", "#######"])("offers all tags after a bare hash: %s", (doc) => {
- const result = complete(doc, doc.length, ["todo", "work"]);
- expect(result?.from).toBe(doc.length);
- expect(result?.options.map((o) => o.label)).toEqual(["todo", "work"]);
- });
-
- it.each([
- "#",
- "##",
- "######",
- " #",
- "> #",
- "> > ###",
- "- #",
- "1. ##",
- "- item\n #",
- "> - ##",
- ])("does not automatically complete an opening heading marker: %s", (doc) => expect(complete(doc, doc.length, ["todo"])).toBeNull());
-
- it("does not complete an opening heading marker before existing heading text", () => {
- for (const pos of [1, 2, 3]) expect(complete("## heading", pos, ["todo"])).toBeNull();
- });
-
- it.each(["#", "> ##", "- #"])("allows explicit completion at an opening heading marker: %s", (doc) => {
- expect(complete(doc, doc.length, ["todo"], true)?.options.map((o) => o.label)).toEqual(["todo"]);
- });
-
- it.each(["#t", "##t", "> #t", "- #t", "1. #t"])("offers tags once the input is not a heading marker: %s", (doc) => {
- expect(complete(doc, doc.length, ["thoughts"])?.options.map((o) => o.label)).toEqual(["thoughts"]);
- });
+/** The token the tag popup sees with the caret at the end of `text`. */
+const tokenAtEnd = (text: string) => match({ text, caret: text.length, content: [{ text, marks: [] }], triggers: ["#", "#"] });
- it.each([
- "`#│`",
- "```\n#│\n```",
- " #│",
- "[#│](/path)",
- "![#│](/path)",
- "[label](https://example.com/#│)",
- "https://example.com/#│",
- "www.點看.com/#│",
- "\\#│",
- "$#│$",
- "$$\n#│\n$$",
- '<span title="#│">',
- "<!-- #│ -->",
- "[#│][known]\n\n[known]: /path",
- ])("completes bare and partial tags regardless of surrounding Markdown: %s", (source) => {
- for (const typed of ["", "t"]) {
- const pos = source.indexOf("│");
- const result = complete(source.replace("│", typed), pos + typed.length, ["thoughts"]);
- expect(result?.from).toBe(pos);
- expect(result?.options.map((o) => o.label)).toEqual(["thoughts"]);
- }
- });
+const allowContext = (overrides: Partial<SuggestionAllowContext>): SuggestionAllowContext =>
+ ({ excluded: false, explicit: false, query: "", textBefore: "", from: 0, ...overrides }) as SuggestionAllowContext;
- it("does not depend on parsing a distant reference definition", () => {
- const doc = `[#ta][known]\n\n${"x".repeat(120_000)}\n\n[known]: /path`;
- expect(complete(doc, doc.indexOf("]"), ["tag"])?.options.map((o) => o.label)).toEqual(["tag"]);
+describe("tag suggestion matching", () => {
+ it.each(["hello #", "#t", "- [ ] #", "#work/", "first line\n#work/"])("finds a tag token being typed: %s", (text) => {
+ expect(tokenAtEnd(text)).not.toBeNull();
});
- it.each(["", "hello world", "# ", "#tag ", "#work//", "&#35;to"])("does not offer tags outside an active tag input: %s", (doc) => {
- expect(complete(doc, doc.length, ["todo", "work/project"])).toBeNull();
- });
-
- it("returns null when no known tags match", () => {
- expect(complete("hello #", 7, [])).toBeNull();
- expect(complete("#missing", 8, ["todo"])).toBeNull();
+ it.each(["", "hello world", "C#", "hello#work", "#work//"])("finds no tag token in %s", (text) => {
+ expect(tokenAtEnd(text)).toBeNull();
});
+});
+describe("tag suggestion ranking", () => {
it("matches a segment of a nested tag path without its parents", () => {
- expect(complete("hello #Mem", 10, ["software/hosted/Memos"])?.options.map((o) => o.label)).toEqual(["software/hosted/Memos"]);
+ expect(rankTags(["software/hosted/Memos"], "Mem")).toEqual(["software/hosted/Memos"]);
});
it("ranks full-path prefixes above segment starts above loose substrings", () => {
- const result = complete("#work", 5, ["home/paperwork", "team/work-log", "work/project"]);
- expect(result?.options.map((o) => o.label)).toEqual(["work/project", "team/work-log", "home/paperwork"]);
- expect(result?.filter).toBe(false);
+ expect(rankTags(["home/paperwork", "team/work-log", "work/project"], "work")).toEqual([
+ "work/project",
+ "team/work-log",
+ "home/paperwork",
+ ]);
});
- it.each(["#work/", "#work/pr", "hello#work/", "first line\n#work/"])("completes child tags after a path separator: %s", (doc) => {
- const result = complete(doc, doc.length, ["work", "work/private", "work/project", "home"]);
- expect(result?.from).toBe(doc.lastIndexOf("#") + 1);
- expect(result?.options.map((o) => o.label)).toEqual(["work/private", "work/project"]);
+ it("completes child tags after a path separator", () => {
+ expect(rankTags(["work/private", "work/project", "home"], "work/")).toEqual(["work/private", "work/project"]);
});
- it.each(["#hosted/", "#software/hosted/"])("matches nested paths at any depth: %s", (doc) => {
- const result = complete(doc, doc.length, ["software/hosted/Memos"]);
- expect(result?.options.map((o) => o.label)).toEqual(["software/hosted/Memos"]);
- expect(result?.from).toBe(1);
- });
-
- it("filters by the emitted Unicode value and replaces the source spelling", () => {
- const result = complete("#A‍B", 4, ["AB", "acorn"]);
- expect(result?.from).toBe(1);
- expect(result?.options.map((o) => o.label)).toEqual(["AB"]);
- expect(complete("#工作/", 4, ["工作/项目"])?.options.map((o) => o.label)).toEqual(["工作/项目"]);
+ it("offers every tag for a bare hash and none when nothing matches", () => {
+ expect(rankTags(["todo", "work"], "")).toEqual(["todo", "work"]);
+ expect(rankTags(["todo"], "missing")).toEqual([]);
});
+});
- it("completes tags containing word-internal apostrophes", () => {
- expect(complete("#O'Br", 5, ["O'Brien", "O’Connor"])?.options.map((o) => o.label)).toEqual(["O'Brien"]);
- expect(complete("#O’Co", 5, ["O'Brien", "O’Connor"])?.options.map((o) => o.label)).toEqual(["O’Connor"]);
+describe("where the tag popup opens", () => {
+ it("stays closed inside code and links", () => {
+ expect(allowTagSuggestion(allowContext({ excluded: true, query: "t" }))).toBe(false);
});
- it("distinguishes keycap emoji from a tag introducer", () => {
- expect(complete("#️⃣", 3, ["#️⃣"])).toBeNull();
- const result = complete("##️⃣", 4, ["#️⃣"]);
- expect(result?.from).toBe(1);
- expect(result?.options.map((o) => o.label)).toEqual(["#️⃣"]);
- for (const [doc, pos] of [
- ["#️⃣", 1],
- ["##️⃣", 2],
- ["#first#️⃣", 7],
- ] as const) {
- expect(complete(doc, pos, ["todo"], true)).toBeNull();
- }
+ it.each(["", " ", "first line\n"])("stays closed for a bare hash that may start a heading: %j", (textBefore) => {
+ expect(allowTagSuggestion(allowContext({ textBefore }))).toBe(false);
});
-});
-// Exercise automatic activation and insertion through the real editor extensions.
-describe("tag completion popup", () => {
- it.each([
- ["hello ", "#", "hello #software/hosted/Memos"],
- ["", "#Mem", "#software/hosted/Memos"],
- ["", "#software/hosted/", "#software/hosted/Memos"],
- ])("opens and inserts a full nested tag after typing %s%s", async (initial, input, expected) => {
- const view = new EditorView({
- state: EditorState.create({
- doc: initial,
- selection: { anchor: initial.length },
- extensions: buildEditorExtensions({
- placeholder: "",
- onChange: () => {},
- onFiles: () => {},
- onUpdate: () => {},
- onSubmit: () => {},
- getTags: () => ["software/hosted/Memos"],
- }),
- }),
- parent: document.body,
- });
- try {
- view.focus();
- for (const character of input) {
- view.dispatch({
- changes: { from: view.state.selection.main.head, insert: character },
- selection: { anchor: view.state.selection.main.head + character.length },
- userEvent: "input.type",
- });
- }
- await waitFor(() => expect(completionStatus(view.state)).toBe("active"));
- expect(currentCompletions(view.state).map((o) => o.label)).toEqual(["software/hosted/Memos"]);
- // CodeMirror briefly ignores acceptance just after the popup opens.
- await waitFor(() => expect(acceptCompletion(view)).toBe(true));
- expect(view.state.doc.toString()).toBe(expected);
- } finally {
- view.destroy();
- }
+ it("opens for a bare hash after text, for a hash with a query, and on Ctrl+Space", () => {
+ expect(allowTagSuggestion(allowContext({ textBefore: "hello " }))).toBe(true);
+ expect(allowTagSuggestion(allowContext({ query: "t" }))).toBe(true);
+ expect(allowTagSuggestion(allowContext({ explicit: true }))).toBe(true);
});
});
diff --git a/web/tests/editor-upload-anchor.test.ts b/web/tests/editor-upload-anchor.test.ts
deleted file mode 100644
index bce8eab8c..000000000
--- a/web/tests/editor-upload-anchor.test.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { EditorState } from "@codemirror/state";
-import { EditorView } from "@codemirror/view";
-import { describe, expect, it, vi } from "vitest";
-import { createController } from "@/components/MemoEditor/Editor/controller";
-import { type UploadAnchorDescriptor, uploadAnchorField } from "@/components/MemoEditor/Editor/uploadAnchors";
-
-const descriptor = (id: string): UploadAnchorDescriptor => ({
- id,
- status: "uploading",
- completed: 0,
- total: 1,
- message: "Uploading images 0/1",
- retryLabel: "Retry",
- keepLabel: "Keep as attachments",
- onRetry: vi.fn(),
- onKeepAttachments: vi.fn(),
-});
-
-const view = (doc = "") => new EditorView({ state: EditorState.create({ doc, extensions: [uploadAnchorField] }) });
-
-describe("editor upload anchors", () => {
- it("maps the anchor through edits before resolving Markdown", () => {
- const editorView = view("alpha");
- const controller = createController(editorView, {} as never);
- controller.setCursor(5);
- controller.createUploadAnchor(descriptor("upload-one"));
-
- editorView.dispatch({ changes: { from: 0, insert: "X" } });
- controller.resolveUploadAnchor("upload-one", "![photo](/file/attachments/photo)");
-
- expect(controller.getMarkdown()).toBe("Xalpha\n\n![photo](/file/attachments/photo)");
- expect(editorView.dom.querySelector(".cm-upload-anchor")).toBeNull();
- });
-
- it("cancels an anchor without changing serialized Markdown", () => {
- const editorView = view("alpha");
- const controller = createController(editorView, {} as never);
- controller.createUploadAnchor(descriptor("upload-two"), 2);
- expect(editorView.dom.querySelector(".cm-upload-anchor")).not.toBeNull();
-
- controller.cancelUploadAnchor("upload-two");
-
- expect(controller.getMarkdown()).toBe("alpha");
- expect(editorView.dom.querySelector(".cm-upload-anchor")).toBeNull();
- });
-
- // The buttons that reach insertMarkdown live outside the editor, and CodeMirror
- // keeps its selection across blur, so an insert must not consume the range.
- it("inserts at the caret without replacing the selection", () => {
- const editorView = view("keep this paragraph of text");
- const controller = createController(editorView, {} as never);
- editorView.dispatch({ selection: { anchor: 5, head: 19 } });
-
- controller.insertMarkdown("![photo](/file/attachments/photo)");
-
- expect(controller.getMarkdown()).toBe("keep this paragraph\n\n![photo](/file/attachments/photo)\n\n of text");
- });
-
- it("re-renders the anchor when only its labels or callbacks change", () => {
- const editorView = view("alpha");
- const controller = createController(editorView, {} as never);
- const stale = vi.fn();
- controller.createUploadAnchor({ ...descriptor("upload-three"), status: "failed", onRetry: stale });
-
- const fresh = vi.fn();
- controller.updateUploadAnchor({ ...descriptor("upload-three"), status: "failed", message: "Retrying soon", onRetry: fresh });
-
- expect(editorView.dom.querySelector(".cm-upload-anchor-badge")?.textContent).toBe("Retrying soon");
- editorView.dom.querySelector<HTMLButtonElement>(".cm-upload-anchor-action")?.click();
- expect(fresh).toHaveBeenCalledTimes(1);
- expect(stale).not.toHaveBeenCalled();
- });
-});
diff --git a/web/tests/editor.test.tsx b/web/tests/editor.test.tsx
index 0015fab4b..7e9fad15d 100644
--- a/web/tests/editor.test.tsx
+++ b/web/tests/editor.test.tsx
@@ -1,143 +1,115 @@
-import { fireEvent, render, waitFor } from "@testing-library/react";
+import { create } from "@bufbuild/protobuf";
+import { render, waitFor } from "@testing-library/react";
import { createRef } from "react";
import { describe, expect, it, vi } from "vitest";
import Editor from "@/components/MemoEditor/Editor";
import type { EditorController } from "@/components/MemoEditor/types/editorController";
+import { UserSetting_TagsSettingSchema } from "@/types/proto/api/user_service_pb";
+import { ColorSchema } from "@/types/proto/google/type/color_pb";
const queries = vi.hoisted(() => ({
useTagCounts: vi.fn(() => ({ data: {} })),
+ users: new Map<string, unknown>(),
}));
vi.mock("@/hooks/useUserQueries", () => ({
useTagCounts: queries.useTagCounts,
+ useUsersByUsernames: (usernames: string[]) => ({
+ data: usernames.length ? new Map(usernames.map((username) => [username, queries.users.get(username)])) : undefined,
+ }),
}));
+const baseProps = {
+ className: "x",
+ placeholder: "memo",
+ onContentChange: () => {},
+ onFiles: () => {},
+ onSubmit: () => {},
+};
+
describe("Editor", () => {
it("scopes tag autocomplete stats to the current user", () => {
- render(<Editor className="x" initialContent="" placeholder="memo" onContentChange={vi.fn()} onFiles={vi.fn()} onSubmit={vi.fn()} />);
+ render(<Editor {...baseProps} value="" />);
expect(queries.useTagCounts).toHaveBeenCalledWith(true);
});
it("loads markdown and serializes it back verbatim", () => {
const ref = createRef<EditorController>();
- render(
- <Editor
- ref={ref}
- className="x"
- initialContent={"# Title\n\n- a\n 1. b"}
- placeholder="memo"
- onContentChange={vi.fn()}
- onFiles={vi.fn()}
- onSubmit={vi.fn()}
- />,
- );
+ render(<Editor {...baseProps} ref={ref} value={"# Title\n\n- a\n 1. b"} />);
expect(ref.current?.getMarkdown()).toBe("# Title\n\n- a\n 1. b");
});
- it("emits changes through onContentChange", () => {
+ it("emits edits through onContentChange", async () => {
const ref = createRef<EditorController>();
- const onChange = vi.fn();
- render(
- <Editor
- ref={ref}
- className="x"
- initialContent=""
- placeholder="memo"
- onContentChange={onChange}
- onFiles={vi.fn()}
- onSubmit={vi.fn()}
- />,
- );
- ref.current?.setMarkdown("hello");
- expect(onChange).toHaveBeenCalledWith("hello");
+ const onContentChange = vi.fn();
+ render(<Editor {...baseProps} ref={ref} value="alpha" onContentChange={onContentChange} />);
+ ref.current?.setSelection({ anchor: { block: 0, offset: 5 }, focus: { block: 0, offset: 5 } });
+ ref.current?.insertMarkdown("beta");
+ await waitFor(() => expect(onContentChange).toHaveBeenLastCalledWith("alpha\n\nbeta"));
});
- it("does not replace newer editor text with a stale local echo", () => {
+ it("applies a new value from outside the editor", () => {
const ref = createRef<EditorController>();
- const props = {
- ref,
- className: "x",
- placeholder: "memo",
- onContentChange: vi.fn(),
- onFiles: vi.fn(),
- onSubmit: vi.fn(),
- };
- const { rerender } = render(<Editor {...props} initialContent="" />);
-
- ref.current?.setMarkdown("H");
- ref.current?.setMarkdown("Hello");
- rerender(<Editor {...props} initialContent="H" contentIsExternal={false} />);
-
- expect(ref.current?.getMarkdown()).toBe("Hello");
+ const { rerender } = render(<Editor {...baseProps} ref={ref} value="draft" />);
+ rerender(<Editor {...baseProps} ref={ref} value="" />);
+ expect(ref.current?.getMarkdown()).toBe("");
});
- it("defers external content until an IME composition ends", async () => {
+ it("does not replace newer editor text with a stale local echo", async () => {
const ref = createRef<EditorController>();
- const onChange = vi.fn();
- const onExternalContentApplied = vi.fn();
- const props = {
- ref,
- className: "x",
- placeholder: "memo",
- onContentChange: onChange,
- onExternalContentApplied,
- onFiles: vi.fn(),
- onSubmit: vi.fn(),
- contentIsExternal: true,
- };
- const { container, rerender } = render(<Editor {...props} initialContent="" />);
- const content = container.querySelector<HTMLElement>(".cm-content");
- expect(content).not.toBeNull();
-
- fireEvent.compositionStart(content!);
- rerender(<Editor {...props} initialContent="server value" />);
- expect(ref.current?.getMarkdown()).toBe("");
+ const emitted: string[] = [];
+ const props = { ...baseProps, ref, onContentChange: (markdown: string) => emitted.push(markdown) };
+ const { rerender } = render(<Editor {...props} value="H" />);
- // A final IME transaction can arrive after the external value entered the
- // store. The deferred external value must still win at compositionend.
- ref.current?.setMarkdown("local composition value");
- expect(onChange).toHaveBeenLastCalledWith("local composition value");
- fireEvent.compositionEnd(content!);
+ ref.current?.insertMarkdown("first");
+ await waitFor(() => expect(emitted).toHaveLength(1));
+ ref.current?.insertMarkdown("second");
+ await waitFor(() => expect(emitted).toHaveLength(2));
+ rerender(<Editor {...props} value={emitted[0]} />);
- await waitFor(() => expect(ref.current?.getMarkdown()).toBe("server value"));
- expect(onExternalContentApplied).toHaveBeenLastCalledWith("server value");
- expect(onChange).not.toHaveBeenCalledWith("server value");
+ expect(ref.current?.getMarkdown()).toBe(emitted[1]);
});
it("enables native text assistance for prose input", () => {
- const props = {
- className: "x",
- initialContent: "",
- placeholder: "memo",
- onContentChange: vi.fn(),
- onFiles: vi.fn(),
- onSubmit: vi.fn(),
- };
- const { container } = render(<Editor {...props} />);
-
- const content = container.querySelector(".cm-content");
- expect(content).toHaveAttribute("autocorrect", "on");
- expect(content).toHaveAttribute("autocapitalize", "on");
- expect(content).toHaveAttribute("spellcheck", "true");
+ const { container } = render(<Editor {...baseProps} value="" />);
+
+ const root = container.querySelector(".memo-editor-root");
+ expect(root).toHaveAttribute("autocorrect", "on");
+ expect(root).toHaveAttribute("autocapitalize", "on");
+ expect(root).toHaveAttribute("spellcheck", "true");
});
- it("reconfigures the placeholder when its translation changes", () => {
- const props = {
- className: "x",
- initialContent: "",
- onContentChange: vi.fn(),
- onFiles: vi.fn(),
- onSubmit: vi.fn(),
- };
- const { container, rerender } = render(<Editor {...props} placeholder="Any thoughts?" />);
+ it("updates the placeholder when its translation changes", () => {
+ const { container, rerender } = render(<Editor {...baseProps} value="" placeholder="Any thoughts?" />);
+ const root = container.querySelector<HTMLElement>(".memo-editor-root");
+ expect(root?.style.getPropertyValue("--mbe-placeholder")).toBe('"Any thoughts?"');
- expect(container.querySelector(".cm-content")).toHaveAttribute("aria-placeholder", "Any thoughts?");
- expect(container.querySelector(".cm-placeholder")).toHaveTextContent("Any thoughts?");
+ rerender(<Editor {...baseProps} value="" placeholder="有什么想法?" />);
+ expect(root?.style.getPropertyValue("--mbe-placeholder")).toBe('"有什么想法?"');
+ });
- rerender(<Editor {...props} placeholder="有什么想法?" />);
+ it("draws tags as the memo view does, in their custom colors", async () => {
+ const tagsSetting = create(UserSetting_TagsSettingSchema, {
+ tags: { work: { backgroundColor: create(ColorSchema, { red: 1, green: 0, blue: 0 }) } },
+ });
+ const { container, rerender } = render(<Editor {...baseProps} value="#work and #life" />);
+ const tag = (name: string) => container.querySelector<HTMLElement>(`.mbe-tag[data-tag="${name}"]`);
+ expect(tag("life")).toHaveClass("rounded-full", "border-primary");
+ expect(tag("work")).not.toHaveAttribute("style");
+
+ rerender(<Editor {...baseProps} value="#work and #life" tagsSetting={tagsSetting} />);
+ await waitFor(() => expect(tag("work")?.getAttribute("style")).toContain("color-mix"));
+ expect(tag("work")).not.toHaveClass("border-primary");
+ });
- expect(container.querySelector(".cm-content")).toHaveAttribute("aria-placeholder", "有什么想法?");
- expect(container.querySelector(".cm-placeholder")).toHaveTextContent("有什么想法?");
+ it("draws mentions of people who exist as the memo view does", async () => {
+ queries.users = new Map([["alice", { name: "users/alice" }]]);
+ const { container } = render(<Editor {...baseProps} value="Hi @alice and @nobody" />);
+ const mention = (name: string) => container.querySelector<HTMLElement>(`.mbe-mention[data-mention="${name}"]`);
+ await waitFor(() => expect(mention("alice")).toHaveAttribute("data-resolved"), { timeout: 2000 });
+ expect(mention("alice")).toHaveClass("text-primary");
+ expect(mention("nobody")).not.toHaveAttribute("data-resolved");
+ expect(mention("nobody")).not.toHaveClass("text-primary");
});
});
diff --git a/web/tests/focus-mode-exit-button.test.tsx b/web/tests/focus-mode-exit-button.test.tsx
new file mode 100644
index 000000000..2df835612
--- /dev/null
+++ b/web/tests/focus-mode-exit-button.test.tsx
@@ -0,0 +1,19 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { FocusModeExitButton } from "@/components/MemoEditor/components/FocusModeOverlay";
+
+vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
+
+describe("FocusModeExitButton", () => {
+ it("minimizes inline focus mode", () => {
+ const onExit = vi.fn();
+ render(<FocusModeExitButton action="minimize" onExit={onExit} />);
+ fireEvent.click(screen.getByRole("button", { name: "editor.exit-focus-mode" }));
+ expect(onExit).toHaveBeenCalledTimes(1);
+ });
+
+ it("reads as Close when a host owns the frame", () => {
+ render(<FocusModeExitButton action="close" onExit={vi.fn()} />);
+ expect(screen.getByRole("button", { name: "common.close" })).toBeInTheDocument();
+ });
+});
diff --git a/web/tests/formatting-toolbar.test.tsx b/web/tests/formatting-toolbar.test.tsx
deleted file mode 100644
index 7786f265f..000000000
--- a/web/tests/formatting-toolbar.test.tsx
+++ /dev/null
@@ -1,96 +0,0 @@
-import { fireEvent, render, screen } from "@testing-library/react";
-import { createRef } from "react";
-import { beforeAll, describe, expect, it, vi } from "vitest";
-import { type ActiveFormatState, EMPTY_ACTIVE_FORMATS } from "@/components/MemoEditor/formatting/commands";
-import { FormattingToolbar } from "@/components/MemoEditor/Toolbar/FormattingToolbar";
-import type { EditorController } from "@/components/MemoEditor/types/editorController";
-
-// Match the repo convention: t echoes the i18n key (no i18next backend in tests),
-// so accessible names below are the keys themselves.
-vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
-
-// Base UI menus reach for layout/pointer APIs jsdom doesn't implement.
-beforeAll(() => {
- Element.prototype.scrollIntoView = vi.fn();
- Element.prototype.hasPointerCapture = vi.fn(() => false);
- Element.prototype.setPointerCapture = vi.fn();
- Element.prototype.releasePointerCapture = vi.fn();
-});
-
-function makeController(opts: { active?: Partial<ActiveFormatState> } = {}) {
- const run = vi.fn();
- const activeFormats: ActiveFormatState = { ...EMPTY_ACTIVE_FORMATS, ...opts.active };
- const controller: EditorController = {
- getTags: () => [],
- hasChecklist: () => false,
- insertTag: vi.fn(() => true),
- focus: () => {},
- hasFocus: () => false,
- isEmpty: () => true,
- getMarkdown: () => "",
- setMarkdown: () => {},
- insertMarkdown: vi.fn(),
- getCursor: () => 0,
- setCursor: vi.fn(),
- scrollToCursor: () => {},
- selectAll: () => {},
- createUploadAnchor: vi.fn(),
- updateUploadAnchor: vi.fn(),
- resolveUploadAnchor: vi.fn(),
- cancelUploadAnchor: vi.fn(),
- formatting: {
- run,
- getActiveFormats: () => activeFormats,
- subscribe: () => () => {},
- },
- };
- return { controller, run };
-}
-
-function renderToolbar(controller: EditorController, action: "minimize" | "close" = "minimize") {
- const ref = createRef<EditorController>();
- ref.current = controller;
- const onExit = vi.fn();
- render(<FormattingToolbar controllerRef={ref} exit={{ action, onExit }} />);
- return { onExit };
-}
-
-describe("FormattingToolbar", () => {
- it("runs the bold command when the bold button is clicked", () => {
- const { controller, run } = makeController();
- renderToolbar(controller);
- fireEvent.click(screen.getByRole("button", { name: "editor.format.bold" }));
- expect(run).toHaveBeenCalledWith("bold");
- });
-
- it("runs the heading command when a heading level is chosen", () => {
- const { controller, run } = makeController();
- renderToolbar(controller);
- fireEvent.click(screen.getByRole("button", { name: "editor.format.heading" }));
- fireEvent.click(screen.getByRole("menuitem", { name: "editor.format.heading-2" }));
- expect(run).toHaveBeenCalledWith("heading2");
- });
-
- it("reflects active marks via aria-pressed", () => {
- const { controller } = makeController({ active: { bold: true } });
- renderToolbar(controller);
- expect(screen.getByRole("button", { name: "editor.format.bold" })).toHaveAttribute("aria-pressed", "true");
- expect(screen.getByRole("button", { name: "editor.format.italic" })).toHaveAttribute("aria-pressed", "false");
- });
-
- it("calls onExit when the exit button is clicked", () => {
- const { controller } = makeController();
- const { onExit } = renderToolbar(controller);
- fireEvent.click(screen.getByRole("button", { name: "editor.exit-focus-mode" }));
- expect(onExit).toHaveBeenCalledTimes(1);
- });
-
- it("labels the exit button as close when a host owns the frame", () => {
- const { controller } = makeController();
- const { onExit } = renderToolbar(controller, "close");
-
- expect(screen.queryByRole("button", { name: "editor.exit-focus-mode" })).not.toBeInTheDocument();
- fireEvent.click(screen.getByRole("button", { name: "common.close" }));
- expect(onExit).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/web/tests/gfm-email.test.ts b/web/tests/gfm-email.test.ts
deleted file mode 100644
index ea1f3ed2c..000000000
--- a/web/tests/gfm-email.test.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { parser as markdownParser } from "@lezer/markdown";
-import { describe, expect, it } from "vitest";
-import { findGFMEmailMatches, findMarkdownGFMEmailRanges, type MarkdownSourceNode } from "@/utils/gfm-email";
-import { resolvedMarkdownLinkRanges } from "@/utils/markdown-link";
-import { memoMarkdownExtensions } from "@/utils/memo-markdown-extension";
-
-describe("GFM email source ranges", () => {
- const range = (from: number, to: number, value: string) => ({ from, to, value });
- const sourceParser = markdownParser.configure(memoMarkdownExtensions);
-
- it.each([
- ["#foo/[email protected]", [range(5, 24, "[email protected]")]],
- ["#foo\\[email protected]", [range(1, 21, "[email protected]")]],
- ["#next\\[email protected]", [range(1, 23, "[email protected]")]],
- ["#foo&#46;[email protected]", [range(1, 24, "[email protected]")]],
- ["#foo&period;[email protected]", [range(1, 27, "[email protected]")]],
- ["#foo&#64;example.com", [range(1, 20, "[email protected]")]],
- ["#foo&bogus;[email protected]", [range(11, 26, "[email protected]")]],
- ["#[email protected]", [range(5, 20, "[email protected]")]],
- ["[email protected]@baz.example", [range(0, 11, "[email protected]")]],
- ["[email protected].", [range(0, 16, "[email protected]")]],
- ["[email protected]_", []],
- ["[email protected]_m", [range(0, 16, "[email protected]_m")]],
- ["[email protected]_", []],
- ["😀[email protected]", [range(2, 17, "[email protected]")]],
- ["([email protected]", [range(1, 17, "[email protected]")]],
- ])("matches canonical ranges in %s", (source, expected) => {
- expect(findGFMEmailMatches(source)).toEqual(expected);
- });
-
- it.each([
- ["[x][_#[email protected]_]", [range(6, 21, "[email protected]")]],
- ["![x][_#[email protected]_]", [range(7, 22, "[email protected]")]],
- ["[x][`#[email protected]`]", []],
- ])("reparses unresolved second-label Markdown in %s", (source, expected) => {
- const root = sourceParser.parse(source).topNode as MarkdownSourceNode;
-
- expect(findMarkdownGFMEmailRanges(source, root, resolvedMarkdownLinkRanges(source, root), true)).toEqual(expected);
- });
-});
diff --git a/web/tests/gfm-url.test.ts b/web/tests/gfm-url.test.ts
deleted file mode 100644
index b3bb702bb..000000000
--- a/web/tests/gfm-url.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { writtenGFMURLSourceRange } from "@/utils/gfm-url";
-
-describe("written GFM URL source ranges", () => {
- it.each([
- ["www.example.com/path?!", "www.example.com/path"],
- ['www.example.com/path\"', "www.example.com/path"],
- ["www.example.com/path))", "www.example.com/path"],
- ["www.example.com/path(value))", "www.example.com/path(value)"],
- ["www.example.com/path&amp;", "www.example.com/path"],
- ["www.example.com/path]", "www.example.com/path"],
- ["www.example.com/path(value)", "www.example.com/path(value)"],
- ])("trims the canonical tail in %s", (source, expected) => {
- expect(writtenGFMURLSourceRange(source, 0)).toEqual({ from: 0, to: expected.length });
- });
-
- it("keeps punctuation that is followed by URL content", () => {
- const source = "www.example.com/path?#tag";
- expect(writtenGFMURLSourceRange(source, 0)).toEqual({ from: 0, to: source.length });
- });
-});
diff --git a/web/tests/insert-menu.test.tsx b/web/tests/insert-menu.test.tsx
index 6e1b9964a..8281ee80b 100644
--- a/web/tests/insert-menu.test.tsx
+++ b/web/tests/insert-menu.test.tsx
@@ -23,8 +23,6 @@ beforeAll(() => {
const viewToggles = {
onToggleFocusMode: vi.fn(),
- isFormattingToolbarVisible: false,
- onToggleFormattingToolbar: vi.fn(),
};
/** `hosted` mirrors an editor whose presentation belongs to a host (the global composer). */
@@ -56,7 +54,6 @@ describe("InsertMenu", () => {
"editor.insert-menu.link-memo",
"editor.insert-menu.add-location",
"editor.focus-mode",
- "editor.formatting-toolbar",
]);
});
@@ -67,7 +64,6 @@ describe("InsertMenu", () => {
const labels = screen.getAllByRole("menuitem").map((item) => item.textContent);
expect(labels).not.toContain("editor.focus-mode");
- expect(labels).not.toContain("editor.formatting-toolbar");
expect(screen.queryByRole("separator")).not.toBeInTheDocument();
});
diff --git a/web/tests/markdown-manipulation.test.ts b/web/tests/markdown-manipulation.test.ts
index f75b86705..b5b0d5516 100644
--- a/web/tests/markdown-manipulation.test.ts
+++ b/web/tests/markdown-manipulation.test.ts
@@ -1,30 +1,5 @@
import { describe, expect, it } from "vitest";
-import { findAnchorTarget, findMemoAnchorTarget, slugify, toggleTaskAtIndex } from "@/utils/markdown-manipulation";
-
-describe("toggleTaskAtIndex", () => {
- it.each(["1.", "1)", "42.", "42)", "-", "*", "+"])("checks and unchecks %s tasks", (marker) => {
- expect(toggleTaskAtIndex(`${marker} [ ] Buy milk`, 0, true)).toBe(`${marker} [x] Buy milk`);
- expect(toggleTaskAtIndex(`${marker} [x] Buy milk`, 0, false)).toBe(`${marker} [ ] Buy milk`);
- expect(toggleTaskAtIndex(`${marker} [X] Buy milk`, 0, false)).toBe(`${marker} [ ] Buy milk`);
- });
-
- it.each(["\n", "\r\n"])("preserves formatting and targets only the selected nested task with %j line endings", (eol) => {
- const lines = ["Intro", "", "- [ ] First", " 1) [ ] Second ", " 2) [x] Third", "", "1. [ ] Last", ""];
- const markdown = lines.join(eol);
- lines[3] = " 1) [x] Second ";
- expect(toggleTaskAtIndex(markdown, 1, true)).toBe(lines.join(eol));
- expect(toggleTaskAtIndex(lines.join(eol), 1, false)).toBe(markdown);
- });
-
- it("ignores checkbox-looking text in fenced, indented, and inline code", () => {
- const lines = ["```md", "1. [ ] Fenced", "```", "", " 1) [ ] Indented", "", "`1. [ ] Inline`", "", "1) [ ] Real"];
- const markdown = lines.join("\n");
- lines[8] = "1) [x] Real";
- expect(toggleTaskAtIndex(markdown, 0, true)).toBe(lines.join("\n"));
- expect(toggleTaskAtIndex(markdown, 1, true)).toBe(markdown);
- expect(toggleTaskAtIndex(markdown, -1, true)).toBe(markdown);
- });
-});
+import { findAnchorTarget, findMemoAnchorTarget, slugify } from "@/utils/markdown-manipulation";
describe("slugify", () => {
it("keeps non-Latin headings addressable", () => {
diff --git a/web/tests/media-loading.test.tsx b/web/tests/media-loading.test.tsx
deleted file mode 100644
index 1abbabac2..000000000
--- a/web/tests/media-loading.test.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { fireEvent, render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
-import { Image } from "@/components/MemoContent/markdown/Image";
-import AudioAttachmentItem from "@/components/MemoMetadata/Attachment/AudioAttachmentItem";
-import MotionPhotoPlayer from "@/components/MotionPhotoPlayer";
-
-describe("media loading", () => {
- it("marks markdown images for native lazy loading", () => {
- render(<Image src="/image.jpg" alt="memo illustration" />);
-
- const image = screen.getByRole("img", { name: "memo illustration" });
- expect(image).toHaveAttribute("loading", "lazy");
- expect(image).toHaveAttribute("decoding", "async");
- });
-
- it("does not bind an audio source until playback is requested", async () => {
- const play = vi.spyOn(HTMLMediaElement.prototype, "play").mockResolvedValue();
- const { container } = render(<AudioAttachmentItem filename="recording.mp3" sourceUrl="/recording.mp3" mimeType="audio/mpeg" />);
- const audio = container.querySelector("audio");
-
- expect(audio).not.toHaveAttribute("src");
- expect(audio).toHaveAttribute("preload", "none");
-
- fireEvent.click(screen.getByRole("button", { name: "Play recording.mp3" }));
-
- expect(audio).toHaveAttribute("src", "/recording.mp3");
- expect(play).toHaveBeenCalledOnce();
- });
-
- it("defers binding the motion video until first activation, then keeps it for replays", () => {
- vi.spyOn(HTMLMediaElement.prototype, "play").mockResolvedValue();
- const pause = vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(() => {});
-
- const { container, rerender } = render(
- <MotionPhotoPlayer posterUrl="/poster.jpg" motionUrl="/motion.mp4" alt="Live photo" active={false} />,
- );
- const video = container.querySelector("video");
-
- expect(video).not.toHaveAttribute("src");
- expect(video).toHaveAttribute("preload", "none");
-
- rerender(<MotionPhotoPlayer posterUrl="/poster.jpg" motionUrl="/motion.mp4" alt="Live photo" active />);
- expect(video).toHaveAttribute("src", "/motion.mp4");
-
- // Deactivating pauses playback but keeps the buffered source bound.
- rerender(<MotionPhotoPlayer posterUrl="/poster.jpg" motionUrl="/motion.mp4" alt="Live photo" active={false} />);
- expect(pause).toHaveBeenCalled();
- expect(video).toHaveAttribute("src", "/motion.mp4");
- });
-});
diff --git a/web/tests/memo-body-compact.test.tsx b/web/tests/memo-body-compact.test.tsx
index 3f0e956cb..996c793f5 100644
--- a/web/tests/memo-body-compact.test.tsx
+++ b/web/tests/memo-body-compact.test.tsx
@@ -25,8 +25,12 @@ vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({
useResolvedMentionUsernames: () => new Set<string>(),
}));
-vi.mock("@/components/MemoContent/MemoMarkdownRenderer", () => ({
- MemoMarkdownRenderer: ({ content }: { content: string }) => <div>{content}</div>,
+vi.mock("@/components/MemoContent", () => ({
+ default: ({ content }: { content: string }) => <div>{content}</div>,
+}));
+
+vi.mock("@/hooks/useMemoQueries", () => ({
+ useUpdateMemo: () => ({ mutate: vi.fn() }),
}));
vi.mock("@/components/MemoMetadata", () => ({
diff --git a/web/tests/memo-content-details.test.tsx b/web/tests/memo-content-details.test.tsx
deleted file mode 100644
index 5bc0a1cc8..000000000
--- a/web/tests/memo-content-details.test.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { fireEvent, render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
-import { MemoMarkdownRenderer } from "@/components/MemoContent/MemoMarkdownRenderer";
-
-vi.mock("@/contexts/ViewContext", () => ({
- useLinkPreviewEnabled: () => true,
-}));
-
-const renderContent = (content: string) => render(<MemoMarkdownRenderer content={content} resolvedMentionUsernames={new Set()} />);
-
-describe("memo content disclosures", () => {
- it("preserves native toggling, inline summary markup, and authored open state", () => {
- const { container } = renderContent("<details open><summary>Read <em>more</em></summary>\n\nSupporting text.\n\n</details>");
- const details = container.querySelector("details");
- const summary = container.querySelector("summary");
-
- expect(details).toHaveAttribute("open");
- expect(details?.firstElementChild).toBe(summary);
- expect(summary?.querySelector("em")).toHaveTextContent("more");
- expect(summary?.querySelector("svg")).toHaveAttribute("aria-hidden", "true");
- expect(screen.getByText("Supporting text.")).toBeVisible();
- expect(container.querySelector("[node]")).toBeNull();
-
- fireEvent.click(summary!);
- expect(details).not.toHaveAttribute("open");
- fireEvent.click(summary!);
- expect(details).toHaveAttribute("open");
- });
-
- it("keeps nested and sibling disclosures independent", () => {
- const { container } = renderContent(
- "<details open><summary>Outer</summary><details><summary>Inner</summary>Nested text</details></details>\n\n<details><summary>Sibling</summary>Other text</details>",
- );
- const [outer, inner, sibling] = container.querySelectorAll("details");
-
- fireEvent.click(screen.getByText("Inner"));
- expect(outer).toHaveAttribute("open");
- expect(inner).toHaveAttribute("open");
- expect(sibling).not.toHaveAttribute("open");
-
- fireEvent.click(screen.getByText("Outer"));
- expect(outer).not.toHaveAttribute("open");
- expect(inner).toHaveAttribute("open");
- });
-
- it("keeps Markdown and bare links inside the disclosure without promoting links to preview cards", () => {
- const { container } = renderContent(
- "<details><summary>Notes</summary>\n\n- **First** point\n- Second point\n\nhttps://example.com\n\n</details>",
- );
-
- expect(container.querySelector("details ul li strong")).toHaveTextContent("First");
- expect(container.querySelector("details p > a")).toHaveAttribute("href", "https://example.com");
- });
-
- it("retains the browser fallback when a summary is omitted", () => {
- const { container } = renderContent("<details>\n\nSupporting text.\n\n</details>");
-
- expect(container.querySelector("details > p")).toHaveTextContent("Supporting text.");
- expect(container.querySelector("summary")).toBeNull();
- });
-});
diff --git a/web/tests/memo-content-footnotes.test.tsx b/web/tests/memo-content-footnotes.test.tsx
deleted file mode 100644
index eed1ede12..000000000
--- a/web/tests/memo-content-footnotes.test.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { fireEvent, render, screen } from "@testing-library/react";
-import { MemoryRouter, useLocation } from "react-router-dom";
-import { beforeAll, describe, expect, it, vi } from "vitest";
-import { MemoMarkdownRendererCore } from "@/components/MemoContent/MemoMarkdownRenderer";
-
-const FOOTNOTE_MARKDOWN = "A statement with a note.[^1]\n\n[^1]: The footnote body.";
-
-const LocationProbe = () => {
- const location = useLocation();
- return (
- <>
- <output data-testid="location">{`${location.pathname}${location.hash}`}</output>
- <output data-testid="origin">{typeof location.state?.from === "string" ? location.state.from : ""}</output>
- </>
- );
-};
-
-const renderFootnote = (compact = false, parentPage?: string) =>
- render(
- <MemoryRouter>
- <div data-memo-content>
- <MemoMarkdownRendererCore
- content={FOOTNOTE_MARKDOWN}
- resolvedMentionUsernames={new Set()}
- memoName="memos/abc123"
- parentPage={parentPage}
- compact={compact}
- />
- </div>
- <LocationProbe />
- </MemoryRouter>,
- );
-
-describe("memo footnotes", () => {
- beforeAll(() => {
- Element.prototype.scrollIntoView = vi.fn();
- if (!globalThis.CSS) {
- Object.defineProperty(globalThis, "CSS", { configurable: true, value: {} });
- }
- if (!globalThis.CSS.escape) {
- globalThis.CSS.escape = (value: string) => value;
- }
- });
-
- it("keeps GFM footnote references aligned with their sanitized target ids", () => {
- const { container } = renderFootnote();
-
- const reference = container.querySelector<HTMLAnchorElement>("a[data-footnote-ref]");
- const target = container.querySelector<HTMLElement>("#user-content-fn-1");
-
- expect(reference).not.toBeNull();
- expect(reference).toHaveAttribute("href", "/memos/abc123#user-content-fn-1");
- expect(target).not.toBeNull();
- expect(container.querySelector("#user-content-user-content-fn-1")).toBeNull();
- });
-
- it("scrolls to a footnote inside the same fully rendered memo", () => {
- const { container } = renderFootnote();
- const reference = container.querySelector<HTMLAnchorElement>("a[data-footnote-ref]");
- const target = container.querySelector<HTMLElement>("#user-content-fn-1");
- const scrollIntoView = vi.fn();
- target!.scrollIntoView = scrollIntoView;
-
- fireEvent.click(reference!);
-
- expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "center" });
- expect(screen.getByTestId("location")).toHaveTextContent("/");
- });
-
- it("navigates compact cards to the memo detail footnote", () => {
- const { container } = renderFootnote(true, "/archived?filter=tagSearch%3Awork");
- const reference = container.querySelector<HTMLAnchorElement>("a[data-footnote-ref]");
-
- fireEvent.click(reference!);
-
- expect(screen.getByTestId("location")).toHaveTextContent("/memos/abc123#user-content-fn-1");
- expect(screen.getByTestId("origin")).toHaveTextContent("/archived?filter=tagSearch%3Awork");
- });
-});
diff --git a/web/tests/memo-content-lazy-renderers.test.tsx b/web/tests/memo-content-lazy-renderers.test.tsx
deleted file mode 100644
index b1a4b6a08..000000000
--- a/web/tests/memo-content-lazy-renderers.test.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-import { render, waitFor } from "@testing-library/react";
-import { describe, expect, it } from "vitest";
-import { highlightCode } from "@/components/MemoContent/highlight";
-import MathMarkdownRenderer from "@/components/MemoContent/MathMarkdownRenderer";
-import { MemoMarkdownRenderer } from "@/components/MemoContent/MemoMarkdownRenderer";
-import { hasMathSyntax } from "@/components/MemoContent/math";
-
-const ISSUE_CURRENCY_CONTENT = `list of 10 houses
-$140,000 max - buffer of ~10k
-diy, add amount to down payment
-no appliances covered
-less than $1,000, client responsibilities
-over $1,000 - owner responsibility
-vacant is good to rent
-for sale by owner
-path to ownership -$50
-rent insurance - my of`;
-
-describe("memo content lazy renderers", () => {
- it("detects math in prose but ignores escaped dollars and code", () => {
- expect(hasMathSyntax("Inline $L$ formula")).toBe(true);
- expect(hasMathSyntax("Display $$x$$ formula")).toBe(true);
- expect(hasMathSyntax("Display\n$$\nx + y\n$$")).toBe(true);
-
- expect(hasMathSyntax(String.raw`Price is \$5`)).toBe(false);
- expect(hasMathSyntax("Inline code: `$L$`")).toBe(false);
- expect(hasMathSyntax("```text\n$L$\n```")).toBe(false);
- });
-
- it("loads the math renderer when math syntax is present", async () => {
- const { container } = render(<MemoMarkdownRenderer content="$L$" resolvedMentionUsernames={new Set()} />);
-
- await waitFor(() => expect(container.querySelector(".katex")).not.toBeNull());
- });
-
- it("keeps currency dollars literal across and within lines", () => {
- const content = `${ISSUE_CURRENCY_CONTENT}\n\n$20,000 and $30,000`;
- const { container } = render(<MathMarkdownRenderer content={content} resolvedMentionUsernames={new Set()} />);
-
- expect(container.querySelector(".katex")).toBeNull();
- expect(container.querySelectorAll("br")).toHaveLength(9);
- for (const price of ["$140,000", "$1,000", "$50", "$20,000", "$30,000"]) {
- expect(container.textContent).toContain(price);
- }
- });
-
- it("retries later dollars after rejecting currency and preserves display math", () => {
- const inline = render(<MathMarkdownRenderer content="A $5 amount and $x$" resolvedMentionUsernames={new Set()} />);
- expect(inline.container.textContent).toContain("A $5 amount and ");
- expect(inline.container.querySelectorAll(".katex")).toHaveLength(1);
-
- const multiline = render(<MathMarkdownRenderer content={"$x +\ny$"} resolvedMentionUsernames={new Set()} />);
- expect(multiline.container.querySelector(".katex")).not.toBeNull();
-
- const display = render(<MathMarkdownRenderer content={"$$\nx + y\n$$"} resolvedMentionUsernames={new Set()} />);
- expect(display.container.querySelector(".katex-display .katex")).not.toBeNull();
- });
-
- it.each([
- "$ x$",
- "$x $",
- "$x$2",
- "$\u00a0x$",
- "$x\u00a0$",
- "$\u0085x$",
- "$x\u0085$",
- ])("keeps invalid single-dollar boundaries literal: %s", (content) => {
- const { container } = render(<MathMarkdownRenderer content={content} resolvedMentionUsernames={new Set()} />);
-
- expect(container.querySelector(".katex")).toBeNull();
- expect(container.textContent).toBe(content);
- });
-
- it.each([
- ["$x $ and $y$", "$x $ and "],
- ["$x$2 and $y$", "$x$2 and "],
- ["$20 and $30 then $x$", "$20 and $30 then "],
- ])("abandons an invalid closer before parsing later math: %s", (content, literalPrefix) => {
- const { container } = render(<MathMarkdownRenderer content={content} resolvedMentionUsernames={new Set()} />);
-
- expect(container.textContent).toContain(literalPrefix);
- expect(container.querySelectorAll(".katex")).toHaveLength(1);
- });
-
- it("renders escaped currency without the Markdown escape", () => {
- const { container } = render(<MathMarkdownRenderer content={String.raw`Price is \$20`} resolvedMentionUsernames={new Set()} />);
-
- expect(container.querySelector(".katex")).toBeNull();
- expect(container.textContent).toBe("Price is $20");
- });
-
- it("escapes plain code and highlights common languages", async () => {
- expect(await highlightCode('<script data-test="x">&</script>', "")).toBe("&lt;script data-test=&quot;x&quot;&gt;&amp;&lt;/script&gt;");
- expect(await highlightCode("echo hello", "bash")).toContain("hljs-built_in");
- expect(await highlightCode("const value = 1;", "js")).toContain("hljs-keyword");
- });
-});
diff --git a/web/tests/memo-content-link-preview.test.tsx b/web/tests/memo-content-link-preview.test.tsx
deleted file mode 100644
index 5ac028971..000000000
--- a/web/tests/memo-content-link-preview.test.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import type { Element } from "hast";
-import { describe, expect, it, vi } from "vitest";
-import { Paragraph } from "@/components/MemoContent/markdown/Paragraph";
-
-const viewState = vi.hoisted(() => ({ linkPreview: true }));
-
-// Paragraph reads the global preference via this hook.
-vi.mock("@/contexts/ViewContext", () => ({
- useLinkPreviewEnabled: () => viewState.linkPreview,
-}));
-
-// The link-preview card fetches metadata via this hook; stub it so the card would
-// render whenever it is allowed to.
-vi.mock("@/hooks/useMemoQueries", () => ({
- useLinkMetadata: () => ({
- data: { url: "https://example.com", title: "Example Title", description: "An example site", image: "" },
- isSuccess: true,
- }),
-}));
-
-// A single bare-link paragraph node, the shape that triggers a preview card.
-const singleLinkNode = {
- type: "element",
- tagName: "p",
- properties: {},
- children: [
- {
- type: "element",
- tagName: "a",
- properties: { href: "https://example.com" },
- children: [{ type: "text", value: "https://example.com" }],
- },
- ],
-} as unknown as Element;
-
-const renderParagraph = () =>
- render(
- <Paragraph node={singleLinkNode}>
- <a href="https://example.com">https://example.com</a>
- </Paragraph>,
- );
-
-describe("<Paragraph /> link preview gating", () => {
- it("renders the link preview card when the setting is enabled (default)", () => {
- viewState.linkPreview = true;
- renderParagraph();
- expect(screen.getByText("Example Title")).toBeInTheDocument();
- });
-
- it("renders the plain link without a card when the setting is disabled", () => {
- viewState.linkPreview = false;
- renderParagraph();
- expect(screen.queryByText("Example Title")).not.toBeInTheDocument();
- expect(screen.getByText("https://example.com")).toBeInTheDocument();
- });
-});
diff --git a/web/tests/memo-content-list.test.tsx b/web/tests/memo-content-list.test.tsx
deleted file mode 100644
index 84a0f167a..000000000
--- a/web/tests/memo-content-list.test.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { renderToStaticMarkup } from "react-dom/server";
-import ReactMarkdown from "react-markdown";
-import remarkGfm from "remark-gfm";
-import { describe, expect, it } from "vitest";
-import { TASK_LIST_CLASS, TASK_LIST_ITEM_CLASS } from "@/components/MemoContent/constants";
-import { List, ListItem } from "@/components/MemoContent/markdown";
-import { markdownStyles } from "@/lib/markdownStyles";
-import { remarkSplitMixedTaskLists } from "@/utils/remark-plugins/remark-split-mixed-task-lists";
-
-// renderToStaticMarkup escapes `&` and `>` inside attribute values.
-const listItemClass = markdownStyles.listItem.replaceAll("&", "&amp;").replaceAll(">", "&gt;");
-
-const renderListContent = (content: string): string =>
- renderToStaticMarkup(
- <ReactMarkdown
- remarkPlugins={[remarkGfm, remarkSplitMixedTaskLists]}
- components={{
- ul: ({ children, ...props }) => <List {...props}>{children}</List>,
- li: ({ children, ...props }) => <ListItem {...props}>{children}</ListItem>,
- }}
- >
- {content}
- </ReactMarkdown>,
- );
-
-describe("memo content lists", () => {
- it("keeps bullets on regular items in mixed task and bullet lists", () => {
- const html = renderListContent("- [ ] pickup package\n- [ ] library returns\n\n- milk\n- eggs\n- bread");
- const listOpenTags = html.match(/<ul class="[^"]*"/g) ?? [];
-
- expect(listOpenTags).toHaveLength(2);
- expect(listOpenTags[0]).toContain(TASK_LIST_CLASS);
- expect(listOpenTags[0]).toContain("list-none");
- expect(listOpenTags[0]).not.toContain("ps-6");
- expect(listOpenTags[1]).not.toContain(TASK_LIST_CLASS);
- expect(listOpenTags[1]).toContain("ps-6");
- expect(listOpenTags[1]).toContain("list-disc");
- expect(html).toContain(`<li class="${listItemClass}">milk</li>`);
- expect(html).not.toContain(`<li class="${listItemClass}">\n<p>milk</p>`);
- expect(html).toContain(TASK_LIST_ITEM_CLASS);
- expect(html).toContain("grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-2");
- expect(html).toContain('<div class="min-w-0 [overflow-wrap:anywhere] [&amp;&gt;*:last-child]:mb-0"> pickup package</div>');
- expect(html).not.toMatch(/<li class="[^"]*task-list-item[^"]*"><p\b/);
- });
-
- it("keeps compact styling for pure task lists", () => {
- const html = renderListContent("- [ ] pickup package\n- [ ] library returns");
-
- expect(html).toMatch(/<ul class="[^"]*\blist-none\b[^"]*"/);
- expect(html).not.toMatch(/<ul class="[^"]*\blist-disc\b[^"]*"/);
- expect(html).not.toMatch(/<li class="[^"]*task-list-item[^"]*"><p\b/);
- });
-
- it("keeps nested task lists on their own row", () => {
- const html = renderListContent("- [ ] asdas\n - [ ] zzzz");
-
- expect(html).toContain("grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-2");
- expect(html).toContain('<div class="min-w-0 [overflow-wrap:anywhere] [&amp;&gt;*:last-child]:mb-0"> asdas');
- expect(html).not.toContain("[&amp;_ul.contains-task-list]:ml-6");
- expect(html).toContain("zzzz");
- });
-
- it("keeps loose task list paragraphs while aligning the first line", () => {
- const html = renderListContent("- [ ] plan\n\n keep details\n\n- [ ] zzzz");
-
- expect(html).toMatch(/<li class="[^"]*task-list-item[^"]*">\s*<input type="checkbox" disabled=""\/>/);
- expect(html).toContain('<div class="min-w-0 [overflow-wrap:anywhere] [&amp;&gt;*:last-child]:mb-0">');
- expect(html).toContain("<p> plan</p>");
- expect(html).toContain("<p>keep details</p>");
- expect(html).toContain("zzzz");
- });
-
- it("keeps inline task markdown in the task body", () => {
- const html = renderListContent("- [ ] Northern Lights in Iceland — booking this for winter, *finally*");
-
- expect(html).toContain('<input type="checkbox" disabled=""/>');
- expect(html).toContain(
- '<div class="min-w-0 [overflow-wrap:anywhere] [&amp;&gt;*:last-child]:mb-0"> Northern Lights in Iceland — booking this for winter, <em>finally</em></div>',
- );
- });
-});
diff --git a/web/tests/memo-content-paragraph.test.tsx b/web/tests/memo-content-paragraph.test.tsx
deleted file mode 100644
index b273eea6a..000000000
--- a/web/tests/memo-content-paragraph.test.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { renderToStaticMarkup } from "react-dom/server";
-import ReactMarkdown from "react-markdown";
-import remarkGfm from "remark-gfm";
-import { describe, expect, it } from "vitest";
-import { memoUrlTransform } from "@/components/MemoContent/constants";
-import { getSingleLinkHref } from "@/components/MemoContent/markdown/Paragraph";
-
-const collectSingleLinkHrefs = (content: string): Array<string | undefined> => {
- const hrefs: Array<string | undefined> = [];
-
- renderToStaticMarkup(
- <ReactMarkdown
- remarkPlugins={[remarkGfm]}
- // Match production so handoff schemes reach the helper instead of being stripped upstream.
- urlTransform={memoUrlTransform}
- components={{
- p: ({ children, node }) => {
- hrefs.push(getSingleLinkHref(node));
- return <p>{children}</p>;
- },
- }}
- >
- {content}
- </ReactMarkdown>,
- );
-
- return hrefs;
-};
-
-describe("memo content paragraph links", () => {
- it("treats only bare single-link paragraphs as single link hrefs", () => {
- expect(collectSingleLinkHrefs("https://www.bilibili.com/\n\n[bilibili](https://www.bilibili.com/)")).toEqual([
- "https://www.bilibili.com/",
- undefined,
- ]);
- });
-
- it("does not offer previews for handoff links", () => {
- expect(
- collectSingleLinkHrefs("<tel:+440000000000>\n\n<sms:+440000000000>\n\n<mailto:[email protected]>\n\n<https://example.com>"),
- ).toEqual([undefined, undefined, undefined, "https://example.com"]);
- });
-});
diff --git a/web/tests/memo-content-security.test.ts b/web/tests/memo-content-security.test.ts
new file mode 100644
index 000000000..834a0e48e
--- /dev/null
+++ b/web/tests/memo-content-security.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from "vitest";
+import { isTrustedIframeSrc } from "@/lib/html-sanitize-schema";
+import { renderSanitizedHtml } from "@/lib/sanitized-html";
+
+const renderHtml = (source: string): string => {
+ const element = document.createElement("div");
+ renderSanitizedHtml(source, element);
+ return element.innerHTML;
+};
+
+describe("raw HTML sanitization", () => {
+ it("strips user-controlled inline styles from raw HTML spans", () => {
+ const html = renderHtml('<span style="position:fixed;inset:0;z-index:99999">overlay</span>');
+ expect(html).toContain("overlay");
+ expect(html).not.toMatch(/style=/);
+ expect(html).not.toMatch(/position:fixed/);
+ });
+
+ it("strips scripts and event handlers", () => {
+ const html = renderHtml(
+ '<div onclick="alert(1)">a<script>alert(2)</script><img src="https://img.example/a.png" onerror="alert(3)"></div>',
+ );
+ expect(html).not.toMatch(/onclick|onerror|<script|alert/);
+ expect(html).toContain("https://img.example/a.png");
+ });
+
+ it("keeps tel: and sms: link targets and strips script-capable ones", () => {
+ const html = renderHtml('<p><a href="tel:+440000000000">phone</a> <a href="sms:+44">text</a> <a href="javascript:alert(1)">x</a></p>');
+ expect(html).toContain('href="tel:+440000000000"');
+ expect(html).toContain('href="sms:+44"');
+ expect(html).not.toMatch(/javascript:/);
+ });
+
+ it("opens links in a new tab without leaking the opener", () => {
+ expect(renderHtml('<p><a href="https://example.com">x</a></p>')).toMatch(/target="_blank" rel="noopener noreferrer"/);
+ });
+
+ it("drops picture sources that would bypass the https-only image rule", () => {
+ const html = renderHtml('<picture><source srcset="http://tracker.example/a.png"><img src="https://img.example/a.png"></picture>');
+ expect(html).not.toMatch(/<picture|<source|tracker\.example/);
+ expect(html).toMatch(/img\.example\/a\.png/);
+ });
+
+ it("drops untrusted iframe embeds", () => {
+ expect(renderHtml('<iframe src="https://www.youtube.com/embed/abc123" title="demo"></iframe>')).toMatch(
+ /<iframe[^>]+youtube\.com\/embed\/abc123/,
+ );
+ expect(renderHtml('<iframe src="https://evil.example/embed/abc123" title="demo"></iframe>')).not.toMatch(/<iframe/);
+ });
+
+ it("renders Markdown between disclosure tags and keeps the authored open state", () => {
+ const html = renderHtml("<details open>\n<summary>More <b>info</b></summary>\n\nSome **bold** text\n\n</details>");
+ expect(html).toMatch(/<details[^>]* open=""/);
+ expect(html).toMatch(/<summary[^>]*>More <b>info<\/b><\/summary>/);
+ expect(html).toContain("<strong>bold</strong>");
+ });
+});
+
+describe("trusted iframe providers", () => {
+ it("accepts trusted providers only", () => {
+ expect(isTrustedIframeSrc("https://www.youtube.com/embed/abc123")).toBe(true);
+ expect(isTrustedIframeSrc("https://www.youtube-nocookie.com/embed/abc123?si=test")).toBe(true);
+ expect(isTrustedIframeSrc("https://player.vimeo.com/video/123456")).toBe(true);
+ expect(isTrustedIframeSrc("https://open.spotify.com/embed/track/123456")).toBe(true);
+ expect(isTrustedIframeSrc("https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/123456")).toBe(true);
+ expect(isTrustedIframeSrc("https://www.loom.com/embed/123456")).toBe(true);
+ expect(isTrustedIframeSrc("https://www.google.com/maps/embed?pb=test")).toBe(true);
+ expect(isTrustedIframeSrc("https://app.diagrams.net/?embed=1")).toBe(true);
+ expect(isTrustedIframeSrc("https://www.draw.io/?embed=1")).toBe(true);
+ expect(isTrustedIframeSrc("https://evil.example/embed/abc123")).toBe(false);
+ });
+});
diff --git a/web/tests/memo-content-security.test.tsx b/web/tests/memo-content-security.test.tsx
deleted file mode 100644
index 4d970db92..000000000
--- a/web/tests/memo-content-security.test.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import React from "react";
-import { renderToStaticMarkup } from "react-dom/server";
-import ReactMarkdown from "react-markdown";
-import rehypeKatex from "rehype-katex";
-import rehypeRaw from "rehype-raw";
-import rehypeSanitize from "rehype-sanitize";
-import remarkGfm from "remark-gfm";
-import { describe, expect, it } from "vitest";
-import { isTrustedIframeSrc, memoUrlTransform, SANITIZE_SCHEMA } from "@/components/MemoContent/constants";
-import { remarkCurrencySafeMath } from "@/utils/remark-plugins/remark-currency-safe-math";
-
-type IframeProps = React.ComponentProps<"iframe">;
-
-const TrustedIframe = (props: IframeProps) => {
- if (typeof props.src !== "string" || !isTrustedIframeSrc(props.src)) {
- return null;
- }
- return <iframe {...props} />;
-};
-
-const renderMemoContent = (content: string): string =>
- renderToStaticMarkup(
- <ReactMarkdown
- remarkPlugins={[remarkCurrencySafeMath]}
- rehypePlugins={[rehypeRaw, [rehypeSanitize, SANITIZE_SCHEMA], [rehypeKatex, { throwOnError: false, strict: false }]]}
- components={{ iframe: TrustedIframe }}
- >
- {content}
- </ReactMarkdown>,
- );
-
-const renderGfmContent = (content: string): string =>
- renderToStaticMarkup(
- <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[[rehypeSanitize, SANITIZE_SCHEMA]]} urlTransform={memoUrlTransform}>
- {content}
- </ReactMarkdown>,
- );
-
-describe("memo content sanitization", () => {
- it("strips user-controlled inline styles from raw HTML spans", () => {
- const html = renderMemoContent('<span style="position:fixed;inset:0;z-index:99999">overlay</span>');
-
- expect(html).toMatch(/<span>overlay<\/span>/);
- expect(html).not.toMatch(/style=/);
- expect(html).not.toMatch(/position:fixed/);
- });
-
- it("still renders KaTeX output after sanitizing math marker classes", () => {
- const html = renderMemoContent("$L$");
-
- expect(html).toMatch(/class="katex"/);
- expect(html).toMatch(/class="katex-html"/);
- });
-
- it("keeps tel: and sms: link targets", () => {
- const html = renderGfmContent("[phone me](tel:+440000000000) [text me](sms:+440000000000?body=hi)");
-
- expect(html).toContain('href="tel:+440000000000"');
- expect(html).toContain('href="sms:+440000000000?body=hi"');
- });
-
- it("still strips script-capable link targets", () => {
- const html = renderGfmContent("[x](javascript:alert(1)) [y](data:text/html,hi) [z](vbscript:msgbox)");
-
- expect(html).not.toMatch(/javascript:/);
- expect(html).not.toMatch(/data:/);
- expect(html).not.toMatch(/vbscript:/);
- expect(html).toMatch(/<a>x<\/a>/);
- });
-
- it("preserves checked state for GFM task list items", () => {
- const html = renderGfmContent("- [x] Done\n- [ ] Todo");
- const inputs = html.match(/<input[^>]+\/>/g) ?? [];
-
- expect(inputs).toHaveLength(2);
- expect(inputs[0]).toContain('checked=""');
- expect(inputs[1]).not.toContain('checked=""');
- });
-});
-
-describe("trusted iframe providers", () => {
- it("accepts trusted providers only", () => {
- expect(isTrustedIframeSrc("https://www.youtube.com/embed/abc123")).toBe(true);
- expect(isTrustedIframeSrc("https://www.youtube-nocookie.com/embed/abc123?si=test")).toBe(true);
- expect(isTrustedIframeSrc("https://player.vimeo.com/video/123456")).toBe(true);
- expect(isTrustedIframeSrc("https://open.spotify.com/embed/track/123456")).toBe(true);
- expect(isTrustedIframeSrc("https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/123456")).toBe(true);
- expect(isTrustedIframeSrc("https://www.loom.com/embed/123456")).toBe(true);
- expect(isTrustedIframeSrc("https://www.google.com/maps/embed?pb=test")).toBe(true);
- expect(isTrustedIframeSrc("https://app.diagrams.net/?embed=1")).toBe(true);
- expect(isTrustedIframeSrc("https://www.draw.io/?embed=1")).toBe(true);
- expect(isTrustedIframeSrc("https://evil.example/embed/abc123")).toBe(false);
- });
-
- it("drops picture sources that would bypass the https-only image rule", () => {
- const html = renderMemoContent(
- '<picture><source srcset="http://tracker.example/a.png"><img src="https://img.example/a.png"></picture>',
- );
-
- expect(html).not.toMatch(/<picture/);
- expect(html).not.toMatch(/<source/);
- expect(html).not.toMatch(/tracker\.example/);
- expect(html).toMatch(/img\.example\/a\.png/);
- });
-
- it("drops untrusted iframe embeds during rendering", () => {
- const trusted = renderMemoContent('<iframe src="https://www.youtube.com/embed/abc123" title="demo"></iframe>');
- const untrusted = renderMemoContent('<iframe src="https://evil.example/embed/abc123" title="demo"></iframe>');
-
- expect(trusted).toMatch(/<iframe/);
- expect(trusted).toMatch(/youtube\.com\/embed\/abc123/);
- expect(untrusted).not.toMatch(/<iframe/);
- });
-});
diff --git a/web/tests/memo-content.test.tsx b/web/tests/memo-content.test.tsx
new file mode 100644
index 000000000..ae5f24ce6
--- /dev/null
+++ b/web/tests/memo-content.test.tsx
@@ -0,0 +1,215 @@
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import MemoContent from "@/components/MemoContent";
+import { highlightLoadedCode, loadHighlighter } from "@/lib/code-highlight";
+
+const state = vi.hoisted(() => ({
+ linkPreview: true,
+ resolved: new Set<string>(),
+ tagsSetting: undefined as unknown,
+ filters: [] as { factor: string; value: string }[],
+ addFilter: vi.fn(),
+ removeFilter: vi.fn(),
+ navigateTo: vi.fn(),
+}));
+
+vi.mock("@/contexts/AuthContext", () => ({
+ useAuth: () => ({ userTagsSetting: state.tagsSetting, userGeneralSetting: { theme: "default" } }),
+}));
+
+vi.mock("@/contexts/MemoFilterContext", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/contexts/MemoFilterContext")>()),
+ useMemoFilterContext: () => ({
+ getFiltersByFactor: (factor: string) => state.filters.filter((filter) => filter.factor === factor),
+ addFilter: state.addFilter,
+ removeFilter: state.removeFilter,
+ }),
+}));
+
+vi.mock("@/contexts/ViewContext", () => ({ useLinkPreviewEnabled: () => state.linkPreview }));
+vi.mock("@/components/MemoContent/MentionResolutionContext", () => ({ useResolvedMentionUsernames: () => state.resolved }));
+vi.mock("@/hooks/useNavigateTo", () => ({ default: () => state.navigateTo }));
+vi.mock("@/hooks/useNearViewport", () => ({ useNearViewport: () => ({ ref: () => {}, isNearViewport: true }) }));
+vi.mock("@/hooks/useMemoQueries", () => ({
+ useLinkMetadata: () => ({
+ data: { url: "https://example.com", title: "Example Title", description: "An example site", image: "" },
+ isSuccess: true,
+ }),
+}));
+
+const renderMemo = (content: string, props: Partial<React.ComponentProps<typeof MemoContent>> = {}, path = "/") =>
+ render(
+ <MemoryRouter initialEntries={[path]}>
+ <MemoContent content={content} memoName="memos/1" {...props} />
+ </MemoryRouter>,
+ );
+
+beforeEach(() => {
+ state.linkPreview = true;
+ state.resolved = new Set();
+ state.tagsSetting = undefined;
+ state.filters = [];
+});
+
+describe("memo view", () => {
+ it("shows the memo read-only", () => {
+ const { container } = renderMemo("# Title\n\nSome **bold** text");
+ const root = container.querySelector(".memo-content-root");
+ expect(root).toHaveAttribute("aria-readonly", "true");
+ expect(container.querySelector("h1")).toHaveTextContent("Title");
+ expect(container.querySelector("strong")).toHaveTextContent("bold");
+ });
+
+ it("lets an owner tick a task, changing only its bracket", async () => {
+ const onTaskToggle = vi.fn();
+ const content = "- [ ] First\n- [x] Second\n\nNote";
+ const { container } = renderMemo(content, { onTaskToggle });
+ const checkbox = container.querySelector<HTMLInputElement>("input.mbe-checkbox");
+ expect(checkbox).not.toBeDisabled();
+ fireEvent.mouseDown(checkbox!);
+ await waitFor(() => expect(onTaskToggle).toHaveBeenCalledWith("- [x] First\n- [x] Second\n\nNote"));
+ });
+
+ it("keeps tasks locked for readers", () => {
+ const { container } = renderMemo("- [ ] First");
+ expect(container.querySelector("input.mbe-checkbox")).toBeDisabled();
+ });
+});
+
+describe("tags and mentions", () => {
+ it("toggles the tag filter from a list", () => {
+ renderMemo("Plan #work today");
+ fireEvent.click(screen.getByText("#work"));
+ expect(state.addFilter).toHaveBeenCalledWith({ factor: "tagSearch", value: "work" });
+ });
+
+ it("opens the collection filtered by the tag from a memo detail page", () => {
+ renderMemo("Plan #work today", { parentPage: "/?creator=alice" }, "/memos/1");
+ fireEvent.click(screen.getByText("#work"));
+ expect(state.navigateTo).toHaveBeenCalledWith("/?creator=alice&filter=tagSearch%3Awork");
+ });
+
+ it("does not treat code or links as tags", () => {
+ const { container } = renderMemo("`#code` [#link](/x) #real");
+ expect(Array.from(container.querySelectorAll(".mbe-tag"), (tag) => tag.textContent)).toEqual(["#real"]);
+ });
+
+ it("links resolved mentions to the profile and leaves unknown ones as text", () => {
+ state.resolved = new Set(["alice"]);
+ const { container } = renderMemo("Hi @alice and @nobody");
+ const [alice, nobody] = container.querySelectorAll<HTMLElement>(".mbe-mention");
+ expect(alice).toHaveAttribute("data-resolved");
+ expect(nobody).not.toHaveAttribute("data-resolved");
+ });
+});
+
+describe("headings", () => {
+ it("gives every heading the anchor the outline links to", () => {
+ const { container } = renderMemo("# Intro\n\n## Dup\n\n##### Dup\n\n## Dup\n\n# 🎉🎉\n\n# Comments");
+ expect(Array.from(container.querySelectorAll("h1, h2, h5"), (heading) => heading.id)).toEqual([
+ "intro",
+ "dup",
+ "dup-1",
+ "dup-2",
+ "heading",
+ "comments-1",
+ ]);
+ });
+});
+
+describe("code blocks", () => {
+ it("highlights the code and has the editor's copy button", async () => {
+ const { container } = renderMemo("```js\nconst value = 1;\n```");
+ expect(container.querySelector(".mbe-code .mbe-code-copy")).toBeInTheDocument();
+ expect(container.querySelector<HTMLInputElement>(".mbe-code-lang")?.value).toBe("js");
+ expect(container.querySelector(".mbe-code code")).toHaveTextContent("const value = 1;");
+ await waitFor(() => expect(container.querySelector(".mbe-code code .hljs-keyword")).toHaveTextContent("const"));
+ });
+
+ it("escapes plain code and highlights common languages", async () => {
+ expect(highlightLoadedCode('<script data-test="x">&</script>', "")).toBe("&lt;script data-test=&quot;x&quot;&gt;&amp;&lt;/script&gt;");
+ await loadHighlighter("js");
+ expect(highlightLoadedCode("const value = 1;", "js")).toContain("hljs-keyword");
+ });
+});
+
+describe("link previews", () => {
+ it("shows a card for a paragraph that is only a bare link", async () => {
+ renderMemo("https://example.com");
+ await waitFor(() => expect(screen.getByText("Example Title")).toBeInTheDocument());
+ });
+
+ it("keeps the plain link when previews are off or the link has its own text", () => {
+ state.linkPreview = false;
+ const { container } = renderMemo("https://example.com\n\n[Example](https://example.com)");
+ expect(screen.queryByText("Example Title")).not.toBeInTheDocument();
+ expect(container.querySelectorAll("a")).toHaveLength(2);
+ });
+});
+
+describe("raw HTML", () => {
+ it("renders inline HTML through the sanitizer", async () => {
+ const { container } = renderMemo('Press <kbd>Ctrl</kbd> <span onclick="x">now</span>');
+ await waitFor(() => expect(container.querySelector("kbd")).toHaveTextContent("Ctrl"));
+ expect(container.querySelector("[onclick]")).toBeNull();
+ expect(container).not.toHaveTextContent("<kbd>");
+ });
+
+ it("renders disclosures once the sanitizer loads", async () => {
+ const { container } = renderMemo("<details open><summary>Read <em>more</em></summary>\n\nSupporting text.\n\n</details>");
+ await waitFor(() => expect(container.querySelector("details")).toHaveAttribute("open"));
+ expect(container.querySelector("summary em")).toHaveTextContent("more");
+ expect(screen.getByText("Supporting text.")).toBeInTheDocument();
+ });
+});
+
+describe("math", () => {
+ it("renders formulas with KaTeX once it loads", async () => {
+ const { container } = renderMemo("$L$ and\n\n$$\nx + y\n$$");
+ await waitFor(() => expect(container.querySelector(".katex")).not.toBeNull());
+ expect(container.querySelector(".katex-display")).not.toBeNull();
+ });
+
+ it("keeps currency dollars literal", async () => {
+ const { container } = renderMemo("less than $1,000, and over $1,000 - owner");
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+ expect(container.querySelector(".katex")).toBeNull();
+ expect(container).toHaveTextContent("less than $1,000, and over $1,000 - owner");
+ });
+});
+
+describe("footnotes", () => {
+ it("shows a reference as a raised label and its definition as a note", () => {
+ const { container } = renderMemo("Fact[^1]\n\n[^1]: The source.");
+ expect(container.querySelector(".mbe-footnote-ref")).toHaveTextContent("1");
+ expect(container.querySelector(".mbe-footnote")).toHaveTextContent("1The source.");
+ });
+});
+
+describe("links", () => {
+ it("scrolls to an in-memo anchor instead of opening a new tab", () => {
+ const open = vi.spyOn(window, "open").mockImplementation(() => null);
+ const scrollIntoView = vi.fn();
+ Element.prototype.scrollIntoView = scrollIntoView;
+ const { container } = renderMemo("# Intro\n\n[back to top](#intro) [sms](sms:+44)");
+ fireEvent.click(screen.getByText("back to top"));
+ expect(scrollIntoView).toHaveBeenCalled();
+ expect(open).not.toHaveBeenCalled();
+ expect(container.querySelector('a[href="sms:+44"]')).not.toBeNull();
+ });
+});
+
+describe("images", () => {
+ it("loads relative and https images and drops other schemes", () => {
+ const { container } = renderMemo("![a](/file/a.png) ![b](https://img.example/b.png) ![c](http://tracker.example/c.png)");
+ const sources = Array.from(container.querySelectorAll("img"), (image) => image.getAttribute("src"));
+ expect(sources[0]).toBe("/file/a.png");
+ expect(sources[1]).toBe("https://img.example/b.png");
+ expect(sources[2] ?? "").not.toContain("tracker.example");
+ expect(container.querySelector("img")).toHaveAttribute("referrerpolicy", "no-referrer");
+ expect(container.querySelector("img")).toHaveAttribute("loading", "lazy");
+ });
+});
diff --git a/web/tests/memo-editor-cache.test.ts b/web/tests/memo-editor-cache.test.ts
index e4193e8b0..469d8b8be 100644
--- a/web/tests/memo-editor-cache.test.ts
+++ b/web/tests/memo-editor-cache.test.ts
@@ -128,9 +128,10 @@ describe("memo editor cache", () => {
it("keeps the cursor for the next editor mount", () => {
const key = cacheService.key("users/steven", "global-memo-editor");
- cacheService.saveCursor(key, 9);
+ const selection = { anchor: { block: 1, offset: 9 }, focus: { block: 1, offset: 9 } };
+ cacheService.saveCursor(key, selection);
- expect(cacheService.loadCursor(key)).toBe(9);
+ expect(cacheService.loadCursor(key)).toEqual(selection);
cacheService.clear(key);
expect(cacheService.loadCursor(key)).toBeUndefined();
});
diff --git a/web/tests/memo-editor-extensions.test.ts b/web/tests/memo-editor-extensions.test.ts
deleted file mode 100644
index 6517f175f..000000000
--- a/web/tests/memo-editor-extensions.test.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { EditorState } from "@codemirror/state";
-import { EditorView } from "@codemirror/view";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { buildEditorExtensions } from "@/components/MemoEditor/Editor/extensions";
-
-describe("MemoEditor CodeMirror extensions", () => {
- const views: EditorView[] = [];
-
- afterEach(() => {
- for (const view of views.splice(0)) {
- view.destroy();
- }
- document.body.replaceChildren();
- });
-
- it("uses the native selection and CodeMirror placeholder without enabling multi-cursor selection", () => {
- const parent = document.body.appendChild(document.createElement("div"));
- const state = EditorState.create({
- doc: "",
- extensions: buildEditorExtensions({
- placeholder: "Any thoughts...",
- onChange: vi.fn(),
- onFiles: vi.fn(),
- onUpdate: vi.fn(),
- onSubmit: vi.fn(),
- getTags: () => [],
- }),
- });
- const view = new EditorView({ state, parent });
- views.push(view);
-
- expect(view.state.facet(EditorState.allowMultipleSelections)).toBe(false);
- expect(view.dom.querySelector(".cm-selectionLayer")).toBeNull();
- expect(view.dom.querySelector(".cm-cursorLayer")).toBeNull();
- expect(view.contentDOM).toHaveAttribute("aria-placeholder", "Any thoughts...");
- expect(view.dom.querySelector(".cm-placeholder")).toHaveTextContent("Any thoughts...");
- });
-
- it.each([
- ["paste", "clipboardData"],
- ["drop", "dataTransfer"],
- ] as const)("intercepts files on %s before CodeMirror inserts their contents", (eventType, transferProperty) => {
- const onFiles = vi.fn();
- const parent = document.body.appendChild(document.createElement("div"));
- const view = new EditorView({
- state: EditorState.create({
- doc: "memo",
- extensions: buildEditorExtensions({
- placeholder: "",
- onChange: vi.fn(),
- onFiles,
- onUpdate: vi.fn(),
- onSubmit: vi.fn(),
- getTags: () => [],
- }),
- }),
- parent,
- });
- views.push(view);
- view.dispatch({ selection: { anchor: 2 } });
- const file = new File(["must not become memo content"], "attachment.txt", { type: "text/plain" });
- const transfer =
- eventType === "paste" ? { items: [{ kind: "file", getAsFile: () => file }], files: [file] } : { files: [file], types: ["Files"] };
- const event = new Event(eventType, { bubbles: true, cancelable: true });
- Object.defineProperty(event, transferProperty, { value: transfer });
-
- view.contentDOM.dispatchEvent(event);
-
- expect(onFiles).toHaveBeenCalledWith([file], eventType === "paste" ? { source: "paste" } : { source: "drop", position: 0 });
- expect(event.defaultPrevented).toBe(true);
- expect(view.state.doc.toString()).toBe("memo");
- });
-});
diff --git a/web/tests/memo-editor-paste-files.test.tsx b/web/tests/memo-editor-paste-files.test.tsx
index 0c6304f61..39ffd57bb 100644
--- a/web/tests/memo-editor-paste-files.test.tsx
+++ b/web/tests/memo-editor-paste-files.test.tsx
@@ -8,7 +8,7 @@ vi.mock("@/utils/i18n", async (importOriginal) => ({
...(await importOriginal<typeof import("@/utils/i18n")>()),
useTranslate: () => (key: string) => key,
}));
-vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }) }));
+vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }), useUsersByUsernames: () => ({ data: undefined }) }));
vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/1" }) }));
vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userGeneralSetting: {} }) }));
vi.mock("@/contexts/InstanceContext", () => ({
@@ -32,7 +32,7 @@ URL.revokeObjectURL = () => {};
const paste = (target: Element, files: File[]) => {
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", {
- value: { items: files.map((file) => ({ kind: "file", getAsFile: () => file })) },
+ value: { files, items: files.map((file) => ({ kind: "file", getAsFile: () => file })), getData: () => "" },
});
target.dispatchEvent(event);
return event;
@@ -45,7 +45,7 @@ const mount = () => {
<MemoEditor cacheKey="paste-test" />
</QueryClientProvider>,
);
- const content = result.container.querySelector<HTMLElement>(".cm-content");
+ const content = result.container.querySelector<HTMLElement>(".memo-editor-root");
expect(content).not.toBeNull();
return { ...result, content: content! };
};
diff --git a/web/tests/memo-editor-transcription.test.tsx b/web/tests/memo-editor-transcription.test.tsx
index 376e94579..01d2614df 100644
--- a/web/tests/memo-editor-transcription.test.tsx
+++ b/web/tests/memo-editor-transcription.test.tsx
@@ -7,7 +7,7 @@ import { transcriptionService } from "@/components/MemoEditor/services";
import { AttachmentSchema } from "@/types/proto/api/attachment_service_pb";
import { MemoSchema, Visibility } from "@/types/proto/api/memo_service_pb";
-vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }) }));
+vi.mock("@/hooks/useUserQueries", () => ({ useTagCounts: () => ({ data: {} }), useUsersByUsernames: () => ({ data: undefined }) }));
vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/1" }) }));
vi.mock("@/contexts/AuthContext", () => ({ useAuth: () => ({ userGeneralSetting: {} }) }));
vi.mock("@/contexts/InstanceContext", () => ({
@@ -48,15 +48,15 @@ describe("existing memo audio transcription", () => {
<MemoEditor memo={memo} />
</QueryClientProvider>,
);
- await waitFor(() => expect(container.querySelector(".cm-content")?.textContent).toBe(memo.content));
+ await waitFor(() => expect(container.querySelector(".memo-editor-root")?.textContent).toBe(memo.content));
fireEvent.click(screen.getByRole("button", { name: "Transcribe" }));
expect(screen.getByRole("button", { name: "Update" })).toBeDisabled();
await act(async () => {
pending.resolve("Recognized meeting discussion");
await pending.promise;
});
- await waitFor(() => expect(container.querySelector(".cm-content")?.textContent).toContain("Recognized meeting discussion"));
- expect(container.querySelector(".cm-content")?.textContent).toContain(memo.content);
+ await waitFor(() => expect(container.querySelector(".memo-editor-root")?.textContent).toContain("Recognized meeting discussion"));
+ expect(container.querySelector(".memo-editor-root")?.textContent).toContain(memo.content);
expect(screen.getByText("voice.wav")).toBeInTheDocument();
expect(clients.updateMemo).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Update" }));
diff --git a/web/tests/memo-markdown-extension.test.ts b/web/tests/memo-markdown-extension.test.ts
deleted file mode 100644
index cae56aca0..000000000
--- a/web/tests/memo-markdown-extension.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { markdown } from "@codemirror/lang-markdown";
-import { EditorState } from "@codemirror/state";
-import { parser as markdownParser } from "@lezer/markdown";
-import { describe, expect, it } from "vitest";
-import { findMarkdownTagMatches } from "@/components/MemoEditor/Editor/markdownTagRanges";
-import { memoMarkdownExtensions } from "@/utils/memo-markdown-extension";
-
-const sourceParser = markdownParser.configure(memoMarkdownExtensions);
-
-function inlineMath(source: string): string[] {
- const ranges: string[] = [];
- sourceParser.parse(source).iterate({
- enter(node) {
- if (node.name === "InlineMath") ranges.push(source.slice(node.from, node.to));
- },
- });
- return ranges;
-}
-
-describe("memo Markdown math", () => {
- it("keeps the issue's multiline currency list as ordinary text", () => {
- const source = `list of 10 houses
-$140,000 max - buffer of ~10k
-diy, add amount to down payment
-no appliances covered
-less than $1,000, client responsibilities
-over $1,000 - owner responsibility
-vacant is good to rent
-for sale by owner
-path to ownership -$50
-rent insurance - my of`;
-
- expect(inlineMath(source)).toEqual([]);
- });
-
- it("keeps two same-line currency amounts as ordinary text", () => {
- expect(inlineMath("$20,000 and $30,000")).toEqual([]);
-
- const source = "$20,000 #budget and $30,000";
- const state = EditorState.create({ doc: source, extensions: [markdown({ extensions: memoMarkdownExtensions })] });
- expect(findMarkdownTagMatches(state, 0, source.length).map((match) => match.value)).toEqual(["budget"]);
- });
-
- it("applies Pandoc-style boundaries to single-dollar inline math", () => {
- expect(inlineMath("$ x$ and $x $ and $x$2")).toEqual([]);
- expect(inlineMath("$\u0085x$ and $x\u0085$")).toEqual([]);
- expect(inlineMath("$x$, then $y$")).toEqual(["$x$", "$y$"]);
- });
-
- it.each([
- ["$x $ and $y$", ["$y$"]],
- ["$x$2 and $y$", ["$y$"]],
- ["$20 and $30 then $x$", ["$x$"]],
- ])("retries after an invalid exact-size closer in %s", (source, expected) => {
- expect(inlineMath(source)).toEqual(expected);
- });
-
- it("keeps valid and multi-dollar math opaque", () => {
- const source = "$x$ and $#hidden$ and $$#also-hidden$$, then #visible";
- const state = EditorState.create({ doc: source, extensions: [markdown({ extensions: memoMarkdownExtensions })] });
-
- expect(inlineMath(source)).toEqual(["$x$", "$#hidden$", "$$#also-hidden$$"]);
- expect(findMarkdownTagMatches(state, 0, source.length).map((match) => match.value)).toEqual(["visible"]);
- });
-});
diff --git a/web/tests/memo-markdown-memoization.test.tsx b/web/tests/memo-markdown-memoization.test.tsx
deleted file mode 100644
index a52d664fd..000000000
--- a/web/tests/memo-markdown-memoization.test.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { MemoMarkdownRenderer } from "@/components/MemoContent/MemoMarkdownRenderer";
-import { hasMathSyntax } from "@/components/MemoContent/math";
-
-vi.mock("@/components/MemoContent/math", () => ({
- hasMathSyntax: vi.fn(() => false),
-}));
-
-describe("<MemoMarkdownRenderer /> memoization", () => {
- beforeEach(() => {
- vi.mocked(hasMathSyntax).mockClear();
- });
-
- it("does not parse again when only the resolved mention Set identity changes", () => {
- const { rerender } = render(
- <MemoMarkdownRenderer content="Hello @alice" memoName="memos/1" resolvedMentionUsernames={new Set(["alice"])} />,
- );
-
- rerender(<MemoMarkdownRenderer content="Hello @alice" memoName="memos/1" resolvedMentionUsernames={new Set(["alice"])} />);
-
- expect(hasMathSyntax).toHaveBeenCalledTimes(1);
- });
-
- it("renders again when the relevant resolved mentions change", () => {
- const { rerender } = render(
- <MemoMarkdownRenderer content="Hello @alice" memoName="memos/1" resolvedMentionUsernames={new Set<string>()} />,
- );
-
- rerender(<MemoMarkdownRenderer content="Hello @alice" memoName="memos/1" resolvedMentionUsernames={new Set(["alice"])} />);
-
- expect(hasMathSyntax).toHaveBeenCalledTimes(2);
- expect(screen.getByRole("link", { name: "@alice" })).toHaveAttribute("href", "/?creator=alice");
- });
-});
diff --git a/web/tests/memo-outline-headings.test.ts b/web/tests/memo-outline-headings.test.ts
new file mode 100644
index 000000000..53695f5f5
--- /dev/null
+++ b/web/tests/memo-outline-headings.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+import { extractHeadings } from "@/components/MemoContent/headings";
+
+// The memo view sets the same anchors as element ids (see memo-content.test.tsx), so an
+// outline link always has somewhere to land.
+describe("outline headings", () => {
+ it("handles duplicates and repeated suffixes", () => {
+ const headings = extractHeadings("# Intro\n\n## Dup\n\n##### Dup\n\n## Dup\n\n### 連\n\n### 連\n\n### 連-1\n\nbody");
+
+ expect(headings[0]).toEqual({ text: "Intro", level: 1, slug: "intro" });
+ // The h5 consumes "dup-1" even though it never reaches the outline.
+ expect(headings.filter((heading) => heading.text === "Dup").map((heading) => heading.slug)).toEqual(["dup", "dup-2"]);
+ // A literal "連-1" heading must not collide with the suffix generated for the second "連".
+ expect(headings.filter((heading) => heading.level === 3).map((heading) => heading.slug)).toEqual(["連", "連-1", "連-1-1"]);
+ });
+
+ it("ignores setext headings, which memos disables", () => {
+ expect(extractHeadings("Title\n-----\n\n# Title")).toEqual([{ text: "Title", level: 1, slug: "title" }]);
+ });
+
+ it("reserves current and legacy comment-section anchors from memo headings", () => {
+ expect(extractHeadings("# Comments\n\n## Memo comments").map((heading) => heading.slug)).toEqual(["comments-1", "memo-comments-1"]);
+ });
+
+ it("returns nothing for content that cannot contain a heading", () => {
+ // The cheap pre-check must not mistake a tag or a shebang for a heading, and must still
+ // catch an indented ATX heading.
+ expect(extractHeadings("just a note about #work and #life")).toEqual([]);
+ expect(extractHeadings("```sh\n#!/bin/bash\necho hi\n```")).toEqual([]);
+ expect(extractHeadings(" ## Indented")).toEqual([{ text: "Indented", level: 2, slug: "indented" }]);
+ expect(extractHeadings("#\tTabbed")).toEqual([{ text: "Tabbed", level: 1, slug: "tabbed" }]);
+ });
+
+ it("gives headings with no slugifiable characters a usable anchor", () => {
+ expect(extractHeadings("# Intro\n\n# 🎉🎉\n\n# ✨").map((heading) => heading.slug)).toEqual(["intro", "heading", "heading-1"]);
+ });
+});
diff --git a/web/tests/memo-outline-headings.test.tsx b/web/tests/memo-outline-headings.test.tsx
deleted file mode 100644
index c128c91ff..000000000
--- a/web/tests/memo-outline-headings.test.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-import { render } from "@testing-library/react";
-import { MemoryRouter } from "react-router-dom";
-import { describe, expect, it, vi } from "vitest";
-import { MemoMarkdownRenderer } from "@/components/MemoContent/MemoMarkdownRenderer";
-import { extractHeadings } from "@/components/MemoContent/pipeline";
-import { findMemoAnchorTarget } from "@/utils/markdown-manipulation";
-
-vi.mock("@/components/MemoContent/math", () => ({
- hasMathSyntax: vi.fn(() => false),
-}));
-
-/**
- * The outline and the rendered heading ids come from one pipeline run, so these cases are about
- * keeping that so: each one previously produced an outline slug that no rendered heading carried.
- */
-const renderMemo = (content: string) => {
- const { container } = render(
- <MemoryRouter>
- <MemoMarkdownRenderer content={content} memoName="memos/1" resolvedMentionUsernames={new Set<string>()} />
- </MemoryRouter>,
- );
- return container;
-};
-
-const expectOutlineLandsOnRenderedHeadings = (content: string) => {
- const container = renderMemo(content);
- const headings = extractHeadings(content);
- const renderedIds = Array.from(container.querySelectorAll("h1, h2, h3, h4, h5, h6"), (heading) => heading.id).filter(Boolean);
-
- expect(new Set(renderedIds).size, "rendered heading ids must be unique").toBe(renderedIds.length);
- for (const heading of headings) {
- expect(container.querySelector(`[id="${CSS.escape(heading.slug)}"]`), `no element carries id "${heading.slug}"`).not.toBeNull();
- }
- return headings;
-};
-
-describe("outline slugs against rendered heading ids", () => {
- it("handles inline HTML, duplicates and repeated suffixes", () => {
- const headings = expectOutlineLandsOnRenderedHeadings(
- `# <ruby>連濁<rt>れんだく</rt></ruby>: intro\n\n## Dup\n\n##### Dup\n\n## Dup\n\n### 連\n\n### 連\n\n### 連-1\n\nbody`,
- );
-
- expect(headings[0]).toEqual({ text: "連濁れんだく: intro", level: 1, slug: "連濁れんだく-intro" });
- // The h5 consumes "dup-1" even though it never reaches the outline.
- expect(headings.filter((heading) => heading.text === "Dup").map((heading) => heading.slug)).toEqual(["dup", "dup-2"]);
- // A literal "連-1" heading must not collide with the suffix generated for the second "連".
- expect(headings.filter((heading) => heading.level === 3).map((heading) => heading.slug)).toEqual(["連", "連-1", "連-1-1"]);
- });
-
- it("ignores setext headings, which the renderer disables", () => {
- const headings = expectOutlineLandsOnRenderedHeadings("Title\n-----\n\n# Title");
-
- expect(headings).toEqual([{ text: "Title", level: 1, slug: "title" }]);
- });
-
- it("lists headings written as raw HTML alongside markdown ones", () => {
- const headings = expectOutlineLandsOnRenderedHeadings("<h2>Dup</h2>\n\n## Dup");
-
- expect(headings.map((heading) => heading.slug)).toEqual(["dup", "dup-1"]);
- });
-
- it("keeps an author-supplied id and numbers around it", () => {
- const headings = expectOutlineLandsOnRenderedHeadings('<h2 id="custom">Dup</h2>\n\n## custom');
-
- expect(headings.map((heading) => heading.slug)).toEqual(["custom", "custom-1"]);
- });
-
- it("uses the sanitized text when an element is stripped with its content", () => {
- const headings = expectOutlineLandsOnRenderedHeadings("# Alert <script>alert(1)</script>");
-
- expect(headings).toHaveLength(1);
- expect(headings[0].text).not.toContain("alert(1)");
- expect(headings[0].slug).toBe("alert");
- });
-
- it("includes the footnote marker the rendered heading shows, and omits the footnote label", () => {
- const headings = expectOutlineLandsOnRenderedHeadings("# Intro[^1]\n\n## Intro\n\n[^1]: note");
-
- expect(headings.map((heading) => heading.slug)).toEqual(["intro1", "intro"]);
- expect(headings.some((heading) => heading.text === "Footnotes")).toBe(false);
- });
-
- it("reserves the referenced footnote label id before assigning heading slugs", () => {
- const container = renderMemo("# Footnote label\n\nText[^1]\n\n[^1]: note");
- const reference = container.querySelector("[data-footnote-ref]");
- const label = container.querySelector(".footnotes > h2");
-
- expect(reference).toHaveAttribute("aria-describedby", "footnote-label");
- expect(label).toHaveAttribute("id", "footnote-label");
- expect(container.querySelector("h1")).toHaveAttribute("id", "footnote-label-1");
- });
-
- it("reserves current and legacy comment-section anchors from memo headings", () => {
- const headings = expectOutlineLandsOnRenderedHeadings(
- '# Comments\n\n## Memo comments\n\n<h3 id="memo-comments">Explicit comment anchor</h3>',
- );
-
- expect(headings.map((heading) => heading.slug)).toEqual(["comments-1", "memo-comments-1", "memo-comments-2"]);
- });
-
- it("keeps a historical raw comment-anchor id resolvable after reserving it", () => {
- const container = renderMemo('<h2 id="memo-comments">A custom section</h2>');
- const heading = container.querySelector("h2");
-
- expect(heading).toHaveAttribute("id", "memo-comments-1");
- expect(heading).toHaveAttribute("data-original-heading-id", "memo-comments");
- expect(findMemoAnchorTarget(container, "memos/1", "memo-comments")).toBe(heading);
- });
-
- it("returns nothing for content that cannot contain a heading", () => {
- // The cheap pre-check must not mistake a tag or a shebang for a heading, and must still
- // catch an indented ATX heading.
- expect(extractHeadings("just a note about #work and #life")).toEqual([]);
- expect(extractHeadings("```sh\n#!/bin/bash\necho hi\n```")).toEqual([]);
- expect(extractHeadings(" ## Indented")).toEqual([{ text: "Indented", level: 2, slug: "indented" }]);
- expect(extractHeadings("#\tTabbed")).toEqual([{ text: "Tabbed", level: 1, slug: "tabbed" }]);
- });
-
- it("gives headings with no slugifiable characters a usable anchor", () => {
- const headings = expectOutlineLandsOnRenderedHeadings("# Intro\n\n# 🎉🎉\n\n# ✨");
-
- expect(headings.map((heading) => heading.slug)).toEqual(["intro", "heading", "heading-1"]);
- });
-});
diff --git a/web/tests/memo-tag-navigation.test.tsx b/web/tests/memo-tag-navigation.test.tsx
deleted file mode 100644
index 3852cb85b..000000000
--- a/web/tests/memo-tag-navigation.test.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { fireEvent, render, screen } from "@testing-library/react";
-import { MemoryRouter } from "react-router-dom";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { Tag } from "@/components/MemoContent/Tag";
-
-const navigateTo = vi.hoisted(() => vi.fn());
-const origin = vi.hoisted(() => ({ parentPage: "/" as string }));
-
-vi.mock("@/hooks/useNavigateTo", () => ({
- default: () => navigateTo,
-}));
-
-vi.mock("@/components/MemoView/MemoViewContext", () => ({
- useMemoViewContext: () => origin,
-}));
-
-vi.mock("@/contexts/MemoFilterContext", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@/contexts/MemoFilterContext")>();
- return {
- ...actual,
- useMemoFilterContext: () => ({
- getFiltersByFactor: () => [],
- removeFilter: vi.fn(),
- addFilter: vi.fn(),
- }),
- };
-});
-
-vi.mock("@/contexts/AuthContext", () => ({
- useAuth: () => ({ userTagsSetting: undefined }),
-}));
-
-describe("Memo tag navigation", () => {
- beforeEach(() => {
- navigateTo.mockClear();
- origin.parentPage = "/";
- });
-
- it("navigates directly to the global collection from a global detail", () => {
- render(
- <MemoryRouter initialEntries={["/memos/parent"]}>
- <Tag data-tag="work">#work</Tag>
- </MemoryRouter>,
- );
-
- fireEvent.click(screen.getByText("#work"));
- expect(navigateTo).toHaveBeenCalledWith("/?filter=tagSearch%3Awork");
- });
-
- it("returns a creator-scoped tag to that creator's memo list", () => {
- origin.parentPage = "/?creator=alice";
-
- render(
- <MemoryRouter initialEntries={["/memos/parent"]}>
- <Tag data-tag="work">#work</Tag>
- </MemoryRouter>,
- );
-
- fireEvent.click(screen.getByText("#work"));
- expect(navigateTo).toHaveBeenCalledWith("/?creator=alice&filter=tagSearch%3Awork");
- });
-});
diff --git a/web/tests/mention-extraction.test.ts b/web/tests/mention-extraction.test.ts
new file mode 100644
index 000000000..5115bbfa6
--- /dev/null
+++ b/web/tests/mention-extraction.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { extractMentionUsernames } from "@/lib/memo-markdown";
+
+describe("extractMentionUsernames", () => {
+ it("uses the same Markdown contexts and exact spelling as rendering", () => {
+ expect(
+ extractMentionUsernames("**@Alice** ~~@bob~~ `@code` [@link](/x) ![@image](/x) https://example.com/@url $@math$ @Alice"),
+ ).toEqual(["Alice", "bob"]);
+ });
+
+ it("keeps escapes and GFM emails opaque", () => {
+ expect(extractMentionUsernames("\\@escaped @[email protected] @ok")).toEqual(["ok"]);
+ });
+
+ it("keeps case-distinct username references distinct", () => {
+ expect(extractMentionUsernames("@Alice @alice @Alice")).toEqual(["Alice", "alice"]);
+ });
+});
diff --git a/web/tests/mermaid-block.test.tsx b/web/tests/mermaid-block.test.tsx
deleted file mode 100644
index 0705640a1..000000000
--- a/web/tests/mermaid-block.test.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { render, waitFor } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
-import { MermaidBlock } from "@/components/MemoContent/MermaidBlock";
-
-vi.mock("@/contexts/AuthContext", () => ({
- useAuth: () => ({
- userGeneralSetting: { theme: "default" },
- }),
-}));
-
-const renderMermaid = vi.fn(async () => ({ svg: '<svg data-testid="diagram"></svg>' }));
-const initializeMermaid = vi.fn();
-
-vi.mock("mermaid", () => ({
- default: {
- initialize: initializeMermaid,
- render: renderMermaid,
- },
-}));
-
-const codeElement = (content: string) => <code className="language-mermaid">{content}</code>;
-
-describe("MermaidBlock", () => {
- it("clears rendered output when code content becomes empty", async () => {
- const { container, rerender } = render(<MermaidBlock>{codeElement("graph TD; A-->B")}</MermaidBlock>);
-
- await waitFor(() => expect(container.querySelector(".mermaid-diagram")).not.toBeNull());
-
- rerender(<MermaidBlock>{codeElement("")}</MermaidBlock>);
-
- await waitFor(() => expect(container.querySelector(".mermaid-diagram")).toBeNull());
- });
-});
diff --git a/web/tests/remark-mention.test.ts b/web/tests/remark-mention.test.ts
deleted file mode 100644
index b601c7319..000000000
--- a/web/tests/remark-mention.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { extractMentionUsernames } from "@/utils/mention-extraction";
-import { findMentionMatches } from "@/utils/mention-grammar";
-import { MAX_USERNAME_LENGTH } from "@/utils/username";
-
-describe("findMentionMatches", () => {
- it("recognizes complete writable usernames without changing case", () => {
- expect(findMentionMatches("@alice @Alice-2 @1alice @a--b @123 @123-456").map((match) => match.username)).toEqual([
- "alice",
- "Alice-2",
- "1alice",
- "a--b",
- "123",
- "123-456",
- ]);
- });
-
- it("accepts 36 characters and rejects the complete 37-character run", () => {
- const maximum = `a${"b".repeat(MAX_USERNAME_LENGTH - 1)}`;
- expect(findMentionMatches(`@${maximum}`).map((match) => match.username)).toEqual([maximum]);
- expect(findMentionMatches(`@${maximum}c`)).toEqual([]);
- });
-
- it.each(["@-alice", "@alice-", "@álîçé"])('rejects the invalid username shape "%s"', (source) => {
- expect(findMentionMatches(source)).toEqual([]);
- });
-
- it("uses username characters as the source boundary", () => {
- expect(findMentionMatches("hello@alice foo-@bob foo_@carol 中文@dave (@erin)").map((match) => match.username)).toEqual([
- "carol",
- "dave",
- "erin",
- ]);
- expect(findMentionMatches("@alice", false)).toEqual([]);
- });
-
- it("treats other characters as ordinary right boundaries", () => {
- expect(findMentionMatches("@alice_smith @bob@carol").map((match) => match.username)).toEqual(["alice", "bob"]);
- });
-});
-
-describe("extractMentionUsernames", () => {
- it("uses the same Markdown contexts and exact spelling as rendering", () => {
- expect(
- extractMentionUsernames("**@Alice** ~~@bob~~ `@code` [@link](/x) ![@image](/x) https://example.com/@url $@math$ @Alice"),
- ).toEqual(["Alice", "bob"]);
- });
-
- it("keeps escapes, character references, and GFM emails opaque", () => {
- expect(extractMentionUsernames("\\@escaped &#64;entity @[email protected] [email protected]@bob @ok")).toEqual(["ok"]);
- });
-
- it("keeps case-distinct username references distinct", () => {
- expect(extractMentionUsernames("@Alice @alice @Alice")).toEqual(["Alice", "alice"]);
- });
-});
diff --git a/web/tests/remark-tag.test.tsx b/web/tests/remark-tag.test.tsx
deleted file mode 100644
index ed372d853..000000000
--- a/web/tests/remark-tag.test.tsx
+++ /dev/null
@@ -1,689 +0,0 @@
-import { renderToStaticMarkup } from "react-dom/server";
-import ReactMarkdown from "react-markdown";
-import remarkBreaks from "remark-breaks";
-import remarkGfm from "remark-gfm";
-import { describe, expect, it } from "vitest";
-import { remarkCurrencySafeMath } from "@/utils/remark-plugins/remark-currency-safe-math";
-import { remarkMemoSyntax } from "@/utils/remark-plugins/remark-tag";
-
-const renderMarkdown = (content: string): string =>
- renderToStaticMarkup(
- <ReactMarkdown remarkPlugins={[remarkCurrencySafeMath, remarkGfm, remarkMemoSyntax, remarkBreaks]}>{content}</ReactMarkdown>,
- );
-
-const renderMarkdownWithoutMath = (content: string): string =>
- renderToStaticMarkup(<ReactMarkdown remarkPlugins={[remarkGfm, remarkMemoSyntax, remarkBreaks]}>{content}</ReactMarkdown>);
-
-describe("remarkMemoSyntax", () => {
- it("does not turn URL fragments inside autolinks into tags", () => {
- const html = renderMarkdown("https://github.com/dmtrKovalenko/fff#pi-agent-extension\n\nProject #memo-tag");
-
- expect(html).toContain('href="https://github.com/dmtrKovalenko/fff#pi-agent-extension"');
- expect(html).not.toContain('data-tag="pi-agent-extension"');
- expect(html).toContain('data-tag="memo-tag"');
- });
-
- it("uses written GFM URL nodes as the opaque boundary", () => {
- const html = renderMarkdown("https://example.com/#hidden https://localhost/#local HTTP://example.com/#upper ftp://example.com/#ftp");
-
- expect(html).not.toContain('data-tag="hidden"');
- expect(html).toContain('data-tag="local"');
- expect(html).toContain('data-tag="upper"');
- expect(html).toContain('data-tag="ftp"');
- });
-
- it("keeps complete written-GFM link suffixes opaque", () => {
- const html = renderMarkdown("x https://example.com/%#&_; http://example.com#z\n\nhttps://foo.example_/#suffix #ok");
-
- expect(html).not.toContain('data-tag="&amp;"');
- expect(html).not.toContain('data-tag="z"');
- expect(html).toContain('data-tag="suffix"');
- expect(html).toContain('data-tag="ok"');
- });
-
- it("coalesces text after unwrapping a remark-only URL", () => {
- const html = renderMarkdown("#&HTTP://example.com/");
-
- expect(html).toContain('<span class="tag" data-tag="&amp;HTTP">#&amp;HTTP</span>://example.com/');
- expect(html).not.toContain('data-tag="&amp;"');
- });
-
- it("recovers positionless text around remark-only email links", () => {
- const html = renderMarkdown("\\[email protected] #ok *\\[email protected] #inside*");
- const fallbackHTML = renderMarkdownWithoutMath("$\\[email protected] #math$ #outside");
-
- expect(html).toContain('data-tag="ok"');
- expect(html).toContain('data-tag="inside"');
- expect(fallbackHTML).not.toContain('data-tag="math"');
- expect(fallbackHTML).toContain('data-tag="outside"');
- });
-
- it("maps decoded positionless siblings without stealing a later source match", () => {
- const html = renderMarkdown("&#35;same \\[email protected] #same #left&amp; \\[email protected] #right");
-
- expect(html).toContain('#same <a href="mailto:[email protected]">[email protected]</a> <span class="tag" data-tag="same">#same</span>');
- expect(html).toContain('data-tag="left"');
- expect(html).toContain('data-tag="right"');
- expect(html.match(/data-tag="same"/g)).toHaveLength(1);
- });
-
- it.each([
- "*\\[email protected] #ok*",
- "# \\[email protected] #ok",
- "~~\\[email protected] #ok~~",
- "| value |\n| - |\n| \\[email protected] #ok |",
- ])("recovers positionless text inside a transparent Markdown container: %s", (source) => {
- expect(renderMarkdown(source)).toContain('data-tag="ok"');
- });
-
- it("keeps complete entity and escape ranges as source boundaries", () => {
- const html = renderMarkdown("https://localhost/#w&#35; HTTP://example.com/#q\\+ HTTP://example.com/#r&amp;x");
-
- expect(html).toContain('data-tag="w"');
- expect(html).not.toContain('data-tag="w&amp;"');
- expect(html).not.toContain('data-tag="35"');
- expect(html).toContain('data-tag="q"');
- expect(html).not.toContain('data-tag="q+"');
- expect(html).toContain('data-tag="r"');
- expect(html).not.toContain('data-tag="r&amp;"');
- expect(html).not.toContain("\\+");
- expect(html).not.toContain("&amp;amp;");
- });
- it("supplements decoded boundaries hidden by broad parser nodes", () => {
- const rejectedURL = renderMarkdown("+http://x.m/#u&#35;#v +http://x.m/#w\\|");
- expect(rejectedURL).toContain('data-tag="u"');
- expect(rejectedURL).toContain('data-tag="v"');
- expect(rejectedURL).toContain('data-tag="w"');
- expect(rejectedURL).not.toContain('data-tag="35"');
-
- const longEntity = renderMarkdown("#a&CounterClockwiseContourIntegral;b#c");
- expect(longEntity).toContain('data-tag="a"');
- expect(longEntity).toContain('data-tag="c"');
- });
- it.each(["~#a!&&amp;)*", ":#b[&-&amp;)", "&\\;#-"])("does not widen decoded source boundaries: %s", (source) => {
- expect(renderMarkdown(source)).toContain("data-tag=");
- });
- it("keeps tags after parser-omitted trailing whitespace", () => {
- expect(renderMarkdown("before \n#tag")).toContain('data-tag="tag"');
- expect(renderMarkdown(";.$;\nab- )> \n#&")).toContain('data-tag="&amp;"');
- });
- it("does not resolve a link through a rejected reference definition", () => {
- const html = renderMarkdown("[#use][bad]\n\n[bad]:(");
- expect(html).toContain('data-tag="use"');
- expect(html).not.toContain("<a ");
- });
- it("keeps GFM autolinks inside a rejected reference definition opaque", () => {
- expect(renderMarkdown("[#[email protected]]:(")).not.toContain('data-tag="foo"');
- expect(renderMarkdown("[ https://example.com/#hidden]:(")).not.toContain('data-tag="hidden"');
- });
- it.each([
- ".https://a.b/`#code` #tail",
- ".https://a.b/[#link](/x) #tail",
- ".https://a.b/![#image](/x) #tail",
- ".https://a.b/$#math$ #tail",
- ])("reparses opaque syntax swallowed by a rejected URL node: %s", (source) => {
- const html = renderMarkdown(source);
- expect(html).not.toContain('data-tag="code"');
- expect(html).not.toContain('data-tag="link"');
- expect(html).not.toContain('data-tag="image"');
- expect(html).not.toContain('data-tag="math"');
- expect(html).toContain('data-tag="tail"');
- });
- it("projects emphasis closed inside a rejected URL node", () => {
- const html = renderMarkdown("_[http://x.m/#v_>");
- expect(html).toContain('data-tag="v"');
- expect(html).not.toContain('data-tag="v_"');
- });
-
- it("follows written-GFM domain and email boundaries", () => {
- const html = renderMarkdown(
- "https://example.COM/#hidden www.example.123/#also-hidden https://a_b.foo.example/路径#still-hidden " +
- "https://foo_bar.example/#visible foo#[email protected] <foo#[email protected]> [email protected]/#after",
- );
-
- expect(html).not.toContain('data-tag="hidden"');
- expect(html).not.toContain('data-tag="also-hidden"');
- expect(html).not.toContain('data-tag="still-hidden"');
- expect(html).not.toContain('data-tag="angle"');
- expect(html).toContain('data-tag="visible"');
- expect(html).not.toContain('data-tag="mail"');
- expect(html).toContain('foo#<a href="mailto:[email protected]">[email protected]</a>');
- expect(html).toContain('data-tag="after"');
- });
-
- it("keeps written GFM URLs with Unicode domains opaque", () => {
- const html = renderMarkdown(
- "https://點看.com/#hidden www.點看.com/#also-hidden https://a_b.點看.com/#still-hidden " +
- "https://foo_bar.點看/#visible https://點看.com_/#suffix hellohttps://點看.com/#joined",
- );
-
- expect(html).toContain('href="https://%E9%BB%9E%E7%9C%8B.com/#hidden"');
- expect(html).toContain('href="http://www.%E9%BB%9E%E7%9C%8B.com/#also-hidden"');
- expect(html).not.toContain('data-tag="hidden"');
- expect(html).not.toContain('data-tag="also-hidden"');
- expect(html).not.toContain('data-tag="still-hidden"');
- expect(html).toContain('data-tag="visible"');
- expect(html).toContain('data-tag="suffix"');
- expect(html).toContain('data-tag="joined"');
- });
-
- it("uses GFM protocol and www boundaries for Unicode-domain URLs", () => {
- const html = renderMarkdown(
- "1https://點看.com/#digit .https://點看.com/#punctuation ]www.點看.com/#www " +
- "中https://點看.com/#unicode hellohttps://點看.com/#joined",
- );
-
- expect(html).toContain('data-tag="digit"');
- expect(html).toContain('data-tag="punctuation"');
- expect(html).toContain('data-tag="www"');
- expect(html).toContain('data-tag="unicode"');
- expect(html).toContain('data-tag="joined"');
- });
-
- it("keeps URLs blocked by unbalanced brackets tag-eligible", () => {
- const html = renderMarkdown(
- "[https://點看.com/#protocol\n\n[www.點看.com/#www\n\n\\[https://點看.com/#escaped\n\n\\[www.點看.com/#escaped-www",
- );
-
- expect(html).toContain('data-tag="protocol"');
- expect(html).toContain('data-tag="www"');
- expect(html).toContain('data-tag="escaped"');
- expect(html).toContain('data-tag="escaped-www"');
- });
-
- it("keeps a URL later in unresolved bracket text opaque", () => {
- const html = renderMarkdown("[text https://點看.com/#inside\n\n[more https://example.com/#ascii");
-
- expect(html).not.toContain('data-tag="inside"');
- expect(html).not.toContain('data-tag="ascii"');
- });
-
- it.each([
- "[ https://example.com/#hidden]",
- "[x https://example.com/#hidden]",
- "![ https://example.com/#hidden]",
- ])("follows GFM URL boundaries inside unresolved bracket text: %s", (source) =>
- expect(renderMarkdown(source)).not.toContain('data-tag="hidden"'));
-
- it("uses one explicit separator class for written URLs", () => {
- const html = renderMarkdown(
- "https://點看.com/\u00a0#nbsp https://點看.com/\u2003#em-space https://點看.com/\u000b#vertical-tab " +
- "https://點看.com/\u2028#line-separator https://點看.com/\u2029#paragraph-separator https://點看.com/\u0085#nel-hidden",
- );
-
- expect(html).toContain('data-tag="nbsp"');
- expect(html).toContain('data-tag="em-space"');
- expect(html).toContain('data-tag="vertical-tab"');
- expect(html).toContain('data-tag="line-separator"');
- expect(html).toContain('data-tag="paragraph-separator"');
- expect(html).not.toContain('data-tag="nel-hidden"');
- });
-
- it.each([
- "`[` https://example.com/#hidden",
- "$[$ https://example.com/#hidden",
- '<span data-x="[">x</span> https://example.com/#hidden',
- "<https://x.example/[> https://example.com/#hidden",
- ])("ignores brackets in earlier opaque syntax when classifying a URL: %s", (source) => {
- expect(renderMarkdown(source)).not.toContain('data-tag="hidden"');
- });
-
- it.each([
- [
- "foo",
- "foo/bar_baz",
- '<span class="tag" data-tag="foo">#foo</span>/<a href="mailto:[email protected]">[email protected]</a>',
- ],
- [
- "next",
- "next/item_",
- '<span class="tag" data-tag="next">#next</span>/<a href="mailto:[email protected]">[email protected]</a>',
- ],
- [
- "tag",
- "tag_",
- '<em><a href="mailto:[email protected]">[email protected]</a> <span class="tag" data-tag="tag">#tag</span></em>',
- ],
- ])("uses the complete GFM email and emphasis source ranges: %s", (source, tag, excludedTag, rendered) => {
- const html = renderMarkdown(source);
-
- expect(html).toContain(`data-tag="${tag}"`);
- expect(html).not.toContain(`data-tag="${excludedTag}"`);
- expect(html).toContain(rendered);
- });
-
- it("keeps only canonical GFM emails opaque before the mention transform", () => {
- const html = renderMarkdown("#foo/[email protected] @alice\n\n#next/[email protected] @bob\n\[email protected] #tag_ @carol");
-
- expect(html).not.toContain('data-mention="example"');
- expect(html).toContain('data-mention="alice"');
- expect(html).toContain('data-mention="bob"');
- expect(html).toContain('data-mention="carol"');
- expect(html).toContain('<em><a href="mailto:[email protected]">[email protected]</a> <span class="tag" data-tag="tag">#tag</span></em>');
- });
-
- it("renders only complete writable usernames and preserves their case", () => {
- const maximum = `A${"b".repeat(35)}`;
- const html = renderMarkdown(`@Alice-2 @1alice @123 @-alice @alice- @alice_smith @${maximum} @${maximum}c`);
-
- expect(html).toContain('data-mention="Alice-2"');
- expect(html).toContain('data-mention="1alice"');
- expect(html).toContain(`data-mention="${maximum}"`);
- expect(html).toContain('data-mention="123"');
- expect(html).not.toContain('data-mention="-alice"');
- expect(html).not.toContain('data-mention="alice-"');
- expect(html).toContain('data-mention="alice"');
- expect(html).not.toContain(`data-mention="${maximum}c"`);
- });
-
- it("uses Markdown structure for mention eligibility", () => {
- const html = renderMarkdown("**@Alice** `@code` [@link](/x) https://example.com/@url $@math$ \\@escaped &#64;entity @ok");
-
- expect(html).toContain('data-mention="Alice"');
- expect(html).toContain('data-mention="ok"');
- expect(html.match(/data-mention=/g)).toHaveLength(2);
- });
-
- it.each([
- [
- "[email protected] #tag__ @carol",
- '<strong><a href="mailto:[email protected]">[email protected]</a> <span class="tag" data-tag="tag">#tag</span></strong>',
- ],
- [
- "[email protected] #tag___ @carol",
- '<em><strong><a href="mailto:[email protected]">[email protected]</a> <span class="tag" data-tag="tag">#tag</span></strong></em>',
- ],
- [
- "[email protected] #tag____ @carol",
- '<strong><strong><a href="mailto:[email protected]">[email protected]</a> <span class="tag" data-tag="tag">#tag</span></strong></strong>',
- ],
- ])("reconciles nested underscore formatting around GFM emails: %s", (source, expected) => {
- const html = renderMarkdown(source);
-
- expect(html).toContain(expected);
- expect(html).toContain('data-mention="carol"');
- });
-
- it("decodes escapes while reconciling repeated and adjacent GFM email ranges", () => {
- const escaped = renderMarkdown("#foo\\[email protected] #next\\[email protected] @alice");
- const repeated = renderMarkdown("[email protected]@baz.example");
- const adjacent = renderMarkdown("[email protected][email protected]");
- const invalidSuffix = renderMarkdown("#foo/[email protected]_");
-
- expect(escaped).toContain('#<a href="mailto:[email protected]">[email protected]</a>');
- expect(escaped).toContain('#<a href="mailto:[email protected]">[email protected]</a>');
- expect(escaped).not.toContain('data-tag="foo"');
- expect(escaped).not.toContain('data-tag="next"');
- expect(escaped).not.toContain('data-mention="example"');
- expect(escaped).toContain('data-mention="alice"');
- expect(repeated).toContain('<a href="mailto:[email protected]">[email protected]</a>@baz.example');
- expect(repeated.match(/href="mailto:/g)).toHaveLength(1);
- expect(adjacent).toContain('<a href="mailto:[email protected]">[email protected]</a><a href="mailto:[email protected]">[email protected]</a>');
- expect(adjacent.match(/href="mailto:/g)).toHaveLength(2);
- expect(invalidSuffix).toContain('data-tag="foo/bar"');
- });
-
- it.each([
- ["#foo&#64;example.com", "[email protected]"],
- ])("decodes known entities before reconciling a GFM email: %s", (source, address) => {
- const html = renderMarkdown(source);
-
- expect(html).not.toContain('data-tag="foo"');
- expect(html).toContain(`href="mailto:${address}"`);
- });
-
- it("uses only contiguous literal source across mention node boundaries", () => {
- const html = renderMarkdown("#next/[email protected]@alice");
- const spacedHTML = renderMarkdown("#next/[email protected] @alice");
- const linkedHTML = renderMarkdown("[mail](https://example.com)@alice");
- const strongHTML = renderMarkdown("**bold**@alice");
- const emphasisHTML = renderMarkdown("*x*@alice");
- const tagHTML = renderMarkdown("#tag@alice");
- const adjacentMentionsHTML = renderMarkdown("@alice@bob");
-
- expect(html).not.toContain('data-mention="alice"');
- expect(spacedHTML).toContain('data-mention="alice"');
- expect(linkedHTML).toContain('data-mention="alice"');
- expect(strongHTML).toContain('data-mention="alice"');
- expect(emphasisHTML).toContain('data-mention="alice"');
- expect(tagHTML).not.toContain('data-mention="alice"');
- expect(adjacentMentionsHTML).toContain('data-mention="alice"');
- expect(adjacentMentionsHTML).not.toContain('data-mention="bob"');
- });
-
- it("does not turn link text or reference link fragments into tags", () => {
- const html = renderMarkdown(
- [
- "[release #notes](https://example.com/releases#release-notes)",
- "[**section #heading**](https://example.com/docs#section-heading)",
- "![preview #image](https://example.com/image#preview)",
- "[reference #anchor][docs]",
- "",
- "[docs]: https://example.com/docs#reference-anchor",
- "",
- "Outside #memo-tag",
- ].join("\n"),
- );
-
- expect(html).not.toContain('data-tag="notes"');
- expect(html).not.toContain('data-tag="heading"');
- expect(html).not.toContain('data-tag="image"');
- expect(html).not.toContain('data-tag="anchor"');
- expect(html).not.toContain('data-tag="release-notes"');
- expect(html).not.toContain('data-tag="section-heading"');
- expect(html).not.toContain('data-tag="preview"');
- expect(html).not.toContain('data-tag="reference-anchor"');
- expect(html).toContain('data-tag="memo-tag"');
- });
-
- it.each([
- "[a [#link](x) b][missing]",
- "[a ![#image](x) b][missing]",
- ])("keeps a resolved child opaque inside an unresolved outer link: %s", (source) =>
- expect(renderMarkdown(source)).not.toMatch(/data-tag="(?:link|image)"/));
-
- it("treats unresolved link-like syntax as ordinary tag-eligible text", () => {
- const html = renderMarkdown("[#tag][missing] [#other](unterminated");
-
- expect(html).toContain('data-tag="tag"');
- expect(html).toContain('data-tag="other"');
- });
-
- it.each([
- "[#[email protected]][missing]",
- "[#[email protected]](unterminated",
- "![#[email protected]][missing]",
- "[x][_#[email protected]_]",
- "![x][_#[email protected]_]",
- ])("keeps GFM emails opaque inside unresolved link-like source: %s", (source) => {
- const html = renderMarkdown(source);
-
- expect(html).not.toContain('data-tag="foo"');
- expect(html).toContain('href="mailto:[email protected]"');
- });
-
- it("keeps code opaque while reparsing an unresolved second label", () => {
- const html = renderMarkdown("[x][`#[email protected]`]");
-
- expect(html).not.toContain('data-tag="foo"');
- expect(html).not.toContain('href="mailto:[email protected]"');
- });
-
- it.each([
- "[x][https://example.com/#foo]",
- "![x][https://example.com/#foo]",
- ])("does not give a second-label URL a synthetic boundary: %s", (source) => expect(renderMarkdown(source)).toContain('data-tag="foo"'));
-
- it.each(["\n", "\r", "\r\n"])("deduplicates a %j boundary projected from an unresolved second label", (lineEnding) => {
- const html = renderMarkdown(`[#a][${lineEnding}]${lineEnding}${lineEnding}[#a]: /x`);
-
- expect(html).toContain('data-tag="a"');
- });
-
- it.each([
- "[x][<#[email protected]>]",
- "![x][<#[email protected]>]",
- "[x][<https://example.com/#foo>]",
- "![x][<https://example.com/#foo>]",
- ])("keeps autolinks opaque while reparsing an unresolved second label: %s", (source) =>
- expect(renderMarkdown(source)).not.toContain('data-tag="foo"'));
-
- it.each([
- "[x][\\#escaped #real]",
- "![x][\\#escaped #real]",
- "[x][&#35;escaped #real]",
- "![x][&#35;escaped #real]",
- ])("projects escaped introducer boundaries from an unresolved second label: %s", (source) => {
- const html = renderMarkdown(source);
-
- expect(html).not.toContain('data-tag="escaped"');
- expect(html).toContain('data-tag="real"');
- });
-
- it.each(["[x][#R&amp;D #real]", "![x][#R&amp;D #real]"])("projects entity boundaries from an unresolved second label: %s", (source) => {
- const html = renderMarkdown(source);
-
- expect(html).toContain('data-tag="R"');
- expect(html).toContain('data-tag="real"');
- expect(html).not.toContain('data-tag="R&D"');
- });
-
- it("recognizes tags in unresolved second labels while preserving emphasis boundaries", () => {
- const html = renderMarkdown("[x][#two] [#one][#two] [x][**#two**] [#x][#_foo_]");
-
- expect(html.match(/data-tag="two"/g)).toHaveLength(3);
- expect(html).toContain('data-tag="one"');
- expect(html).toContain('data-tag="x"');
- expect(html).not.toContain('data-tag="_foo_"');
- });
-
- it("uses CommonMark identifier normalization for reference links", () => {
- const sharpS = renderMarkdown("[#hidden][ẞ]\n\n[SS]: /path");
- const nul = renderMarkdown("[#hidden][a\0b]\n\n[a�b]: /path");
- const nonbreakingSpace = renderMarkdown("[#visible][\u00a0ref]\n\n[ref]: /path");
-
- expect(sharpS).not.toContain('data-tag="hidden"');
- expect(nul).not.toContain('data-tag="hidden"');
- expect(nonbreakingSpace).toContain('data-tag="visible"');
- });
-
- it("continues to turn formatted text outside links into tags", () => {
- const html = renderMarkdown("**#urgent** and _#later_ but not #_split_");
-
- expect(html).toContain('data-tag="urgent"');
- expect(html).toContain('data-tag="later"');
- expect(html).not.toContain('data-tag="_split_"');
- });
-
- it("does not turn a backslash-escaped \\#tag into a tag, but still tags an unescaped one", () => {
- const html = renderMarkdown("\\#NAS is my server and a #real tag");
-
- // Escaped: rendered as the literal text "#NAS", never a tag pill.
- expect(html).not.toContain('data-tag="NAS"');
- expect(html).toContain("#NAS");
- // Unescaped neighbour is unaffected.
- expect(html).toContain('data-tag="real"');
- });
-
- it("escapes only the marked hash when escaped and unescaped tags share a node", () => {
- const html = renderMarkdown("\\#first then #second");
-
- expect(html).not.toContain('data-tag="first"');
- expect(html).toContain("#first");
- expect(html).toContain('data-tag="second"');
- });
-
- it("tags a whole word containing combining marks", () => {
- // Malayalam കവിത = ka, va, vowel-sign-i (U+0D3F, a spacing combining mark),
- // ta. The vowel sign is a \p{M} character, so the tag must not stop at കവ.
- const html = renderMarkdown("#കവിത");
-
- expect(html).toContain('data-tag="കവിത"');
- expect(html).not.toContain('data-tag="കവ"');
- });
-
- it("still tags a hash that shares a text node with an entity reference", () => {
- const html = renderMarkdown("Tom &amp; Jerry #cartoon");
-
- expect(html).toContain('data-tag="cartoon"');
- expect(html).toContain("Tom &amp; Jerry");
- });
-
- it("uses original-source syntax boundaries rather than decoded text", () => {
- const html = renderMarkdown("&#35;tag &num;tag #foo\\+bar #R&amp;D #R&D #R&bogus;D #Q&amp;&bogus;D #ok");
-
- expect(html).not.toContain('data-tag="tag"');
- expect(html).toContain('data-tag="foo"');
- expect(html).toContain('data-tag="R"');
- expect(html).toContain('data-tag="R&amp;D"');
- expect(html).toContain('data-tag="R&amp;bogus"');
- expect(html).toContain('data-tag="Q"');
- expect(html).toContain('data-tag="ok"');
- });
-
- it("renders source spelling while exposing the emitted tag value", () => {
- const html = renderMarkdown("#A‍B #́foo #foo/́bar #👩‍💻");
-
- expect(html).toContain('<span class="tag" data-tag="AB">#A‍B</span>');
- expect(html).toContain('<span class="tag" data-tag="foo">#́foo</span>');
- expect(html).toContain('<span class="tag" data-tag="foo/bar">#foo/́bar</span>');
- expect(html).toContain('data-tag="👩‍💻"');
- });
-
- it("keeps word-internal apostrophes without absorbing quotation punctuation", () => {
- const html = renderMarkdown("#tag's #сім'я #O’Brien '#quoted' #users'");
-
- expect(html).toContain('<span class="tag" data-tag="tag&#x27;s">#tag&#x27;s</span>');
- expect(html).toContain('<span class="tag" data-tag="сім&#x27;я">#сім&#x27;я</span>');
- expect(html).toContain('<span class="tag" data-tag="O’Brien">#O’Brien</span>');
- expect(html).toContain('&#x27;<span class="tag" data-tag="quoted">#quoted</span>&#x27;');
- expect(html).toContain('<span class="tag" data-tag="users">#users</span>&#x27;');
- });
-
- it("uses maximal-prefix hierarchy and adjacent-introducer rules", () => {
- const html = renderMarkdown("#book/ #book//fiction #first#second ##tag #️⃣ ##️⃣");
-
- expect(html.match(/data-tag="book"/g)).toHaveLength(2);
- expect(html).toContain('data-tag="first"');
- expect(html).toContain('data-tag="second"');
- expect(html).toContain('data-tag="tag"');
- expect(html.match(/data-tag="#️⃣"/g)).toHaveLength(1);
- });
-
- it("maps tag source on both sides of CRLF line endings", () => {
- const html = renderMarkdown("#one\r\n#two");
-
- expect(html).toContain('data-tag="one"');
- expect(html).toContain('data-tag="two"');
- });
-
- it.each([1, 2, 3])("maps paragraph continuation indentation of %d spaces", (indent) => {
- const spaces = " ".repeat(indent);
- const after = renderMarkdown(`#before\n${spaces}text`);
- const before = renderMarkdown(`text\n${spaces}#after`);
-
- expect(after).toContain('data-tag="before"');
- expect(before).toContain('data-tag="after"');
- });
-
- it.each([
- ["- #before\n text", "before"],
- ["- text\n #after", "after"],
- ["1. #before\n text", "before"],
- ["1. text\n #after", "after"],
- ["> #before\n> text", "before"],
- ["> text\n> #after", "after"],
- ["#before\n\t#after", "before"],
- ["#before\n\t#after", "after"],
- ["- > #before\n > #after", "before"],
- ["- > #before\n > #after", "after"],
- ["> - #before\n> #after", "before"],
- ["> - #before\n> #after", "after"],
- ])("maps parser-consumed continuation prefixes in %s", (source, tag) => {
- expect(renderMarkdown(source)).toContain(`data-tag="${tag}"`);
- });
-
- it("maps CommonMark NUL replacement without losing adjacent tags", () => {
- const html = renderMarkdown("\uFEFF#bom \0#left #right\0");
-
- expect(html).toContain('<span class="tag" data-tag="bom">#bom</span>');
- expect(html).not.toContain('data-tag="bo"');
- expect(html).toContain('data-tag="left"');
- expect(html).toContain('data-tag="right"');
- });
-
- it("keeps URL context aligned after a leading BOM", () => {
- const html = renderMarkdown("\uFEFFhttp://example.com#hidden #shown");
-
- expect(html).not.toContain('data-tag="hidden"');
- expect(html).toContain('data-tag="shown"');
- });
-
- it("treats a second leading BOM as ordinary text", () => {
- const html = renderMarkdown("\uFEFF\uFEFFhttp://example.com#shown");
-
- expect(html).toContain('data-tag="shown"');
- });
-
- it("does not treat a mid-document BOM as a written URL boundary", () => {
- const html = renderMarkdown("before\n\n\uFEFFhttp://example.com#shown");
-
- expect(html).toContain('data-tag="shown"');
- });
-
- it("keeps source positions before hard-break and mention transforms", () => {
- const html = renderMarkdown("first #one\nsecond #two\n#tag@alice #tag @bob");
-
- expect(html).toContain('data-tag="one"');
- expect(html).toContain('data-tag="two"');
- expect(html).not.toContain('data-mention="alice"');
- expect(html).toContain('data-mention="bob"');
- });
-
- it("does not tag opaque Markdown contexts", () => {
- const html = renderMarkdown("`#code` and $#math$ and <https://example.com/#link> and #ok");
-
- expect(html).not.toContain('data-tag="code"');
- expect(html).not.toContain('data-tag="math"');
- expect(html).not.toContain('data-tag="link"');
- expect(html).toContain('data-tag="ok"');
- });
-
- it("keeps tags between currency dollars visible", () => {
- const html = renderMarkdown("$20,000 #budget and $30,000");
-
- expect(html).toContain('data-tag="budget"');
- expect(html).not.toContain("math-inline");
- });
-
- it("keeps math opaque while the math renderer is loading", () => {
- const html = renderMarkdownWithoutMath("$#inline$ and $$#mismatch$ plus #ok\n\n$$\n#block\n$$");
-
- expect(html).not.toContain('data-tag="inline"');
- expect(html).toContain('data-tag="mismatch"');
- expect(html).not.toContain('data-tag="block"');
- expect(html).toContain('data-tag="ok"');
- });
-
- it("maps CRLF flow math while the math renderer is loading", () => {
- const html = renderMarkdownWithoutMath("$$\r\n#inside\r\n$$\r\n#outside");
-
- expect(html).not.toContain('data-tag="inside"');
- expect(html).toContain('data-tag="outside"');
- });
-
- it.each([
- ["$#inner\\$#outer", "$#inner$"],
- ["$#inner&amp;$#outer", "$#inner&amp;$"],
- ])("maps decoded math source before an outside tag: %s", (source, renderedPrefix) => {
- const html = renderMarkdownWithoutMath(source);
-
- expect(html).toContain(`${renderedPrefix}<span class="tag" data-tag="outer">#outer</span>`);
- expect(html).not.toContain('data-tag="inner"');
- });
-
- it("maps CommonMark NUL replacement inside fallback math", () => {
- const html = renderMarkdownWithoutMath("$#inside\0$#outside");
-
- expect(html).not.toContain('data-tag="inside"');
- expect(html).toContain('data-tag="outside"');
- });
-
- it("keeps undeclared footnote definitions opaque", () => {
- const html = renderMarkdown("A[^1]\n\n[^1]: #foot\n\n#ok");
-
- expect(html).not.toContain('data-tag="foot"');
- expect(html).toContain('data-tag="ok"');
- });
-
- it("follows flow-math metadata boundaries", () => {
- expect(renderMarkdown("$$meta\n#math")).not.toContain('data-tag="math"');
- expect(renderMarkdown("$$meta$x\n#tag")).toContain('data-tag="tag"');
- });
-});
diff --git a/web/tests/setup.ts b/web/tests/setup.ts
index 79e46d4c1..cabf9b340 100644
--- a/web/tests/setup.ts
+++ b/web/tests/setup.ts
@@ -9,7 +9,7 @@ afterEach(() => {
cleanup();
});
-// ProseMirror probes layout APIs jsdom doesn't implement.
+// The Markdown editor probes layout APIs jsdom doesn't implement.
if (typeof document !== "undefined") {
if (!document.elementFromPoint) {
document.elementFromPoint = () => null;
@@ -19,10 +19,20 @@ if (typeof document !== "undefined") {
Range.prototype.getBoundingClientRect = () =>
({ x: 0, y: 0, top: 0, left: 0, bottom: 0, right: 0, width: 0, height: 0, toJSON: () => ({}) }) as DOMRect;
}
- // CodeMirror probes additional layout APIs jsdom doesn't implement while measuring.
if (typeof Element !== "undefined" && !Element.prototype.getClientRects) {
Element.prototype.getClientRects = () => [] as unknown as DOMRectList;
}
+ // jsdom does not treat contenteditable elements as focusable, and the editor's root is one.
+ // A tabindex makes jsdom focus it as a browser would.
+ if (typeof HTMLElement !== "undefined") {
+ const focus = HTMLElement.prototype.focus;
+ HTMLElement.prototype.focus = function (this: HTMLElement, options?: FocusOptions) {
+ // jsdom does not reflect the contentEditable property to the attribute either.
+ const editable = this.getAttribute("contenteditable") === "true" || this.contentEditable === "true";
+ if (editable && !this.hasAttribute("tabindex")) this.setAttribute("tabindex", "-1");
+ focus.call(this, options);
+ };
+ }
}
// jsdom runs with an opaque origin (no URL set), so its built-in localStorage
diff --git a/web/tests/task-list-item-check-all.test.tsx b/web/tests/task-list-item-check-all.test.tsx
deleted file mode 100644
index cda38820d..000000000
--- a/web/tests/task-list-item-check-all.test.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
-import { TaskListItem } from "@/components/MemoContent/TaskListItem";
-
-// Regression test for usememos/memos#6143 ("Check all tasks not working").
-//
-// remark-gfm passes `checked: undefined` for unchecked task items (`- [ ]`).
-// Base UI's Checkbox locks controlled/uncontrolled mode at mount, so a checkbox
-// that mounts with `checked === undefined` becomes uncontrolled and silently
-// ignores `checked=true` arriving later — exactly what happens after
-// "Check all tasks" rewrites the memo content and the markdown re-renders.
-// TaskListItem must coerce `checked` to a boolean so the checkbox is always
-// controlled.
-
-const mockUpdateMemo = vi.hoisted(() => vi.fn());
-
-vi.mock("@/hooks/useMemoQueries", () => ({
- useUpdateMemo: () => ({ mutate: mockUpdateMemo }),
-}));
-
-vi.mock("@/components/MemoView/MemoViewContext", () => ({
- useMemoViewContext: () => ({
- memo: {
- name: "memos/1",
- content: "- [ ] task one",
- relations: [],
- attachments: [],
- reactions: [],
- },
- }),
- useMemoViewDerived: () => ({
- readonly: false,
- }),
-}));
-
-describe("<TaskListItem /> check-all regression (#6143)", () => {
- it("reflects checked=true arriving after mounting unchecked (Check all tasks)", () => {
- // remark-gfm renders `- [ ]` with `checked` undefined.
- const { rerender } = render(<TaskListItem checked={undefined} node={undefined} />);
-
- const checkbox = screen.getByRole("checkbox");
- expect(checkbox).toHaveAttribute("aria-checked", "false");
-
- // "Check all tasks" updates memo content; the markdown re-renders with checked=true.
- rerender(<TaskListItem checked={true} node={undefined} />);
- expect(checkbox).toHaveAttribute("aria-checked", "true");
- });
-
- it("reflects checked reverting to undefined (Uncheck all tasks)", () => {
- const { rerender } = render(<TaskListItem checked={true} node={undefined} />);
-
- const checkbox = screen.getByRole("checkbox");
- expect(checkbox).toHaveAttribute("aria-checked", "true");
-
- // remark-gfm passes undefined (not false) for `- [ ]` items.
- rerender(<TaskListItem checked={undefined} node={undefined} />);
- expect(checkbox).toHaveAttribute("aria-checked", "false");
- });
-});
diff --git a/web/tests/toolbar-compact-width.test.ts b/web/tests/toolbar-compact-width.test.ts
deleted file mode 100644
index 13006f88b..000000000
--- a/web/tests/toolbar-compact-width.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { COMPACT_TOOLBAR_WIDTH, isCompactWidth } from "@/components/MemoEditor/hooks/useElementWidth";
-
-describe("isCompactWidth", () => {
- it("treats an unmeasured (0) width as not compact (full layout default)", () => {
- expect(isCompactWidth(0)).toBe(false);
- });
-
- it("is compact below the threshold", () => {
- expect(isCompactWidth(COMPACT_TOOLBAR_WIDTH - 1)).toBe(true);
- });
-
- it("is not compact at or above the threshold", () => {
- expect(isCompactWidth(COMPACT_TOOLBAR_WIDTH)).toBe(false);
- expect(isCompactWidth(COMPACT_TOOLBAR_WIDTH + 200)).toBe(false);
- });
-});
diff --git a/web/tests/use-inline-image-upload.test.tsx b/web/tests/use-inline-image-upload.test.tsx
index 91a407f3a..77108e719 100644
--- a/web/tests/use-inline-image-upload.test.tsx
+++ b/web/tests/use-inline-image-upload.test.tsx
@@ -56,10 +56,11 @@ describe("useInlineImageUpload", () => {
const editorRef = { current: controller } as RefObject<EditorController>;
const { result } = renderHook(() => useInlineImageUpload(editorRef), { wrapper });
- act(() => result.current.insertLocalImages([localImage("first.png"), localImage("second.png")], 7));
+ const position = { blockId: "b1", offset: 7 };
+ act(() => result.current.insertLocalImages([localImage("first.png"), localImage("second.png")], position));
await waitFor(() => expect(controller.resolveUploadAnchor).toHaveBeenCalledTimes(1));
- expect(controller.createUploadAnchor).toHaveBeenCalledWith(expect.any(Object), 7);
+ expect(controller.createUploadAnchor).toHaveBeenCalledWith(expect.any(Object), position);
expect(controller.resolveUploadAnchor).toHaveBeenCalledWith(
expect.any(String),
"![first](/file/attachments/first)\n\n![second](/file/attachments/second)",
diff --git a/web/tests/use-memo-init.test.tsx b/web/tests/use-memo-init.test.tsx
index 03b11cd45..53d425ce0 100644
--- a/web/tests/use-memo-init.test.tsx
+++ b/web/tests/use-memo-init.test.tsx
@@ -56,13 +56,14 @@ describe("useMemoInit", () => {
vi.useFakeTimers();
const key = cacheService.key("users/steven", "restored-draft");
cacheService.saveNow(key, { content: "An unfinished memo", attachments: [] });
- cacheService.saveCursor(key, 5);
+ const selection = { anchor: { block: 0, offset: 5 }, focus: { block: 0, offset: 5 } };
+ cacheService.saveCursor(key, selection);
const focus = vi.fn();
- const setCursor = vi.fn();
- editorRef.current = { focus, setCursor } as unknown as EditorController;
+ const setSelection = vi.fn();
+ editorRef.current = { focus, setSelection } as unknown as EditorController;
const autoFocus = vi.fn(() => {
expect(getEditorState().content).toBe("An unfinished memo");
- expect(setCursor).toHaveBeenCalledWith(5);
+ expect(setSelection).toHaveBeenCalledWith(selection);
return allowed;
});