Skip to content

Feat: Enable the wiki's Markdown editor to navigate to a new Markdown file when a link is clicked. - #17019

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
cike8899:feat-structure-wiki
Jul 17, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
cike8899:feat-structure-wiki

Conversation

@cike8899

Copy link
Copy Markdown
Contributor

Summary

Feat: Enable the wiki's Markdown editor to navigate to a new Markdown file when a link is clicked.

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 17, 2026
@cike8899 cike8899 added the ci Continue Integration label Jul 17, 2026
@cike8899
cike8899 marked this pull request as draft July 17, 2026 02:18
@cike8899
cike8899 marked this pull request as ready for review July 17, 2026 02:18
@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Wiki detail pages now support wiki-link click navigation, navigation history, centralized loading/editing state, and decomposed header, toolbar, and editor-panel rendering.

Changes

Wiki detail navigation

Layer / File(s) Summary
Wiki link parsing and navigation state
web/src/pages/dataset/compilation/utils/parse-wiki-link.ts, web/src/pages/dataset/compilation/hooks/use-wiki-link-navigation.ts
Wiki hrefs are parsed into typed page links, and navigation history supports push, back, reset, and title updates.
Editor wiki-link click routing
web/src/components/markdown-editor.tsx, web/src/lib/editor/lexical-editor.tsx, web/src/lib/editor/plugins/wiki-link-click-plugin.tsx
Wiki-link callbacks are forwarded through the editors, and matching anchor clicks are parsed and routed to the callback.
Detail state, loading, and editing orchestration
web/src/hooks/use-knowledge-request.ts, web/src/pages/dataset/compilation/hooks/use-wiki-detail-content.ts
Detail state selects artifact or version content, manages navigation, editing, commits, references, export, and loading state.
Detail view composition and parent wiring
web/src/pages/dataset/compilation/wiki-detail-content.tsx, web/src/pages/dataset/compilation/wiki-detail-header.tsx, web/src/pages/dataset/compilation/wiki-detail-toolbar.tsx, web/src/pages/dataset/compilation/wiki-detail-editor-panel.tsx, web/src/pages/dataset/compilation/index.tsx
The detail view delegates state and rendering to dedicated components, with artifact selection wired from the compilation page.

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
Loading

Poem

I’m a rabbit with links in my hay,
Hopping through pages the clever new way.
Stack, back, and title all neatly align,
Editors catch clicks with a twitch of the vine.
The wiki now dances—what wonderful shine!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly matches the main change: adding wiki-link navigation from the Markdown editor.
Description check ✅ Passed The description includes the required Summary section and states the feature clearly, though it is brief and lacks background context.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c698f8 and 2fd8f08.

📒 Files selected for processing (12)
  • web/src/components/markdown-editor.tsx
  • web/src/hooks/use-knowledge-request.ts
  • web/src/lib/editor/lexical-editor.tsx
  • web/src/lib/editor/plugins/wiki-link-click-plugin.tsx
  • web/src/pages/dataset/compilation/hooks/use-wiki-detail-content.ts
  • web/src/pages/dataset/compilation/hooks/use-wiki-link-navigation.ts
  • web/src/pages/dataset/compilation/index.tsx
  • web/src/pages/dataset/compilation/utils/parse-wiki-link.ts
  • web/src/pages/dataset/compilation/wiki-detail-content.tsx
  • web/src/pages/dataset/compilation/wiki-detail-editor-panel.tsx
  • web/src/pages/dataset/compilation/wiki-detail-header.tsx
  • web/src/pages/dataset/compilation/wiki-detail-toolbar.tsx

Comment on lines +30 to +42
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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.

Comment on lines +48 to +68
// 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 ?? '',
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Comment on lines +100 to +102
const handleMarkdownLinkClick = useCallback(
(pageType: WikiPageType, slug: string) => {
if (isVersionView) return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +100 to +139
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]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Comment on lines +20 to +40
// 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],
};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +55 to +64
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="size-8"
onClick={onExport}
>
<Download className="size-4" />
</Button>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Clean component decomposition — The refactor from a single ~200-line file into focused components (header, editor panel, toolbar) is a welcome improvement for maintainability.

  2. Navigation stack — useWikiLinkNavigation with push/goBack/reset is well-implemented for wiki-style browsing. Truncating the forward stack on push is the correct UX pattern.

  3. Event delegation pattern — WikiLinkClickPlugin uses rootElement.addEventListener('click', ...) with proper cleanup, which is the right approach for Lexical plugins.

  4. Multiple link format support — parseWikiLinkHref handles both artifact/{id}/{type}/{slug} and {type}/{slug} formats.

  5. 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 enabled parameter on useFetchArtifactPage is gated on IArtifact | null type union, and enabled defaults to true — good backward compatibility.
  • WikiLinkClickPlugin returns null (correct pattern for a non-rendering Lexical plugin).
  • Event listener cleanup uses the stored rootElement reference which is stable for the hook's lifecycle — no stale closure issue.
  • Navigation stack uses currentIndex correctly 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.

@wangq8
wangq8 merged commit 6779607 into infiniflow:main Jul 17, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants