Skip to content

Conversation

@trangdoan982
Copy link
Collaborator

@trangdoan982 trangdoan982 commented May 16, 2025

Summary by CodeRabbit

  • New Features

    • Added a customizable trigger key setting for the Discourse Node Search Menu, allowing users to set their preferred shortcut (default "@") via the personal settings UI.
    • Introduced a new UI component for configuring the trigger key, including support for special characters and keyboard shortcuts.
  • Improvements

    • The Discourse Node Search Menu now responds to the user-defined trigger key, providing a more flexible and personalized experience.
    • Enhanced settings interface with clear explanations and reset functionality for the trigger key configuration.
  • Bug Fixes

    • Improved handling and detection of trigger key events for the Discourse Node Search Menu.

@linear
Copy link

linear bot commented May 16, 2025

@vercel
Copy link

vercel bot commented May 16, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
discourse-graph ⬜️ Skipped (Inspect) May 16, 2025 2:03pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 16, 2025

📝 Walkthrough

Walkthrough

The changes introduce a customizable trigger key for the Discourse Node Search Menu, allowing users to configure which key combination opens the search. This includes exporting utility functions for key normalization, adding a settings UI for the trigger, updating event listeners to use the dynamic trigger, and adjusting logic for inserting the trigger character and rendering the menu.

Changes

File(s) Change Summary
apps/roam/src/components/DiscourseNodeMenu.tsx Exported previously internal constants and functions (isMac, MODIFIER_BIT_MASKS, ALIASES, normalizeKeyCombo) to make them available for use in other modules. No logic was changed.
apps/roam/src/components/DiscourseNodeSearchMenu.tsx Added extensionAPI prop to NodeSearchMenu. Introduced and exported NodeSearchMenuTriggerComponent for configuring the trigger key combo. Updated search input handling to use substring logic instead of regex.
apps/roam/src/components/settings/HomePersonalSettings.tsx Added a new settings section for "Node Search Menu Trigger," displaying and managing the new trigger key combo using NodeSearchMenuTriggerComponent. No changes to existing logic or exported entities.
apps/roam/src/utils/initializeObserversAndListeners.ts Implemented dynamic discourse node search trigger logic using a new setting. Added handleNodeSearchRender to manage inserting the trigger and opening the menu. Updated trigger listener to use the configurable key combo and modifiers. Updated imports for block text updates and added debug logging. No changes to personal/global node menu triggers.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SettingsUI as NodeSearchMenuTriggerComponent
    participant ExtensionAPI
    participant RoamBlock as Roam Block Textarea
    participant Listener as Trigger Listener
    participant Menu as NodeSearchMenu

    User->>SettingsUI: Open settings, configure trigger key
    SettingsUI->>ExtensionAPI: Save trigger key combo
    User->>RoamBlock: Focus and press configured trigger key
    RoamBlock->>Listener: Keydown event
    Listener->>ExtensionAPI: Retrieve trigger key combo
    Listener->>Listener: Check if key combo matches
    alt Combo matches
        Listener->>RoamBlock: Insert trigger if needed
        Listener->>Menu: Render NodeSearchMenu at cursor
    end
Loading

Possibly related PRs

Suggested reviewers

  • mdroidian

Poem

A hop, a skip, a brand new key,
Now search is triggered easily!
With combos set by rabbit paws,
The menu pops without a pause.
Settings fresh and logic neat—
This update’s truly quite a treat!
🐇⌨️✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@trangdoan982
Copy link
Collaborator Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 16, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (5)
apps/roam/src/components/settings/HomePersonalSettings.tsx (1)

32-41: Nice UX consistency – minor copy nit

Great to see the new trigger setting mirroring the existing “Personal Node Menu Trigger”.
If you want absolute wording parity with the sibling setting, consider dropping “Customize” so both descriptions start with a verb (“Override …” / “Customize …”) or both with “Override …”. Totally optional.

apps/roam/src/components/DiscourseNodeMenu.tsx (1)

199-228: Utilities are now exported – consider relocating to avoid future tangling

Making isMac, MODIFIER_BIT_MASKS, ALIASES, and normalizeKeyCombo public is fine for now, but this component file is already large and heavily UI-oriented. As more features start depending on these helpers, moving them (plus getModifiersFromCombo) into a small ~/utils/keyboard.ts (or similar) would
• keep concerns separated,
• prevent accidental circular-import chains, and
• speed up unit-testing such pure helpers.

apps/roam/src/components/DiscourseNodeSearchMenu.tsx (1)

526-626: Trigger component duplicates existing logic – extract a shared helper

NodeSearchMenuTriggerComponent is nearly a copy of NodeMenuTriggerComponent with a small special-char map difference. Duplicating ~100 lines makes maintenance harder (bug-fixes & behaviour tweaks must be applied twice).

Consider:

  1. Create a generic <KeyComboInput> that accepts props
    settingKey (e.g. "discourse-node-search-trigger"), and
    defaultCombo (e.g. { modifiers: 0, key: "@" }),
    then reuse it for both Personal-Menu and Search-Menu triggers.
  2. Move specialCharMap into a shared keyboard-helper module for reuse.

No immediate functional issue, just a maintainability win.

apps/roam/src/utils/initializeObserversAndListeners.ts (2)

252-253: Remove leftover console debugging statements
console.log lines will spam the browser console in production and leak internal data. Please remove them or guard them behind a "development" flag.

-    console.log("evt.key", evt.key);
-    console.log("personal trigger", personalTrigger, nodeSearchTriggerCombo);

247-249: Variable naming is misleading
personalTrigger / personalModifiers actually refer to the “node-search” trigger, not the “personal” node-menu trigger. Consider renaming to nodeSearchTrigger / nodeSearchModifiers for clarity and future maintenance.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5b410c2 and 846022c.

📒 Files selected for processing (4)
  • apps/roam/src/components/DiscourseNodeMenu.tsx (2 hunks)
  • apps/roam/src/components/DiscourseNodeSearchMenu.tsx (5 hunks)
  • apps/roam/src/components/settings/HomePersonalSettings.tsx (2 hunks)
  • apps/roam/src/utils/initializeObserversAndListeners.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
apps/roam/src/components/settings/HomePersonalSettings.tsx (1)
apps/roam/src/components/DiscourseNodeSearchMenu.tsx (1)
  • NodeSearchMenuTriggerComponent (526-626)
apps/roam/src/components/DiscourseNodeSearchMenu.tsx (1)
apps/roam/src/components/DiscourseNodeMenu.tsx (2)
  • getModifiersFromCombo (230-238)
  • normalizeKeyCombo (222-228)
🔇 Additional comments (1)
apps/roam/src/components/settings/HomePersonalSettings.tsx (1)

5-6: Import looks good

NodeSearchMenuTriggerComponent is correctly referenced from the Search-menu module and passed through the same alias path convention used elsewhere. No concerns here.

Comment on lines +246 to +254
const textAfterTrigger = textarea.value.substring(
triggerPosition,
textarea.selectionStart,
);
const match = atTriggerRegex.exec(textBeforeCursor);
if (match) {
debouncedSearchTerm(match[1]);
} else {
onClose();
return;

if (textAfterTrigger.length > 0) {
debouncedSearchTerm(textAfterTrigger);
}
}, [textarea, onClose, debouncedSearchTerm, triggerPosition]);
}, [textarea, debouncedSearchTerm, triggerPosition]);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Empty query leaves menu open – UI feels “stuck”

handleTextAreaInput no longer closes the menu when the user backspaces past the trigger.
That means the pop-over lingers with an empty result list, which can feel broken.

-    if (textAfterTrigger.length > 0) {
-      debouncedSearchTerm(textAfterTrigger);
-    }
+    if (textAfterTrigger.length > 0) {
+      debouncedSearchTerm(textAfterTrigger);
+    } else {
+      onClose();          // hide menu when no query is present
+    }

Alternatively, keep it open but call debouncedSearchTerm("") so the UI refreshes to an explicit “No matches” state.

📝 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 textAfterTrigger = textarea.value.substring(
triggerPosition,
textarea.selectionStart,
);
const match = atTriggerRegex.exec(textBeforeCursor);
if (match) {
debouncedSearchTerm(match[1]);
} else {
onClose();
return;
if (textAfterTrigger.length > 0) {
debouncedSearchTerm(textAfterTrigger);
}
}, [textarea, onClose, debouncedSearchTerm, triggerPosition]);
}, [textarea, debouncedSearchTerm, triggerPosition]);
const textAfterTrigger = textarea.value.substring(
triggerPosition,
textarea.selectionStart,
);
if (textAfterTrigger.length > 0) {
debouncedSearchTerm(textAfterTrigger);
} else {
onClose(); // hide menu when no query is present
}
}, [textarea, debouncedSearchTerm, triggerPosition]);
🤖 Prompt for AI Agents
In apps/roam/src/components/DiscourseNodeSearchMenu.tsx around lines 246 to 254,
the current code does not close the menu or refresh the UI when the query is
empty after backspacing past the trigger, causing the menu to remain open with
no results. Modify the logic so that if textAfterTrigger is empty, either close
the menu explicitly or call debouncedSearchTerm with an empty string to refresh
the UI and show a "No matches" state, ensuring the menu does not feel stuck.

Comment on lines +190 to +200
if (!evt.isComposing && evt.key !== triggerChar) {
const text = textarea.value;
const newText =
text.slice(0, cursorPos) + triggerChar + text.slice(cursorPos);

const blockUid = getUids(textarea).blockUid;
if (blockUid) {
updateBlock({ uid: blockUid, text: newText });
}
triggerPosition = cursorPos;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Asynchronous write may race with UI state and cursor management
updateBlock is asynchronous but the surrounding function is not async, and its returned promise is ignored.
• If the Roam API lags, renderDiscourseNodeSearchMenu can pop up before the block text actually includes the trigger character, causing a mismatch between what the menu thinks is in the block and the real DOM.
• The textarea value is never updated locally, so the user keeps seeing the pre-update text until Roam re-renders, which feels glitchy, and the caret position will jump.

-          updateBlock({ uid: blockUid, text: newText });
+          await updateBlock({ uid: blockUid, text: newText });
+          // Keep the local textarea in-sync and restore cursor
+          textarea.value = newText;
+          textarea.setSelectionRange(triggerPosition + 1, triggerPosition + 1);

Turning handleNodeSearchRender into an async function (and awaiting it from the listener) prevents the race and preserves UX.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/roam/src/utils/initializeObserversAndListeners.ts around lines 190 to
200, the updateBlock call is asynchronous but not awaited, causing potential
race conditions with UI updates and cursor management. To fix this, make the
surrounding function async and await the updateBlock call to ensure the block
text is updated before continuing. Also, update the textarea value locally to
reflect the new text immediately and manage the caret position to prevent jumps,
preserving a smooth user experience.

Comment on lines +254 to +260
if (evt.key === personalTrigger) {
triggerMatched =
(!personalModifiers.includes("ctrl") || evt.ctrlKey) &&
(!personalModifiers.includes("shift") || evt.shiftKey) &&
(!personalModifiers.includes("alt") || evt.altKey) &&
(!personalModifiers.includes("meta") || evt.metaKey);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Trigger matching is fragile – make it case-insensitive and reuse normalizeKeyCombo
evt.key differs between "d" and "D" depending on Shift, so Shift-modified combos can fail to match even when modifiers are correct. Compare keys after normalisation:

-    if (evt.key === personalTrigger) {
+    if (evt.key.toLowerCase() === personalTrigger.toLowerCase()) {

Even better, call the already-exported normalizeKeyCombo helper and compare the fully-normalised combo objects to avoid hand-rolled logic.

📝 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
if (evt.key === personalTrigger) {
triggerMatched =
(!personalModifiers.includes("ctrl") || evt.ctrlKey) &&
(!personalModifiers.includes("shift") || evt.shiftKey) &&
(!personalModifiers.includes("alt") || evt.altKey) &&
(!personalModifiers.includes("meta") || evt.metaKey);
}
if (evt.key.toLowerCase() === personalTrigger.toLowerCase()) {
triggerMatched =
(!personalModifiers.includes("ctrl") || evt.ctrlKey) &&
(!personalModifiers.includes("shift") || evt.shiftKey) &&
(!personalModifiers.includes("alt") || evt.altKey) &&
(!personalModifiers.includes("meta") || evt.metaKey);
}
🤖 Prompt for AI Agents
In apps/roam/src/utils/initializeObserversAndListeners.ts around lines 254 to
260, the current trigger matching logic compares evt.key directly, which is
case-sensitive and can fail for Shift-modified keys. To fix this, replace the
manual key and modifier checks by using the existing normalizeKeyCombo helper to
normalize both the event key combo and the personalTrigger combo, then compare
these normalized objects for equality. This ensures case-insensitive and
consistent matching without hand-rolled logic.

@github-project-automation github-project-automation bot moved this to Done in General May 16, 2025
@trangdoan982 trangdoan982 deleted the eng-299-trigger branch May 16, 2025 17:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants