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

refactor: extract i18n to class module #176

Merged
merged 1 commit into from
Dec 30, 2024
Merged

Conversation

zzxming
Copy link
Collaborator

@zzxming zzxming commented Dec 28, 2024

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Introduced a new internationalization (i18n) module for the FluentEditor
    • Enhanced language handling and configuration options
  • Refactor

    • Restructured language configuration to use a more modular approach
    • Updated event handling for language changes
    • Simplified access to language-specific text properties
  • Bug Fixes

    • Improved error handling for language text retrieval
    • Added checks to prevent potential errors when accessing language options

Copy link

coderabbitai bot commented Dec 28, 2024

Warning

Rate limit exceeded

@zzxming has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 13 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 0605cca and 9f8fdba.

📒 Files selected for processing (10)
  • packages/docs/fluent-editor/demos/i18n-custom.vue (1 hunks)
  • packages/docs/fluent-editor/demos/i18n.vue (1 hunks)
  • packages/fluent-editor/src/config/types/editor-config.interface.ts (1 hunks)
  • packages/fluent-editor/src/counter/index.ts (4 hunks)
  • packages/fluent-editor/src/custom-clipboard.ts (2 hunks)
  • packages/fluent-editor/src/fluent-editor.ts (5 hunks)
  • packages/fluent-editor/src/i18n/index.ts (1 hunks)
  • packages/fluent-editor/src/link/modules/tooltip.ts (1 hunks)
  • packages/fluent-editor/src/table/modules/table-operation-menu.ts (2 hunks)
  • packages/fluent-editor/src/toolbar/toolbar-tip.ts (2 hunks)

Walkthrough

The pull request introduces a comprehensive refactoring of the internationalization (i18n) configuration in the FluentEditor. The changes centralize language settings by introducing an i18n object that replaces the previous top-level lang and langText properties. This modification affects multiple components across the editor, including configuration interfaces, event handling, and language text access. The restructuring aims to improve the organization and modularity of language-related functionality within the editor.

Changes

File Change Summary
packages/fluent-editor/src/config/types/editor-config.interface.ts - Removed lang and langText properties
- Added i18n object with lang and langText
- Updated file upload method signatures
packages/fluent-editor/src/fluent-editor.ts - Added lang and langText properties
- Removed language resolution logic
- Registered i18n module
packages/fluent-editor/src/i18n/index.ts - Added new I18N module
- Implemented I18NOptions interface
- Created methods for language management
Demo files (packages/docs/fluent-editor/demos/) - Updated i18n-custom.vue and i18n.vue to use new i18n configuration
Various modules - Updated event handling from this.quill.on to this.quill.emitter.on
- Changed language text access from options.langText to langText

Suggested labels

refactoring, i18n, configuration

Suggested reviewers

  • kagol

Possibly related PRs

Poem

🐰 A Rabbit's Ode to Internationalization 🌍

Configs once scattered, now neatly aligned,
Language settings beautifully refined.
With i18n module, our editor speaks clear,
Translations dancing, bringing cultures near!
Code hops with joy, boundaries fade away! 🚀


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

@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 (11)
packages/docs/fluent-editor/demos/i18n-custom.vue (1)

23-31: Encapsulate translation data in a separate language resource file.
Encouraging the use of a dedicated language resource file (or JSON) to store and organize localized strings can improve maintainability. It helps avoid large configuration objects and makes further translations easier to add.

packages/fluent-editor/src/config/types/editor-config.interface.ts (1)

17-20: Ensure clarity of file parameter typing.
Changing from an explicitly typed file: File to an untyped parameter may introduce confusion or potential runtime errors. You might consider adding a TypeScript interface or type alias for the file parameter, clarifying how it should be consumed.

packages/fluent-editor/src/i18n/index.ts (3)

5-8: Document usage of langText more extensively.
It would be helpful to add a simple explanatory comment about what langText typically contains (UI strings, button texts, etc.) and how it can be extended.


22-34: Fallback warnings are user-friendly, consider integrating logging for i18n analytics.
When a requested language isn’t supported, the console warns appropriately. To further enhance i18n QA, some teams log unsupported languages or usage patterns for analytics or monitoring.

Would you like me to show how to integrate a minimal logging utility for capturing these events?


41-48: Check for concurrency or race conditions if changeLanguage is invoked repeatedly.
If multiple calls happen in quick succession, ensure event listeners or intermediate states don’t cause race conditions. You might want to queue or debounce changes if that becomes an issue in production.

packages/fluent-editor/src/counter/index.ts (1)

36-36: Handle missing or undefined translations gracefully.
Accessing this.quill.langText.char or this.quill.langText.word is fine when language text is guaranteed. Otherwise, consider providing a safe fallback in case these keys don’t exist.

packages/fluent-editor/src/toolbar/toolbar-tip.ts (1)

23-24: Robust language handling with optional checks.
Using if (!this.quill.lang) return result is a nice safeguard to avoid undefined references. Just confirm that all code paths use a safe fallback if lang is not set.

packages/fluent-editor/src/fluent-editor.ts (1)

35-36: Explicit lang and langText fields.
Defining them directly on FluentEditor clarifies ownership and reduces confusion. Consider documenting their usage in a docstring to guide future maintainers.

packages/fluent-editor/src/table/modules/table-operation-menu.ts (3)

54-54: Consider syncing colorSubTitle on language change.
You update DEFAULT_COLOR_SUBTITLE after CHANGE_LANGUAGE_EVENT, but you do not update this.colorSubTitle. If a user configures a custom color title, the language change might cause DEFAULT_COLOR_SUBTITLE to shift, but the actual colorSubTitle remains stale.

 this.quill.on(CHANGE_LANGUAGE_EVENT, () => {
   this.destroy()
   this.DEFAULT_COLOR_SUBTITLE = this.quill.langText['sub-title-bg-color']
   this.setDefaultMenu()
+  this.colorSubTitle
+    = this.options.color && this.options.color.text
+      ? this.options.color.text
+      : this.DEFAULT_COLOR_SUBTITLE
 })

69-69: Avoid repeating the assignment to DEFAULT_COLOR_SUBTITLE.
The same assignment also appears in the constructor (line 54). While this is logical for re-initialization after the language changes, consider wrapping this logic in a helper method to reduce duplication.


75-75: Minor improvement: destructure longText from this.quill.
Destructuring can be more concise and consistent with the rest of the code’s style.

- const langText = this.quill.langText
+ const { langText } = this.quill
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 24be218 and 0605cca.

📒 Files selected for processing (10)
  • packages/docs/fluent-editor/demos/i18n-custom.vue (1 hunks)
  • packages/docs/fluent-editor/demos/i18n.vue (1 hunks)
  • packages/fluent-editor/src/config/types/editor-config.interface.ts (1 hunks)
  • packages/fluent-editor/src/counter/index.ts (4 hunks)
  • packages/fluent-editor/src/custom-clipboard.ts (2 hunks)
  • packages/fluent-editor/src/fluent-editor.ts (5 hunks)
  • packages/fluent-editor/src/i18n/index.ts (1 hunks)
  • packages/fluent-editor/src/link/modules/tooltip.ts (1 hunks)
  • packages/fluent-editor/src/table/modules/table-operation-menu.ts (2 hunks)
  • packages/fluent-editor/src/toolbar/toolbar-tip.ts (2 hunks)
🔇 Additional comments (15)
packages/docs/fluent-editor/demos/i18n.vue (2)

24-26: Initialization with reactive lang property looks appropriate.
This approach is straightforward, ensuring that changes in lang.value propagate correctly through the editor’s i18n module.


33-33: Check error handling when calling getModule('i18n').
If the i18n module is absent for any reason, a null/undefined return may cause runtime errors. Consider gracefully handling scenarios where the i18n module has not been registered or loaded.

Want me to add a fallback check here to avoid disruptions if the module fails to load?

packages/fluent-editor/src/i18n/index.ts (2)

1-4: Imports and default exports are well-organized.
The import structure is clear and descriptive, aiding readability.


36-39: Synchronize with the new quill.langText fields.
Updating both this.quill.langText and this.quill.lang is a succinct approach. Ensure no conflicting leftover references to old langText or direct lang usage continue in the code elsewhere.

packages/fluent-editor/src/counter/index.ts (3)

14-14: Great consistency in event refactoring.
The switch from quill.on to this.quill.emitter.on aligns well with the broader refactor, ensuring consistency and centralization of event handling throughout the codebase.


25-25: Directly accessing langText is clear and concise.
Referencing this.quill.langText['counter-template'] keeps the code straightforward and consistent with the new i18n approach. Just confirm that this key always exists to avoid potential runtime errors.


46-46: Ensure fallback for 'counter-limit-tips' key.
Similarly, verify that 'counter-limit-tips' exists in this.quill.langText to avoid potential edge cases if the translation key is missing.

packages/fluent-editor/src/toolbar/toolbar-tip.ts (1)

14-14: Consistent transition to emitter for language event.
This is in line with the codebase refactor. Good job maintaining a uniform approach for handling CHANGE_LANGUAGE_EVENT across modules.

packages/fluent-editor/src/fluent-editor.ts (4)

6-6: Consolidated imports look good.
Importing getListValue, ICONS_CONFIG, and inputFile from ./config keeps relevant utilities in one place, aligning with the modular design of the refactor.


17-17: i18n module import is well-organized.
Introducing { I18N } here centralizes language handling and is consistent with the pull request goal of extracting and modularizing i18n functionality.


51-51: Activating i18n by default.
Setting 'i18n': true in the defaults ensures the feature is always available, supporting a straightforward internationalization setup.


164-164: Registering the i18n module as core functionality.
Adding 'modules/i18n': I18N seamlessly integrates the module into FluentEditor, highlighting i18n's importance in your architecture.

packages/fluent-editor/src/link/modules/tooltip.ts (2)

43-43: Consistent event handling approach.
Transitioning from this.quill.on to this.quill.emitter.on matches the refactoring in other classes, creating a uniform event orchestration pattern.


50-50: Safely reference linkplaceholder.
Using this.quill.langText?.linkplaceholder is good, but verify that a sensible fallback is provided if the property is missing or undefined.

packages/fluent-editor/src/custom-clipboard.ts (1)

474-474: Ensure the i18n key 'img-error' is always defined.
If the 'img-error' key is missing or changes, the fallback logic may not work as expected. Consider providing a default message to ensure stable behavior.

export class FluentEditor extends Quill {
isFullscreen: boolean = false
options: IEditorConfig & ExpandedQuillOptions
lang: string
langText: Record<string, string>
Copy link
Member

@kagol kagol Dec 30, 2024

Choose a reason for hiding this comment

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

@zzxming 这两个变量为什么从 quill.options 移到了 quill 呢?直接放到 quill 中和放到 quill.options 中,一般如何选择呢?
另外是不是从 i18n 模块也能获取这两个变量,比如:this.quill.getModule('i18n').options.lang,这样是不是就重复了?

之前可能是没有抽取 i18n 模块,所以需要有一个地方承载 lang / langText,现在有 i18n 模块了,我觉得挂在 quill 的这两个变量是没有必要的。

不过这个不太要紧,我先合入,可以后续持续优化。

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

你说的有道理,这个是我在删依赖包的时候顺手改的,没注意太多。

但是我觉得在 this.quill 上挂 lang 这个变量还是有用的,i18n 是处理编辑器内文字的,有这个也可以更方便的获取当前编辑器的语,可以挂 getter,这样要修改还是要通过 changeLanguage 改,但是获取可以直接 quill.lang 获取。langText我可以抽离一个函数去获取对应文本,这样也不用每次获取文本都要写一长串了

@kagol kagol merged commit 47d74dd into opentiny:main Dec 30, 2024
2 checks passed
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.

2 participants