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 some components #1417

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from

Conversation

PrographerMan
Copy link
Contributor

@PrographerMan PrographerMan commented Mar 11, 2023

Summary by CodeRabbit

Release Notes

  • New Features

    • Improved localization of error messages across various components using the translationMacro.
    • Added a new method isNameOfCurrentComponent to enhance component name checks.
    • Introduced a function to generate new route names for edit forms.
  • Bug Fixes

    • Simplified logic for determining button captions and menu item titles.
  • Refactor

    • Streamlined translation handling in multiple components for better readability and maintainability.
    • Refactored existing methods to use Ember.computed for consistency.
  • Chores

    • Updated imports to utilize the new translation macro for improved internationalization practices.

@sonarcloud
Copy link

sonarcloud bot commented Mar 11, 2023

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 0 Code Smells

No Coverage information No Coverage information
No Duplication information No Duplication information

@TeterinaSvetlana TeterinaSvetlana changed the base branch from feature-ember-update to develop October 23, 2024 10:17
@@ -98,14 +98,14 @@ export default FlexberryBaseComponent.extend({
saveAdvLimit: function() {
this._hideMessage();
const advLimitName = this.get('model.advLimitName');
if (isBlank(advLimitName)) {
this._showMessage('warning', this.get('i18n').t('components.advlimit-dialog-content.enter-setting-name'));
if (Ember.isBlank(advLimitName)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

просто isBlank

return typeOf(caption) === 'string' && $.trim(caption) !== '' ||
typeOf(isHTMLSafe) === 'function' && isHTMLSafe(caption) && $.trim(get(caption, 'string')) !== '' ||
caption instanceof htmlSafe && $.trim(get(caption, 'string')) !== '';
_hasCaption: Ember.computed('caption', function () {
Copy link
Contributor

Choose a reason for hiding this comment

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

просто computed

_hasCaption: Ember.computed('caption', function () {
const caption = this.get('caption');

if (Ember.isEmpty(caption)) return false;
Copy link
Contributor

Choose a reason for hiding this comment

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

isEmpty и добавить в импорт


return isCaptionTypeIsString && isCaptionNotEmpty
|| isHTMLSafeDefined && isCaptionSafe && isStringOfCaptionEmpty === false
|| caption instanceof Ember.Handlebars.SafeString && isStringOfCaptionEmpty === false;
Copy link
Contributor

Choose a reason for hiding this comment

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

везде где Ember.что-то убрать Ember и добавить в импорт если надо

@@ -1189,8 +1190,8 @@ export default FlexberryBaseComponent.extend({
}
};

later((function() {
modelController.transitionToRoute(editFormRoute + '.new', transitionOptions);
Ember.run.later((function() {
Copy link
Contributor

Choose a reason for hiding this comment

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

просто later?

@@ -255,8 +258,7 @@ export default FlexberryBaseComponent.extend({
@property colsSettingsItems
@readOnly
*/
colsSettingsItems: computed('i18n.locale', 'userSettingsService.isUserSettingsServiceEnabled', function() {
let i18n = this.get('i18n');
colsSettingsItems: Ember.computed('i18n.locale', 'userSettingsService.isUserSettingsServiceEnabled', function() {
Copy link
Contributor

Choose a reason for hiding this comment

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

везде где Ember.что-то убрать Ember и добавить в импорт если надо

@@ -2,10 +2,9 @@
@module ember-flexberry
*/

import Mixin from '@ember/object/mixin';
Copy link
Contributor

Choose a reason for hiding this comment

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

без этого импорта работает разве?

@@ -71,13 +70,12 @@ export default Mixin.create({
@property formSuccessMessageCaption.
@type String
*/
formSuccessMessageCaption: computed('i18n.locale', 'latestOperationType', function() {
let i18n = this.get('i18n');
formSuccessMessageCaption: Ember.computed('i18n.locale', 'latestOperationType', function() {
Copy link
Contributor

Choose a reason for hiding this comment

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

везде где Ember.что-то убрать Ember и добавить в импорт если надо

@@ -2,6 +2,8 @@
@module ember-flexberry
*/

import Ember from 'ember';
Copy link
Contributor

Choose a reason for hiding this comment

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

этот импорт вроде не нужен

@@ -4,6 +4,8 @@

import Mixin from '@ember/object/mixin';
import { merge } from '@ember/polyfills';
import Ember from 'ember';
Copy link
Contributor

Choose a reason for hiding this comment

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

не нужно

Copy link

coderabbitai bot commented Oct 24, 2024

Walkthrough

The changes in this pull request focus on enhancing localization and improving code clarity across multiple components and mixins in the Ember application. Key modifications include the introduction of the translationMacro for translating messages, replacing direct calls to the i18n service. Additionally, several components have been updated to utilize a new method for checking component names, which streamlines logic and enhances maintainability. Other changes involve refactoring methods for improved readability and consistency, particularly in computed properties and action handlers.

Changes

File Change Summary
addon/components/advlimit-dialog-content.js Introduced translationMacro for translations; updated apply, check, and saveAdvLimit methods; replaced isBlank utility with Ember.isBlank.
addon/components/flexberry-base-component.js Added isNameOfCurrentComponent method for component name checking.
addon/components/flexberry-button.js Simplified _hasCaption computed property logic; replaced direct references with Ember counterparts.
addon/components/flexberry-file.js Replaced i18n service calls with translationMacro in error message methods.
addon/components/flexberry-lookup.js Updated private methods to use isNameOfCurrentComponent and replaced i18n with t for localization.
addon/components/flexberry-objectlistview.js Added import for getNewRouteNameOfEditForm; updated createNewByPrototype and setMenuWidth methods for improved routing logic and name checking.
addon/components/groupedit-toolbar.js Replaced direct component name checks with isNameOfCurrentComponent in _rowSelected and _rowsDeleted methods.
addon/components/mobile/flexberry-file.js Updated menu item titles to use t for localization instead of i18n.
addon/components/mobile/flexberry-objectlistview.js Replaced i18n.t with t in _mobileSortingSettingsCaption for localization.
addon/components/mobile/object-list-view.js Introduced translationMacro to replace i18n.t in _checkRowsSettingsItems.
addon/components/object-list-view-row.js Refactored customButtonInRowAction method from if-else to switch statement.
addon/components/object-list-view.js Refactored columns computed property; added _conditionsByType method for filter conditions; updated _setContent to use isNameOfCurrentComponent.
addon/components/olv-toolbar.js Added imports for routing and translation; updated computed properties and actions to use t for localization.
addon/mixins/edit-form-controller-operations-indication.js Updated computed properties to use Ember.computed and translationMacro for localization.
addon/mixins/flexberry-lookup-controller.js Updated previewLookupValue action to use translationMacro for setting modal titles.
addon/mixins/flexberry-objectlistview-route.js Replaced i18n.t with t in objectListViewRowClick action for error message localization.
addon/utils/routes-names-builder.js Added getNewRouteNameOfEditForm function for route name generation.

Poem

In the garden of code, changes bloom bright,
With macros for translation, everything's right.
Components now sing, with clarity and grace,
A rabbit hops happily, in this coding space! 🐇✨
With each little tweak, our app's growing strong,
Join in the dance, as we all sing along!


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

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

🧹 Outside diff range and nitpick comments (10)
addon/components/mobile/flexberry-file.js (2)

Line range hint 4-5: Add missing import for translation macro.

The code uses the t() function but doesn't import it. This would cause runtime errors.

Add the following import:

 import { computed  } from '@ember/object';
+import { t } from 'ember-i18n/macro';
 import FlexberryFile from './../flexberry-file';

Line range hint 28-28: Consider removing unnecessary dependency.

The computed property still depends on 'i18n.locale' but this might not be needed when using the t() macro as it handles locale changes automatically.

-  _menuItems: computed('showPreview', 'readonly', 'i18n.locale', '_uploadButtonIsVisible', '_downloadButtonIsVisible', function() {
+  _menuItems: computed('showPreview', 'readonly', '_uploadButtonIsVisible', '_downloadButtonIsVisible', function() {
addon/components/flexberry-button.js (1)

73-86: Consider extracting caption handling logic to a utility function.

The caption validation logic could be beneficial for other components. Consider extracting it to a shared utility function to improve reusability and testability.

Example structure:

// utils/string-helpers.js
export function hasValidCaption(caption) {
  if (isEmpty(caption)) {
    return false;
  }

  const trimmedCaption = $.trim(caption);
  
  if (typeOf(caption) === 'string') {
    return trimmedCaption !== '';
  }

  if (isHTMLSafe(caption)) {
    return $.trim(get(caption, 'string')) !== '';
  }

  return false;
}

// In component:
_hasCaption: computed('caption', function() {
  return hasValidCaption(get(this, 'caption'));
}),
addon/components/mobile/object-list-view.js (1)

125-126: LGTM! Correct usage of translation macro.

The replacement of i18n.t with the translation macro is implemented correctly and maintains the existing functionality.

Consider reducing duplication by combining the title and titleKey logic:

-      let checkAllAtPageTitle = isUncheckAllAtPage ? t('components.olv-toolbar.uncheck-all-at-page-button-text') :
-      t('components.olv-toolbar.check-all-at-page-button-text');
-      let checkAllAtPageTitleKey = isUncheckAllAtPage ? 'components.olv-toolbar.uncheck-all-at-page-button-text' :
-      'components.olv-toolbar.check-all-at-page-button-text';
+      let checkAllAtPageKey = `components.olv-toolbar.${isUncheckAllAtPage ? 'uncheck' : 'check'}-all-at-page-button-text`;
+      let checkAllAtPageTitle = t(checkAllAtPageKey);
+      let checkAllAtPageTitleKey = checkAllAtPageKey;

-      let checkAllTitle = allSelect ? t('components.olv-toolbar.uncheck-all-button-text') :
-      t('components.olv-toolbar.check-all-button-text');
-      let checkAllTitleKey = allSelect ? 'components.olv-toolbar.uncheck-all-button-text' :
-      'components.olv-toolbar.check-all-button-text';
+      let checkAllKey = `components.olv-toolbar.${allSelect ? 'uncheck' : 'check'}-all-button-text`;
+      let checkAllTitle = t(checkAllKey);
+      let checkAllTitleKey = checkAllKey;

Also applies to: 130-131

addon/mixins/edit-form-controller-operations-indication.js (1)

Line range hint 126-134: Potential XSS vulnerability in error message handling

The error messages are directly inserted as HTML without sanitization. If errorMessages contains user input or external data, this could lead to XSS vulnerabilities.

Consider either:

  1. Sanitizing the error messages before insertion
  2. Using plain text instead of HTML
-      errorMessages.forEach((currentErrorMessage) => {
-        message += '<li>' + currentErrorMessage + '</li>';
+      errorMessages.forEach((currentErrorMessage) => {
+        message += '<li>' + Ember.Handlebars.Utils.escapeExpression(currentErrorMessage) + '</li>';
       });
addon/components/mobile/flexberry-objectlistview.js (1)

280-284: Add null check for columnHeader.

The code assumes columnHeader will be defined after the translation call. Consider adding proper null checks to handle cases where the translation might not exist.

- let columnHeader = t(getAttrLocaleKey(this.get('modelName'), this.get('modelProjection').projectionName, column.key)).string;
- if (columnHeader !== undefined) {
-   let key = column.key.split('.')[0];
-   columnHeader = t(getAttrLocaleKey(this.get('modelName'), this.get('modelProjection').projectionName, key)).string;
- }
+ let columnHeader = t(getAttrLocaleKey(this.get('modelName'), this.get('modelProjection').projectionName, column.key))?.string;
+ if (!columnHeader) {
+   const key = column.key.split('.')[0];
+   columnHeader = t(getAttrLocaleKey(this.get('modelName'), this.get('modelProjection').projectionName, key))?.string || key;
+ }
addon/components/flexberry-base-component.js (1)

253-257: Add JSDoc documentation for the new method.

The method should follow the existing documentation pattern in the file. Also, remove the extra blank line for consistency.

+  /**
+    Checks if the given component name matches the current component's name.
+
+    @method isNameOfCurrentComponent
+    @param {String} componentName The name to compare against
+    @return {Boolean} True if names match, false otherwise
+   */
   isNameOfCurrentComponent(componentName) {
     const currentComponentName = this.get('componentName');
-    
     return currentComponentName === componentName;
   },
addon/components/groupedit-toolbar.js (1)

Line range hint 272-280: Refactor DOM manipulation to follow Ember best practices.

While the component name check improvement is good, there are some concerns with the DOM manipulation code:

  1. Using jQuery (this.$()) for DOM manipulation is deprecated in modern Ember and should be avoided.
  2. Direct DOM queries create tight coupling between the template and JavaScript logic.

Consider refactoring to use Ember's element modifiers or computed properties:

// In the component
@tracked selectedIndex;
@tracked totalRows;

@computed('selectedIndex')
get isFirstRowSelected() {
  return this.selectedIndex === 0;
}

@computed('selectedIndex', 'totalRows')
get isLastRowSelected() {
  return this.selectedIndex === this.totalRows - 1;
}

_rowSelected(componentName, record, count, checked, recordWithKey) {
  if (this.isNameOfCurrentComponent(componentName) && !this.get('isDestroying')) {
    this.set('_hasSelectedRows', count > 0);
    
    // Update these properties from your row selection logic
    this.selectedIndex = /* index of selected row */;
    this.totalRows = /* total number of rows */;
    
    this.set('_disableMoveUpButton', this.isFirstRowSelected);
    this.set('_disableMoveDownButton', this.isLastRowSelected);
  }
}

This approach:

  • Removes deprecated jQuery usage
  • Decouples the logic from DOM structure
  • Makes the code more maintainable and testable
addon/components/object-list-view-row.js (1)

282-292: LGTM! Consider enhancing error handling.

The switch statement refactoring improves readability. However, consider enhancing the error handling:

 customButtonInRowAction(action, model) {
+  if (!action) {
+    throw new Error('Action parameter is required for custom buttons in row.');
+  }
+
   switch (typeof action) {
     case 'function':
+      if (typeof model === 'undefined') {
+        throw new Error('Model parameter is required when executing function actions.');
+      }
       action(model);
       break;
     
     case 'string':
       this.sendAction('customButtonInRowAction', action, model);
       break;
     
     default:
-      throw new Error('Unsupported action type for custom buttons in row.');
+      throw new Error(`Unsupported action type '${typeof action}' for custom buttons in row. Expected 'function' or 'string'.`);
   }
 }
addon/components/object-list-view.js (1)

1440-1440: Add missing semicolon after 'contentLength' declaration

There's a missing semicolon after the declaration of contentLength.

Here's the fix:

- const contentLength = contentForRender.get('length')
+ const contentLength = contentForRender.get('length');
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d1c7d81 and 391e1ff.

📒 Files selected for processing (17)
  • addon/components/advlimit-dialog-content.js (5 hunks)
  • addon/components/flexberry-base-component.js (1 hunks)
  • addon/components/flexberry-button.js (1 hunks)
  • addon/components/flexberry-file.js (4 hunks)
  • addon/components/flexberry-lookup.js (5 hunks)
  • addon/components/flexberry-objectlistview.js (3 hunks)
  • addon/components/groupedit-toolbar.js (2 hunks)
  • addon/components/mobile/flexberry-file.js (1 hunks)
  • addon/components/mobile/flexberry-objectlistview.js (1 hunks)
  • addon/components/mobile/object-list-view.js (2 hunks)
  • addon/components/object-list-view-row.js (1 hunks)
  • addon/components/object-list-view.js (12 hunks)
  • addon/components/olv-toolbar.js (17 hunks)
  • addon/mixins/edit-form-controller-operations-indication.js (4 hunks)
  • addon/mixins/flexberry-lookup-controller.js (2 hunks)
  • addon/mixins/flexberry-objectlistview-route.js (2 hunks)
  • addon/utils/routes-names-builder.js (1 hunks)
🧰 Additional context used
🪛 Biome
addon/components/object-list-view.js

[error] 573-573: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

addon/components/olv-toolbar.js

[error] 19-19: Shouldn't redeclare 'getOwner'. Consider to delete it or rename it.

'getOwner' is defined here:

(lint/suspicious/noRedeclare)

🔇 Additional comments (24)
addon/utils/routes-names-builder.js (2)

1-5: LGTM! Good separation of concerns.

The function successfully centralizes the route name generation logic, making it more maintainable and consistent across the application.


1-5: Verify the impact of this change.

Let's verify how this utility is being used across the codebase to ensure all use cases are covered.

✅ Verification successful

Let me gather more context about how this utility is being used in the files that import it.


Based on the comprehensive analysis of the codebase, I can now provide a final response:

The utility function is properly used and its changes are safe

The getNewRouteNameOfEditForm utility function is consistently used across three components:

  • flexberry-objectlistview.js
  • flexberry-simpleolv.js
  • olv-toolbar.js

In all cases, it's used to construct the route name for new form transitions by appending '.new' to the base route name. This matches the established routing pattern seen throughout the codebase where new form routes consistently follow the pattern {base-route}.new with corresponding path {base-route}/new.

The implementation:

export default function getNewRouteNameOfEditForm(routeName) {
    const postfix = '.new';
    return `${routeName}${postfix}`;
}

maintains this convention and is used correctly in all its implementations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct string concatenation with '.new' that could be replaced with this utility
rg -g '!routes-names-builder.js' "\.new['\"]\s*\+" || rg -g '!routes-names-builder.js' "\.new\s*\+"

# Search for existing imports of this utility to verify proper adoption
rg "import.*getNewRouteNameOfEditForm.*from.*routes-names-builder"

Length of output: 513


Script:

#!/bin/bash
# Check usage in flexberry-objectlistview.js
rg -A 5 "getNewRouteNameOfEditForm" addon/components/flexberry-objectlistview.js

# Check usage in flexberry-simpleolv.js
rg -A 5 "getNewRouteNameOfEditForm" addon/components/flexberry-simpleolv.js

# Check usage in olv-toolbar.js
rg -A 5 "getNewRouteNameOfEditForm" addon/components/olv-toolbar.js

# Also search for any other occurrences of '.new' in route context
rg -g "!*.{json,md,txt}" "\.new" -C 3

Length of output: 35659

addon/components/mobile/flexberry-file.js (1)

39-39: Translation changes look good!

The conversion from this.get('i18n').t() to t() macro is consistent and maintains the same translation keys.

Also applies to: 47-47, 55-55, 62-62, 69-69

addon/mixins/flexberry-objectlistview-route.js (1)

73-73: LGTM! Good localization improvement

The switch to using the translation macro (t) instead of direct i18n service calls is a good practice that aligns with ember-i18n's recommendations and improves consistency across the codebase.

addon/components/advlimit-dialog-content.js (3)

5-5: LGTM! Good improvement in localization handling.

The introduction of translationMacro is a positive change that aligns with Ember's best practices for internationalization, reducing boilerplate code and improving maintainability.


87-89: LGTM! Consistent error message localization.

The conversion of error messages to use the translation macro is thorough and consistent throughout the component.

Also applies to: 108-108, 126-126


59-59: Verify consistency of translation keys across components.

Let's ensure the translation keys follow the same pattern across all components that have been updated as part of this refactoring effort.

Also applies to: 87-87, 89-89, 102-102, 108-108, 118-118, 120-120, 126-126

✅ Verification successful

Based on the shell script results, I can now generate the final response as we have sufficient information to verify the translation key consistency.

Translation keys follow consistent naming pattern across components

The search results show that the translation keys in advlimit-dialog-content.js follow a consistent pattern:

  • All keys are prefixed with components.advlimit-dialog-content.
  • The keys are used consistently across multiple files (advlimit-dialog.js, olv-toolbar.js, advlimit-dialog-content.js)
  • The translation macro t is imported correctly from 'ember-i18n' and used consistently

The translation keys follow the same hierarchical pattern used throughout the codebase, where other components also use the pattern components.<component-name>.<key>.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all translation keys used in components to verify consistency
rg -g '*.js' "components\.advlimit-dialog-content\." --type js

# Search for other components using translationMacro to compare patterns
rg -g '*.js' "import.*translationMacro.*from 'ember-i18n'" -A 5 --type js

Length of output: 28019

addon/components/mobile/object-list-view.js (1)

10-10: LGTM! Import of translationMacro follows conventions.

The addition of the translationMacro import aligns with the PR's localization improvements and follows common Ember conventions.

addon/mixins/edit-form-controller-operations-indication.js (1)

113-118: Same modernization applies here

The same modernization suggestions apply to this computed property as discussed above.

addon/components/flexberry-base-component.js (1)

253-257: Verify the method usage across components.

The method appears to be used by several components. Let's verify its usage to ensure all implementations are updated.

✅ Verification successful

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

Method isNameOfCurrentComponent is actively used across the codebase

The verification confirms that the method is indeed used in several components:

  • flexberry-lookup.js (3 usages)
  • groupedit-toolbar.js (2 usages)
  • flexberry-objectlistview.js (1 usage)
  • olv-toolbar.js (5 usages)
  • object-list-view.js (8 usages)
  • flexberry-simpleolv.js (10 usages)

Additionally, no direct component name comparisons were found, indicating that all components are properly using this method for component name checks.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of isNameOfCurrentComponent across components
# Expected: Find calls in the components mentioned in the summary

echo "Searching for direct usage of isNameOfCurrentComponent..."
rg "isNameOfCurrentComponent\(" addon/components/

echo -e "\nSearching for potential places where component name comparison is still done directly..."
rg "componentName\s*===?\s*['\"]" addon/components/

Length of output: 3451

addon/components/groupedit-toolbar.js (1)

295-298: LGTM!

The change to use isNameOfCurrentComponent improves code consistency and maintainability.

addon/components/object-list-view-row.js (1)

282-292: Verify custom button usage patterns.

Let's ensure this refactoring doesn't introduce breaking changes for existing custom button implementations.

✅ Verification successful

Let me gather more information about the usage patterns and implementation details to better understand the impact.


Let me try one more search pattern to find concrete examples of custom button usage and their action definitions.


Based on the comprehensive search results, I can now provide a final response about the custom button action handler refactoring:

The action handler implementation is safe and consistent with existing usage patterns

The verification shows that:

  • The switch statement handling both function and string action types is correctly implemented as it supports both:
    • Direct function handlers (case 'function')
    • Named actions that bubble up through sendAction (case 'string')
  • This pattern is consistently used across the component hierarchy:
    • flexberry-objectlistview and flexberry-groupedit components both implement the same action bubbling pattern
    • Template usage shows both patterns are actively used in the codebase
  • The error case for unsupported action types provides appropriate validation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for custom button configurations and usages
echo "Searching for custom button configurations..."
rg -l "customButtonInRowAction" --type js

echo -e "\nSearching for action parameter patterns..."
# Look for places where actions are passed to check their types
rg "customButtonInRowAction.*['\"]" --type js -A 2

Length of output: 1190


Script:

#!/bin/bash
# Check how customButtonInRowAction is handled in parent components
echo "Checking customButtonInRowAction implementations in parent components..."
rg "customButtonInRowAction.*function" -A 5 --type js

echo -e "\nChecking custom button configurations..."
# Look for custom button setup patterns
rg "buttons.*=.*\[" -A 5 --type js

echo -e "\nChecking for action parameter types..."
# Look for places where action types are defined/used
ast-grep --pattern 'action: $_'

Length of output: 471


Script:

#!/bin/bash
# Search for custom button definitions and their action configurations
echo "Searching for button configurations in templates..."
rg "customButtons" -B 2 -A 5 --type hbs

echo -e "\nSearching for button action definitions in components..."
rg "customButtons.*=" -B 2 -A 5 --type js

echo -e "\nSearching for action handling in flexberry components..."
rg "customButtonInRowAction" -B 2 -A 5 addon/components/flexberry-*.js

Length of output: 20663

addon/mixins/flexberry-lookup-controller.js (2)

327-327: LGTM: Good use of translation macro

The change from direct i18n service to translation macro is a good improvement as it will automatically update when the locale changes.


5-6: ⚠️ Potential issue

Remove unused Ember import

The Ember import appears to be unused as the code uses the newer @ember imports throughout. This aligns with modern Ember practices.

Apply this diff to remove the unused import:

-import Ember from 'ember';
import { translationMacro as t } from 'ember-i18n';

This issue was previously identified in a past review comment.

addon/components/flexberry-file.js (2)

975-976: LGTM! Consistent use of translationMacro for file size error messages.

The change from i18n service to translationMacro (t) aligns with the component's existing translation patterns and improves consistency.


996-997: LGTM! Consistent use of translationMacro for file extension error messages.

The change from i18n service to translationMacro (t) aligns with the component's existing translation patterns and improves consistency.

addon/components/olv-toolbar.js (3)

289-289: LGTM: Improved translation handling using macros.

The replacement of direct i18n.t() calls with the translation macro t() is a good improvement that:

  • Enhances performance through computed translations
  • Ensures automatic updates on locale changes
  • Enables better static analysis

Also applies to: 298-298, 306-306, 331-331, 358-358, 402-402, 501-501, 773-773, 819-821, 888-888


961-961: LGTM: Improved component name validation.

The use of isNameOfCurrentComponent helper method instead of direct component name comparisons:

  • Makes the code more maintainable
  • Reduces potential for errors
  • Follows the DRY principle

Also applies to: 981-981, 988-988, 1039-1039, 1047-1047


538-540: Consider improving the route transition handling.

The use of Ember.run.later with a hardcoded 50ms delay could be problematic:

  1. It might lead to race conditions
  2. The purpose of the delay is not documented
  3. Uses a magic number

Consider either:

  • Removing the delay if not strictly necessary
  • Adding a comment explaining why the delay is needed
  • Using a named constant for the delay value
addon/components/flexberry-objectlistview.js (2)

20-20: LGTM!

The import statement is correctly placed and follows the standard import format.


1515-1515: LGTM!

The use of isNameOfCurrentComponent method improves code readability and maintainability by encapsulating the component name comparison logic.

addon/components/flexberry-lookup.js (2)

1181-1183: LGTM: Translation macro changes improve i18n handling.

The transition from direct i18n service usage to translation macros (t) for message templates is a good improvement that follows Ember's best practices for internationalization.

Also applies to: 1431-1431


1089-1089: LGTM: Component name checks are now more maintainable.

The replacement of direct component name comparisons with isNameOfCurrentComponent method improves code maintainability by:

  1. Centralizing the component name check logic
  2. Making the code more DRY by reusing the base component's functionality

Also applies to: 1103-1103, 1118-1118

addon/components/object-list-view.js (1)

2862-2862: ⚠️ Potential issue

Typo in variable name 'skipConfugureRows'

The variable skipConfugureRows seems to be misspelled. It should be skipConfigureRows.

Apply this diff to fix the typo:

- if (!skipConfugureRows) {
+ if (!skipConfigureRows) {

Likely invalid or redundant comment.

Comment on lines +1 to +5
export default function getNewRouteNameOfEditForm(routeName) {
const postfix = '.new';

return `${routeName}${postfix}`;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding input validation and documentation.

To improve robustness and maintainability:

  1. Add parameter validation
  2. Add JSDoc documentation describing the purpose, parameters, and return value

Here's a suggested implementation:

+/**
+ * Generates a new route name for edit form by appending '.new' to the base route name
+ * @param {string} routeName - The base route name
+ * @returns {string} The generated route name for new form
+ * @throws {Error} If routeName is null, undefined or not a string
+ */
 export default function getNewRouteNameOfEditForm(routeName) {
+    if (!routeName || typeof routeName !== 'string') {
+        throw new Error('Route name must be a non-empty string');
+    }
+
     const postfix = '.new';
 
     return `${routeName}${postfix}`;
 }
📝 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 default function getNewRouteNameOfEditForm(routeName) {
const postfix = '.new';
return `${routeName}${postfix}`;
}
/**
* Generates a new route name for edit form by appending '.new' to the base route name
* @param {string} routeName - The base route name
* @returns {string} The generated route name for new form
* @throws {Error} If routeName is null, undefined or not a string
*/
export default function getNewRouteNameOfEditForm(routeName) {
if (!routeName || typeof routeName !== 'string') {
throw new Error('Route name must be a non-empty string');
}
const postfix = '.new';
return `${routeName}${postfix}`;
}

@@ -4,6 +4,8 @@

import Mixin from '@ember/object/mixin';
import { merge } from '@ember/polyfills';
import Ember from 'ember';
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unnecessary Ember import

The global Ember import is not needed as the code already uses modular imports (e.g., @ember/object/mixin). This aligns with modern Ember.js best practices.

-import Ember from 'ember';
📝 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
import Ember from 'ember';

Comment on lines +118 to +120
t('components.advlimit-dialog-content.limit') +
advLimitName +
this.get('i18n').t('components.advlimit-dialog-content.is-saved')
t('components.advlimit-dialog-content.is-saved')
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using template literals for better readability.

The string concatenation could be simplified using template literals.

-            t('components.advlimit-dialog-content.limit') +
-              advLimitName +
-              t('components.advlimit-dialog-content.is-saved')
+            `${t('components.advlimit-dialog-content.limit')}${advLimitName}${t('components.advlimit-dialog-content.is-saved')}`
📝 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
t('components.advlimit-dialog-content.limit') +
advLimitName +
this.get('i18n').t('components.advlimit-dialog-content.is-saved')
t('components.advlimit-dialog-content.is-saved')
`${t('components.advlimit-dialog-content.limit')}${advLimitName}${t('components.advlimit-dialog-content.is-saved')}`

@@ -98,14 +98,14 @@ export default FlexberryBaseComponent.extend({
saveAdvLimit: function() {
this._hideMessage();
const advLimitName = this.get('model.advLimitName');
if (isBlank(advLimitName)) {
this._showMessage('warning', this.get('i18n').t('components.advlimit-dialog-content.enter-setting-name'));
if (Ember.isBlank(advLimitName)) {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use imported isBlank instead of Ember.isBlank.

Since isBlank is already imported from @ember/utils, use it directly instead of accessing it through the Ember namespace.

-      if (Ember.isBlank(advLimitName)) {
+      if (isBlank(advLimitName)) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (Ember.isBlank(advLimitName)) {
if (isBlank(advLimitName)) {

Comment on lines +73 to +86
_hasCaption: Ember.computed('caption', function () {
const caption = this.get('caption');

if (Ember.isEmpty(caption)) return false;

const isCaptionTypeIsString = Ember.typeOf(caption) === 'string';
const isCaptionNotEmpty = Ember.$.trim(caption) !== '';
const isCaptionSafe = Ember.String.isHTMLSafe(caption);
const isHTMLSafeDefined = Ember.typeOf(Ember.String.isHTMLSafe) === 'function';
const isStringOfCaptionEmpty = Ember.$.trim(Ember.get(caption, 'string')) === '';

return isCaptionTypeIsString && isCaptionNotEmpty
|| isHTMLSafeDefined && isCaptionSafe && isStringOfCaptionEmpty === false
|| caption instanceof Ember.Handlebars.SafeString && isStringOfCaptionEmpty === false;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Refactor to use imports and optimize the implementation.

Several improvements can be made to enhance maintainability and consistency:

  1. Use the imported computed instead of Ember.computed
  2. Replace direct Ember. references with imports
  3. Optimize the string checks

Apply these changes:

-    _hasCaption: Ember.computed('caption', function () {
-      const caption = this.get('caption');
-
-      if (Ember.isEmpty(caption)) return false;
-
-      const isCaptionTypeIsString = Ember.typeOf(caption) === 'string';
-      const isCaptionNotEmpty = Ember.$.trim(caption) !== '';
-      const isCaptionSafe = Ember.String.isHTMLSafe(caption);
-      const isHTMLSafeDefined = Ember.typeOf(Ember.String.isHTMLSafe) === 'function';
-      const isStringOfCaptionEmpty = Ember.$.trim(Ember.get(caption, 'string')) === '';
-      
-      return isCaptionTypeIsString && isCaptionNotEmpty
-        || isHTMLSafeDefined && isCaptionSafe && isStringOfCaptionEmpty === false
-        || caption instanceof Ember.Handlebars.SafeString && isStringOfCaptionEmpty === false;
+    _hasCaption: computed('caption', function() {
+      const caption = get(this, 'caption');
+
+      if (isEmpty(caption)) {
+        return false;
+      }
+
+      const trimmedCaption = $.trim(caption);
+      
+      if (typeOf(caption) === 'string') {
+        return trimmedCaption !== '';
+      }
+
+      if (isHTMLSafe(caption)) {
+        return $.trim(get(caption, 'string')) !== '';
+      }
+
+      return false;
+    }),

Add these imports at the top:

+ import { isEmpty } from '@ember/utils';

Committable suggestion was skipped due to low confidence.

@@ -14,6 +14,9 @@ import { getOwner } from '@ember/application';
import { A } from '@ember/array';
import FlexberryBaseComponent from './flexberry-base-component';
import serializeSortingParam from '../utils/serialize-sorting-param';
import { getNewRouteNameOfEditForm } from '../utils/routes-names-builder';
import { translationMacro as t } from 'ember-i18n';
const { getOwner } = Ember;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove redundant getOwner declaration.

The getOwner is already imported at line 9. This redeclaration is unnecessary and could lead to confusion.

-const { getOwner } = Ember;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const { getOwner } = Ember;
🧰 Tools
🪛 Biome

[error] 19-19: Shouldn't redeclare 'getOwner'. Consider to delete it or rename it.

'getOwner' is defined here:

(lint/suspicious/noRedeclare)

Comment on lines +1193 to +1194
Ember.run.later((function() {
modelController.transitionToRoute(getNewRouteNameOfEditForm(editFormRoute), transitionOptions);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unnecessary timer for route transition.

The use of Ember.run.later with a hardcoded 50ms delay is not recommended as it:

  • Introduces a magic number
  • Could lead to race conditions
  • Makes the code harder to test

Consider removing the timer and transitioning directly:

-      Ember.run.later((function() {
-        modelController.transitionToRoute(getNewRouteNameOfEditForm(editFormRoute), transitionOptions);
-      }), 50);
+      modelController.transitionToRoute(getNewRouteNameOfEditForm(editFormRoute), transitionOptions);

Committable suggestion was skipped due to low confidence.

let allWords = this.get('filterByAllWords');
assert(`Only one of the options can be used: 'filterByAnyWord' or 'filterByAllWords'.`, !(allWords && anyWord));
if (this.isNameOfCurrentComponent(componentName)) {
Ember.assert(`Only one of the options can be used: 'filterByAnyWord' or 'filterByAllWords'.`, !(allWords && anyWord));
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Undefined variables 'anyWord' and 'allWords' in assertion

Variables anyWord and allWords are not defined in this scope, which will cause a ReferenceError.

Please define anyWord and allWords, or remove the assertion if these variables are not needed.

componentSettings.sorting.forEach((sorting, sortingIndex) => {
if (cachedColumn[sorting.propName]) {
cachedColumn[sorting.propName].sorted = true;
cachedColumn[sorting.propName].sortAscending = sorting.direction === 'asc' ? true : false;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Simplify boolean assignment in 'sortAscending'

You can simplify the assignment of sortAscending by directly using the comparison result without the ternary operator.

Apply this diff to fix the issue:

- cachedColumn[sorting.propName].sortAscending = sorting.direction === 'asc' ? true : false;
+ cachedColumn[sorting.propName].sortAscending = sorting.direction === 'asc';
📝 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
cachedColumn[sorting.propName].sortAscending = sorting.direction === 'asc' ? true : false;
cachedColumn[sorting.propName].sortAscending = sorting.direction === 'asc';
🧰 Tools
🪛 Biome

[error] 573-573: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

'eq': locale.eq,
'neq': locale.neq,
};
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove extraneous return statement at the end of '_conditionsByType'

There is an unnecessary return get(model, 'attributes').get(attributeName); statement at the end of the _conditionsByType method, which uses undefined variables and does not align with the method's purpose.

Remove the extraneous return statement:

-     return get(model, 'attributes').get(attributeName);

Committable suggestion was skipped due to low confidence.

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

Successfully merging this pull request may close these issues.

2 participants