Skip to content

Fix: reduce size of text-editor (split into plugin files)#55

Closed
will-lp1 wants to merge 4 commits intomainfrom
staging
Closed

Fix: reduce size of text-editor (split into plugin files)#55
will-lp1 wants to merge 4 commits intomainfrom
staging

Conversation

@will-lp1
Copy link
Copy Markdown
Owner

@will-lp1 will-lp1 commented Jul 20, 2025

Summary by CodeRabbit

  • New Features

    • Introduced new plugins for document diff previews, formatting state tracking, and modular editor plugin creation.
    • Added real-time inline suggestion streaming with improved handling and abort support.
    • Enhanced placeholder styling for a more polished editing experience.
  • Refactor

    • Streamlined the text editor by consolidating plugin setup, simplifying save and suggestion logic, and improving modularity.
    • Delegated complex logic to dedicated helper functions, resulting in a leaner and more maintainable editor component.
  • Bug Fixes

    • Improved error handling and validation for document saving and suggestion application.
  • Chores

    • Updated import sources and removed unused utility functions and files to reduce codebase clutter.

@locadex-agent
Copy link
Copy Markdown

locadex-agent bot commented Jul 20, 2025

🚀 Locadex i18n Started

Locadex is now analyzing your changes and generating localizations for this pull request.

What's happening:

  • 🔍 Analyzing your code changes for translatable content
  • 🌐 Generating translations for supported languages
  • 📝 Adding localization commits directly to this PR

Estimated time: 2-10 minutes depending on the size of your changes.


You'll receive another comment when the localization is complete.

@vercel
Copy link
Copy Markdown

vercel bot commented Jul 20, 2025

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

Name Status Preview Comments Updated (UTC)
cursorforwriting-wkur ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 20, 2025 4:17pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 20, 2025

Walkthrough

This update refactors the text editor component and its associated plugins for improved modularity and maintainability. Key changes include introducing new plugin factories, extracting inline suggestion and save logic into reusable functions, adding new plugins for diffing and formatting, and reorganizing event handling. Several utility functions and a React renderer class were removed.

Changes

File(s) Change Summary
components/document/text-editor.tsx Refactored: replaced manual plugin construction and inline logic with plugin factories and helper functions; simplified state and event handling; removed inline diff and preview logic.
components/suggestion-overlay-provider.tsx Updated import paths for suggestion context constants.
lib/editor/config.ts Removed handleTransaction function and related type imports.
lib/editor/diff-plugin.ts Added new diffPlugin managing document diff previews and applying updates via global events with animation and cleanup.
lib/editor/editor-plugins.ts Added new module exporting EditorPluginOptions interface and createEditorPlugins function to centralize plugin configuration.
lib/editor/format-plugin.ts Added new formatPlugin to track and report active text formatting states in the editor.
lib/editor/functions.tsx Removed decoration and text position utility functions related to ProseMirror.
lib/editor/inline-suggestion-plugin.ts Added createInlineSuggestionCallback async function for SSE-based inline suggestions; updated plugin to accept optional callback.
lib/editor/placeholder-plugin.ts Enhanced plugin to dynamically inject and remove placeholder CSS via a view method.
lib/editor/react-renderer.tsx Removed ReactRenderer class and its static render method.
lib/editor/save-plugin.ts Added createSaveFunction and createForceSaveHandler for modular save logic with improved error handling and validation.
lib/editor/suggestion-plugin.ts Updated selectionContextPlugin to accept documentId and added global event listener for applying suggestions with validation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Editor
    participant Plugins
    participant Backend

    User->>Editor: Interacts (type, format, etc.)
    Editor->>Plugins: Dispatch transactions
    Plugins->>Plugins: Track formatting, suggestions, diff, etc.
    Plugins->>Backend: (Optional) Save content, request suggestions
    Backend-->>Plugins: Returns save status or suggestion
    Plugins->>Editor: Update state/UI
    Editor->>User: Reflects changes
Loading

Possibly related PRs

  • Feat/update document.ts inline #38: Focuses on improving diff preview and apply update event handling inside text-editor.tsx by splitting preview, cancel, and apply events with diff-based incremental updates; closely related to this PR’s refactor of diff and preview logic.

Poem

In the warren of code, plugins now bloom,
Refactored and tidy, they banish the gloom.
Suggestions and saves, now modular and neat,
With diffs and formats, the system’s complete!
The rabbit hops on, with a jubilant cheer—
“This editor’s future is bright, never fear!”
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 397d7f2 and 42e5732.

📒 Files selected for processing (1)
  • apps/snow-leopard/lib/editor/save-plugin.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/snow-leopard/lib/editor/save-plugin.ts
✨ 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.

Copy link
Copy Markdown

@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: 2

🧹 Nitpick comments (12)
apps/snow-leopard/lib/editor/placeholder-plugin.ts (2)

2-2: Use import type for type-only imports.

EditorView is only used as a type parameter and should be imported with import type.

-import { Decoration, DecorationSet, EditorView } from 'prosemirror-view';
+import { Decoration, DecorationSet } from 'prosemirror-view';
+import type { EditorView } from 'prosemirror-view';

30-59: Consider handling multiple editor instances.

The current implementation could create duplicate style elements if multiple editors use the placeholder plugin. Consider checking if the style already exists or using a more isolated approach.

 view(editorView: EditorView) {
+  // Check if style already exists
+  const existingStyle = document.querySelector('[data-placeholder-style="true"]');
+  if (existingStyle) {
+    return { destroy() {} };
+  }
+
   const style = document.createElement('style');
   style.setAttribute('data-placeholder-style', 'true');

Alternatively, consider using inline styles or CSS-in-JS approaches for better isolation between editor instances.

apps/snow-leopard/lib/editor/suggestion-plugin.ts (2)

2-2: Use import type for type-only imports.

EditorView is only used as a type parameter and should be imported with import type.

-import { EditorView, Decoration, DecorationSet } from 'prosemirror-view';
+import { Decoration, DecorationSet } from 'prosemirror-view';
+import type { EditorView } from 'prosemirror-view';

93-147: Improve type safety for event handler.

Instead of using type assertions, properly type the event handler to avoid potential runtime issues.

-      const handleApplySuggestion = (event: CustomEvent) => {
+      const handleApplySuggestion = (event: Event) => {
+        if (!(event instanceof CustomEvent)) return;
         if (!event.detail) return;
         const { state, dispatch } = editorView;
 
         const {
           from,
           to,
           suggestion,
           documentId: suggestionDocId,
         } = event.detail;
-      window.addEventListener("apply-suggestion", handleApplySuggestion as EventListener);
+      window.addEventListener("apply-suggestion", handleApplySuggestion);
 
       return {
         destroy() {
-          window.removeEventListener("apply-suggestion", handleApplySuggestion as EventListener);
+          window.removeEventListener("apply-suggestion", handleApplySuggestion);
         },
       };
apps/snow-leopard/lib/editor/editor-plugins.ts (1)

3-3: Use import type for type-only imports.

Plugin is only used as a type in the return signature and should be imported with import type.

-import { Plugin } from 'prosemirror-state';
+import type { Plugin } from 'prosemirror-state';
apps/snow-leopard/lib/editor/format-plugin.ts (1)

1-2: Use import type for type-only imports

These imports are only used as type annotations and should be imported using import type to ensure they are removed during compilation.

-import { Plugin, PluginKey, EditorState } from 'prosemirror-state';
-import { EditorView } from 'prosemirror-view';
+import { Plugin, PluginKey } from 'prosemirror-state';
+import type { EditorState } from 'prosemirror-state';
+import type { EditorView } from 'prosemirror-view';
apps/snow-leopard/lib/editor/save-plugin.ts (1)

29-32: Consider more robust document ID validation

The current validation checks for specific string values which could be fragile. Consider using a more robust approach or extracting this validation logic.

-    if (!docId || docId === "init" || docId === "undefined" || docId === "null") {
-      console.warn("[Save Function] Attempted to save with invalid or init documentId:", docId);
-      throw new Error("Cannot save with invalid or initial document ID.");
-    }
+    const isValidDocumentId = (id: string): boolean => {
+      return Boolean(id) && id !== "init" && !["undefined", "null"].includes(id);
+    };
+    
+    if (!isValidDocumentId(docId)) {
+      console.warn("[Save Function] Attempted to save with invalid or init documentId:", docId);
+      throw new Error("Cannot save with invalid or initial document ID.");
+    }
apps/snow-leopard/lib/editor/diff-plugin.ts (3)

2-2: Use import type for type-only import

EditorView is only used as a type annotation and should be imported using import type.

-import { EditorView } from 'prosemirror-view';
+import type { EditorView } from 'prosemirror-view';

11-11: Remove redundant type annotation

The type annotation : boolean is redundant as it can be inferred from the initialization value.

-  let previewActiveRef: boolean = false;
+  let previewActiveRef = false;

71-71: Use const instead of let for non-reassigned variable

The tr variable is never reassigned, only mutated. Use const for better code clarity.

-          let tr = state.tr;
+          const tr = state.tr;
apps/snow-leopard/components/document/text-editor.tsx (2)

19-19: Use import type for type-only import

FormatState is only used as a type annotation and should be imported using import type.

-import { type FormatState } from "@/lib/editor/format-plugin";
+import type { FormatState } from "@/lib/editor/format-plugin";

251-251: Remove unnecessary type casting

The type casting as unknown as Record<string, boolean> appears unnecessary. If EditorToolbar expects Record<string, boolean> and FormatState has all boolean properties, they should be compatible without casting.

-        <EditorToolbar activeFormats={activeFormats as unknown as Record<string, boolean>} />
+        <EditorToolbar activeFormats={activeFormats} />

If this causes a type error, consider updating the EditorToolbar prop types to accept FormatState directly for better type safety.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 81aa7ee and 397d7f2.

📒 Files selected for processing (12)
  • apps/snow-leopard/components/document/text-editor.tsx (8 hunks)
  • apps/snow-leopard/components/suggestion-overlay-provider.tsx (1 hunks)
  • apps/snow-leopard/lib/editor/config.ts (0 hunks)
  • apps/snow-leopard/lib/editor/diff-plugin.ts (1 hunks)
  • apps/snow-leopard/lib/editor/editor-plugins.ts (1 hunks)
  • apps/snow-leopard/lib/editor/format-plugin.ts (1 hunks)
  • apps/snow-leopard/lib/editor/functions.tsx (1 hunks)
  • apps/snow-leopard/lib/editor/inline-suggestion-plugin.ts (2 hunks)
  • apps/snow-leopard/lib/editor/placeholder-plugin.ts (2 hunks)
  • apps/snow-leopard/lib/editor/react-renderer.tsx (0 hunks)
  • apps/snow-leopard/lib/editor/save-plugin.ts (3 hunks)
  • apps/snow-leopard/lib/editor/suggestion-plugin.ts (5 hunks)
💤 Files with no reviewable changes (2)
  • apps/snow-leopard/lib/editor/react-renderer.tsx
  • apps/snow-leopard/lib/editor/config.ts
🧰 Additional context used
🧬 Code Graph Analysis (2)
apps/snow-leopard/lib/editor/placeholder-plugin.ts (2)
apps/snow-leopard/lib/editor/inline-suggestion-plugin.ts (1)
  • decorations (171-227)
apps/snow-leopard/lib/editor/suggestion-plugin.ts (1)
  • decorations (67-90)
apps/snow-leopard/lib/editor/diff-plugin.ts (2)
apps/snow-leopard/lib/editor/functions.tsx (2)
  • buildContentFromDocument (26-26)
  • buildDocumentFromContent (10-16)
apps/snow-leopard/lib/editor/config.ts (1)
  • documentSchema (27-33)
🪛 Biome (1.9.4)
apps/snow-leopard/lib/editor/placeholder-plugin.ts

[error] 2-2: Some named imports are only used as types.

This import is only used as a type.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Add inline type keywords.

(lint/style/useImportType)

apps/snow-leopard/lib/editor/suggestion-plugin.ts

[error] 2-2: Some named imports are only used as types.

This import is only used as a type.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Add inline type keywords.

(lint/style/useImportType)

apps/snow-leopard/lib/editor/editor-plugins.ts

[error] 3-3: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

apps/snow-leopard/lib/editor/format-plugin.ts

[error] 1-1: Some named imports are only used as types.

This import is only used as a type.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Add inline type keywords.

(lint/style/useImportType)


[error] 2-2: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

apps/snow-leopard/lib/editor/diff-plugin.ts

[error] 11-11: This type annotation is trivially inferred from its initialization.

Safe fix: Remove the type annotation.

(lint/style/noInferrableTypes)


[error] 2-2: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)


[error] 71-71: This let declares a variable that is only assigned once.

'tr' is never reassigned.

Safe fix: Use const instead.

(lint/style/useConst)

apps/snow-leopard/components/document/text-editor.tsx

[error] 19-19: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the compilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

🔇 Additional comments (4)
apps/snow-leopard/components/suggestion-overlay-provider.tsx (1)

12-12: Import source update looks good.

The constants have been correctly moved to their new location in the suggestion plugin module, aligning with the modular plugin architecture.

apps/snow-leopard/lib/editor/functions.tsx (1)

22-22: Correct handling of diffMark in serializer.

Adding diffMark with empty open/close strings ensures diff marks are properly stripped when serializing to markdown.

apps/snow-leopard/lib/editor/inline-suggestion-plugin.ts (1)

124-124: Good use of optional callback pattern

Making the requestSuggestion callback optional with safe invocation using optional chaining improves the plugin's flexibility and robustness.

Also applies to: 252-252

apps/snow-leopard/components/document/text-editor.tsx (1)

71-78: Excellent refactoring to use plugin factory pattern

The use of createEditorPlugins factory significantly improves code organization and maintainability. The component is now much cleaner and focused on its core responsibilities.

Also applies to: 134-141

Comment on lines +15 to +22
export interface EditorPluginOptions {
documentId: string;
initialLastSaved: Date | null;
placeholder?: string;
performSave: (content: string) => Promise<any>;
requestInlineSuggestion: (state: any) => void;
setActiveFormats: (formats: any) => void;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace 'any' types with more specific types.

Using any reduces type safety. Consider defining proper types for these parameters.

+import type { EditorState } from 'prosemirror-state';
+
+interface SaveResult {
+  // Define the expected save result structure
+  success: boolean;
+  error?: string;
+}
+
+interface ActiveFormats {
+  // Define the format structure based on your format plugin
+  bold?: boolean;
+  italic?: boolean;
+  // ... other formats
+}
+
 export interface EditorPluginOptions {
   documentId: string;
   initialLastSaved: Date | null;
   placeholder?: string;
-  performSave: (content: string) => Promise<any>;
-  requestInlineSuggestion: (state: any) => void;
-  setActiveFormats: (formats: any) => void;
+  performSave: (content: string) => Promise<SaveResult>;
+  requestInlineSuggestion: (state: EditorState) => void;
+  setActiveFormats: (formats: ActiveFormats) => void;
 }

Would you like me to help define the proper types based on your plugin implementations?

📝 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
export interface EditorPluginOptions {
documentId: string;
initialLastSaved: Date | null;
placeholder?: string;
performSave: (content: string) => Promise<any>;
requestInlineSuggestion: (state: any) => void;
setActiveFormats: (formats: any) => void;
}
import type { EditorState } from 'prosemirror-state';
interface SaveResult {
// Define the expected save result structure
success: boolean;
error?: string;
}
interface ActiveFormats {
// Define the format structure based on your format plugin
bold?: boolean;
italic?: boolean;
// ... other formats
}
export interface EditorPluginOptions {
documentId: string;
initialLastSaved: Date | null;
placeholder?: string;
performSave: (content: string) => Promise<SaveResult>;
requestInlineSuggestion: (state: EditorState) => void;
setActiveFormats: (formats: ActiveFormats) => void;
}
🤖 Prompt for AI Agents
In apps/snow-leopard/lib/editor/editor-plugins.ts around lines 15 to 22, the
EditorPluginOptions interface uses 'any' for the types of the parameters in
requestInlineSuggestion and setActiveFormats, which reduces type safety. To fix
this, analyze the actual data structures or types used in your plugin
implementations for these parameters and replace 'any' with those specific types
or interfaces. This will improve type safety and code clarity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant