1
0
Fork 0

feat(wiki): replace textarea overlay with a CodeMirror markdown editor

The body editor painted highlighted markdown in a div behind a transparent-text
textarea, so the painted text and the caret were two different layout engines.
Any wrap-point difference (borders, scrollbar gutters, engine rounding, trailing
newlines) shifted the overlay by whole lines once content soft-wrapped, making
clicks land on the wrong glyph and the document end feel unreachable. The CSS
patch that preceded this reduced the drift but could not remove the class of bug.

CodeMirror 6 owns text and caret together, so the failure mode is gone by
construction rather than by maintenance. The body remains a markdown string, so
prepareMarkdown, ::: directives, wikilinks, templates, revisions and the preview
pipeline are untouched, with no data migration.

- WikiMarkdownEditor: EditorView lifecycle, theme and markdown HighlightStyle
  bound to the app's CSS tokens, history, line wrapping, IME-safe keymap.
- markdownCommands: one pure command table shared by toolbar buttons and keys.
- editorChange: toolbar updates dispatch only the differing span, keeping undo
  granular and selections outside the edit intact.
- Removes WikiEditorHighlightLayer, editorMetrics, lib/wiki/editorHighlight,
  useEditorHistory and the now-dead textarea selection reader.
- Adds e2e proof: glyph-precise clicks across wrapped paragraphs, list items,
  image markdown and scrolled documents land at the exact clicked offset.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Jason Fraley 2026-11-18 15:12:22 -05:00
parent de60e5d3e0
commit 5e1f200261
17 changed files with 714 additions and 632 deletions

View file

@ -6,6 +6,11 @@
"name": "polaris-task-force",
"dependencies": {
"@ai-stack/payloadcms": "^3.2.30",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-markdown": "^6.5.2",
"@codemirror/language": "^6.13.1",
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.15",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
@ -15,6 +20,7 @@
"@lexical/react": "0.41.0",
"@lexical/rich-text": "0.41.0",
"@lexical/selection": "0.41.0",
"@lezer/highlight": "^1.2.5",
"@microsoft/clarity": "^1.0.2",
"@payloadcms/db-postgres": "3.88.0",
"@payloadcms/email-nodemailer": "3.88.0",
@ -266,6 +272,28 @@
"@borewit/text-codec": ["@borewit/text-codec@0.1.1", "", {}, "sha512-5L/uBxmjaCIX5h8Z+uu+kA9BQLkc/Wl06UGR5ajNRxu+/XjonB5i8JpgFMrPj3LXTCPA0pv8yxUvbUi+QthGGA=="],
"@codemirror/autocomplete": ["@codemirror/autocomplete@6.20.4", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0" } }, "sha512-yF8RhOf2SXlg00+qtupzLhrglcas61boqaONiNcbPIebHCpJocpqTBA6dyrtUrQO47hqyTdeob/3XnYilT7TaQ=="],
"@codemirror/commands": ["@codemirror/commands@6.11.1", "", { "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.7.0", "@codemirror/view": "^6.27.0", "@lezer/common": "^1.1.0" } }, "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg=="],
"@codemirror/lang-css": ["@codemirror/lang-css@6.3.1", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", "@lezer/common": "^1.0.2", "@lezer/css": "^1.1.7" } }, "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg=="],
"@codemirror/lang-html": ["@codemirror/lang-html@6.4.12", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/lang-css": "^6.0.0", "@codemirror/lang-javascript": "^6.0.0", "@codemirror/language": "^6.4.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/css": "^1.1.0", "@lezer/html": "^1.3.12" } }, "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w=="],
"@codemirror/lang-javascript": ["@codemirror/lang-javascript@6.2.5", "", { "dependencies": { "@codemirror/autocomplete": "^6.0.0", "@codemirror/language": "^6.6.0", "@codemirror/lint": "^6.0.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.17.0", "@lezer/common": "^1.0.0", "@lezer/javascript": "^1.0.0" } }, "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A=="],
"@codemirror/lang-markdown": ["@codemirror/lang-markdown@6.5.2", "", { "dependencies": { "@codemirror/autocomplete": "^6.7.1", "@codemirror/lang-html": "^6.0.0", "@codemirror/language": "^6.3.0", "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.0.0", "@lezer/common": "^1.2.1", "@lezer/markdown": "^1.0.0" } }, "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw=="],
"@codemirror/language": ["@codemirror/language@6.13.1", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/streamparser": "^6.0.0", "@codemirror/view": "^6.23.0", "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0", "style-mod": "^4.0.0" } }, "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw=="],
"@codemirror/lint": ["@codemirror/lint@6.9.8", "", { "dependencies": { "@codemirror/state": "^6.0.0", "@codemirror/view": "^6.42.0", "crelt": "^1.0.5" } }, "sha512-qNvtcE73xUto/D1RvtgSRI4A1Hg8ekxlvtZpjHpdpisLBnhyu82EUEJMEgaxkjuQCA8vqnrylENWKOsEDCOHcw=="],
"@codemirror/state": ["@codemirror/state@6.7.6", "", { "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } }, "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w=="],
"@codemirror/streamparser": ["@codemirror/streamparser@6.0.0", "", {}, "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w=="],
"@codemirror/view": ["@codemirror/view@6.43.15", "", { "dependencies": { "@codemirror/state": "^6.7.0", "crelt": "^1.0.6", "style-mod": "^4.1.0", "w3c-keyname": "^2.2.4" } }, "sha512-HHsfpqFeHyXLs983pSRe38Xajs0vFWZQ2BuX0m7Ki8w3jZ5iD8cuR3lBz2/5/X53Dhf32SBHKh6rtSTB6tKeGw=="],
"@colors/colors": ["@colors/colors@1.5.0", "", {}, "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ=="],
"@csstools/color-helpers": ["@csstools/color-helpers@5.1.0", "", {}, "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA=="],
@ -548,6 +576,22 @@
"@lexical/yjs": ["@lexical/yjs@0.41.0", "", { "dependencies": { "@lexical/offset": "0.41.0", "@lexical/selection": "0.41.0", "lexical": "0.41.0" }, "peerDependencies": { "yjs": ">=13.5.22" } }, "sha512-PaKTxSbVC4fpqUjQ7vUL9RkNF1PjL8TFl5jRe03PqoPYpE33buf3VXX6+cOUEfv9+uknSqLCPHoBS/4jN3a97w=="],
"@lezer/common": ["@lezer/common@1.5.5", "", {}, "sha512-Pw7PVCndruF1pb3ebCxpSVpkMHSDjwRCLcTRw+RizUKco5QbWylwq2g4lnG/RYN7yTTQDXE9F77MwtkAyphrjg=="],
"@lezer/css": ["@lezer/css@1.3.9", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.3.0" } }, "sha512-ZmzgvTOBdJWGIsY/ItAfN7UW8DV802oZG+jeG6E508SwEzz5YhuAajptpWPICvIyqYAD2+VjMdOS40GgGkyEOQ=="],
"@lezer/highlight": ["@lezer/highlight@1.2.5", "", { "dependencies": { "@lezer/common": "^1.3.0" } }, "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w=="],
"@lezer/html": ["@lezer/html@1.3.13", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.0.0", "@lezer/lr": "^1.0.0" } }, "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg=="],
"@lezer/javascript": ["@lezer/javascript@1.5.6", "", { "dependencies": { "@lezer/common": "^1.2.0", "@lezer/highlight": "^1.1.3", "@lezer/lr": "^1.3.0" } }, "sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA=="],
"@lezer/lr": ["@lezer/lr@1.4.12", "", { "dependencies": { "@lezer/common": "^1.0.0" } }, "sha512-On9HU4oMMiHPMkQDgoTnGahjgG5n/MkN38CgG77sMraKLL+3JBbeQNi1FcCXV9QRqwF9/BUXP3caHyJC1fBOTQ=="],
"@lezer/markdown": ["@lezer/markdown@1.8.1", "", { "dependencies": { "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0" } }, "sha512-M5YmEcKWO4mJ45Y1hECwqyu8cLv25EiXOK554PVOvDOWOP0olwelHHQUWr9sjF+d1bENVhy0nfJ8E57XZUTiXg=="],
"@marijn/find-cluster-break": ["@marijn/find-cluster-break@1.0.4", "", {}, "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ=="],
"@microsoft/clarity": ["@microsoft/clarity@1.0.2", "", {}, "sha512-9EZYROFpJxEGmQpHvUFqvD3ZJ7QQSqnibYSWmS+1xusoZfG1QQ1/Al9yVBBc11DWMbJrs1pe1hLT273it/skJg=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.30.0", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA=="],
@ -608,7 +652,7 @@
"@payloadcms/richtext-lexical": ["@payloadcms/richtext-lexical@3.88.0", "", { "dependencies": { "@lexical/clipboard": "0.41.0", "@lexical/headless": "0.41.0", "@lexical/html": "0.41.0", "@lexical/link": "0.41.0", "@lexical/list": "0.41.0", "@lexical/mark": "0.41.0", "@lexical/react": "0.41.0", "@lexical/rich-text": "0.41.0", "@lexical/selection": "0.41.0", "@lexical/table": "0.41.0", "@lexical/utils": "0.41.0", "@payloadcms/translations": "3.88.0", "@payloadcms/ui": "3.88.0", "acorn": "8.16.0", "bson-objectid": "2.0.4", "csstype": "3.1.3", "dequal": "2.0.3", "escape-html": "1.0.3", "jsox": "1.2.121", "lexical": "0.41.0", "mdast-util-from-markdown": "2.0.2", "mdast-util-mdx-jsx": "3.1.3", "micromark-extension-mdx-jsx": "3.0.1", "qs-esm": "8.0.1", "react-error-boundary": "4.1.2", "ts-essentials": "10.0.3", "uuid": "13.0.2" }, "peerDependencies": { "@faceless-ui/modal": "3.0.0", "@faceless-ui/scroll-info": "2.0.0", "@payloadcms/next": "3.88.0", "payload": "3.88.0", "react": "^19.0.1 || ^19.1.2 || ^19.2.1", "react-dom": "^19.0.1 || ^19.1.2 || ^19.2.1" } }, "sha512-lY8oIUiggykWKB3ljMfSidxBtA8ahMq0Qqp28OuvaCNIDp0HTMIPxcHvFOQZngMqtQHhpautD6vcQR0Q9CEHHQ=="],
"@payloadcms/translations": ["@payloadcms/translations@3.79.1", "", { "dependencies": { "date-fns": "4.1.0" } }, "sha512-v+UUDMqVl50TQhCPOVuVmsayw2tupDqWHfW6CzkPjA7hYuF5Wb8Bm2wyPE6sPUJB7+TqprziN3ecCUhwXyGr2A=="],
"@payloadcms/translations": ["@payloadcms/translations@3.88.0", "", { "dependencies": { "date-fns": "4.1.0" } }, "sha512-AZVQjjW5pKxO+K9ODeh6yw6/EfXK1hxGPw55KzzDC5srO3hjNskgyWtkauKvbz+S0+xFspANbRc4OD/Rg/74WA=="],
"@payloadcms/ui": ["@payloadcms/ui@3.88.0", "", { "dependencies": { "@date-fns/tz": "1.2.0", "@dnd-kit/core": "6.3.1", "@dnd-kit/sortable": "10.0.0", "@dnd-kit/utilities": "3.2.2", "@faceless-ui/modal": "3.0.0", "@faceless-ui/scroll-info": "2.0.0", "@faceless-ui/window-info": "3.0.1", "@monaco-editor/react": "4.7.0", "@payloadcms/translations": "3.88.0", "bson-objectid": "2.0.4", "date-fns": "4.1.0", "dequal": "2.0.3", "md5": "2.3.0", "object-to-formdata": "4.5.1", "qs-esm": "8.0.1", "react-datepicker": "7.6.0", "react-image-crop": "10.1.8", "react-select": "5.9.0", "scheduler": "0.25.0", "sonner": "^1.7.2", "ts-essentials": "10.0.3", "use-context-selector": "2.0.0", "uuid": "13.0.2" }, "peerDependencies": { "next": ">=15.2.9 <15.3.0 || >=15.3.9 <15.4.0 || >=15.4.11 <15.5.0 || >=16.2.6 <17.0.0", "payload": "3.88.0", "react": "^19.0.1 || ^19.1.2 || ^19.2.1", "react-dom": "^19.0.1 || ^19.1.2 || ^19.2.1" } }, "sha512-iwQhHPDn4Oj2bPg1UV467BoxfUNo1rUmD8jMZaw2Vtt/nmxAPl3W3CWN/CsOX/yITuPuGHJxznOg4PZNMF3gEg=="],
@ -1328,6 +1372,8 @@
"cosmiconfig": ["cosmiconfig@7.1.0", "", { "dependencies": { "@types/parse-json": "4.0.2", "import-fresh": "3.3.1", "parse-json": "5.2.0", "path-type": "4.0.0", "yaml": "1.10.2" } }, "sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA=="],
"crelt": ["crelt@1.0.7", "", {}, "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA=="],
"croner": ["croner@10.0.1", "", {}, "sha512-ixNtAJndqh173VQ4KodSdJEI6nuioBWI0V1ITNKhZZsO0pEMoDxz539T4FTTbSZ/xIOSuDnzxLVRqBVSvPNE2g=="],
"cross-env": ["cross-env@10.1.0", "", { "dependencies": { "@epic-web/invariant": "1.0.0", "cross-spawn": "7.0.6" }, "bin": { "cross-env": "dist/bin/cross-env.js", "cross-env-shell": "dist/bin/cross-env-shell.js" } }, "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw=="],
@ -2478,6 +2524,8 @@
"strtok3": ["strtok3@10.3.5", "", { "dependencies": { "@tokenizer/token": "^0.3.0" } }, "sha512-ki4hZQfh5rX0QDLLkOCj+h+CVNkqmp/CMf8v8kZpkNVK6jGQooMytqzLZYUVYIZcFZ6yDB70EfD8POcFXiF5oA=="],
"style-mod": ["style-mod@4.1.5", "", {}, "sha512-WQ2llCZa9sZSkJA+aOwpg5DkfbAXFKGh//t3MRTBeruFiSBC+GXUmbBzrw3bXyboCWAbtCW9InDfBsXrRD/rAg=="],
"style-to-js": ["style-to-js@1.1.21", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
"style-to-object": ["style-to-object@1.0.14", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="],
@ -2646,6 +2694,8 @@
"vitest": ["vitest@4.0.16", "", { "dependencies": { "@vitest/expect": "4.0.16", "@vitest/mocker": "4.0.16", "@vitest/pretty-format": "4.0.16", "@vitest/runner": "4.0.16", "@vitest/snapshot": "4.0.16", "@vitest/spy": "4.0.16", "@vitest/utils": "4.0.16", "es-module-lexer": "1.7.0", "expect-type": "1.2.2", "magic-string": "0.30.21", "obug": "2.1.1", "pathe": "2.0.3", "picomatch": "4.0.3", "std-env": "3.10.0", "tinybench": "2.9.0", "tinyexec": "1.0.2", "tinyglobby": "0.2.15", "tinyrainbow": "3.0.3", "vite": "7.1.10", "why-is-node-running": "2.3.0" }, "optionalDependencies": { "@types/node": "25.0.3", "jsdom": "27.3.0" }, "bin": { "vitest": "vitest.mjs" } }, "sha512-E4t7DJ9pESL6E3I8nFjPa4xGUd3PmiWDLsDztS2qXSJWfHtbQnwAWylaBvSNY48I3vr8PTqIZlyK8TE3V3CA4Q=="],
"w3c-keyname": ["w3c-keyname@2.2.8", "", {}, "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ=="],
"w3c-xmlserializer": ["w3c-xmlserializer@5.0.0", "", { "dependencies": { "xml-name-validator": "5.0.0" } }, "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA=="],
"web-streams-polyfill": ["web-streams-polyfill@3.3.3", "", {}, "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="],
@ -2772,22 +2822,14 @@
"@payloadcms/graphql/tsx": ["tsx@4.22.4", "", { "dependencies": { "esbuild": "~0.28.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg=="],
"@payloadcms/next/@payloadcms/translations": ["@payloadcms/translations@3.88.0", "", { "dependencies": { "date-fns": "4.1.0" } }, "sha512-AZVQjjW5pKxO+K9ODeh6yw6/EfXK1hxGPw55KzzDC5srO3hjNskgyWtkauKvbz+S0+xFspANbRc4OD/Rg/74WA=="],
"@payloadcms/payload-cloud/nodemailer": ["nodemailer@9.0.3", "", {}, "sha512-n+YP+NKwR5zRWa60k3GiQ6Q3B4KXCoAw40dAKeCtYn020iNN74aWK2liXIC3ZEATeGql7we3tE3t8QwhY0eskw=="],
"@payloadcms/plugin-form-builder/@payloadcms/translations": ["@payloadcms/translations@3.88.0", "", { "dependencies": { "date-fns": "4.1.0" } }, "sha512-AZVQjjW5pKxO+K9ODeh6yw6/EfXK1hxGPw55KzzDC5srO3hjNskgyWtkauKvbz+S0+xFspANbRc4OD/Rg/74WA=="],
"@payloadcms/plugin-mcp/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"@payloadcms/richtext-lexical/@payloadcms/translations": ["@payloadcms/translations@3.88.0", "", { "dependencies": { "date-fns": "4.1.0" } }, "sha512-AZVQjjW5pKxO+K9ODeh6yw6/EfXK1hxGPw55KzzDC5srO3hjNskgyWtkauKvbz+S0+xFspANbRc4OD/Rg/74WA=="],
"@payloadcms/richtext-lexical/csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="],
"@payloadcms/richtext-lexical/react-error-boundary": ["react-error-boundary@4.1.2", "", { "dependencies": { "@babel/runtime": "7.28.4" }, "peerDependencies": { "react": "19.2.3" } }, "sha512-GQDxZ5Jd+Aq/qUxbCm1UtzmL/s++V7zKgE8yMktJiCQXCCFZnMZh9ng+6/Ne6PjNSXH0L9CjeOEREfRnq6Duag=="],
"@payloadcms/ui/@payloadcms/translations": ["@payloadcms/translations@3.88.0", "", { "dependencies": { "date-fns": "4.1.0" } }, "sha512-AZVQjjW5pKxO+K9ODeh6yw6/EfXK1hxGPw55KzzDC5srO3hjNskgyWtkauKvbz+S0+xFspANbRc4OD/Rg/74WA=="],
"@payloadcms/ui/sonner": ["sonner@1.7.4", "", { "peerDependencies": { "react": "19.2.3", "react-dom": "19.2.3" } }, "sha512-DIS8z4PfJRbIyfVFDVnK9rO3eYDtse4Omcm6bt0oEr5/jtLgysmjuBl1frJ9E/EQZrFmKx2A8m/s5s9CRXIzhw=="],
"@redis/client/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],
@ -2940,8 +2982,6 @@
"payload/@next/env": ["@next/env@15.5.5", "", {}, "sha512-2Zhvss36s/yL+YSxD5ZL5dz5pI6ki1OLxYlh6O77VJ68sBnlUrl5YqhBgCy7FkdMsp9RBeGFwpuDCdpJOqdKeQ=="],
"payload/@payloadcms/translations": ["@payloadcms/translations@3.88.0", "", { "dependencies": { "date-fns": "4.1.0" } }, "sha512-AZVQjjW5pKxO+K9ODeh6yw6/EfXK1hxGPw55KzzDC5srO3hjNskgyWtkauKvbz+S0+xFspANbRc4OD/Rg/74WA=="],
"payload/ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
"payload/jose": ["jose@5.10.0", "", {}, "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg=="],

View file

@ -36,6 +36,11 @@
},
"dependencies": {
"@ai-stack/payloadcms": "^3.2.30",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-markdown": "^6.5.2",
"@codemirror/language": "^6.13.1",
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.15",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
@ -45,6 +50,7 @@
"@lexical/react": "0.41.0",
"@lexical/rich-text": "0.41.0",
"@lexical/selection": "0.41.0",
"@lezer/highlight": "^1.2.5",
"@microsoft/clarity": "^1.0.2",
"@payloadcms/db-postgres": "3.88.0",
"@payloadcms/email-nodemailer": "3.88.0",

View file

@ -53,6 +53,9 @@ Pages are server components that fetch via `getPayload()`, then pass data as pro
### Rich-text rendering
Front-end surfaces render serialized Lexical with the shared `RichTextView` (`src/components/frontend/RichTextView.tsx`): it applies `.lexical-content` typography and paints saved text colours (TextStateFeature state or inline styles), both of which Payload's default JSX renderer drops. Briefings render through this component too (mission briefing sections use it directly). Editors come from `ptfLexicalEditor()` (`src/lib/lexical/editor.ts`) so every rich-text field gets the fixed toolbar + colour palette by default.
### Wiki body editor
`/wiki/new` and the edit route render `WikiMarkdownEditor` (`src/components/frontend/wiki/WikiMarkdownEditor.tsx`), a CodeMirror 6 markdown editor over the page's plain markdown string; the body field stays markdown, so `prepareMarkdown`, templates, `:::` directives, wikilinks and the preview pipeline are untouched. Do NOT reintroduce a mirrored overlay (a highlighted `<div>` behind a transparent `<textarea>`) or a custom textarea metrics contract: the caret and the painted text must be the same engine, otherwise soft-wrapped lines drift apart by a line or more and clicks land on the wrong glyph. Toolbar buttons, the editor keymap and tests all call the pure commands in `markdownCommands.ts` (built on `src/lib/wiki/editorFormatting.ts`), and toolbar edits dispatch only the minimal changed span (`src/lib/wiki/editorChange.ts`) so history stays granular.
### SSE consumers
- `GameTickRealtime` mounts in `(frontend)/layout.tsx` for all authed users.
- `ShipmentToasts` mounts only for logistics-qualified users.

View file

@ -24,6 +24,7 @@ import { track } from "@/lib/client-analytics";
import { buildTemplateStyles } from "@/lib/wiki/templateCss";
import { MarkdownGuide } from "@/components/frontend/wiki/MarkdownGuide";
import { WikiEditorBody } from "@/components/frontend/wiki/WikiEditorBody";
import type { WikiMarkdownEditorHandle } from "@/components/frontend/wiki/WikiMarkdownEditor";
import { WikiStandardsDialog } from "@/components/frontend/wiki/WikiStandardsDialog";
import { WikiPreparedBody } from "@/components/frontend/wiki/WikiContent";
@ -82,7 +83,7 @@ export function WikiEditor({
canEditDocumentation = false,
}: WikiEditorProps) {
const router = useRouter();
const bodyRef = useRef<HTMLTextAreaElement>(null);
const editorRef = useRef<WikiMarkdownEditorHandle>(null);
const [title, setTitle] = useState(initial?.title ?? initialTitle ?? "");
const [category, setCategory] = useState<WikiCategory>(initial?.category ?? "Meta");
const [tags, setTags] = useState(initial?.tags.join(", ") ?? "");
@ -253,7 +254,7 @@ export function WikiEditor({
<div className="lg:sticky lg:top-5">
<WikiEditorBody
body={body}
bodyRef={bodyRef}
editorRef={editorRef}
existingPages={existingPages}
linkDialogOpen={linkDialogOpen}
onBodyChange={setBody}

View file

@ -1,6 +1,6 @@
"use client";
import { type ChangeEvent, type KeyboardEvent, type RefObject, useRef, useState } from "react";
import { type ChangeEvent, type RefObject, useRef, useState } from "react";
import {
Bold,
Code,
@ -24,33 +24,19 @@ import {
} from "lucide-react";
import { toast } from "sonner";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { WIKI_EDITOR_METRICS, WIKI_EDITOR_SCROLLBAR_NONE } from "./editorMetrics";
import { WikiLinkDialog } from "@/components/frontend/wiki/WikiLinkDialog";
import { WikiEditorHighlightLayer } from "@/components/frontend/wiki/WikiEditorHighlightLayer";
import { WikiTemplateDialog } from "@/components/frontend/wiki/WikiTemplateDialog";
import { useEditorHistory } from "@/components/frontend/wiki/useEditorHistory";
import { uploadWikiImage } from "@/app/(frontend)/wiki/actions";
import type { TemplateMap } from "@/lib/wiki/templates";
import {
IMAGE_SNIPPET,
INFOBOX_SNIPPET,
TABLE_SNIPPET,
THREE_COLUMN_SNIPPET,
TWO_COLUMN_SNIPPET,
createLinePrefixUpdate,
createListContinueUpdate,
createFormatUpdate,
createIndentUpdate,
createReferenceUpdate,
createSnippetUpdate,
createWrappedUpdate,
readBodySelection,
type BodyUpdate,
type SnippetInsertion,
type WrappedFormat,
} from "@/lib/wiki/editorFormatting";
WikiMarkdownEditor,
type WikiMarkdownEditorHandle,
} from "@/components/frontend/wiki/WikiMarkdownEditor";
import {
markdownCommands,
type MarkdownCommand,
} from "@/components/frontend/wiki/markdownCommands";
import { uploadWikiImage } from "@/app/(frontend)/wiki/actions";
import { createSnippetUpdate, type BodyUpdate } from "@/lib/wiki/editorFormatting";
import type { TemplateMap } from "@/lib/wiki/templates";
import {
WikiEditorToolbar,
type WikiEditorToolbarAction,
@ -58,7 +44,7 @@ import {
interface WikiEditorBodyProps {
readonly body: string;
readonly bodyRef: RefObject<HTMLTextAreaElement | null>;
readonly editorRef: RefObject<WikiMarkdownEditorHandle | null>;
readonly existingPages: readonly { title: string }[];
readonly linkDialogOpen: boolean;
readonly onBodyChange: (value: string) => void;
@ -71,7 +57,7 @@ interface WikiEditorBodyProps {
export function WikiEditorBody({
body,
bodyRef,
editorRef,
existingPages,
linkDialogOpen,
onBodyChange,
@ -82,51 +68,25 @@ export function WikiEditorBody({
templateHtmlMap,
}: WikiEditorBodyProps) {
const fileInputRef = useRef<HTMLInputElement>(null);
const mirrorRef = useRef<HTMLDivElement>(null);
const { record, undo, redo } = useEditorHistory(body, bodyRef);
const [uploading, setUploading] = useState(false);
const [templateDialogOpen, setTemplateDialogOpen] = useState(false);
function syncMirrorScroll(textarea: HTMLTextAreaElement) {
if (mirrorRef.current) mirrorRef.current.scrollTop = textarea.scrollTop;
function currentBody(): string {
return editorRef.current?.getValue() ?? body;
}
function scrollCaretIntoView(caret: number) {
const textarea = bodyRef.current;
const mirror = mirrorRef.current;
if (!textarea || !mirror || caret < 0) return;
const walker = document.createTreeWalker(mirror, NodeFilter.SHOW_TEXT);
let remaining = caret;
let node = walker.nextNode() as Text | null;
let lastNode = node;
while (node && remaining > (node.textContent?.length ?? 0)) {
remaining -= node.textContent?.length ?? 0;
lastNode = node;
node = walker.nextNode() as Text | null;
function applyUpdate(update: BodyUpdate) {
editorRef.current?.applyUpdate(update);
}
const target = node ?? lastNode;
if (!target) return;
const offset = Math.min(remaining, target.textContent?.length ?? 0);
const range = document.createRange();
try {
range.setStart(target, offset);
} catch {
return;
}
range.collapse(true);
const mirrorRect = mirror.getBoundingClientRect();
const caretTop =
range.getBoundingClientRect().top - mirrorRect.top + mirror.scrollTop;
const lineHeight = parseFloat(getComputedStyle(textarea).lineHeight) || 20;
const viewTop = textarea.scrollTop;
const viewBottom = viewTop + textarea.clientHeight - lineHeight;
if (caretTop < viewTop || caretTop > viewBottom) {
textarea.scrollTop = Math.max(0, caretTop - textarea.clientHeight / 2);
syncMirrorScroll(textarea);
}
function runCommand(command: MarkdownCommand) {
const selection = editorRef.current?.getSelection() ?? {
start: 0,
end: 0,
text: "",
};
const update = command(currentBody(), selection);
if (update) applyUpdate(update);
}
async function handleFileChange(event: ChangeEvent<HTMLInputElement>) {
@ -144,7 +104,12 @@ export function WikiEditorBody({
return;
}
const { url, alt } = result.data;
insertSnippet({ insertion: `![${alt}](${url})`, placeholder: alt });
runCommand((value, selection) =>
createSnippetUpdate(value, selection, {
insertion: `![${alt}](${url})`,
placeholder: alt,
}),
);
toast.success("Image uploaded.");
} catch {
toast.error("Upload failed.");
@ -153,187 +118,51 @@ export function WikiEditorBody({
}
}
function applyBodyUpdate(update: BodyUpdate, recordHistory = true) {
if (recordHistory) {
record(update.value, update.selectionStart, update.selectionEnd, false);
}
onBodyChange(update.value);
requestAnimationFrame(() => {
requestAnimationFrame(() => {
const textarea = bodyRef.current;
if (!textarea) return;
textarea.focus();
textarea.setSelectionRange(update.selectionStart, update.selectionEnd);
scrollCaretIntoView(update.selectionStart);
syncMirrorScroll(textarea);
});
});
}
function handleBodyChange(event: ChangeEvent<HTMLTextAreaElement>) {
const { value, selectionStart, selectionEnd } = event.target;
record(value, selectionStart, selectionEnd, true);
onBodyChange(value);
}
function wrapSelection(format: WrappedFormat) {
const selection = readBodySelection(body, bodyRef);
applyBodyUpdate(createWrappedUpdate(body, selection, format));
}
function prefixLines(prefix: string) {
const selection = readBodySelection(body, bodyRef);
applyBodyUpdate(createLinePrefixUpdate(body, selection, prefix));
}
function insertSnippet(snippet: SnippetInsertion) {
const selection = readBodySelection(body, bodyRef);
applyBodyUpdate(createSnippetUpdate(body, selection, snippet));
}
function insertReference(definitionSuffix: string) {
const selection = readBodySelection(body, bodyRef);
applyBodyUpdate(createReferenceUpdate(body, selection, { definitionSuffix }));
}
function insertWikilink(pageTitle: string) {
const selection = readBodySelection(body, bodyRef);
applyBodyUpdate(
createSnippetUpdate(body, selection, {
insertion: `[[${pageTitle}]]`,
}),
runCommand((value, selection) =>
createSnippetUpdate(value, selection, { insertion: `[[${pageTitle}]]` }),
);
onLinkDialogChange(false);
}
function insertTemplateBody(value: string) {
const selection = readBodySelection(body, bodyRef);
applyBodyUpdate(
createSnippetUpdate(body, selection, { insertion: value }),
runCommand((current, selection) =>
createSnippetUpdate(current, selection, { insertion: value }),
);
setTemplateDialogOpen(false);
}
function formatBody() {
const selection = readBodySelection(body, bodyRef);
applyBodyUpdate(createFormatUpdate(body, selection));
}
function handleBodyKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
if (event.nativeEvent.isComposing) return;
if ((event.metaKey || event.ctrlKey) && !event.altKey) {
const undoKey = event.key.toLowerCase();
if (undoKey === "z") {
event.preventDefault();
const entry = event.shiftKey ? redo() : undo();
if (entry) applyBodyUpdate(entry, false);
return;
}
if (undoKey === "y" && !event.shiftKey) {
event.preventDefault();
const entry = redo();
if (entry) applyBodyUpdate(entry, false);
return;
}
}
if (event.key === "Tab") {
event.preventDefault();
const selection = readBodySelection(body, bodyRef);
const update = createIndentUpdate(body, selection, event.shiftKey);
if (update) applyBodyUpdate(update);
return;
}
if (event.key === "Enter" && !event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey) {
const selection = readBodySelection(body, bodyRef);
const update = createListContinueUpdate(body, selection);
if (update) {
event.preventDefault();
applyBodyUpdate(update);
}
return;
}
const modifierPressed = event.metaKey || event.ctrlKey;
if (!modifierPressed || event.altKey) return;
const key = event.key.toLowerCase();
if (key === "b" && !event.shiftKey) {
event.preventDefault();
wrapSelection({ prefix: "**", suffix: "**", placeholder: "bold text" });
return;
}
if (key === "i" && !event.shiftKey) {
event.preventDefault();
wrapSelection({ prefix: "*", suffix: "*", placeholder: "italic text" });
return;
}
if (key === "x" && event.shiftKey) {
event.preventDefault();
wrapSelection({ prefix: "~~", suffix: "~~", placeholder: "strikethrough text" });
return;
}
if (key === "h" && event.shiftKey) {
event.preventDefault();
prefixLines("## ");
return;
}
if (key === "f" && event.shiftKey) {
event.preventDefault();
formatBody();
return;
}
if (key === "k" && !event.shiftKey) {
event.preventDefault();
onLinkDialogChange(true);
return;
}
if (key === "e" && !event.shiftKey) {
event.preventDefault();
wrapSelection({ prefix: "`", suffix: "`", placeholder: "code" });
return;
}
const browserComboKeys = new Set(["b", "i", "e", "k", "h", "u"]);
if (browserComboKeys.has(key)) {
event.preventDefault();
}
}
const groups: readonly (readonly WikiEditorToolbarAction[])[] = [
[
{
label: "Bold",
shortcut: "Ctrl/Cmd+B",
icon: Bold,
onClick: () => wrapSelection({ prefix: "**", suffix: "**", placeholder: "bold text" }),
onClick: () => runCommand(markdownCommands.bold),
},
{
label: "Italic",
shortcut: "Ctrl/Cmd+I",
icon: Italic,
onClick: () => wrapSelection({ prefix: "*", suffix: "*", placeholder: "italic text" }),
onClick: () => runCommand(markdownCommands.italic),
},
{
label: "Strikethrough",
shortcut: "Ctrl/Cmd+Shift+X",
icon: Strikethrough,
onClick: () =>
wrapSelection({ prefix: "~~", suffix: "~~", placeholder: "strikethrough text" }),
onClick: () => runCommand(markdownCommands.strikethrough),
},
{
label: "Heading",
shortcut: "Ctrl/Cmd+Shift+H",
icon: Heading2,
onClick: () => prefixLines("## "),
onClick: () => runCommand(markdownCommands.heading),
},
{
label: "Format",
shortcut: "Ctrl/Cmd+Shift+F",
icon: Sparkles,
onClick: formatBody,
onClick: () => runCommand(markdownCommands.format),
},
],
[
@ -341,24 +170,27 @@ export function WikiEditorBody({
label: "Inline code",
shortcut: "Ctrl/Cmd+E",
icon: Code,
onClick: () => wrapSelection({ prefix: "`", suffix: "`", placeholder: "code" }),
onClick: () => runCommand(markdownCommands.inlineCode),
},
{
label: "Code block",
icon: FileCode2,
onClick: () =>
wrapSelection({ prefix: "```\n", suffix: "\n```", placeholder: "code block" }),
onClick: () => runCommand(markdownCommands.codeBlock),
},
{ label: "Quote", icon: Quote, onClick: () => prefixLines("> ") },
{ label: "Quote", icon: Quote, onClick: () => runCommand(markdownCommands.quote) },
],
[
{ label: "Bulleted list", icon: List, onClick: () => prefixLines("- ") },
{ label: "Numbered list", icon: ListOrdered, onClick: () => prefixLines("1. ") },
{
label: "Table",
icon: Table,
onClick: () => insertSnippet({ insertion: TABLE_SNIPPET, placeholder: "Header" }),
label: "Bulleted list",
icon: List,
onClick: () => runCommand(markdownCommands.bulletList),
},
{
label: "Numbered list",
icon: ListOrdered,
onClick: () => runCommand(markdownCommands.numberedList),
},
{ label: "Table", icon: Table, onClick: () => runCommand(markdownCommands.table) },
],
[
{
@ -370,37 +202,35 @@ export function WikiEditorBody({
{
label: "Captioned image",
icon: Image,
onClick: () => insertSnippet({ insertion: IMAGE_SNIPPET, placeholder: "Alt text" }),
onClick: () => runCommand(markdownCommands.captionedImage),
},
{
label: "Upload image",
icon: ImageUp,
onClick: () => fileInputRef.current?.click(),
},
{ label: "Footnote", icon: NotebookPen, onClick: () => insertReference("") },
{
label: "Footnote",
icon: NotebookPen,
onClick: () => runCommand(markdownCommands.footnote),
},
{
label: "Citation",
icon: NotebookPen,
onClick: () => insertReference('Author, "Title", <URL>'),
onClick: () => runCommand(markdownCommands.citation),
},
],
[
{
label: "Infobox",
icon: PanelRight,
onClick: () => insertSnippet({ insertion: INFOBOX_SNIPPET, placeholder: "Infobox title" }),
},
{ label: "Infobox", icon: PanelRight, onClick: () => runCommand(markdownCommands.infobox) },
{
label: "2 columns",
icon: Columns2,
onClick: () =>
insertSnippet({ insertion: TWO_COLUMN_SNIPPET, placeholder: "Left column content" }),
onClick: () => runCommand(markdownCommands.twoColumns),
},
{
label: "3 columns",
icon: Columns3,
onClick: () =>
insertSnippet({ insertion: THREE_COLUMN_SNIPPET, placeholder: "Left column content" }),
onClick: () => runCommand(markdownCommands.threeColumns),
},
{
label: "Template",
@ -439,25 +269,14 @@ export function WikiEditorBody({
templateHtmlMap={templateHtmlMap}
/>
<WikiEditorToolbar groups={groups} disabled={pending || uploading} />
<div className="relative min-h-[23.5rem] w-full rounded-md border border-input bg-transparent shadow-sm transition-[box-shadow] focus-within:border-ring focus-within:ring-1 focus-within:ring-ring lg:h-[calc(100vh-10rem)]">
<WikiEditorHighlightLayer body={body} ref={mirrorRef} />
<Textarea
ref={bodyRef}
id="wiki-body"
<div className="relative w-full rounded-md border border-input bg-transparent shadow-sm transition-[box-shadow] focus-within:border-ring focus-within:ring-1 focus-within:ring-ring">
<WikiMarkdownEditor
value={body}
onChange={handleBodyChange}
onScroll={(event) => syncMirrorScroll(event.currentTarget)}
onKeyDown={handleBodyKeyDown}
placeholder="Write the field guide entry in Markdown."
onChange={onBodyChange}
editorRef={editorRef}
onRequestWikilink={() => onLinkDialogChange(true)}
disabled={pending}
className={cn(
// Must stay identical to the overlay metrics (editorMetrics.ts), plus no
// scrollbar gutter: a reserved classic scrollbar (Firefox/Safari) would
// shrink the textarea's content width vs the overlay and re-introduce wrap drift.
WIKI_EDITOR_METRICS,
WIKI_EDITOR_SCROLLBAR_NONE,
"absolute inset-0 h-full w-full resize-none border-0 bg-transparent text-transparent caret-foreground shadow-none selection:bg-primary/30 focus-visible:outline-none focus-visible:ring-0",
)}
className="h-[23.5rem] lg:h-[calc(100vh-10rem)]"
/>
</div>
</div>

View file

@ -1,52 +0,0 @@
"use client";
import { forwardRef, useMemo, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { highlightMarkdownLines } from "@/lib/wiki/editorHighlight";
import { WIKI_EDITOR_METRICS } from "./editorMetrics";
interface WikiEditorHighlightLayerProps extends HTMLAttributes<HTMLDivElement> {
readonly body: string;
}
/**
* Colored text layer rendered underneath the editor textarea (which uses
* transparent text). Sizing must mirror the textarea exactly — identical
* metrics/padding (`WIKI_EDITOR_METRICS`) and NO border of its own: children
* of the editor wrapper are absolutely positioned, so `inset-0` already places
* them inside the wrapper border; an extra transparent border here would just
* shrink the overlay by 2px and desynchronize where long lines wrap.
*/
export const WikiEditorHighlightLayer = forwardRef<
HTMLDivElement,
WikiEditorHighlightLayerProps
>(function WikiEditorHighlightLayer({ body, className, ...rest }, ref) {
const lines = useMemo(() => highlightMarkdownLines(body), [body]);
const nodes: ReactNode[] = [];
lines.forEach((segments, lineIndex) => {
if (lineIndex > 0) nodes.push("\n");
segments.forEach((segment, segmentIndex) => {
if (segment.className) {
nodes.push(
<span key={`${lineIndex}-${segmentIndex}`} className={segment.className}>
{segment.text}
</span>,
);
} else {
nodes.push(segment.text);
}
});
});
return (
<div
ref={ref}
aria-hidden="true"
className={cn("pointer-events-none absolute inset-0 overflow-hidden", className)}
{...rest}
>
<div className={cn(WIKI_EDITOR_METRICS, "whitespace-pre-wrap break-words text-foreground/90")}>
{nodes}
</div>
</div>
);
});

View file

@ -0,0 +1,250 @@
"use client";
import { useEffect, useImperativeHandle, useRef, type RefObject } from "react";
import { Compartment, EditorState, Transaction } from "@codemirror/state";
import { EditorView, drawSelection, keymap, placeholder as cmPlaceholder } from "@codemirror/view";
import { defaultKeymap, history, historyKeymap, redo as redoCommand } from "@codemirror/commands";
import { markdown } from "@codemirror/lang-markdown";
import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
import { tags } from "@lezer/highlight";
import { cn } from "@/lib/utils";
import { minimalEditorChange } from "@/lib/wiki/editorChange";
import type { BodySelection, BodyUpdate } from "@/lib/wiki/editorFormatting";
import { markdownCommands, type MarkdownCommand } from "./markdownCommands";
export interface WikiMarkdownEditorHandle {
focus: () => void;
getValue: () => string;
getSelection: () => BodySelection;
applyUpdate: (update: BodyUpdate) => void;
}
interface WikiMarkdownEditorProps {
readonly value: string;
readonly onChange: (value: string) => void;
readonly editorRef: RefObject<WikiMarkdownEditorHandle | null>;
/** Called by Cmd/Ctrl+K; the dialog itself lives in WikiEditorBody. */
readonly onRequestWikilink: () => void;
readonly disabled?: boolean;
readonly placeholder?: string;
readonly className?: string;
}
const PTF_EDITOR_THEME = EditorView.theme(
{
"&": {
height: "100%",
backgroundColor: "transparent",
color: "var(--color-foreground)",
fontSize: "0.875rem",
},
"&.cm-focused": { outline: "none" },
".cm-scroller": {
fontFamily: "var(--font-mono), ui-monospace, SFMono-Regular, Menlo, monospace",
lineHeight: "1.5",
overflow: "auto",
},
".cm-content": {
padding: "0.5rem 0.75rem",
caretColor: "var(--color-foreground)",
},
".cm-line": { padding: "0" },
".cm-cursor, .cm-dropCursor": { borderLeftColor: "var(--color-foreground)" },
".cm-selectionBackground, .cm-content ::selection": {
backgroundColor: "color-mix(in oklab, var(--color-primary) 30%, transparent)",
},
"&.cm-focused .cm-selectionBackground": {
backgroundColor: "color-mix(in oklab, var(--color-primary) 38%, transparent)",
},
".cm-placeholder": { color: "var(--color-muted-foreground)" },
".cm-tooltip": {
backgroundColor: "var(--color-background)",
border: "1px solid var(--color-border)",
},
},
{ dark: true },
);
/**
* Markdown syntax colors. Mirrors the palette the old overlay painted, but
* these are real editor decorations bound to the app's CSS tokens instead of a
* second copy of the document.
*/
const PTF_HIGHLIGHT_STYLE = HighlightStyle.define([
{ tag: tags.heading1, color: "var(--color-foreground)", fontWeight: "700", fontSize: "1.15em" },
{ tag: tags.heading2, color: "var(--color-foreground)", fontWeight: "700", fontSize: "1.08em" },
{
tag: [tags.heading3, tags.heading4, tags.heading5, tags.heading6],
color: "var(--color-foreground)",
fontWeight: "700",
},
{ tag: tags.strong, color: "var(--color-foreground)", fontWeight: "700" },
{ tag: tags.emphasis, fontStyle: "italic" },
{
tag: tags.strikethrough,
color: "var(--color-muted-foreground)",
textDecoration: "line-through",
},
{
tag: tags.monospace,
color: "var(--color-foreground)",
backgroundColor: "color-mix(in oklab, var(--color-muted) 55%, transparent)",
},
{ tag: tags.link, color: "var(--color-primary)", textDecoration: "underline" },
{ tag: tags.url, color: "var(--color-muted-foreground)" },
{ tag: tags.list, color: "var(--color-muted-foreground)" },
{ tag: tags.quote, color: "var(--color-muted-foreground)", fontStyle: "italic" },
{
tag: [tags.processingInstruction, tags.contentSeparator, tags.meta],
color: "var(--color-muted-foreground)",
},
]);
function selectionOf(view: EditorView): BodySelection {
const { from, to } = view.state.selection.main;
return { start: from, end: to, text: view.state.doc.sliceString(from, to) };
}
function dispatchUpdate(view: EditorView, update: BodyUpdate): void {
const change = minimalEditorChange(view.state.doc.toString(), update.value);
view.dispatch({
changes: change,
selection: { anchor: update.selectionStart, head: update.selectionEnd },
scrollIntoView: true,
userEvent: "input.markdown-command",
});
}
export function WikiMarkdownEditor({
value,
onChange,
editorRef,
onRequestWikilink,
disabled = false,
placeholder = "Write the field guide entry in Markdown.",
className,
}: WikiMarkdownEditorProps) {
const hostRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<EditorView | null>(null);
const onChangeRef = useRef(onChange);
const onRequestWikilinkRef = useRef(onRequestWikilink);
const valueRef = useRef(value);
const editableCompartment = useRef(new Compartment());
onChangeRef.current = onChange;
onRequestWikilinkRef.current = onRequestWikilink;
valueRef.current = value;
useEffect(() => {
const host = hostRef.current;
if (!host) return;
const runCommand =
(command: MarkdownCommand) =>
(view: EditorView): boolean => {
const update = command(view.state.doc.toString(), selectionOf(view));
if (!update) return false;
dispatchUpdate(view, update);
return true;
};
const editorKeymap = keymap.of([
// Our bindings sit before the defaults so they win over browser-ish defaults.
{ key: "Mod-b", run: runCommand(markdownCommands.bold) },
{ key: "Mod-i", run: runCommand(markdownCommands.italic) },
{ key: "Mod-e", run: runCommand(markdownCommands.inlineCode) },
{ key: "Mod-Shift-x", run: runCommand(markdownCommands.strikethrough) },
{ key: "Mod-Shift-h", run: runCommand(markdownCommands.heading) },
{ key: "Mod-Shift-f", run: runCommand(markdownCommands.format) },
{ key: "Tab", run: runCommand(markdownCommands.indent) },
{ key: "Shift-Tab", run: runCommand(markdownCommands.outdent) },
{ key: "Enter", run: runCommand(markdownCommands.listContinue) },
{ key: "Mod-y", run: redoCommand },
{
key: "Mod-k",
run: () => {
onRequestWikilinkRef.current();
return true;
},
},
]);
const view = new EditorView({
parent: host,
state: EditorState.create({
doc: value,
extensions: [
editorKeymap,
history(),
drawSelection(),
EditorView.lineWrapping,
markdown(),
syntaxHighlighting(PTF_HIGHLIGHT_STYLE),
PTF_EDITOR_THEME,
cmPlaceholder(placeholder),
editableCompartment.current.of(EditorView.editable.of(!disabled)),
EditorView.contentAttributes.of({
id: "wiki-body",
"aria-label": "Body",
role: "textbox",
"aria-multiline": "true",
spellcheck: "false",
autocorrect: "off",
autocapitalize: "off",
}),
EditorView.updateListener.of((update) => {
if (update.docChanged) onChangeRef.current(update.state.doc.toString());
}),
keymap.of([...defaultKeymap, ...historyKeymap]),
],
}),
});
viewRef.current = view;
return () => {
view.destroy();
viewRef.current = null;
};
// The view is created once; live props flow through refs and effects below.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const view = viewRef.current;
if (!view) return;
if (view.state.doc.toString() === value) return;
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: value },
annotations: Transaction.addToHistory.of(false),
});
}, [value]);
useEffect(() => {
const view = viewRef.current;
if (!view) return;
view.dispatch({
effects: editableCompartment.current.reconfigure(EditorView.editable.of(!disabled)),
});
}, [disabled]);
useImperativeHandle(
editorRef,
() => ({
focus: () => viewRef.current?.focus(),
getValue: () => viewRef.current?.state.doc.toString() ?? valueRef.current,
getSelection: () =>
viewRef.current ? selectionOf(viewRef.current) : { start: 0, end: 0, text: "" },
applyUpdate: (update: BodyUpdate) => {
const view = viewRef.current;
if (!view) return;
dispatchUpdate(view, update);
view.focus();
},
}),
// Methods only read refs, so one handle instance is enough.
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
return <div ref={hostRef} className={cn("h-full w-full", className)} />;
}

View file

@ -1,25 +0,0 @@
/**
* Typography + box-model classes that MUST stay identical between the editor
* textarea and the painted highlight overlay underneath it.
*
* The overlay is positioned `absolute inset-0` over the textarea and paints the
* visible text while the textarea keeps `text-transparent`. If the two layers
* ever differ in font size, line height, padding or available content width,
* soft-wrapped lines break at different columns; every difference shifts the
* overlay text vertically against the caret/click geometry of the textarea
* below it. Inserting an image markdown token (`![alt](/media/...png)`, one
* giant unbreakable word) maximizes wrap-point sensitivity, which is why the
* drift becomes obvious right after an upload. Both components import these
* classes from here instead of duplicating them; keep new shared metrics here,
* not inline in either component (see tests/int/wiki-editor-metrics.int.spec.ts).
*/
export const WIKI_EDITOR_METRICS = "px-3 py-2 font-mono text-sm";
/**
* Classic scrollbars (Firefox, Safari, non-overlay Chrome) reserve layout width
* inside the scrolling textarea, shrinking its content width relative to the
* overflow-hidden overlay. Hiding the scrollbar keeps both boxes exactly the
* same width everywhere; wheel/keyboard scrolling and the existing
* caret-into-view logic still work without a draggable thumb.
*/
export const WIKI_EDITOR_SCROLLBAR_NONE = "[scrollbar-width:none] [&::-webkit-scrollbar]:hidden";

View file

@ -0,0 +1,68 @@
import {
IMAGE_SNIPPET,
INFOBOX_SNIPPET,
TABLE_SNIPPET,
THREE_COLUMN_SNIPPET,
TWO_COLUMN_SNIPPET,
createFormatUpdate,
createIndentUpdate,
createLinePrefixUpdate,
createListContinueUpdate,
createReferenceUpdate,
createSnippetUpdate,
createWrappedUpdate,
type BodySelection,
type BodyUpdate,
} from "@/lib/wiki/editorFormatting";
/**
* Pure markdown editing commands shared by the wiki toolbar and the editor
* keymap. Each takes the current document plus selection and returns the
* resulting document plus where the selection should land, or null when the
* command does not apply (for example Enter outside a list item).
*
* Keeping these independent of CodeMirror means the same functions back the
* toolbar buttons, the keyboard shortcuts and the unit tests.
*/
export type MarkdownCommand = (body: string, selection: BodySelection) => BodyUpdate | null;
function wrap(prefix: string, suffix: string, placeholder: string): MarkdownCommand {
return (body, selection) => createWrappedUpdate(body, selection, { prefix, suffix, placeholder });
}
function prefixLines(prefix: string): MarkdownCommand {
return (body, selection) => createLinePrefixUpdate(body, selection, prefix);
}
function snippet(insertion: string, placeholder?: string): MarkdownCommand {
return (body, selection) => createSnippetUpdate(body, selection, { insertion, placeholder });
}
function reference(definitionSuffix: string): MarkdownCommand {
return (body, selection) => createReferenceUpdate(body, selection, { definitionSuffix });
}
export const markdownCommands = {
bold: wrap("**", "**", "bold text"),
italic: wrap("*", "*", "italic text"),
strikethrough: wrap("~~", "~~", "strikethrough text"),
inlineCode: wrap("`", "`", "code"),
codeBlock: wrap("```\n", "\n```", "code block"),
heading: prefixLines("## "),
bulletList: prefixLines("- "),
numberedList: prefixLines("1. "),
quote: prefixLines("> "),
format: (body, selection) => createFormatUpdate(body, selection),
indent: (body, selection) => createIndentUpdate(body, selection, false),
outdent: (body, selection) => createIndentUpdate(body, selection, true),
listContinue: createListContinueUpdate,
table: snippet(TABLE_SNIPPET, "Header"),
captionedImage: snippet(IMAGE_SNIPPET, "Alt text"),
infobox: snippet(INFOBOX_SNIPPET, "Infobox title"),
twoColumns: snippet(TWO_COLUMN_SNIPPET, "Left column content"),
threeColumns: snippet(THREE_COLUMN_SNIPPET, "Left column content"),
footnote: reference(""),
citation: reference('Author, "Title", <URL>'),
} satisfies Record<string, MarkdownCommand>;
export type MarkdownCommandName = keyof typeof markdownCommands;

View file

@ -1,91 +0,0 @@
"use client";
import { type RefObject, useCallback, useEffect, useRef } from "react";
export interface HistoryEntry {
readonly value: string;
readonly selectionStart: number;
readonly selectionEnd: number;
}
const COALESCE_WINDOW_MS = 400;
const COALESCE_MAX_DELTA = 8;
const MAX_HISTORY = 200;
function countLines(value: string): number {
let lines = 1;
for (let i = 0; i < value.length; i += 1) {
if (value.charCodeAt(i) === 10) lines += 1;
}
return lines;
}
export function useEditorHistory(
body: string,
bodyRef: RefObject<HTMLTextAreaElement | null>,
) {
const stackRef = useRef<HistoryEntry[]>([]);
const indexRef = useRef(-1);
const lastRecordAtRef = useRef(0);
if (stackRef.current.length === 0) {
stackRef.current = [{ value: body, selectionStart: 0, selectionEnd: 0 }];
indexRef.current = 0;
}
useEffect(() => {
const top = stackRef.current[indexRef.current];
if (top && top.value === body) return;
stackRef.current = [
{
value: body,
selectionStart: bodyRef.current?.selectionStart ?? 0,
selectionEnd: bodyRef.current?.selectionEnd ?? 0,
},
];
indexRef.current = 0;
lastRecordAtRef.current = 0;
}, [body, bodyRef]);
const record = useCallback(
(value: string, selectionStart: number, selectionEnd: number, coalesce: boolean) => {
const stack = stackRef.current;
const top = stack[indexRef.current];
const now = Date.now();
const canCoalesce =
coalesce &&
top !== undefined &&
now - lastRecordAtRef.current <= COALESCE_WINDOW_MS &&
Math.abs(value.length - top.value.length) <= COALESCE_MAX_DELTA &&
countLines(value) === countLines(top.value);
if (canCoalesce && top) {
stack[indexRef.current] = { value, selectionStart, selectionEnd };
} else {
stack.length = indexRef.current + 1;
stack.push({ value, selectionStart, selectionEnd });
if (stack.length > MAX_HISTORY) stack.shift();
indexRef.current = stack.length - 1;
}
lastRecordAtRef.current = now;
},
[],
);
const undo = useCallback((): HistoryEntry | null => {
if (indexRef.current <= 0) return null;
indexRef.current -= 1;
lastRecordAtRef.current = 0;
return stackRef.current[indexRef.current];
}, []);
const redo = useCallback((): HistoryEntry | null => {
const stack = stackRef.current;
if (indexRef.current >= stack.length - 1) return null;
indexRef.current += 1;
lastRecordAtRef.current = 0;
return stack[indexRef.current];
}, []);
return { record, undo, redo };
}

View file

@ -19,7 +19,7 @@
- `service.ts`: `createPage`/`updatePage`/`restoreRevision`/`setPageLockdown`/`deletePage`/`listTemplates`/`templateMap`. All mutations run with `overrideAccess: true`; `updatePage`/`restoreRevision` throw `"This page is locked and cannot be edited."` when `lockdown` is set; `deletePage` cascades the page's revisions; slug collisions get a `-2`, `-3`, ... suffix; revision numbers are `max + 1`. Does NOT emit events (the actions layer does).
- **Server actions**: `src/app/(frontend)/wiki/actions.ts`. `createWikiPage`, `updateWikiPage`, `restoreWikiRevision` (moderator), `setPageLockdown` (moderator), `deleteWikiPage` (moderator). Canonical repo pattern (duplicated `authenticate()`, `ActionResult<T>`, `emitGameEvent` after mutation). Moderator = `hasIntelligenceQualification(payload, user)` (intel division members + admin/developer pass). Emits `wiki:page-create` / `wiki:page-edit` / `wiki:page-restore` / `wiki:page-lock` / `wiki:page-unlock` / `wiki:page-delete`.
- **Markdown rendering**: `react-markdown@10.1.0` + `remark-gfm@4.0.1` (GFM provides footnotes natively: `[^1]` marker + `[^1]:` definition) + `remark-directive@4.0.0` (layout/callout directives). The shared pipeline lives in `src/lib/wiki/markdown.tsx` (client-safe, no Payload imports): exports `wikiRemarkPlugins` (= `[remarkGfm, remarkDirective]`), `wikiRemarkRehypeOptions` (handlers mapping containerDirective/leafDirective → div and textDirective → span), `wikiMarkdownComponents`, and re-exports `ReactMarkdown`. Wired into both the server component `WikiContent` and the editor's live preview. No raw HTML (no rehype-raw). Images are URL-only `<img>` (no upload support yet). Captioned images `![alt text](url "Caption on hover")` render the caption as a hover `title` only, no figure/figcaption (deliberate: a figure inside a `<p>` is invalid HTML and would cause a hydration mismatch). Two/three-column layout via `::::columns` / `:::column` / `::::` fences, the closing fence must use the same or more colons. `:::note` and `:::warning` callouts render as styled divs. Wikilinks `[[Page]]`/`[[Page|label]]` and `{{Template}}` expansion still run through `prepareMarkdown` before rendering.
- **Editor**: `WikiEditor` (`src/components/frontend/wiki/WikiEditor.tsx`): title/category/tags/edit-summary fields plus a markdown body with live preview (`prepareMarkdown` → react-markdown via the shared pipeline) and an "Insert wikilink" dialog (`WikiLinkDialog`, picks from existing pages at the cursor). The body (`WikiEditorBody.tsx`) sits under a formatting toolbar (`WikiEditorToolbar.tsx`): bold / italic / strikethrough / heading / inline code / code block / quote / bulleted list / numbered list / table, plus insert actions for wikilink, footnote, captioned image, 2-column, 3-column, and citation. Selection helpers live in `src/lib/wiki/editorFormatting.ts`. Keyboard shortcuts: Ctrl/Cmd+B bold, Ctrl/Cmd+I italic, Ctrl/Cmd+Shift+X strikethrough, Ctrl/Cmd+Shift+H heading, Ctrl/Cmd+K insert wikilink, Ctrl/Cmd+E inline code. An in-editor Markdown reference guide (`MarkdownGuide.tsx`) sits next to the live preview.
- **Editor**: `WikiEditor` (`src/components/frontend/wiki/WikiEditor.tsx`): title/category/tags/edit-summary fields plus a markdown body with live preview (`prepareMarkdown` → react-markdown via the shared pipeline) and an "Insert wikilink" dialog (`WikiLinkDialog`, picks from existing pages at the cursor). The body (`WikiEditorBody.tsx`) is a CodeMirror 6 markdown editor (`WikiMarkdownEditor.tsx`, `@codemirror/*`, no React wrapper) sitting under a formatting toolbar (`WikiEditorToolbar.tsx`): bold / italic / strikethrough / heading / inline code / code block / quote / bulleted list / numbered list / table, plus insert actions for wikilink, footnote, captioned image, columns, infobox and citation. Toolbar buttons and the editor keymap share the pure commands in `markdownCommands.ts`, which wrap the selection helpers in `src/lib/wiki/editorFormatting.ts`; only the differing span is dispatched (`editorChange.ts`) so CodeMirror history stays granular. Keyboard shortcuts (CM keymap, not React handlers): Ctrl/Cmd+B bold, Ctrl/Cmd+I italic, Ctrl/Cmd+Shift+X strikethrough, Ctrl/Cmd+Shift+H heading, Ctrl/Cmd+K insert wikilink, Ctrl/Cmd+E inline code, Tab/Shift+Tab indent. Deliberate architecture: the caret and the painted text are the same editor, so do not reintroduce a transparent-textarea-plus-highlight-overlay (it drifts by line once content soft-wraps; see `src/components/frontend/AGENTS.md`). An in-editor Markdown reference guide (`MarkdownGuide.tsx`) sits next to the live preview.
- **UI**: `src/app/(frontend)/wiki/`: `/wiki` index (`WikiIndex`: search, tag filter, category tabs, "New page"), `/wiki/new`, `/wiki/[slug]` (detail: `WikiContent` render + `WikiToolbar` with Edit/History/Lock/Delete; `LockdownBanner` when locked; missing pages show a "Create this page" CTA that prefills `?title=`), `/wiki/[slug]/edit` (redirects to `/wiki/new?title=` for missing pages, shows `LockdownBanner` when locked), `/wiki/[slug]/history` (`RevisionList` with type badges and moderator-only Restore). Tests: `tests/int/wiki.int.spec.ts`.
- **Entry surfaces**: the index shows a moderator-curated "Start here" featured strip above the toolbar: `curation.featured` + `curation.featuredOrder` group fields on wiki-pages (field access create/update = `hasIntelligenceQualification`, so plain users cannot self-feature; admin-panel only). `selectFeatured` (`src/lib/wiki/indexView.ts`) orders explicit picks first then newest, capped at `FEATURED_CAP` (6); the strip hides while any filter is active. The starter guide (`documentation/welcome-to-the-unit.md`, slug `welcome-to-the-unit`) is kept featured at position 1 by `seedDocumentation.ts`. Category portals at `/wiki/category/[category]` (server component, `notFound()` for unknown categories) render the `CATEGORY_META` blurb (`src/lib/wiki/categories.ts`), a tag cloud deep-linking `/wiki?category=X&tag=Y`, and rows via the shared `WikiRow` (tags as filter links when `tagLinkBase` is passed, toggle buttons otherwise). Both index and portal map documents through `mapWikiPageToEntry` (excerpt + System editor fallback + curation flags). Gotcha: the index URL-sync effect must key only off local filter state (pathname/searchParams via refs); re-running it on `useSearchParams` identity churn during a client navigation fires a debounced `router.replace` that aborts in-flight navigations to cold-compiled routes.
- **Event targets**: `wiki-pages`, `wiki-revisions`, `wiki-templates` added to `GameEventLogs` `TARGET_COLLECTIONS` and `emit.ts` `targetCollection` union. Wiki event types in `eventTypes.ts`.

View file

@ -0,0 +1,33 @@
import type { BodyUpdate } from "@/lib/wiki/editorFormatting";
export interface EditorTextChange {
readonly from: number;
readonly to: number;
readonly insert: string;
}
/**
* Smallest contiguous replacement that turns `previous` into `next`, found by
* trimming the shared prefix and suffix.
*
* The wiki toolbar computes its results as whole-document strings. Dispatching
* only the differing span (instead of replacing the document) keeps CodeMirror
* history granular, preserves the user's selection outside the edited span and
* avoids churning the whole view on every toolbar click.
*/
export function minimalEditorChange(previous: string, next: string): EditorTextChange {
if (previous === next) return { from: 0, to: 0, insert: "" };
const maxPrefix = Math.min(previous.length, next.length);
let from = 0;
while (from < maxPrefix && previous[from] === next[from]) from += 1;
let previousEnd = previous.length;
let nextEnd = next.length;
while (previousEnd > from && nextEnd > from && previous[previousEnd - 1] === next[nextEnd - 1]) {
previousEnd -= 1;
nextEnd -= 1;
}
return { from, to: previousEnd, insert: next.slice(from, nextEnd) };
}

View file

@ -1,4 +1,3 @@
import type { RefObject } from "react";
import { formatMarkdown } from "@/lib/wiki/formatMarkdown";
export interface BodySelection {
@ -68,15 +67,6 @@ export const INFOBOX_SNIPPET = `::::infobox
| Field 3 | Value 3 |
::::`;
export function readBodySelection(
body: string,
bodyRef: RefObject<HTMLTextAreaElement | null>,
): BodySelection {
const start = bodyRef.current?.selectionStart ?? body.length;
const end = bodyRef.current?.selectionEnd ?? body.length;
return { start, end, text: body.slice(start, end) };
}
export function createWrappedUpdate(
body: string,
selection: BodySelection,
@ -205,8 +195,7 @@ export function createIndentUpdate(
};
}
const LIST_ITEM_RE =
/^(\s*)(?:([-*+])|(\d+)([.)]))[ \t]+(\[[ xX]\][ \t]+)?(.*)$/;
const LIST_ITEM_RE = /^(\s*)(?:([-*+])|(\d+)([.)]))[ \t]+(\[[ xX]\][ \t]+)?(.*)$/;
const FENCE_LINE_RE = /^\s{0,3}(?:```|~~~)/;
export function createListContinueUpdate(

View file

@ -1,109 +0,0 @@
/**
* Lightweight markdown tokenizer for the editor highlight mirror.
*
* Pure module — safe to import client-side. Splits the source into lines and
* returns, per line, segments tagged with a Tailwind class for the mirror
* layer behind the editor textarea. Not a full parser: fence state is tracked
* across lines, everything else is line-local.
*/
export interface HighlightSegment {
readonly text: string;
readonly className?: string;
}
const HL = {
heading: "font-semibold text-sky-200",
bold: "font-semibold text-foreground",
italic: "italic text-foreground",
strike: "line-through text-muted-foreground/70",
code: "rounded bg-muted px-0.5 text-emerald-300",
wikilink: "text-sky-300 underline underline-offset-2",
link: "text-sky-300 underline underline-offset-2",
quote: "italic text-muted-foreground/80",
directive: "text-violet-300",
fence: "text-muted-foreground/60",
codeBlock: "text-emerald-300/50",
listMarker: "text-amber-300",
} as const;
const INLINE_RE =
/(`[^`\n]+`)|(\*\*[^*\n]+\*\*)|(__[^_\n]+__)|(~~[^~\n]+~~)|(\*[^*\n]+\*)|((?<![A-Za-z0-9])_[^_\n]+_(?![A-Za-z0-9]))|(\[\[[^\]\n]+\]\])|(\[[^\]\n]*\]\([^)\n]+\))/g;
const INLINE_CLASSES = [
HL.code,
HL.bold,
HL.bold,
HL.strike,
HL.italic,
HL.italic,
HL.wikilink,
HL.link,
] as const;
function tokenizeInline(text: string): HighlightSegment[] {
const segments: HighlightSegment[] = [];
let cursor = 0;
for (const match of text.matchAll(INLINE_RE)) {
const start = match.index ?? 0;
if (start > cursor) segments.push({ text: text.slice(cursor, start) });
const groupIndex =
match.findIndex((capture, index) => index > 0 && capture !== undefined) - 1;
segments.push({ text: match[0], className: INLINE_CLASSES[groupIndex] });
cursor = start + match[0].length;
}
if (cursor < text.length) {
segments.push({ text: text.slice(cursor) });
}
return segments;
}
const FENCE_RE = /^\s{0,3}(```|~~~)/;
const HEADING_RE = /^\s{0,3}#{1,6}\s/;
const QUOTE_RE = /^\s{0,3}>/;
const DIRECTIVE_RE = /^\s{0,3}:::/;
const HRULE_RE = /^\s{0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/;
const LIST_MARKER_RE = /^(\s*)([-*+]|\d+[.)])(\s+)/;
export function highlightMarkdownLines(source: string): HighlightSegment[][] {
const lines: HighlightSegment[][] = [];
let inFence = false;
for (const line of source.split("\n")) {
if (FENCE_RE.test(line)) {
lines.push([{ text: line, className: HL.fence }]);
inFence = !inFence;
continue;
}
if (inFence) {
lines.push([{ text: line, className: HL.codeBlock }]);
continue;
}
if (HEADING_RE.test(line)) {
lines.push([{ text: line, className: HL.heading }]);
continue;
}
if (QUOTE_RE.test(line)) {
lines.push([{ text: line, className: HL.quote }]);
continue;
}
if (DIRECTIVE_RE.test(line)) {
lines.push([{ text: line, className: HL.directive }]);
continue;
}
if (HRULE_RE.test(line)) {
lines.push([{ text: line, className: HL.fence }]);
continue;
}
const listMatch = line.match(LIST_MARKER_RE);
if (listMatch) {
const markerEnd = listMatch[0].length;
lines.push([
{ text: listMatch[0], className: HL.listMarker },
...tokenizeInline(line.slice(markerEnd)),
]);
continue;
}
lines.push(tokenizeInline(line));
}
return lines;
}

View file

@ -0,0 +1,176 @@
import { expect, test, type Page } from "@playwright/test";
/**
* Regression guard for the wiki body editor's caret geometry.
*
* The previous implementation painted the text in an overlay <div> while a
* transparent <textarea> owned the caret, so any wrap-point difference between
* the two layers put the caret on the wrong line as soon as lines soft-wrapped
* (and it was worst right after an image markdown token was inserted). These
* tests click a real glyph and assert the typed character lands at that exact
* document offset, which is only true when the editor owns both the text and
* the caret.
*/
const SAMPLE = [
"Introduction paragraph with enough words to wrap across the editor column at least twice so a click can target a continuation line inside it.",
"",
"Second paragraph with its own wrapping behaviour and a distinctive platypus.",
"",
"- list item one with a few words",
"- list item two with a few words",
"- list item three with a few words",
"",
"![Diagram of the outpost](/media/uploads/20261118_outpost_diagram_generated_name.png)",
"",
].join("\n");
async function login(page: Page) {
await page.goto("/login");
await page.getByLabel("Username").fill("dev");
await page.getByLabel("Password").fill("Test123");
await page.getByRole("button", { name: "Log in" }).click();
await page.waitForURL((url) => !url.pathname.startsWith("/login"), { timeout: 30_000 });
}
/** Document text as CodeMirror currently holds it (lines joined with newlines). */
async function readDoc(page: Page): Promise<string> {
return page.evaluate(() =>
Array.from(document.querySelectorAll(".cm-content .cm-line"))
.map((line) => line.textContent ?? "")
.join("\n"),
);
}
/**
* Screen centre of a character (plus its document offset), located through the
* rendered DOM, exactly like a human clicking that glyph would.
*/
async function locateCharacter(
page: Page,
needle: string,
offsetInNeedle: number,
): Promise<{ x: number; y: number; index: number }> {
const target = await page.evaluate(
({ needle: text, offsetInNeedle: offset }) => {
const lines = Array.from(document.querySelectorAll(".cm-content .cm-line"));
const joined = lines.map((line) => line.textContent ?? "").join("\n");
const index = joined.indexOf(text);
if (index < 0) throw new Error(`"${text}" not found in document`);
const absolute = index + offset;
// Map the absolute document offset onto (line, offset inside line).
let remaining = absolute;
for (const line of lines) {
const content = line.textContent ?? "";
if (remaining <= content.length) {
// Walk the line's text nodes (syntax highlighting splits them).
const walker = document.createTreeWalker(line, NodeFilter.SHOW_TEXT);
let seen = 0;
let node = walker.nextNode() as Text | null;
while (node) {
const length = node.textContent?.length ?? 0;
if (remaining <= seen + length) {
const local = Math.min(remaining - seen, Math.max(length - 1, 0));
const range = document.createRange();
range.setStart(node, local);
range.setEnd(node, Math.min(local + 1, length));
const rect = range.getBoundingClientRect();
return {
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2,
index: absolute,
};
}
seen += length;
node = walker.nextNode() as Text | null;
}
const fallback = line.getBoundingClientRect();
return { x: fallback.left + 4, y: fallback.top + 8, index: absolute };
}
remaining -= content.length + 1; // + newline separator
}
throw new Error("offset outside document");
},
{ needle, offsetInNeedle },
);
const clipped = await page.evaluate(
({ x, y }) => ({ x, y, width: window.innerWidth, height: window.innerHeight }),
{ x: target.x, y: target.y },
);
expect(clipped.x).toBeGreaterThan(0);
expect(clipped.y).toBeGreaterThan(0);
return target;
}
async function clickAndMark(page: Page, needle: string, offset: number, marker: string) {
const spot = await locateCharacter(page, needle, offset);
await page.mouse.click(spot.x, spot.y);
await page.keyboard.type(marker);
const doc = await readDoc(page);
const markerIndex = doc.indexOf(marker);
expect(
markerIndex,
`marker ${marker} landed at ${markerIndex}, clicked offset was ${spot.index}`,
).toBe(spot.index);
return doc;
}
test.describe("wiki editor caret geometry", () => {
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => {
window.localStorage.setItem("ptf:wiki-standards-accepted", "1");
});
await login(page);
});
test("clicks land on the glyph under the pointer across wrapped lines, lists and long tokens", async ({
page,
}) => {
await page.goto("/wiki/new");
const editor = page.locator(".cm-content");
await expect(editor).toBeVisible({ timeout: 60_000 });
await editor.click();
await page.keyboard.insertText(SAMPLE);
await expect(page.locator(".cm-content .cm-line").first()).toContainText("Introduction");
// 1. A glyph on a soft-wrapped continuation line of the first paragraph.
await clickAndMark(page, "editor column", 2, "ZQ1");
// 2. A glyph inside the second list item (line-based structure).
await clickAndMark(page, "item two", 4, "ZQ2");
// 3. A glyph inside the image markdown URL token.
await clickAndMark(page, "outpost_diagram", 3, "ZQ3");
// 4. The end of the document must be reachable and editable.
await page.locator(".cm-content").click();
await page.keyboard.press("Control+End");
await page.keyboard.type("ENDMARK");
const finalDoc = await readDoc(page);
expect(finalDoc.trimEnd().endsWith("ENDMARK")).toBe(true);
});
test("clicks stay aligned after scrolling a long document", async ({ page }) => {
await page.goto("/wiki/new");
const editor = page.locator(".cm-content");
await expect(editor).toBeVisible({ timeout: 60_000 });
const long = Array.from(
{ length: 60 },
(_, i) => `Paragraph ${i + 1} with wrapping words ${"and more ".repeat(6)}`,
).join("\n\n");
await editor.click();
await page.keyboard.insertText(long);
await page.locator(".cm-scroller").evaluate((el) => {
el.scrollTop = el.scrollHeight;
});
await page.waitForTimeout(250);
const lastParagraph = "Paragraph 60 with wrapping words";
await clickAndMark(page, lastParagraph, 12, "ZQ4");
});
});

View file

@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import { minimalEditorChange } from "@/lib/wiki/editorChange";
function apply(previous: string, change: ReturnType<typeof minimalEditorChange>): string {
return previous.slice(0, change.from) + change.insert + previous.slice(change.to);
}
describe("minimalEditorChange", () => {
it("returns a no-op change for identical documents", () => {
expect(minimalEditorChange("same", "same")).toEqual({ from: 0, to: 0, insert: "" });
});
it("only touches the appended tail", () => {
const change = minimalEditorChange("alpha", "alpha beta");
expect(change).toEqual({ from: 5, to: 5, insert: " beta" });
expect(apply("alpha", change)).toBe("alpha beta");
});
it("only touches the prepended head", () => {
const change = minimalEditorChange("world", "hello world");
expect(change.from).toBe(0);
expect(apply("world", change)).toBe("hello world");
});
it("replaces just the differing middle span", () => {
const previous = "line one\nline two\nline three";
const next = "line one\nline TWO\nline three";
const change = minimalEditorChange(previous, next);
expect(change).toEqual({ from: 14, to: 17, insert: "TWO" });
expect(apply(previous, change)).toBe(next);
});
it("handles full replacement and emptying", () => {
expect(apply("abc", minimalEditorChange("abc", ""))).toBe("");
expect(apply("", minimalEditorChange("", "abc"))).toBe("abc");
expect(apply("abc", minimalEditorChange("abc", "xyz"))).toBe("xyz");
});
it("keeps multi-byte characters intact", () => {
const previous = "café ☕ planned";
const next = "café ☕ shipped";
expect(apply(previous, minimalEditorChange(previous, next))).toBe(next);
});
it("round-trips a wrapping edit without touching surrounding text", () => {
const body = "some **bold** words here";
const update = "some ****bold**** words here";
const change = minimalEditorChange(body, update);
expect(change.from).toBe(7);
expect(change.insert.startsWith("**")).toBe(true);
expect(apply(body, change)).toBe(update);
});
});

View file

@ -1,79 +0,0 @@
// @vitest-environment jsdom
import { createElement, createRef } from "react";
import { cleanup, render } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { WikiEditorBody } from "@/components/frontend/wiki/WikiEditorBody";
import { WIKI_EDITOR_METRICS, WIKI_EDITOR_SCROLLBAR_NONE } from "@/components/frontend/wiki/editorMetrics";
vi.mock("@/app/(frontend)/wiki/actions", () => ({
uploadWikiImage: vi.fn(),
}));
afterEach(cleanup);
function tokens(className: string | null): Set<string> {
return new Set((className ?? "").trim().split(/\s+/).filter(Boolean));
}
describe("wiki editor overlay/textarea parity", () => {
const body = "# Heading\n\nSome long line ".repeat(10);
function renderEditor() {
const ref = createRef<HTMLTextAreaElement>();
const { container } = render(
createElement(WikiEditorBody, {
body,
bodyRef: ref,
existingPages: [],
linkDialogOpen: false,
onBodyChange: () => {},
onLinkDialogChange: () => {},
pending: false,
templates: {},
}),
);
const textarea = container.querySelector("textarea#wiki-body");
const overlayInner = container.querySelector("div.pointer-events-none > div");
return { textarea, overlayInner };
}
it("renders both layers", () => {
const { textarea, overlayInner } = renderEditor();
expect(textarea).not.toBeNull();
expect(overlayInner).not.toBeNull();
});
it("shares identical padding/typography classes between textarea and overlay", () => {
const { textarea, overlayInner } = renderEditor();
const shared = tokens(WIKI_EDITOR_METRICS);
expect(shared.size).toBeGreaterThan(0);
for (const layer of [textarea, overlayInner]) {
const cls = tokens(layer?.className ?? null);
for (const metric of shared) {
expect(cls.has(metric), `${layer?.id ?? "overlay"} missing "${metric}"`).toBe(true);
}
}
});
it("keeps the overlay borderless (a border shrinks its width and desyncs wrapping)", () => {
const { overlayInner } = renderEditor();
const cls = tokens(overlayInner?.className ?? "");
for (const clsName of cls) expect(clsName).not.toMatch(/^border/);
});
it("hides the textarea scrollbar so its gutter never shrinks the content width", () => {
const { textarea } = renderEditor();
const cls = tokens(textarea?.className ?? "");
for (const token of tokens(WIKI_EDITOR_SCROLLBAR_NONE)) {
expect(cls.has(token), `textarea missing "${token}"`).toBe(true);
}
});
it("keeps the textarea flush and borderless inside the shared wrapper", () => {
const { textarea } = renderEditor();
const cls = tokens(textarea?.className ?? "");
for (const clsName of ["absolute", "inset-0", "border-0"]) {
expect(cls.has(clsName), `textarea missing "${clsName}"`).toBe(true);
}
});
});