Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

253 图片无法回显行内元素包含行内元素无法解析 #283

Conversation

cycleccc
Copy link
Owner

@cycleccc cycleccc commented Oct 23, 2024

Changes Overview

Implementation Approach

Testing Done

Verification Steps

Additional Notes

Checklist

  • I have created a changeset for this PR if necessary.
  • My changes do not break the library.
  • I have added tests where applicable.
  • I have followed the project guidelines.
  • I have fixed any lint issues.

Related Issues

Summary by CodeRabbit

  • New Features

    • Enhanced handling of text nodes within <span> elements for improved content parsing.
    • Improved event handling and error management in the TextArea and Toolbar classes.
    • Introduced new constants for editor events and minimum textarea height validation.
    • Added a new function to initialize content based on provided HTML or JSON.
    • Enhanced editor configuration and creation options with new types and interfaces.
  • Bug Fixes

    • Addressed rendering issues for inline elements containing images.
    • Removed outdated test cases for compatibility with previous JSON formats in list and video modules.
  • Tests

    • Updated test cases for list plugin functionality, ensuring correct behavior for list item interactions.
    • Modified test suite for video module, focusing on the behavior of the withVideo plugin.

@cycleccc cycleccc linked an issue Oct 23, 2024 that may be closed by this pull request
Copy link

changeset-bot bot commented Oct 23, 2024

⚠️ No Changeset found

Latest commit: 8d57fd3

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Oct 23, 2024

Walkthrough

The changes primarily involve modifications to several TypeScript files within the project. The create-editor.ts file has undergone restructuring of imports and enhancements to the createEditor function for better readability. The parse-elem-html.ts file has added logic to better handle text nodes within <span> elements. In the test files for the list and video modules, specific test cases have been removed, focusing on refining the functionality of the respective plugins without backward compatibility checks. The Toolbar and TextArea classes have also seen improvements in event handling and error management.

Changes

File Path Change Summary
packages/core/src/create/create-editor.ts Reorganized imports; added genEditorConfig, EditorEvents, ICreateOption; refactored createEditor into createBaseEditor and applyPlugins; commented out normalizeContent method call.
packages/core/src/parse-html/parse-elem-html.ts Added NodeType import; enhanced handling of child nodes in <span> to return text node content.
packages/list-module/__tests__/plugin.test.ts Removed test case for compatibility with previous JSON format for bulleted lists; retained other list functionality tests.
packages/video-module/__tests__/plugin.test.ts Removed test case for normalizeNode method behavior with withVideo plugin; retained other video functionality tests.
packages/core/src/create/helper.ts Added import for EditorEvents; updated event listener to use EditorEvents.DESTROYED; modified function signatures for clarity.
packages/core/src/menus/bar/Toolbar.ts Reorganized imports; debounced changeToolbarState method; added error handling and checks in toolbar methods.
packages/core/src/text-area/TextArea.ts Enhanced event handling and error management; updated imports to use EditorEvents for consistency.
packages/core/src/config/interface.ts Added new types and constants, including EditorEvents, EditorEventType, PluginFnType, and ICreateOption.
packages/core/src/menus/bar/HoverBar.ts Updated event listeners to use EditorEvents constants instead of string literals.

Possibly related PRs

🐰 In the code garden, changes bloom bright,
Imports are tidy, and functions take flight.
Spans now whisper their text in delight,
Tests are refined, with focus in sight.
A hop and a skip, through logic we dart,
In the world of code, we play our part! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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
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: 5

🧹 Outside diff range and nitpick comments (2)
packages/core/src/parse-html/parse-elem-html.ts (1)

44-44: Approve functionality with style suggestions

The text node handling logic is correct and properly addresses the inline element parsing issue. However, consider improving readability with better formatting:

-        if ($childElem[0].nodeType === NodeType.TEXT_NODE) { return { text: $childElem[0].textContent || '' } }
+        if ($childElem[0].nodeType === NodeType.TEXT_NODE) {
+          return { text: $childElem[0].textContent || '' }
+        }
packages/core/src/create/create-editor.ts (1)

8-31: Consider organizing imports by category.

The imports could be better organized into clear categories for improved maintainability:

  1. External dependencies (slate, slate-history)
  2. Core configurations and interfaces
  3. Editor plugins
  4. UI components
  5. Utilities
 import { createEditor, Descendant } from 'slate'
 import { withHistory } from 'slate-history'
+
 import { genEditorConfig } from '../config/index'
 import { IEditorConfig } from '../config/interface'
 import { IDomEditor } from '../editor/interface'
+
 import { withConfig } from '../editor/plugins/with-config'
 import { withContent } from '../editor/plugins/with-content'
 import { withDOM } from '../editor/plugins/with-dom'
 import { withEmitter } from '../editor/plugins/with-emitter'
 import { withEventData } from '../editor/plugins/with-event-data'
 import { withMaxLength } from '../editor/plugins/with-max-length'
 import { withSelection } from '../editor/plugins/with-selection'
+
 import HoverBar from '../menus/bar/HoverBar'
 import TextArea from '../text-area/TextArea'
+
 import type { DOMElement } from '../utils/dom'
 import { promiseResolveThen } from '../utils/util'
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9b93d4b and 3adbb39.

📒 Files selected for processing (4)
  • packages/core/src/create/create-editor.ts (5 hunks)
  • packages/core/src/parse-html/parse-elem-html.ts (2 hunks)
  • packages/list-module/tests/plugin.test.ts (0 hunks)
  • packages/video-module/tests/plugin.test.ts (0 hunks)
💤 Files with no reviewable changes (2)
  • packages/list-module/tests/plugin.test.ts
  • packages/video-module/tests/plugin.test.ts
🧰 Additional context used
🔇 Additional comments (3)
packages/core/src/parse-html/parse-elem-html.ts (2)

11-11: LGTM: Clean import addition

The NodeType import is appropriately grouped with related DOM utilities and is used correctly for type checking.


42-47: Verify handling of deeply nested inline elements

While the changes look good, let's verify the handling of deeply nested inline elements to ensure the fix is comprehensive.

✅ Verification successful

Let me gather more specific information about the nested span handling by examining the test files and implementation.

This will help us verify:

  1. How nested spans are tested
  2. The actual implementation of span parsing
  3. Text node handling test coverage

Let me analyze the results to provide a comprehensive verification.


Let me gather one final piece of information to verify the text node handling implementation.

This will help us verify the actual implementation of text node handling and how it integrates with nested elements.


Based on the gathered evidence, I can now provide a final response:

Text node handling in nested spans is properly implemented

The implementation correctly handles text nodes and nested inline elements by:

  • Properly detecting text nodes using nodeType === NodeType.TEXT_NODE
  • Extracting text content safely with fallback (textContent || '')
  • Recursively processing nested elements through parseTextElemHtml

The test coverage shows comprehensive testing of:

  • Nested span scenarios with various text styles
  • Text node content preservation
  • Style inheritance in nested structures

The changes in the PR maintain the proper handling of deeply nested inline elements while adding robust text node processing. The recursive nature of parseTextElemHtml ensures that all levels of nesting are properly handled, and the explicit text node check prevents any loss of content.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test cases involving nested span elements
rg -l 'span.*span' --type ts

# Look for existing nested span handling in the codebase
ast-grep --pattern 'span[data-w-e-type]'

Length of output: 2088


Script:

#!/bin/bash
# Check test files for nested span scenarios
rg -A 5 "span.*span" packages/core/__tests__ packages/basic-modules/__tests__ --type ts

# Look for span parsing implementation
ast-grep --pattern 'parseTextElemHtml($_, $_)'

# Check for text node handling in tests
rg -A 5 "TEXT_NODE" packages/core/__tests__ --type ts

Length of output: 11753


Script:

#!/bin/bash
# Check the implementation of text node handling in parse-elem-html.ts
rg -A 10 "TEXT_NODE" packages/core/src/parse-html/parse-elem-html.ts

# Look for the parseTextElemHtml implementation
rg -A 15 "function parseTextElemHtml" packages/core/src/parse-html/parse-elem-html.ts

Length of output: 484

packages/core/src/create/create-editor.ts (1)

112-112: 🛠️ Refactor suggestion

Improve type safety in hoverbar initialization.

Consider using undefined instead of null for better TypeScript idioms and make the hoverbar keys check more explicit.

- let hoverbar: HoverBar | null
+ let hoverbar: HoverBar | undefined
+
+ const hasHoverbarKeys = (keys: Record<string, unknown>): boolean => {
+   return Object.keys(keys).length > 0
+ }
+
- if (Object.keys(hoverbarKeys).length > 0) {
+ if (hasHoverbarKeys(hoverbarKeys)) {

Likely invalid or redundant comment.

packages/core/src/create/create-editor.ts Show resolved Hide resolved
packages/core/src/create/create-editor.ts Show resolved Hide resolved
packages/core/src/create/create-editor.ts Outdated Show resolved Hide resolved
packages/core/src/create/create-editor.ts Outdated Show resolved Hide resolved
packages/core/src/create/create-editor.ts Outdated Show resolved Hide resolved
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: 1

🧹 Outside diff range and nitpick comments (4)
packages/core/src/create/helper.ts (1)

41-41: Consider applying trailing commas consistently

While adding trailing commas is good for git diffs, it should be applied consistently across all function signatures in the file.

Consider updating other function signatures (like isRepeatedCreate) to maintain consistency:

 function isRepeatedCreate(
   editor: IDomEditor,
   attrKey: string,
-  selector: string | DOMElement
+  selector: string | DOMElement,
 ): boolean {

Also applies to: 51-51

packages/core/src/text-area/TextArea.ts (1)

Line range hint 54-110: Consider adding error handling to the promise-based initialization.

While the initialization logic is solid, the promiseResolveThen callback could benefit from error handling to gracefully handle initialization failures.

Consider wrapping the initialization in a try-catch:

     promiseResolveThen(() => {
+      try {
         const editor = this.editorInstance
         const window = DomEditor.getWindow(editor)
         // ... rest of initialization
+      } catch (error) {
+        console.error('TextArea initialization failed:', error)
+        // Optionally emit an initialization error event
+        editor?.emit(EditorEvents.ERROR, error)
+      }
     })
packages/core/src/menus/bar/Toolbar.ts (2)

Line range hint 44-67: Consider enhancing the error message for better debugging.

The error handling is good, but we could make the error message more helpful.

Consider this enhancement:

-throw new Error(`Cannot find toolbar DOM by selector '${boxSelector}'`)
+throw new Error(`Cannot find toolbar DOM by selector '${boxSelector}'. Please ensure the element exists before initialization.`)

Line range hint 190-236: Consider using custom error types for better error handling.

While the error handling is comprehensive, using custom error types would improve error catching and handling.

Consider creating and using custom error types:

class ToolbarError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'ToolbarError';
  }
}

// Usage:
throw new ToolbarError(`Not found menu item factory by key '${key}'`);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3adbb39 and 48891bc.

📒 Files selected for processing (4)
  • packages/core/src/create/create-editor.ts (5 hunks)
  • packages/core/src/create/helper.ts (6 hunks)
  • packages/core/src/menus/bar/Toolbar.ts (10 hunks)
  • packages/core/src/text-area/TextArea.ts (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/create/create-editor.ts
🧰 Additional context used
🔇 Additional comments (12)
packages/core/src/create/helper.ts (4)

11-11: LGTM: Good practice using EditorEvents enum

The addition of EditorEvents import improves type safety by replacing string literals for event types.


29-29: LGTM: Consistent use of EditorEvents enum

The change from string literal to EditorEvents.DESTROYED improves type safety and maintainability.


77-77: LGTM: Improved code clarity with braces

Adding braces to the if statement improves code clarity and prevents potential errors.


88-89: ⚠️ Potential issue

Security: Consider sanitizing HTML input

The code directly injects HTML into a div using jQuery, which could be vulnerable to XSS attacks if the input is not trusted.

Consider using a HTML sanitization library before injecting the HTML:

+ import DOMPurify from 'dompurify';
  // ...
- const $content = $(`<div>${html}</div>`)
+ const sanitizedHtml = DOMPurify.sanitize(html);
+ const $content = $(`<div>${sanitizedHtml}</div>`)

Likely invalid or redundant comment.

packages/core/src/text-area/TextArea.ts (4)

7-50: LGTM: Well-structured imports and property declarations.

The new imports and state management properties enhance the clarity and maintainability of the code. The TypeScript types are properly defined, and the initialization is handled correctly.


Line range hint 163-173: Verify the setTimeout usage in focus/blur handlers.

The asynchronous focus/blur event handling could potentially lead to race conditions if multiple state changes occur in quick succession.

Consider adding a flag to track pending callbacks:

+  private pendingFocusBlurCallback: NodeJS.Timeout | null = null;
   editor.on(EditorEvents.CHANGE, () => {
     if (this.latestEditorSelection == null && editor.selection != null) {
+      if (this.pendingFocusBlurCallback) clearTimeout(this.pendingFocusBlurCallback);
-      setTimeout(() => onFocus && onFocus(editor))
+      this.pendingFocusBlurCallback = setTimeout(() => {
+        onFocus && onFocus(editor);
+        this.pendingFocusBlurCallback = null;
+      })
     } else if (this.latestEditorSelection != null && editor.selection == null) {
       // Similar changes for blur...
     }
   })

180-189: LGTM: Well-implemented utility methods.

The maxLength info and progress bar implementations are robust and include proper null checks and cleanup.

Also applies to: 196-208

🧰 Tools
🪛 Biome

[error] 181-183: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


Line range hint 212-224: Address the performance TODO comment.

The TODO raises a valid concern about potential performance bottlenecks with large content updates.

Let's analyze the performance impact:

Would you like help implementing performance benchmarks or exploring optimization strategies for the view updates?

packages/core/src/menus/bar/Toolbar.ts (4)

7-21: LGTM! Import organization is clean and logical.

The new imports support the implementation changes and are well organized.


28-36: LGTM! Property declarations are well-structured.

Properties are properly typed and initialized with appropriate visibility modifiers.


Line range hint 84-89: LGTM! Proper cleanup implementation.

The toolbar cleanup before re-initialization prevents potential DOM-related issues.


129-139: LGTM! Robust divider placement logic.

The implementation properly handles all edge cases for divider placement.

packages/core/src/menus/bar/Toolbar.ts Outdated Show resolved Hide resolved
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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6fd5a90 and 8d57fd3.

📒 Files selected for processing (2)
  • packages/core/src/create/create-editor.ts (5 hunks)
  • packages/core/src/create/helper.ts (7 hunks)
🔇 Additional comments (6)
packages/core/src/create/helper.ts (5)

7-7: LGTM! Import changes improve type safety

The addition of EditorEvents import and its usage instead of string literals enhances type safety and maintainability.

Also applies to: 11-11


41-41: LGTM! Consistent parameter formatting

The addition of trailing commas follows TypeScript best practices and improves git diff readability.

Also applies to: 51-51


77-77: LGTM! Improved code block clarity

The addition of braces improves code clarity and prevents potential bugs from future modifications.

Let's check for consistency in other similar if statements:

#!/bin/bash
# Search for single-line if statements without braces
rg "if \(.*\) (?!({|return|throw|continue|break))" --type ts

104-118: 🛠️ Refactor suggestion

Consider adding validation and error handling

The new initializeContent function could benefit from additional robustness:

  1. Add validation for HTML content structure
  2. Add type checking for malformed JSON content
  3. Consider logging when falling back to default content

Let's check how content initialization is handled elsewhere:

#!/bin/bash
# Search for similar content initialization patterns
ast-grep --pattern 'function $_(editor: $_, options: { html?: string, content?: $_[] })'

Consider adding these safety checks:

 export function initializeContent(editor: IDomEditor, options: { html?: string, content?: Descendant[] }) {
   // 传入 html ,转换为 JSON content
   if (options.html != null) {
+    try {
+      const doc = new DOMParser().parseFromString(options.html, 'text/html');
+      if (doc.body.querySelector('parsererror')) {
+        console.warn('Invalid HTML provided, falling back to default content');
+        return genDefaultContent();
+      }
       return htmlToContent(editor, options.html)
+    } catch (e) {
+      console.error('Error parsing HTML:', e);
+      return genDefaultContent();
+    }
   }
   // 传入 JSON content
   if (options.content?.length) {
+    try {
+      // Validate content structure
+      if (!options.content.every(node => 'type' in node)) {
+        console.warn('Invalid content structure, falling back to default content');
+        return genDefaultContent();
+      }
       return options.content
+    } catch (e) {
+      console.error('Error validating content:', e);
+      return genDefaultContent();
+    }
   }
+  console.info('No content provided, using default content');
   // 默认内容
   return genDefaultContent()
 }

29-31: LGTM! Event constant usage improves maintainability

Using EditorEvents.DESTROYED instead of string literal improves type safety and maintainability.

Let's check if there are any remaining string literals for events that should be replaced:

✅ Verification successful

Let me try a different search pattern to verify the event usage in the codebase.

This should help us:

  1. Find all event listener registrations
  2. Specifically identify string literal event names
  3. See how EditorEvents enum is used across the codebase

Based on the search results, I can now provide a final response:

All editor event usages are consistently using EditorEvents enum

The verification shows that all editor-specific events in the codebase are properly using the EditorEvents enum (e.g., DESTROYED, CHANGE, SCROLL, etc.). The string literals found in the search results are for other event types like:

  • DOM events (e.g., 'click', 'mousedown')
  • Third-party library events (e.g., Uppy's 'upload-success', YJS's 'stack-item-added')
  • Custom events for specific features

No inconsistent usage of editor events was found that needs to be converted to use EditorEvents.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for string literals that might be event names
rg -i "\.on\(['\"].*['\"]" --type ts

Length of output: 90


Script:

#!/bin/bash
# Search for .on() method calls with different patterns
rg "\.on\(" --type ts -A 1

# Also search specifically for string event names
rg "\.on\(\s*['\"]" --type ts

# Look for EditorEvents enum usage
ast-grep --pattern 'EditorEvents.$_'

Length of output: 18305

packages/core/src/create/create-editor.ts (1)

66-68: Clarify how changes address image rendering issues.

The PR aims to fix issues with inline elements within images, but it's unclear how the editor creation changes address this. Please explain:

  1. How does the new plugin application order affect image rendering?
  2. What was the root cause of the inline element issues?
  3. Are there test cases that verify the fix?

Let's check for related image handling code:

Also applies to: 87-88

packages/core/src/create/create-editor.ts Outdated Show resolved Hide resolved
packages/core/src/create/create-editor.ts Outdated Show resolved Hide resolved
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: 0

🧹 Outside diff range and nitpick comments (3)
.changeset/dry-zebras-tan.md (1)

7-7: Please add an English description of the changes.

The current description is in Chinese. To improve accessibility for all contributors, please add an English translation that explains:

  • What was the issue (image rendering with nested inline elements)
  • What changes were made to fix it
  • Any important implementation details
packages/core/src/create/create-editor.ts (1)

Line range hint 125-143: Use EditorEvents constant for event emission.

While event handling has been updated to use EditorEvents constants, there's an inconsistency in event emission:

- promiseResolveThen(() => editor.emit('created'))
+ promiseResolveThen(() => editor.emit(EditorEvents.CREATED))
packages/core/src/config/interface.ts (1)

27-44: LGTM: Well-documented editor events

The EditorEvents constant is well-structured and thoroughly documented. The use of 'as const' ensures type safety for the event names.

Consider adding @SInCE tags to the JSDoc to track when these events were introduced:

 /**
  * EditorEvents 包含所有编辑器的生命周期事件。
  *
+ * @since 1.0.0
  * @property {string} CREATED - 编辑器创建后触发,用于初始化操作。
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8d57fd3 and d9f0c37.

📒 Files selected for processing (7)
  • .changeset/dry-zebras-tan.md (1 hunks)
  • packages/core/src/config/interface.ts (3 hunks)
  • packages/core/src/create/create-editor.ts (4 hunks)
  • packages/core/src/create/helper.ts (7 hunks)
  • packages/core/src/menus/bar/HoverBar.ts (2 hunks)
  • packages/core/src/menus/bar/Toolbar.ts (9 hunks)
  • packages/core/src/text-area/TextArea.ts (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/core/src/create/helper.ts
  • packages/core/src/menus/bar/Toolbar.ts
  • packages/core/src/text-area/TextArea.ts
🔇 Additional comments (9)
.changeset/dry-zebras-tan.md (1)

1-4: LGTM on version bumps.

The patch version increments are appropriate since these changes fix a bug without introducing breaking changes, following semantic versioning principles.

packages/core/src/create/create-editor.ts (3)

6-39: Well-structured imports and constants!

Good improvements in code organization:

  • Using typed events through EditorEvents
  • Properly structured i18n messages
  • Clear separation of configuration concerns

46-68: Clean implementation of plugin composition!

The refactoring improves code readability by:

  • Separating editor creation from plugin application
  • Using functional composition for plugin chain
  • Maintaining clear type safety with ICreateOption

87-92: Enhance documentation for disabled content normalization.

While the comment explains the reason for disabling normalization, it would be helpful to:

  1. Provide specific examples of formats that would break with normalization
  2. Document any potential side effects on the editor's behavior
  3. Add test cases demonstrating the need for this change
packages/core/src/config/interface.ts (3)

8-10: LGTM: Clean import structure

The new imports from 'slate' are well-organized and necessary for the type definitions.


46-46: LGTM: Type-safe event type definition

The EditorEventType is properly defined using TypeScript's type system features.


247-255: Consider adding runtime validation for mutually exclusive properties

The types look good, but content and html properties in ICreateOption appear to be mutually exclusive. Consider adding runtime validation to ensure only one is provided.

Let's check if there's any validation in the codebase:

Consider adding a type guard or validation function:

export function validateCreateOption(options: ICreateOption): void {
  if (options.content && options.html) {
    throw new Error('Cannot provide both content and html properties');
  }
}
packages/core/src/menus/bar/HoverBar.ts (2)

12-12: LGTM! Good practice using typed event constants.

The addition of EditorEvents import enhances type safety by replacing string literals with typed constants.


84-84: LGTM! Consistent use of typed event constants.

The changes improve type safety and maintainability by using EditorEvents constants instead of string literals.

Let's verify the event constant definitions match the usage:

Also applies to: 89-89, 92-93

✅ Verification successful

Based on the search results, I can now generate the final response since I have found both the event constant definitions and their usage across the codebase.

Event constant definitions match the usage perfectly

The changes are verified to be correct. The EditorEvents interface in packages/core/src/config/interface.ts defines all the constants used:

  • CHANGE: 'change'
  • SCROLL: 'scroll'
  • FULLSCREEN: 'fullscreen'
  • UNFULLSCREEN: 'unFullScreen'

These constants are consistently used across multiple files including TextArea.ts, create-editor.ts, and Toolbar.ts, showing a codebase-wide adoption of these typed constants.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify EditorEvents interface contains the used event constants
# and that they match the string values being replaced

# Search for EditorEvents interface definition
echo "Searching for EditorEvents interface definition..."
rg -p "interface EditorEvents" -A 10

# Search for any other usage of these events to ensure consistency
echo "Checking other event usages..."
rg "CHANGE|SCROLL|FULLSCREEN|UNFULLSCREEN" --type ts

Length of output: 2923

@cycleccc cycleccc merged commit 41c886e into master Oct 24, 2024
2 checks passed
cycleccc added a commit that referenced this pull request Oct 24, 2024
* style: refactor by new eslint

* style: refactor code style

* style: abbreviated logic

* style: extract the init content function

* Create dry-zebras-tan.md

* docs: add en notes

* style: extract editor event  and create option type
This was referenced Oct 28, 2024
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