Repository navigation
Feat: Enable the wiki's Markdown editor to navigate to a new Markdown file when a link is clicked. - #17019
Conversation
… file when a link is clicked.
📝 WalkthroughWalkthroughWiki detail pages now support wiki-link click navigation, navigation history, centralized loading/editing state, and decomposed header, toolbar, and editor-panel rendering. ChangesWiki detail navigation
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant MarkdownEditor
participant WikiLinkClickPlugin
participant useWikiDetailContent
participant useFetchArtifactPage
User->>MarkdownEditor: click wiki link
MarkdownEditor->>WikiLinkClickPlugin: receive root click
WikiLinkClickPlugin->>useWikiDetailContent: pass pageType and slug
useWikiDetailContent->>useFetchArtifactPage: fetch linked artifact page
useFetchArtifactPage-->>useWikiDetailContent: return page content
useWikiDetailContent-->>MarkdownEditor: update displayed detail state
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@web/src/lib/editor/plugins/wiki-link-click-plugin.tsx`:
- Around line 30-42: Update handleClick to return immediately for
already-prevented events, modified clicks (Ctrl/Cmd/Shift/Alt), and non-primary
mouse buttons before finding or parsing the anchor. Preserve the existing
wiki-link handling for unmodified primary clicks.
In `@web/src/pages/dataset/compilation/hooks/use-wiki-detail-content.ts`:
- Around line 100-139: Update handleMarkdownLinkClick and handleBack to invoke
the existing cancel/confirmation flow when isDirty before replacing the selected
artifact. Preserve the current navigation behavior only after confirmation or
when there are no unsaved edits, ensuring editorKey changes cannot discard
pending edits.
- Around line 48-68: Update the wiki detail synchronization logic around the
currentEntry and selectedArtifact comparisons to use the combined pageType and
slug identity, distinguishing entries such as concept/foo from entity/foo. Apply
this identity consistently to title synchronization, stack reset behavior, and
the editorKey and commit paths referenced by the affected sections, so switching
page types refreshes the entry, title, editor instance, and commit metadata
correctly.
- Around line 100-102: Update the handleMarkdownLinkClick integration so the
editor plugin does not receive a no-op callback when isVersionView is true. Omit
the callback in version view, or alternatively clear selectedVersion before
performing the normal wiki-link navigation; preserve existing navigation
behavior outside version view.
In `@web/src/pages/dataset/compilation/utils/parse-wiki-link.ts`:
- Around line 20-40: Update the wiki-link parsing logic around artifactMatch and
simpleMatch to accept only complete dataset-safe relative URLs, rejecting
external origins and trailing query or hash text. Preserve or validate the
artifact link’s datasetId before returning the parsed result, so cross-dataset
links cannot be routed against the current dataset.
In `@web/src/pages/dataset/compilation/wiki-detail-toolbar.tsx`:
- Around line 55-64: Add aria-label={t('knowledgeDetails.export')} to the
icon-only export Button in the TooltipTrigger, preserving the existing onClick,
styling, and tooltip behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 60e65bdf-fb6a-44c5-9ad7-3ed3f09cdb3f
📒 Files selected for processing (12)
web/src/components/markdown-editor.tsxweb/src/hooks/use-knowledge-request.tsweb/src/lib/editor/lexical-editor.tsxweb/src/lib/editor/plugins/wiki-link-click-plugin.tsxweb/src/pages/dataset/compilation/hooks/use-wiki-detail-content.tsweb/src/pages/dataset/compilation/hooks/use-wiki-link-navigation.tsweb/src/pages/dataset/compilation/index.tsxweb/src/pages/dataset/compilation/utils/parse-wiki-link.tsweb/src/pages/dataset/compilation/wiki-detail-content.tsxweb/src/pages/dataset/compilation/wiki-detail-editor-panel.tsxweb/src/pages/dataset/compilation/wiki-detail-header.tsxweb/src/pages/dataset/compilation/wiki-detail-toolbar.tsx
| const handleClick = (event: MouseEvent) => { | ||
| const anchor = findAnchorElement(event.target); | ||
| if (!anchor) return; | ||
|
|
||
| const href = anchor.getAttribute('href'); | ||
| if (!href) return; | ||
|
|
||
| const parsed = parseWikiLinkHref(href); | ||
| if (!parsed) return; | ||
|
|
||
| event.preventDefault(); | ||
| event.stopPropagation(); | ||
| onWikiLinkClick(parsed.pageType, parsed.slug); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Preserve native modified-click behavior.
Ctrl/Cmd/Shift/Alt-clicks are currently intercepted, preventing users from opening wiki links in a new tab or window. Return early for modified, non-primary, or already-prevented events before parsing the anchor.
Proposed fix
const handleClick = (event: MouseEvent) => {
+ if (
+ event.defaultPrevented ||
+ event.button !== 0 ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey
+ ) {
+ return;
+ }
+
const anchor = findAnchorElement(event.target);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const handleClick = (event: MouseEvent) => { | |
| const anchor = findAnchorElement(event.target); | |
| if (!anchor) return; | |
| const href = anchor.getAttribute('href'); | |
| if (!href) return; | |
| const parsed = parseWikiLinkHref(href); | |
| if (!parsed) return; | |
| event.preventDefault(); | |
| event.stopPropagation(); | |
| onWikiLinkClick(parsed.pageType, parsed.slug); | |
| const handleClick = (event: MouseEvent) => { | |
| if ( | |
| event.defaultPrevented || | |
| event.button !== 0 || | |
| event.metaKey || | |
| event.ctrlKey || | |
| event.shiftKey || | |
| event.altKey | |
| ) { | |
| return; | |
| } | |
| const anchor = findAnchorElement(event.target); | |
| if (!anchor) return; | |
| const href = anchor.getAttribute('href'); | |
| if (!href) return; | |
| const parsed = parseWikiLinkHref(href); | |
| if (!parsed) return; | |
| event.preventDefault(); | |
| event.stopPropagation(); | |
| onWikiLinkClick(parsed.pageType, parsed.slug); |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/lib/editor/plugins/wiki-link-click-plugin.tsx` around lines 30 - 42,
Update handleClick to return immediately for already-prevented events, modified
clicks (Ctrl/Cmd/Shift/Alt), and non-primary mouse buttons before finding or
parsing the anchor. Preserve the existing wiki-link handling for unmodified
primary clicks.
| // Keep the current stack entry's title in sync with pageData. | ||
| useEffect(() => { | ||
| if (!currentEntry || !pageData) return; | ||
| if (currentEntry.slug !== pageData.slug) return; | ||
| updateCurrentTitle(pageData.title); | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps | ||
| }, [currentEntry?.slug, pageData?.slug, pageData?.title, updateCurrentTitle]); | ||
|
|
||
| // When selectedArtifact changes from the left panel (not from our own | ||
| // wiki-link navigation), reset the stack. Wiki-link clicks call push() | ||
| // before onSelectArtifact(), so currentEntry.slug already matches by the | ||
| // time this effect runs and we bail out. | ||
| useEffect(() => { | ||
| if (isVersionView || !selectedArtifact) return; | ||
| if (currentEntry?.slug === selectedArtifact.slug) return; | ||
|
|
||
| reset({ | ||
| slug: selectedArtifact.slug, | ||
| title: selectedArtifact.title, | ||
| pageType: selectedArtifact.page_type ?? '', | ||
| }); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Use pageType + slug as the page identity.
Slug-only comparisons let concept/foo and entity/foo collide. Selecting the other type can leave currentEntry stale, display the wrong title, retain the same editor key, and commit using the old currentEntry.pageType.
Include pageType in the synchronization checks and editorKey.
Also applies to: 83-98, 152-165
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/dataset/compilation/hooks/use-wiki-detail-content.ts` around
lines 48 - 68, Update the wiki detail synchronization logic around the
currentEntry and selectedArtifact comparisons to use the combined pageType and
slug identity, distinguishing entries such as concept/foo from entity/foo. Apply
this identity consistently to title synchronization, stack reset behavior, and
the editorKey and commit paths referenced by the affected sections, so switching
page types refreshes the entry, title, editor instance, and commit metadata
correctly.
| const handleMarkdownLinkClick = useCallback( | ||
| (pageType: WikiPageType, slug: string) => { | ||
| if (isVersionView) return; |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not install a callback that becomes a no-op in version view.
The editor plugin prevents default navigation before this callback returns, so wiki links in historical versions are inert. Either omit the callback in version view or clear selectedVersion and perform the navigation.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/dataset/compilation/hooks/use-wiki-detail-content.ts` around
lines 100 - 102, Update the handleMarkdownLinkClick integration so the editor
plugin does not receive a no-op callback when isVersionView is true. Omit the
callback in version view, or alternatively clear selectedVersion before
performing the normal wiki-link navigation; preserve existing navigation
behavior outside version view.
| const handleMarkdownLinkClick = useCallback( | ||
| (pageType: WikiPageType, slug: string) => { | ||
| if (isVersionView) return; | ||
| if (currentEntry?.slug === slug && currentEntry?.pageType === pageType) | ||
| return; | ||
|
|
||
| // Sync the current entry's title from pageData before pushing a new | ||
| // entry, so the title is preserved when this entry becomes the | ||
| // "previous" entry for the back button. | ||
| if ( | ||
| currentEntry && | ||
| pageData && | ||
| pageData.slug === currentEntry.slug && | ||
| pageData.title | ||
| ) { | ||
| updateCurrentTitle(pageData.title); | ||
| } | ||
|
|
||
| push({ slug, title: '', pageType }); | ||
| onSelectArtifact({ slug, page_type: pageType, title: '' }); | ||
| }, | ||
| [ | ||
| push, | ||
| onSelectArtifact, | ||
| isVersionView, | ||
| currentEntry, | ||
| pageData, | ||
| updateCurrentTitle, | ||
| ], | ||
| ); | ||
|
|
||
| const handleBack = useCallback(() => { | ||
| if (!previousEntry) return; | ||
| goBack(); | ||
| onSelectArtifact({ | ||
| slug: previousEntry.slug, | ||
| page_type: previousEntry.pageType, | ||
| title: previousEntry.title, | ||
| }); | ||
| }, [goBack, previousEntry, onSelectArtifact]); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Protect unsaved edits before link and Back navigation.
Both handlers replace the selected artifact without checking isDirty; changing editorKey can reset the editor and silently discard pending edits. Reuse the existing cancel/confirmation flow before navigating.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/dataset/compilation/hooks/use-wiki-detail-content.ts` around
lines 100 - 139, Update handleMarkdownLinkClick and handleBack to invoke the
existing cancel/confirmation flow when isDirty before replacing the selected
artifact. Preserve the current navigation behavior only after confirmation or
when there are no unsaved edits, ensuring editorKey changes cannot discard
pending edits.
| // Prefer the artifact/{datasetId}/{pageType}/{slug} form. | ||
| const artifactMatch = normalized.match( | ||
| /(?:^|\/)artifact\/[^/]+\/(entity|concept)\/([^/\s"']+)/, | ||
| ); | ||
| if (artifactMatch) { | ||
| return { | ||
| pageType: artifactMatch[1] as WikiPageType, | ||
| slug: artifactMatch[2], | ||
| }; | ||
| } | ||
|
|
||
| // Fallback to a plain {pageType}/{slug} form. | ||
| const simpleMatch = normalized.match( | ||
| /(?:^|\/)(entity|concept)\/([^/\s"']+)/, | ||
| ); | ||
| if (simpleMatch) { | ||
| return { | ||
| pageType: simpleMatch[1] as WikiPageType, | ||
| slug: simpleMatch[2], | ||
| }; | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Restrict parsing to complete, dataset-safe wiki URLs.
These unanchored patterns accept external URLs such as https://example.com/entity/foo; the click plugin then suppresses normal navigation. They also discard the datasetId from artifact links, potentially routing cross-dataset links against the current dataset.
Match the complete relative URL, exclude query/hash text from the slug, and either validate or preserve datasetId.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/dataset/compilation/utils/parse-wiki-link.ts` around lines 20 -
40, Update the wiki-link parsing logic around artifactMatch and simpleMatch to
accept only complete dataset-safe relative URLs, rejecting external origins and
trailing query or hash text. Preserve or validate the artifact link’s datasetId
before returning the parsed result, so cross-dataset links cannot be routed
against the current dataset.
| <Tooltip> | ||
| <TooltipTrigger asChild> | ||
| <Button | ||
| variant="ghost" | ||
| size="icon" | ||
| className="size-8" | ||
| onClick={onExport} | ||
| > | ||
| <Download className="size-4" /> | ||
| </Button> |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Give the export button an accessible name.
The icon-only button has no label for screen readers. Add aria-label={t('knowledgeDetails.export')}; the tooltip alone is insufficient.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/dataset/compilation/wiki-detail-toolbar.tsx` around lines 55 -
64, Add aria-label={t('knowledgeDetails.export')} to the icon-only export Button
in the TooltipTrigger, preserving the existing onClick, styling, and tooltip
behavior.
wangq8
left a comment
There was a problem hiding this comment.
PR Review: #17019 — Wiki Markdown Editor Link Navigation
Author: cike8899
Files: 12 files | +687 / -193
State: OPEN
What This PR Does
Adds click-to-navigate functionality for internal wiki links (/concept/{slug} and /entity/{slug}) in the Lexical-based Markdown editor on the wiki compilation page. It also refactors the monolithic wiki-detail-content.tsx into smaller components (WikiDetailHeader, WikiDetailEditorPanel, WikiDetailToolbar) and extracts business logic into custom hooks (useWikiDetailContent, useWikiLinkNavigation).
✅ What's Good
-
Clean component decomposition — The refactor from a single ~200-line file into focused components (header, editor panel, toolbar) is a welcome improvement for maintainability.
-
Navigation stack —
useWikiLinkNavigationwith push/goBack/reset is well-implemented for wiki-style browsing. Truncating the forward stack on push is the correct UX pattern. -
Event delegation pattern —
WikiLinkClickPluginusesrootElement.addEventListener('click', ...)with proper cleanup, which is the right approach for Lexical plugins. -
Multiple link format support —
parseWikiLinkHrefhandles bothartifact/{id}/{type}/{slug}and{type}/{slug}formats. -
No-op on same-link click — Clicking a link pointing to the currently displayed page is correctly a no-op, preventing unnecessary fetch cycles.
⚠️ Issues & Concerns
1. Missing tests for a pure utility function
parse-wiki-link.ts is a pure function — zero dependencies, deterministic output. With ~50 lines of code and regex matching, this is a prime candidate for unit tests. No test file is included. Recommendation: Add unit tests covering at least the documented formats and edge cases (empty href, malformed URLs, slugs with special characters, etc).
2. gcTime: 0 removed without explanation
The previous code had gcTime: 0 on useFetchArtifactPage. This was removed in favor of the new enabled parameter. For a navigation context where users may go back to previously viewed pages, keeping cache around is actually beneficial. However, this is a behavioral change that should be intentional. If the intent was to allow caching, that's fine — but it should be mentioned.
3. Type mismatch — displayedArtifact may not fully satisfy IArtifact
In useWikiDetailContent:
const displayedArtifact = currentEntry
? { slug: currentEntry.slug, title: currentEntry.title, page_type: currentEntry.pageType }
: selectedArtifact;This object shape is passed to WikiDetailHeader which types it as IArtifact | null | undefined. If IArtifact has required fields beyond slug, title, and page_type, this will either fail at runtime or TypeScript won't complain if those fields are optional. Recommendation: Either use Pick<IArtifact, 'slug' | 'title' | 'page_type'> throughout, or make WikiDetailHeader accept a narrower interface explicitly.
4. Race condition dependency in the dual-effect pattern
The two useEffect hooks in useWikiDetailContent (one syncs title, one resets stack) both depend on selectedArtifact?.slug and currentEntry?.slug. The PR comment explains that push() is called before onSelectArtifact() in the click handler, so currentEntry.slug already matches the artifact slug by the time effects run. This relies on React 18's automatic batching behavior. It's correct today but is a subtle coupling that could break with future React changes. Recommendation: Consider merging the two effects or using a single state reducer to make the dependency explicit.
5. URL-encoded slugs not handled in parseWikiLinkHref
If a wiki slug contains characters that are percent-encoded in the href (e.g., %20 for spaces), the regex captures the raw encoded string. This could cause a navigation to a non-existent slug. Recommendation: Add decodeURIComponent() on the captured slug.
6. Version view ignores link clicks
handleMarkdownLinkClick bails out when isVersionView is true. While this makes sense (viewing a historical version shouldn't trigger navigation), it silently drops the click. Consider showing a tooltip or visual indicator that links are disabled in version-diff mode.
7. updateCurrentTitle returns early when title already matches
In useWikiLinkNavigation.updateCurrentTitle, the function returns prev unchanged if entry.title === title. This is a good optimization but it means if the title hasn't been fetched yet (entry.title === '') and the data comes back with an empty title, the entry remains untitled. This is likely fine in practice since pageData.title would usually be non-empty, but worth noting.
🔍 Minor Style / Quality Notes
- The new
enabledparameter onuseFetchArtifactPageis gated onIArtifact | nulltype union, andenableddefaults totrue— good backward compatibility. WikiLinkClickPluginreturnsnull(correct pattern for a non-rendering Lexical plugin).- Event listener cleanup uses the stored
rootElementreference which is stable for the hook's lifecycle — no stale closure issue. - Navigation stack uses
currentIndexcorrectly and never goes below 0.
🏁 Verdict
Solid feature addition with a well-structured refactor. The core logic is sound, the plugin pattern is correct, and the navigation UX is thoughtful (back button preserves previous entry's title, same-link clicks are no-ops, forward stack is truncated).
The main gaps are lack of tests (especially for the parser), a type looseness in displayedArtifact, and the missing URL decoding in the parser — all easy fixes. None are blockers for merging, but items 1-3 should be addressed before release.
Summary
Feat: Enable the wiki's Markdown editor to navigate to a new Markdown file when a link is clicked.