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

Inject Intl polyfills where used #20798

Merged
merged 3 commits into from
May 29, 2024
Merged

Inject Intl polyfills where used #20798

merged 3 commits into from
May 29, 2024

Conversation

steverep
Copy link
Member

@steverep steverep commented May 15, 2024

Proposed change

Injects the Intl polyfill where needed using the custom Babel plugin and removes manual imports. I left the import in localize for now (see review comment to potentially remove).

This mostly keeps the status quo except automated and injects the polyfill in a few extra places where Intl is used in dependencies (rrule, chart.js, app-datepicker, etc.). As a follow up, the different polyfills should be broken up into pieces so that each is deferred as much as possible.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (thank you!)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Example configuration

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue or discussion:
  • Link to documentation pull request:

Checklist

  • The code change is tested and works locally.
  • There is no commented out code in this PR.
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

Summary by CodeRabbit

  • New Features

    • Enhanced polyfill support for various internationalization features.
    • Improved handling of Intl methods for better localization and formatting.
  • Refactor

    • Simplified and streamlined logic for internationalization across multiple components.
    • Removed redundant intl-polyfill imports to optimize performance.
  • Bug Fixes

    • Refined plugin injection logic to prevent self-injection of polyfills, ensuring more reliable builds.

These updates collectively enhance the overall user experience by providing better localization and formatting support while optimizing the application's performance.

@github-actions github-actions bot added the Build Related to building the code label May 15, 2024
@steverep steverep marked this pull request as ready for review May 16, 2024 02:49
Copy link
Contributor

coderabbitai bot commented May 24, 2024

Walkthrough

Walkthrough

The changes primarily focus on enhancing internationalization support by updating polyfill management and simplifying the codebase. This includes adding new polyfill entries, refining plugin injection logic, and removing redundant imports. Additionally, various modules have been streamlined to directly utilize Intl methods without conditional checks, ensuring consistent behavior across different components and functions.

Changes

Files Change Summary
build-scripts/babel-plugins/custom-polyfill-plugin.js Added new polyfill entries for Intl methods and defined POLYFILL_DIR.
build-scripts/bundle.cjs Refined plugin injection logic and updated exclusion list for polyfills.
src/common/datetime/first_weekday.ts, src/common/datetime/format_date.ts, src/common/datetime/format_date_time.ts, src/common/datetime/format_duration.ts, src/common/datetime/format_time.ts, src/common/datetime/localize_date.ts, src/common/datetime/relative_time.ts, src/common/string/format-list.ts, src/components/ha-country-picker.ts, src/components/ha-currency-picker.ts, src/components/ha-language-picker.ts, src/data/automation_i18n.ts Removed import of intl-polyfill.
src/resources/polyfills/intl-polyfill.ts Updated import path for getLocalLanguage.
src/common/language/format_language.ts Simplified formatLanguageCodeMem function by removing conditional checks for Intl.
src/common/number/format_number.ts Removed conditional check for Intl in formatNumber function.
src/components/ha-country-picker.ts Refactored _getOptions method to directly instantiate Intl.DisplayNames.
src/components/ha-currency-picker.ts Refined logic for currency symbol retrieval and refactored _getOptions method.
src/common/translations/localize.ts Updated import paths and restructured asynchronous import for IntlMessageFormat.

Sequence Diagram(s) (Beta)

sequenceDiagram
    participant User
    participant Component
    participant IntlAPI
    participant Polyfill

    User->>Component: Request for formatted date
    Component->>IntlAPI: Check for Intl support
    alt Intl supported
        IntlAPI-->>Component: Provide formatted date
    else Intl not supported
        Component->>Polyfill: Load necessary polyfill
        Polyfill-->>Component: Provide polyfill methods
        Component->>IntlAPI: Use polyfill methods
        IntlAPI-->>Component: Provide formatted date
    end
    Component-->>User: Return formatted date
Loading

This diagram illustrates how the component interacts with the Intl API to format a date, using polyfills if necessary.


Recent Review Details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits Files that changed from the base of the PR and between 362015f and ce09949.
Files selected for processing (4)
  • src/common/language/format_language.ts (1 hunks)
  • src/common/number/format_number.ts (2 hunks)
  • src/components/ha-country-picker.ts (2 hunks)
  • src/components/ha-currency-picker.ts (3 hunks)
Additional Context Used
Biome (11)
src/common/language/format_language.ts (1)

1-2: All these imports are only used as types.

src/common/number/format_number.ts (5)

60-60: Do not shadow the global "isNaN" property.


73-73: Unexpected any. Specify a different type.


1-4: All these imports are only used as types.


4-5: All these imports are only used as types.


5-6: Some named imports are only used as types.

src/components/ha-country-picker.ts (3)

292-292: Forbidden non-null assertion.


299-299: Forbidden non-null assertion.


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

src/components/ha-currency-picker.ts (2)

195-195: Forbidden non-null assertion.


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

Additional comments not posted (2)
src/common/language/format_language.ts (1)

15-20: Simplified memoization of Intl.DisplayNames creation enhances code clarity and maintainability.

src/components/ha-country-picker.ts (1)

284-287: Direct instantiation of Intl.DisplayNames in _getOptions simplifies the code and improves performance by avoiding unnecessary conditional checks.


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 full the 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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: 6

Outside diff range and nitpick comments (5)
src/components/ha-language-picker.ts (2)

Line range hint 2-2: Optimize imports by using type-only imports where applicable.

- import { css, CSSResultGroup, html, LitElement, PropertyValues } from "lit";
+ import type { CSSResultGroup, PropertyValues } from "lit";
+ import { css, html, LitElement } from "lit";
- import { customElement, property, query, state } from "lit/decorators";
+ import type { PropertyValues } from "lit";
+ import { customElement, property, query, state } from "lit/decorators";

Also applies to: 9-11


Line range hint 92-95: Avoid non-null assertions to ensure better type safety.

- @query("ha-select") private _select!: HaSelect;
+ @query("ha-select") private _select?: HaSelect;
src/data/automation_i18n.ts (3)

Line range hint 2-2: Optimize imports by using type-only imports where applicable.

- import { HassConfig } from "home-assistant-js-websocket";
+ import type { HassConfig } from "home-assistant-js-websocket";
- import { Condition, ForDict, Trigger } from "./automation";
+ import type { Condition, ForDict, Trigger } from "./automation";
- import { DeviceCondition, DeviceTrigger } from "./device_automation";
+ import type { DeviceCondition, DeviceTrigger } from "./device_automation";
- import { EntityRegistryEntry } from "./entity_registry";
+ import type { EntityRegistryEntry } from "./entity_registry";
- import { FrontendLocaleData } from "./translation";
+ import type { FrontendLocaleData } from "./translation";

Also applies to: 13-21


Line range hint 57-57: Use template literals for better readability and consistency.

- msg += ": " + error.message;
+ msg = `${msg}: ${error.message}`;

Also applies to: 81-81, 713-713


Line range hint 75-75: Specify a more precise type than any.

Consider using a more specific error type or a custom error type that better describes the expected errors in this context.

Also applies to: 707-707

src/common/datetime/relative_time.ts Show resolved Hide resolved
src/common/string/format-list.ts Show resolved Hide resolved
src/common/datetime/first_weekday.ts Show resolved Hide resolved
src/common/datetime/format_duration.ts Show resolved Hide resolved
src/common/datetime/format_time.ts Show resolved Hide resolved
src/common/datetime/format_date.ts 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: 9

Outside diff range and nitpick comments (12)
src/components/ha-currency-picker.ts (1)

Line range hint 201-201: Avoid using non-null assertions as they can lead to runtime errors. Consider adding proper null checks or handling the undefined case.

- currencyDisplayNames ? currencyDisplayNames.of(currency)! : currency
+ currencyDisplayNames ? currencyDisplayNames.of(currency) ?? currency : currency
src/components/ha-country-picker.ts (1)

Line range hint 296-296: It's safer to avoid non-null assertions. Consider handling the potential null case explicitly to prevent runtime errors.

- countryDisplayNames.of(country)!
+ countryDisplayNames.of(country) ?? country

Also applies to: 303-303

src/common/translations/localize.ts (3)

Line range hint 37-37: Specify more accurate types instead of any to enhance type safety and maintainability.

- catch (err: any) {
+ catch (err: unknown) {

Also applies to: 55-55, 123-123, 141-141


Line range hint 112-112: Avoid non-null assertions to prevent potential runtime errors. Consider handling the null case explicitly.

- cache._localizationCache![messageKey] = translatedMessage;
+ if (cache._localizationCache) {
+   cache._localizationCache[messageKey] = translatedMessage;
+ }

Also applies to: 126-126


Line range hint 124-124: Use template literals for string concatenation to improve readability and performance.

- return "Translation error: " + err.message;
+ return `Translation error: ${err.message}`;

Also applies to: 148-148

src/components/ha-language-picker.ts (2)

Line range hint 1-1: Optimize imports by using type-only imports where applicable.

- import { css, CSSResultGroup, html, LitElement, PropertyValues } from "lit";
+ import type { CSSResultGroup, PropertyValues } from "lit";
+ import { css, html, LitElement } from "lit";

Line range hint 91-94: Avoid non-null assertions as they can lead to runtime errors if assumptions fail.

Consider adding null checks or handling potential null values gracefully to ensure robustness.

src/data/automation_i18n.ts (5)

Line range hint 56-56: Use template literals for better readability and maintainability.

- let msg = "Error in describing trigger";
- if (error.message) {
-   msg += ": " + error.message;
- }
+ let msg = `Error in describing trigger: ${error.message || ''}`;

Also applies to: 80-80, 712-712


Line range hint 74-74: Specify a more precise type than any to improve type safety.

Consider using a more specific error type or a custom error interface instead of any to enhance type safety and clarity.

Also applies to: 706-706


Line range hint 261-261: Avoid non-null assertions to prevent runtime errors.

Consider adding null checks or handling potential null values gracefully to ensure robustness.

Also applies to: 1002-1002, 1013-1013


Line range hint 401-401: Use Number.parseInt instead of the global parseInt for better clarity and safety.

- seconds = parseInt(trigger.seconds.substring(1));
+ seconds = Number.parseInt(trigger.seconds.substring(1), 10);

Also applies to: 402-402, 430-430


Line range hint 405-405: Use Number.isNaN instead of isNaN for type safety.

- if (isNaN(seconds) || seconds > 59 || seconds < 0 || (seconds_interval && seconds === 0)) {
+ if (Number.isNaN(seconds) || seconds > 59 || seconds < 0 || (seconds_interval && seconds === 0)) {

src/common/datetime/relative_time.ts Show resolved Hide resolved
src/common/string/format-list.ts Show resolved Hide resolved
src/common/datetime/first_weekday.ts Show resolved Hide resolved
src/common/datetime/format_duration.ts Show resolved Hide resolved
src/components/ha-language-picker.ts Show resolved Hide resolved
src/common/datetime/format_date.ts Show resolved Hide resolved
src/common/datetime/format_time.ts Show resolved Hide resolved
src/common/datetime/format_date.ts Show resolved Hide resolved
src/common/datetime/format_date_time.ts Show resolved Hide resolved
@silamon
Copy link
Contributor

silamon commented May 26, 2024

I think there's something broken in the polyfill support for this one, but not sure how I could explain precisely. The polyfill get's injected clearly, but the sensor widgets with a value number or datetime fail to show up.

Some errors (multiple of the same error) are throw in this piece of code:

try {
return new Intl.NumberFormat(
locale,
getDefaultFormatOptions(num, options)
).format(Number(num));
} catch (err: any) {
// Don't fail when using "TEST" language
// eslint-disable-next-line no-console
console.error(err);
return new Intl.NumberFormat(
undefined,
getDefaultFormatOptions(num, options)
).format(Number(num));
}

Error: Missing locale data for
at invariant (utils.js:8:1)
at ResolveLocale (ResolveLocale.js:22:1)
at InitializeNumberFormat (InitializeNumberFormat.js:33:1)
at new exports.NumberFormat (core.js:37:1)
at formatNumber (format_number.ts:70:14)

@steverep
Copy link
Member Author

steverep commented May 26, 2024

That try/catch is funky and should be fixed in another PR. What locale are you using? Can you give me steps to reproduce that?

@silamon
Copy link
Contributor

silamon commented May 28, 2024

That try/catch is funky and should be fixed in another PR. What locale are you using? Can you give me steps to reproduce that?

Legacy build, English locale and setting Intl = {} in the index.html. What's your test procedure for this one?

@steverep
Copy link
Member Author

Legacy build, English locale and setting Intl = {} in the index.html. What's your test procedure for this one?

You cannot fully undo the Intl API (even IE 11 supports some of it). Either set individual objects to undefined or just switch the various shouldPolyfill conditionals to true.

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

Outside diff range comments (1)
src/components/ha-country-picker.ts (1)

Line range hint 292-292: Remove non-null assertions to handle potential undefined values safely.

- countryDisplayNames.of(country)!
+ countryDisplayNames.of(country) ?? 'Unknown Country'

Also applies to: 299-299

src/components/ha-currency-picker.ts Show resolved Hide resolved
src/common/number/format_number.ts Show resolved Hide resolved
@bramkragten bramkragten merged commit 7748315 into dev May 29, 2024
13 checks passed
@bramkragten bramkragten deleted the inject-intl-polyfill branch May 29, 2024 12:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Build Related to building the code cla-signed
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants